text stringlengths 2 1.04M | meta dict |
|---|---|
require 'test_helper'
class RemotePaymentezTest < Test::Unit::TestCase
def setup
@gateway = PaymentezGateway.new(fixtures(:paymentez))
@amount = 100
@credit_card = credit_card('4111111111111111', verification_value: '555')
@declined_card = credit_card('4242424242424242', verification_value: '555')
@options = {
billing_address: address,
description: 'Store Purchase',
user_id: '998',
email: 'joe@example.com',
vat: 0,
dev_reference: 'Testing'
}
end
def test_successful_purchase
response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
end
def test_successful_purchase_with_more_options
options = {
order_id: '1',
ip: '127.0.0.1'
}
response = @gateway.purchase(@amount, @credit_card, @options.merge(options))
assert_success response
end
def test_successful_purchase_with_token
store_response = @gateway.store(@credit_card, @options)
assert_success store_response
token = store_response.authorization
purchase_response = @gateway.purchase(@amount, token, @options)
assert_success purchase_response
end
def test_failed_purchase
response = @gateway.purchase(@amount, @declined_card, @options)
assert_failure response
assert_equal Gateway::STANDARD_ERROR_CODE[:card_declined], response.error_code
end
def test_successful_void
auth = @gateway.purchase(@amount, @credit_card, @options)
assert_success auth
assert void = @gateway.void(auth.authorization)
assert_success void
end
def test_failed_void
response = @gateway.void('')
assert_failure response
assert_equal 'Carrier not supported', response.message
assert_equal Gateway::STANDARD_ERROR_CODE[:config_error], response.error_code
end
def test_successful_authorize_and_capture
auth = @gateway.authorize(@amount, @credit_card, @options)
assert_success auth
assert capture = @gateway.capture(@amount, auth.authorization)
assert_success capture
assert_equal 'Operation Successful', capture.message
end
def test_successful_authorize_and_capture_with_token
store_response = @gateway.store(@credit_card, @options)
assert_success store_response
token = store_response.authorization
auth = @gateway.authorize(@amount, token, @options)
assert_success auth
assert capture = @gateway.capture(@amount, auth.authorization)
assert_success capture
assert_equal 'Operation Successful', capture.message
end
def test_failed_authorize
response = @gateway.authorize(@amount, @declined_card, @options)
assert_failure response
assert_equal 'Not Authorized', response.message
end
def test_partial_capture
auth = @gateway.authorize(@amount, @credit_card, @options)
assert_success auth
assert capture = @gateway.capture(@amount - 1, auth.authorization)
assert_success capture
end
def test_failed_capture
response = @gateway.capture(@amount, '')
assert_failure response
assert_equal 'The capture method is not supported by carrier', response.message
end
def test_store
response = @gateway.store(@credit_card, @options)
assert_success response
end
def test_unstore
response = @gateway.store(@credit_card, @options)
assert_success response
auth = response.authorization
response = @gateway.unstore(auth, @options)
assert_success response
end
def test_invalid_login
gateway = PaymentezGateway.new(application_code: '9z8y7w6x', app_key: '1a2b3c4d')
response = gateway.purchase(@amount, @credit_card, @options)
assert_failure response
assert_equal 'BackendResponseException', response.message
assert_equal Gateway::STANDARD_ERROR_CODE[:config_error], response.error_code
end
def test_transcript_scrubbing
transcript = capture_transcript(@gateway) do
@gateway.purchase(@amount, @credit_card, @options)
end
transcript = @gateway.scrub(transcript)
assert_scrubbed(@credit_card.number, transcript)
assert_scrubbed(@credit_card.verification_value, transcript)
assert_scrubbed(@gateway.options[:app_key], transcript)
end
end
| {
"content_hash": "331b3088fa2f0315608abf54d27f3878",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 85,
"avg_line_length": 31.19402985074627,
"alnum_prop": 0.7119617224880382,
"repo_name": "waysact/active_merchant",
"id": "c22083655ea5e55da748f24e091c741c210b4600",
"size": "4180",
"binary": false,
"copies": "1",
"ref": "refs/heads/waysact/master",
"path": "test/remote/gateways/remote_paymentez_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "198"
},
{
"name": "Ruby",
"bytes": "8088671"
},
{
"name": "Shell",
"bytes": "808"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2002-2004 The Apache Software Foundation
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.
-->
<!-- @version $Id: testsuite.xml,v 1.1 2007-08-24 22:17:42 ewestfal Exp $ -->
<!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "document-v20.dtd">
<document>
<header>
<title>JUnit Test Suite</title>
<authors>
<person name="Armin Waibel" email="arminw@apache.org"/>
<person name="Thomas Mahler" email="thma@apache.org"/>
</authors>
</header>
<body>
<section>
<title>Introduction</title>
<p>
Building an Object/Relational mapping tool with support for multiple API's
is really error prone. To create a solid and stable software, the most awful thing in
programmers life has to be done - Testing.
</p>
<p>
Quality assurance taken seriously! OJB and provide specific tests for each
supported API. Currently more than 800 test cases for regression tests exist.
As testing framework
<a href="ext:junit">JUnit</a> was used.
</p>
<anchor id="location"/>
<section>
<title>Where can I find the test sources?</title>
<p>
The test sources of the <em>OJB Test-Suite</em> can be find under
<strong><code>[db-ojb]/src/test/org/apache/ojb</code></strong>.
<br/>
It's also possible to browse the test sources online using the
<a href="ext:cvs-index"><em>apache cvs view</em></a>. The test directory can be found here:
<a href="ext:cvs-view-tests"><strong><code>[db-ojb]/src/test/org/apache/ojb</code></strong></a>.
</p>
</section>
</section>
<anchor id="run-test-suite"/>
<section>
<title>How to run the Test Suite</title>
<p>
If the
<a href="site:platform">platform depended settings</a> are done, the test suite
can be started with the ant target:
</p>
<source><![CDATA[
ant junit]]></source>
<p>
If compiling of the sources should be skipped use
</p>
<source><![CDATA[
ant junit-no-compile]]></source>
<p>
If you did not manage to set up the target database with the
<code>ant prepare-testdb</code> you can use
</p>
<source><![CDATA[
ant junit-no-compile-no-prepare]]></source>
<p>
to run the testsuite without generation of the test database
(and without compiling).
</p>
<p>
After running the regression tests
you should see a console output similar to this:
</p>
<source><![CDATA[
junit-no-compile-no-prepare:
[junit] Running org.apache.ojb.broker.AllTests
[junit] Tests run: 620, Failures: 0, Errors: 0, Time elapsed: 81,75 sec
[junit] Running org.apache.ojb.odmg.AllTests
[junit] Tests run: 183, Failures: 0, Errors: 0, Time elapsed: 21,719 sec
[junit] Running org.apache.ojb.soda.AllTests
[junit] Tests run: 3, Failures: 0, Errors: 0, Time elapsed: 7,641 sec
[junit] Running org.apache.ojb.otm.AllTests
[junit] Tests run: 79, Failures: 0, Errors: 0, Time elapsed: 28,266 sec
junit-no-compile-no-prepare-selected:
junit-no-compile:
junit:
BUILD SUCCESSFUL
Total time: 3 minutes 26 seconds]]></source>
<p>
We aim at shipping that releases have no failures and errors in the regression tests!
If the Junit tests report errors or failures something does not
work properly! There may be several reasons:
</p>
<ul>
<li>
You made a mistake in configuration (OJB was shipped with settings pass all tests).
See <a href="site:platform">platform</a>,
<a href="site:ojb-properties">OJB.properties</a>,
<a href="site:repository">repository file</a>,
<a href="site:jdbc-types"></a>.
</li>
<li>Your database doesn't support specific features used by the tests</li>
<li>Evil hex</li>
<li>Bug in OJB</li>
</ul>
<p>
JUnit writes a <em>log-file</em> for each tested API. You can find the logs
under <code>[db-ojb]/target/test</code>. The log files named like <code>tests-XXX.txt</code>.
The test logs show in detail what's going wrong.
</p>
<p>
In such a case please check again if you followed all the above
steps. If you still have problems you might post a request to
the OJB user mailinglist.
</p>
<anchor id="change-database"/>
<section>
<title>How to run the test-suite with a different database than OJB default DB</title>
<p>
Basically all you have to do is:
</p>
<ul>
<li>
Get source version of OJB or fetch OJB from CVS (take care of
branches, branch OJB_1_0_RELEASE represents OJB 1.0.x).
</li>
<li>
Adapt the profile file of your database under
<code>[db-ojb]/profile/yourDB.profile</code> and set user, password, ...
</li>
<li>
In <code>[db-ojb]/build.properties</code> file comment the
"profile=hsqldb" line and uncomment the "#profile=yourDB" line.
</li>
<li>
Drop jdo.jar and your database driver into
<code>[db-ojb]/lib</code> directory.
</li>
<li>
Drop <em>junit.jar</em> into your <code>...ant/lib</code> folder.
</li>
<li>
Make sure that your database allows at least 20 concurrent connections.
</li>
</ul>
<p>
Then follow the steps described <a href="#run-test-suite">above</a>.
</p>
</section>
</section>
<section>
<title>What about known issues?</title>
<p>
All major known issues are listed in the <a href="ext:ojb/release-notes">release-notes</a>
file.
<br/>
The tests reproduce open bugs will be skipped on released OJB versions. It is possible to enable
these tests to see all failing test cases of the shipped version by changing a
flag in <code>[db-ojb]/build.properties</code> file:
</p>
<source><![CDATA[
###
# If 'true', junit tests marked as known issue in the junit-test
# source code (see OJBTestCase class for more detailed info) will be
# skipped. Default value is 'true'. For development 'false' is recommended,
# because this will show unsolved problems.
OJB.skip.issues=true]]></source>
</section>
<section>
<title>Donate own tests for OJB Test Suite</title>
<p>
Details about <a href="site:test-write">donate own test to OJB you can find here</a>.
</p>
</section>
</body>
</document> | {
"content_hash": "2ddd2acbcbda776ff509f47feda8c0a3",
"timestamp": "",
"source": "github",
"line_count": 196,
"max_line_length": 116,
"avg_line_length": 43.535714285714285,
"alnum_prop": 0.5264268135474042,
"repo_name": "iu-uits-es/ojb",
"id": "90ecd53d8cb2aef66535a487d8cd65d7921c22a6",
"size": "8533",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/doc/forrest/src/documentation/content/xdocs/docu/testing/testsuite.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1681"
},
{
"name": "GAP",
"bytes": "23099"
},
{
"name": "HTML",
"bytes": "8467"
},
{
"name": "Java",
"bytes": "9156715"
},
{
"name": "Shell",
"bytes": "1496"
},
{
"name": "XSLT",
"bytes": "13370"
}
],
"symlink_target": ""
} |
default[:cvmfs][:remote] = Mash.new
default[:cvmfs][:remote_key] = String.new
| {
"content_hash": "5109074b57bca5b889811ea8ea1483e1",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 41,
"avg_line_length": 39,
"alnum_prop": 0.7051282051282052,
"repo_name": "GSI-HPC/cvmfs-chef-cookbook",
"id": "b9329d4e892f1576097e54b8079b9e88773b7e8e",
"size": "78",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "attributes/remote.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "580"
},
{
"name": "Ruby",
"bytes": "15417"
},
{
"name": "Shell",
"bytes": "6464"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using NHotkey;
using NHotkey.Wpf;
using Wox.Core.Plugin;
using Wox.Core.Resource;
using Wox.Helper;
using Wox.Infrastructure;
using Wox.Infrastructure.Hotkey;
using Wox.Infrastructure.Image;
using Wox.Infrastructure.Storage;
using Wox.Infrastructure.UserSettings;
using Wox.Plugin;
using Wox.Storage;
namespace Wox.ViewModel
{
public class MainViewModel : BaseModel, ISavable
{
#region Private Fields
private bool _queryHasReturn;
private Query _lastQuery;
private string _queryTextBeforeLeaveResults;
private readonly WoxJsonStorage<History> _historyItemsStorage;
private readonly WoxJsonStorage<UserSelectedRecord> _userSelectedRecordStorage;
private readonly WoxJsonStorage<TopMostRecord> _topMostRecordStorage;
private readonly Settings _settings;
private readonly History _history;
private readonly UserSelectedRecord _userSelectedRecord;
private readonly TopMostRecord _topMostRecord;
private CancellationTokenSource _updateSource;
private CancellationToken _updateToken;
private bool _saved;
private Internationalization _translator = InternationalizationManager.Instance;
#endregion
#region Constructor
public MainViewModel(Settings settings)
{
_saved = false;
_queryTextBeforeLeaveResults = "";
_queryText = "";
_lastQuery = new Query();
_settings = settings;
_historyItemsStorage = new WoxJsonStorage<History>();
_userSelectedRecordStorage = new WoxJsonStorage<UserSelectedRecord>();
_topMostRecordStorage = new WoxJsonStorage<TopMostRecord>();
_history = _historyItemsStorage.Load();
_userSelectedRecord = _userSelectedRecordStorage.Load();
_topMostRecord = _topMostRecordStorage.Load();
ContextMenu = new ResultsViewModel(_settings);
Results = new ResultsViewModel(_settings);
History = new ResultsViewModel(_settings);
_selectedResults = Results;
InitializeKeyCommands();
RegisterResultsUpdatedEvent();
SetHotkey(_settings.Hotkey, OnHotkey);
SetCustomPluginHotkey();
}
private void RegisterResultsUpdatedEvent()
{
foreach (var pair in PluginManager.GetPluginsForInterface<IResultUpdated>())
{
var plugin = (IResultUpdated)pair.Plugin;
plugin.ResultsUpdated += (s, e) =>
{
Task.Run(() =>
{
PluginManager.UpdatePluginMetadata(e.Results, pair.Metadata, e.Query);
UpdateResultView(e.Results, pair.Metadata, e.Query);
}, _updateToken);
};
}
}
private void InitializeKeyCommands()
{
EscCommand = new RelayCommand(_ =>
{
if (!ResultsSelected())
{
SelectedResults = Results;
}
else
{
MainWindowVisibility = Visibility.Collapsed;
}
});
SelectNextItemCommand = new RelayCommand(_ =>
{
SelectedResults.SelectNextResult();
});
SelectPrevItemCommand = new RelayCommand(_ =>
{
SelectedResults.SelectPrevResult();
});
SelectNextPageCommand = new RelayCommand(_ =>
{
SelectedResults.SelectNextPage();
});
SelectPrevPageCommand = new RelayCommand(_ =>
{
SelectedResults.SelectPrevPage();
});
StartHelpCommand = new RelayCommand(_ =>
{
Process.Start("http://doc.getwox.com");
});
OpenResultCommand = new RelayCommand(index =>
{
var results = SelectedResults;
if (index != null)
{
results.SelectedIndex = int.Parse(index.ToString());
}
var result = results.SelectedItem?.Result;
if (result != null) // SelectedItem returns null if selection is empty.
{
bool hideWindow = result.Action != null && result.Action(new ActionContext
{
SpecialKeyState = GlobalHotkey.Instance.CheckModifiers()
});
if (hideWindow)
{
MainWindowVisibility = Visibility.Collapsed;
}
if (ResultsSelected())
{
_userSelectedRecord.Add(result);
_history.Add(result.OriginQuery.RawQuery);
}
}
});
LoadContextMenuCommand = new RelayCommand(_ =>
{
if (ResultsSelected())
{
SelectedResults = ContextMenu;
}
else
{
SelectedResults = Results;
}
});
LoadHistoryCommand = new RelayCommand(_ =>
{
if (ResultsSelected())
{
SelectedResults = History;
History.SelectedIndex = _history.Items.Count - 1;
}
else
{
SelectedResults = Results;
}
});
}
#endregion
#region ViewModel Properties
public ResultsViewModel Results { get; private set; }
public ResultsViewModel ContextMenu { get; private set; }
public ResultsViewModel History { get; private set; }
private string _queryText;
public string QueryText
{
get { return _queryText; }
set
{
_queryText = value;
Query();
}
}
/// <summary>
/// we need move cursor to end when we manually changed query
/// but we don't want to move cursor to end when query is updated from TextBox
/// </summary>
/// <param name="queryText"></param>
public void ChangeQueryText(string queryText)
{
QueryTextCursorMovedToEnd = true;
QueryText = queryText;
}
public bool LastQuerySelected { get; set; }
public bool QueryTextCursorMovedToEnd { get; set; }
private ResultsViewModel _selectedResults;
private ResultsViewModel SelectedResults
{
get { return _selectedResults; }
set
{
_selectedResults = value;
if (ResultsSelected())
{
ContextMenu.Visbility = Visibility.Collapsed;
History.Visbility = Visibility.Collapsed;
ChangeQueryText(_queryTextBeforeLeaveResults);
}
else
{
Results.Visbility = Visibility.Collapsed;
_queryTextBeforeLeaveResults = QueryText;
// Because of Fody's optimization
// setter won't be called when property value is not changed.
// so we need manually call Query()
// http://stackoverflow.com/posts/25895769/revisions
if (string.IsNullOrEmpty(QueryText))
{
Query();
}
else
{
QueryText = string.Empty;
}
}
_selectedResults.Visbility = Visibility.Visible;
}
}
public Visibility ProgressBarVisibility { get; set; }
public Visibility MainWindowVisibility { get; set; }
public ICommand EscCommand { get; set; }
public ICommand SelectNextItemCommand { get; set; }
public ICommand SelectPrevItemCommand { get; set; }
public ICommand SelectNextPageCommand { get; set; }
public ICommand SelectPrevPageCommand { get; set; }
public ICommand StartHelpCommand { get; set; }
public ICommand LoadContextMenuCommand { get; set; }
public ICommand LoadHistoryCommand { get; set; }
public ICommand OpenResultCommand { get; set; }
#endregion
public void Query()
{
if (ResultsSelected())
{
QueryResults();
}
else if (ContextMenuSelected())
{
QueryContextMenu();
}
else if (HistorySelected())
{
QueryHistory();
}
}
private void QueryContextMenu()
{
const string id = "Context Menu ID";
var query = QueryText.ToLower().Trim();
ContextMenu.Clear();
var selected = Results.SelectedItem?.Result;
if (selected != null) // SelectedItem returns null if selection is empty.
{
var results = PluginManager.GetContextMenusForPlugin(selected);
results.Add(ContextMenuTopMost(selected));
results.Add(ContextMenuPluginInfo(selected.PluginID));
if (!string.IsNullOrEmpty(query))
{
var filtered = results.Where
(
r => StringMatcher.IsMatch(r.Title, query) ||
StringMatcher.IsMatch(r.SubTitle, query)
).ToList();
ContextMenu.AddResults(filtered, id);
}
else
{
ContextMenu.AddResults(results, id);
}
}
}
private void QueryHistory()
{
const string id = "Query History ID";
var query = QueryText.ToLower().Trim();
History.Clear();
var results = new List<Result>();
foreach (var h in _history.Items)
{
var title = _translator.GetTranslation("executeQuery");
var time = _translator.GetTranslation("lastExecuteTime");
var result = new Result
{
Title = string.Format(title, h.Query),
SubTitle = string.Format(time, h.ExecutedDateTime),
IcoPath = "Images\\history.png",
OriginQuery = new Query { RawQuery = h.Query },
Action = _ =>
{
SelectedResults = Results;
ChangeQueryText(h.Query);
return false;
}
};
results.Add(result);
}
if (!string.IsNullOrEmpty(query))
{
var filtered = results.Where
(
r => StringMatcher.IsMatch(r.Title, query) ||
StringMatcher.IsMatch(r.SubTitle, query)
).ToList();
History.AddResults(filtered, id);
}
else
{
History.AddResults(results, id);
}
}
private void QueryResults()
{
if (!string.IsNullOrEmpty(QueryText))
{
_updateSource?.Cancel();
_updateSource = new CancellationTokenSource();
_updateToken = _updateSource.Token;
ProgressBarVisibility = Visibility.Hidden;
_queryHasReturn = false;
var query = PluginManager.QueryInit(QueryText.Trim());
if (query != null)
{
// handle the exclusiveness of plugin using action keyword
string lastKeyword = _lastQuery.ActionKeyword;
string keyword = query.ActionKeyword;
if (string.IsNullOrEmpty(lastKeyword))
{
if (!string.IsNullOrEmpty(keyword))
{
Results.RemoveResultsExcept(PluginManager.NonGlobalPlugins[keyword].Metadata);
}
}
else
{
if (string.IsNullOrEmpty(keyword))
{
Results.RemoveResultsFor(PluginManager.NonGlobalPlugins[lastKeyword].Metadata);
}
else if (lastKeyword != keyword)
{
Results.RemoveResultsExcept(PluginManager.NonGlobalPlugins[keyword].Metadata);
}
}
_lastQuery = query;
Task.Delay(200, _updateToken).ContinueWith(_ =>
{
if (query.RawQuery == _lastQuery.RawQuery && !_queryHasReturn)
{
ProgressBarVisibility = Visibility.Visible;
}
}, _updateToken);
var plugins = PluginManager.ValidPluginsForQuery(query);
Task.Run(() =>
{
Parallel.ForEach(plugins, plugin =>
{
var config = _settings.PluginSettings.Plugins[plugin.Metadata.ID];
if (!config.Disabled)
{
var results = PluginManager.QueryForPlugin(plugin, query);
UpdateResultView(results, plugin.Metadata, query);
}
});
}, _updateToken);
}
}
else
{
Results.Clear();
Results.Visbility = Visibility.Collapsed;
}
}
private Result ContextMenuTopMost(Result result)
{
Result menu;
if (_topMostRecord.IsTopMost(result))
{
menu = new Result
{
Title = InternationalizationManager.Instance.GetTranslation("cancelTopMostInThisQuery"),
IcoPath = "Images\\down.png",
PluginDirectory = Constant.ProgramDirectory,
Action = _ =>
{
_topMostRecord.Remove(result);
App.API.ShowMsg("Succeed");
return false;
}
};
}
else
{
menu = new Result
{
Title = InternationalizationManager.Instance.GetTranslation("setAsTopMostInThisQuery"),
IcoPath = "Images\\up.png",
PluginDirectory = Constant.ProgramDirectory,
Action = _ =>
{
_topMostRecord.AddOrUpdate(result);
App.API.ShowMsg("Succeed");
return false;
}
};
}
return menu;
}
private Result ContextMenuPluginInfo(string id)
{
var metadata = PluginManager.GetPluginForId(id).Metadata;
var translator = InternationalizationManager.Instance;
var author = translator.GetTranslation("author");
var website = translator.GetTranslation("website");
var version = translator.GetTranslation("version");
var plugin = translator.GetTranslation("plugin");
var title = $"{plugin}: {metadata.Name}";
var icon = metadata.IcoPath;
var subtitle = $"{author}: {metadata.Author}, {website}: {metadata.Website} {version}: {metadata.Version}";
var menu = new Result
{
Title = title,
IcoPath = icon,
SubTitle = subtitle,
PluginDirectory = metadata.PluginDirectory,
Action = _ => false
};
return menu;
}
private bool ResultsSelected()
{
var selected = SelectedResults == Results;
return selected;
}
private bool ContextMenuSelected()
{
var selected = SelectedResults == ContextMenu;
return selected;
}
private bool HistorySelected()
{
var selected = SelectedResults == History;
return selected;
}
#region Hotkey
private void SetHotkey(string hotkeyStr, EventHandler<HotkeyEventArgs> action)
{
var hotkey = new HotkeyModel(hotkeyStr);
SetHotkey(hotkey, action);
}
private void SetHotkey(HotkeyModel hotkey, EventHandler<HotkeyEventArgs> action)
{
string hotkeyStr = hotkey.ToString();
try
{
HotkeyManager.Current.AddOrReplace(hotkeyStr, hotkey.CharKey, hotkey.ModifierKeys, action);
}
catch (Exception)
{
string errorMsg =
string.Format(InternationalizationManager.Instance.GetTranslation("registerHotkeyFailed"), hotkeyStr);
MessageBox.Show(errorMsg);
}
}
public void RemoveHotkey(string hotkeyStr)
{
if (!string.IsNullOrEmpty(hotkeyStr))
{
HotkeyManager.Current.Remove(hotkeyStr);
}
}
/// <summary>
/// Checks if Wox should ignore any hotkeys
/// </summary>
/// <returns></returns>
private bool ShouldIgnoreHotkeys()
{
//double if to omit calling win32 function
if (_settings.IgnoreHotkeysOnFullscreen)
if (WindowsInteropHelper.IsWindowFullscreen())
return true;
return false;
}
private void SetCustomPluginHotkey()
{
if (_settings.CustomPluginHotkeys == null) return;
foreach (CustomPluginHotkey hotkey in _settings.CustomPluginHotkeys)
{
SetHotkey(hotkey.Hotkey, (s, e) =>
{
if (ShouldIgnoreHotkeys()) return;
MainWindowVisibility = Visibility.Visible;
ChangeQueryText(hotkey.ActionKeyword);
});
}
}
private void OnHotkey(object sender, HotkeyEventArgs e)
{
if (!ShouldIgnoreHotkeys())
{
if (_settings.LastQueryMode == LastQueryMode.Empty)
{
ChangeQueryText(string.Empty);
}
else if (_settings.LastQueryMode == LastQueryMode.Preserved)
{
LastQuerySelected = true;
}
else if (_settings.LastQueryMode == LastQueryMode.Selected)
{
LastQuerySelected = false;
}
else
{
throw new ArgumentException($"wrong LastQueryMode: <{_settings.LastQueryMode}>");
}
ToggleWox();
e.Handled = true;
}
}
private void ToggleWox()
{
if (MainWindowVisibility != Visibility.Visible)
{
MainWindowVisibility = Visibility.Visible;
}
else
{
MainWindowVisibility = Visibility.Collapsed;
}
}
#endregion
#region Public Methods
public void Save()
{
if (!_saved)
{
_historyItemsStorage.Save();
_userSelectedRecordStorage.Save();
_topMostRecordStorage.Save();
_saved = true;
}
}
/// <summary>
/// To avoid deadlock, this method should not called from main thread
/// </summary>
public void UpdateResultView(List<Result> list, PluginMetadata metadata, Query originQuery)
{
_queryHasReturn = true;
ProgressBarVisibility = Visibility.Hidden;
foreach (var result in list)
{
if (_topMostRecord.IsTopMost(result))
{
result.Score = int.MaxValue;
}
else
{
result.Score += _userSelectedRecord.GetSelectedCount(result) * 5;
}
}
if (originQuery.RawQuery == _lastQuery.RawQuery)
{
Results.AddResults(list, metadata.ID);
}
if (Results.Visbility != Visibility.Visible && list.Count > 0)
{
Results.Visbility = Visibility.Visible;
}
}
#endregion
}
} | {
"content_hash": "f310a07f06a4563087530758a88c47a8",
"timestamp": "",
"source": "github",
"line_count": 655,
"max_line_length": 122,
"avg_line_length": 33.0793893129771,
"alnum_prop": 0.4860848294641621,
"repo_name": "lances101/Wox",
"id": "bc8b26958653dec833c20cd406bf97362f3c9241",
"size": "21669",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Wox/ViewModel/MainViewModel.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "468431"
},
{
"name": "PowerShell",
"bytes": "4375"
},
{
"name": "Python",
"bytes": "4310"
}
],
"symlink_target": ""
} |
/**************************************************************************/
/*!
@file cmd_nfc_mifareclassic_memdump.c
@author K. Townsend (microBuilder.eu)
@brief Dumps the contents of a Mifare Classic card to the CLI
@ingroup CLI
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2013, K. Townsend (microBuilder.eu)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**************************************************************************/
#include <stdio.h>
#include "projectconfig.h"
#ifdef CFG_PN532
#include "core/gpio/gpio.h"
#include "cli/cli.h"
#include "cli/commands.h" // Generic helper functions
#include "core/i2c/i2c.h"
#include "drivers/rf/nfc/pn532/pn532.h"
#include "drivers/rf/nfc/pn532/pn532_bus.h"
#include "drivers/rf/nfc/pn532/helpers/pn532_config.h"
#include "drivers/rf/nfc/pn532/helpers/pn532_mifare_classic.h"
#include "drivers/rf/nfc/pn532/helpers/pn532_mifare_ultralight.h"
/**************************************************************************/
/*!
'nfc_mifareclassic_memdump' command handler
*/
/**************************************************************************/
void cmd_nfc_mifareclassic_memdump(uint8_t argc, char **argv)
{
pn532_error_t error;
byte_t abtUID[8];
byte_t abtBlock[32];
size_t szUIDLen;
int32_t timeout;
bool retriesChanged = false;
// To dump an NDEF formatted Mifare Classic Card (formatted using NXP TagWriter on Android
// for example), you must use the following authentication keys:
//
// Sector 0: 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5
// Sectors 1..15: 0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7
//
// For more information on NDEF see the following document:
//
// AN1305 - MIFARE Classic as NFC Type MIFARE Classic Tag
// http://www.nxp.com/documents/application_note/AN1305.pdf
// Set this to one for NDEF cards, or 0 for blank factory default cards
#define CARDFORMAT_NDEF (0)
#if CARDFORMAT_NDEF == 1
byte_t abtAuthKey1[6] = { 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5 }; // Sector 0 of NXP formatter NDEF cards
byte_t abtAuthKey2[6] = { 0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7 }; // All other sectors use standard key (AN1305 p.20, Table 6)
#else
byte_t abtAuthKey1[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
byte_t abtAuthKey2[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
#endif
// Set a timeout waiting for passive targets (default = 0xFF, wait forever)
if (argc > 0)
{
getNumber (argv[0], &timeout);
if (timeout > 0xFF || timeout < 0)
{
printf("Invalid timeout [0..255]%s", CFG_PRINTF_NEWLINE);
return;
}
else if (timeout > 0 || timeout < 0xFF)
{
// We can safely ignore errors here since there is a default value anyway
pn532_config_SetPassiveActivationRetries(timeout);
retriesChanged = true;
}
}
// Use the MIFARE Classic Helper to read/write to the tag's EEPROM storage
printf("Please insert a Mifare Classic 1K or 4K card%s%s", CFG_PRINTF_NEWLINE, CFG_PRINTF_NEWLINE);
// Wait for any ISO14443A card
error = pn532_mifareclassic_WaitForPassiveTarget(abtUID, &szUIDLen);
if (!error)
{
// Mifare classic card found ... cycle through each sector
uint8_t block;
bool authenticated = false;
for (block = 0; block < 64; block++)
{
// Check if this is a new block so that we can reauthenticate
if (pn532_mifareclassic_isFirstBlock(block)) authenticated = false;
if (!authenticated)
{
// Start of a new sector ... try to to authenticate
printf("-------------------------Sector %02d--------------------------%s", block / 4, CFG_PRINTF_NEWLINE);
error = pn532_mifareclassic_AuthenticateBlock (abtUID, szUIDLen, block, PN532_MIFARE_CMD_AUTH_A, block / 4 ? abtAuthKey2 : abtAuthKey1);
if (error)
{
switch(error)
{
default:
printf("Authentication error (0x%02x)%s", error, CFG_PRINTF_NEWLINE);
break;
}
}
else
{
authenticated = true;
}
}
// If we're still not authenticated just skip the block
if (!authenticated)
{
printf("Block %02d: ", block);
printf("Unable to authenticate%s", CFG_PRINTF_NEWLINE);
}
else
{
// Authenticated ... we should be able to read the block now
error = pn532_mifareclassic_ReadDataBlock (block, abtBlock);
if (error)
{
switch(error)
{
default:
printf("Block %02d: ", block);
printf("Unable to read this block%s", CFG_PRINTF_NEWLINE);
break;
}
}
else
{
// Read successful
printf("Block %02d: ", block);
pn532PrintHexChar(abtBlock, 16);
}
}
}
}
else
{
switch (error)
{
case PN532_ERROR_WRONGCARDTYPE:
printf("Wrong card type%s", CFG_PRINTF_NEWLINE);
break;
case PN532_ERROR_TIMEOUTWAITINGFORCARD:
printf("Timed out waiting for a card%s", CFG_PRINTF_NEWLINE);
break;
default:
printf("Error establishing passive connection (0x%02x)%s", error, CFG_PRINTF_NEWLINE);
break;
}
}
// Set retry count back to infinite if it was changed
if (retriesChanged)
{
pn532_config_SetPassiveActivationRetries(0xFF);
}
}
#endif
| {
"content_hash": "d5f93e8aabd81fd8f6a76b6106946538",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 144,
"avg_line_length": 35.69072164948454,
"alnum_prop": 0.6205950317735413,
"repo_name": "tummychow/arm-alarm",
"id": "4bbcbce4cfb4bd7baa47c9e315be6b1121cfd224",
"size": "6924",
"binary": false,
"copies": "2",
"ref": "refs/heads/arm-alarm",
"path": "src/cli/commands/cmd_nfc_mifareclassic_memdump.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "4102540"
},
{
"name": "C++",
"bytes": "359456"
},
{
"name": "Objective-C",
"bytes": "10786"
},
{
"name": "Python",
"bytes": "20616"
},
{
"name": "Ruby",
"bytes": "131"
}
],
"symlink_target": ""
} |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.9.5.38_A3_T1;
* @section: 15.9.5.38;
* @assertion: The Date.prototype.setMonth property "length" has { ReadOnly, DontDelete, DontEnum } attributes;
* @description: Checking ReadOnly attribute;
*/
x = Date.prototype.setMonth.length;
Date.prototype.setMonth.length = 1;
if (Date.prototype.setMonth.length !== x) {
$ERROR('#1: The Date.prototype.setMonth.length has the attribute ReadOnly');
}
| {
"content_hash": "f7c54a32b44c566463ad22367093a45a",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 111,
"avg_line_length": 35.375,
"alnum_prop": 0.6996466431095406,
"repo_name": "remobjects/script",
"id": "bfab8f983c4a1687f5e11d164ca11a7b519926b9",
"size": "566",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Test/sputniktests/tests/Conformance/15_Native_ECMA_Script_Objects/15.9_Date_Objects/15.9.5_Properties_of_the_Date_Prototype_Object/15.9.5.38_Date.prototype.setMonth/S15.9.5.38_A3_T1.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1755"
},
{
"name": "CSS",
"bytes": "15950"
},
{
"name": "HTML",
"bytes": "431518"
},
{
"name": "JavaScript",
"bytes": "9852539"
},
{
"name": "Pascal",
"bytes": "802577"
},
{
"name": "Python",
"bytes": "29664"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--Rendered using the Haskell Html Library v0.2-->
<HTML
><HEAD
><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8"
><TITLE
>Yaiba.SPoly</TITLE
><LINK HREF="haddock.css" REL="stylesheet" TYPE="text/css"
><SCRIPT SRC="haddock-util.js" TYPE="text/javascript"
></SCRIPT
></HEAD
><BODY
><DIV CLASS="outer"
><DIV CLASS="mini-topbar"
>Yaiba.SPoly</DIV
><DIV CLASS="mini-synopsis"
><DIV CLASS="decl"
><SPAN CLASS="keyword"
>data</SPAN
> <A HREF="Yaiba-SPoly.html#t%3ASPoly" TARGET="main"
>SPoly</A
> ord</DIV
> <DIV CLASS="decl"
><SPAN CLASS="keyword"
>data</SPAN
> <A HREF="Yaiba-SPoly.html#t%3ACritPair" TARGET="main"
>CritPair</A
> ord</DIV
> <DIV CLASS="decl"
><A HREF="Yaiba-SPoly.html#v%3Aempty" TARGET="main"
>empty</A
></DIV
> <DIV CLASS="decl"
><A HREF="Yaiba-SPoly.html#v%3AisEmpty" TARGET="main"
>isEmpty</A
></DIV
> <DIV CLASS="decl"
><A HREF="Yaiba-SPoly.html#v%3AsizeSP" TARGET="main"
>sizeSP</A
></DIV
> <DIV CLASS="decl"
><A HREF="Yaiba-SPoly.html#v%3AbTest" TARGET="main"
>bTest</A
></DIV
> <DIV CLASS="decl"
><A HREF="Yaiba-SPoly.html#v%3AconstructN" TARGET="main"
>constructN</A
></DIV
> <DIV CLASS="decl"
><A HREF="Yaiba-SPoly.html#v%3AtTest" TARGET="main"
>tTest</A
></DIV
> <DIV CLASS="decl"
><A HREF="Yaiba-SPoly.html#v%3AmTest" TARGET="main"
>mTest</A
></DIV
> <DIV CLASS="decl"
><A HREF="Yaiba-SPoly.html#v%3AupdateSPolys" TARGET="main"
>updateSPolys</A
></DIV
> <DIV CLASS="decl"
><A HREF="Yaiba-SPoly.html#v%3AdelFindSingleLowest" TARGET="main"
>delFindSingleLowest</A
></DIV
> <DIV CLASS="decl"
><A HREF="Yaiba-SPoly.html#v%3AdelFindLowest" TARGET="main"
>delFindLowest</A
></DIV
> <DIV CLASS="decl"
><A HREF="Yaiba-SPoly.html#v%3AfindMinSug" TARGET="main"
>findMinSug</A
></DIV
> <DIV CLASS="decl"
><A HREF="Yaiba-SPoly.html#v%3AtoSPoly" TARGET="main"
>toSPoly</A
></DIV
></DIV
></DIV
></BODY
></HTML
>
| {
"content_hash": "d32e86c523fe3ac67443b0c7eee927ba",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 102,
"avg_line_length": 24.135802469135804,
"alnum_prop": 0.6792838874680307,
"repo_name": "jeremyong/Yaiba",
"id": "1790dbdde36e4435585d7a9aa263bb36eb282c7c",
"size": "1955",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "dist/doc/html/Yaiba/mini_Yaiba-SPoly.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "2338"
},
{
"name": "Haskell",
"bytes": "179322"
},
{
"name": "JavaScript",
"bytes": "6804"
},
{
"name": "Shell",
"bytes": "1375"
}
],
"symlink_target": ""
} |
package org.apache.cassandra.stress;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.google.common.util.concurrent.RateLimiter;
import org.apache.cassandra.stress.generate.*;
import org.apache.cassandra.stress.settings.OptionRatioDistribution;
import org.apache.cassandra.stress.settings.SettingsLog;
import org.apache.cassandra.stress.settings.StressSettings;
import org.apache.cassandra.stress.util.JavaDriverClient;
import org.apache.cassandra.stress.util.ThriftClient;
import org.apache.cassandra.stress.util.Timer;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.transport.SimpleClient;
public abstract class Operation
{
public final StressSettings settings;
public final Timer timer;
protected final DataSpec spec;
private final static RatioDistribution defaultRowPopulationRatio = OptionRatioDistribution.BUILDER.apply("fixed(1)/1").get();
private final List<PartitionIterator> partitionCache = new ArrayList<>();
protected List<PartitionIterator> partitions;
public static final class DataSpec
{
public final PartitionGenerator partitionGenerator;
final SeedManager seedManager;
final Distribution partitionCount;
final RatioDistribution useRatio;
final RatioDistribution rowPopulationRatio;
final Integer targetCount;
public DataSpec(PartitionGenerator partitionGenerator, SeedManager seedManager, Distribution partitionCount, RatioDistribution rowPopulationRatio, Integer targetCount)
{
this(partitionGenerator, seedManager, partitionCount, null, rowPopulationRatio, targetCount);
}
public DataSpec(PartitionGenerator partitionGenerator, SeedManager seedManager, Distribution partitionCount, RatioDistribution useRatio, RatioDistribution rowPopulationRatio)
{
this(partitionGenerator, seedManager, partitionCount, useRatio, rowPopulationRatio, null);
}
private DataSpec(PartitionGenerator partitionGenerator, SeedManager seedManager, Distribution partitionCount, RatioDistribution useRatio, RatioDistribution rowPopulationRatio, Integer targetCount)
{
this.partitionGenerator = partitionGenerator;
this.seedManager = seedManager;
this.partitionCount = partitionCount;
this.useRatio = useRatio;
this.rowPopulationRatio = rowPopulationRatio == null ? defaultRowPopulationRatio : rowPopulationRatio;
this.targetCount = targetCount;
}
}
public Operation(Timer timer, StressSettings settings, DataSpec spec)
{
this.timer = timer;
this.settings = settings;
this.spec = spec;
}
public static interface RunOp
{
public boolean run() throws Exception;
public int partitionCount();
public int rowCount();
}
boolean ready(WorkManager permits, RateLimiter rateLimiter)
{
int partitionCount = (int) spec.partitionCount.next();
if (partitionCount <= 0)
return false;
partitionCount = permits.takePermits(partitionCount);
if (partitionCount <= 0)
return false;
int i = 0;
boolean success = true;
for (; i < partitionCount && success ; i++)
{
if (i >= partitionCache.size())
partitionCache.add(PartitionIterator.get(spec.partitionGenerator, spec.seedManager));
success = false;
while (!success)
{
Seed seed = spec.seedManager.next(this);
if (seed == null)
break;
success = reset(seed, partitionCache.get(i));
}
}
partitionCount = i;
if (rateLimiter != null)
rateLimiter.acquire(partitionCount);
partitions = partitionCache.subList(0, partitionCount);
return !partitions.isEmpty();
}
protected boolean reset(Seed seed, PartitionIterator iterator)
{
if (spec.useRatio == null)
return iterator.reset(seed, spec.targetCount, spec.rowPopulationRatio.next(), isWrite());
else
return iterator.reset(seed, spec.useRatio.next(), spec.rowPopulationRatio.next(), isWrite());
}
public boolean isWrite()
{
return false;
}
/**
* Run operation
* @param client Cassandra Thrift client connection
* @throws IOException on any I/O error.
*/
public abstract void run(ThriftClient client) throws IOException;
public void run(SimpleClient client) throws IOException
{
throw new UnsupportedOperationException();
}
public void run(JavaDriverClient client) throws IOException
{
throw new UnsupportedOperationException();
}
public void timeWithRetry(RunOp run) throws IOException
{
timer.start();
boolean success = false;
String exceptionMessage = null;
int tries = 0;
for (; tries < settings.errors.tries; tries++)
{
try
{
success = run.run();
break;
}
catch (Exception e)
{
switch (settings.log.level)
{
case MINIMAL:
break;
case NORMAL:
System.err.println(e);
break;
case VERBOSE:
e.printStackTrace(System.err);
break;
default:
throw new AssertionError();
}
exceptionMessage = getExceptionMessage(e);
}
}
timer.stop(run.partitionCount(), run.rowCount(), !success);
if (!success)
{
error(String.format("Operation x%d on key(s) %s: %s%n",
tries,
key(),
(exceptionMessage == null)
? "Data returned was not validated"
: "Error executing: " + exceptionMessage));
}
}
private String key()
{
List<String> keys = new ArrayList<>();
for (PartitionIterator partition : partitions)
keys.add(partition.getKeyAsString());
return keys.toString();
}
protected String getExceptionMessage(Exception e)
{
String className = e.getClass().getSimpleName();
String message = (e instanceof InvalidRequestException) ? ((InvalidRequestException) e).getWhy() : e.getMessage();
return (message == null) ? "(" + className + ")" : String.format("(%s): %s", className, message);
}
protected void error(String message) throws IOException
{
if (!settings.errors.ignore)
throw new IOException(message);
else if (settings.log.level.compareTo(SettingsLog.Level.MINIMAL) > 0)
System.err.println(message);
}
}
| {
"content_hash": "6d3e684733c62c3a2942cb3662b8a086",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 204,
"avg_line_length": 33.344339622641506,
"alnum_prop": 0.6208798981468383,
"repo_name": "pcmanus/cassandra",
"id": "139dd537c2cb4bc6597e5734119ed20987304943",
"size": "7874",
"binary": false,
"copies": "2",
"ref": "refs/heads/trunk",
"path": "tools/stress/src/org/apache/cassandra/stress/Operation.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "801"
},
{
"name": "Batchfile",
"bytes": "23782"
},
{
"name": "GAP",
"bytes": "68131"
},
{
"name": "Java",
"bytes": "14566617"
},
{
"name": "Lex",
"bytes": "10154"
},
{
"name": "PowerShell",
"bytes": "37891"
},
{
"name": "Python",
"bytes": "454295"
},
{
"name": "Shell",
"bytes": "48670"
},
{
"name": "Thrift",
"bytes": "40282"
}
],
"symlink_target": ""
} |
There are quite a number of ways in which the wototo service can be deployed. At some point it may be available on a subscription basis (i.e. Software as a Service, SaaS). In the mean time you will need to set up and maintain your own personal wototo service, either on a desktop or laptop computer, or on a server.
You should be able to run Wototo on a moderate specification desktop or laptop computer running a reasonably recent version of Linux, Windows or MacOS X. If you run Wototo on a desktop or laptop computer then you will probably not be able to use the Forms functionality, and if you want publish material generally then you will also need space on a web server that supports static files and PHP.
To run wototo on a server you will need an Internet-accessible Unix (Linux) server with shell access and root/admin permission; typically this will be a virtual machine (VM) or virtual private server (VPS). On a server Wototo can run alongside other services, but you will need to set up your existing web server (assuming you are running one) to forward requests to Wototo.
## Personal / test instance
### Creating
You can create a single personal or test instance of the mediahub using the pre-built docker image `cgreenhalgh/mediahubauto`.
- install docker as per the [docker installation](http://docs.docker.com/installation/) for your operating system. (If you are using windows and having trouble see notes below.)
- if on windows or Mac start boot2docker as per the installation guide, e.g. on Windows click `boot2docker start`. (If you are using Linux then docker will run directly on your machine.)
- download the docker image `cgreenhalgh/mediahubauto:latest` (if on windows or Mac do this in the boot2docker window; on Linux do it in a `term` window - on Linux you will need to be root us add `sudo` to the beginning of the line):
```
docker pull cgreenhalgh/mediahubauto:latest
```
- start a new mediahub instance from that image (and by default make it accessible via port 80 on the docker host):
```
docker run -d -p :80:80 cgreenhalgh/mediahubauto:latest
```
- If on windows or Mac and you want to access the mediahub from other machines on the network then you will need to make the port accessible, e.g. on Windows open `Oracle VM VirtualBox`, find the entry on the left for `boot2docker-vm`, select it and click `Settings`, select `Network`, on the `Adapter 1` tab click `Port Forwarding`, click `Insert new rule` (diamond/plus icon), and enter `Host Port` `80` and `Guest Port` `80`; click `OK`, `OK`.
- Open a browser and enter the URL of the new instance. Note: don't use `localhost` or `127.0.0.1` - find the actual IP address of your machine (or the docker host vm). Open a terminal (on Windows a `Command Prompt`) and type `boot2docker ip`; copy this address (four numbers with dots in between) into the web browser.
- you should see a form prompting for an instance name, username and password. (If you get a `502 Bad Gateway` error then try stopping and re-starting the docker container, or restarting your machine and restarting docker as below.) These will be the admin account for the new server; enter your chosen values and hit configure (don't use credentials that you use elsewhere!). You should see a confirmation page with a Get started link; follow this...
- you should see a simple web page with a title (OpenSharingToolkit Mediahub) and a link `Editor` - click this for the authoring and publishing view. The username and password are the ones you set in the previous step.
- Now try the tutorial in the [general (app first) user guide](userguide.md) or the [kiosk user guide](kioskuserguide.md).
Note that the server uses basic authentication over HTTP; you will need to set it up behind a HTTPS reverse proxy if you want this to be secure!
### Checking / restarting
Note that if you restart your computer or boot2docker, depending on how you do it, the mediahub instance may not be running afterwards. You can check and if necessary restart it as follows:
- If on Windows or Mac check that boot2docker is running, and if not start it (as above).
- Check if you server is still running in docker (as above, if on windows or Mac do this in the boot2docker window; on Linux do it in a `term` window - on Linux you will need to be root us add `sudo` to the beginning of the line):
```
docker ps | grep mediahub
```
- if you see an entry for the mediahub in this list of running docker "containers" then no need to worry - it is running. Otherwise...
- find the stopped container which is your instance:
```
docker ps -a | grep mediahub
```
- if there is NO entry then you don't have an instance here - you'll have to start a new one as above. If there is an entry...
- copy the first "word" in the line (about 12 letters and digits) and paste this instead of `CONTAINERD` below:
```
docker start CONTAINERID
```
- with a bit of luck that will restart the mediahub instance, and you can access it from your browser as before.
| {
"content_hash": "8d49333f47071d9d9a94ad17ee9b092e",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 451,
"avg_line_length": 78.125,
"alnum_prop": 0.762,
"repo_name": "cgreenhalgh/opensharingtoolkit-mediahub",
"id": "d3616391d118c793bd17f1a646d41eac101df376",
"size": "5022",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/installation.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1387"
},
{
"name": "CSS",
"bytes": "853960"
},
{
"name": "CoffeeScript",
"bytes": "271402"
},
{
"name": "HTML",
"bytes": "17890"
},
{
"name": "JavaScript",
"bytes": "401212"
},
{
"name": "Makefile",
"bytes": "8426"
},
{
"name": "PHP",
"bytes": "95316"
},
{
"name": "Ruby",
"bytes": "914"
}
],
"symlink_target": ""
} |
using System;
using System.IO;
using System.Linq;
using static Bullseye.Targets;
using static SimpleExec.Command;
namespace build
{
partial class Program
{
private const string packOutput = "./artifacts";
private const string packOutputCopy = "../../nuget";
private const string envVarMissing = " environment variable is missing. Aborting.";
private static class Targets
{
public const string CleanBuildOutput = "clean-build-output";
public const string CleanPackOutput = "clean-pack-output";
public const string Build = "build";
public const string Test = "test";
public const string Pack = "pack";
public const string SignBinary = "sign-binary";
public const string SignPackage = "sign-package";
public const string CopyPackOutput = "copy-pack-output";
}
static void Main(string[] args)
{
Target(Targets.CleanBuildOutput, () =>
{
//Run("dotnet", "clean -c Release -v m --nologo", echoPrefix: Prefix);
});
Target(Targets.Build, DependsOn(Targets.CleanBuildOutput), () =>
{
Run("dotnet", "build -c Release --nologo", echoPrefix: Prefix);
});
Target(Targets.SignBinary, DependsOn(Targets.Build), () =>
{
Sign("./src/bin/Release", "*.dll");
});
Target(Targets.Test, DependsOn(Targets.Build), () =>
{
Run("dotnet", $"test -c Release --no-build", echoPrefix: Prefix);
});
Target(Targets.CleanPackOutput, () =>
{
if (Directory.Exists(packOutput))
{
Directory.Delete(packOutput, true);
}
});
Target(Targets.Pack, DependsOn(Targets.Build, Targets.CleanPackOutput), () =>
{
var project = Directory.GetFiles("./src", "*.csproj", SearchOption.TopDirectoryOnly).OrderBy(_ => _).First();
Run("dotnet", $"pack {project} -c Release -o \"{Directory.CreateDirectory(packOutput).FullName}\" --no-build --nologo", echoPrefix: Prefix);
});
Target(Targets.SignPackage, DependsOn(Targets.Pack), () =>
{
Sign(packOutput, "*.nupkg");
});
Target(Targets.CopyPackOutput, DependsOn(Targets.Pack), () =>
{
Directory.CreateDirectory(packOutputCopy);
foreach (var file in Directory.GetFiles(packOutput))
{
File.Copy(file, Path.Combine(packOutputCopy, Path.GetFileName(file)), true);
}
});
Target("quick", DependsOn(Targets.CopyPackOutput));
Target("default", DependsOn(Targets.Test, Targets.CopyPackOutput));
Target("sign", DependsOn(Targets.SignBinary, Targets.Test, Targets.SignPackage, Targets.CopyPackOutput));
RunTargetsAndExit(args, ex => ex is SimpleExec.NonZeroExitCodeException || ex.Message.EndsWith(envVarMissing), Prefix);
}
private static void Sign(string path, string searchTerm)
{
var signClientSecret = Environment.GetEnvironmentVariable("SignClientSecret");
if (string.IsNullOrWhiteSpace(signClientSecret))
{
throw new Exception($"SignClientSecret{envVarMissing}");
}
foreach (var file in Directory.GetFiles(path, searchTerm, SearchOption.AllDirectories))
{
Console.WriteLine($" Signing {file}");
Run("dotnet", $"SignClient sign -c ../../signClient.json -i {file} -r sc-ids@dotnetfoundation.org -s \"{signClientSecret}\" -n 'IdentityServer4'", noEcho: true);
}
}
}
}
| {
"content_hash": "12694656e261cbcd958e52b6dfe058ef",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 177,
"avg_line_length": 38.61538461538461,
"alnum_prop": 0.5448207171314741,
"repo_name": "IdentityServer/IdentityServer4",
"id": "bade30f962c49269ee3bd3226911b3176c084d54",
"size": "4018",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "src/build/Program.Partial.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1647"
},
{
"name": "C#",
"bytes": "3033883"
},
{
"name": "CSS",
"bytes": "1491"
},
{
"name": "HTML",
"bytes": "74820"
},
{
"name": "JavaScript",
"bytes": "807"
},
{
"name": "PowerShell",
"bytes": "1832"
},
{
"name": "SCSS",
"bytes": "638544"
},
{
"name": "Shell",
"bytes": "1080"
},
{
"name": "TSQL",
"bytes": "17480"
}
],
"symlink_target": ""
} |
#include "config.h"
#include "core/css/CSSCalculationValue.h"
#include "core/css/CSSPrimitiveValueMappings.h"
#include "core/css/resolver/StyleResolver.h"
#include "wtf/MathExtras.h"
#include "wtf/OwnPtr.h"
#include "wtf/text/StringBuilder.h"
static const int maxExpressionDepth = 100;
enum ParseState {
OK,
TooDeep,
NoMoreTokens
};
namespace blink {
static CalculationCategory unitCategory(CSSPrimitiveValue::UnitType type)
{
switch (type) {
case CSSPrimitiveValue::CSS_NUMBER:
return CalcNumber;
case CSSPrimitiveValue::CSS_PERCENTAGE:
return CalcPercent;
case CSSPrimitiveValue::CSS_EMS:
case CSSPrimitiveValue::CSS_EXS:
case CSSPrimitiveValue::CSS_PX:
case CSSPrimitiveValue::CSS_CM:
case CSSPrimitiveValue::CSS_MM:
case CSSPrimitiveValue::CSS_IN:
case CSSPrimitiveValue::CSS_PT:
case CSSPrimitiveValue::CSS_PC:
case CSSPrimitiveValue::CSS_REMS:
case CSSPrimitiveValue::CSS_CHS:
case CSSPrimitiveValue::CSS_VW:
case CSSPrimitiveValue::CSS_VH:
case CSSPrimitiveValue::CSS_VMIN:
case CSSPrimitiveValue::CSS_VMAX:
return CalcLength;
case CSSPrimitiveValue::CSS_DEG:
case CSSPrimitiveValue::CSS_GRAD:
case CSSPrimitiveValue::CSS_RAD:
case CSSPrimitiveValue::CSS_TURN:
return CalcAngle;
case CSSPrimitiveValue::CSS_MS:
case CSSPrimitiveValue::CSS_S:
return CalcTime;
case CSSPrimitiveValue::CSS_HZ:
case CSSPrimitiveValue::CSS_KHZ:
return CalcFrequency;
default:
return CalcOther;
}
}
static bool hasDoubleValue(CSSPrimitiveValue::UnitType type)
{
switch (type) {
case CSSPrimitiveValue::CSS_NUMBER:
case CSSPrimitiveValue::CSS_PERCENTAGE:
case CSSPrimitiveValue::CSS_EMS:
case CSSPrimitiveValue::CSS_EXS:
case CSSPrimitiveValue::CSS_CHS:
case CSSPrimitiveValue::CSS_REMS:
case CSSPrimitiveValue::CSS_PX:
case CSSPrimitiveValue::CSS_CM:
case CSSPrimitiveValue::CSS_MM:
case CSSPrimitiveValue::CSS_IN:
case CSSPrimitiveValue::CSS_PT:
case CSSPrimitiveValue::CSS_PC:
case CSSPrimitiveValue::CSS_DEG:
case CSSPrimitiveValue::CSS_RAD:
case CSSPrimitiveValue::CSS_GRAD:
case CSSPrimitiveValue::CSS_TURN:
case CSSPrimitiveValue::CSS_MS:
case CSSPrimitiveValue::CSS_S:
case CSSPrimitiveValue::CSS_HZ:
case CSSPrimitiveValue::CSS_KHZ:
case CSSPrimitiveValue::CSS_DIMENSION:
case CSSPrimitiveValue::CSS_VW:
case CSSPrimitiveValue::CSS_VH:
case CSSPrimitiveValue::CSS_VMIN:
case CSSPrimitiveValue::CSS_VMAX:
case CSSPrimitiveValue::CSS_DPPX:
case CSSPrimitiveValue::CSS_DPI:
case CSSPrimitiveValue::CSS_DPCM:
case CSSPrimitiveValue::CSS_FR:
return true;
case CSSPrimitiveValue::CSS_UNKNOWN:
case CSSPrimitiveValue::CSS_STRING:
case CSSPrimitiveValue::CSS_URI:
case CSSPrimitiveValue::CSS_IDENT:
case CSSPrimitiveValue::CSS_ATTR:
case CSSPrimitiveValue::CSS_COUNTER:
case CSSPrimitiveValue::CSS_RECT:
case CSSPrimitiveValue::CSS_RGBCOLOR:
case CSSPrimitiveValue::CSS_PAIR:
case CSSPrimitiveValue::CSS_UNICODE_RANGE:
case CSSPrimitiveValue::CSS_PARSER_HEXCOLOR:
case CSSPrimitiveValue::CSS_COUNTER_NAME:
case CSSPrimitiveValue::CSS_SHAPE:
case CSSPrimitiveValue::CSS_QUAD:
case CSSPrimitiveValue::CSS_CALC:
case CSSPrimitiveValue::CSS_CALC_PERCENTAGE_WITH_NUMBER:
case CSSPrimitiveValue::CSS_CALC_PERCENTAGE_WITH_LENGTH:
case CSSPrimitiveValue::CSS_PROPERTY_ID:
case CSSPrimitiveValue::CSS_VALUE_ID:
return false;
};
ASSERT_NOT_REACHED();
return false;
}
static String buildCSSText(const String& expression)
{
StringBuilder result;
result.appendLiteral("calc");
bool expressionHasSingleTerm = expression[0] != '(';
if (expressionHasSingleTerm)
result.append('(');
result.append(expression);
if (expressionHasSingleTerm)
result.append(')');
return result.toString();
}
String CSSCalcValue::customCSSText() const
{
return buildCSSText(m_expression->customCSSText());
}
bool CSSCalcValue::equals(const CSSCalcValue& other) const
{
return compareCSSValuePtr(m_expression, other.m_expression);
}
double CSSCalcValue::clampToPermittedRange(double value) const
{
return m_nonNegative && value < 0 ? 0 : value;
}
double CSSCalcValue::doubleValue() const
{
return clampToPermittedRange(m_expression->doubleValue());
}
double CSSCalcValue::computeLengthPx(const CSSToLengthConversionData& conversionData) const
{
return clampToPermittedRange(m_expression->computeLengthPx(conversionData));
}
DEFINE_EMPTY_DESTRUCTOR_WILL_BE_REMOVED(CSSCalcExpressionNode)
class CSSCalcPrimitiveValue FINAL : public CSSCalcExpressionNode {
WTF_MAKE_FAST_ALLOCATED_WILL_BE_REMOVED;
public:
static PassRefPtrWillBeRawPtr<CSSCalcPrimitiveValue> create(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> value, bool isInteger)
{
return adoptRefWillBeNoop(new CSSCalcPrimitiveValue(value, isInteger));
}
static PassRefPtrWillBeRawPtr<CSSCalcPrimitiveValue> create(double value, CSSPrimitiveValue::UnitType type, bool isInteger)
{
if (std::isnan(value) || std::isinf(value))
return nullptr;
return adoptRefWillBeNoop(new CSSCalcPrimitiveValue(CSSPrimitiveValue::create(value, type).get(), isInteger));
}
virtual bool isZero() const OVERRIDE
{
return !m_value->getDoubleValue();
}
virtual String customCSSText() const OVERRIDE
{
return m_value->cssText();
}
virtual void accumulatePixelsAndPercent(const CSSToLengthConversionData& conversionData, PixelsAndPercent& value, float multiplier) const OVERRIDE
{
switch (m_category) {
case CalcLength:
value.pixels += m_value->computeLength<float>(conversionData) * multiplier;
break;
case CalcPercent:
ASSERT(m_value->isPercentage());
value.percent += m_value->getDoubleValue() * multiplier;
break;
default:
ASSERT_NOT_REACHED();
}
}
virtual double doubleValue() const OVERRIDE
{
if (hasDoubleValue(primitiveType()))
return m_value->getDoubleValue();
ASSERT_NOT_REACHED();
return 0;
}
virtual double computeLengthPx(const CSSToLengthConversionData& conversionData) const OVERRIDE
{
switch (m_category) {
case CalcLength:
return m_value->computeLength<double>(conversionData);
case CalcNumber:
case CalcPercent:
return m_value->getDoubleValue();
case CalcAngle:
case CalcFrequency:
case CalcPercentLength:
case CalcPercentNumber:
case CalcTime:
case CalcOther:
ASSERT_NOT_REACHED();
break;
}
ASSERT_NOT_REACHED();
return 0;
}
virtual void accumulateLengthArray(CSSLengthArray& lengthArray, double multiplier) const
{
ASSERT(category() != CalcNumber);
m_value->accumulateLengthArray(lengthArray, multiplier);
}
virtual bool equals(const CSSCalcExpressionNode& other) const OVERRIDE
{
if (type() != other.type())
return false;
return compareCSSValuePtr(m_value, static_cast<const CSSCalcPrimitiveValue&>(other).m_value);
}
virtual Type type() const OVERRIDE { return CssCalcPrimitiveValue; }
virtual CSSPrimitiveValue::UnitType primitiveType() const OVERRIDE
{
return m_value->primitiveType();
}
virtual void trace(Visitor* visitor)
{
visitor->trace(m_value);
CSSCalcExpressionNode::trace(visitor);
}
private:
CSSCalcPrimitiveValue(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> value, bool isInteger)
: CSSCalcExpressionNode(unitCategory(value->primitiveType()), isInteger)
, m_value(value)
{
}
RefPtrWillBeMember<CSSPrimitiveValue> m_value;
};
static const CalculationCategory addSubtractResult[CalcOther][CalcOther] = {
// CalcNumber CalcLength CalcPercent CalcPercentNumber CalcPercentLength CalcAngle CalcTime CalcFrequency
/* CalcNumber */ { CalcNumber, CalcOther, CalcPercentNumber, CalcPercentNumber, CalcOther, CalcOther, CalcOther, CalcOther },
/* CalcLength */ { CalcOther, CalcLength, CalcPercentLength, CalcOther, CalcPercentLength, CalcOther, CalcOther, CalcOther },
/* CalcPercent */ { CalcPercentNumber, CalcPercentLength, CalcPercent, CalcPercentNumber, CalcPercentLength, CalcOther, CalcOther, CalcOther },
/* CalcPercentNumber */ { CalcPercentNumber, CalcOther, CalcPercentNumber, CalcPercentNumber, CalcOther, CalcOther, CalcOther, CalcOther },
/* CalcPercentLength */ { CalcOther, CalcPercentLength, CalcPercentLength, CalcOther, CalcPercentLength, CalcOther, CalcOther, CalcOther },
/* CalcAngle */ { CalcOther, CalcOther, CalcOther, CalcOther, CalcOther, CalcAngle, CalcOther, CalcOther },
/* CalcTime */ { CalcOther, CalcOther, CalcOther, CalcOther, CalcOther, CalcOther, CalcTime, CalcOther },
/* CalcFrequency */ { CalcOther, CalcOther, CalcOther, CalcOther, CalcOther, CalcOther, CalcOther, CalcFrequency }
};
static CalculationCategory determineCategory(const CSSCalcExpressionNode& leftSide, const CSSCalcExpressionNode& rightSide, CalcOperator op)
{
CalculationCategory leftCategory = leftSide.category();
CalculationCategory rightCategory = rightSide.category();
if (leftCategory == CalcOther || rightCategory == CalcOther)
return CalcOther;
switch (op) {
case CalcAdd:
case CalcSubtract:
return addSubtractResult[leftCategory][rightCategory];
case CalcMultiply:
if (leftCategory != CalcNumber && rightCategory != CalcNumber)
return CalcOther;
return leftCategory == CalcNumber ? rightCategory : leftCategory;
case CalcDivide:
if (rightCategory != CalcNumber || rightSide.isZero())
return CalcOther;
return leftCategory;
}
ASSERT_NOT_REACHED();
return CalcOther;
}
static bool isIntegerResult(const CSSCalcExpressionNode* leftSide, const CSSCalcExpressionNode* rightSide, CalcOperator op)
{
// Not testing for actual integer values.
// Performs W3C spec's type checking for calc integers.
// http://www.w3.org/TR/css3-values/#calc-type-checking
return op != CalcDivide && leftSide->isInteger() && rightSide->isInteger();
}
class CSSCalcBinaryOperation FINAL : public CSSCalcExpressionNode {
public:
static PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> create(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> leftSide, PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> rightSide, CalcOperator op)
{
ASSERT(leftSide->category() != CalcOther && rightSide->category() != CalcOther);
CalculationCategory newCategory = determineCategory(*leftSide, *rightSide, op);
if (newCategory == CalcOther)
return nullptr;
return adoptRefWillBeNoop(new CSSCalcBinaryOperation(leftSide, rightSide, op, newCategory));
}
static PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> createSimplified(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> leftSide, PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> rightSide, CalcOperator op)
{
CalculationCategory leftCategory = leftSide->category();
CalculationCategory rightCategory = rightSide->category();
ASSERT(leftCategory != CalcOther && rightCategory != CalcOther);
bool isInteger = isIntegerResult(leftSide.get(), rightSide.get(), op);
// Simplify numbers.
if (leftCategory == CalcNumber && rightCategory == CalcNumber) {
return CSSCalcPrimitiveValue::create(evaluateOperator(leftSide->doubleValue(), rightSide->doubleValue(), op), CSSPrimitiveValue::CSS_NUMBER, isInteger);
}
// Simplify addition and subtraction between same types.
if (op == CalcAdd || op == CalcSubtract) {
if (leftCategory == rightSide->category()) {
CSSPrimitiveValue::UnitType leftType = leftSide->primitiveType();
if (hasDoubleValue(leftType)) {
CSSPrimitiveValue::UnitType rightType = rightSide->primitiveType();
if (leftType == rightType)
return CSSCalcPrimitiveValue::create(evaluateOperator(leftSide->doubleValue(), rightSide->doubleValue(), op), leftType, isInteger);
CSSPrimitiveValue::UnitCategory leftUnitCategory = CSSPrimitiveValue::unitCategory(leftType);
if (leftUnitCategory != CSSPrimitiveValue::UOther && leftUnitCategory == CSSPrimitiveValue::unitCategory(rightType)) {
CSSPrimitiveValue::UnitType canonicalType = CSSPrimitiveValue::canonicalUnitTypeForCategory(leftUnitCategory);
if (canonicalType != CSSPrimitiveValue::CSS_UNKNOWN) {
double leftValue = leftSide->doubleValue() * CSSPrimitiveValue::conversionToCanonicalUnitsScaleFactor(leftType);
double rightValue = rightSide->doubleValue() * CSSPrimitiveValue::conversionToCanonicalUnitsScaleFactor(rightType);
return CSSCalcPrimitiveValue::create(evaluateOperator(leftValue, rightValue, op), canonicalType, isInteger);
}
}
}
}
} else {
// Simplify multiplying or dividing by a number for simplifiable types.
ASSERT(op == CalcMultiply || op == CalcDivide);
CSSCalcExpressionNode* numberSide = getNumberSide(leftSide.get(), rightSide.get());
if (!numberSide)
return create(leftSide, rightSide, op);
if (numberSide == leftSide && op == CalcDivide)
return nullptr;
CSSCalcExpressionNode* otherSide = leftSide == numberSide ? rightSide.get() : leftSide.get();
double number = numberSide->doubleValue();
if (std::isnan(number) || std::isinf(number))
return nullptr;
if (op == CalcDivide && !number)
return nullptr;
CSSPrimitiveValue::UnitType otherType = otherSide->primitiveType();
if (hasDoubleValue(otherType))
return CSSCalcPrimitiveValue::create(evaluateOperator(otherSide->doubleValue(), number, op), otherType, isInteger);
}
return create(leftSide, rightSide, op);
}
virtual bool isZero() const OVERRIDE
{
return !doubleValue();
}
virtual void accumulatePixelsAndPercent(const CSSToLengthConversionData& conversionData, PixelsAndPercent& value, float multiplier) const OVERRIDE
{
switch (m_operator) {
case CalcAdd:
m_leftSide->accumulatePixelsAndPercent(conversionData, value, multiplier);
m_rightSide->accumulatePixelsAndPercent(conversionData, value, multiplier);
break;
case CalcSubtract:
m_leftSide->accumulatePixelsAndPercent(conversionData, value, multiplier);
m_rightSide->accumulatePixelsAndPercent(conversionData, value, -multiplier);
break;
case CalcMultiply:
ASSERT((m_leftSide->category() == CalcNumber) != (m_rightSide->category() == CalcNumber));
if (m_leftSide->category() == CalcNumber)
m_rightSide->accumulatePixelsAndPercent(conversionData, value, multiplier * m_leftSide->doubleValue());
else
m_leftSide->accumulatePixelsAndPercent(conversionData, value, multiplier * m_rightSide->doubleValue());
break;
case CalcDivide:
ASSERT(m_rightSide->category() == CalcNumber);
m_leftSide->accumulatePixelsAndPercent(conversionData, value, multiplier / m_rightSide->doubleValue());
break;
default:
ASSERT_NOT_REACHED();
}
}
virtual double doubleValue() const OVERRIDE
{
return evaluate(m_leftSide->doubleValue(), m_rightSide->doubleValue());
}
virtual double computeLengthPx(const CSSToLengthConversionData& conversionData) const OVERRIDE
{
const double leftValue = m_leftSide->computeLengthPx(conversionData);
const double rightValue = m_rightSide->computeLengthPx(conversionData);
return evaluate(leftValue, rightValue);
}
virtual void accumulateLengthArray(CSSLengthArray& lengthArray, double multiplier) const
{
switch (m_operator) {
case CalcAdd:
m_leftSide->accumulateLengthArray(lengthArray, multiplier);
m_rightSide->accumulateLengthArray(lengthArray, multiplier);
break;
case CalcSubtract:
m_leftSide->accumulateLengthArray(lengthArray, multiplier);
m_rightSide->accumulateLengthArray(lengthArray, -multiplier);
break;
case CalcMultiply:
ASSERT((m_leftSide->category() == CalcNumber) != (m_rightSide->category() == CalcNumber));
if (m_leftSide->category() == CalcNumber)
m_rightSide->accumulateLengthArray(lengthArray, multiplier * m_leftSide->doubleValue());
else
m_leftSide->accumulateLengthArray(lengthArray, multiplier * m_rightSide->doubleValue());
break;
case CalcDivide:
ASSERT(m_rightSide->category() == CalcNumber);
m_leftSide->accumulateLengthArray(lengthArray, multiplier / m_rightSide->doubleValue());
break;
default:
ASSERT_NOT_REACHED();
}
}
static String buildCSSText(const String& leftExpression, const String& rightExpression, CalcOperator op)
{
StringBuilder result;
result.append('(');
result.append(leftExpression);
result.append(' ');
result.append(static_cast<char>(op));
result.append(' ');
result.append(rightExpression);
result.append(')');
return result.toString();
}
virtual String customCSSText() const OVERRIDE
{
return buildCSSText(m_leftSide->customCSSText(), m_rightSide->customCSSText(), m_operator);
}
virtual bool equals(const CSSCalcExpressionNode& exp) const OVERRIDE
{
if (type() != exp.type())
return false;
const CSSCalcBinaryOperation& other = static_cast<const CSSCalcBinaryOperation&>(exp);
return compareCSSValuePtr(m_leftSide, other.m_leftSide)
&& compareCSSValuePtr(m_rightSide, other.m_rightSide)
&& m_operator == other.m_operator;
}
virtual Type type() const OVERRIDE { return CssCalcBinaryOperation; }
virtual CSSPrimitiveValue::UnitType primitiveType() const OVERRIDE
{
switch (m_category) {
case CalcNumber:
ASSERT(m_leftSide->category() == CalcNumber && m_rightSide->category() == CalcNumber);
return CSSPrimitiveValue::CSS_NUMBER;
case CalcLength:
case CalcPercent: {
if (m_leftSide->category() == CalcNumber)
return m_rightSide->primitiveType();
if (m_rightSide->category() == CalcNumber)
return m_leftSide->primitiveType();
CSSPrimitiveValue::UnitType leftType = m_leftSide->primitiveType();
if (leftType == m_rightSide->primitiveType())
return leftType;
return CSSPrimitiveValue::CSS_UNKNOWN;
}
case CalcAngle:
return CSSPrimitiveValue::CSS_DEG;
case CalcTime:
return CSSPrimitiveValue::CSS_MS;
case CalcFrequency:
return CSSPrimitiveValue::CSS_HZ;
case CalcPercentLength:
case CalcPercentNumber:
case CalcOther:
return CSSPrimitiveValue::CSS_UNKNOWN;
}
ASSERT_NOT_REACHED();
return CSSPrimitiveValue::CSS_UNKNOWN;
}
virtual void trace(Visitor* visitor)
{
visitor->trace(m_leftSide);
visitor->trace(m_rightSide);
CSSCalcExpressionNode::trace(visitor);
}
private:
CSSCalcBinaryOperation(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> leftSide, PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> rightSide, CalcOperator op, CalculationCategory category)
: CSSCalcExpressionNode(category, isIntegerResult(leftSide.get(), rightSide.get(), op))
, m_leftSide(leftSide)
, m_rightSide(rightSide)
, m_operator(op)
{
}
static CSSCalcExpressionNode* getNumberSide(CSSCalcExpressionNode* leftSide, CSSCalcExpressionNode* rightSide)
{
if (leftSide->category() == CalcNumber)
return leftSide;
if (rightSide->category() == CalcNumber)
return rightSide;
return 0;
}
double evaluate(double leftSide, double rightSide) const
{
return evaluateOperator(leftSide, rightSide, m_operator);
}
static double evaluateOperator(double leftValue, double rightValue, CalcOperator op)
{
switch (op) {
case CalcAdd:
return leftValue + rightValue;
case CalcSubtract:
return leftValue - rightValue;
case CalcMultiply:
return leftValue * rightValue;
case CalcDivide:
if (rightValue)
return leftValue / rightValue;
return std::numeric_limits<double>::quiet_NaN();
}
return 0;
}
const RefPtrWillBeMember<CSSCalcExpressionNode> m_leftSide;
const RefPtrWillBeMember<CSSCalcExpressionNode> m_rightSide;
const CalcOperator m_operator;
};
static ParseState checkDepthAndIndex(int* depth, unsigned index, CSSParserValueList* tokens)
{
(*depth)++;
if (*depth > maxExpressionDepth)
return TooDeep;
if (index >= tokens->size())
return NoMoreTokens;
return OK;
}
class CSSCalcExpressionNodeParser {
STACK_ALLOCATED();
public:
PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> parseCalc(CSSParserValueList* tokens)
{
unsigned index = 0;
Value result;
bool ok = parseValueExpression(tokens, 0, &index, &result);
ASSERT_WITH_SECURITY_IMPLICATION(index <= tokens->size());
if (!ok || index != tokens->size())
return nullptr;
return result.value;
}
private:
struct Value {
STACK_ALLOCATED();
public:
RefPtrWillBeMember<CSSCalcExpressionNode> value;
};
char operatorValue(CSSParserValueList* tokens, unsigned index)
{
if (index >= tokens->size())
return 0;
CSSParserValue* value = tokens->valueAt(index);
if (value->unit != CSSParserValue::Operator)
return 0;
return value->iValue;
}
bool parseValue(CSSParserValueList* tokens, unsigned* index, Value* result)
{
CSSParserValue* parserValue = tokens->valueAt(*index);
if (parserValue->unit >= CSSParserValue::Operator)
return false;
CSSPrimitiveValue::UnitType type = static_cast<CSSPrimitiveValue::UnitType>(parserValue->unit);
if (unitCategory(type) == CalcOther)
return false;
result->value = CSSCalcPrimitiveValue::create(
CSSPrimitiveValue::create(parserValue->fValue, type), parserValue->isInt);
++*index;
return true;
}
bool parseValueTerm(CSSParserValueList* tokens, int depth, unsigned* index, Value* result)
{
if (checkDepthAndIndex(&depth, *index, tokens) != OK)
return false;
if (operatorValue(tokens, *index) == '(') {
unsigned currentIndex = *index + 1;
if (!parseValueExpression(tokens, depth, ¤tIndex, result))
return false;
if (operatorValue(tokens, currentIndex) != ')')
return false;
*index = currentIndex + 1;
return true;
}
return parseValue(tokens, index, result);
}
bool parseValueMultiplicativeExpression(CSSParserValueList* tokens, int depth, unsigned* index, Value* result)
{
if (checkDepthAndIndex(&depth, *index, tokens) != OK)
return false;
if (!parseValueTerm(tokens, depth, index, result))
return false;
while (*index < tokens->size() - 1) {
char operatorCharacter = operatorValue(tokens, *index);
if (operatorCharacter != CalcMultiply && operatorCharacter != CalcDivide)
break;
++*index;
Value rhs;
if (!parseValueTerm(tokens, depth, index, &rhs))
return false;
result->value = CSSCalcBinaryOperation::createSimplified(result->value, rhs.value, static_cast<CalcOperator>(operatorCharacter));
if (!result->value)
return false;
}
ASSERT_WITH_SECURITY_IMPLICATION(*index <= tokens->size());
return true;
}
bool parseAdditiveValueExpression(CSSParserValueList* tokens, int depth, unsigned* index, Value* result)
{
if (checkDepthAndIndex(&depth, *index, tokens) != OK)
return false;
if (!parseValueMultiplicativeExpression(tokens, depth, index, result))
return false;
while (*index < tokens->size() - 1) {
char operatorCharacter = operatorValue(tokens, *index);
if (operatorCharacter != CalcAdd && operatorCharacter != CalcSubtract)
break;
++*index;
Value rhs;
if (!parseValueMultiplicativeExpression(tokens, depth, index, &rhs))
return false;
result->value = CSSCalcBinaryOperation::createSimplified(result->value, rhs.value, static_cast<CalcOperator>(operatorCharacter));
if (!result->value)
return false;
}
ASSERT_WITH_SECURITY_IMPLICATION(*index <= tokens->size());
return true;
}
bool parseValueExpression(CSSParserValueList* tokens, int depth, unsigned* index, Value* result)
{
return parseAdditiveValueExpression(tokens, depth, index, result);
}
};
PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(PassRefPtrWillBeRawPtr<CSSPrimitiveValue> value, bool isInteger)
{
return CSSCalcPrimitiveValue::create(value, isInteger);
}
PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> leftSide, PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> rightSide, CalcOperator op)
{
return CSSCalcBinaryOperation::create(leftSide, rightSide, op);
}
PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(double pixels, double percent)
{
return createExpressionNode(
createExpressionNode(CSSPrimitiveValue::create(pixels, CSSPrimitiveValue::CSS_PX), pixels == trunc(pixels)),
createExpressionNode(CSSPrimitiveValue::create(percent, CSSPrimitiveValue::CSS_PERCENTAGE), percent == trunc(percent)),
CalcAdd);
}
PassRefPtrWillBeRawPtr<CSSCalcValue> CSSCalcValue::create(CSSParserString name, CSSParserValueList* parserValueList, ValueRange range)
{
CSSCalcExpressionNodeParser parser;
RefPtrWillBeRawPtr<CSSCalcExpressionNode> expression = nullptr;
if (equalIgnoringCase(name, "calc") || equalIgnoringCase(name, "-webkit-calc"))
expression = parser.parseCalc(parserValueList);
// FIXME calc (http://webkit.org/b/16662) Add parsing for min and max here
return expression ? adoptRefWillBeNoop(new CSSCalcValue(expression, range)) : nullptr;
}
PassRefPtrWillBeRawPtr<CSSCalcValue> CSSCalcValue::create(PassRefPtrWillBeRawPtr<CSSCalcExpressionNode> expression, ValueRange range)
{
return adoptRefWillBeNoop(new CSSCalcValue(expression, range));
}
void CSSCalcValue::traceAfterDispatch(Visitor* visitor)
{
visitor->trace(m_expression);
CSSValue::traceAfterDispatch(visitor);
}
} // namespace blink
| {
"content_hash": "e59927c613f87653995a9d124815dff9",
"timestamp": "",
"source": "github",
"line_count": 746,
"max_line_length": 210,
"avg_line_length": 37.95844504021448,
"alnum_prop": 0.6640533954868101,
"repo_name": "temasek/android_external_chromium_org_third_party_WebKit",
"id": "cd6008d373694a9e274762584d58274b2ff54750",
"size": "29885",
"binary": false,
"copies": "9",
"ref": "refs/heads/cm-12.1",
"path": "Source/core/css/CSSCalculationValue.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "14584"
},
{
"name": "Bison",
"bytes": "64394"
},
{
"name": "C",
"bytes": "105000"
},
{
"name": "C++",
"bytes": "41917773"
},
{
"name": "CSS",
"bytes": "386919"
},
{
"name": "Groff",
"bytes": "26536"
},
{
"name": "HTML",
"bytes": "11501040"
},
{
"name": "Java",
"bytes": "66510"
},
{
"name": "JavaScript",
"bytes": "9328662"
},
{
"name": "Makefile",
"bytes": "99861997"
},
{
"name": "Objective-C",
"bytes": "48021"
},
{
"name": "Objective-C++",
"bytes": "377388"
},
{
"name": "PHP",
"bytes": "3941"
},
{
"name": "Perl",
"bytes": "490099"
},
{
"name": "Python",
"bytes": "3712782"
},
{
"name": "Ruby",
"bytes": "141818"
},
{
"name": "Shell",
"bytes": "8841"
}
],
"symlink_target": ""
} |
import chai from 'chai';
import delayedQueueLib from '../lib/delayedQueueAmqp';
import amqp from 'amqplib';
const expect = chai.expect;
const config = {
url: 'amqp://guest:guest@localhost:5672',
ack: true
};
const delayedQueue = delayedQueueLib(config);
function cleanUpRabbitMQ(done) {
amqp
.connect(config.url)
.then(conn => {
conn
.createChannel()
.then(ch => {
return Promise.all([
ch.deleteQueue('transactionCheck1'),
ch.deleteQueue('transactionCheck2'),
ch.deleteExchange('transactionChecks')
]);
})
.then(() => {
done();
})
});
}
before(done => cleanUpRabbitMQ(done));
describe('The delayed queue', () => {
it('should create a consumer', done => {
// Set up consumer
delayedQueue.consume('transactionCheck1', msg => {})
.then(() => {
// Check if consumer exists
amqp
.connect(config.url)
.then(conn => {
conn
.createChannel()
.then(ch => {
ch.checkQueue('transactionCheck1')
.then(res => {
done();
});
});
});
});
});
it('should send a delayed message', done => {
delayedQueue.consume('transactionCheck2', msg => {
let parsedMsg = msg.content.toString();
expect(msg).to.be.defined;
expect(msg.properties.headers).to.be.defined;
expect(msg.properties.headers['x-delay']).to.be.equal(500);
expect(parsedMsg).to.be.a('string');
expect(parsedMsg).to.have.string('transactionId1');
done();
})
// listen for transaction outcome on listener 'api2'
.then(res => {
delayedQueue.send('transactionCheck2', 'transactionId1', 500);
});
});
});
| {
"content_hash": "4bbc7b0d1823bc9928dee21fe6a0a590",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 68,
"avg_line_length": 26.314285714285713,
"alnum_prop": 0.5439739413680782,
"repo_name": "mfressdorf/master-thesis",
"id": "cbe2093c79167abca08a073b536e2fe363bc8046",
"size": "1842",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/transaction-state-checker/test/delayedQueueSpec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "160404"
},
{
"name": "Lua",
"bytes": "2361"
}
],
"symlink_target": ""
} |
using System;
using System.Diagnostics;
using System.Dynamic;
using System.Threading;
using L4p.Common.DumpToLogs;
using L4p.Common.IoCs;
using L4p.Common.Loggers;
using L4p.Common.PubSub.utils;
namespace L4p.Common.PubSub.client
{
interface ILocalFactory : IHaveDump
{
Topic make_topic(Type type);
HandlerInfo make_handler<T>(Topic topic, Action<T> call, Func<T, bool> filter, StackFrame filterAt);
}
class LocalFactory : ILocalFactory
{
#region counters
class Counters
{
public int NonTransferableFilters;
}
#endregion
#region members
private readonly Counters _counters;
private readonly ILogFile _log;
private readonly IFiltersEngine _filters;
private readonly ITopicsRepo _topics;
#endregion
#region construction
public static ILocalFactory New(IIoC ioc)
{
return
new LocalFactory(ioc);
}
private LocalFactory(IIoC ioc)
{
_counters = new Counters();
_log = ioc.Resolve<ILogFile>();
_filters = ioc.Resolve<IFiltersEngine>();
_topics = ioc.Resolve<ITopicsRepo>();
}
#endregion
private PHandlerAction make_phandler<T>(Action<T> handler)
{
return
msg => handler((T)msg);
}
private PFilterFunc make_pfilter<T>(Func<T, bool> filter)
{
if (filter == null)
return null;
return
msg => filter((T) msg);
}
#region private
#endregion
#region interface
Topic ILocalFactory.make_topic(Type type)
{
var topicName = type.Name;
var topicGuid = type.GUID;
var details = _topics.GetTopicDetails(topicGuid, topicName);
var topic = new Topic
{
Name = topicName,
Guid = topicGuid,
Type = type,
Details = details
};
return topic;
}
HandlerInfo ILocalFactory.make_handler<T>(Topic topic, Action<T> call, Func<T, bool> filter, StackFrame filterAt)
{
var filterInfo = _filters.MakeFilterInfo(filter, filterAt);
if (filterInfo != null)
if (filterInfo.IsTransferable == false)
{
Interlocked.Increment(ref _counters.NonTransferableFilters);
_log.Warn("Topic '{0}': filter '{1}' ({2}) can't be transferred (using member variables in lambda?)", topic.Name, filter.Method.Name);
}
var handler = new HandlerInfo
{
Topic = topic,
Call = make_phandler(call),
Filter = make_pfilter(filter),
FilterInfo = filterInfo
};
return handler;
}
ExpandoObject IHaveDump.Dump(dynamic root)
{
if (root == null)
root = new ExpandoObject();
root.Counters = _counters;
return root;
}
#endregion
}
} | {
"content_hash": "7dd8ef9962ee0e6a75e3baadb112dd95",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 150,
"avg_line_length": 25.375,
"alnum_prop": 0.5258620689655172,
"repo_name": "Kidify/L4p",
"id": "03787cd3f75b7020f82c3be002e8944e733e712f",
"size": "3248",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "L4p.Common/PubSub/client/LocalFactory.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "661077"
},
{
"name": "JavaScript",
"bytes": "1298"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "5942fbc2dc4916244b9c86ffdf38c608",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "236e1379b2e5b24b6c4fe8f073cc2525e4471595",
"size": "187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Carex/Carex echinodes/ Syn. Carex straminea echinodes/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-16" http-equiv="Content-Type" />
<title _locid="PortabilityAnalysis0">.NET Portability Report</title>
<style>
/* Body style, for the entire document */
body {
background: #F3F3F4;
color: #1E1E1F;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
padding: 0;
margin: 0;
}
/* Header1 style, used for the main title */
h1 {
padding: 10px 0px 10px 10px;
font-size: 21pt;
background-color: #E2E2E2;
border-bottom: 1px #C1C1C2 solid;
color: #201F20;
margin: 0;
font-weight: normal;
}
/* Header2 style, used for "Overview" and other sections */
h2 {
font-size: 18pt;
font-weight: normal;
padding: 15px 0 5px 0;
margin: 0;
}
/* Header3 style, used for sub-sections, such as project name */
h3 {
font-weight: normal;
font-size: 15pt;
margin: 0;
padding: 15px 0 5px 0;
background-color: transparent;
}
h4 {
font-weight: normal;
font-size: 12pt;
margin: 0;
padding: 0 0 0 0;
background-color: transparent;
}
/* Color all hyperlinks one color */
a {
color: #1382CE;
}
/* Paragraph text (for longer informational messages) */
p {
font-size: 10pt;
}
/* Table styles */
table {
border-spacing: 0 0;
border-collapse: collapse;
font-size: 10pt;
}
table th {
background: #E7E7E8;
text-align: left;
text-decoration: none;
font-weight: normal;
padding: 3px 6px 3px 6px;
}
table td {
vertical-align: top;
padding: 3px 6px 5px 5px;
margin: 0px;
border: 1px solid #E7E7E8;
background: #F7F7F8;
}
.NoBreakingChanges {
color: darkgreen;
font-weight:bold;
}
.FewBreakingChanges {
color: orange;
font-weight:bold;
}
.ManyBreakingChanges {
color: red;
font-weight:bold;
}
.BreakDetails {
margin-left: 30px;
}
.CompatMessage {
font-style: italic;
font-size: 10pt;
}
.GoodMessage {
color: darkgreen;
}
/* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */
.localLink {
color: #1E1E1F;
background: #EEEEED;
text-decoration: none;
}
.localLink:hover {
color: #1382CE;
background: #FFFF99;
text-decoration: none;
}
/* Center text, used in the over views cells that contain message level counts */
.textCentered {
text-align: center;
}
/* The message cells in message tables should take up all avaliable space */
.messageCell {
width: 100%;
}
/* Padding around the content after the h1 */
#content {
padding: 0px 12px 12px 12px;
}
/* The overview table expands to width, with a max width of 97% */
#overview table {
width: auto;
max-width: 75%;
}
/* The messages tables are always 97% width */
#messages table {
width: 97%;
}
/* All Icons */
.IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded {
min-width: 18px;
min-height: 18px;
background-repeat: no-repeat;
background-position: center;
}
/* Success icon encoded */
.IconSuccessEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==);
}
/* Information icon encoded */
.IconInfoEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=);
}
/* Warning icon encoded */
.IconWarningEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==);
}
/* Error icon encoded */
.IconErrorEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=);
}
</style>
</head>
<body>
<h1 _locid="PortabilityReport">.NET Portability Report</h1>
<div id="content">
<div id="submissionId" style="font-size:8pt;">
<p>
<i>
Submission Id
94e817f7-a147-4892-a1e7-e9aeca87dc30
</i>
</p>
</div>
<h2 _locid="SummaryTitle">
<a name="Portability Summary"></a>Portability Summary
</h2>
<div id="summary">
<table>
<tbody>
<tr>
<th>Assembly</th>
<th>ASP.NET 5,Version=v1.0</th>
<th>Windows,Version=v8.1</th>
<th>.NET Framework,Version=v4.6</th>
<th>Windows Phone,Version=v8.1</th>
</tr>
<tr>
<td><strong><a href="#Autofac">Autofac</a></strong></td>
<td class="text-center">97.11 %</td>
<td class="text-center">95.26 %</td>
<td class="text-center">100.00 %</td>
<td class="text-center">95.26 %</td>
</tr>
</tbody>
</table>
</div>
<div id="details">
<a name="Autofac"><h3>Autofac</h3></a>
<table>
<tbody>
<tr>
<th>Target type</th>
<th>ASP.NET 5,Version=v1.0</th>
<th>Windows,Version=v8.1</th>
<th>.NET Framework,Version=v4.6</th>
<th>Windows Phone,Version=v8.1</th>
<th>Recommended changes</th>
</tr>
<tr>
<td>System.Attribute</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">GetCustomAttribute(System.Reflection.MemberInfo,System.Type,System.Boolean)</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>System.Delegate</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Use MethodInfo.CreateDelegate</td>
</tr>
<tr>
<td style="padding-left:2em">CreateDelegate(System.Type,System.Reflection.MethodInfo)</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Use MethodInfo.CreateDelegate</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>System.Reflection.Assembly</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Use Assembly.DefinedTypes</td>
</tr>
<tr>
<td style="padding-left:2em">GetTypes</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Use Assembly.DefinedTypes</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>System.Reflection.BindingFlags</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>System.Reflection.PropertyInfo</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Use PropertyInfo.SetMethod property</td>
</tr>
<tr>
<td style="padding-left:2em">GetAccessors(System.Boolean)</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">GetGetMethod</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Use PropertyInfo.GetMethod property</td>
</tr>
<tr>
<td style="padding-left:2em">GetGetMethod(System.Boolean)</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Use PropertyInfo.GetMethod property</td>
</tr>
<tr>
<td style="padding-left:2em">GetSetMethod</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Use PropertyInfo.SetMethod property</td>
</tr>
<tr>
<td style="padding-left:2em">GetSetMethod(System.Boolean)</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Use PropertyInfo.SetMethod property</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>System.Threading.Thread</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">get_CurrentThread</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">get_ManagedThreadId</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">MemoryBarrier</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Use System.Threading.Interlocked.MemoryBarrier instead</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>System.Type</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">get_Assembly</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>.GetTypeInfo().Assembly</td>
</tr>
<tr>
<td style="padding-left:2em">get_BaseType</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>.GetTypeInfo().BaseType</td>
</tr>
<tr>
<td style="padding-left:2em">get_ContainsGenericParameters</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>.GetTypeInfo().ContainsGenericParameters</td>
</tr>
<tr>
<td style="padding-left:2em">get_GenericParameterAttributes</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">get_IsAbstract</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>.GetTypeInfo().IsAbstract</td>
</tr>
<tr>
<td style="padding-left:2em">get_IsClass</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>.GetTypeInfo().IsClass</td>
</tr>
<tr>
<td style="padding-left:2em">get_IsEnum</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>.GetTypeInfo().IsEnum</td>
</tr>
<tr>
<td style="padding-left:2em">get_IsGenericType</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>.GetTypeInfo().IsGenericType</td>
</tr>
<tr>
<td style="padding-left:2em">get_IsGenericTypeDefinition</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>.GetTypeInfo().IsGenericTypeDefinition</td>
</tr>
<tr>
<td style="padding-left:2em">get_IsInterface</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>.GetTypeInfo().IsInterface</td>
</tr>
<tr>
<td style="padding-left:2em">get_IsValueType</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>.GetTypeInfo().IsValueType</td>
</tr>
<tr>
<td style="padding-left:2em">GetConstructor(System.Type[])</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">GetConstructors</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">GetGenericArguments</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">GetGenericParameterConstraints</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>.GetTypeInfo().GetGenericParameterConstraints()</td>
</tr>
<tr>
<td style="padding-left:2em">GetInterfaces</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">GetMethod(System.String)</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">GetMethod(System.String,System.Reflection.BindingFlags)</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>Equivalent available: Add using for System.Reflection, and reference System.Reflection.TypeExtensions </td>
</tr>
<tr>
<td style="padding-left:2em">GetProperties</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">GetProperties(System.Reflection.BindingFlags)</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">GetProperty(System.String)</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">IsAssignableFrom(System.Type)</td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td></td>
</tr>
<tr>
<td style="padding-left:2em">IsSubclassOf(System.Type)</td>
<td class="IconErrorEncoded"></td>
<td class="IconErrorEncoded"></td>
<td class="IconSuccessEncoded"></td>
<td class="IconErrorEncoded"></td>
<td>.GetTypeInfo().IsSubclassOf</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
<p>
<a href="#Portability Summary">Back to Summary</a>
</p>
</div>
</div>
</body>
</html> | {
"content_hash": "a76bc6c289c6b72abada42a7dc3e4db3",
"timestamp": "",
"source": "github",
"line_count": 723,
"max_line_length": 562,
"avg_line_length": 43.82572614107884,
"alnum_prop": 0.41109638326074605,
"repo_name": "kuhlenh/port-to-core",
"id": "0eccfb0938cef0e24dafd00ba7bfdc219678f2fc",
"size": "31686",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "Reports/au/autofac.3.5.2/Autofac-net40.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2323514650"
}
],
"symlink_target": ""
} |
package simpledb;
import java.util.*;
import java.io.*;
/**
* HeapPage stores pages of HeapFiles and implements the Page interface that
* is used by BufferPool.
*
* @see HeapFile
* @see BufferPool
*/
public class HeapPage implements Page {
HeapPageId pid;
TupleDesc td;
byte header[];
Tuple tuples[];
int numSlots;
boolean dirty;
TransactionId tid;
byte[] oldData;
/**
* Create a HeapPage from a set of bytes of data read from disk.
* The format of a HeapPage is a set of header bytes indicating
* the slots of the page that are in use, some number of tuple slots.
* Specifically, the number of tuples is equal to: <p>
* floor((BufferPool.PAGE_SIZE*8) / (tuple size * 8 + 1))
* <p> where tuple size is the size of tuples in this
* database table, which can be determined via {@link Catalog#getTupleDesc}.
* The number of 8-bit header words is equal to:
* <p>
* ceiling(no. tuple slots / 8)
* <p>
* @see Database#getCatalog
* @see Catalog#getTupleDesc
* @see BufferPool#PAGE_SIZE
*/
public HeapPage(HeapPageId id, byte[] data) throws IOException {
this.dirty = false;
this.tid = null;
this.pid = id;
this.td = Database.getCatalog().getTupleDesc(id.getTableId());
this.numSlots = getNumTuples();
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
// allocate and read the header slots of this page
header = new byte[getHeaderSize()];
for (int i = 0; i < header.length; i++)
header[i] = dis.readByte();
try {
// allocate and read the actual records of this page
tuples = new Tuple[numSlots];
for (int i = 0; i < tuples.length; i++)
tuples[i] = readNextTuple(dis,i);
} catch (NoSuchElementException e) {
e.printStackTrace();
}
dis.close();
setBeforeImage();
}
/** Retrieve the number of tuples on this page.
@return the number of tuples on this page
*/
private int getNumTuples() {
// some code goes here
// (BufferPool.PAGE_SIZE*8) / (tuple size * 8 + 1)
int tupleSize = td.getSize();
return (BufferPool.PAGE_SIZE * 8) / (tupleSize * 8 + 1);
}
/**
* Computes the number of bytes in the header of a page in a HeapFile with each tuple occupying tupleSize bytes
* @return the number of bytes in the header of a page in a HeapFile with each tuple occupying tupleSize bytes
*/
private int getHeaderSize() {
// some code goes here
if (numSlots % 8 == 0)
return numSlots / 8;
else
return (numSlots / 8) + 1;
}
/** Return a view of this page before it was modified
-- used by recovery */
public HeapPage getBeforeImage(){
try {
return new HeapPage(pid,oldData);
} catch (IOException e) {
e.printStackTrace();
//should never happen -- we parsed it OK before!
System.exit(1);
}
return null;
}
public void setBeforeImage() {
oldData = getPageData().clone();
}
/**
* @return the PageId associated with this page.
*/
public HeapPageId getId() {
// some code goes here
return pid;
}
/**
* Suck up tuples from the source file.
*/
private Tuple readNextTuple(DataInputStream dis, int slotId) throws NoSuchElementException {
// if associated bit is not set, read forward to the next tuple, and
// return null.
if (!getSlot(slotId)) {
for (int i=0; i<td.getSize(); i++) {
try {
dis.readByte();
} catch (IOException e) {
throw new NoSuchElementException("error reading empty tuple");
}
}
return null;
}
// read fields in the tuple
Tuple t = new Tuple(td);
RecordId rid = new RecordId(pid, slotId);
t.setRecordId(rid);
try {
for (int j=0; j<td.numFields(); j++) {
Field f = td.getType(j).parse(dis);
t.setField(j, f);
}
} catch (java.text.ParseException e) {
e.printStackTrace();
throw new NoSuchElementException("parsing error!");
}
return t;
}
/**
* Generates a byte array representing the contents of this page.
* Used to serialize this page to disk.
* <p>
* The invariant here is that it should be possible to pass the byte
* array generated by getPageData to the HeapPage constructor and
* have it produce an identical HeapPage object.
*
* @see #HeapPage
* @return A byte array correspond to the bytes of this page.
*/
public byte[] getPageData() {
int len = BufferPool.PAGE_SIZE;
ByteArrayOutputStream baos = new ByteArrayOutputStream(len);
DataOutputStream dos = new DataOutputStream(baos);
// create the header of the page
for (int i=0; i<header.length; i++) {
try {
dos.writeByte(header[i]);
} catch (IOException e) {
// this really shouldn't happen
e.printStackTrace();
}
}
// create the tuples
for (int i=0; i<tuples.length; i++) {
// empty slot
if (!getSlot(i)) {
for (int j=0; j<td.getSize(); j++) {
try {
dos.writeByte(0);
} catch (IOException e) {
e.printStackTrace();
}
}
continue;
}
// non-empty slot
for (int j=0; j<td.numFields(); j++) {
Field f = tuples[i].getField(j);
try {
f.serialize(dos);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// padding
int zerolen = BufferPool.PAGE_SIZE - (header.length + td.getSize() * tuples.length); //- numSlots * td.getSize();
byte[] zeroes = new byte[zerolen];
try {
dos.write(zeroes, 0, zerolen);
} catch (IOException e) {
e.printStackTrace();
}
try {
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
return baos.toByteArray();
}
/**
* Static method to generate a byte array corresponding to an empty
* HeapPage.
* Used to add new, empty pages to the file. Passing the results of
* this method to the HeapPage constructor will create a HeapPage with
* no valid tuples in it.
*
* @param tableid The id of the table that this empty page will belong to.
* @return The returned ByteArray.
*/
public static byte[] createEmptyPageData() {
int len = BufferPool.PAGE_SIZE;
return new byte[len]; //all 0
}
/**
* Delete the specified tuple from the page; the tuple should be updated to reflect
* that it is no longer stored on any page.
* @throws DbException if this tuple is not on this page, or tuple slot is
* already empty.
* @param t The tuple to delete
*/
public void deleteTuple(Tuple t) throws DbException {
// some code goes here
// not necessary for lab1
RecordId id = t.getRecordId();
PageId pageid = id.getPageId();
if (!pid.equals(pageid)) {
throw new DbException("Page: " + pid + " != " + pageid);
}
int tupleno = id.tupleno();
if (!getSlot(tupleno)) {
throw new DbException("The slot for Tuple " + tupleno + " is already empty");
}
// Mark corresponding head bit empty
setSlot(tupleno, false);
}
/**
* Adds the specified tuple to the page; the tuple should be updated to reflect
* that it is now stored on this page.
* @throws DbException if the page is full (no empty slots) or tupledesc
* is mismatch.
* @param t The tuple to add.
*/
public void addTuple(Tuple t) throws DbException {
// some code goes here
// not necessary for lab1
if (!t.getTupleDesc().equals(td)) {
throw new DbException("TupleDesc mismatch");
}
if (getNumEmptySlots() == 0) {
throw new DbException("Page is full");
}
int tupleno = getFirstEmptySlot();
tuples[tupleno] = t;
setSlot(tupleno, true);
RecordId rid = new RecordId(pid, tupleno);
t.setRecordId(rid);
}
private int getFirstEmptySlot() {
int i = 0;
for (; i < numSlots; i++) {
if (!getSlot(i)) {
return i;
}
}
return -1;
}
/**
* Marks this page as dirty/not dirty and record that transaction
* that did the dirtying
*/
public void markDirty(boolean dirty, TransactionId tid) {
// some code goes here
// not necessary for lab1
this.dirty = dirty;
this.tid = tid;
}
/**
* Returns the tid of the transaction that last dirtied this page, or null if the page is not dirty
*/
public TransactionId isDirty() {
// some code goes here
// Not necessary for lab1
if (this.dirty)
return this.tid;
else
return null;
}
/**
* Returns the number of empty slots on this page.
*/
public int getNumEmptySlots() {
// some code goes here
int emptySlots = 0;
for (int i = 0; i < header.length; i++) {
for (int j = 0; j < 8; j++) {
if ((header[i] >> j & 1) == 0) {
// Big-endian JVM
emptySlots++;
}
}
}
return emptySlots;
}
/**
* Returns true if associated slot on this page is filled.
*/
public boolean getSlot(int i) {
// some code goes here
byte b = header[i / 8];
if ((b >> (i % 8) & 1) == 0) {
return false;
}
return true;
}
/**
* Abstraction to fill or clear a slot on this page.
*/
private void setSlot(int i, boolean value) {
// some code goes here
// not necessary for lab1
byte orig = header[i / 8];
byte mask = (byte) (1 << (i % 8));
if (!value) {
header[i / 8] = (byte) (orig & ~mask);
} else {
header[i / 8] = (byte) (orig | mask);
}
}
/**
* @return an iterator over all tuples on this page (calling remove on this iterator throws an UnsupportedOperationException)
* (note that this iterator shouldn't return tuples in empty slots!)
*/
public Iterator<Tuple> iterator() {
// some code goes here
return new TupleIterator();
}
/*
* Private class TupleIterator used to iterate over the non-empty tuples
*/
private class TupleIterator implements Iterator<Tuple> {
private List<Tuple> tups;
private int index;
TupleIterator() {
index = 0;
tups = new ArrayList<Tuple>();
for (int i = 0; i < numSlots; i++) {
if (getSlot(i)) {
tups.add(tuples[i]);
}
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasNext() {
if (index < tups.size())
return true;
return false;
}
@Override
public Tuple next() {
// TODO Auto-generated method stub
if (!hasNext())
throw new NoSuchElementException();
Tuple tup = tups.get(index);
index++;
return tup;
}
}
}
| {
"content_hash": "4c4297d7966784ea588b4251c0f68ea0",
"timestamp": "",
"source": "github",
"line_count": 412,
"max_line_length": 129,
"avg_line_length": 29.859223300970875,
"alnum_prop": 0.5252804422045196,
"repo_name": "tavaresdong/courses",
"id": "479f5b9b2c53cf08fa6221aebfd90fe8143927ae",
"size": "12302",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "mit6.830/simpledb/src/simpledb/HeapPage.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "7670"
},
{
"name": "Awk",
"bytes": "968"
},
{
"name": "C",
"bytes": "4233508"
},
{
"name": "C++",
"bytes": "1577020"
},
{
"name": "CSS",
"bytes": "33922"
},
{
"name": "Emacs Lisp",
"bytes": "6604"
},
{
"name": "Gnuplot",
"bytes": "287"
},
{
"name": "Go",
"bytes": "342067"
},
{
"name": "HTML",
"bytes": "1293638"
},
{
"name": "Java",
"bytes": "526725"
},
{
"name": "JavaScript",
"bytes": "175741"
},
{
"name": "Makefile",
"bytes": "152445"
},
{
"name": "Objective-C",
"bytes": "17798"
},
{
"name": "Perl",
"bytes": "160647"
},
{
"name": "Python",
"bytes": "874441"
},
{
"name": "Roff",
"bytes": "327243"
},
{
"name": "Scala",
"bytes": "39825"
},
{
"name": "Scheme",
"bytes": "21980"
},
{
"name": "Shell",
"bytes": "374107"
},
{
"name": "TeX",
"bytes": "293853"
},
{
"name": "Yacc",
"bytes": "173967"
}
],
"symlink_target": ""
} |
<!doctype html>
<!-- This file is generated by build.py. -->
<title>video tall.jpg; overflow:hidden; -o-object-fit:contain; -o-object-position:30px bottom</title>
<link rel="stylesheet" href="../../support/reftests.css">
<link rel='match' href='hidden_contain_30px_bottom-ref.html'>
<style>
#test > * { overflow:hidden; -o-object-fit:contain; -o-object-position:30px bottom }
</style>
<div id="test">
<video poster="../../support/tall.jpg"></video>
</div>
| {
"content_hash": "808f658da6eff603c47f393afac61a2b",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 101,
"avg_line_length": 41.63636363636363,
"alnum_prop": 0.6855895196506551,
"repo_name": "Ms2ger/presto-testo",
"id": "8049bf4ad6f21303cb4f8e689871ca2a039027a0",
"size": "458",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "css/image-fit/reftests/video-poster-jpg-tall/hidden_contain_30px_bottom.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "2312"
},
{
"name": "ActionScript",
"bytes": "23470"
},
{
"name": "AutoHotkey",
"bytes": "8832"
},
{
"name": "Batchfile",
"bytes": "5001"
},
{
"name": "C",
"bytes": "116512"
},
{
"name": "C++",
"bytes": "219233"
},
{
"name": "CSS",
"bytes": "207914"
},
{
"name": "Erlang",
"bytes": "18523"
},
{
"name": "Groff",
"bytes": "674"
},
{
"name": "HTML",
"bytes": "103272540"
},
{
"name": "Haxe",
"bytes": "3874"
},
{
"name": "Java",
"bytes": "125658"
},
{
"name": "JavaScript",
"bytes": "22516936"
},
{
"name": "Makefile",
"bytes": "13409"
},
{
"name": "PHP",
"bytes": "524911"
},
{
"name": "Perl",
"bytes": "321672"
},
{
"name": "Python",
"bytes": "948191"
},
{
"name": "Ruby",
"bytes": "1006850"
},
{
"name": "Shell",
"bytes": "12140"
},
{
"name": "Smarty",
"bytes": "1860"
},
{
"name": "XSLT",
"bytes": "2567445"
}
],
"symlink_target": ""
} |
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/back_button_normal" android:state_pressed="false"></item>
<item android:drawable="@drawable/back_button_press" android:state_pressed="true"></item>
<item android:drawable="@drawable/back_button_disable" android:state_enabled="false" ></item>
</selector> | {
"content_hash": "67cf40393e124aa9ad02903f621a984d",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 99,
"avg_line_length": 54.142857142857146,
"alnum_prop": 0.7229551451187335,
"repo_name": "przemek29/GeoDron",
"id": "6ca10842a81b77c83bf90339b84de2f35be140a0",
"size": "379",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "GEODemo/app/src/main/res/drawable/selector_back_button.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "50545"
}
],
"symlink_target": ""
} |
.. _index:
.. esft::stor documentation master file, created by
sphinx-quickstart on Wed Oct 25 16:37:54 2017.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
*****
STOR
*****
.. toctree::
:maxdepth: 2
Introduction <self>
installation/cpp
installation/c
installation/py
tutorial/cpp
tutorial/c
tutorial/py
api/cpp/modules
api/c/modules
api/py/modules
Introduction
============
STOR is a multiplatform server-less*, embeddable** NoSQL Document Store written in C++11.
(*), (**)
Similar to `SQLite <https://www.sqlite.org/>`_, STOR does not operate in a client-server scenario.
Rather, you include it/link to it in your project and it works within a single process.
The major features are the following:
- Create/Modify/Delete **JSON Documents**
- Create Databases that persist the spanning process, or get deleted on destruction.
- Manage **Collections** of Documents
- **Index** Documents by their fields
- Query Documents by their IDs
- **Query** Documents by indexed fields, with **MongoDB-like** query syntax.
- **Back-up/Restore** Databases.
- Optionally **encrypt** a Database, by compiling with OpenSSL support and providing a key.
- **C Bindings**
- **Python Bindings** + **REPL**
License
--------
Both STOR and the bindings are released with the `BSD-2-Clause License <https://github.com/ethronsoft/stor/blob/master/LICENSE>`_.
Dependencies and platforms
--------------------------
Platforms targeted are:
- Windows
- OSX
- Linux
- Android & iOS (in progress; it just needs CMake toolchain adjustments)
Compilers we tested:
- MinGW G++ (by `TDM <http://tdm-gcc.tdragon.net/>`_, 64bit) version 5.1.0 on Windows 10
- G++ v. 6.2.0 on Ubuntu 16.10
- Clang v. 600.0.65 (LLVM 6.0) on Mac OSX El Capitan
Dependencies:
- `CMake <https://cmake.org/>`_, as the build tool.
- `LevelDB <https://github.com/google/leveldb>`_, as the underlying key/value storage engine
- `Boost.UUID <http://www.boost.org/doc/libs/1_64_0/libs/uuid/>`_, to produce unique Documents' ids
- `RapidJSON <http://rapidjson.org/>`_, as default JSON parser
- `Catch <https://github.com/philsquared/Catch>`_, for testing.
- (Optional) `OpenSSL <https://www.openssl.org/>`_, for database encryption
.. note::
All dependencies are provided in the git repository,
for simplicity of usage and testing. You are free to
provide your own if desired. Some guidance on this will
be provided in the Installation sections of the various
products.
A warm **THANK YOU** to the developers of the dependencies. Licenses provided in the respective
stor/core/dependencies folders.
Installation
------------
- :ref:`cpp-inst`
- :ref:`c-bindings-inst`
- :ref:`py-inst`
API Docs
--------
- `STOR API <_static/api/cpp/html/index.html>`_
- `C Bindings API <_static/api/c/html/index.html>`_
- :ref:`py-api`
Tutorials
---------
- :ref:`cpp-tut`
- :ref:`c-bindings-tut`
- :ref:`py-tut`
| {
"content_hash": "241f568cc0f2a2cce9f13d0c4e088fab",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 131,
"avg_line_length": 27.149122807017545,
"alnum_prop": 0.6665589660743134,
"repo_name": "ethronsoft/stor",
"id": "ad3eb9d255f1dfcff119ad5a7e93af02664ec633",
"size": "3095",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/wikis/index.rst",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "1013064"
},
{
"name": "Batchfile",
"bytes": "150910"
},
{
"name": "C",
"bytes": "55357275"
},
{
"name": "C++",
"bytes": "11536237"
},
{
"name": "CMake",
"bytes": "9497"
},
{
"name": "CSS",
"bytes": "3381"
},
{
"name": "DIGITAL Command Language",
"bytes": "966051"
},
{
"name": "Emacs Lisp",
"bytes": "15891"
},
{
"name": "HTML",
"bytes": "151865"
},
{
"name": "M4",
"bytes": "147090"
},
{
"name": "Makefile",
"bytes": "2375662"
},
{
"name": "Objective-C",
"bytes": "243615"
},
{
"name": "Perl",
"bytes": "1742620"
},
{
"name": "Perl 6",
"bytes": "7487077"
},
{
"name": "Prolog",
"bytes": "900100"
},
{
"name": "Python",
"bytes": "65866"
},
{
"name": "Roff",
"bytes": "15"
},
{
"name": "Scheme",
"bytes": "12747"
},
{
"name": "Shell",
"bytes": "491983"
},
{
"name": "XS",
"bytes": "12957"
},
{
"name": "eC",
"bytes": "15474"
}
],
"symlink_target": ""
} |
<?php
namespace PDepend\Source\AST;
use PDepend\Source\ASTVisitor\ASTVisitor;
/**
* This ast class represents a list for formal parameters. This means the
* parameters of a method, function or closure declaration.
*
* <code>
* // --
* function foo() {}
* // --
*
* // --------
* $x = function($x, $y) {}
* // --------
*
* class Foo {
* // -----------------
* public function bar(Foo $obj = null) {}
* // -----------------
* }
* </code>
*
* @copyright 2008-2013 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @since 0.9.6
*/
class ASTFormalParameters extends ASTNode
{
/**
* Accept method of the visitor design pattern. This method will be called
* by a visitor during tree traversal.
*
* @param \PDepend\Source\ASTVisitor\ASTVisitor $visitor The calling visitor instance.
* @param mixed $data
* @return mixed
* @since 0.9.12
*/
public function accept(ASTVisitor $visitor, $data = null)
{
return $visitor->visitFormalParameters($this, $data);
}
}
| {
"content_hash": "9377056c7db45a2695c1ed5b5368d732",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 91,
"avg_line_length": 26.085106382978722,
"alnum_prop": 0.5415986949429038,
"repo_name": "tarikgwa/test",
"id": "dec2bac81b0e97c2fbfbc3466d31c74c0be606c3",
"size": "3068",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "html/vendor/pdepend/pdepend/src/main/php/PDepend/Source/AST/ASTFormalParameters.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "26588"
},
{
"name": "CSS",
"bytes": "4874492"
},
{
"name": "HTML",
"bytes": "8635167"
},
{
"name": "JavaScript",
"bytes": "6810903"
},
{
"name": "PHP",
"bytes": "55645559"
},
{
"name": "Perl",
"bytes": "7938"
},
{
"name": "Shell",
"bytes": "4505"
},
{
"name": "XSLT",
"bytes": "19889"
}
],
"symlink_target": ""
} |
package com.datatorrent.tutorial.fixedwidthparser;
import java.util.Date;
public class Ad
{
private int adId;
private int campaignId;
private String adName;
private double bidPrice;
private Date startDate;
private Date endDate;
private long securityCode;
private boolean active;
private boolean optimized;
private String parentCampaign;
private Character weatherTargeted;
private String valid;
public Ad()
{
}
public int getAdId()
{
return adId;
}
public void setAdId(int adId)
{
this.adId = adId;
}
public int getCampaignId()
{
return campaignId;
}
public void setCampaignId(int campaignId)
{
this.campaignId = campaignId;
}
public String getAdName()
{
return adName;
}
public void setAdName(String adName)
{
this.adName = adName;
}
public double getBidPrice()
{
return bidPrice;
}
public void setBidPrice(double bidPrice)
{
this.bidPrice = bidPrice;
}
public long getSecurityCode()
{
return securityCode;
}
public void setSecurityCode(long securityCode)
{
this.securityCode = securityCode;
}
public boolean isActive()
{
return active;
}
public void setActive(boolean active)
{
this.active = active;
}
public boolean isOptimized()
{
return optimized;
}
public void setOptimized(boolean optimized)
{
this.optimized = optimized;
}
public String getParentCampaign()
{
return parentCampaign;
}
public void setParentCampaign(String parentCampaign)
{
this.parentCampaign = parentCampaign;
}
public Character getWeatherTargeted()
{
return weatherTargeted;
}
public void setWeatherTargeted(Character weatherTargeted)
{
this.weatherTargeted = weatherTargeted;
}
public String getValid()
{
return valid;
}
public void setValid(String valid)
{
this.valid = valid;
}
public Date getEndDate()
{
return endDate;
}
public void setEndDate(Date endDate)
{
this.endDate = endDate;
}
public Date getStartDate()
{
return startDate;
}
public void setStartDate(Date startDate)
{
this.startDate = startDate;
}
@Override
public String toString()
{
return "Ad [adId=" + adId + ", campaignId=" + campaignId + ", adName=" + adName + ", bidPrice=" + bidPrice
+ ", startDate=" + startDate + ", endDate=" + endDate + ", securityCode=" + securityCode + ", active="
+ active + ", optimized=" + optimized + ", parentCampaign=" + parentCampaign + ", weatherTargeted="
+ weatherTargeted + ", valid=" + valid + "]";
}
}
| {
"content_hash": "ad78fb0d701caec687b4dfd46f343f97",
"timestamp": "",
"source": "github",
"line_count": 153,
"max_line_length": 110,
"avg_line_length": 17.084967320261438,
"alnum_prop": 0.6602907421576129,
"repo_name": "DataTorrent/examples",
"id": "05ae34b3a392fd94e496f442d5e07498422647da",
"size": "2614",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tutorials/parser/src/main/java/com/datatorrent/tutorial/fixedwidthparser/Ad.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2070"
},
{
"name": "CSS",
"bytes": "87"
},
{
"name": "HTML",
"bytes": "268"
},
{
"name": "Java",
"bytes": "763787"
},
{
"name": "Shell",
"bytes": "5921"
},
{
"name": "XSLT",
"bytes": "44671"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Miscellaneous C functionality — MNE 0.16.1 documentation</title>
<link rel="stylesheet" href="../../_static/bootstrap-sphinx.css" type="text/css" />
<link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="../../_static/gallery.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
<script type="text/javascript" src="../../_static/jquery.js"></script>
<script type="text/javascript" src="../../_static/underscore.js"></script>
<script type="text/javascript" src="../../_static/doctools.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/javascript" src="../../_static/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="../../_static/js/jquery-fix.js"></script>
<script type="text/javascript" src="../../_static/bootstrap-3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../../_static/bootstrap-sphinx.js"></script>
<link rel="shortcut icon" href="../../_static/favicon.ico"/>
<link rel="index" title="Index" href="../../genindex.html" />
<link rel="search" title="Search" href="../../search.html" />
<script type="text/javascript" src="../../_static/copybutton.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-37225609-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<link rel="stylesheet" href="../../_static/style.css " type="text/css" />
<link rel="stylesheet" href="../../_static/font-awesome.css" type="text/css" />
<link rel="stylesheet" href="../../_static/flag-icon.css" type="text/css" />
<script type="text/javascript">
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);
js.id=id;js.src="https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
</script>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
<link rel="canonical" href="https://mne.tools/stable/index.html" />
</head><body>
<div id="navbar" class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<!-- .btn-navbar is used as the toggle for collapsed navbar content -->
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../../index.html"><span><img src="../../_static/mne_logo_small.png"></span>
</a>
<span class="navbar-text navbar-version pull-left"><b>0.16.1</b></span>
</div>
<div class="collapse navbar-collapse nav-collapse">
<ul class="nav navbar-nav">
<li><a href="../../getting_started.html">Install</a></li>
<li><a href="../../documentation.html">Documentation</a></li>
<li><a href="../../python_reference.html">API</a></li>
<li><a href="../../auto_examples/index.html">Examples</a></li>
<li><a href="../../contributing.html">Contribute</a></li>
<li class="dropdown globaltoc-container">
<a role="button"
id="dLabelGlobalToc"
data-toggle="dropdown"
data-target="#"
href="../../index.html">Site <b class="caret"></b></a>
<ul class="dropdown-menu globaltoc"
role="menu"
aria-labelledby="dLabelGlobalToc"></ul>
</li>
<li class="hidden-sm"></li>
</ul>
<div class="navbar-form navbar-right navbar-btn dropdown btn-group-sm" style="margin-left: 20px; margin-top: 5px; margin-bottom: 5px">
<button type="button" class="btn btn-primary navbar-btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">
v0.16.1
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="https://mne-tools.github.io/dev/index.html">Development</a></li>
<li><a href="https://mne-tools.github.io/stable/index.html">v0.16 (stable)</a></li>
<li><a href="https://mne-tools.github.io/0.15/index.html">v0.15</a></li>
<li><a href="https://mne-tools.github.io/0.14/index.html">v0.14</a></li>
<li><a href="https://mne-tools.github.io/0.13/index.html">v0.13</a></li>
<li><a href="https://mne-tools.github.io/0.12/index.html">v0.12</a></li>
<li><a href="https://mne-tools.github.io/0.11/index.html">v0.11</a></li>
</ul>
</div>
<form class="navbar-form navbar-right" action="../../search.html" method="get">
<div class="form-group">
<input type="text" name="q" class="form-control" placeholder="Search" />
</div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<p class="logo"><a href="../../index.html">
<img class="logo" src="../../_static/mne_logo_small.png" alt="Logo"/>
</a></p><ul>
<li><a class="reference internal" href="#">Miscellaneous C functionality</a><ul>
<li><a class="reference internal" href="#setting-up-anatomical-mr-images-for-mrilab">Setting up anatomical MR images for MRIlab</a></li>
<li><a class="reference internal" href="#cleaning-the-digital-trigger-channel">Cleaning the digital trigger channel</a></li>
<li><a class="reference internal" href="#fixing-channel-information">Fixing channel information</a></li>
</ul>
</li>
</ul>
<form action="../../search.html" method="get">
<div class="form-group">
<input type="text" name="q" class="form-control" placeholder="Search" />
</div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="col-md-12 content">
<div class="section" id="miscellaneous-c-functionality">
<h1>Miscellaneous C functionality<a class="headerlink" href="#miscellaneous-c-functionality" title="Permalink to this headline">¶</a></h1>
<div class="section" id="setting-up-anatomical-mr-images-for-mrilab">
<span id="babccehf"></span><h2>Setting up anatomical MR images for MRIlab<a class="headerlink" href="#setting-up-anatomical-mr-images-for-mrilab" title="Permalink to this headline">¶</a></h2>
<p>If you have the Neuromag software installed, the Neuromag
MRI viewer, MRIlab, can be used to access the MRI slice data created
by FreeSurfer . In addition, the
Neuromag MRI directories can be used for storing the MEG/MRI coordinate
transformations created with mne_analyze ,
see <a class="reference internal" href="../gui/analyze.html#cacehgcd"><span class="std std-ref">Coordinate frame alignment</span></a>. During the computation of the forward
solution, mne_do_forwand_solution searches
for the MEG/MRI coordinate in the Neuromag MRI directories, see <a class="reference internal" href="../cookbook.html#babchejd"><span class="std std-ref">Computing the forward solution</span></a>. The fif files created by mne_setup_mri can
be loaded into Matlab with the fiff_read_mri function,
see <a class="reference internal" href="../matlab.html#ch-matlab"><span class="std std-ref">MNE-MATLAB toolbox</span></a>.</p>
<p>These functions require running the script mne_setup_mri which
requires that the subject is set with the <code class="docutils literal notranslate"><span class="pre">--subject</span></code> option
or by the SUBJECT environment variable. The script processes one
or more MRI data sets from <code class="docutils literal notranslate"><span class="pre">$SUBJECTS_DIR/$SUBJECT/mri</span></code> ,
by default they are T1 and brain. This default can be changed by
specifying the sets by one or more <code class="docutils literal notranslate"><span class="pre">--mri</span></code> options.</p>
<p>The script creates the directories <code class="docutils literal notranslate"><span class="pre">mri/</span></code> <<em>name</em>> <code class="docutils literal notranslate"><span class="pre">-neuromag/slices</span></code> and <code class="docutils literal notranslate"><span class="pre">mri/</span></code> <<em>name</em>> <code class="docutils literal notranslate"><span class="pre">-neuromag/sets</span></code> .
If the input data set is in COR format, mne_setup_mri makes
symbolic links from the COR files in the directory <code class="docutils literal notranslate"><span class="pre">mri/</span></code> <<em>name</em>> into <code class="docutils literal notranslate"><span class="pre">mri/</span></code> <<em>name</em>> <code class="docutils literal notranslate"><span class="pre">-neuromag/slices</span></code> ,
and creates a corresponding fif file COR.fif in <code class="docutils literal notranslate"><span class="pre">mri/</span></code> <<em>name</em>> <code class="docutils literal notranslate"><span class="pre">-neuromag/sets</span></code> ..
This “description file” contains references to
the actual MRI slices.</p>
<p>If the input MRI data are stored in the newer mgz format,
the file created in the <code class="docutils literal notranslate"><span class="pre">mri/</span></code> <<em>name</em>> <code class="docutils literal notranslate"><span class="pre">-neuromag/sets</span></code> directory
will include the MRI pixel data as well. If available, the coordinate
transformations to allow conversion between the MRI (surface RAS)
coordinates and MNI and FreeSurfer Talairach coordinates are copied
to the MRI description file. mne_setup_mri invokes mne_make_cor_set ,
described in <a class="reference internal" href="../c_reference.html#mne-make-cor-set"><span class="std std-ref">mne_make_cor_set</span></a> to convert the data.</p>
<p>For example:</p>
<p><code class="docutils literal notranslate"><span class="pre">mne_setup_mri</span> <span class="pre">--subject</span> <span class="pre">duck_donald</span> <span class="pre">--mri</span> <span class="pre">T1</span></code></p>
<p>This command processes the MRI data set T1 for subject duck_donald.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If the SUBJECT environment variable is set it is usually sufficient to run mne_setup_mri without any options.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If the name specified with the <code class="docutils literal notranslate"><span class="pre">--mri</span></code> option contains a slash, the MRI data are accessed from the directory specified and the <code class="docutils literal notranslate"><span class="pre">SUBJECT</span></code> and <code class="docutils literal notranslate"><span class="pre">SUBJECTS_DIR</span></code> environment variables as well as the <code class="docutils literal notranslate"><span class="pre">--subject</span></code> option are ignored.</p>
</div>
<p>MRIlab can also be used for coordinate frame alignment.
Section 3.3.1 of the MRIlab User’s Guide,
Neuromag P/N NM20419A-A contains a detailed description of
this task. Employ the images in the set <code class="docutils literal notranslate"><span class="pre">mri/T1-neuromag/sets/COR.fif</span></code> for
the alignment. Check the alignment carefully using the digitization
data included in the measurement file as described in Section 5.3.1
of the above manual. Save the aligned description file in the same
directory as the original description file without the alignment
information but under a different name.</p>
</div>
<div class="section" id="cleaning-the-digital-trigger-channel">
<span id="babcdbdi"></span><h2>Cleaning the digital trigger channel<a class="headerlink" href="#cleaning-the-digital-trigger-channel" title="Permalink to this headline">¶</a></h2>
<p>The calibration factor of the digital trigger channel used
to be set to a value much smaller than one by the Neuromag data
acquisition software. Especially to facilitate viewing of raw data
in graph it is advisable to change the calibration factor to one.
Furthermore, the eighth bit of the trigger word is coded incorrectly
in the original raw files. Both problems can be corrected by saying:</p>
<p><code class="docutils literal notranslate"><span class="pre">mne_fix_stim14</span></code> <<em>raw file</em>></p>
<p>More information about mne_fix_stim14 is
available in <a class="reference internal" href="../c_reference.html#mne-fix-stim14"><span class="std std-ref">mne_fix_stim14</span></a>. It is recommended that this
fix is included as the first raw data processing step. Note, however,
the mne_browse_raw and mne_process_raw always sets
the calibration factor to one internally.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If your data file was acquired on or after November 10, 2005 on the Martinos center Vectorview system, it is not necessary to use mne_fix_stim14 .</p>
</div>
</div>
<div class="section" id="fixing-channel-information">
<span id="babcdfjh"></span><h2>Fixing channel information<a class="headerlink" href="#fixing-channel-information" title="Permalink to this headline">¶</a></h2>
<p>There are two potential discrepancies in the channel information
which need to be fixed before proceeding:</p>
<ul class="simple">
<li>EEG electrode locations may be incorrect
if more than 60 EEG channels are acquired.</li>
<li>The magnetometer coil identifiers are not always correct.</li>
</ul>
<p>These potential problems can be fixed with the utilities mne_check_eeg_locations and mne_fix_mag_coil_types,
see <a class="reference internal" href="../c_reference.html#mne-check-eeg-locations"><span class="std std-ref">mne_check_eeg_locations</span></a> and <a class="reference internal" href="../c_reference.html#mne-fix-mag-coil-types"><span class="std std-ref">mne_fix_mag_coil_types</span></a>.</p>
</div>
</div>
</div>
</div>
</div>
<footer class="footer">
<div class="container"><img src="../../_static/institutions.png" alt="Institutions"></div>
<div class="container">
<ul class="list-inline">
<li><a href="https://github.com/mne-tools/mne-python">GitHub</a></li>
<li>·</li>
<li><a href="https://mail.nmr.mgh.harvard.edu/mailman/listinfo/mne_analysis">Mailing list</a></li>
<li>·</li>
<li><a href="https://gitter.im/mne-tools/mne-python">Gitter</a></li>
<li>·</li>
<li><a href="whats_new.html">What's new</a></li>
<li>·</li>
<li><a href="faq.html#cite">Cite MNE</a></li>
<li class="pull-right"><a href="#">Back to top</a></li>
</ul>
<p>© Copyright 2012-2018, MNE Developers. Last updated on 2018-06-24.</p>
</div>
</footer>
<script src="https://mne.tools/versionwarning.js"></script>
</body>
</html> | {
"content_hash": "2d735ca335765422533454ce9f59f9f8",
"timestamp": "",
"source": "github",
"line_count": 284,
"max_line_length": 545,
"avg_line_length": 56.855633802816904,
"alnum_prop": 0.6770297888152598,
"repo_name": "mne-tools/mne-tools.github.io",
"id": "2d137b156dd46a040244e45110fe9448dac51c2e",
"size": "16161",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "0.16/manual/appendix/c_misc.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "708696"
},
{
"name": "Dockerfile",
"bytes": "1820"
},
{
"name": "HTML",
"bytes": "1526247783"
},
{
"name": "JavaScript",
"bytes": "1323087"
},
{
"name": "Jupyter Notebook",
"bytes": "24820047"
},
{
"name": "Python",
"bytes": "18575494"
}
],
"symlink_target": ""
} |
var L = require('leaflet');
var esri = require('esri-leaflet');
var geocoding = require('esri-leaflet-geocoder');
// since leaflet is bundled into the browserify package it won't be able to detect where the images
// solution is to point it to where you host the the leaflet images yourself
L.Icon.Default.imagePath = 'http://cdn.leafletjs.com/leaflet-0.7.3/images';
// create map
var map = L.map('map').setView([45.526, -122.667], 15);
// add basemap
esri.basemapLayer('Topographic').addTo(map);
// add layer
esri.featureLayer({
url: '//services.arcgis.com/uCXeTVveQzP4IIcx/arcgis/rest/services/gisday/FeatureServer/0/'
}).addTo(map);
// add search control
geocoding.geosearch({
providers: [
geocoding.arcgisOnlineProvider(),
geocoding.featureLayerProvider({
url: '//services.arcgis.com/uCXeTVveQzP4IIcx/arcgis/rest/services/gisday/FeatureServer/0/',
searchFields: ['Name', 'Organization'],
label: 'GIS Day Events',
bufferRadius: 20000,
formatSuggestion: function (feature) {
return feature.properties.Name + ' - ' + feature.properties.Organization;
}
})
]
}).addTo(map);
| {
"content_hash": "6ec936a0f1227f6dae580ad47d4d08b7",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 99,
"avg_line_length": 33.529411764705884,
"alnum_prop": 0.7026315789473684,
"repo_name": "Esri/esri-leaflet-browserify-example",
"id": "be9c63dab07397d9b7d04b84fcdee367d9a279b1",
"size": "1159",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "453"
},
{
"name": "JavaScript",
"bytes": "1159"
}
],
"symlink_target": ""
} |
#!/usr/bin/env python
"""
python %prog [options] <in_schema.xsd> <out_schema.xsd>
Synopsis:
Prepare schema document. Replace include and import elements.
Examples:
python %prog myschema.xsd
python %prog myschema.xsd newschema.xsd
python %prog -f myschema.xsd newschema.xsd
cat infile.xsd | python %prog > outfile.xsd
"""
#
# Imports
import sys
import os
import urllib.request, urllib.error, urllib.parse
import copy
from optparse import OptionParser, Values
import itertools
from copy import deepcopy
from lxml import etree
#
# Globals and constants
#
# Do not modify the following VERSION comments.
# Used by updateversion.py.
##VERSION##
VERSION = '2.12a'
##VERSION##
Namespaces = {'xs': 'http://www.w3.org/2001/XMLSchema'}
Xsd_namespace_uri = 'http://www.w3.org/2001/XMLSchema'
CatalogDict = {}
# the base url to use for all relative paths in the catalog
CatalogBaseUrl = None
def load_catalog(catalogpath):
global CatalogBaseUrl
if catalogpath:
CatalogBaseUrl = os.path.split(catalogpath)[0]
catalog = etree.parse(open(catalogpath))
for elements in catalog.getroot().findall(
"{urn:oasis:names:tc:entity:xmlns:xml:catalog}public"):
CatalogDict[elements.get("publicId")] = elements.get("uri")
#
# Functions for external use
def process_include_files(
infile, outfile, inpath='', catalogpath=None,
fixtypenames=None):
load_catalog(catalogpath)
options = Values({
'force': False,
'fixtypenames': fixtypenames,
})
prep_schema_doc(infile, outfile, inpath, options)
def get_all_root_file_paths(infile, inpath='', catalogpath=None):
load_catalog(catalogpath)
doc1 = etree.parse(infile)
root1 = doc1.getroot()
rootPaths = []
params = Params()
params.parent_url = infile
params.base_url = os.path.split(inpath)[0]
get_root_file_paths(root1, params, rootPaths)
rootPaths.append(inpath)
return rootPaths
#
# Classes
class Params(object):
members = ('base_url', 'already_processed', 'parent_url', )
def __init__(self):
self.base_url = None
self.already_processed = set()
self.parent_url = None
def __setattr__(self, name, value):
if name not in self.members:
raise AttributeError('Class %s has no set-able attribute "%s"' % (
self.__class__.__name__, name, ))
self.__dict__[name] = value
class SchemaIOError(IOError):
pass
class RaiseComplexTypesError(Exception):
pass
#
# Functions for internal use and testing
def clear_includes_and_imports(node):
namespace = node.nsmap[node.prefix]
child_iter1 = node.iterfind('{%s}include' % (namespace, ))
child_iter2 = node.iterfind('{%s}import' % (namespace, ))
for child in itertools.chain(child_iter1, child_iter2):
repl = etree.Comment(etree.tostring(child))
repl.tail = '\n'
node.replace(child, repl)
def get_ref_info(node, params):
# first look for the schema location in the catalog, if not
# there, then see if it's specified in the node
namespace = node.get('namespace')
url = None
baseUrl = None
if namespace in CatalogDict:
url = CatalogDict[namespace]
# setup the base url in case the path
# in the catalog was a relative path
baseUrl = CatalogBaseUrl
if not url:
url = node.get('schemaLocation')
if not url:
msg = '*** Warning: missing "schemaLocation" attribute in %s\n' % (
params.parent_url, )
sys.stderr.write(msg)
return (None, None)
# Uncomment the next lines to help track down missing schemaLocation etc.
# print '(resolve_ref) url: %s\n parent-url: %s' % (
# url, params.parent_url, )
if not baseUrl:
baseUrl = params.base_url
if baseUrl and not (
url.startswith('/') or
url.startswith('http:') or
url.startswith('ftp:')):
locn = '%s/%s' % (baseUrl, url, )
schema_name = locn
else:
locn = url
schema_name = url
return locn, schema_name
def resolve_ref(node, params, options):
content = None
locn, schema_name = get_ref_info(node, params)
if locn is not None and not (
locn.startswith('/') or
locn.startswith('http:') or
locn.startswith('ftp:')):
schema_name = os.path.abspath(locn)
if locn is not None:
if schema_name not in params.already_processed:
params.already_processed.add(schema_name)
## print 'trace --'
## print ' url: : %s' % (url, )
## print ' base : %s' % (params.base_url, )
## print ' parent : %s' % (params.parent_url, )
## print ' locn : %s' % (locn, )
## print ' schema_name : %s\n' % (schema_name, )
if locn.startswith('http:') or locn.startswith('ftp:'):
try:
urlfile = urllib.request.urlopen(locn)
content = urlfile.read()
urlfile.close()
params.parent_url = locn
params.base_url = os.path.split(locn)[0]
except urllib.error.HTTPError:
msg = "Can't find file %s referenced in %s." % (
locn, params.parent_url, )
raise SchemaIOError(msg)
else:
if os.path.exists(locn):
infile = open(locn, 'rb')
content = infile.read()
infile.close()
params.parent_url = locn
params.base_url = os.path.split(locn)[0]
if content is None:
msg = "Can't find file %s referenced in %s." % (
locn, params.parent_url, )
raise SchemaIOError(msg)
## if content is None:
## msg = "Can't find file %s referenced in %s." % (
## locn, params.parent_url, )
## raise SchemaIOError(msg)
return content
def collect_inserts(node, params, inserts, options):
namespace = node.nsmap[node.prefix]
roots = []
child_iter1 = node.iterfind('{%s}include' % (namespace, ))
child_iter2 = node.iterfind('{%s}import' % (namespace, ))
for child in itertools.chain(child_iter1, child_iter2):
aux_roots = collect_inserts_aux(child, params, inserts, options)
roots.extend(aux_roots)
return roots
def collect_inserts_aux(child, params, inserts, options):
roots = []
save_base_url = params.base_url
string_content = resolve_ref(child, params, options)
if string_content is not None:
root = etree.fromstring(string_content, base_url=params.base_url)
roots.append(root)
for child1 in root:
if not isinstance(child1, etree._Comment):
namespace = child1.nsmap[child1.prefix]
if (child1.tag != '{%s}include' % (namespace, ) and
child1.tag != '{%s' % (namespace, )):
comment = etree.Comment(etree.tostring(child))
comment.tail = '\n'
inserts.append(comment)
inserts.append(child1)
insert_roots = collect_inserts(root, params, inserts, options)
roots.extend(insert_roots)
params.base_url = save_base_url
return roots
def get_root_file_paths(node, params, rootPaths):
namespace = node.nsmap[node.prefix]
child_iter1 = node.iterfind('{%s}include' % (namespace, ))
child_iter2 = node.iterfind('{%s}import' % (namespace, ))
for child in itertools.chain(child_iter1, child_iter2):
get_root_file_paths_aux(child, params, rootPaths)
def get_root_file_paths_aux(child, params, rootPaths):
save_base_url = params.base_url
path, _ = get_ref_info(child, params)
string_content = resolve_ref(child, params, None)
if string_content is not None:
root = etree.fromstring(string_content, base_url=params.base_url)
get_root_file_paths(root, params, rootPaths)
if path is not None and path not in rootPaths:
rootPaths.append(path)
params.base_url = save_base_url
def make_file(outFileName, options):
outFile = None
if (not options.force) and os.path.exists(outFileName):
reply = input('File %s exists. Overwrite? (y/n): ' % outFileName)
if reply == 'y':
outFile = open(outFileName, 'w')
else:
outFile = open(outFileName, 'w')
return outFile
def prep_schema_doc(infile, outfile, inpath, options):
doc1 = etree.parse(infile)
root1 = doc1.getroot()
params = Params()
params.parent_url = infile
params.base_url = os.path.split(inpath)[0]
inserts = []
collect_inserts(root1, params, inserts, options)
root2 = copy.copy(root1)
clear_includes_and_imports(root2)
for insert_node in inserts:
root2.append(insert_node)
process_groups(root2)
raise_anon_complextypes(root2)
fix_type_names(root2, options)
doc2 = etree.ElementTree(root2)
doc2.write(outfile)
return doc2
def prep_schema(inpath, outpath, options):
if inpath:
infile = open(inpath, 'r')
else:
infile = sys.stdin
if outpath:
outfile = make_file(outpath, options)
else:
outfile = sys.stdout
if outfile is None:
return
prep_schema_doc(infile, outfile, inpath, options)
if inpath:
infile.close()
if outpath:
outfile.close()
def process_groups(root):
# Get all the xs:group definitions at top level.
defs = root.xpath('./xs:group', namespaces=Namespaces)
defs = [node for node in defs if node.get('name') is not None]
# Get all the xs:group references (below top level).
refs = root.xpath('./*//xs:group', namespaces=Namespaces)
refs = [node for node in refs if node.get('ref') is not None]
# Create a dictionary of the named model groups (definitions).
def_dict = {}
for node in defs:
def_dict[trim_prefix(node.get('name'))] = node
replace_group_defs(def_dict, refs)
def fix_type_names(root, options):
fixnamespec = options.fixtypenames
if fixnamespec:
namespecs = fixnamespec.split(';')
else:
namespecs = []
for namespec in namespecs:
names = namespec.split(':')
if len(names) == 2:
oldname = names[0]
newname = names[1]
elif len(names) == 1:
oldname = names[0]
newname = '%sxx' % (oldname, )
else:
continue
# Change the name (name attribute) of the complexType.
pat = './/%s:complexType[@name="%s"]' % (
root.prefix, oldname)
elements = xpath_find(root, pat)
if len(elements) < 1:
sys.stderr.write(
"\nWarning: fix-type-names can't find complexType '%s'. "
"Exiting.\n\n" % (oldname, ))
sys.exit(1)
if len(elements) < 1:
sys.stderr.write(
"Warning: fix-type-names found more than "
"one complexType '%s'. "
"Changing first." % (oldname, ))
element = elements[0]
element.set('name', newname)
# Change the reference (type attribute) of child elements.
pat = './/%s:element' % (root.prefix, )
elements = xpath_find(root, pat)
for element in elements:
typename = element.get('type')
if not typename:
continue
names = typename.split(':')
if len(names) == 2:
typename = names[1]
elif len(names) == 1:
typename = names[0]
else:
continue
if typename != oldname:
continue
if not element.getchildren():
element.set('type', newname)
# Change the extensions ('base' attribute) that refer to the old type.
pat = './/%s:extension' % (root.prefix, )
elements = xpath_find(root, pat)
for element in elements:
typename = element.get('base')
if not typename:
continue
names = typename.split(':')
if len(names) == 2:
typename = names[1]
elif len(names) == 1:
typename = names[0]
else:
continue
if typename != oldname:
continue
element.set('base', newname)
def xpath_find(node, pat):
namespaces = {node.prefix: node.nsmap[node.prefix]}
elements = node.xpath(pat, namespaces=namespaces)
return elements
def replace_group_defs(def_dict, refs):
for ref_node in refs:
name = trim_prefix(ref_node.get('ref'))
if name is None:
continue
def_node = def_dict.get(name)
if def_node is not None:
content = def_node.xpath(
'./xs:sequence|./xs:choice|./xs:all',
namespaces=Namespaces)
if content:
content = content[0]
parent = ref_node.getparent()
for node in content:
new_node = deepcopy(node)
# Copy minOccurs and maxOccurs attributes to new node.
value = ref_node.get('minOccurs')
if value is not None:
new_node.set('minOccurs', value)
value = ref_node.get('maxOccurs')
if value is not None:
new_node.set('maxOccurs', value)
ref_node.addprevious(new_node)
parent.remove(ref_node)
def raise_anon_complextypes(root):
""" Raise each anonymous complexType to top level and give it a name.
Rename if necessary to prevent duplicates.
"""
def_names = collect_type_names(root)
def_count = 0
# Find all complexTypes below top level.
# Raise them to top level and name them.
# Re-name if there is a duplicate (simpleType, complexType, or
# previous renamed type).
# Change the parent (xs:element) so the "type" attribute refers to
# the raised and renamed type.
# Collect the new types.
el = etree.Comment(text="Raised anonymous complexType definitions")
el.tail = "\n\n"
root.append(el)
prefix = root.prefix
if prefix:
pattern = './*/*//%s:complexType|./*/*//%s:simpleType' % (
prefix, prefix, )
element_tag = '{%s}element' % (root.nsmap[prefix], )
else:
pattern = './*/*//complexType|./*/*//simpleType'
element_tag = 'element'
defs = root.xpath(pattern, namespaces=Namespaces)
for node in defs:
parent = node.getparent()
if parent.tag != element_tag:
continue
name = parent.get('name')
if not name:
continue
type_name = '%sType' % (name, )
type_name, def_count = unique_name(type_name, def_names, def_count)
def_names.add(type_name)
parent.set('type', type_name)
node.set('name', type_name)
# Move the complexType node to top level.
root.append(node)
#
# Collect the names of all currently defined types (complexType,
# simpleType, element).
def collect_type_names(node):
prefix = node.prefix
if prefix is not None and prefix.strip():
pattern = './/%s:complexType|.//%s:simpleType|.//%s:element' % (
prefix, prefix, prefix)
# Must make sure that we have a namespace dictionary that does *not*
# have a key None.
namespaces = {prefix: node.nsmap[prefix]}
elements = node.xpath(pattern, namespaces=namespaces)
else:
pattern = './/complexType|.//simpleType|.//element'
elements = node.xpath(pattern)
names = [
el.attrib['name'] for el in elements if
'name' in el.attrib and el.getchildren()
]
names = set(names)
return names
def unique_name(type_name, def_names, def_count):
orig_type_name = type_name
while True:
if type_name not in def_names:
return type_name, def_count
def_count += 1
type_name = '%s%d' % (orig_type_name, def_count, )
def trim_prefix(name):
names = name.split(':')
if len(names) == 1:
return names[0]
elif len(names) == 2:
return names[1]
else:
return None
USAGE_TEXT = __doc__
def usage(parser):
parser.print_help()
sys.exit(1)
def main():
parser = OptionParser(USAGE_TEXT)
parser.add_option(
"-f", "--force", action="store_true",
dest="force", default=False,
help="force overwrite without asking")
(options, args) = parser.parse_args()
if len(args) == 2:
inpath = args[0]
outpath = args[1]
elif len(args) == 1:
inpath = args[0]
outpath = None
elif len(args) == 0:
inpath = None
outpath = None
else:
usage(parser)
prep_schema(inpath, outpath, options)
if __name__ == "__main__":
#import pdb; pdb.set_trace()
main()
| {
"content_hash": "e2f2c05eb2d560966280ead93d9cde58",
"timestamp": "",
"source": "github",
"line_count": 542,
"max_line_length": 78,
"avg_line_length": 31.833948339483396,
"alnum_prop": 0.5740697809203663,
"repo_name": "ricksladkey/generateDS",
"id": "a0902de74cb6a000027b783410a6b4b3103253cd",
"size": "17254",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "process_includes.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "321"
},
{
"name": "C++",
"bytes": "665"
},
{
"name": "Python",
"bytes": "2717835"
},
{
"name": "Shell",
"bytes": "695"
}
],
"symlink_target": ""
} |
package org.culturegraph.mf.framework;
/**
* Default implementation for {@link Sender}s that simply stores a reference to
* the receiver and implements the correct behaviour required by the LifeCycle
* interface.
*
* @param <T>
* receiver base type of the downstream module
*
* @see DefaultStreamPipe
* @see DefaultObjectPipe
* @see DefaultXmlPipe
*
* @author Christoph Böhme
*
*/
public class DefaultSender<T extends Receiver> implements Sender<T> {
private T receiver;
private boolean isClosed;
public final boolean isClosed() {
return isClosed;
}
@Override
public final <R extends T> R setReceiver(final R receiver) {
this.receiver = receiver;
onSetReceiver();
return receiver;
}
@Override
public final void resetStream() {
onResetStream();
if (receiver != null) {
receiver.resetStream();
}
isClosed = false;
}
@Override
public final void closeStream() {
if (!isClosed) {
onCloseStream();
if (receiver != null) {
receiver.closeStream();
}
}
isClosed = true;
}
/**
* Invoked when the sender is connected with a receiver. This method is
* called after the receiver has been updated. Hence, {@code getReceiver}
* will return a reference to the new receiver.
*/
protected void onSetReceiver() {
// Default implementation does nothing
}
/**
* Invoked when the {@code resetStream()} method is called. Override this
* method to perform a reset of the module.
*
* Do not call the {@code resetStream()} method of the next module
* downstream. This is handled by the implementation of
* {@code resetStream()} in {@code DefaultSender}.
*
* {@code onResetStream()} is called before {@code DefaultSender} calls the
* {@code resetStream()} method of the downstream module.
*/
protected void onResetStream() {
// Default implementation does nothing
}
/**
* Invoked when the {@code closeStream()} method is called. Override this
* method to close any resources used by the module.
*
* Do not call the {@code closeStream()} method of the next module
* downstream. This is handled by the implementation of
* {@code closeStream()} in {@code DefaultSender}.
*
* {@code onCloseStream()} is called before {@code DefaultSender} calls the
* {@code closeStream()} method of the downstream module.
*/
protected void onCloseStream() {
// Default implementation does nothing
}
/**
* Returns a reference to the downstream module.
*
* @return reference to the downstream module
*/
protected final T getReceiver() {
return receiver;
}
}
| {
"content_hash": "32ea2586a32891c318d9f2fb82c7c7ef",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 79,
"avg_line_length": 24.980582524271846,
"alnum_prop": 0.6945200155460551,
"repo_name": "zazi/metafacture-core",
"id": "90411fef14f7e6efaab5eb3a864964b124db606f",
"size": "3188",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/org/culturegraph/mf/framework/DefaultSender.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GAP",
"bytes": "6980"
},
{
"name": "Java",
"bytes": "1327420"
},
{
"name": "JavaScript",
"bytes": "90"
},
{
"name": "Python",
"bytes": "1389"
}
],
"symlink_target": ""
} |
* Fixed issue with non-HTTPS Git repository was triggering an error on RHEL.
## v1.1.4
* Fixed hardcoded path to `node` within runit.
* Fix reference to runit service and delay notification.
## v1.1.3
* Add `reference` attribute to specify StatsD versions.
## v1.1.2
* Changed Git repository protocol to HTTPS.
## v1.1.1
* Added `percentThreshold` option to StatsD configuration.
## v1.1.0
* Added auto-discovery for Graphite.
* Added deleteIdleStats, deleteSets and deleteCounters.
## v1.0.0
* Switched to runit for uniform init support across Debian + RHEL.
* Fixed FC002.
* Added Test Kitchen support.
## v0.1.4
* Added `deleteGauges` and `deleteTimers` options to StatsD configuration.
## v0.1.3
* Fixed hardcoded StatsD path in Upstart script.
## v0.1.2
* Added the rest of the namespacing attributes. See: https://github.com/etsy/statsd/blob/master/docs/namespacing.md
## v0.1.1
* Added a legacyNamespace attribute for metric namespacing.
## v0.1.0
* Fixed hardcoded StatsD path in RHEL init script.
* Added test-kitchen support.
## v0.1.0
* Fixed issues with stopping statsd service via init.d.
## v0.0.10
* Removed trailing comma that was causing issues with Chef on Ruby 1.8.7.
## v0.0.9
* Fixed service resource restart support.
## v0.0.8
* Added support for RHEL.
## v0.0.7
* Fixed order of shell redirection to ensure that `STDERR` flows to log file.
## v0.0.6
* Added init script support for Ubuntu 10.04 and Upstart 0.6.5.
## v0.0.5
* Altered Upstart configuration file for version 1.4 and above.
## v0.0.4
* Added Foodcritic and Travis CI.
| {
"content_hash": "01d48539d3790f81fb0f221fc6349cc9",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 115,
"avg_line_length": 19.426829268292682,
"alnum_prop": 0.7219083490269931,
"repo_name": "rackspace-orchestration-templates/graphite",
"id": "3d8bfb4327c7af52b3b1d6a640c4e367d8853b0c",
"size": "1604",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "cookbooks/statsd/CHANGELOG.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "188022"
},
{
"name": "Perl",
"bytes": "1694"
},
{
"name": "Python",
"bytes": "1656379"
},
{
"name": "Ruby",
"bytes": "577220"
},
{
"name": "Shell",
"bytes": "20155"
}
],
"symlink_target": ""
} |
using System;
using System.IO;
using Aspose.Email.Imap;
using Aspose.Email.Mail;
namespace Aspose.Email.Examples.CSharp.Email.IMAP
{
class ReadMessagesRecursively
{
// ExStart:ReadMessagesRecursively
public static void Run()
{
// Create an instance of the ImapClient class
ImapClient client = new ImapClient();
// Specify host, username, password, Port and SecurityOptions for your client
client.Host = "imap.gmail.com";
client.Username = "your.username@gmail.com";
client.Password = "your.password";
client.Port = 993;
client.SecurityOptions = SecurityOptions.Auto;
try
{
// The root folder (which will be created on disk) consists of host and username
string rootFolder = client.Host + "-" + client.Username;
// Create the root folder and List all the folders from IMAP server
Directory.CreateDirectory(rootFolder);
ImapFolderInfoCollection folderInfoCollection = client.ListFolders();
foreach (ImapFolderInfo folderInfo in folderInfoCollection)
{
// Call the recursive method to read messages and get sub-folders
ListMessagesInFolder(folderInfo, rootFolder, client);
}
// Disconnect to the remote IMAP server
client.Dispose();
}
catch (Exception ex)
{
Console.Write(Environment.NewLine + ex);
}
Console.WriteLine(Environment.NewLine + "Downloaded messages recursively from IMAP server.");
}
/// Recursive method to get messages from folders and sub-folders
private static void ListMessagesInFolder(ImapFolderInfo folderInfo, string rootFolder, ImapClient client)
{
// Create the folder in disk (same name as on IMAP server)
string currentFolder = RunExamples.GetDataDir_IMAP();
Directory.CreateDirectory(currentFolder);
// Read the messages from the current folder, if it is selectable
if (folderInfo.Selectable)
{
// Send status command to get folder info
ImapFolderInfo folderInfoStatus = client.GetFolderInfo(folderInfo.Name);
Console.WriteLine(folderInfoStatus.Name + " folder selected. New messages: " + folderInfoStatus.NewMessageCount + ", Total messages: " + folderInfoStatus.TotalMessageCount);
// Select the current folder and List messages
client.SelectFolder(folderInfo.Name);
ImapMessageInfoCollection msgInfoColl = client.ListMessages();
Console.WriteLine("Listing messages....");
foreach (ImapMessageInfo msgInfo in msgInfoColl)
{
// Get subject and other properties of the message
Console.WriteLine("Subject: " + msgInfo.Subject);
Console.WriteLine("Read: " + msgInfo.IsRead + ", Recent: " + msgInfo.Recent + ", Answered: " + msgInfo.Answered);
// Get rid of characters like ? and :, which should not be included in a file name and Save the message in MSG format
string fileName = msgInfo.Subject.Replace(":", " ").Replace("?", " ");
MailMessage msg = client.FetchMessage(msgInfo.SequenceNumber);
msg.Save(currentFolder + "\\" + fileName + "-" + msgInfo.SequenceNumber + ".msg", SaveOptions.DefaultMsgUnicode);
}
Console.WriteLine("============================\n");
}
else
{
Console.WriteLine(folderInfo.Name + " is not selectable.");
}
try
{
// If this folder has sub-folders, call this method recursively to get messages
ImapFolderInfoCollection folderInfoCollection = client.ListFolders(folderInfo.Name);
foreach (ImapFolderInfo subfolderInfo in folderInfoCollection)
{
ListMessagesInFolder(subfolderInfo, rootFolder, client);
}
}
catch (Exception) { }
// ExEnd:ReadMessagesRecursively
}
}
}
| {
"content_hash": "f7f7238c184033dca5b4d26b4d03c717",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 189,
"avg_line_length": 45.927083333333336,
"alnum_prop": 0.580403719664323,
"repo_name": "jawadaspose/Aspose.Email-for-.NET",
"id": "866d855c142924d4931f81b32f6dd3908a1db7b0",
"size": "4411",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Examples/CSharp/IMAP/ReadMessagesRecursively.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "110578"
}
],
"symlink_target": ""
} |
/*
* 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 com.facebook.presto.orc.stream;
import com.facebook.presto.orc.OrcCorruptionException;
import com.facebook.presto.orc.OrcDecompressor;
import com.facebook.presto.orc.checkpoint.DecimalStreamCheckpoint;
import com.facebook.presto.spi.type.Decimals;
import io.airlift.slice.Slice;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import static com.facebook.presto.memory.context.AggregatedMemoryContext.newSimpleAggregatedMemoryContext;
import static com.facebook.presto.orc.OrcDecompressor.createOrcDecompressor;
import static com.facebook.presto.orc.metadata.CompressionKind.SNAPPY;
public class TestShortDecimalStream
extends AbstractTestValueStream<Long, DecimalStreamCheckpoint, DecimalOutputStream, DecimalInputStream>
{
@Test
public void test()
throws IOException
{
Random random = new Random(0);
List<List<Long>> groups = new ArrayList<>();
for (int groupIndex = 0; groupIndex < 3; groupIndex++) {
List<Long> group = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
long value = random.nextLong();
group.add(value);
}
groups.add(group);
}
testWriteValue(groups);
}
@Override
protected DecimalOutputStream createValueOutputStream()
{
return new DecimalOutputStream(SNAPPY, COMPRESSION_BLOCK_SIZE);
}
@Override
protected void writeValue(DecimalOutputStream outputStream, Long value)
{
outputStream.writeUnscaledValue(Decimals.encodeUnscaledValue(value));
}
@Override
protected DecimalInputStream createValueStream(Slice slice)
throws OrcCorruptionException
{
Optional<OrcDecompressor> orcDecompressor = createOrcDecompressor(ORC_DATA_SOURCE_ID, SNAPPY, COMPRESSION_BLOCK_SIZE);
OrcInputStream input = new OrcInputStream(ORC_DATA_SOURCE_ID, slice.getInput(), orcDecompressor, newSimpleAggregatedMemoryContext(), slice.getRetainedSize());
return new DecimalInputStream(input);
}
@Override
protected Long readValue(DecimalInputStream valueStream)
throws IOException
{
return valueStream.nextLong();
}
}
| {
"content_hash": "8d9574a0d80c1b66598198a37b33513f",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 166,
"avg_line_length": 36.1875,
"alnum_prop": 0.7195164075993091,
"repo_name": "Yaliang/presto",
"id": "83d1b7ade33f805c70f85d3c0d8fc8645aa3b3e6",
"size": "2895",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "presto-orc/src/test/java/com/facebook/presto/orc/stream/TestShortDecimalStream.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "26997"
},
{
"name": "CSS",
"bytes": "13018"
},
{
"name": "HTML",
"bytes": "28633"
},
{
"name": "Java",
"bytes": "31905833"
},
{
"name": "JavaScript",
"bytes": "214692"
},
{
"name": "Makefile",
"bytes": "6830"
},
{
"name": "PLSQL",
"bytes": "2797"
},
{
"name": "PLpgSQL",
"bytes": "11504"
},
{
"name": "Python",
"bytes": "7664"
},
{
"name": "SQLPL",
"bytes": "926"
},
{
"name": "Shell",
"bytes": "29871"
},
{
"name": "Thrift",
"bytes": "12631"
}
],
"symlink_target": ""
} |
package com.google.samples.apps.iosched.feed;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.samples.apps.iosched.lib.R;
import com.google.samples.apps.iosched.navigation.NavigationModel;
import com.google.samples.apps.iosched.ui.BaseActivity;
/**
* This is the host Activity for a list of cards that present key updates on the conference.
* The cards are shown in a {@link RecyclerView} and the content in each card comes from a Firebase
* Real-Time Database.
*/
public class FeedActivity extends BaseActivity {
private static final String SCREEN_LABEL = "Feed";
private FeedContract.Presenter mPresenter;
private DatabaseReference mDatabaseReference;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feed_act);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
setFullscreenLayout();
FeedFragment feedFragment = (FeedFragment) getSupportFragmentManager()
.findFragmentById(R.id.main_content);
feedFragment.setRetainInstance(true);
mPresenter = new FeedPresenter(feedFragment);
feedFragment.setPresenter(mPresenter);
}
@Override
protected void onResume() {
super.onResume();
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("feed");
mPresenter.initializeDataListener(mDatabaseReference);
FeedState.getInstance().enterFeedPage();
FeedState.getInstance().updateNewFeedItem(this, false);
updateFeedBadge();
}
@Override
protected void onPause() {
mPresenter.removeDataListener(mDatabaseReference);
FeedState.getInstance().exitFeedPage();
super.onPause();
}
@Override
protected NavigationModel.NavigationItemEnum getSelfNavDrawerItem() {
return NavigationModel.NavigationItemEnum.FEED;
}
@Override
public boolean canSwipeRefreshChildScrollUp() {
return true;
}
@Override
protected String getAnalyticsScreenLabel() {
return SCREEN_LABEL;
}
@Override
protected int getNavigationTitleId() {
return R.string.title_feed;
}
}
| {
"content_hash": "ee6170d0ce81047fa588c585b1c2ddca",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 99,
"avg_line_length": 31.746666666666666,
"alnum_prop": 0.7173456530869382,
"repo_name": "WeRockStar/iosched",
"id": "b6ecabc04a99386b85834f701866f3b4429b1fd4",
"size": "2969",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/src/main/java/com/google/samples/apps/iosched/feed/FeedActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2105"
},
{
"name": "HTML",
"bytes": "36389"
},
{
"name": "Java",
"bytes": "1517624"
},
{
"name": "Shell",
"bytes": "10537"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `S_IFSOCK` constant in crate `libc`.">
<meta name="keywords" content="rust, rustlang, rust-lang, S_IFSOCK">
<title>libc::S_IFSOCK - Rust</title>
<link rel="stylesheet" type="text/css" href="../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../main.css">
<link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<a href='../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a>
<p class='location'><a href='index.html'>libc</a></p><script>window.sidebarCurrent = {name: 'S_IFSOCK', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content constant">
<h1 class='fqn'><span class='in-band'><a href='index.html'>libc</a>::<wbr><a class='constant' href=''>S_IFSOCK</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-1380' class='srclink' href='../src/libc/unix/notbsd/mod.rs.html#251' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const S_IFSOCK: <a class='type' href='../libc/type.mode_t.html' title='libc::mode_t'>mode_t</a><code> = </code><code>49152</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../";
window.currentCrate = "libc";
window.playgroundUrl = "";
</script>
<script src="../jquery.js"></script>
<script src="../main.js"></script>
<script defer src="../search-index.js"></script>
</body>
</html> | {
"content_hash": "6ae664eac96f84ddbb5d1b42c2b7dceb",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 196,
"avg_line_length": 37.40350877192982,
"alnum_prop": 0.5058630393996247,
"repo_name": "rxse/rust-markov-text",
"id": "9fc276916a38b1171eb033e7f07084f39bb181e2",
"size": "4274",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/libc/constant.S_IFSOCK.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Rust",
"bytes": "3915"
}
],
"symlink_target": ""
} |
import unittest
if False:
import os, sys, imp
sys.path.append(os.path.realpath(os.path.dirname(__file__)+"/../../../"))
imp.load_module('electroncash', *imp.find_module('lib'))
imp.load_module('electroncash_gui', *imp.find_module('gui/qt'))
imp.load_module('electroncash_plugins', *imp.find_module('plugins'))
from plugins.fusion import encrypt
def fastslowcase(testmethod):
""" method -> class decorator to run with pycryptodomex's fast AES enabled/disabled """
class _TestClass(unittest.TestCase):
def test_slow(self):
saved = encrypt.AES
encrypt.AES = None
try:
testmethod(self)
finally:
encrypt.AES = saved
def test_fast(self):
if not encrypt.AES:
self.skipTest("accelerated AES library not available")
testmethod(self)
_TestClass.__name__ = testmethod.__name__
return _TestClass
@fastslowcase
def TestNormal(self):
Apriv = bytes.fromhex('0000000000000000000000000000000000000000000000000000000000000005')
Apub = bytes.fromhex('022f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4')
# short message
msg12 = b'test message'
assert len(msg12) == 12
e12 = encrypt.encrypt(msg12, Apub)
self.assertEqual(len(e12), 65) # since it's only 12 bytes, it and length fit into one block
e12 = encrypt.encrypt(msg12, Apub, pad_to_length = 16)
self.assertEqual(len(e12), 65)
d12, k = encrypt.decrypt(e12, Apriv)
self.assertEqual(d12, msg12)
d12 = encrypt.decrypt_with_symmkey(e12, k)
self.assertEqual(d12, msg12)
# tweak the nonce point's oddness bit
e12_bad = bytearray(e12) ; e12_bad[0] ^= 1
with self.assertRaises(encrypt.DecryptionFailed):
encrypt.decrypt(e12_bad, Apriv)
d12 = encrypt.decrypt_with_symmkey(e12_bad, k) # works because it doesn't care about nonce point
self.assertEqual(d12, msg12)
# tweak the hmac
e12_bad = bytearray(e12) ; e12_bad[-1] ^= 1
with self.assertRaises(encrypt.DecryptionFailed):
encrypt.decrypt(e12_bad, Apriv)
with self.assertRaises(encrypt.DecryptionFailed):
encrypt.decrypt_with_symmkey(e12_bad, k)
# tweak the message
e12_bad = bytearray(e12) ; e12_bad[35] ^= 1
with self.assertRaises(encrypt.DecryptionFailed):
encrypt.decrypt(e12_bad, Apriv)
with self.assertRaises(encrypt.DecryptionFailed):
encrypt.decrypt_with_symmkey(e12_bad, k)
# drop a byte
e12_bad = bytearray(e12) ; e12_bad.pop()
with self.assertRaises(encrypt.DecryptionFailed):
encrypt.decrypt(e12_bad, Apriv)
with self.assertRaises(encrypt.DecryptionFailed):
encrypt.decrypt_with_symmkey(e12_bad, k)
msg13 = msg12 + b'!'
e13 = encrypt.encrypt(msg13, Apub)
self.assertEqual(len(e13), 81) # need another block
with self.assertRaises(ValueError):
encrypt.encrypt(msg13, Apub, pad_to_length = 16)
e13 = encrypt.encrypt(msg13, Apub, pad_to_length = 32)
self.assertEqual(len(e13), 81)
encrypt.decrypt(e13, Apriv)
msgbig = b'a'*1234
ebig = encrypt.encrypt(msgbig, Apub)
self.assertEqual(len(ebig), 33 + (1234+4+10) + 16)
dbig, k = encrypt.decrypt(ebig, Apriv)
self.assertEqual(dbig, msgbig)
self.assertEqual(len(encrypt.encrypt(b'', Apub)), 65)
self.assertEqual(len(encrypt.encrypt(b'', Apub, pad_to_length = 1248)), 1297)
with self.assertRaises(ValueError):
encrypt.encrypt(b'', Apub, pad_to_length = 0)
| {
"content_hash": "ce85164415f1c8b5f8f117b1a87029aa",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 101,
"avg_line_length": 36.56701030927835,
"alnum_prop": 0.6630955737242741,
"repo_name": "fyookball/electrum",
"id": "27031afb7a4a5b5e3a23cad231873e5a311ee667",
"size": "3708",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/fusion/tests/test_encrypt.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "GLSL",
"bytes": "289"
},
{
"name": "Java",
"bytes": "1574"
},
{
"name": "Makefile",
"bytes": "842"
},
{
"name": "NSIS",
"bytes": "7309"
},
{
"name": "Objective-C",
"bytes": "415997"
},
{
"name": "Python",
"bytes": "2365528"
},
{
"name": "Shell",
"bytes": "26389"
}
],
"symlink_target": ""
} |
function baseselect(widget_id, url, skin, parameters)
{
// Will be using "self" throughout for the various flavors of "this"
// so for consistency ...
self = this;
// Initialization
self.widget_id = widget_id;
// Store on brightness or fallback to a default
// Parameters may come in useful later on
self.parameters = parameters;
self.initial = 1
self.onChange = onChange;
var callbacks = [
{"observable": "selectedoption", "action": "change", "callback": self.onChange}
];
// Define callbacks for entities - this model allows a widget to monitor multiple entities if needed
// Initial will be called when the dashboard loads and state has been gathered for the entity
// Update will be called every time an update occurs for that entity
self.OnStateAvailable = OnStateAvailable;
self.OnStateUpdate = OnStateUpdate;
if ("entity" in parameters)
{
var monitored_entities =
[
{"entity": parameters.entity, "initial": self.OnStateAvailable, "update": self.OnStateUpdate}
]
}
else
{
var monitored_entities = []
}
// Finally, call the parent constructor to get things moving
WidgetBase.call(self, widget_id, url, skin, parameters, monitored_entities, callbacks);
// Function Definitions
// The StateAvailable function will be called when
// self.state[<entity>] has valid information for the requested entity
// state is the initial state
// Methods
function OnStateAvailable(self, state)
{
self.state = state;
self.options = state.attributes.options;
set_options(self, self.options, state);
set_value(self, state)
}
function OnStateUpdate(self, state)
{
if (self.options != state.attributes.options)
{
self.options = state.attributes.options;
set_options(self, self.options, state);
}
if (self.state != state.state)
{
self.state = state.state;
set_value(self, state);
}
}
function set_value(self, state)
{
value = self.map_state(self, state.state);
self.set_field(self, "selectedoption", value)
}
function onChange(self, state)
{
if (self.state != self.ViewModel.selectedoption())
{
self.state = self.ViewModel.selectedoption();
if (self.initial != 1)
{
args = self.parameters.post_service;
args["option"] = self.state;
self.call_service(self, args)
}
else
{
self.initial = 0
}
}
}
function set_options(self, options, state)
{
self.set_field(self, "inputoptions", options)
}
}
| {
"content_hash": "d8876cc720b4e86e412c9f4d8dbf5eeb",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 109,
"avg_line_length": 27.150943396226417,
"alnum_prop": 0.5872133425990271,
"repo_name": "acockburn/appdaemon",
"id": "a141014253b7847e785508ff1c428e82f31fb727",
"size": "2878",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "appdaemon/widgets/baseselect/baseselect.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "96201"
},
{
"name": "Shell",
"bytes": "1768"
}
],
"symlink_target": ""
} |
Front-end web development framework: HTML5 & CSS3 by [*Zaffri*](http://www.zaffri.com/).
The project is still a WIP!
---------------------------------------
## Documentation
* http://jolt.zaffri.com
---------------------------------------
## Live Examples
* http://jolt.zaffri.com
* http://zaffri.com
---------------------------------------
## Notable Features
1. Full-page classes
2. Responsive cells
3. Horizontal & Vertical alignment
4. Topbar component
4.1. Dyanmic scroll styles
4.2. Responsive navigation with mobile 'burger' toggle
4.3. JavaScript fallback for mobile toggle
5. Sidebar component
5.1. Responsive Sidebar navigation with 'burger' toggle
5.2. JS nav collapse class
---------------------------------------
## Demos
1. **Basic Topbar**: demo-basic.html - Basic demo of vertical/horizontal alignment and Topbar component.
2. **Dropdowns Topbar**: demo-dropdowns.html - Basic demo of dropdown links (nested lists) within the Topbar component.
3. **Basic Sidebar**: demo-sidebar.html - Basic sidebar demo.
---------------------------------------
## Templates (Markup only)
1. **Basic Topbar**: "starter-template-1.html" - Basic structure for Jolt site with single level navigation using Topbar component.
2. **Dropdowns Topbar**: "starter-template-2.html" - Basic structure for Jolt site with dropdowns using Topbar component.
3. **Basic Sidebar**: "starter-template-3.html" - Basic structure for Jolt sidebar component.
---------------------------------------
I will be adding more functionality/fixing bugs as time goes on, let me know if you have any suggestions or constructive critism. Thanks!
Steven. | {
"content_hash": "4624800d14b60f43b9aab2352d8c9c96",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 137,
"avg_line_length": 35.91489361702128,
"alnum_prop": 0.6261848341232228,
"repo_name": "Zaffri/Jolt",
"id": "10fc79d8603041eddaa7e146fe012e938737a255",
"size": "1695",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9211"
},
{
"name": "HTML",
"bytes": "4478"
},
{
"name": "JavaScript",
"bytes": "3126"
}
],
"symlink_target": ""
} |
Public Class Form1
Private Sub btnBeenden_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBeenden.Click
Me.Close()
End Sub
Private Sub drvLaufwerk_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles drvLaufwerk.SelectedIndexChanged
dirVerzeichnis.Path = drvLaufwerk.Drive
End Sub
Private Sub dirVerzeichnis_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dirVerzeichnis.SelectedIndexChanged
filDatei.Path = dirVerzeichnis.DirList(dirVerzeichnis.DirListIndex)
End Sub
Private Sub filDatei_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filDatei.SelectedIndexChanged
picBild.Image = Image.FromFile(filDatei.Path & "\" & filDatei.FileName)
lblPfad.Text = filDatei.Path & "\" & filDatei.FileName
End Sub
End Class
| {
"content_hash": "14cfcaf0a9d42363aa16f3e3fc4c166a",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 155,
"avg_line_length": 49.26315789473684,
"alnum_prop": 0.7649572649572649,
"repo_name": "severinkaderli/gibb",
"id": "db5a9469d6583ac579ee7a7124b23c3b11621982",
"size": "938",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Lehrjahr_2/Modul_303/Bildbetrachter/Bildbetrachter/Form1.vb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "2987"
},
{
"name": "CSS",
"bytes": "10570"
},
{
"name": "HTML",
"bytes": "42182"
},
{
"name": "Java",
"bytes": "151613"
},
{
"name": "JavaScript",
"bytes": "1270"
},
{
"name": "PHP",
"bytes": "73673"
},
{
"name": "Python",
"bytes": "10117"
},
{
"name": "Shell",
"bytes": "5569"
},
{
"name": "Visual Basic",
"bytes": "281760"
}
],
"symlink_target": ""
} |
- Removed wound penalties from affecting soak rolls (reported by **Wolf**)
### Version 1.82 (2019-01-08):
- Add names to all roll button, so they can be dragged to user's macro bar
### Version 1.81 (2018-09-25):
- Change roll templates of different kind of rolls to have matching colors: Blue for attributes/skills, red for weapon/armor, black for custom and initiative rolls, and keep force rolls purple
- Readme link fix
### Version 1.80 (2018-09-17):
- Roll Templates added (Blue, red, green, black versions of the default)
- Force Emptiness sheet worker simplified (courtesy to **G G**)
- simplified npc/ pc toggle (code cleanup)
- remove redundant "sheet-" from all classes in html
- separate Changelog from Readme
### Version 1.72 (2018-08-22)
- Readme formatting
### Version 1.71 (2018-07-31)
**Fix:**
- Corrected Force Emptiness to scale properly with DarkSidePoints
### Version 1.70 (2018-07-24)
**Layout:**
- Made wound tracker wider
- Force section
**New Feature:**
- Under Force skills, space for powers and their roll buttons added
### Version 1.68 (2018-07-17)
**Layout:**
- remove empty gap on top of sheet
- improved layout in most sections
- added some tooltip info to menu settings
- Moved Backgorund section under Equipment Section
- Sheet version number & sheet type is now shown in corner
**Fixes:**
- corrected Lightsaber Combat dmg roll
- Force Emptiness bonus is now properly reduced by number of DSP
**New Feature:**
- added Resist Pain Force power(with sheet worker)
**Other:**
- code cleanup of some rolls
- removed all sheetworkers that where Gumshoe inmort and unnecessary
- updated preview
### Version 1.6 (2018-07-10)
- sheet customization menu added with these options:
- pc/npc sheet switch (condenced basic info block & equipment sections)
- hide/show gmroll buttons option (these rolls are whispered to GM)
- show/hide options for Force, Background & Equipment section
- Fixed Force Emptiness tracker (now able to change it's strength according to DSP)
- minor formatting
- some code cleanup
### Prior v1.6
- Weapon section roll fixed (2018-02)
- Vehicle/Ship text blocks have been added to the bottom of the sheet(2018-02)
- "Lightsaber Combat" option added to the Force section so you can have your attack and damage rolls preset for "Lightsaber Combat" (2018-02)
- Unused Resist Pain attribute removed (2018-02)
- Added a Skill Section and Attack Button (weapon section) (2018-01-15)
- Increased the Size of the Medium Range to take triple digit numbers (weapon section) (2018-01-15)
- Weapon name is properly showed when damage is rolled from the sheet (2017-11)
- Perception skills and old weapons are back! (2017-11)
- All skills and attributes now rolls with a template and dice/pip mod can be given (2017-11)
- Armor section is working, rolls and all (2017-11)
- added tracker for permanent initiative bonus(some races have that) (2017-11)
- A initiative skill have been added to second section next to char points, with a roll that sends to tracker (2017-11)
- Custom rollers, with and without wild die have been added to same section (2017-11)
- Roller for char points have been added next to char point attribute (2017-11)
- Force and Background section can now be hidden with a checkbox each (2017-11)
- Resist pain in force section have been disabled for not working properly (2017-11)
- Duplicating text fields "character connections" <-> "other notes" is fixed (2017-11)
- Added attributes for wound levels, and trackers for force emptiness, number of force powers active and Resist Pain (2017-11-15)
- Added repeating armor section with soak rolls (2017-11)
- All attributes & skill roll using a template, taking wounds in considerations, and the player can additionally choose to include Dice/pip mods for the rolls (2017-11-15)
- Added missing Star Wars logo & black space background (2017-11-15)
- Checkbox to hide force section (2017-11-15)
- Change dice icon to d6 (2017-11-15)
| {
"content_hash": "33a9ef089d1941e3f4a9962343b113b5",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 192,
"avg_line_length": 29.33093525179856,
"alnum_prop": 0.7319107186656856,
"repo_name": "neovatar/roll20-character-sheets",
"id": "c42a1d8ab3c1f1d9a03230d96c9eb51f701b71bf",
"size": "4109",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "D6StarWars/CHANGELOG.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "154"
},
{
"name": "CSS",
"bytes": "12171505"
},
{
"name": "HTML",
"bytes": "120869714"
},
{
"name": "JavaScript",
"bytes": "1247312"
},
{
"name": "Makefile",
"bytes": "50"
},
{
"name": "Python",
"bytes": "340"
},
{
"name": "Shell",
"bytes": "953"
}
],
"symlink_target": ""
} |
using namespace web::json;
static void GenStat(Stat& stat, const value& v) {
switch (v.type()) {
case value::value_type::Array:
for (auto const& element : v.as_array())
GenStat(stat, element);
stat.arrayCount++;
stat.elementCount += v.size();
break;
case value::value_type::Object:
for (auto const& kv : v.as_object()) {
GenStat(stat, kv.second);
stat.stringLength += kv.first.size();
}
stat.objectCount++;
stat.memberCount += v.size();
stat.stringCount += v.size(); // member names
break;
case value::value_type::String:
stat.stringCount++;
stat.stringLength += v.as_string().size();
break;
case value::value_type::Number:
stat.numberCount++;
break;
case value::value_type::Boolean:
if (v.as_bool())
stat.trueCount++;
else
stat.falseCount++;
break;
case value::value_type::Null:
stat.nullCount++;
break;
}
}
class CasablancaParseResult : public ParseResultBase {
public:
value root;
};
class CasablancaStringResult : public StringResultBase {
public:
virtual const char* c_str() const { return s.c_str(); }
std::string s;
};
class CasablancaTest : public TestBase {
public:
#if TEST_INFO
virtual const char* GetName() const { return "C++ REST SDK (C++11)"; }
virtual const char* GetFilename() const { return __FILE__; }
#endif
#if TEST_PARSE
virtual ParseResultBase* Parse(const char* json, size_t length) const {
(void)length;
CasablancaParseResult* pr = new CasablancaParseResult;
std::istrstream is (json);
try {
pr->root = value::parse(is);
}
catch (web::json::json_exception& e) {
printf("Parse error '%s'\n", e.what());
delete pr;
pr = 0;
}
catch (...) {
delete pr;
pr = 0;
}
return pr;
}
#endif
#if TEST_STRINGIFY
virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const {
const CasablancaParseResult* pr = static_cast<const CasablancaParseResult*>(parseResult);
CasablancaStringResult* sr = new CasablancaStringResult;
std::ostringstream os;
pr->root.serialize(os);
sr->s = os.str();
return sr;
}
#endif
#if TEST_STATISTICS
virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const {
const CasablancaParseResult* pr = static_cast<const CasablancaParseResult*>(parseResult);
memset(stat, 0, sizeof(Stat));
GenStat(*stat, pr->root);
return true;
}
#endif
#if TEST_CONFORMANCE
virtual bool ParseDouble(const char* json, double* d) const {
std::istrstream is(json);
try {
value root = value::parse(is);
*d = root.at(0).as_double();
return true;
}
catch (...) {
}
return false;
}
virtual bool ParseString(const char* json, std::string& s) const {
std::istrstream is(json);
try {
value root = value::parse(is);
s = to_utf8string(root.at(0).as_string());
return true;
}
catch (...) {
}
return false;
}
#endif
};
REGISTER_TEST(CasablancaTest);
#endif | {
"content_hash": "6dcc0b1b1287505a79ad1fcadd399990",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 97,
"avg_line_length": 25.458646616541355,
"alnum_prop": 0.5694034258712345,
"repo_name": "wangfakang/nativejson-benchmark",
"id": "24526d81deedbb1d6db05367ba4b21b349df902b",
"size": "4707",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/tests/casablancatest.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "72"
},
{
"name": "C",
"bytes": "9556"
},
{
"name": "C++",
"bytes": "205012"
},
{
"name": "HTML",
"bytes": "687715"
},
{
"name": "JavaScript",
"bytes": "1133589"
},
{
"name": "Lua",
"bytes": "5457"
},
{
"name": "Makefile",
"bytes": "1283"
},
{
"name": "PHP",
"bytes": "28214"
},
{
"name": "Shell",
"bytes": "1358"
}
],
"symlink_target": ""
} |
<h2>Chat</h2>
<form>
<input placeholder="Message..." ng-model="newMessage">
<button type="submit" ng-click="addMessage(newMessage);newMessage = null;">send</button>
</form>
<ul id="messages" ng-show="messages.length">
<li ng-repeat="message in messages | reverse">{{message.text}}</li>
</ul>
<p class="alert alert-danger" ng-show="err">{{err}}</p>
| {
"content_hash": "04d7cfdd8b95f93da2e5f51b355d2a0b",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 90,
"avg_line_length": 29.75,
"alnum_prop": 0.6694677871148459,
"repo_name": "briandiephuis/IP",
"id": "67fd4ff48be58595ee5ecb540f4dfff627fd1704",
"size": "358",
"binary": false,
"copies": "26",
"ref": "refs/heads/master",
"path": "app/views/chat.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "24072"
},
{
"name": "CSS",
"bytes": "1753"
},
{
"name": "HTML",
"bytes": "106192"
},
{
"name": "JavaScript",
"bytes": "84537"
}
],
"symlink_target": ""
} |
#include "tensorflow/core/kernels/cwise_ops_common.h"
namespace tensorflow {
#if !defined(MLIR_GENERATED_CPU_KERNELS_ENABLED) || \
!defined(MLIR_GENERATED_EXPERIMENTAL_KERNELS_ENABLED)
REGISTER8(BinaryOp, CPU, "LeftShift", functor::left_shift, int8, int16, int32,
int64, uint8, uint16, uint32, uint64);
#else
// TODO(b/172804967): We do not generate unsigned kernels for CPU via mlir.
REGISTER4(BinaryOp, CPU, "LeftShift", functor::left_shift, uint8, uint16,
uint32, uint64);
#endif
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED)
REGISTER8(BinaryOp, GPU, "LeftShift", functor::left_shift, int8, int16, int32,
int64, uint8, uint16, uint32, uint64);
#else
// TODO(b/172804967): We do not generate unsigned kernels for GPU via mlir.
REGISTER4(BinaryOp, GPU, "LeftShift", functor::left_shift, uint8, uint16,
uint32, uint64);
#endif
#endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM
} // namespace tensorflow
| {
"content_hash": "ce884a184204111223273f3bfad24f05",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 78,
"avg_line_length": 35.42857142857143,
"alnum_prop": 0.7137096774193549,
"repo_name": "sarvex/tensorflow",
"id": "83e9b69a3c136066d4619a9a9ed2aeca95881969",
"size": "1660",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "tensorflow/core/kernels/cwise_op_left_shift.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "148184"
},
{
"name": "C++",
"bytes": "6224499"
},
{
"name": "CSS",
"bytes": "107"
},
{
"name": "HTML",
"bytes": "650478"
},
{
"name": "Java",
"bytes": "53519"
},
{
"name": "JavaScript",
"bytes": "6659"
},
{
"name": "Jupyter Notebook",
"bytes": "777935"
},
{
"name": "Objective-C",
"bytes": "1288"
},
{
"name": "Protocol Buffer",
"bytes": "61743"
},
{
"name": "Python",
"bytes": "3474762"
},
{
"name": "Shell",
"bytes": "45640"
},
{
"name": "TypeScript",
"bytes": "283668"
}
],
"symlink_target": ""
} |
.skin-blue .main-header .navbar {
background-color: #1a2226;
}
.skin-blue .main-header .navbar .nav > li > a {
color: #fff;
}
.skin-blue .main-header .navbar .nav > li > a:hover, .skin-blue .main-header .navbar .nav > li > a:active, .skin-blue .main-header .navbar .nav > li > a:focus, .skin-blue .main-header .navbar .nav .open > a, .skin-blue .main-header .navbar .nav .open > a:hover, .skin-blue .main-header .navbar .nav .open > a:focus, .skin-blue .main-header .navbar .nav > .active > a {
background: rgba(0,0,0,0.1);
color: #f6f6f6;
}
.skin-blue .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-blue .main-header .navbar .sidebar-toggle:hover {
color: #f6f6f6;
background: rgba(0,0,0,0.1);
}
.skin-blue .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-blue .main-header .navbar .sidebar-toggle:hover {
background-color: #367fa9;
}
@media (max-width:767px) {
.skin-blue .main-header .navbar .dropdown-menu li.divider {
background-color: rgba(255,255,255,0.1);
}
.skin-blue .main-header .navbar .dropdown-menu li a {
color: #fff;
}
.skin-blue .main-header .navbar .dropdown-menu li a:hover {
background: #367fa9;
}
}
.skin-blue .main-header .logo {
background-color: #1a2226;
color: #fff;
border-bottom: 0 solid transparent;
}
.skin-blue .main-header .logo:hover {
background-color: #357ca5;
}
.skin-blue .main-header li.user-header {
background-color: #3c8dbc;
}
.skin-blue .content-header {
background: transparent;
}
.skin-blue .wrapper, .skin-blue .main-sidebar, .skin-blue .left-side {
background-color: #222d32;
}
.skin-blue .user-panel > .info, .skin-blue .user-panel > .info > a {
color: #fff;
}
.skin-blue .sidebar-menu > li.header {
color: #4b646f;
background: #1a2226;
}
.skin-blue .sidebar-menu > li > a {
border-left: 3px solid transparent;
}
.skin-blue .sidebar-menu > li:hover > a, .skin-blue .sidebar-menu > li.active > a {
color: #fff;
background: #1e282c;
border-left-color: #3c8dbc;
}
.skin-blue .sidebar-menu > li > .treeview-menu {
margin: 0 1px;
background: #2c3b41;
}
.skin-blue .sidebar a {
color: #b8c7ce;
}
.skin-blue .sidebar a:hover {
text-decoration: none;
}
.skin-blue .treeview-menu > li > a {
color: #8aa4af;
}
.skin-blue .treeview-menu > li.active > a, .skin-blue .treeview-menu > li > a:hover {
color: #fff;
}
.skin-blue .sidebar-form {
border-radius: 3px;
border: 1px solid #374850;
margin: 10px 10px;
}
.skin-blue .sidebar-form input[type="text"], .skin-blue .sidebar-form .btn {
box-shadow: none;
background-color: #374850;
border: 1px solid transparent;
height: 35px;
-webkit-transition: all .3s ease-in-out;
-o-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.skin-blue .sidebar-form input[type="text"] {
color: #666;
border-top-left-radius: 2px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-bottom-left-radius: 2px;
}
.skin-blue .sidebar-form input[type="text"]:focus, .skin-blue .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
background-color: #fff;
color: #666;
}
.skin-blue .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
border-left-color: #fff;
}
.skin-blue .sidebar-form .btn {
color: #999;
border-top-left-radius: 0;
border-top-right-radius: 2px;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 0;
}
.skin-blue.layout-top-nav .main-header > .logo {
background-color: #3c8dbc;
color: #fff;
border-bottom: 0 solid transparent;
}
.skin-blue.layout-top-nav .main-header > .logo:hover {
background-color: #3b8ab8;
}
.skin-blue-light .main-header .navbar {
background-color: #3c8dbc;
}
.skin-blue-light .main-header .navbar .nav > li > a {
color: #fff;
}
.skin-blue-light .main-header .navbar .nav > li > a:hover, .skin-blue-light .main-header .navbar .nav > li > a:active, .skin-blue-light .main-header .navbar .nav > li > a:focus, .skin-blue-light .main-header .navbar .nav .open > a, .skin-blue-light .main-header .navbar .nav .open > a:hover, .skin-blue-light .main-header .navbar .nav .open > a:focus, .skin-blue-light .main-header .navbar .nav > .active > a {
background: rgba(0,0,0,0.1);
color: #f6f6f6;
}
.skin-blue-light .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-blue-light .main-header .navbar .sidebar-toggle:hover {
color: #f6f6f6;
background: rgba(0,0,0,0.1);
}
.skin-blue-light .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-blue-light .main-header .navbar .sidebar-toggle:hover {
background-color: #367fa9;
}
@media (max-width:767px) {
.skin-blue-light .main-header .navbar .dropdown-menu li.divider {
background-color: rgba(255,255,255,0.1);
}
.skin-blue-light .main-header .navbar .dropdown-menu li a {
color: #fff;
}
.skin-blue-light .main-header .navbar .dropdown-menu li a:hover {
background: #367fa9;
}
}
.skin-blue-light .main-header .logo {
background-color: #3c8dbc;
color: #fff;
border-bottom: 0 solid transparent;
}
.skin-blue-light .main-header .logo:hover {
background-color: #3b8ab8;
}
.skin-blue-light .main-header li.user-header {
background-color: #3c8dbc;
}
.skin-blue-light .content-header {
background: transparent;
}
.skin-blue-light .wrapper, .skin-blue-light .main-sidebar, .skin-blue-light .left-side {
background-color: #f9fafc;
}
.skin-blue-light .content-wrapper, .skin-blue-light .main-footer {
border-left: 1px solid #d2d6de;
}
.skin-blue-light .user-panel > .info, .skin-blue-light .user-panel > .info > a {
color: #444;
}
.skin-blue-light .sidebar-menu > li {
-webkit-transition: border-left-color .3s ease;
-o-transition: border-left-color .3s ease;
transition: border-left-color .3s ease;
}
.skin-blue-light .sidebar-menu > li.header {
color: #848484;
background: #f9fafc;
}
.skin-blue-light .sidebar-menu > li > a {
border-left: 3px solid transparent;
font-weight: 600;
}
.skin-blue-light .sidebar-menu > li:hover > a, .skin-blue-light .sidebar-menu > li.active > a {
color: #000;
background: #f4f4f5;
}
.skin-blue-light .sidebar-menu > li.active {
border-left-color: #3c8dbc;
}
.skin-blue-light .sidebar-menu > li.active > a {
font-weight: 600;
}
.skin-blue-light .sidebar-menu > li > .treeview-menu {
background: #f4f4f5;
}
.skin-blue-light .sidebar a {
color: #444;
}
.skin-blue-light .sidebar a:hover {
text-decoration: none;
}
.skin-blue-light .treeview-menu > li > a {
color: #777;
}
.skin-blue-light .treeview-menu > li.active > a, .skin-blue-light .treeview-menu > li > a:hover {
color: #000;
}
.skin-blue-light .treeview-menu > li.active > a {
font-weight: 600;
}
.skin-blue-light .sidebar-form {
border-radius: 3px;
border: 1px solid #d2d6de;
margin: 10px 10px;
}
.skin-blue-light .sidebar-form input[type="text"], .skin-blue-light .sidebar-form .btn {
box-shadow: none;
background-color: #fff;
border: 1px solid transparent;
height: 35px;
-webkit-transition: all .3s ease-in-out;
-o-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.skin-blue-light .sidebar-form input[type="text"] {
color: #666;
border-top-left-radius: 2px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-bottom-left-radius: 2px;
}
.skin-blue-light .sidebar-form input[type="text"]:focus, .skin-blue-light .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
background-color: #fff;
color: #666;
}
.skin-blue-light .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
border-left-color: #fff;
}
.skin-blue-light .sidebar-form .btn {
color: #999;
border-top-left-radius: 0;
border-top-right-radius: 2px;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 0;
}
@media (min-width:768px) {
.skin-blue-light.sidebar-mini.sidebar-collapse .sidebar-menu > li > .treeview-menu {
border-left: 1px solid #d2d6de;
}
}
.skin-blue-light .main-footer {
border-top-color: #d2d6de;
}
.skin-blue.layout-top-nav .main-header > .logo {
background-color: #3c8dbc;
color: #fff;
border-bottom: 0 solid transparent;
}
.skin-blue.layout-top-nav .main-header > .logo:hover {
background-color: #3b8ab8;
}
.skin-black .main-header {
-webkit-box-shadow: 0 1px 1px rgba(0,0,0,0.05);
box-shadow: 0 1px 1px rgba(0,0,0,0.05);
}
.skin-black .main-header .navbar-toggle {
color: #333;
}
.skin-black .main-header .navbar-brand {
color: #333;
border-right: 1px solid #eee;
}
.skin-black .main-header > .navbar {
background-color: #fff;
}
.skin-black .main-header > .navbar .nav > li > a {
color: #333;
}
.skin-black .main-header > .navbar .nav > li > a:hover, .skin-black .main-header > .navbar .nav > li > a:active, .skin-black .main-header > .navbar .nav > li > a:focus, .skin-black .main-header > .navbar .nav .open > a, .skin-black .main-header > .navbar .nav .open > a:hover, .skin-black .main-header > .navbar .nav .open > a:focus, .skin-black .main-header > .navbar .nav > .active > a {
background: #fff;
color: #999;
}
.skin-black .main-header > .navbar .sidebar-toggle {
color: #333;
}
.skin-black .main-header > .navbar .sidebar-toggle:hover {
color: #999;
background: #fff;
}
.skin-black .main-header > .navbar > .sidebar-toggle {
color: #333;
border-right: 1px solid #eee;
}
.skin-black .main-header > .navbar .navbar-nav > li > a {
border-right: 1px solid #eee;
}
.skin-black .main-header > .navbar .navbar-custom-menu .navbar-nav > li > a, .skin-black .main-header > .navbar .navbar-right > li > a {
border-left: 1px solid #eee;
border-right-width: 0;
}
.skin-black .main-header > .logo {
background-color: #fff;
color: #333;
border-bottom: 0 solid transparent;
border-right: 1px solid #eee;
}
.skin-black .main-header > .logo:hover {
background-color: #fcfcfc;
}
@media (max-width:767px) {
.skin-black .main-header > .logo {
background-color: #222;
color: #fff;
border-bottom: 0 solid transparent;
border-right: none;
}
.skin-black .main-header > .logo:hover {
background-color: #1f1f1f;
}
}
.skin-black .main-header li.user-header {
background-color: #222;
}
.skin-black .content-header {
background: transparent;
box-shadow: none;
}
.skin-black .wrapper, .skin-black .main-sidebar, .skin-black .left-side {
background-color: #222d32;
}
.skin-black .user-panel > .info, .skin-black .user-panel > .info > a {
color: #fff;
}
.skin-black .sidebar-menu > li.header {
color: #4b646f;
background: #1a2226;
}
.skin-black .sidebar-menu > li > a {
border-left: 3px solid transparent;
}
.skin-black .sidebar-menu > li:hover > a, .skin-black .sidebar-menu > li.active > a {
color: #fff;
background: #1e282c;
border-left-color: #fff;
}
.skin-black .sidebar-menu > li > .treeview-menu {
margin: 0 1px;
background: #2c3b41;
}
.skin-black .sidebar a {
color: #b8c7ce;
}
.skin-black .sidebar a:hover {
text-decoration: none;
}
.skin-black .treeview-menu > li > a {
color: #8aa4af;
}
.skin-black .treeview-menu > li.active > a, .skin-black .treeview-menu > li > a:hover {
color: #fff;
}
.skin-black .sidebar-form {
border-radius: 3px;
border: 1px solid #374850;
margin: 10px 10px;
}
.skin-black .sidebar-form input[type="text"], .skin-black .sidebar-form .btn {
box-shadow: none;
background-color: #374850;
border: 1px solid transparent;
height: 35px;
-webkit-transition: all .3s ease-in-out;
-o-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.skin-black .sidebar-form input[type="text"] {
color: #666;
border-top-left-radius: 2px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-bottom-left-radius: 2px;
}
.skin-black .sidebar-form input[type="text"]:focus, .skin-black .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
background-color: #fff;
color: #666;
}
.skin-black .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
border-left-color: #fff;
}
.skin-black .sidebar-form .btn {
color: #999;
border-top-left-radius: 0;
border-top-right-radius: 2px;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 0;
}
.skin-black-light .main-header {
-webkit-box-shadow: 0 1px 1px rgba(0,0,0,0.05);
box-shadow: 0 1px 1px rgba(0,0,0,0.05);
}
.skin-black-light .main-header .navbar-toggle {
color: #333;
}
.skin-black-light .main-header .navbar-brand {
color: #333;
border-right: 1px solid #eee;
}
.skin-black-light .main-header > .navbar {
background-color: #fff;
}
.skin-black-light .main-header > .navbar .nav > li > a {
color: #333;
}
.skin-black-light .main-header > .navbar .nav > li > a:hover, .skin-black-light .main-header > .navbar .nav > li > a:active, .skin-black-light .main-header > .navbar .nav > li > a:focus, .skin-black-light .main-header > .navbar .nav .open > a, .skin-black-light .main-header > .navbar .nav .open > a:hover, .skin-black-light .main-header > .navbar .nav .open > a:focus, .skin-black-light .main-header > .navbar .nav > .active > a {
background: #fff;
color: #999;
}
.skin-black-light .main-header > .navbar .sidebar-toggle {
color: #333;
}
.skin-black-light .main-header > .navbar .sidebar-toggle:hover {
color: #999;
background: #fff;
}
.skin-black-light .main-header > .navbar > .sidebar-toggle {
color: #333;
border-right: 1px solid #eee;
}
.skin-black-light .main-header > .navbar .navbar-nav > li > a {
border-right: 1px solid #eee;
}
.skin-black-light .main-header > .navbar .navbar-custom-menu .navbar-nav > li > a, .skin-black-light .main-header > .navbar .navbar-right > li > a {
border-left: 1px solid #eee;
border-right-width: 0;
}
.skin-black-light .main-header > .logo {
background-color: #fff;
color: #333;
border-bottom: 0 solid transparent;
border-right: 1px solid #eee;
}
.skin-black-light .main-header > .logo:hover {
background-color: #fcfcfc;
}
@media (max-width:767px) {
.skin-black-light .main-header > .logo {
background-color: #222;
color: #fff;
border-bottom: 0 solid transparent;
border-right: none;
}
.skin-black-light .main-header > .logo:hover {
background-color: #1f1f1f;
}
}
.skin-black-light .main-header li.user-header {
background-color: #222;
}
.skin-black-light .content-header {
background: transparent;
box-shadow: none;
}
.skin-black-light .wrapper, .skin-black-light .main-sidebar, .skin-black-light .left-side {
background-color: #f9fafc;
}
.skin-black-light .content-wrapper, .skin-black-light .main-footer {
border-left: 1px solid #d2d6de;
}
.skin-black-light .user-panel > .info, .skin-black-light .user-panel > .info > a {
color: #444;
}
.skin-black-light .sidebar-menu > li {
-webkit-transition: border-left-color .3s ease;
-o-transition: border-left-color .3s ease;
transition: border-left-color .3s ease;
}
.skin-black-light .sidebar-menu > li.header {
color: #848484;
background: #f9fafc;
}
.skin-black-light .sidebar-menu > li > a {
border-left: 3px solid transparent;
font-weight: 600;
}
.skin-black-light .sidebar-menu > li:hover > a, .skin-black-light .sidebar-menu > li.active > a {
color: #000;
background: #f4f4f5;
}
.skin-black-light .sidebar-menu > li.active {
border-left-color: #fff;
}
.skin-black-light .sidebar-menu > li.active > a {
font-weight: 600;
}
.skin-black-light .sidebar-menu > li > .treeview-menu {
background: #f4f4f5;
}
.skin-black-light .sidebar a {
color: #444;
}
.skin-black-light .sidebar a:hover {
text-decoration: none;
}
.skin-black-light .treeview-menu > li > a {
color: #777;
}
.skin-black-light .treeview-menu > li.active > a, .skin-black-light .treeview-menu > li > a:hover {
color: #000;
}
.skin-black-light .treeview-menu > li.active > a {
font-weight: 600;
}
.skin-black-light .sidebar-form {
border-radius: 3px;
border: 1px solid #d2d6de;
margin: 10px 10px;
}
.skin-black-light .sidebar-form input[type="text"], .skin-black-light .sidebar-form .btn {
box-shadow: none;
background-color: #fff;
border: 1px solid transparent;
height: 35px;
-webkit-transition: all .3s ease-in-out;
-o-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.skin-black-light .sidebar-form input[type="text"] {
color: #666;
border-top-left-radius: 2px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-bottom-left-radius: 2px;
}
.skin-black-light .sidebar-form input[type="text"]:focus, .skin-black-light .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
background-color: #fff;
color: #666;
}
.skin-black-light .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
border-left-color: #fff;
}
.skin-black-light .sidebar-form .btn {
color: #999;
border-top-left-radius: 0;
border-top-right-radius: 2px;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 0;
}
@media (min-width:768px) {
.skin-black-light.sidebar-mini.sidebar-collapse .sidebar-menu > li > .treeview-menu {
border-left: 1px solid #d2d6de;
}
}
.skin-green .main-header .navbar {
background-color: #00a65a;
}
.skin-green .main-header .navbar .nav > li > a {
color: #fff;
}
.skin-green .main-header .navbar .nav > li > a:hover, .skin-green .main-header .navbar .nav > li > a:active, .skin-green .main-header .navbar .nav > li > a:focus, .skin-green .main-header .navbar .nav .open > a, .skin-green .main-header .navbar .nav .open > a:hover, .skin-green .main-header .navbar .nav .open > a:focus, .skin-green .main-header .navbar .nav > .active > a {
background: rgba(0,0,0,0.1);
color: #f6f6f6;
}
.skin-green .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-green .main-header .navbar .sidebar-toggle:hover {
color: #f6f6f6;
background: rgba(0,0,0,0.1);
}
.skin-green .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-green .main-header .navbar .sidebar-toggle:hover {
background-color: #008d4c;
}
@media (max-width:767px) {
.skin-green .main-header .navbar .dropdown-menu li.divider {
background-color: rgba(255,255,255,0.1);
}
.skin-green .main-header .navbar .dropdown-menu li a {
color: #fff;
}
.skin-green .main-header .navbar .dropdown-menu li a:hover {
background: #008d4c;
}
}
.skin-green .main-header .logo {
background-color: #008d4c;
color: #fff;
border-bottom: 0 solid transparent;
}
.skin-green .main-header .logo:hover {
background-color: #008749;
}
.skin-green .main-header li.user-header {
background-color: #00a65a;
}
.skin-green .content-header {
background: transparent;
}
.skin-green .wrapper, .skin-green .main-sidebar, .skin-green .left-side {
background-color: #222d32;
}
.skin-green .user-panel > .info, .skin-green .user-panel > .info > a {
color: #fff;
}
.skin-green .sidebar-menu > li.header {
color: #4b646f;
background: #1a2226;
}
.skin-green .sidebar-menu > li > a {
border-left: 3px solid transparent;
}
.skin-green .sidebar-menu > li:hover > a, .skin-green .sidebar-menu > li.active > a {
color: #fff;
background: #1e282c;
border-left-color: #00a65a;
}
.skin-green .sidebar-menu > li > .treeview-menu {
margin: 0 1px;
background: #2c3b41;
}
.skin-green .sidebar a {
color: #b8c7ce;
}
.skin-green .sidebar a:hover {
text-decoration: none;
}
.skin-green .treeview-menu > li > a {
color: #8aa4af;
}
.skin-green .treeview-menu > li.active > a, .skin-green .treeview-menu > li > a:hover {
color: #fff;
}
.skin-green .sidebar-form {
border-radius: 3px;
border: 1px solid #374850;
margin: 10px 10px;
}
.skin-green .sidebar-form input[type="text"], .skin-green .sidebar-form .btn {
box-shadow: none;
background-color: #374850;
border: 1px solid transparent;
height: 35px;
-webkit-transition: all .3s ease-in-out;
-o-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.skin-green .sidebar-form input[type="text"] {
color: #666;
border-top-left-radius: 2px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-bottom-left-radius: 2px;
}
.skin-green .sidebar-form input[type="text"]:focus, .skin-green .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
background-color: #fff;
color: #666;
}
.skin-green .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
border-left-color: #fff;
}
.skin-green .sidebar-form .btn {
color: #999;
border-top-left-radius: 0;
border-top-right-radius: 2px;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 0;
}
.skin-green-light .main-header .navbar {
background-color: #00a65a;
}
.skin-green-light .main-header .navbar .nav > li > a {
color: #fff;
}
.skin-green-light .main-header .navbar .nav > li > a:hover, .skin-green-light .main-header .navbar .nav > li > a:active, .skin-green-light .main-header .navbar .nav > li > a:focus, .skin-green-light .main-header .navbar .nav .open > a, .skin-green-light .main-header .navbar .nav .open > a:hover, .skin-green-light .main-header .navbar .nav .open > a:focus, .skin-green-light .main-header .navbar .nav > .active > a {
background: rgba(0,0,0,0.1);
color: #f6f6f6;
}
.skin-green-light .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-green-light .main-header .navbar .sidebar-toggle:hover {
color: #f6f6f6;
background: rgba(0,0,0,0.1);
}
.skin-green-light .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-green-light .main-header .navbar .sidebar-toggle:hover {
background-color: #008d4c;
}
@media (max-width:767px) {
.skin-green-light .main-header .navbar .dropdown-menu li.divider {
background-color: rgba(255,255,255,0.1);
}
.skin-green-light .main-header .navbar .dropdown-menu li a {
color: #fff;
}
.skin-green-light .main-header .navbar .dropdown-menu li a:hover {
background: #008d4c;
}
}
.skin-green-light .main-header .logo {
background-color: #00a65a;
color: #fff;
border-bottom: 0 solid transparent;
}
.skin-green-light .main-header .logo:hover {
background-color: #00a157;
}
.skin-green-light .main-header li.user-header {
background-color: #00a65a;
}
.skin-green-light .content-header {
background: transparent;
}
.skin-green-light .wrapper, .skin-green-light .main-sidebar, .skin-green-light .left-side {
background-color: #f9fafc;
}
.skin-green-light .content-wrapper, .skin-green-light .main-footer {
border-left: 1px solid #d2d6de;
}
.skin-green-light .user-panel > .info, .skin-green-light .user-panel > .info > a {
color: #444;
}
.skin-green-light .sidebar-menu > li {
-webkit-transition: border-left-color .3s ease;
-o-transition: border-left-color .3s ease;
transition: border-left-color .3s ease;
}
.skin-green-light .sidebar-menu > li.header {
color: #848484;
background: #f9fafc;
}
.skin-green-light .sidebar-menu > li > a {
border-left: 3px solid transparent;
font-weight: 600;
}
.skin-green-light .sidebar-menu > li:hover > a, .skin-green-light .sidebar-menu > li.active > a {
color: #000;
background: #f4f4f5;
}
.skin-green-light .sidebar-menu > li.active {
border-left-color: #00a65a;
}
.skin-green-light .sidebar-menu > li.active > a {
font-weight: 600;
}
.skin-green-light .sidebar-menu > li > .treeview-menu {
background: #f4f4f5;
}
.skin-green-light .sidebar a {
color: #444;
}
.skin-green-light .sidebar a:hover {
text-decoration: none;
}
.skin-green-light .treeview-menu > li > a {
color: #777;
}
.skin-green-light .treeview-menu > li.active > a, .skin-green-light .treeview-menu > li > a:hover {
color: #000;
}
.skin-green-light .treeview-menu > li.active > a {
font-weight: 600;
}
.skin-green-light .sidebar-form {
border-radius: 3px;
border: 1px solid #d2d6de;
margin: 10px 10px;
}
.skin-green-light .sidebar-form input[type="text"], .skin-green-light .sidebar-form .btn {
box-shadow: none;
background-color: #fff;
border: 1px solid transparent;
height: 35px;
-webkit-transition: all .3s ease-in-out;
-o-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.skin-green-light .sidebar-form input[type="text"] {
color: #666;
border-top-left-radius: 2px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-bottom-left-radius: 2px;
}
.skin-green-light .sidebar-form input[type="text"]:focus, .skin-green-light .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
background-color: #fff;
color: #666;
}
.skin-green-light .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
border-left-color: #fff;
}
.skin-green-light .sidebar-form .btn {
color: #999;
border-top-left-radius: 0;
border-top-right-radius: 2px;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 0;
}
@media (min-width:768px) {
.skin-green-light.sidebar-mini.sidebar-collapse .sidebar-menu > li > .treeview-menu {
border-left: 1px solid #d2d6de;
}
}
.skin-red .main-header .navbar {
background-color: #dd4b39;
}
.skin-red .main-header .navbar .nav > li > a {
color: #fff;
}
.skin-red .main-header .navbar .nav > li > a:hover, .skin-red .main-header .navbar .nav > li > a:active, .skin-red .main-header .navbar .nav > li > a:focus, .skin-red .main-header .navbar .nav .open > a, .skin-red .main-header .navbar .nav .open > a:hover, .skin-red .main-header .navbar .nav .open > a:focus, .skin-red .main-header .navbar .nav > .active > a {
background: rgba(0,0,0,0.1);
color: #f6f6f6;
}
.skin-red .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-red .main-header .navbar .sidebar-toggle:hover {
color: #f6f6f6;
background: rgba(0,0,0,0.1);
}
.skin-red .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-red .main-header .navbar .sidebar-toggle:hover {
background-color: #d73925;
}
@media (max-width:767px) {
.skin-red .main-header .navbar .dropdown-menu li.divider {
background-color: rgba(255,255,255,0.1);
}
.skin-red .main-header .navbar .dropdown-menu li a {
color: #fff;
}
.skin-red .main-header .navbar .dropdown-menu li a:hover {
background: #d73925;
}
}
.skin-red .main-header .logo {
background-color: #d73925;
color: #fff;
border-bottom: 0 solid transparent;
}
.skin-red .main-header .logo:hover {
background-color: #d33724;
}
.skin-red .main-header li.user-header {
background-color: #dd4b39;
}
.skin-red .content-header {
background: transparent;
}
.skin-red .wrapper, .skin-red .main-sidebar, .skin-red .left-side {
background-color: #222d32;
}
.skin-red .user-panel > .info, .skin-red .user-panel > .info > a {
color: #fff;
}
.skin-red .sidebar-menu > li.header {
color: #4b646f;
background: #1a2226;
}
.skin-red .sidebar-menu > li > a {
border-left: 3px solid transparent;
}
.skin-red .sidebar-menu > li:hover > a, .skin-red .sidebar-menu > li.active > a {
color: #fff;
background: #1e282c;
border-left-color: #dd4b39;
}
.skin-red .sidebar-menu > li > .treeview-menu {
margin: 0 1px;
background: #2c3b41;
}
.skin-red .sidebar a {
color: #b8c7ce;
}
.skin-red .sidebar a:hover {
text-decoration: none;
}
.skin-red .treeview-menu > li > a {
color: #8aa4af;
}
.skin-red .treeview-menu > li.active > a, .skin-red .treeview-menu > li > a:hover {
color: #fff;
}
.skin-red .sidebar-form {
border-radius: 3px;
border: 1px solid #374850;
margin: 10px 10px;
}
.skin-red .sidebar-form input[type="text"], .skin-red .sidebar-form .btn {
box-shadow: none;
background-color: #374850;
border: 1px solid transparent;
height: 35px;
-webkit-transition: all .3s ease-in-out;
-o-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.skin-red .sidebar-form input[type="text"] {
color: #666;
border-top-left-radius: 2px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-bottom-left-radius: 2px;
}
.skin-red .sidebar-form input[type="text"]:focus, .skin-red .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
background-color: #fff;
color: #666;
}
.skin-red .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
border-left-color: #fff;
}
.skin-red .sidebar-form .btn {
color: #999;
border-top-left-radius: 0;
border-top-right-radius: 2px;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 0;
}
.skin-red-light .main-header .navbar {
background-color: #dd4b39;
}
.skin-red-light .main-header .navbar .nav > li > a {
color: #fff;
}
.skin-red-light .main-header .navbar .nav > li > a:hover, .skin-red-light .main-header .navbar .nav > li > a:active, .skin-red-light .main-header .navbar .nav > li > a:focus, .skin-red-light .main-header .navbar .nav .open > a, .skin-red-light .main-header .navbar .nav .open > a:hover, .skin-red-light .main-header .navbar .nav .open > a:focus, .skin-red-light .main-header .navbar .nav > .active > a {
background: rgba(0,0,0,0.1);
color: #f6f6f6;
}
.skin-red-light .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-red-light .main-header .navbar .sidebar-toggle:hover {
color: #f6f6f6;
background: rgba(0,0,0,0.1);
}
.skin-red-light .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-red-light .main-header .navbar .sidebar-toggle:hover {
background-color: #d73925;
}
@media (max-width:767px) {
.skin-red-light .main-header .navbar .dropdown-menu li.divider {
background-color: rgba(255,255,255,0.1);
}
.skin-red-light .main-header .navbar .dropdown-menu li a {
color: #fff;
}
.skin-red-light .main-header .navbar .dropdown-menu li a:hover {
background: #d73925;
}
}
.skin-red-light .main-header .logo {
background-color: #dd4b39;
color: #fff;
border-bottom: 0 solid transparent;
}
.skin-red-light .main-header .logo:hover {
background-color: #dc4735;
}
.skin-red-light .main-header li.user-header {
background-color: #dd4b39;
}
.skin-red-light .content-header {
background: transparent;
}
.skin-red-light .wrapper, .skin-red-light .main-sidebar, .skin-red-light .left-side {
background-color: #f9fafc;
}
.skin-red-light .content-wrapper, .skin-red-light .main-footer {
border-left: 1px solid #d2d6de;
}
.skin-red-light .user-panel > .info, .skin-red-light .user-panel > .info > a {
color: #444;
}
.skin-red-light .sidebar-menu > li {
-webkit-transition: border-left-color .3s ease;
-o-transition: border-left-color .3s ease;
transition: border-left-color .3s ease;
}
.skin-red-light .sidebar-menu > li.header {
color: #848484;
background: #f9fafc;
}
.skin-red-light .sidebar-menu > li > a {
border-left: 3px solid transparent;
font-weight: 600;
}
.skin-red-light .sidebar-menu > li:hover > a, .skin-red-light .sidebar-menu > li.active > a {
color: #000;
background: #f4f4f5;
}
.skin-red-light .sidebar-menu > li.active {
border-left-color: #dd4b39;
}
.skin-red-light .sidebar-menu > li.active > a {
font-weight: 600;
}
.skin-red-light .sidebar-menu > li > .treeview-menu {
background: #f4f4f5;
}
.skin-red-light .sidebar a {
color: #444;
}
.skin-red-light .sidebar a:hover {
text-decoration: none;
}
.skin-red-light .treeview-menu > li > a {
color: #777;
}
.skin-red-light .treeview-menu > li.active > a, .skin-red-light .treeview-menu > li > a:hover {
color: #000;
}
.skin-red-light .treeview-menu > li.active > a {
font-weight: 600;
}
.skin-red-light .sidebar-form {
border-radius: 3px;
border: 1px solid #d2d6de;
margin: 10px 10px;
}
.skin-red-light .sidebar-form input[type="text"], .skin-red-light .sidebar-form .btn {
box-shadow: none;
background-color: #fff;
border: 1px solid transparent;
height: 35px;
-webkit-transition: all .3s ease-in-out;
-o-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.skin-red-light .sidebar-form input[type="text"] {
color: #666;
border-top-left-radius: 2px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-bottom-left-radius: 2px;
}
.skin-red-light .sidebar-form input[type="text"]:focus, .skin-red-light .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
background-color: #fff;
color: #666;
}
.skin-red-light .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
border-left-color: #fff;
}
.skin-red-light .sidebar-form .btn {
color: #999;
border-top-left-radius: 0;
border-top-right-radius: 2px;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 0;
}
@media (min-width:768px) {
.skin-red-light.sidebar-mini.sidebar-collapse .sidebar-menu > li > .treeview-menu {
border-left: 1px solid #d2d6de;
}
}
.skin-yellow .main-header .navbar {
background-color: #f39c12;
}
.skin-yellow .main-header .navbar .nav > li > a {
color: #fff;
}
.skin-yellow .main-header .navbar .nav > li > a:hover, .skin-yellow .main-header .navbar .nav > li > a:active, .skin-yellow .main-header .navbar .nav > li > a:focus, .skin-yellow .main-header .navbar .nav .open > a, .skin-yellow .main-header .navbar .nav .open > a:hover, .skin-yellow .main-header .navbar .nav .open > a:focus, .skin-yellow .main-header .navbar .nav > .active > a {
background: rgba(0,0,0,0.1);
color: #f6f6f6;
}
.skin-yellow .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-yellow .main-header .navbar .sidebar-toggle:hover {
color: #f6f6f6;
background: rgba(0,0,0,0.1);
}
.skin-yellow .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-yellow .main-header .navbar .sidebar-toggle:hover {
background-color: #e08e0b;
}
@media (max-width:767px) {
.skin-yellow .main-header .navbar .dropdown-menu li.divider {
background-color: rgba(255,255,255,0.1);
}
.skin-yellow .main-header .navbar .dropdown-menu li a {
color: #fff;
}
.skin-yellow .main-header .navbar .dropdown-menu li a:hover {
background: #e08e0b;
}
}
.skin-yellow .main-header .logo {
background-color: #e08e0b;
color: #fff;
border-bottom: 0 solid transparent;
}
.skin-yellow .main-header .logo:hover {
background-color: #db8b0b;
}
.skin-yellow .main-header li.user-header {
background-color: #f39c12;
}
.skin-yellow .content-header {
background: transparent;
}
.skin-yellow .wrapper, .skin-yellow .main-sidebar, .skin-yellow .left-side {
background-color: #222d32;
}
.skin-yellow .user-panel > .info, .skin-yellow .user-panel > .info > a {
color: #fff;
}
.skin-yellow .sidebar-menu > li.header {
color: #4b646f;
background: #1a2226;
}
.skin-yellow .sidebar-menu > li > a {
border-left: 3px solid transparent;
}
.skin-yellow .sidebar-menu > li:hover > a, .skin-yellow .sidebar-menu > li.active > a {
color: #fff;
background: #1e282c;
border-left-color: #f39c12;
}
.skin-yellow .sidebar-menu > li > .treeview-menu {
margin: 0 1px;
background: #2c3b41;
}
.skin-yellow .sidebar a {
color: #b8c7ce;
}
.skin-yellow .sidebar a:hover {
text-decoration: none;
}
.skin-yellow .treeview-menu > li > a {
color: #8aa4af;
}
.skin-yellow .treeview-menu > li.active > a, .skin-yellow .treeview-menu > li > a:hover {
color: #fff;
}
.skin-yellow .sidebar-form {
border-radius: 3px;
border: 1px solid #374850;
margin: 10px 10px;
}
.skin-yellow .sidebar-form input[type="text"], .skin-yellow .sidebar-form .btn {
box-shadow: none;
background-color: #374850;
border: 1px solid transparent;
height: 35px;
-webkit-transition: all .3s ease-in-out;
-o-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.skin-yellow .sidebar-form input[type="text"] {
color: #666;
border-top-left-radius: 2px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-bottom-left-radius: 2px;
}
.skin-yellow .sidebar-form input[type="text"]:focus, .skin-yellow .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
background-color: #fff;
color: #666;
}
.skin-yellow .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
border-left-color: #fff;
}
.skin-yellow .sidebar-form .btn {
color: #999;
border-top-left-radius: 0;
border-top-right-radius: 2px;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 0;
}
.skin-yellow-light .main-header .navbar {
background-color: #f39c12;
}
.skin-yellow-light .main-header .navbar .nav > li > a {
color: #fff;
}
.skin-yellow-light .main-header .navbar .nav > li > a:hover, .skin-yellow-light .main-header .navbar .nav > li > a:active, .skin-yellow-light .main-header .navbar .nav > li > a:focus, .skin-yellow-light .main-header .navbar .nav .open > a, .skin-yellow-light .main-header .navbar .nav .open > a:hover, .skin-yellow-light .main-header .navbar .nav .open > a:focus, .skin-yellow-light .main-header .navbar .nav > .active > a {
background: rgba(0,0,0,0.1);
color: #f6f6f6;
}
.skin-yellow-light .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-yellow-light .main-header .navbar .sidebar-toggle:hover {
color: #f6f6f6;
background: rgba(0,0,0,0.1);
}
.skin-yellow-light .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-yellow-light .main-header .navbar .sidebar-toggle:hover {
background-color: #e08e0b;
}
@media (max-width:767px) {
.skin-yellow-light .main-header .navbar .dropdown-menu li.divider {
background-color: rgba(255,255,255,0.1);
}
.skin-yellow-light .main-header .navbar .dropdown-menu li a {
color: #fff;
}
.skin-yellow-light .main-header .navbar .dropdown-menu li a:hover {
background: #e08e0b;
}
}
.skin-yellow-light .main-header .logo {
background-color: #f39c12;
color: #fff;
border-bottom: 0 solid transparent;
}
.skin-yellow-light .main-header .logo:hover {
background-color: #f39a0d;
}
.skin-yellow-light .main-header li.user-header {
background-color: #f39c12;
}
.skin-yellow-light .content-header {
background: transparent;
}
.skin-yellow-light .wrapper, .skin-yellow-light .main-sidebar, .skin-yellow-light .left-side {
background-color: #f9fafc;
}
.skin-yellow-light .content-wrapper, .skin-yellow-light .main-footer {
border-left: 1px solid #d2d6de;
}
.skin-yellow-light .user-panel > .info, .skin-yellow-light .user-panel > .info > a {
color: #444;
}
.skin-yellow-light .sidebar-menu > li {
-webkit-transition: border-left-color .3s ease;
-o-transition: border-left-color .3s ease;
transition: border-left-color .3s ease;
}
.skin-yellow-light .sidebar-menu > li.header {
color: #848484;
background: #f9fafc;
}
.skin-yellow-light .sidebar-menu > li > a {
border-left: 3px solid transparent;
font-weight: 600;
}
.skin-yellow-light .sidebar-menu > li:hover > a, .skin-yellow-light .sidebar-menu > li.active > a {
color: #000;
background: #f4f4f5;
}
.skin-yellow-light .sidebar-menu > li.active {
border-left-color: #f39c12;
}
.skin-yellow-light .sidebar-menu > li.active > a {
font-weight: 600;
}
.skin-yellow-light .sidebar-menu > li > .treeview-menu {
background: #f4f4f5;
}
.skin-yellow-light .sidebar a {
color: #444;
}
.skin-yellow-light .sidebar a:hover {
text-decoration: none;
}
.skin-yellow-light .treeview-menu > li > a {
color: #777;
}
.skin-yellow-light .treeview-menu > li.active > a, .skin-yellow-light .treeview-menu > li > a:hover {
color: #000;
}
.skin-yellow-light .treeview-menu > li.active > a {
font-weight: 600;
}
.skin-yellow-light .sidebar-form {
border-radius: 3px;
border: 1px solid #d2d6de;
margin: 10px 10px;
}
.skin-yellow-light .sidebar-form input[type="text"], .skin-yellow-light .sidebar-form .btn {
box-shadow: none;
background-color: #fff;
border: 1px solid transparent;
height: 35px;
-webkit-transition: all .3s ease-in-out;
-o-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.skin-yellow-light .sidebar-form input[type="text"] {
color: #666;
border-top-left-radius: 2px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-bottom-left-radius: 2px;
}
.skin-yellow-light .sidebar-form input[type="text"]:focus, .skin-yellow-light .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
background-color: #fff;
color: #666;
}
.skin-yellow-light .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
border-left-color: #fff;
}
.skin-yellow-light .sidebar-form .btn {
color: #999;
border-top-left-radius: 0;
border-top-right-radius: 2px;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 0;
}
@media (min-width:768px) {
.skin-yellow-light.sidebar-mini.sidebar-collapse .sidebar-menu > li > .treeview-menu {
border-left: 1px solid #d2d6de;
}
}
.skin-purple .main-header .navbar {
background-color: #605ca8;
}
.skin-purple .main-header .navbar .nav > li > a {
color: #fff;
}
.skin-purple .main-header .navbar .nav > li > a:hover, .skin-purple .main-header .navbar .nav > li > a:active, .skin-purple .main-header .navbar .nav > li > a:focus, .skin-purple .main-header .navbar .nav .open > a, .skin-purple .main-header .navbar .nav .open > a:hover, .skin-purple .main-header .navbar .nav .open > a:focus, .skin-purple .main-header .navbar .nav > .active > a {
background: rgba(0,0,0,0.1);
color: #f6f6f6;
}
.skin-purple .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-purple .main-header .navbar .sidebar-toggle:hover {
color: #f6f6f6;
background: rgba(0,0,0,0.1);
}
.skin-purple .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-purple .main-header .navbar .sidebar-toggle:hover {
background-color: #555299;
}
@media (max-width:767px) {
.skin-purple .main-header .navbar .dropdown-menu li.divider {
background-color: rgba(255,255,255,0.1);
}
.skin-purple .main-header .navbar .dropdown-menu li a {
color: #fff;
}
.skin-purple .main-header .navbar .dropdown-menu li a:hover {
background: #555299;
}
}
.skin-purple .main-header .logo {
background-color: #555299;
color: #fff;
border-bottom: 0 solid transparent;
}
.skin-purple .main-header .logo:hover {
background-color: #545096;
}
.skin-purple .main-header li.user-header {
background-color: #605ca8;
}
.skin-purple .content-header {
background: transparent;
}
.skin-purple .wrapper, .skin-purple .main-sidebar, .skin-purple .left-side {
background-color: #222d32;
}
.skin-purple .user-panel > .info, .skin-purple .user-panel > .info > a {
color: #fff;
}
.skin-purple .sidebar-menu > li.header {
color: #4b646f;
background: #1a2226;
}
.skin-purple .sidebar-menu > li > a {
border-left: 3px solid transparent;
}
.skin-purple .sidebar-menu > li:hover > a, .skin-purple .sidebar-menu > li.active > a {
color: #fff;
background: #1e282c;
border-left-color: #605ca8;
}
.skin-purple .sidebar-menu > li > .treeview-menu {
margin: 0 1px;
background: #2c3b41;
}
.skin-purple .sidebar a {
color: #b8c7ce;
}
.skin-purple .sidebar a:hover {
text-decoration: none;
}
.skin-purple .treeview-menu > li > a {
color: #8aa4af;
}
.skin-purple .treeview-menu > li.active > a, .skin-purple .treeview-menu > li > a:hover {
color: #fff;
}
.skin-purple .sidebar-form {
border-radius: 3px;
border: 1px solid #374850;
margin: 10px 10px;
}
.skin-purple .sidebar-form input[type="text"], .skin-purple .sidebar-form .btn {
box-shadow: none;
background-color: #374850;
border: 1px solid transparent;
height: 35px;
-webkit-transition: all .3s ease-in-out;
-o-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.skin-purple .sidebar-form input[type="text"] {
color: #666;
border-top-left-radius: 2px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-bottom-left-radius: 2px;
}
.skin-purple .sidebar-form input[type="text"]:focus, .skin-purple .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
background-color: #fff;
color: #666;
}
.skin-purple .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
border-left-color: #fff;
}
.skin-purple .sidebar-form .btn {
color: #999;
border-top-left-radius: 0;
border-top-right-radius: 2px;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 0;
}
.skin-purple-light .main-header .navbar {
background-color: #605ca8;
}
.skin-purple-light .main-header .navbar .nav > li > a {
color: #fff;
}
.skin-purple-light .main-header .navbar .nav > li > a:hover, .skin-purple-light .main-header .navbar .nav > li > a:active, .skin-purple-light .main-header .navbar .nav > li > a:focus, .skin-purple-light .main-header .navbar .nav .open > a, .skin-purple-light .main-header .navbar .nav .open > a:hover, .skin-purple-light .main-header .navbar .nav .open > a:focus, .skin-purple-light .main-header .navbar .nav > .active > a {
background: rgba(0,0,0,0.1);
color: #f6f6f6;
}
.skin-purple-light .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-purple-light .main-header .navbar .sidebar-toggle:hover {
color: #f6f6f6;
background: rgba(0,0,0,0.1);
}
.skin-purple-light .main-header .navbar .sidebar-toggle {
color: #fff;
}
.skin-purple-light .main-header .navbar .sidebar-toggle:hover {
background-color: #555299;
}
@media (max-width:767px) {
.skin-purple-light .main-header .navbar .dropdown-menu li.divider {
background-color: rgba(255,255,255,0.1);
}
.skin-purple-light .main-header .navbar .dropdown-menu li a {
color: #fff;
}
.skin-purple-light .main-header .navbar .dropdown-menu li a:hover {
background: #555299;
}
}
.skin-purple-light .main-header .logo {
background-color: #605ca8;
color: #fff;
border-bottom: 0 solid transparent;
}
.skin-purple-light .main-header .logo:hover {
background-color: #5d59a6;
}
.skin-purple-light .main-header li.user-header {
background-color: #605ca8;
}
.skin-purple-light .content-header {
background: transparent;
}
.skin-purple-light .wrapper, .skin-purple-light .main-sidebar, .skin-purple-light .left-side {
background-color: #f9fafc;
}
.skin-purple-light .content-wrapper, .skin-purple-light .main-footer {
border-left: 1px solid #d2d6de;
}
.skin-purple-light .user-panel > .info, .skin-purple-light .user-panel > .info > a {
color: #444;
}
.skin-purple-light .sidebar-menu > li {
-webkit-transition: border-left-color .3s ease;
-o-transition: border-left-color .3s ease;
transition: border-left-color .3s ease;
}
.skin-purple-light .sidebar-menu > li.header {
color: #848484;
background: #f9fafc;
}
.skin-purple-light .sidebar-menu > li > a {
border-left: 3px solid transparent;
font-weight: 600;
}
.skin-purple-light .sidebar-menu > li:hover > a, .skin-purple-light .sidebar-menu > li.active > a {
color: #000;
background: #f4f4f5;
}
.skin-purple-light .sidebar-menu > li.active {
border-left-color: #605ca8;
}
.skin-purple-light .sidebar-menu > li.active > a {
font-weight: 600;
}
.skin-purple-light .sidebar-menu > li > .treeview-menu {
background: #f4f4f5;
}
.skin-purple-light .sidebar a {
color: #444;
}
.skin-purple-light .sidebar a:hover {
text-decoration: none;
}
.skin-purple-light .treeview-menu > li > a {
color: #777;
}
.skin-purple-light .treeview-menu > li.active > a, .skin-purple-light .treeview-menu > li > a:hover {
color: #000;
}
.skin-purple-light .treeview-menu > li.active > a {
font-weight: 600;
}
.skin-purple-light .sidebar-form {
border-radius: 3px;
border: 1px solid #d2d6de;
margin: 10px 10px;
}
.skin-purple-light .sidebar-form input[type="text"], .skin-purple-light .sidebar-form .btn {
box-shadow: none;
background-color: #fff;
border: 1px solid transparent;
height: 35px;
-webkit-transition: all .3s ease-in-out;
-o-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.skin-purple-light .sidebar-form input[type="text"] {
color: #666;
border-top-left-radius: 2px;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
border-bottom-left-radius: 2px;
}
.skin-purple-light .sidebar-form input[type="text"]:focus, .skin-purple-light .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
background-color: #fff;
color: #666;
}
.skin-purple-light .sidebar-form input[type="text"]:focus + .input-group-btn .btn {
border-left-color: #fff;
}
.skin-purple-light .sidebar-form .btn {
color: #999;
border-top-left-radius: 0;
border-top-right-radius: 2px;
border-bottom-right-radius: 2px;
border-bottom-left-radius: 0;
}
@media (min-width:768px) {
.skin-purple-light.sidebar-mini.sidebar-collapse .sidebar-menu > li > .treeview-menu {
border-left: 1px solid #d2d6de;
}
}
| {
"content_hash": "f712246f36fb09aa688a6be7f9e0346c",
"timestamp": "",
"source": "github",
"line_count": 1991,
"max_line_length": 443,
"avg_line_length": 27.62230035158212,
"alnum_prop": 0.589970179649429,
"repo_name": "jmcabelloquispe/MiBlogger",
"id": "cab08ad60ce10484f39ccfd3f9003d688edd9a1a",
"size": "54996",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dist/css/skins/_all-skins.m.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "659134"
},
{
"name": "HTML",
"bytes": "3204459"
},
{
"name": "JavaScript",
"bytes": "3024049"
},
{
"name": "PHP",
"bytes": "1684"
}
],
"symlink_target": ""
} |
#include "propertiesdialog.h"
#include "ui_propertiesdialog.h"
#include "changeproperties.h"
#ifndef BUILDINGED_SA
#include "imagelayer.h"
#include "imagelayerpropertiesdialog.h"
#include "mapdocument.h"
#include "objectgroup.h"
#include "objectgrouppropertiesdialog.h"
#endif
#include "propertiesmodel.h"
#include <QShortcut>
#include <QUndoStack>
using namespace Tiled;
using namespace Tiled::Internal;
PropertiesDialog::PropertiesDialog(const QString &kind,
Object *object,
QUndoStack *undoStack,
QWidget *parent):
QDialog(parent),
mUi(new Ui::PropertiesDialog),
mUndoStack(undoStack),
mObject(object),
mKind(kind)
{
mUi->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
mModel = new PropertiesModel(this);
mModel->setProperties(mObject->properties());
mUi->propertiesView->setModel(mModel);
// Delete selected properties when the delete or backspace key is pressed
QShortcut *deleteShortcut = new QShortcut(QKeySequence::Delete,
mUi->propertiesView);
QShortcut *alternativeDeleteShortcut =
new QShortcut(QKeySequence(Qt::Key_Backspace),
mUi->propertiesView);
deleteShortcut->setContext(Qt::WidgetShortcut);
alternativeDeleteShortcut->setContext(Qt::WidgetShortcut);
connect(deleteShortcut, &QShortcut::activated,
this, &PropertiesDialog::deleteSelectedProperties);
connect(alternativeDeleteShortcut, &QShortcut::activated,
this, &PropertiesDialog::deleteSelectedProperties);
setWindowTitle(tr("%1 Properties").arg(mKind));
}
PropertiesDialog::~PropertiesDialog()
{
delete mUi;
}
void PropertiesDialog::accept()
{
// On OSX, the accept button doesn't receive focus when clicked, and
// taking the focus off the currently-being-edited field is what causes
// it to commit its data to the model. This work around makes sure that
// the data being edited gets saved when the user clicks OK.
mUi->propertiesView->setFocus();
const Properties &properties = mModel->properties();
if (mObject && mObject->properties() != properties) {
mUndoStack->push(new ChangeProperties(mKind,
mObject,
properties));
}
QDialog::accept();
}
#ifndef BUILDINGED_SA
void PropertiesDialog::showDialogFor(Layer *layer,
MapDocument *mapDocument,
QWidget *parent)
{
PropertiesDialog *dialog;
if (ObjectGroup *objectGroup = layer->asObjectGroup()) {
dialog = new ObjectGroupPropertiesDialog(mapDocument,
objectGroup,
parent);
} else if (ImageLayer *imageLayer = layer->asImageLayer()) {
dialog = new ImageLayerPropertiesDialog(mapDocument,
imageLayer,
parent);
} else {
dialog = new PropertiesDialog(tr("Layer"),
layer,
mapDocument->undoStack(),
parent);
}
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->exec();
}
#endif // BUILDINGED_SA
void PropertiesDialog::deleteSelectedProperties()
{
QItemSelectionModel *selection = mUi->propertiesView->selectionModel();
const QModelIndexList indices = selection->selectedRows();
if (!indices.isEmpty()) {
mModel->deleteProperties(indices);
selection->select(mUi->propertiesView->currentIndex(),
QItemSelectionModel::ClearAndSelect |
QItemSelectionModel::Rows);
}
}
| {
"content_hash": "d6047447ce2aa44deb3302ee40620065",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 77,
"avg_line_length": 34.582608695652176,
"alnum_prop": 0.5981895901433241,
"repo_name": "timbaker/buildinged",
"id": "4975c61b747c90562efca69a1de88689d9cd6cf2",
"size": "4811",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/tiled/propertiesdialog.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1906"
},
{
"name": "C",
"bytes": "486748"
},
{
"name": "C++",
"bytes": "2336669"
},
{
"name": "CMake",
"bytes": "4591"
},
{
"name": "HTML",
"bytes": "27557"
},
{
"name": "QMake",
"bytes": "15365"
},
{
"name": "Tcl",
"bytes": "4424"
}
],
"symlink_target": ""
} |
using PocDatabase;
using SpentBook.Domain;
using System;
using System.Collections.Generic;
namespace SpentBook.Web
{
internal class PocDatabaseUoW : IUnitOfWork
{
public static PocFile<Schema> _staticPocFile;
private readonly Dictionary<Type, IRepository<IEntity>> repositories;
public class Schema
{
public List<Dashboard> Dashboards { get; set; }
public List<Transaction> Transactions { get; set; }
public List<TransactionImport> TransactionsImports { get; set; }
public List<Bank> Banks { get; set; }
}
public static PocFile<Schema> PocFile
{
get
{
if (_staticPocFile == null)
_staticPocFile = new PocFile<Schema>();
return _staticPocFile;
}
set
{
_staticPocFile = value;
}
}
public PocDatabaseUoW()
{
this.repositories = new Dictionary<Type, IRepository<IEntity>>();
}
public IRepository<Dashboard> Dashboards
{
get
{
IRepository<Dashboard> repository;
if (repositories.ContainsKey(typeof(Dashboard)))
repository = (IRepository<Dashboard>)repositories[typeof(Dashboard)];
else
repository = new PocDatabaseRepository<Dashboard>(PocFile);
return repository;
}
}
public IRepository<Transaction> Transactions
{
get
{
IRepository<Transaction> repository;
if (repositories.ContainsKey(typeof(Transaction)))
repository = (IRepository<Transaction>)repositories[typeof(Transaction)];
else
repository = new PocDatabaseRepository<Transaction>(PocFile);
return repository;
}
}
public IRepository<TransactionImport> TransactionsImports
{
get
{
IRepository<TransactionImport> repository;
if (repositories.ContainsKey(typeof(TransactionImport)))
repository = (IRepository<TransactionImport>)repositories[typeof(TransactionImport)];
else
repository = new PocDatabaseRepository<TransactionImport>(PocFile);
return repository;
}
}
public IRepository<Bank> Banks
{
get
{
IRepository<Bank> repository;
if (repositories.ContainsKey(typeof(Bank)))
repository = (IRepository<Bank>)repositories[typeof(Bank)];
else
repository = new PocDatabaseRepository<Bank>(PocFile);
return repository;
}
}
public void Save()
{
lock(_staticPocFile)
PocFile.Save();
}
}
}
| {
"content_hash": "5558b90884b3602c19c463caa1a262af",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 105,
"avg_line_length": 29.70873786407767,
"alnum_prop": 0.5281045751633987,
"repo_name": "juniorgasparotto/SpentBook",
"id": "de35d415790692520ed09700caed4d9b7c0db8c8",
"size": "3062",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src3/SpentBook.Web/PocDatabase/PocDatabaseUoW.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "104"
},
{
"name": "Batchfile",
"bytes": "7290"
},
{
"name": "C#",
"bytes": "4665722"
},
{
"name": "CSS",
"bytes": "1688137"
},
{
"name": "HTML",
"bytes": "595122"
},
{
"name": "JavaScript",
"bytes": "36825166"
},
{
"name": "PowerShell",
"bytes": "2775"
},
{
"name": "Ruby",
"bytes": "3090"
},
{
"name": "TypeScript",
"bytes": "18735"
}
],
"symlink_target": ""
} |
The current date/time. Use this in conjunction with other date functions.
## ago
The `ago` function returns duration from time.Now in seconds resolution.
```
ago .CreatedAt"
```
returns in `time.Duration` String() format
```
2h34m7s
```
## date
The `date` function formats a date.
Format the date to YEAR-MONTH-DAY:
```
now | date "2006-01-02"
```
Date formatting in Go is a [little bit different](https://pauladamsmith.com/blog/2011/05/go_time.html).
In short, take this as the base date:
```
Mon Jan 2 15:04:05 MST 2006
```
Write it in the format you want. Above, `2006-01-02` is the same date, but
in the format we want.
## dateInZone
Same as `date`, but with a timezone.
```
dateInZone "2006-01-02" (now) "UTC"
```
## duration
Formats a given amount of seconds as a `time.Duration`.
This returns 1m35s
```
duration "95"
```
## durationRound
Rounds a given duration to the most significant unit. Strings and `time.Duration`
gets parsed as a duration, while a `time.Time` is calculated as the duration since.
This return 2h
```
durationRound "2h10m5s"
```
This returns 3mo
```
durationRound "2400h10m5s"
```
## unixEpoch
Returns the seconds since the unix epoch for a `time.Time`.
```
now | unixEpoch
```
## dateModify, mustDateModify
The `dateModify` takes a modification and a date and returns the timestamp.
Subtract an hour and thirty minutes from the current time:
```
now | date_modify "-1.5h"
```
If the modification format is wrong `dateModify` will return the date unmodified. `mustDateModify` will return an error otherwise.
## htmlDate
The `htmlDate` function formats a date for inserting into an HTML date picker
input field.
```
now | htmlDate
```
## htmlDateInZone
Same as htmlDate, but with a timezone.
```
htmlDateInZone (now) "UTC"
```
## toDate, mustToDate
`toDate` converts a string to a date. The first argument is the date layout and
the second the date string. If the string can't be convert it returns the zero
value.
`mustToDate` will return an error in case the string cannot be converted.
This is useful when you want to convert a string date to another format
(using pipe). The example below converts "2017-12-31" to "31/12/2017".
```
toDate "2006-01-02" "2017-12-31" | date "02/01/2006"
```
| {
"content_hash": "980b30cdeb98f2938627ff4b68adad88",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 130,
"avg_line_length": 18.565573770491802,
"alnum_prop": 0.7156732891832229,
"repo_name": "Masterminds/sprig",
"id": "9f02651e868f86ea40cd736c098d7798c9f1c035",
"size": "2291",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/date.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "133037"
},
{
"name": "Makefile",
"bytes": "179"
}
],
"symlink_target": ""
} |
package com.azure.tools.apiview.processor.model.maven;
public class Gav implements MavenGAV {
private String groupId;
private String artifactId;
private String version;
public Gav(final String groupId, final String artifactId, final String version) {
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
}
public String getGroupId() {
return groupId;
}
public String getArtifactId() {
return artifactId;
}
public String getVersion() {
return version;
}
}
| {
"content_hash": "5b4ff041b0179df63b00e290dd0099bc",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 85,
"avg_line_length": 23.08,
"alnum_prop": 0.6551126516464472,
"repo_name": "tg-msft/azure-sdk-tools",
"id": "a963c6a5022119b6b506472b7cdaa26dc6f8d35b",
"size": "577",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/java/apiview-java-processor/src/main/java/com/azure/tools/apiview/processor/model/maven/Gav.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "816"
},
{
"name": "C#",
"bytes": "1358017"
},
{
"name": "CSS",
"bytes": "6089"
},
{
"name": "Dockerfile",
"bytes": "868"
},
{
"name": "Go",
"bytes": "35301"
},
{
"name": "HTML",
"bytes": "59599"
},
{
"name": "Java",
"bytes": "187077"
},
{
"name": "JavaScript",
"bytes": "9361"
},
{
"name": "PowerShell",
"bytes": "312580"
},
{
"name": "Python",
"bytes": "187175"
},
{
"name": "SCSS",
"bytes": "9152"
},
{
"name": "Shell",
"bytes": "8139"
},
{
"name": "TypeScript",
"bytes": "21823"
}
],
"symlink_target": ""
} |
<?php
namespace TwoDojo\ModuleManager\Support;
class ModuleDescriptor implements \ArrayAccess
{
protected $attributes = [];
public function __construct(array $attributes = [])
{
foreach ($attributes as $key => $value) {
$this->setAttribute($key, $value);
}
}
public function hasAttribute($key)
{
return array_has($this->attributes, $key);
}
public function getAttribute($key, $default = null)
{
return array_get($this->attributes, $key, $default);
}
public function getAttributes()
{
return $this->attributes;
}
public function setAttribute($key, $value)
{
$this->attributes = array_set($this->attributes, $key, $value);
}
public function __set($key, $value)
{
$this->setAttribute($key, $value);
}
public function __get($name)
{
return $this->getAttribute($name);
}
/**
* @inheritdoc
*/
public function offsetExists($offset)
{
return !is_null($this->getAttribute($offset));
}
/**
* @inheritdoc
*/
public function offsetGet($offset)
{
return $this->getAttribute($offset);
}
/**
* @inheritdoc
*/
public function offsetSet($offset, $value)
{
$this->setAttribute($offset, $value);
}
/**
* @inheritdoc
*/
public function offsetUnset($offset)
{
unset($this->attributes[$offset]);
}
}
| {
"content_hash": "75b1b75107507ec7730dab99b7151422",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 71,
"avg_line_length": 19.363636363636363,
"alnum_prop": 0.5553319919517102,
"repo_name": "2dojo/module_manager",
"id": "ce2f74b00c73011b27cd70e3e3cc80b82e604675",
"size": "1491",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Support/ModuleDescriptor.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "71474"
}
],
"symlink_target": ""
} |
This is the code that runs on the BeagleBone Black to control the ultrabot.
## Overview
Essentially this code establishes socket (UDP) connection with another device
(BASE) and waits for commands. The commands are either of the form of
directives or queries. An example directive is setting the PWM values of the
motors. An example query is getting IR sensor values.
## Installation
Clone the repo into home directory:
cd ~
git clone https://github.com/o-botics/quickbot_bbb.git
## Running
Check IP address of BASE and ROBOT (run command on both systems and look for IP
address):
ifconfig
Example output from BBB:
ra0 Link encap:Ethernet HWaddr 00:0C:43:00:14:F8
inet addr:192.168.1.101 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::20c:43ff:fe00:14f8/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:315687 errors:1113 dropped:1 overruns:0 frame:0
TX packets:12321 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:66840454 (63.7 MiB) TX bytes:1878384 (1.7 MiB)
Here the IP address for the robot is 192.168.1.101. Let's assume the IP address
for the BASE is 192.168.1.100.
Change into working directory:
$ cd ~/quickbot_bbb
Quick run with given ips:
$ python run.py -i 192.168.1.100 -r 192.168.1.101
All commands:
$ python run.py --help
usage: run.py [-h] [--ip IP] [--rip RIP] [--rtype RTYPE]
optional arguments:
-h, --help show this help message and exit
--ip IP, -i IP Computer ip (base ip)
--rip RIP, -r RIP BBB ip (robot ip)
--rtype RTYPE, -t RTYPE
Type of robot (quick|ultra)
## Command Set
* Check that the ultrabot is up and running:
* Command
"$CHECK*\n"
* Response
"Hello from [Quick|Ultra]Bot\n"
* Get PWM values:
* Command
"$PWM?*\n"
* Example response
"[50, -50]\n"
* Set PWM values:
* Command
"$PWM=[-100,100]*\n"
* Get IR values:
* Command
"$IRVAL?*\n"
* Example response
"[800, 810, 820, 830, 840]\n"
* Get Ultra values:
* Command
"$ULTRAVAL?*\n"
* Example response
"[80.0, 251.0, 234.1, 12.1, 21.3]\n"
* Get encoder position:
* Command
"$ENVAL?*\n"
* Example response
"[200, -200]\n"
* Get encoder velocity (tick velocity -- 16 ticks per rotation):
* Command
"$ENVEL?*\n"
* Example response
"[20.0, -20.0]\n"
* Reset encoder position to zero:
* Command
"$RESET*\n"
* End program
* Command:
"$END*\n"
| {
"content_hash": "e7e0eb7b45d88d882cbe7483af64f0f3",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 79,
"avg_line_length": 19.69465648854962,
"alnum_prop": 0.637984496124031,
"repo_name": "kohloderso/quickbot_bbb",
"id": "e43b55ec8f2dcdc075fd233817043856ef4b1687",
"size": "2595",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "44081"
},
{
"name": "Shell",
"bytes": "278"
}
],
"symlink_target": ""
} |
/* */
var convert = require('./convert'),
func = convert('isInteger', require('../isInteger'), require('./_falseOptions'));
func.placeholder = require('./placeholder');
module.exports = func;
| {
"content_hash": "47dba8d99eb090f5668e9e254aa49e83",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 85,
"avg_line_length": 39.4,
"alnum_prop": 0.6548223350253807,
"repo_name": "onlabsorg/olowc",
"id": "2781ff7aad7ab4adc562407133bc87bd8b85d0fe",
"size": "197",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "jspm_packages/npm/lodash@4.17.4/fp/isInteger.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2128"
},
{
"name": "JavaScript",
"bytes": "2069038"
},
{
"name": "Makefile",
"bytes": "188"
},
{
"name": "OCaml",
"bytes": "485"
},
{
"name": "Shell",
"bytes": "973"
}
],
"symlink_target": ""
} |
/* global io */
import { communicator, eventHandler } from 'lib/decorators/socket';
@communicator
class DesktopApp {
beforeRegister() {
this.is = 'ai-app';
}
attached() {
this.async(() => {
this.run();
});
}
run() {
this.socket = io();
this._lobby = this.querySelector('ai-lobby');
this._lobby.socket = this._socket;
this._roster = this.querySelector('ai-roster');
this._roster.socket = this._socket;
this._table = this.querySelector('ai-table');
this._table.socket = this._socket;
}
@eventHandler('game:start')
_handleGameStart() {
this._lobby.remove();
this.querySelector('.game-area').dataset.state = 'table';
this._table.show();
}
}
Polymer(DesktopApp);
| {
"content_hash": "9643e1dfbcebdd913f607d5acfa57fde",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 67,
"avg_line_length": 20.583333333333332,
"alnum_prop": 0.6099865047233468,
"repo_name": "Meesayen/all-in",
"id": "7feb195b03d8459bc73eff16821d7e606063384e",
"size": "741",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/client/components/desktop/ai-app.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "22888"
},
{
"name": "HTML",
"bytes": "4754"
},
{
"name": "JavaScript",
"bytes": "43388"
}
],
"symlink_target": ""
} |
export default {
setChanges(source, map, change, isShallow, path, parent, parentKey) {
if(!source) {
source = {};
}
if(!map) {
map = {};
}
let changedProps = {};
for(let prop in map) {
const isSourceObject = typeof source[prop] === 'object' && source[prop] !== null;
const isMapObject = typeof map[prop] === 'object' && map[prop] !== null;
let isDifferent = false;
if(isSourceObject || isMapObject) {
const flatSource = source[prop] ? JSON.stringify(source[prop]) : '';
const flatMap = map[prop] ? JSON.stringify(map[prop]) : '';
isDifferent = flatSource !== flatMap;
if(isDifferent) {
if(isShallow) {
changedProps[prop] = this.getChangedAsObject(source[prop], map[prop]);
}
else {
const propPath = path ? path + '.' + prop : prop;
changedProps[propPath] = this.getChangedAsObject(source[prop], map[prop]);
let changedObject = this.setChanges(source[prop], map[prop], isSourceObject && change, isShallow, propPath, source, prop);
if(Object.keys(changedObject).length > 0) {
Object.assign(changedProps, changedObject);
}
}
}
}
else {
isDifferent = source[prop] != map[prop];
if(isDifferent) {
const propPath = path ? path + '.' + prop : prop;
const clonedNewValue = map[prop] ? JSON.parse(JSON.stringify(map[prop])) : map[prop];
const clonedOldValue = source[prop] ? JSON.parse(JSON.stringify(source[prop])) : source[prop];
changedProps[propPath] = this.getChangedAsObject(clonedOldValue, clonedNewValue);
}
}
if(isDifferent && change){
if(parent) {
if(!parent[parentKey]) {
parent[parentKey] = map;
}
parent[parentKey][prop] = map[prop];
}
else {
source[prop] = map[prop];
}
}
}
return changedProps;
},
getChangedAsObject(oldValue, newValue) {
return {
oldValue: typeof oldValue !== 'undefined' ? JSON.parse(JSON.stringify(oldValue)) : null,
newValue: typeof newValue !== 'undefined' ? JSON.parse(JSON.stringify(newValue)) : null
};
}
}; | {
"content_hash": "c093d9b7940ccc65db1f56aeba12b17a",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 146,
"avg_line_length": 42.5,
"alnum_prop": 0.47352941176470587,
"repo_name": "sepcon-rnd/sepcon",
"id": "64cc8c41874c271a1eae83091359bf1822d02448",
"size": "2720",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/shared/utils.changes.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "3637"
},
{
"name": "JavaScript",
"bytes": "240320"
}
],
"symlink_target": ""
} |
package com.rhcloud.igorbotian.rsskit.rest.facebook;
import com.fasterxml.jackson.databind.JsonNode;
import com.rhcloud.igorbotian.rsskit.rest.EntityParser;
import com.rhcloud.igorbotian.rsskit.rest.RestParseException;
import java.util.Objects;
/**
* @author Igor Botian
*/
public class FacebookProfile {
private static final EntityParser<FacebookProfile> PARSER = new FacebookProfileParser();
public final String id;
public final String name;
public final String link;
public FacebookProfile(String id, String name, String link) {
this.id = Objects.requireNonNull(id);
this.name = Objects.requireNonNull(name);
this.link = Objects.requireNonNull(link);
}
public static FacebookProfile parse(JsonNode json) throws RestParseException {
Objects.requireNonNull(json);
return PARSER.parse(json);
}
private static class FacebookProfileParser extends EntityParser<FacebookProfile> {
@Override
public FacebookProfile parse(JsonNode json) throws RestParseException {
Objects.requireNonNull(json);
String id = getAttribute(json, "id").asText();
String name = getAttribute(json, "name").asText();
String link = "https://www.facebook.com/" + id;
return new FacebookProfile(id, name, link);
}
}
}
| {
"content_hash": "f4e9b2e834047d90089bbefa94f3de40",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 92,
"avg_line_length": 30.954545454545453,
"alnum_prop": 0.6945668135095447,
"repo_name": "igorbotian/rsskit",
"id": "e0b7d44f41dd4008d36e4aea83e9638669adb856",
"size": "1362",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/rhcloud/igorbotian/rsskit/rest/facebook/FacebookProfile.java",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Java",
"bytes": "1022"
}
],
"symlink_target": ""
} |
<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">
<ogc:ClassifiedAs>
<ogc:TypeName>csw:Record</ogc:TypeName>
<ogc:ClassificationScheme>GetClass</ogc:ClassificationScheme>
<ogc:ClassificationNode>/GeoClass/NorthAmerica/%/Ontario</ogc:ClassificationNode>
</ogc:ClassifiedAs>
</ogc:Filter>
| {
"content_hash": "b0f8f722173af25cd7c4871052378c8e",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 87,
"avg_line_length": 44.714285714285715,
"alnum_prop": 0.7348242811501597,
"repo_name": "highsource/ogc-schemas",
"id": "9fdcaef0c63b8305ff3661f8f74206e2b0dcb7a1",
"size": "313",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "schemas/src/main/resources/ogc/csw/2.0.2/examples/Clause_6.2.3_Example.xml",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "6093"
},
{
"name": "HTML",
"bytes": "669"
},
{
"name": "Java",
"bytes": "43533"
},
{
"name": "JavaScript",
"bytes": "4700986"
},
{
"name": "Shell",
"bytes": "182"
},
{
"name": "XSLT",
"bytes": "1681938"
}
],
"symlink_target": ""
} |
from ..constructs import Instruction
class Trie(object):
BUCKET_LEN = 1
BUCKET_MASK = (2**BUCKET_LEN)-1
def __init__(self):
self.children = [None for _ in range(2**Trie.BUCKET_LEN)]
self.value = None
def __setitem__(self, key, value):
assert type(value) == Instruction
node = self
for bucket in [(key >> i) & Trie.BUCKET_MASK for \
i in range(64, -1, -Trie.BUCKET_LEN)]:
if not node.children[bucket]:
node.children[bucket] = Trie()
node = node.children[bucket]
node.value = value
def __getitem__(self, item):
if type(item) in (int, long):
node = self
for bucket in [(item >> i) & Trie.BUCKET_MASK for \
i in range(64, -1, -Trie.BUCKET_LEN)]:
if not node.children[bucket]:
raise KeyError()
node = node.children[bucket]
return node.value
elif type(item) == slice:
start = item.start
stop = item.stop
if start is None:
start = 0
if stop is None:
# 128 bits max address. Seems big enough for practical purposes
stop = 0xFFFFFFFFFFFFFFFF
uncommon_bits = (stop ^ start).bit_length()
node = self
for bucket in [(start >> i) & Trie.BUCKET_MASK for \
i in range(64, uncommon_bits, -Trie.BUCKET_LEN)]:
if not node.children[bucket]:
raise KeyError()
node = node.children[bucket]
return [v for v in iter(node) if start <= v.address < stop][::item.step]
def __iter__(self):
if self.value:
yield self.value
for child in filter(None, self.children):
for v in child:
yield v
def __contains__(self, item):
node = self
for bucket in [(item >> i) & Trie.BUCKET_MASK for \
i in range(64, -1, -Trie.BUCKET_LEN)]:
if not node.children[bucket]:
return False
node = node.children[bucket]
return True
def __delitem__(self, key):
node = self
for bucket in [(key >> i) & Trie.BUCKET_MASK for \
i in range(64, -1, -Trie.BUCKET_LEN)]:
if not node.children[bucket]:
raise KeyError()
node = node.children[bucket]
node.value = None
| {
"content_hash": "a3f78b9e1aa61bfdd526ac45f51bb8b6",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 84,
"avg_line_length": 33.421052631578945,
"alnum_prop": 0.494488188976378,
"repo_name": "isislab/dispatch",
"id": "e6de4d7db0a9316b047ba425c2692a42d9442369",
"size": "2540",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dispatch/util/trie.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2241"
},
{
"name": "Python",
"bytes": "112692"
}
],
"symlink_target": ""
} |
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.10.0-master-dd11583
*/md-toolbar.md-THEME_NAME-theme{background-color:'{{primary-color}}';color:'{{primary-contrast}}'}md-toolbar.md-THEME_NAME-theme .md-button,md-toolbar.md-THEME_NAME-theme md-icon{color:'{{primary-contrast}}'}md-toolbar.md-THEME_NAME-theme.md-accent{background-color:'{{accent-color}}';color:'{{accent-contrast}}'}md-toolbar.md-THEME_NAME-theme.md-warn{background-color:'{{warn-color}}';color:'{{warn-contrast}}'} | {
"content_hash": "1eb2988eda1271bbbce875e34574b61b",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 414,
"avg_line_length": 87.66666666666667,
"alnum_prop": 0.7300380228136882,
"repo_name": "SvitlanaShepitsena/svet-newspaper-material",
"id": "53ca55dacecc06d845715b12e56768e6dca97e24",
"size": "526",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/bower_components/angular-material/modules/js/toolbar/toolbar-default-theme.min.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "356"
},
{
"name": "CSS",
"bytes": "77022"
},
{
"name": "HTML",
"bytes": "4591633"
},
{
"name": "JavaScript",
"bytes": "623424"
},
{
"name": "Objective-J",
"bytes": "148"
},
{
"name": "Shell",
"bytes": "1361"
},
{
"name": "Smarty",
"bytes": "989"
}
],
"symlink_target": ""
} |
package br.com.doe.utils;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Created by heitornascimento on 4/11/16.
*/
public class PropertiesHelper {
private static final String DOE_WS_PROPERTIES = "doe_ws.properties";
private static final String LOGIN_API_ENDPOINT_URL = "loginApiEndpointUrl";
private static final String REGISTER_API_ENDPOINT_URL = "registerApiEndpointUrl";
private static final String INSTITUTION_API_ENDPOINT = "institutionsApiEndpoint";
private static final String BASE_URL = "ApiEnpointUrl";
/**
* Load the URL login in properties file.
**/
public static String readLoginUrlProperties(Context ctx) throws IOException {
Properties properties = new Properties();
Resources resource = ctx.getResources();
AssetManager assetManager = resource.getAssets();
InputStream is = assetManager.open(DOE_WS_PROPERTIES);
properties.load(is);
String loginApiUrl = properties.getProperty(LOGIN_API_ENDPOINT_URL);
return loginApiUrl;
}
/**
* Load the URL login in properties file.
**/
public static String readRegisterUrlProperties(Context ctx) throws IOException {
Properties properties = new Properties();
Resources resource = ctx.getResources();
AssetManager assetManager = resource.getAssets();
InputStream is = assetManager.open(DOE_WS_PROPERTIES);
properties.load(is);
String registerUrl = properties.getProperty(REGISTER_API_ENDPOINT_URL);
return registerUrl;
}
/**
* Load the URL login in properties file.
**/
public static String readInstituionsURLProperties(Context ctx) throws IOException {
Properties properties = new Properties();
Resources resource = ctx.getResources();
AssetManager assetManager = resource.getAssets();
InputStream is = assetManager.open(DOE_WS_PROPERTIES);
properties.load(is);
String registerUrl = properties.getProperty(INSTITUTION_API_ENDPOINT);
return registerUrl;
}
/**
* Load the base URL in properties file.
**/
public static String readbaseURLProperties(Context ctx) throws IOException {
Properties properties = new Properties();
Resources resource = ctx.getResources();
AssetManager assetManager = resource.getAssets();
InputStream is = assetManager.open(DOE_WS_PROPERTIES);
properties.load(is);
String baseUrl = properties.getProperty(BASE_URL);
return baseUrl;
}
}
| {
"content_hash": "2a4555e2d08a7517678c6df6300539b3",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 87,
"avg_line_length": 34.379746835443036,
"alnum_prop": 0.6940353460972017,
"repo_name": "heitornascimento/doe-recife",
"id": "00ef500409d5f8fa1e5d827bb78ca5a3a29f9892",
"size": "2716",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doe-recife/app/src/main/java/br/com/doe/utils/PropertiesHelper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "191535"
}
],
"symlink_target": ""
} |
/**
* @overview A home for the odds and ends that other objects dont want.
* @license Apache License, Version 2.0
* @property {utils.PublicInterface} - available public methods
*/
/**
* ** Utilities Object **
*
* @namespace utils
* @property {utils.PublicInterface} - available public methods
*/
function utils (spreadsheet, tz) {
var spreadsheet;
var ss = spreadsheet || Config.spreadsheet();
var tz = tz || ss.getSpreadsheetTimeZone();
/**
* ---
* Get the most common occurrence and count of an element in an array.
* Also, check if it is the [2/3rd] majority of occurrences.
*
* @memberof! utils#
* @param {Array} arr - the array to check
* @return {Array}
* ```
* [0][i] most common elements
* [1] count
* [2] is_majority
* ```
*/
function getMostCommon (arr) {
var arr = arr || [];
var high_count;
// Return if only one value
if (!arr.length) { return [[arr], 1] }
// Reduce the elements into key:value object
var count = arr.reduce(function (r, k) {
r[k] ? r[k]++ : r[k] = 1;
return r;
}, {});
// Return the key(s) with the highest occurrence
var common = Object.keys(count).reduce(function (r, k, i) {
if (!i || count[k] > count[r[0]]) {
high_count = count[k];
return [(parseInt(k) || k)];
}
// Add additional keys equal to highest occurrence
if (count[k] === count[r[0]]) { r.push((parseInt(k) || k)) }
return r;
}, []);
// Check if most common element is also 2/3rd majority
var is_majority = (arr.length >= 3)
? (Math.floor(.67 * arr.length) <= high_count)
: false;
return [common, high_count, is_majority];
}
/*******************************************************************************
* utils().date *
*******************************************************************************/
/**
* ---
* Formats date objects into strings or numbers
*
* @memberof! utils#
* @param {String=} - the format type
* @param {Array|Date=} - the date object or array of date objects to format
* @return {Number[]|String[][]}
*/
function formatDateTime () {
var a = arguments.length
? (typeof arguments[1] != 'undefined'
? (arguments[1].length ? arguments[1] : [arguments[1]]) : [new Date()])
: [new Date()];
var df = {
logs: "dd-MMM-yy 'at' h:mm:s a",
short: "EEE MMM d",
split: ["EEEE, MMMM dd","h:mm a"],
yearday: "D"
};
var format = a.map(function (e) {
switch (true) {
// Log email timestamp
case this == "logs":
return Utilities.formatDate(new Date(e), tz, df.logs);
break;
// Format into short display [Dayname shortMonth daynum]
case this == "short":
return Utilities.formatDate(new Date(e), tz, df.short);
break;
// Format and splits into [date, time]
case this == "split":
return [Utilities.formatDate(new Date(e), tz, df.split[0]),
Utilities.formatDate(new Date(e), tz, df.split[1])];
break;
// Day number of the week: `1 = Monday...7 =Sunday`
case this == "weekday":
return e.getDay();
break;
// Day number of the year
case this == "yearday":
return Number(Utilities.formatDate(new Date(e), tz, df.yearday));
break;
// Current datetime
default:
return new Date(e);
}
}, arguments[0]);
return format;
}
/**
* ---
* Combines date and time to create string date with time.
*
* @memberof! utils#
* @param {String} date - string month and day
* @param {String} time - string time
* @param {Date} today - todays date
* @return {String} _"MMM dd h:mm a"_ || "M/d/y h:mm a"
*/
function rawDateTime (date, time, today) {
const months = ["jan", "feb", "mar", "apr", "may", "jun",
"jul","aug", "sep", "oct", "nov", "dec"];
var full_gamedate;
try {
if (typeof date != "undefined") {
var today_month = today.getMonth();
var today_year = today.getFullYear();
var gamedate = date + " " + time;
// Split the date into its parts
var gd_parts = gamedate.slice(4).split(" ");
var game_month = months.indexOf(gd_parts[0].toLowerCase());
// If today is Oct-Dec - set new year for games scheduled Jan-Mar
if (today_month >= 9 && game_month <= 3) {
var game_year = today_year + 1;
} else {
throw {message: "utils().rawDateTime(): Dates not within range"}
}
full_gamedate = (game_month +1 ) + "/" + gd_parts[1] + "/" + game_year
+ " " + gd_parts[2] + " " + gd_parts[3];
}
}
catch (e) {
// Run the old dateTime if the aboved erred
var clean_date = date.replace(/-/, " ");
full_gamedate = clean_date + " " + time;
}
finally {
return full_gamedate;
}
}
/*******************************************************************************
* utils().form *
*******************************************************************************/
/**
* ---
* Fetches and returns a super-duper fun and inspiring quote.
*
* @memberof! utils#
* @cache - 1.5 hours to prevent exceeding hourly quota
* @return {Struct}
* ```
* {
* "author": author,
* "quote": quote,
* "source": source
* }
* ```
*/
function fetchQuoteOfTheDay () {
var cache = (function () {
if (Config.debug) { return CacheService.getScriptCache() }
else { return CacheService.getDocumentCache() }
})();
if (!cache.get("author") || !cache.get("quote")) {
var form_msg = UrlFetchApp.fetch("http://quotes.rest/qod?category=inspire");
var json = JSON.parse(form_msg);
var quote = json.contents.quotes[0].quote;
var author = json.contents.quotes[0].author;
cache.put("quote", quote, 5400);
cache.put("author", author, 5400);
}
var author = cache.get("author");
var quote = cache.get("quote");
var source = '\n\n\n[powered by quotes from theysaidso.com]';
var message = {
"author": author,
"quote": quote,
"source": source
};
return message;
}
/*******************************************************************************
* utils().script *
*******************************************************************************/
/**
* ---
* Installs the triggers for the spreadsheet.
*
* | Trigger | |
* |--------------|---|
* | onFormSubmit | [onFormSubmit]{@link onFormSubmit}
* | onEdit | [onSheetEdit]{@link onSheetEdit}
* | Time-Based | [onTimeTrigger]{@link onDailyTrigger} (6am sheet timezone)
*
* @memberof! utils#
*/
function addTriggers () {
// Clear previously installed script triggers before re-installing them
clearTriggers();
ScriptApp.newTrigger("onFormSubmit")
.forSpreadsheet(ss)
.onFormSubmit()
.create();
ScriptApp.newTrigger("onSheetEdit")
.forSpreadsheet(ss)
.onEdit()
.create();
ScriptApp.newTrigger("onDailyTrigger")
.timeBased()
.atHour(6)
.everyDays(1)
.inTimezone(tz)
.create();
}
/**
* ---
* Checks for major or minor updates that may require
* script property/setting updates. Runs the update
* and sets the new version in storage.
*
* @memberof! utils#
*/
function checkUpdateVersion () {
var current_ver = parseFloat(storage().get("version")) || "0.0";
// Check for major or minor version changes
if (current_ver < parseFloat(Config.version)) {
try {
// Run updates
_updateScript();
SpreadsheetApp.flush();
// Set the new version in storage
storage().set("version", Config.version);
} catch (e) {}
}
}
/**
* ---
* Delete the spreadsheets installed triggers.
*
* @memberof! utils#
*/
function clearTriggers () {
var installed = ScriptApp.getUserTriggers(ss);
if (installed.length != 0) {
installed.forEach(function (e) { ScriptApp.deleteTrigger(e) });
}
}
/**
* ---
* Updates the script when major or minor script changes require it
*
* @memberof! utils#
*/
function _updateScript () {
// Updates for 1.3 - update NamedRanges
sheetService().update.namedRanges();
// Apply pending Spreadsheet changes
SpreadsheetApp.flush();
}
/**
* ---
* Invokes a function, performing up to 5 retries with exponential backoff.
* Retries with delays of approximately 1, 2, 4, 8 then 16 seconds for a total of
* about 32 seconds before it gives up and rethrows the last error.
* See: https://developers.google.com/google-apps/documents-list/#implementing_exponential_backoff
* <br>Author: peter.herrmann@gmail.com (Peter Herrmann)
<h3>Examples:</h3>
<pre>//Calls an anonymous function that concatenates a greeting with the current Apps user's email
var example1 = GASRetry.call(function(){return "Hello, " + Session.getActiveUser().getEmail();});
</pre><pre>//Calls an existing function
var example2 = GASRetry.call(myFunction);
</pre><pre>//Calls an anonymous function that calls an existing function with an argument
var example3 = GASRetry.call(function(){myFunction("something")});
</pre><pre>//Calls an anonymous function that invokes DocsList.setTrashed on myFile and logs retries with the Logger.log function.
var example4 = GASRetry.call(function(){myFile.setTrashed(true)}, Logger.log);
</pre>
*
* @memberof! utils#
* @param {Function} func The anonymous or named function to call.
* @param {Function} optLoggerFunction Optionally, you can pass a function that will be used to log
to in the case of a retry. For example, Logger.log (no parentheses) will work.
* @return {*} The value returned by the called function.
*/
function gasRetry (func, optLoggerFunction) {
for (var n = 0; n < 6; n++) {
try {
return func();
} catch (e) {
if (optLoggerFunction) { optLoggerFunction("GASRetry " + n + ": " + e); }
if (n == 5) {
throw e;
}
Utilities.sleep((Math.pow(2,n)*1000) + (Math.round(Math.random() * 1000)));
}
}
}
/**
* @typedef {utils} utils.PublicInterface
* @property {Function} getMostCommon - [utils().getMostCommon()]{@link utils#getMostCommon}
* @property {Function} formatDateTime - [utils().date.format()]{@link utils#formatDateTime}
* @property {Function} rawDateTime - [utils().date.makeDateTime()]{@link utils#rawDateTime}
* @property {Function} fetchQuoteOfTheDay - [utils().form.fetchQuote()]{@link utils#fetchQuoteOfTheDay}
* @property {Function} clearTriggers - [utils().script.clean.triggers()]{@link utils#clearTriggers}
* @property {Function} addTriggers - [utils().script.install.triggers()]{@link utils#addTriggers}
* @property {Function} gasRetry - [utils().script.retry()]{@link utils#gasRetry}
* @property {Function} checkUpdateVersion - [utils().script.update()]{@link utils#checkUpdateVersion}
*/
return {
getMostCommon: getMostCommon,
date: {
format: formatDateTime,
makeDateTime: rawDateTime
},
form: {
fetchQuote: fetchQuoteOfTheDay
},
script: {
clean: {
triggers: clearTriggers
},
install: {
triggers: addTriggers
},
retry: gasRetry,
update: checkUpdateVersion
}
}
}
| {
"content_hash": "f32bf65ca41cf09d6b48ed8a15c4ca6a",
"timestamp": "",
"source": "github",
"line_count": 375,
"max_line_length": 133,
"avg_line_length": 31.842666666666666,
"alnum_prop": 0.5480278033665522,
"repo_name": "random-parts/Team-Sports-RSVP",
"id": "9ee9ca5f14f5ebf9676da4975511892cd20d1698",
"size": "13236",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/tools/Utils.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "29272"
},
{
"name": "JavaScript",
"bytes": "167160"
}
],
"symlink_target": ""
} |
'use strict';
try {
angular.module('uiPetri');
} catch (e) {
angular.module('uiPetri', []);
}
angular.module('uiPetri').run(['$templateCache', function ($templateCache) {
'use strict';
$templateCache.put('views/activityPanel.html',
"<div class=\"box\" style=\"height: 40px;width: 150px;\" >\n" +
" <div ng-repeat=\"state in states | orderBy : 'state'\">\n" +
" <button style=\"float: left; background: transparent;border: none;margin: 1px;padding-bottom: 1;padding-top: 1px\">\n" +
" <img height=\"35px\" width=\"35ps\" relative-src=\"{{ state }}\" >\n" +
" </button>\n" +
" </div>\n" +
"</div>\n"
);
}]); | {
"content_hash": "10e6ea1a14d651357e0dbbb2402eec61",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 134,
"avg_line_length": 32.42857142857143,
"alnum_prop": 0.5550660792951542,
"repo_name": "wix/petri",
"id": "0b950527d8a66997f25e3107089f394d78ad7f86",
"size": "681",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "petri-ui-statics/statics/views/activityPanel.html.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "166973"
},
{
"name": "HTML",
"bytes": "52557"
},
{
"name": "Java",
"bytes": "692422"
},
{
"name": "JavaScript",
"bytes": "1004602"
},
{
"name": "Scala",
"bytes": "218807"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Lex.Db
{
/// <summary>
/// Pure POCO data entity
/// </summary>
public class MyData
{
public int Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public int IntField { get; set; }
public int? IntNField { get; set; }
public long LongField { get; set; }
public long? LongNField { get; set; }
public double DoubleField { get; set; }
public double? DoubleNField { get; set; }
public decimal DecimalField { get; set; }
public decimal? DecimalNField { get; set; }
public float FloatField { get; set; }
public float? FloatNField { get; set; }
public bool BoolField { get; set; }
public bool? BoolNField { get; set; }
public DateTime DateTimeField { get; set; }
public DateTime? DateTimeNField { get; set; }
public DateTimeOffset DateTimeOffsetField { get; set; }
public DateTimeOffset? DateTimeOffsetNField { get; set; }
public TimeSpan TimeSpanField { get; set; }
public TimeSpan? TimeSpanNField { get; set; }
public Guid GuidField { get; set; }
public Guid? GuidNField { get; set; }
public List<int> ListField { get; set; }
#if !SILVERLIGHT || WINDOWS_PHONE
public SortedSet<int> SortedSetField { get; set; }
#endif
public Dictionary<string, int> DictField { get; set; }
public ObservableCollection<int> CollectionField { get; set; }
public TestEnum EnumField { get; set; }
public TestEnum? EnumNField { get; set; }
public byte[] BlobField;
}
/// <summary>
/// Test enumeration for serialization roundtrip
/// </summary>
public enum TestEnum
{
None,
EnumValue1,
EnumValue2
}
/// <summary>
/// Pure POCO with references
/// </summary>
public class MyDataGroup
{
public int Id { get; set; }
public string Name { get; set; }
public List<MyData> Items { get; set; }
public MyDataGroup Parent { get; set; }
}
/// <summary>
/// Interface for interface based data entity
/// </summary>
public interface IData
{
int Id { get; set; }
string Name { get; set; }
}
/// <summary>
/// Implementation for interface based data entity
/// </summary>
public class InterfaceBasedData: IData
{
public int Id { get; set; }
public string Name { get; set; }
}
/// <summary>
/// Prototype for prototype based data entity
/// </summary>
public abstract class AData
{
public abstract int Id { get; set; }
public abstract string Name { get; set; }
}
/// <summary>
/// Implementation for prototype based data entity
/// </summary>
public class PrototypeBasedData: AData
{
public override int Id { get; set; }
public override string Name { get; set; }
}
public class MyDataKeys
{
public bool KeyBool;
public bool? KeyBoolN;
public int KeyInt;
public int? KeyIntN;
public long KeyLong;
public long? KeyLongN;
public Guid KeyGuid;
public Guid? KeyGuidN;
public TimeSpan KeyTimeSpan;
public TimeSpan? KeyTimeSpanN;
public DateTime KeyDateTime;
public DateTime? KeyDateTimeN;
public DateTimeOffset KeyDateTimeOffset;
public DateTimeOffset? KeyDateTimeOffsetN;
}
}
| {
"content_hash": "12c37582cf51fe76d8ae3b328e01177a",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 66,
"avg_line_length": 23.85611510791367,
"alnum_prop": 0.6477683956574186,
"repo_name": "churchs19/lex.db",
"id": "4369536b35c69c03169dc98e3cb28aef0c3be7e0",
"size": "3318",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/Lex.Db.Tests.Shared/UnitTests/Entities.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "385989"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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">
<parent>
<artifactId>nifi-metrics-reporting-bundle</artifactId>
<groupId>org.apache.nifi</groupId>
<version>1.5.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>nifi-metrics-reporting-task</artifactId>
<dependencies>
<dependency>
<groupId>org.apache.nifi</groupId>
<artifactId>nifi-utils</artifactId>
</dependency>
<dependency>
<groupId>org.apache.nifi</groupId>
<artifactId>nifi-metrics-reporter-service-api</artifactId>
<version>1.5.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-graphite</artifactId>
<version>3.1.2</version>
</dependency>
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-jvm</artifactId>
<version>3.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.nifi</groupId>
<artifactId>nifi-mock</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
| {
"content_hash": "0e0568c825dd92bc3bebd941d8ff88f1",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 108,
"avg_line_length": 41.527272727272724,
"alnum_prop": 0.6576182136602452,
"repo_name": "dlukyanov/nifi",
"id": "7b437bca31ec832ac8720b4bbb97570589b4bbc4",
"size": "2284",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "nifi-nar-bundles/nifi-metrics-reporting-bundle/nifi-metrics-reporting-task/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "18771"
},
{
"name": "CSS",
"bytes": "220997"
},
{
"name": "Clojure",
"bytes": "3993"
},
{
"name": "GAP",
"bytes": "30012"
},
{
"name": "Groovy",
"bytes": "1278340"
},
{
"name": "HTML",
"bytes": "363029"
},
{
"name": "Java",
"bytes": "27493516"
},
{
"name": "JavaScript",
"bytes": "2653865"
},
{
"name": "Lua",
"bytes": "983"
},
{
"name": "Python",
"bytes": "17954"
},
{
"name": "Ruby",
"bytes": "8028"
},
{
"name": "Shell",
"bytes": "42620"
},
{
"name": "XSLT",
"bytes": "5681"
}
],
"symlink_target": ""
} |
require_xpr64;
require_fp;
softfloat_roundingMode = RM;
WRITE_RD(f32_to_i64(HFRS1, RM, true));
set_fp_exceptions;
| {
"content_hash": "4e09374228197b4e05dd255049a0e336",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 38,
"avg_line_length": 22.8,
"alnum_prop": 0.7456140350877193,
"repo_name": "HackLinux/goblin-core",
"id": "1551ce2ef7fbd90deecad9e298543b8ea4a3f8c9",
"size": "114",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "riscv/riscv-sim/hwacha/insns_ut/ut_fcvt_l_h.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "1429"
},
{
"name": "Assembly",
"bytes": "37233636"
},
{
"name": "Awk",
"bytes": "1296"
},
{
"name": "Batchfile",
"bytes": "31924"
},
{
"name": "C",
"bytes": "121284973"
},
{
"name": "C#",
"bytes": "12418"
},
{
"name": "C++",
"bytes": "125922408"
},
{
"name": "CMake",
"bytes": "710908"
},
{
"name": "CSS",
"bytes": "43924"
},
{
"name": "Common Lisp",
"bytes": "65656"
},
{
"name": "Cuda",
"bytes": "12393"
},
{
"name": "D",
"bytes": "16218707"
},
{
"name": "DIGITAL Command Language",
"bytes": "53633"
},
{
"name": "DTrace",
"bytes": "8175207"
},
{
"name": "E",
"bytes": "3290"
},
{
"name": "Eiffel",
"bytes": "2314"
},
{
"name": "Elixir",
"bytes": "314"
},
{
"name": "Emacs Lisp",
"bytes": "41146"
},
{
"name": "FORTRAN",
"bytes": "377751"
},
{
"name": "Forth",
"bytes": "4188"
},
{
"name": "GAP",
"bytes": "21991"
},
{
"name": "GDScript",
"bytes": "54941"
},
{
"name": "Gnuplot",
"bytes": "446"
},
{
"name": "Groff",
"bytes": "1976484"
},
{
"name": "HTML",
"bytes": "1119644"
},
{
"name": "JavaScript",
"bytes": "24233"
},
{
"name": "LLVM",
"bytes": "48362057"
},
{
"name": "Lex",
"bytes": "596732"
},
{
"name": "Limbo",
"bytes": "755"
},
{
"name": "M",
"bytes": "1797"
},
{
"name": "Makefile",
"bytes": "12715642"
},
{
"name": "Mathematica",
"bytes": "5497"
},
{
"name": "Matlab",
"bytes": "54444"
},
{
"name": "Mercury",
"bytes": "1222"
},
{
"name": "OCaml",
"bytes": "748821"
},
{
"name": "Objective-C",
"bytes": "4995355"
},
{
"name": "Objective-C++",
"bytes": "1419213"
},
{
"name": "Perl",
"bytes": "880961"
},
{
"name": "Perl6",
"bytes": "80742"
},
{
"name": "PicoLisp",
"bytes": "31994"
},
{
"name": "Pure Data",
"bytes": "22171"
},
{
"name": "Python",
"bytes": "1375992"
},
{
"name": "R",
"bytes": "627855"
},
{
"name": "Rebol",
"bytes": "51929"
},
{
"name": "Scheme",
"bytes": "4296232"
},
{
"name": "Shell",
"bytes": "1994645"
},
{
"name": "SourcePawn",
"bytes": "4564"
},
{
"name": "Standard ML",
"bytes": "5682"
},
{
"name": "SuperCollider",
"bytes": "734239"
},
{
"name": "Tcl",
"bytes": "2234"
},
{
"name": "TeX",
"bytes": "601780"
},
{
"name": "VimL",
"bytes": "26411"
},
{
"name": "Yacc",
"bytes": "769886"
}
],
"symlink_target": ""
} |
public class JBossLogTest {
private static final org.jboss.logging.Logger LOGGER1 = org.jboss.logging.Logger.getLogger(JBossLogTest.class);
public void logSomething() {
LOGGER1.info("Hello World!");
}
public static void main(String[] args) {
LOGGER1.info("Test");
new JBossLogTest().logSomething();
}
}
| {
"content_hash": "46ddc229c95c48dcad00eb7a8517d68c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 113,
"avg_line_length": 25.23076923076923,
"alnum_prop": 0.7042682926829268,
"repo_name": "mplushnikov/lombok-intellij-plugin",
"id": "41d6334e311f6a676dbe7ba37f6ac02ba310876f",
"size": "328",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "testData/configsystem/log/fieldName/after/JBossLogTest.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "33025"
},
{
"name": "Java",
"bytes": "2152851"
},
{
"name": "Lex",
"bytes": "1624"
}
],
"symlink_target": ""
} |
'use strict';
var Lib = require('../../lib');
var hasColumns = require('./has_columns');
var handleXYZDefaults = require('./xyz_defaults');
var colorscaleDefaults = require('../../components/colorscale/defaults');
var attributes = require('./attributes');
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var len = handleXYZDefaults(traceIn, traceOut, coerce);
if(!len) {
traceOut.visible = false;
return;
}
coerce('text');
coerce('zsmooth');
coerce('connectgaps', hasColumns(traceOut) && (traceOut.zsmooth !== false));
colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'});
};
| {
"content_hash": "8f99e613455446ff3042d2f922392bca",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 86,
"avg_line_length": 26.833333333333332,
"alnum_prop": 0.6571428571428571,
"repo_name": "oudalab/fajita",
"id": "f0fdfb1aafd125d0a256231e1b3fe2c2b9c55cd0",
"size": "996",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "node_modules/plotly.js/src/traces/heatmap/defaults.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "5936"
},
{
"name": "CSS",
"bytes": "14791"
},
{
"name": "HTML",
"bytes": "79261"
},
{
"name": "JavaScript",
"bytes": "203863"
},
{
"name": "Jupyter Notebook",
"bytes": "2483101"
},
{
"name": "Pug",
"bytes": "13130"
},
{
"name": "Python",
"bytes": "7851995"
},
{
"name": "Shell",
"bytes": "3299"
}
],
"symlink_target": ""
} |
<?php
namespace Zend\EventManager\Test;
use PHPUnit_Framework_Assert as Assert;
use ReflectionProperty;
use Zend\EventManager\EventManager;
/**
* Trait providing utility methods and assertions for use in PHPUnit tests cases.
*
* This trait may be composed into a tests case, and provides:
*
* - methods for introspecting events and listeners
* - methods for asserting listeners are attached at a specific priority
*
* Some functionality in this trait duplicates functionality present in the
* version 2 EventManagerInterface and/or EventManager implementation, but
* abstracts that functionality for use in v3. As such, components or code
* that is testing for listener registration should use the methods in this
* trait to ensure tests are forwards-compatible between zend-eventmanager
* versions.
*/
trait EventListenerIntrospectionTrait
{
/**
* Retrieve a list of event names from an event manager.
*
* @param EventManager $events
* @return string[]
*/
private function getEventsFromEventManager(EventManager $events)
{
$r = new ReflectionProperty($events, 'events');
$r->setAccessible(true);
$listeners = $r->getValue($events);
return array_keys($listeners);
}
/**
* Retrieve an interable list of listeners for an event.
*
* Given an event and an event manager, returns an iterator with the
* listeners for that event, in priority order.
*
* If $withPriority is true, the key values will be the priority at which
* the given listener is attached.
*
* Do not pass $withPriority if you want to cast the iterator to an array,
* as many listeners will likely have the same priority, and thus casting
* will collapse to the last added.
*
* @param string $event
* @param EventManager $events
* @param bool $withPriority
* @return \Traversable
*/
private function getListenersForEvent($event, EventManager $events, $withPriority = false)
{
$r = new ReflectionProperty($events, 'events');
$r->setAccessible(true);
$internal = $r->getValue($events);
$listeners = [];
foreach (isset($internal[$event]) ? $internal[$event] : [] as $p => $listOfListeners) {
foreach ($listOfListeners as $l) {
$listeners[$p] = isset($listeners[$p]) ? array_merge($listeners[$p], $l) : $l;
}
}
return $this->traverseListeners($listeners, $withPriority);
}
/**
* Assert that a given listener exists at the specified priority.
*
* @param callable $expectedListener
* @param int $expectedPriority
* @param string $event
* @param EventManager $events
* @param string $message Failure message to use, if any.
*/
private function assertListenerAtPriority(
callable $expectedListener,
$expectedPriority,
$event,
EventManager $events,
$message = ''
) {
$message = $message ?: sprintf(
'Listener not found for event "%s" and priority %d',
$event,
$expectedPriority
);
$listeners = $this->getListenersForEvent($event, $events, true);
$found = false;
foreach ($listeners as $priority => $listener) {
if ($listener === $expectedListener
&& $priority === $expectedPriority
) {
$found = true;
break;
}
}
Assert::assertTrue($found, $message);
}
/**
* Returns an indexed array of listeners for an event.
*
* Returns an indexed array of listeners for an event, in priority order.
* Priority values will not be included; use this only for testing if
* specific listeners are present, or for a count of listeners.
*
* @param string $event
* @param EventManager $events
* @return callable[]
*/
private function getArrayOfListenersForEvent($event, EventManager $events)
{
return iterator_to_array($this->getListenersForEvent($event, $events));
}
/**
* Generator for traversing listeners in priority order.
*
* @param array $listeners
* @param bool $withPriority When true, yields priority as key.
*/
public function traverseListeners(array $queue, $withPriority = false)
{
krsort($queue, SORT_NUMERIC);
foreach ($queue as $priority => $listeners) {
$priority = (int) $priority;
foreach ($listeners as $listener) {
if ($withPriority) {
yield $priority => $listener;
} else {
yield $listener;
}
}
}
}
}
| {
"content_hash": "cb106ecc5380ec761ee9aea88e0b417d",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 95,
"avg_line_length": 32.8013698630137,
"alnum_prop": 0.6134892461891835,
"repo_name": "geninhocell/clinica",
"id": "055c7678a354090b3e7fc8ab9b5f35eafe0da539",
"size": "5121",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/zendframework/zend-eventmanager/src/Test/EventListenerIntrospectionTrait.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5530"
},
{
"name": "PHP",
"bytes": "288862"
}
],
"symlink_target": ""
} |
package ensemble.samples.charts.line;
import ensemble.Sample;
import ensemble.controls.PropertySheet;
import ensemble.util.ChartActions;
import java.util.ArrayList;
import java.util.List;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.util.Duration;
/**
* A line chart demonstrating a CategoryAxis implementation, with a variety of
* controls.
*
* @see javafx.scene.chart.CategoryAxis
* @see javafx.scene.chart.Chart
* @see javafx.scene.chart.NumberAxis
* @see javafx.scene.chart.LineChart
* @see javafx.scene.chart.XYChart
*/
public class AdvLineCategoryChartSample extends Sample {
private static final String[] CATEGORIES = {"Alpha","Beta","RC1","RC2","1.0","1.1"};
public AdvLineCategoryChartSample() {
getChildren().add(createChart());
}
protected LineChart<String, Number> createChart() {
final CategoryAxis xAxis = new CategoryAxis();
final NumberAxis yAxis = new NumberAxis();
final LineChart<String,Number> lc = new LineChart<String,Number>(xAxis,yAxis);
// setup chart
lc.setTitle("LineChart with Category Axis");
xAxis.setLabel("X Axis");
yAxis.setLabel("Y Axis");
// add starting data
XYChart.Series<String,Number> series = new XYChart.Series<String,Number>();
series.setName("Data Series 1");
series.getData().add(new XYChart.Data<String,Number>(CATEGORIES[0], 50d));
series.getData().add(new XYChart.Data<String,Number>(CATEGORIES[1], 80d));
series.getData().add(new XYChart.Data<String,Number>(CATEGORIES[2], 90d));
series.getData().add(new XYChart.Data<String,Number>(CATEGORIES[3], 30d));
series.getData().add(new XYChart.Data<String,Number>(CATEGORIES[4], 122d));
series.getData().add(new XYChart.Data<String,Number>(CATEGORIES[5], 10d));
lc.getData().add(series);
return lc;
}
// REMOVE ME
@Override public Node getSideBarExtraContent() {
return createPropertySheet();
}
@Override public String getSideBarExtraContentTitle() {
return "Chart Properties";
}
protected PropertySheet createPropertySheet() {
final LineChart<String,Number> lc = (LineChart<String,Number>)getChildren().get(0);
final CategoryAxis xAxis = (CategoryAxis)lc.getXAxis();
final NumberAxis yAxis = (NumberAxis)lc.getYAxis();
EventHandler<ActionEvent> addDataItem = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
if (lc.getData() != null && !lc.getData().isEmpty()) {
XYChart.Series<String, Number> s = lc.getData().get((int)(Math.random() * lc.getData().size()));
if(s!=null) s.getData().add(
new LineChart.Data<String, Number>(CATEGORIES[(int)(Math.random()*CATEGORIES.length)], Math.random()*1000));
}
}
};
EventHandler<ActionEvent> insertDataItem = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
if (lc.getData() != null && !lc.getData().isEmpty()) {
XYChart.Series<String, Number> s = lc.getData().get((int)(Math.random() * lc.getData().size()));
if(s!=null) s.getData().add((int)(s.getData().size()*Math.random()) ,
new LineChart.Data<String, Number>(CATEGORIES[(int)(Math.random()*CATEGORIES.length)], Math.random()*1000));
}
}
};
EventHandler<ActionEvent> addDataItemNegative = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
if (lc.getData() != null && !lc.getData().isEmpty()) {
XYChart.Series<String, Number> s = lc.getData().get((int)(Math.random() * lc.getData().size()));
if(s!=null) s.getData().add(
new LineChart.Data<String, Number>(CATEGORIES[(int)(Math.random()*CATEGORIES.length)], Math.random()*-200));
}
}
};
EventHandler<ActionEvent> deleteDataItem = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
ChartActions.deleteDataItem(lc);
}
};
EventHandler<ActionEvent> changeDataItem = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
if (lc.getData() != null && !lc.getData().isEmpty()) {
XYChart.Series<String, Number> s = lc.getData().get((int)(Math.random()*(lc.getData().size())));
if(s!=null && !s.getData().isEmpty()) {
XYChart.Data<String,Number> d = s.getData().get((int)(Math.random()*(s.getData().size())));
if (d!=null) {
d.setYValue(Math.random() * 1000);
}
}
}
}
};
EventHandler<ActionEvent> addSeries = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
try {
LineChart.Series<String, Number> series = new LineChart.Series<String, Number>();
series.setName("Data Series 1");
for (String category : CATEGORIES) {
series.getData().add(new LineChart.Data<String, Number>(category, Math.random() * 800));
}
if (lc.getData() == null) lc.setData(FXCollections.<XYChart.Series<String,Number>>observableArrayList());
lc.getData().add(series);
} catch (Exception e) {
e.printStackTrace();
}
}
};
EventHandler<ActionEvent> deleteSeries = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
if (lc.getData() != null && !lc.getData().isEmpty()) {
lc.getData().remove((int)(Math.random() * lc.getData().size()));
}
}
};
EventHandler<ActionEvent> animateData = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
if (lc.getData() == null) {
return;
}
Timeline tl = new Timeline();
tl.getKeyFrames().add(
new KeyFrame(Duration.millis(500), new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
for (XYChart.Series<String, Number> series: lc.getData()) {
for (XYChart.Data<String, Number> data: series.getData()) {
// data.setXValue(Math.random()*1000);
data.setYValue(Math.random()*1000);
}
}
}
})
);
tl.setCycleCount(30);
tl.play();
}
};
EventHandler<ActionEvent> removeAllData = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
lc.setData(null);
}
};
EventHandler<ActionEvent> setNewData = new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
ObservableList<XYChart.Series<String,Number>> data = FXCollections.observableArrayList();
for (int j=0; j<5;j++) {
LineChart.Series<String, Number> series = new LineChart.Series<String, Number>();
series.setName("Data Series "+j);
for (String category : CATEGORIES) {
series.getData().add(new LineChart.Data<String, Number>(category, Math.random()*800));
}
data.add(series);
}
lc.setData(data);
}
};
//Create X/Y side overriding values to filter out unhelpful values
List<Enum> xValidSides = new ArrayList();
xValidSides.add(Side.BOTTOM);
xValidSides.add(Side.TOP);
List<Enum> yValidSides = new ArrayList();
yValidSides.add(Side.LEFT);
yValidSides.add(Side.RIGHT);
// create property editor
return new PropertySheet(
new PropertySheet.PropertyGroup("Actions",
PropertySheet.createProperty("Add Data Item",addDataItem),
PropertySheet.createProperty("Insert Data Item",insertDataItem),
PropertySheet.createProperty("Add Data Item Negative",addDataItemNegative),
PropertySheet.createProperty("Delete Data Item",deleteDataItem),
PropertySheet.createProperty("Change Data Item",changeDataItem),
PropertySheet.createProperty("Add Series",addSeries),
PropertySheet.createProperty("Delete Series",deleteSeries),
PropertySheet.createProperty("Remove All Data",removeAllData),
PropertySheet.createProperty("Set New Data",setNewData)
),
new PropertySheet.PropertyGroup("Chart Properties",
PropertySheet.createProperty("Title",lc.titleProperty()),
PropertySheet.createProperty("Title Side",lc.titleSideProperty()),
PropertySheet.createProperty("Legend Side",lc.legendSideProperty())
),
new PropertySheet.PropertyGroup("XY Chart Properties",
PropertySheet.createProperty("Vertical Grid Line Visible",lc.verticalGridLinesVisibleProperty()),
PropertySheet.createProperty("Horizontal Grid Line Visible",lc.horizontalGridLinesVisibleProperty()),
PropertySheet.createProperty("Alternative Column Fill Visible",lc.alternativeColumnFillVisibleProperty()),
PropertySheet.createProperty("Alternative Row Fill Visible",lc.alternativeRowFillVisibleProperty()),
PropertySheet.createProperty("Vertical Zero Line Visible",lc.verticalZeroLineVisibleProperty()),
PropertySheet.createProperty("Horizontal Zero Line Visible",lc.horizontalZeroLineVisibleProperty()),
PropertySheet.createProperty("Animated",lc.animatedProperty())
),
new PropertySheet.PropertyGroup("X Axis Properties",
PropertySheet.createProperty("Side",xAxis.sideProperty(), xValidSides),
PropertySheet.createProperty("Label",xAxis.labelProperty()),
PropertySheet.createProperty("Tick Mark Length",xAxis.tickLengthProperty()),
PropertySheet.createProperty("Tick Label Rotation",xAxis.tickLabelRotationProperty()),
PropertySheet.createProperty("Auto Ranging",xAxis.autoRangingProperty()),
PropertySheet.createProperty("Tick Label Font",xAxis.tickLabelFontProperty()),
PropertySheet.createProperty("Tick Label Fill",xAxis.tickLabelFillProperty()),
PropertySheet.createProperty("Tick Label Gap",xAxis.tickLabelGapProperty())
),
new PropertySheet.PropertyGroup("Y Axis Properties",
PropertySheet.createProperty("Side",yAxis.sideProperty(), yValidSides),
PropertySheet.createProperty("Label",yAxis.labelProperty()),
PropertySheet.createProperty("Tick Mark Length",yAxis.tickLengthProperty()),
PropertySheet.createProperty("Tick Label Rotation",yAxis.tickLabelRotationProperty()),
PropertySheet.createProperty("Auto Ranging",yAxis.autoRangingProperty()),
PropertySheet.createProperty("Tick Label Font",yAxis.tickLabelFontProperty()),
PropertySheet.createProperty("Tick Label Fill",yAxis.tickLabelFillProperty()),
PropertySheet.createProperty("Tick Label Gap",yAxis.tickLabelGapProperty()),
// Value Axis Props
//PropertySheet.createProperty("Scale",yAxis.scaleProperty(), true),
PropertySheet.createProperty("Lower Bound",yAxis.lowerBoundProperty(), true),
PropertySheet.createProperty("Upper Bound",yAxis.upperBoundProperty(), true),
PropertySheet.createProperty("Tick Label Formatter",yAxis.tickLabelFormatterProperty()),
PropertySheet.createProperty("Minor Tick Length",yAxis.minorTickLengthProperty()),
PropertySheet.createProperty("Minor Tick Count",yAxis.minorTickCountProperty()),
// Number Axis Properties
PropertySheet.createProperty("Force Zero In Range",yAxis.forceZeroInRangeProperty()),
PropertySheet.createProperty("Tick Unit",yAxis.tickUnitProperty())
)
);
}
// END REMOVE ME
}
| {
"content_hash": "65800eddf6a4894f9a5b9d0e72446399",
"timestamp": "",
"source": "github",
"line_count": 251,
"max_line_length": 136,
"avg_line_length": 53.69322709163347,
"alnum_prop": 0.6036209838984937,
"repo_name": "eugenkiss/kotlinfx-ensemble",
"id": "dad2ac6f1117e13fc088135fa6d9928356d092d7",
"size": "15180",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/main/java/ensemble/samples/charts/line/AdvLineCategoryChartSample.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "72460"
},
{
"name": "Groovy",
"bytes": "843"
},
{
"name": "Java",
"bytes": "1131710"
},
{
"name": "Kotlin",
"bytes": "615"
}
],
"symlink_target": ""
} |
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { TranslateModule } from '@ngx-translate/core';
import { AddonMessagesConversationInfoPage } from './conversation-info';
import { CoreComponentsModule } from '@components/components.module';
import { CoreDirectivesModule } from '@directives/directives.module';
@NgModule({
declarations: [
AddonMessagesConversationInfoPage,
],
imports: [
CoreComponentsModule,
CoreDirectivesModule,
IonicPageModule.forChild(AddonMessagesConversationInfoPage),
TranslateModule.forChild()
],
})
export class AddonMessagesConversationInfoPageModule {}
| {
"content_hash": "86a86e8ced11fdbb7abb0fee96f98d3a",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 72,
"avg_line_length": 36.1578947368421,
"alnum_prop": 0.7379912663755459,
"repo_name": "moodlehq/moodlemobile2",
"id": "df49d4eedc2e5ed044273384c53845875027427f",
"size": "1284",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/addon/messages/pages/conversation-info/conversation-info.module.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "215100"
},
{
"name": "Dockerfile",
"bytes": "619"
},
{
"name": "HTML",
"bytes": "698205"
},
{
"name": "Java",
"bytes": "1782"
},
{
"name": "JavaScript",
"bytes": "240820"
},
{
"name": "PHP",
"bytes": "31462"
},
{
"name": "Shell",
"bytes": "14375"
},
{
"name": "TypeScript",
"bytes": "8373893"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
class WorkDays
{
static int WorkDaysFromNow(DateTime today, DateTime inpDate)
{
int workdays = 0;
List<DateTime> officialHolidays = new List<DateTime>() {
DateTime.Parse("06.09.2012"),
DateTime.Parse("22.09.2012"),
DateTime.Parse("24.12.2012"),
DateTime.Parse("25.12.2012"),
DateTime.Parse("26.12.2012"),
DateTime.Parse("01.01.2013"),
DateTime.Parse("03.03.2013"),
DateTime.Parse("01.05.2013"),
DateTime.Parse("24.05.2013"),
DateTime.Parse("06.09.2013"),
DateTime.Parse("22.09.2013"),
DateTime.Parse("24.12.2013"),
DateTime.Parse("25.12.2013"),
DateTime.Parse("26.12.2013"),
};
for (DateTime date = today; date <= inpDate; date = date.AddDays(1))
{
if ((date.DayOfWeek != DayOfWeek.Saturday) && (date.DayOfWeek != DayOfWeek.Sunday)
&& (officialHolidays.IndexOf(date) == -1))
{
workdays++;
}
}
return workdays;
}
static void Main()
{
Console.WriteLine("Calculate the number of workdays between today and given date,\npassed as parameter");
DateTime date;
DateTime dateNow=DateTime.Now;
string strNum;
int workDays = 0;
do
{
Console.Write("Enter a date in format dd.mm.yyyy: ");
}
while (!DateTime.TryParse(strNum = Console.ReadLine(), out date));
if (date > dateNow)
{
workDays = WorkDaysFromNow(dateNow, date);
}
else
{
workDays = WorkDaysFromNow(date, dateNow);
}
Console.WriteLine("Work days between {0:d} and {1:d}: {2}", dateNow, date, workDays);
}
}
| {
"content_hash": "2bee89b1406cbb9b9449846f20b1a14c",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 113,
"avg_line_length": 43.03174603174603,
"alnum_prop": 0.3707119144227222,
"repo_name": "studware/Ange-Git",
"id": "93993b02f60c0ae1354091fe0140014ddfe27c3a",
"size": "2713",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MyTelerikAcademyHomeWorks/CSharp1/HW11.ClassesAndObjects/T11.5.WorkDays/WorkDays.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1833657"
},
{
"name": "CSS",
"bytes": "52022"
},
{
"name": "HTML",
"bytes": "48849"
},
{
"name": "JavaScript",
"bytes": "6247"
},
{
"name": "PLSQL",
"bytes": "6610"
},
{
"name": "PowerShell",
"bytes": "332"
},
{
"name": "XSLT",
"bytes": "2371"
}
],
"symlink_target": ""
} |
require 'spec_helper'
RSpec.describe 'Projects > Files > User edits files', :js do
include ProjectForksHelper
let(:project) { create(:project, :repository, name: 'Shop') }
let(:project2) { create(:project, :repository, name: 'Another Project', path: 'another-project') }
let(:project_tree_path_root_ref) { project_tree_path(project, project.repository.root_ref) }
let(:project2_tree_path_root_ref) { project_tree_path(project2, project2.repository.root_ref) }
let(:user) { create(:user) }
before do
sign_in(user)
end
shared_examples 'unavailable for an archived project' do
it 'does not show the edit link for an archived project', :js do
project.update!(archived: true)
visit project_tree_path(project, project.repository.root_ref)
click_link('.gitignore')
aggregate_failures 'available edit buttons' do
expect(page).not_to have_text('Edit')
expect(page).not_to have_text('Web IDE')
expect(page).not_to have_text('Replace')
expect(page).not_to have_text('Delete')
end
end
end
context 'when an user has write access', :js do
before do
project.add_maintainer(user)
visit(project_tree_path_root_ref)
wait_for_requests
end
it 'inserts a content of a file' do
click_link('.gitignore')
find('.js-edit-blob').click
find('.file-editor', match: :first)
find('#editor')
execute_script("monaco.editor.getModels()[0].setValue('*.rbca')")
expect(evaluate_script('monaco.editor.getModels()[0].getValue()')).to eq('*.rbca')
end
it 'does not show the edit link if a file is binary' do
binary_file = File.join(project.repository.root_ref, 'files/images/logo-black.png')
visit(project_blob_path(project, binary_file))
wait_for_requests
page.within '.content' do
expect(page).not_to have_link('edit')
end
end
it 'commits an edited file' do
click_link('.gitignore')
find('.js-edit-blob').click
find('.file-editor', match: :first)
find('#editor')
execute_script("monaco.editor.getModels()[0].setValue('*.rbca')")
fill_in(:commit_message, with: 'New commit message', visible: true)
click_button('Commit changes')
expect(current_path).to eq(project_blob_path(project, 'master/.gitignore'))
wait_for_requests
expect(page).to have_content('*.rbca')
end
it 'commits an edited file to a new branch' do
click_link('.gitignore')
find('.js-edit-blob').click
find('.file-editor', match: :first)
find('#editor')
execute_script("monaco.editor.getModels()[0].setValue('*.rbca')")
fill_in(:commit_message, with: 'New commit message', visible: true)
fill_in(:branch_name, with: 'new_branch_name', visible: true)
click_button('Commit changes')
expect(current_path).to eq(project_new_merge_request_path(project))
click_link('Changes')
expect(page).to have_content('*.rbca')
end
it 'shows the diff of an edited file' do
click_link('.gitignore')
find('.js-edit-blob').click
find('.file-editor', match: :first)
find('#editor')
execute_script("monaco.editor.getModels()[0].setValue('*.rbca')")
click_link('Preview changes')
expect(page).to have_css('.line_holder.new')
end
it_behaves_like 'unavailable for an archived project'
end
context 'when an user does not have write access', :js do
before do
project2.add_reporter(user)
visit(project2_tree_path_root_ref)
wait_for_requests
end
def expect_fork_prompt
expect(page).to have_link('Fork')
expect(page).to have_button('Cancel')
expect(page).to have_content(
"You're not allowed to edit files in this project directly. "\
"Please fork this project, make your changes there, and submit a merge request."
)
end
def expect_fork_status
expect(page).to have_content(
"You're not allowed to make changes to this project directly. "\
"A fork of this project has been created that you can make changes in, so you can submit a merge request."
)
end
it 'inserts a content of a file in a forked project', :sidekiq_might_not_need_inline do
click_link('.gitignore')
click_button('Edit')
expect_fork_prompt
click_link('Fork')
expect_fork_status
find('.file-editor', match: :first)
find('#editor')
execute_script("monaco.editor.getModels()[0].setValue('*.rbca')")
expect(evaluate_script('monaco.editor.getModels()[0].getValue()')).to eq('*.rbca')
end
it 'opens the Web IDE in a forked project', :sidekiq_might_not_need_inline do
click_link('.gitignore')
click_button('Web IDE')
expect_fork_prompt
click_link('Fork')
expect_fork_status
expect(page).to have_css('.ide-sidebar-project-title', text: "#{project2.name} #{user.namespace.full_path}/#{project2.path}")
expect(page).to have_css('.ide .multi-file-tab', text: '.gitignore')
end
it 'commits an edited file in a forked project', :sidekiq_might_not_need_inline do
click_link('.gitignore')
find('.js-edit-blob').click
expect_fork_prompt
click_link('Fork')
find('.file-editor', match: :first)
find('#editor')
execute_script("monaco.editor.getModels()[0].setValue('*.rbca')")
fill_in(:commit_message, with: 'New commit message', visible: true)
click_button('Commit changes')
fork = user.fork_of(project2.reload)
expect(current_path).to eq(project_new_merge_request_path(fork))
wait_for_requests
expect(page).to have_content('New commit message')
end
context 'when the user already had a fork of the project', :js do
let!(:forked_project) { fork_project(project2, user, namespace: user.namespace, repository: true) }
before do
visit(project2_tree_path_root_ref)
wait_for_requests
end
it 'links to the forked project for editing', :sidekiq_might_not_need_inline do
click_link('.gitignore')
find('.js-edit-blob').click
expect(page).not_to have_link('Fork')
expect(page).not_to have_button('Cancel')
find('#editor')
execute_script("monaco.editor.getModels()[0].setValue('*.rbca')")
fill_in(:commit_message, with: 'Another commit', visible: true)
click_button('Commit changes')
fork = user.fork_of(project2)
expect(current_path).to eq(project_new_merge_request_path(fork))
wait_for_requests
expect(page).to have_content('Another commit')
expect(page).to have_content("From #{forked_project.full_path}")
expect(page).to have_content("into #{project2.full_path}")
end
it_behaves_like 'unavailable for an archived project' do
let(:project) { project2 }
end
end
end
end
| {
"content_hash": "14c5647b39cad31aefe80cd2002f400a",
"timestamp": "",
"source": "github",
"line_count": 226,
"max_line_length": 131,
"avg_line_length": 30.858407079646017,
"alnum_prop": 0.6377975336965873,
"repo_name": "mmkassem/gitlabhq",
"id": "d3e075001c8639d708e98370fb3d8dedac9ff7cb",
"size": "7005",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/features/projects/files/user_edits_files_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "113683"
},
{
"name": "CoffeeScript",
"bytes": "139197"
},
{
"name": "Cucumber",
"bytes": "119759"
},
{
"name": "HTML",
"bytes": "447030"
},
{
"name": "JavaScript",
"bytes": "29805"
},
{
"name": "Ruby",
"bytes": "2417833"
},
{
"name": "Shell",
"bytes": "14336"
}
],
"symlink_target": ""
} |
Built with [Slim PHP framework](http://www.slimframework.com/) and [Foundation CSS framework](http://foundation.zurb.com/).
------------
**What does it do?**
Webception is a deployable web-application that allows you to run all your Codeception tests in the browser.
You can access multiple test suites and decide which tests to include in a run. It allows you start, stop and restart the process whilst watching the test results in the Console.
**What does it look like?**
I'm glad you asked...
<img src="http://i.imgur.com/nSsMFIS.gif">
**What's the ideal usage?**
If you're a web developer, it's likely you run a staging server that hosts work in progress for your clients.
Webception's ideal setup would be on a sub-domain on your staging server (`webception.your-staging-domain.com`) so it could have access to all of your test suites.
**What it will it do?**
Webception is a work in progress. Check out the [roadmap](#roadmap) for short-term goals.
Check out how to [contribute](#contribute) if you want to get involved.
------------
## Requirements
A web-server running PHP 5.3.0+ and [Composer](http://getcomposer.org/download/). Codeception will be installed via Composer.
------------
## Installation
Out of the box, Webception is configured to run it's own Codeception tests.
You'll need [Composer](http://getcomposer.org/download/) to be installed and the Codeception executable and logs directory need full read/write permissions.
The *only* configuration file you need to update is `App/Config/codeception.php`. It's here where you add references to the `codeception.yml` configurations.
Also note Webception's `codeception.yml` is setup to use `http://webception:80` as it's host. Change this to be whatever host and port you decide to run Webception on.
### 1. Deploy Webception
You can either install Webception using Composer:
`composer create-project jayhealey/webception --stability=dev`
Or [downloaded Webception](https://github.com/jayhealey/Webception/archive/master.zip) and unzip it. Once you've unzipped it, you need to install the Composer dependancies with:
`composer install`
Now you can do the following:
1. Ensure Codeception has permissions:
`sudo chmod a+x vendor/bin/codecept`
2. Set permissions so Codeception can write out the log files:
`sudo chmod -R 777 App/Tests/_log`
3. Set permissions so Slim PHP can write to the template cache:
`sudo chmod -R 777 App/Templates/_cache`
4. Point your new server to the `public` path of where you unzipped Webception.
You'll now be able to load Webception in your browser.
If there are any issues Webception will do it's best to tell what you need to do.
### 2. Customise the Webception configuration
There are a few configuration files you can play with in `/App/Config/codeception.php`.
#### Adding your own tests to Webception
You can add as many Codeception test suites as you need by adding to the `sites` array:
```
'sites' => array(
'Webception' => dirname(__FILE__) .'/../../codeception.yml',
),
```
Put them in order you want to see in the dropdown. And if you only have one entry, you won't see the dropdown.
Feel free to remove/replace the `Webception` entry with one of your own suites.
If you have more than one site in the configuration, you can use the site picker on the top-left of Webception to swap between test suites.
**And remember**: it's important you set `sudo chmod -R 777 /path/to/logs` on the log directories declared in your `codeception.yml` configurations. If you don't, Webception will fail to run the tests.
*Note*: You may experience issues using `$_SERVER['DOCUMENT_ROOT']` to define the configuration path. It may be best to put the absolute path to your application root or a relative path using `dirname(__FILE__)`.
### 3. Run your tests!
If you've configured everything correctly, Webception will show all your available tests. Just click **START** to run everything!
That's it! **Happy Testing!**
------------
<a name='contribute'></a>
## Want to Contribute?
There's a few ways you can get in touch:
* **Chat on Twitter**. Follow [@WebceptionApp](https://www.twitter.com/WebceptionApp) for release updates or follow [@JayHealey](https://www.twitter.com/JayHealey) for everything else.
* **Post bugs, issues, feature requests** via [GitHub Issues](https://github.com/jayhealey/webception/issues).
* **Pull & Fork** on [GitHub](https://github.com/jayhealey/Webception/pulls) if you want to get your hands dirty.
And **please let me know** if you use Webception. I'm keen to understand how you'd *like* to use it and if there's anything you'd like to see in future releases.
I'm open to any feedback on how to improve Webception. From tips on SlimPHP, to how best to improve the Codeception handling to improving the UI. I'd be happy to hear it!
------------
## Infrequently Asked Questions (IAQs)
**Why would I use Webception?**
The aim of Webception is to open the test suites up to anyone involved in a web-development project. This could be a team leader, another developer (who might not be a PHP developer), client manager or even the client.
The plan is to grow the tool to be a worthwhile part of your process. Potentially integrating CI tools or part of a bug reporting process.
And selfishly, I couldn't find anything else that acted as a web interface for Codeception, so it was a problem worth solving.
**Is Webception made by the same people as Codeception?**
No. It's completely un-official. It's not affiliated or sponsored in anyway by the people who built Codeception.
So, raise all issues about Webception on the Webception [GitHub Issues](https://github.com/jayhealey/Webception/issues) page.
**How do I run webception in WAMP on windows?
By default WAMP disables environment variables and the php executable cannot be found without the system path being available.
Enable environment variables by editing c:\wamp\bin\apache\apache2.4.9\bin\php.ini and ensure the line
variables_order = "EGPCS"
------------
<a name='roadmap'></a>
## Roadmap
* **Automated/Interactive Setup**: I'd like to replace the manual setup with an interactive installation that asks for the Codeception test suites whilst verifying the details as you enter them. You'll should also be able to add/remove test suites via the app instead of modifying configuration files. It's possible to find all available `codeception.yml` files which would help automate installation.
* **Logs and Screenshots**: When Codeception runs, it creates HTML snapshots and screenshots of where a test fails. It'd be useful for Webception to copy those files across and make them accessible via the console.
* **Security**: At the moment, you can just secure the installation with .htaccess - but it might be worth adding built-in security via a Slim module.
* **Exposed Unit Tests**: Unit tests contain multiple tests in a single file, so it'd be nice to scan Unit tests to expose them - and then allow the ability to run each of these tests individually (is that even possible in Codeception?).
* **More Webception Tests**: It feels fitting that an application that runs tests should be drowning in tests. So, there'll be more of them in future.
There's also the [TODO](todo.md) list which contains a list of things I'd like to improve.
If you have any ideas or issues, jump on [GitHub Issues](https://github.com/jayhealey/Webception/issues) or [@WebceptionApp](https://www.twitter.com/WebceptionApp) on Twitter. | {
"content_hash": "0b55cba7e833ae5d65946dec23f23a77",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 401,
"avg_line_length": 46.50310559006211,
"alnum_prop": 0.7521036463202885,
"repo_name": "Naktibalda/Webception",
"id": "3b40dc5199a35c2577109975ee33f898a72e5be0",
"size": "7582",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "325"
},
{
"name": "CSS",
"bytes": "1607"
},
{
"name": "HTML",
"bytes": "10645"
},
{
"name": "JavaScript",
"bytes": "27476"
},
{
"name": "PHP",
"bytes": "162590"
},
{
"name": "Shell",
"bytes": "1135"
}
],
"symlink_target": ""
} |
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { DatePipe } from '@angular/common';
import { Router, ActivatedRoute } from '@angular/router';
import {Entreprise, Contrat, User, CommandeLogiciel} from '../authentication.service';
import {DeclarationService} from '../declaration/declaration.service';
import {DeclarationEditService} from './declaration-edit.service';
declare var classie: any;
declare var SelectFxJs: any;
declare var inputlabel: any;
declare var jQuery:any;
@Component({
moduleId: module.id,
selector: 'app-declaration',
templateUrl: 'declaration-edit.component.html',
styleUrls: ['declaration-edit.component.css']
})
export class DeclarationEditComponent implements OnInit {
public title: string = "";
public client = new Entreprise(null, '', '', '', '', '', null);
public user: User = JSON.parse(localStorage.getItem("user"));
public declaration: Contrat = new Contrat(null, null, null, null, '',null, null, null, '', null, this.client, null, null);
private sub: any;
public isadmin: boolean = false;
public msg: string = "";
public successMsg: String;
public showSubmit: boolean =true;
public showLoading: boolean =false;
public showMessage: boolean =false;
public responsables: User[];
public users: User[];
public isAdmin: boolean = false;
public isResponsable: boolean = false;
public onPremiseInList: boolean = false;
public nbAccesPremise: number = 0;
public saasInList: boolean = false;
public nbAccesSaas: number = 0;
public prixEntreeSaas: number = 0;
constructor(private ref: ChangeDetectorRef, private router: Router, private route: ActivatedRoute, private declarationService: DeclarationService,
private editService: DeclarationEditService, private datePipe: DatePipe) {
}
ngOnInit() {
jQuery.noConflict();
jQuery('#dateContact').datepicker({ dateFormat: 'dd/mm/yy' });
jQuery('#dateSignature').datepicker({ dateFormat: 'dd/mm/yy' });
jQuery('#dateDebut').datepicker({ dateFormat: 'dd/mm/yy' });
jQuery('#dateFin').datepicker({ dateFormat: 'dd/mm/yy' });
inputlabel.inputlabelcheck();
this.sub = this.route.params.subscribe(params => {
this.declaration.id = +params['id']; // (+) converts string 'id' to a number
this.declarationService
.getDeclaration(+params['id'])
.subscribe(declaration => {
this.declaration = declaration;
this.declaration.commandeLogiciels = declaration.commandeLogiciels;
jQuery('#dateContact').val(this.datePipe.transform(this.declaration.datecontact, 'dd/MM/yyyy'));
jQuery('#dateSignature').val(this.datePipe.transform(this.declaration.datesignature, 'dd/MM/yyyy'));
jQuery('#dateDebut').val(this.datePipe.transform(this.declaration.datedebut, 'dd/MM/yyyy'));
jQuery('#dateFin').val(this.datePipe.transform(this.declaration.datefin, 'dd/MM/yyyy'));
},
error => {
console.log("Impossible de récupérer le contrat")
});
});
if(this.user.role.id == 1 || this.user.role.id == 2) {
this.isadmin = true;
this.editService.getListResponsable().subscribe(
responsables => {
this.responsables = responsables;
this.ref.reattach();
},
error => console.log('Les responsables n\'ont pas pu être chargés')
);
this.ref.reattach();
}
if(this.user.role.id == 3) {
this.isResponsable = true;
this.editService.getListUser(this.user).subscribe(
users => {
this.users = users;
this.ref.reattach();
},
error => console.log('Les responsables n\'ont pas pu être chargés')
);
}
}
deleteCommande(commande: CommandeLogiciel){
this.editService.deleteCommandeLogiciel(commande).subscribe(
commande => {
if(commande) {
let index = this.declaration.commandeLogiciels.indexOf(commande);
this.declaration.commandeLogiciels.splice(index, 1);
this.declaration.montant = 0;
this.onPremiseInList = false;
this.nbAccesPremise = 0;
this.saasInList = false;
this.nbAccesSaas = 0;
this.prixEntreeSaas = 0;
this.declaration.commandeLogiciels.forEach( commande => {
commande.prix = 0;
if(commande.logiciel != null) {
if(commande.logiciel.categorie.libelle == 'On Premise') {
if(!this.onPremiseInList) {
commande.prix = commande.logiciel.prix + (commande.logiciel.prixacces * ( commande.nbacces - 1 ) );
this.nbAccesPremise = commande.nbacces;
this.onPremiseInList = true;
} else{
if(commande.nbacces > this.nbAccesPremise) {
let nbAccesToAdd = commande.nbacces - this.nbAccesPremise;
commande.prix = commande.logiciel.prix + (nbAccesToAdd * commande.logiciel.prixacces);
this.nbAccesPremise = commande.nbacces;
} else{
commande.prix = commande.logiciel.prix;
}
}
this.declaration.montant += commande.prix;
} else{
if(!this.saasInList) {
this.prixEntreeSaas = commande.logiciel.prixentree;
commande.prix = commande.logiciel.prixentree + (commande.logiciel.prix + (commande.logiciel.prixacces * (commande.nbacces-1) ) ) * commande.logiciel.duree;
this.saasInList = true;
this.nbAccesSaas = commande.nbacces;
this.prixEntreeSaas = commande.logiciel.prixentree;
} else{
if(commande.logiciel.prixentree > this.prixEntreeSaas) {
let prixEntreeToAdd = commande.logiciel.prixentree - this.prixEntreeSaas;
commande.prix += prixEntreeToAdd;
}
if(commande.nbacces > this.nbAccesSaas) {
let nbAccesToAdd = commande.nbacces - this.nbAccesSaas;
commande.prix += ((80 + (commande.logiciel.prixacces * nbAccesToAdd) ) * commande.logiciel.duree);
this.nbAccesSaas = commande.nbacces;
} else{
commande.prix += (80 * commande.logiciel.duree);
}
}
this.declaration.montant += commande.prix;
}
}
});
this.editService.updateDeclarationMontant(this.declaration).subscribe(
commande => {
},
error =>{
}
);
this.showLoading = false;
this.successMsg = "La commande a été supprimée avec succès";
this.showMessage = true;
this.showSubmit = true;
} else{
this.showLoading = false;
this.successMsg = "La commande n'a pas été supprimée";
this.showMessage = true;
this.showSubmit = true;
}
this.ref.reattach();
},
error => {
this.showLoading = false;
this.successMsg = "La commande n'a pas pu être supprimée"
this.showMessage = true;
this.showSubmit = true;
this.ref.reattach();
}
);
}
updateDeclaration(){
if(jQuery('#dateContact').val() != '') {
this.declaration.datecontact = jQuery('#dateContact').val();
}
if(jQuery('#dateSignature').val() != '') {
this.declaration.datesignature = jQuery('#dateSignature').val();
}
if(jQuery('#dateDebut').val() != '') {
this.declaration.datedebut = jQuery('#dateDebut').val();
}
if(jQuery('#dateFin').val() != '') {
this.declaration.datefin = jQuery('#dateFin').val();
}
this.showSubmit = false;
this.showLoading = true;
if(this.showLoading) {
this.editService.updateDeclaration(this.declaration).subscribe(
declaration => {
if(declaration) {
this.showLoading = false;
this.successMsg = "Déclaration mise à jour";
this.showMessage = true;
this.ref.reattach();
} else{
this.showLoading = false;
this.successMsg = "La mise à jour a échouée";
this.showMessage = true;
this.showSubmit = true;
this.ref.reattach();
}
},
error => {
this.showLoading = false;
this.successMsg = "La mise à jour n'a pas pu être effectuée"
this.showMessage = true;
this.showSubmit = true;
this.ref.reattach();
}
);
}
}
}
| {
"content_hash": "b40fb30865bd45468c3c60c31c98d293",
"timestamp": "",
"source": "github",
"line_count": 258,
"max_line_length": 178,
"avg_line_length": 36.201550387596896,
"alnum_prop": 0.5534261241970021,
"repo_name": "RechadS/extranetpartenaire",
"id": "604d717066e6b12f2dfa030f566bc4c4d0e06617",
"size": "9363",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/declaration-edit/declaration-edit.component.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23173"
},
{
"name": "HTML",
"bytes": "37099"
},
{
"name": "JavaScript",
"bytes": "17724"
},
{
"name": "TypeScript",
"bytes": "90575"
}
],
"symlink_target": ""
} |
<main data-title="Header navigation">
<p>
In the top left of pages with hierarchy, a <code><nav></code> element can be placed containing a link to the previous page in the hierarchy.
</p>
<p>
To allow multiple-nested hierarchies, a <code>data-back</code> attribute can be added to the <code><main></code> element on the page, which can be read by your server/client side framework to update the nav link, keeping presentation data within the HTML file it represents.
</p>
</main> | {
"content_hash": "aaef228f1d8255500cefe3405a7288b4",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 279,
"avg_line_length": 61.625,
"alnum_prop": 0.7403651115618661,
"repo_name": "g105b/sass-app",
"id": "4fa027b8d62b2e35a554a39f51e707e04a6365d6",
"size": "493",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PageView/Header/Navigation.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "52026"
},
{
"name": "JavaScript",
"bytes": "3793"
},
{
"name": "PHP",
"bytes": "647"
}
],
"symlink_target": ""
} |
<?php
namespace Numbers\Backend\Db\PostgreSQL\Model;
class PlPgSQL extends \Object\Extension {
public $db_link;
public $db_link_flag;
public $module_code = 'SM';
public $title = 'PL/pgSQL - SQL Procedural Language';
public $schema = 'pg_catalog';
public $name = 'plpgsql';
public $backend = 'PostgreSQL';
} | {
"content_hash": "94e87cc499a6b778e4c0d22d283285d9",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 54,
"avg_line_length": 26.166666666666668,
"alnum_prop": 0.7101910828025477,
"repo_name": "volodymyr-volynets/backend",
"id": "78ebce8ed2e68103a7a0d6fea750bf325b2e968d",
"size": "314",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Db/PostgreSQL/Model/PlPgSQL.php",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1257"
},
{
"name": "HTML",
"bytes": "41042"
},
{
"name": "Makefile",
"bytes": "1126"
},
{
"name": "PHP",
"bytes": "641648"
}
],
"symlink_target": ""
} |
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setEnabled(false);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
if(!model)
return;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
case AddressTableModel::NO_CHANGES:
// No changes were made during edit operation. Just reject.
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid HighFiveCoin address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
| {
"content_hash": "d09027eab1a08011853d9cfae716616f",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 115,
"avg_line_length": 27.84375,
"alnum_prop": 0.6111111111111112,
"repo_name": "n00bsys0p/h5c",
"id": "cd0178773aea6c55f783b390a8c78cb7e7104878",
"size": "3736",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/qt/editaddressdialog.cpp",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
'''
OpenShiftCLI class that wraps the oc commands in a subprocess
'''
# pylint: disable=too-many-lines
from __future__ import print_function
import atexit
import copy
import json
import os
import re
import shutil
import subprocess
import tempfile
# pylint: disable=import-error
try:
import ruamel.yaml as yaml
except ImportError:
import yaml
from ansible.module_utils.basic import AnsibleModule
# -*- -*- -*- End included fragment: lib/import.py -*- -*- -*-
# -*- -*- -*- Begin included fragment: doc/registry -*- -*- -*-
DOCUMENTATION = '''
---
module: oc_adm_registry
short_description: Module to manage openshift registry
description:
- Manage openshift registry programmatically.
options:
state:
description:
- The desired action when managing openshift registry
- present - update or create the registry
- absent - tear down the registry service and deploymentconfig
- list - returns the current representiation of a registry
required: false
default: False
aliases: []
kubeconfig:
description:
- The path for the kubeconfig file to use for authentication
required: false
default: /etc/origin/master/admin.kubeconfig
aliases: []
debug:
description:
- Turn on debug output.
required: false
default: False
aliases: []
name:
description:
- The name of the registry
required: false
default: None
aliases: []
namespace:
description:
- The selector when filtering on node labels
required: false
default: None
aliases: []
images:
description:
- The image to base this registry on - ${component} will be replaced with --type
required: 'openshift3/ose-${component}:${version}'
default: None
aliases: []
latest_images:
description:
- If true, attempt to use the latest image for the registry instead of the latest release.
required: false
default: False
aliases: []
labels:
description:
- A set of labels to uniquely identify the registry and its components.
required: false
default: None
aliases: []
enforce_quota:
description:
- If set, the registry will refuse to write blobs if they exceed quota limits
required: False
default: False
aliases: []
mount_host:
description:
- If set, the registry volume will be created as a host-mount at this path.
required: False
default: False
aliases: []
ports:
description:
- A comma delimited list of ports or port pairs to expose on the registry pod. The default is set for 5000.
required: False
default: [5000]
aliases: []
replicas:
description:
- The replication factor of the registry; commonly 2 when high availability is desired.
required: False
default: 1
aliases: []
selector:
description:
- Selector used to filter nodes on deployment. Used to run registries on a specific set of nodes.
required: False
default: None
aliases: []
service_account:
description:
- Name of the service account to use to run the registry pod.
required: False
default: 'registry'
aliases: []
tls_certificate:
description:
- An optional path to a PEM encoded certificate (which may contain the private key) for serving over TLS
required: false
default: None
aliases: []
tls_key:
description:
- An optional path to a PEM encoded private key for serving over TLS
required: false
default: None
aliases: []
volume_mounts:
description:
- The volume mounts for the registry.
required: false
default: None
aliases: []
daemonset:
description:
- Use a daemonset instead of a deployment config.
required: false
default: False
aliases: []
edits:
description:
- A list of modifications to make on the deploymentconfig
required: false
default: None
aliases: []
env_vars:
description:
- A dictionary of modifications to make on the deploymentconfig. e.g. FOO: BAR
required: false
default: None
aliases: []
force:
description:
- Force a registry update.
required: false
default: False
aliases: []
author:
- "Kenny Woodson <kwoodson@redhat.com>"
extends_documentation_fragment: []
'''
EXAMPLES = '''
- name: create a secure registry
oc_adm_registry:
name: docker-registry
service_account: registry
replicas: 2
namespace: default
selector: type=infra
images: "registry.ops.openshift.com/openshift3/ose-${component}:${version}"
env_vars:
REGISTRY_CONFIGURATION_PATH: /etc/registryconfig/config.yml
REGISTRY_HTTP_TLS_CERTIFICATE: /etc/secrets/registry.crt
REGISTRY_HTTP_TLS_KEY: /etc/secrets/registry.key
REGISTRY_HTTP_SECRET: supersecret
volume_mounts:
- path: /etc/secrets
name: dockercerts
type: secret
secret_name: registry-secret
- path: /etc/registryconfig
name: dockersecrets
type: secret
secret_name: docker-registry-config
edits:
- key: spec.template.spec.containers[0].livenessProbe.httpGet.scheme
value: HTTPS
action: put
- key: spec.template.spec.containers[0].readinessProbe.httpGet.scheme
value: HTTPS
action: put
- key: spec.strategy.rollingParams
value:
intervalSeconds: 1
maxSurge: 50%
maxUnavailable: 50%
timeoutSeconds: 600
updatePeriodSeconds: 1
action: put
- key: spec.template.spec.containers[0].resources.limits.memory
value: 2G
action: update
- key: spec.template.spec.containers[0].resources.requests.memory
value: 1G
action: update
register: registryout
'''
# -*- -*- -*- End included fragment: doc/registry -*- -*- -*-
# -*- -*- -*- Begin included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
class YeditException(Exception): # pragma: no cover
''' Exception class for Yedit '''
pass
# pylint: disable=too-many-public-methods
class Yedit(object): # pragma: no cover
''' Class to modify yaml files '''
re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z{}/_-]+)"
com_sep = set(['.', '#', '|', ':'])
# pylint: disable=too-many-arguments
def __init__(self,
filename=None,
content=None,
content_type='yaml',
separator='.',
backup=False):
self.content = content
self._separator = separator
self.filename = filename
self.__yaml_dict = content
self.content_type = content_type
self.backup = backup
self.load(content_type=self.content_type)
if self.__yaml_dict is None:
self.__yaml_dict = {}
@property
def separator(self):
''' getter method for separator '''
return self._separator
@separator.setter
def separator(self, inc_sep):
''' setter method for separator '''
self._separator = inc_sep
@property
def yaml_dict(self):
''' getter method for yaml_dict '''
return self.__yaml_dict
@yaml_dict.setter
def yaml_dict(self, value):
''' setter method for yaml_dict '''
self.__yaml_dict = value
@staticmethod
def parse_key(key, sep='.'):
'''parse the key allowing the appropriate separator'''
common_separators = list(Yedit.com_sep - set([sep]))
return re.findall(Yedit.re_key.format(''.join(common_separators)), key)
@staticmethod
def valid_key(key, sep='.'):
'''validate the incoming key'''
common_separators = list(Yedit.com_sep - set([sep]))
if not re.match(Yedit.re_valid_key.format(''.join(common_separators)), key):
return False
return True
@staticmethod
def remove_entry(data, key, sep='.'):
''' remove data at location key '''
if key == '' and isinstance(data, dict):
data.clear()
return True
elif key == '' and isinstance(data, list):
del data[:]
return True
if not (key and Yedit.valid_key(key, sep)) and \
isinstance(data, (list, dict)):
return None
key_indexes = Yedit.parse_key(key, sep)
for arr_ind, dict_key in key_indexes[:-1]:
if dict_key and isinstance(data, dict):
data = data.get(dict_key)
elif (arr_ind and isinstance(data, list) and
int(arr_ind) <= len(data) - 1):
data = data[int(arr_ind)]
else:
return None
# process last index for remove
# expected list entry
if key_indexes[-1][0]:
if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
del data[int(key_indexes[-1][0])]
return True
# expected dict entry
elif key_indexes[-1][1]:
if isinstance(data, dict):
del data[key_indexes[-1][1]]
return True
@staticmethod
def add_entry(data, key, item=None, sep='.'):
''' Get an item from a dictionary with key notation a.b.c
d = {'a': {'b': 'c'}}}
key = a#b
return c
'''
if key == '':
pass
elif (not (key and Yedit.valid_key(key, sep)) and
isinstance(data, (list, dict))):
return None
key_indexes = Yedit.parse_key(key, sep)
for arr_ind, dict_key in key_indexes[:-1]:
if dict_key:
if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
data = data[dict_key]
continue
elif data and not isinstance(data, dict):
raise YeditException("Unexpected item type found while going through key " +
"path: {} (at key: {})".format(key, dict_key))
data[dict_key] = {}
data = data[dict_key]
elif (arr_ind and isinstance(data, list) and
int(arr_ind) <= len(data) - 1):
data = data[int(arr_ind)]
else:
raise YeditException("Unexpected item type found while going through key path: {}".format(key))
if key == '':
data = item
# process last index for add
# expected list entry
elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
data[int(key_indexes[-1][0])] = item
# expected dict entry
elif key_indexes[-1][1] and isinstance(data, dict):
data[key_indexes[-1][1]] = item
# didn't add/update to an existing list, nor add/update key to a dict
# so we must have been provided some syntax like a.b.c[<int>] = "data" for a
# non-existent array
else:
raise YeditException("Error adding to object at path: {}".format(key))
return data
@staticmethod
def get_entry(data, key, sep='.'):
''' Get an item from a dictionary with key notation a.b.c
d = {'a': {'b': 'c'}}}
key = a.b
return c
'''
if key == '':
pass
elif (not (key and Yedit.valid_key(key, sep)) and
isinstance(data, (list, dict))):
return None
key_indexes = Yedit.parse_key(key, sep)
for arr_ind, dict_key in key_indexes:
if dict_key and isinstance(data, dict):
data = data.get(dict_key)
elif (arr_ind and isinstance(data, list) and
int(arr_ind) <= len(data) - 1):
data = data[int(arr_ind)]
else:
return None
return data
@staticmethod
def _write(filename, contents):
''' Actually write the file contents to disk. This helps with mocking. '''
tmp_filename = filename + '.yedit'
with open(tmp_filename, 'w') as yfd:
yfd.write(contents)
os.rename(tmp_filename, filename)
def write(self):
''' write to file '''
if not self.filename:
raise YeditException('Please specify a filename.')
if self.backup and self.file_exists():
shutil.copy(self.filename, self.filename + '.orig')
# Try to set format attributes if supported
try:
self.yaml_dict.fa.set_block_style()
except AttributeError:
pass
# Try to use RoundTripDumper if supported.
try:
Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
except AttributeError:
Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
return (True, self.yaml_dict)
def read(self):
''' read from file '''
# check if it exists
if self.filename is None or not self.file_exists():
return None
contents = None
with open(self.filename) as yfd:
contents = yfd.read()
return contents
def file_exists(self):
''' return whether file exists '''
if os.path.exists(self.filename):
return True
return False
def load(self, content_type='yaml'):
''' return yaml file '''
contents = self.read()
if not contents and not self.content:
return None
if self.content:
if isinstance(self.content, dict):
self.yaml_dict = self.content
return self.yaml_dict
elif isinstance(self.content, str):
contents = self.content
# check if it is yaml
try:
if content_type == 'yaml' and contents:
# Try to set format attributes if supported
try:
self.yaml_dict.fa.set_block_style()
except AttributeError:
pass
# Try to use RoundTripLoader if supported.
try:
self.yaml_dict = yaml.safe_load(contents, yaml.RoundTripLoader)
except AttributeError:
self.yaml_dict = yaml.safe_load(contents)
# Try to set format attributes if supported
try:
self.yaml_dict.fa.set_block_style()
except AttributeError:
pass
elif content_type == 'json' and contents:
self.yaml_dict = json.loads(contents)
except yaml.YAMLError as err:
# Error loading yaml or json
raise YeditException('Problem with loading yaml file. {}'.format(err))
return self.yaml_dict
def get(self, key):
''' get a specified key'''
try:
entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
except KeyError:
entry = None
return entry
def pop(self, path, key_or_item):
''' remove a key, value pair from a dict or an item for a list'''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if entry is None:
return (False, self.yaml_dict)
if isinstance(entry, dict):
# AUDIT:maybe-no-member makes sense due to fuzzy types
# pylint: disable=maybe-no-member
if key_or_item in entry:
entry.pop(key_or_item)
return (True, self.yaml_dict)
return (False, self.yaml_dict)
elif isinstance(entry, list):
# AUDIT:maybe-no-member makes sense due to fuzzy types
# pylint: disable=maybe-no-member
ind = None
try:
ind = entry.index(key_or_item)
except ValueError:
return (False, self.yaml_dict)
entry.pop(ind)
return (True, self.yaml_dict)
return (False, self.yaml_dict)
def delete(self, path):
''' remove path from a dict'''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if entry is None:
return (False, self.yaml_dict)
result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
if not result:
return (False, self.yaml_dict)
return (True, self.yaml_dict)
def exists(self, path, value):
''' check if value exists at path'''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if isinstance(entry, list):
if value in entry:
return True
return False
elif isinstance(entry, dict):
if isinstance(value, dict):
rval = False
for key, val in value.items():
if entry[key] != val:
rval = False
break
else:
rval = True
return rval
return value in entry
return entry == value
def append(self, path, value):
'''append value to a list'''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if entry is None:
self.put(path, [])
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
if not isinstance(entry, list):
return (False, self.yaml_dict)
# AUDIT:maybe-no-member makes sense due to loading data from
# a serialized format.
# pylint: disable=maybe-no-member
entry.append(value)
return (True, self.yaml_dict)
# pylint: disable=too-many-arguments
def update(self, path, value, index=None, curr_value=None):
''' put path, value into a dict '''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if isinstance(entry, dict):
# AUDIT:maybe-no-member makes sense due to fuzzy types
# pylint: disable=maybe-no-member
if not isinstance(value, dict):
raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' +
'value=[{}] type=[{}]'.format(value, type(value)))
entry.update(value)
return (True, self.yaml_dict)
elif isinstance(entry, list):
# AUDIT:maybe-no-member makes sense due to fuzzy types
# pylint: disable=maybe-no-member
ind = None
if curr_value:
try:
ind = entry.index(curr_value)
except ValueError:
return (False, self.yaml_dict)
elif index is not None:
ind = index
if ind is not None and entry[ind] != value:
entry[ind] = value
return (True, self.yaml_dict)
# see if it exists in the list
try:
ind = entry.index(value)
except ValueError:
# doesn't exist, append it
entry.append(value)
return (True, self.yaml_dict)
# already exists, return
if ind is not None:
return (False, self.yaml_dict)
return (False, self.yaml_dict)
def put(self, path, value):
''' put path, value into a dict '''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if entry == value:
return (False, self.yaml_dict)
# deepcopy didn't work
# Try to use ruamel.yaml and fallback to pyyaml
try:
tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
default_flow_style=False),
yaml.RoundTripLoader)
except AttributeError:
tmp_copy = copy.deepcopy(self.yaml_dict)
# set the format attributes if available
try:
tmp_copy.fa.set_block_style()
except AttributeError:
pass
result = Yedit.add_entry(tmp_copy, path, value, self.separator)
if result is None:
return (False, self.yaml_dict)
# When path equals "" it is a special case.
# "" refers to the root of the document
# Only update the root path (entire document) when its a list or dict
if path == '':
if isinstance(result, list) or isinstance(result, dict):
self.yaml_dict = result
return (True, self.yaml_dict)
return (False, self.yaml_dict)
self.yaml_dict = tmp_copy
return (True, self.yaml_dict)
def create(self, path, value):
''' create a yaml file '''
if not self.file_exists():
# deepcopy didn't work
# Try to use ruamel.yaml and fallback to pyyaml
try:
tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
default_flow_style=False),
yaml.RoundTripLoader)
except AttributeError:
tmp_copy = copy.deepcopy(self.yaml_dict)
# set the format attributes if available
try:
tmp_copy.fa.set_block_style()
except AttributeError:
pass
result = Yedit.add_entry(tmp_copy, path, value, self.separator)
if result is not None:
self.yaml_dict = tmp_copy
return (True, self.yaml_dict)
return (False, self.yaml_dict)
@staticmethod
def get_curr_value(invalue, val_type):
'''return the current value'''
if invalue is None:
return None
curr_value = invalue
if val_type == 'yaml':
curr_value = yaml.load(invalue)
elif val_type == 'json':
curr_value = json.loads(invalue)
return curr_value
@staticmethod
def parse_value(inc_value, vtype=''):
'''determine value type passed'''
true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
'on', 'On', 'ON', ]
false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
'off', 'Off', 'OFF']
# It came in as a string but you didn't specify value_type as string
# we will convert to bool if it matches any of the above cases
if isinstance(inc_value, str) and 'bool' in vtype:
if inc_value not in true_bools and inc_value not in false_bools:
raise YeditException('Not a boolean type. str=[{}] vtype=[{}]'.format(inc_value, vtype))
elif isinstance(inc_value, bool) and 'str' in vtype:
inc_value = str(inc_value)
# There is a special case where '' will turn into None after yaml loading it so skip
if isinstance(inc_value, str) and inc_value == '':
pass
# If vtype is not str then go ahead and attempt to yaml load it.
elif isinstance(inc_value, str) and 'str' not in vtype:
try:
inc_value = yaml.safe_load(inc_value)
except Exception:
raise YeditException('Could not determine type of incoming value. ' +
'value=[{}] vtype=[{}]'.format(type(inc_value), vtype))
return inc_value
@staticmethod
def process_edits(edits, yamlfile):
'''run through a list of edits and process them one-by-one'''
results = []
for edit in edits:
value = Yedit.parse_value(edit['value'], edit.get('value_type', ''))
if edit.get('action') == 'update':
# pylint: disable=line-too-long
curr_value = Yedit.get_curr_value(
Yedit.parse_value(edit.get('curr_value')),
edit.get('curr_value_format'))
rval = yamlfile.update(edit['key'],
value,
edit.get('index'),
curr_value)
elif edit.get('action') == 'append':
rval = yamlfile.append(edit['key'], value)
else:
rval = yamlfile.put(edit['key'], value)
if rval[0]:
results.append({'key': edit['key'], 'edit': rval[1]})
return {'changed': len(results) > 0, 'results': results}
# pylint: disable=too-many-return-statements,too-many-branches
@staticmethod
def run_ansible(params):
'''perform the idempotent crud operations'''
yamlfile = Yedit(filename=params['src'],
backup=params['backup'],
separator=params['separator'])
state = params['state']
if params['src']:
rval = yamlfile.load()
if yamlfile.yaml_dict is None and state != 'present':
return {'failed': True,
'msg': 'Error opening file [{}]. Verify that the '.format(params['src']) +
'file exists, that it is has correct permissions, and is valid yaml.'}
if state == 'list':
if params['content']:
content = Yedit.parse_value(params['content'], params['content_type'])
yamlfile.yaml_dict = content
if params['key']:
rval = yamlfile.get(params['key']) or {}
return {'changed': False, 'result': rval, 'state': state}
elif state == 'absent':
if params['content']:
content = Yedit.parse_value(params['content'], params['content_type'])
yamlfile.yaml_dict = content
if params['update']:
rval = yamlfile.pop(params['key'], params['value'])
else:
rval = yamlfile.delete(params['key'])
if rval[0] and params['src']:
yamlfile.write()
return {'changed': rval[0], 'result': rval[1], 'state': state}
elif state == 'present':
# check if content is different than what is in the file
if params['content']:
content = Yedit.parse_value(params['content'], params['content_type'])
# We had no edits to make and the contents are the same
if yamlfile.yaml_dict == content and \
params['value'] is None:
return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
yamlfile.yaml_dict = content
# If we were passed a key, value then
# we enapsulate it in a list and process it
# Key, Value passed to the module : Converted to Edits list #
edits = []
_edit = {}
if params['value'] is not None:
_edit['value'] = params['value']
_edit['value_type'] = params['value_type']
_edit['key'] = params['key']
if params['update']:
_edit['action'] = 'update'
_edit['curr_value'] = params['curr_value']
_edit['curr_value_format'] = params['curr_value_format']
_edit['index'] = params['index']
elif params['append']:
_edit['action'] = 'append'
edits.append(_edit)
elif params['edits'] is not None:
edits = params['edits']
if edits:
results = Yedit.process_edits(edits, yamlfile)
# if there were changes and a src provided to us we need to write
if results['changed'] and params['src']:
yamlfile.write()
return {'changed': results['changed'], 'result': results['results'], 'state': state}
# no edits to make
if params['src']:
# pylint: disable=redefined-variable-type
rval = yamlfile.write()
return {'changed': rval[0],
'result': rval[1],
'state': state}
# We were passed content but no src, key or value, or edits. Return contents in memory
return {'changed': False, 'result': yamlfile.yaml_dict, 'state': state}
return {'failed': True, 'msg': 'Unkown state passed'}
# -*- -*- -*- End included fragment: ../../lib_utils/src/class/yedit.py -*- -*- -*-
# -*- -*- -*- Begin included fragment: lib/base.py -*- -*- -*-
# pylint: disable=too-many-lines
# noqa: E301,E302,E303,T001
class OpenShiftCLIError(Exception):
'''Exception class for openshiftcli'''
pass
ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
def locate_oc_binary():
''' Find and return oc binary file '''
# https://github.com/openshift/openshift-ansible/issues/3410
# oc can be in /usr/local/bin in some cases, but that may not
# be in $PATH due to ansible/sudo
paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS
oc_binary = 'oc'
# Use shutil.which if it is available, otherwise fallback to a naive path search
try:
which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))
if which_result is not None:
oc_binary = which_result
except AttributeError:
for path in paths:
if os.path.exists(os.path.join(path, oc_binary)):
oc_binary = os.path.join(path, oc_binary)
break
return oc_binary
# pylint: disable=too-few-public-methods
class OpenShiftCLI(object):
''' Class to wrap the command line tools '''
def __init__(self,
namespace,
kubeconfig='/etc/origin/master/admin.kubeconfig',
verbose=False,
all_namespaces=False):
''' Constructor for OpenshiftCLI '''
self.namespace = namespace
self.verbose = verbose
self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig)
self.all_namespaces = all_namespaces
self.oc_binary = locate_oc_binary()
# Pylint allows only 5 arguments to be passed.
# pylint: disable=too-many-arguments
def _replace_content(self, resource, rname, content, force=False, sep='.'):
''' replace the current object with the content '''
res = self._get(resource, rname)
if not res['results']:
return res
fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, res['results'][0], separator=sep)
changes = []
for key, value in content.items():
changes.append(yed.put(key, value))
if any([change[0] for change in changes]):
yed.write()
atexit.register(Utils.cleanup, [fname])
return self._replace(fname, force)
return {'returncode': 0, 'updated': False}
def _replace(self, fname, force=False):
'''replace the current object with oc replace'''
# We are removing the 'resourceVersion' to handle
# a race condition when modifying oc objects
yed = Yedit(fname)
results = yed.delete('metadata.resourceVersion')
if results[0]:
yed.write()
cmd = ['replace', '-f', fname]
if force:
cmd.append('--force')
return self.openshift_cmd(cmd)
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
fname = Utils.create_tmpfile(rname + '-')
yed = Yedit(fname, content=content)
yed.write()
atexit.register(Utils.cleanup, [fname])
return self._create(fname)
def _create(self, fname):
'''call oc create on a filename'''
return self.openshift_cmd(['create', '-f', fname])
def _delete(self, resource, name=None, selector=None):
'''call oc delete on a resource'''
cmd = ['delete', resource]
if selector is not None:
cmd.append('--selector={}'.format(selector))
elif name is not None:
cmd.append(name)
else:
raise OpenShiftCLIError('Either name or selector is required when calling delete.')
return self.openshift_cmd(cmd)
def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501
'''process a template
template_name: the name of the template to process
create: whether to send to oc create after processing
params: the parameters for the template
template_data: the incoming template's data; instead of a file
'''
cmd = ['process']
if template_data:
cmd.extend(['-f', '-'])
else:
cmd.append(template_name)
if params:
param_str = ["{}={}".format(key, str(value).replace("'", r'"')) for key, value in params.items()]
cmd.append('-v')
cmd.extend(param_str)
results = self.openshift_cmd(cmd, output=True, input_data=template_data)
if results['returncode'] != 0 or not create:
return results
fname = Utils.create_tmpfile(template_name + '-')
yed = Yedit(fname, results['results'])
yed.write()
atexit.register(Utils.cleanup, [fname])
return self.openshift_cmd(['create', '-f', fname])
def _get(self, resource, name=None, selector=None):
'''return a resource by name '''
cmd = ['get', resource]
if selector is not None:
cmd.append('--selector={}'.format(selector))
elif name is not None:
cmd.append(name)
cmd.extend(['-o', 'json'])
rval = self.openshift_cmd(cmd, output=True)
# Ensure results are retuned in an array
if 'items' in rval:
rval['results'] = rval['items']
elif not isinstance(rval['results'], list):
rval['results'] = [rval['results']]
return rval
def _schedulable(self, node=None, selector=None, schedulable=True):
''' perform oadm manage-node scheduable '''
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
cmd.append('--schedulable={}'.format(schedulable))
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501
def _list_pods(self, node=None, selector=None, pod_selector=None):
''' perform oadm list pods
node: the node in which to list pods
selector: the label selector filter if provided
pod_selector: the pod selector filter if provided
'''
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
cmd.extend(['--list-pods', '-o', 'json'])
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
# pylint: disable=too-many-arguments
def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False):
''' perform oadm manage-node evacuate '''
cmd = ['manage-node']
if node:
cmd.extend(node)
else:
cmd.append('--selector={}'.format(selector))
if dry_run:
cmd.append('--dry-run')
if pod_selector:
cmd.append('--pod-selector={}'.format(pod_selector))
if grace_period:
cmd.append('--grace-period={}'.format(int(grace_period)))
if force:
cmd.append('--force')
cmd.append('--evacuate')
return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw')
def _version(self):
''' return the openshift version'''
return self.openshift_cmd(['version'], output=True, output_type='raw')
def _import_image(self, url=None, name=None, tag=None):
''' perform image import '''
cmd = ['import-image']
image = '{0}'.format(name)
if tag:
image += ':{0}'.format(tag)
cmd.append(image)
if url:
cmd.append('--from={0}/{1}'.format(url, image))
cmd.append('-n{0}'.format(self.namespace))
cmd.append('--confirm')
return self.openshift_cmd(cmd)
def _run(self, cmds, input_data):
''' Actually executes the command. This makes mocking easier. '''
curr_env = os.environ.copy()
curr_env.update({'KUBECONFIG': self.kubeconfig})
proc = subprocess.Popen(cmds,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=curr_env)
stdout, stderr = proc.communicate(input_data)
return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8')
# pylint: disable=too-many-arguments,too-many-branches
def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None):
'''Base command for oc '''
cmds = [self.oc_binary]
if oadm:
cmds.append('adm')
cmds.extend(cmd)
if self.all_namespaces:
cmds.extend(['--all-namespaces'])
elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501
cmds.extend(['-n', self.namespace])
if self.verbose:
print(' '.join(cmds))
try:
returncode, stdout, stderr = self._run(cmds, input_data)
except OSError as ex:
returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex)
rval = {"returncode": returncode,
"cmd": ' '.join(cmds)}
if output_type == 'json':
rval['results'] = {}
if output and stdout:
try:
rval['results'] = json.loads(stdout)
except ValueError as verr:
if "No JSON object could be decoded" in verr.args:
rval['err'] = verr.args
elif output_type == 'raw':
rval['results'] = stdout if output else ''
if self.verbose:
print("STDOUT: {0}".format(stdout))
print("STDERR: {0}".format(stderr))
if 'err' in rval or returncode != 0:
rval.update({"stderr": stderr,
"stdout": stdout})
return rval
class Utils(object): # pragma: no cover
''' utilities for openshiftcli modules '''
@staticmethod
def _write(filename, contents):
''' Actually write the file contents to disk. This helps with mocking. '''
with open(filename, 'w') as sfd:
sfd.write(contents)
@staticmethod
def create_tmp_file_from_contents(rname, data, ftype='yaml'):
''' create a file in tmp with name and contents'''
tmp = Utils.create_tmpfile(prefix=rname)
if ftype == 'yaml':
# AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
# pylint: disable=no-member
if hasattr(yaml, 'RoundTripDumper'):
Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper))
else:
Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False))
elif ftype == 'json':
Utils._write(tmp, json.dumps(data))
else:
Utils._write(tmp, data)
# Register cleanup when module is done
atexit.register(Utils.cleanup, [tmp])
return tmp
@staticmethod
def create_tmpfile_copy(inc_file):
'''create a temporary copy of a file'''
tmpfile = Utils.create_tmpfile('lib_openshift-')
Utils._write(tmpfile, open(inc_file).read())
# Cleanup the tmpfile
atexit.register(Utils.cleanup, [tmpfile])
return tmpfile
@staticmethod
def create_tmpfile(prefix='tmp'):
''' Generates and returns a temporary file name '''
with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp:
return tmp.name
@staticmethod
def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
path = Utils.create_tmp_file_from_contents(item['path'] + '-',
item['data'],
ftype=content_type)
files.append({'name': os.path.basename(item['path']),
'path': path})
return files
@staticmethod
def cleanup(files):
'''Clean up on exit '''
for sfile in files:
if os.path.exists(sfile):
if os.path.isdir(sfile):
shutil.rmtree(sfile)
elif os.path.isfile(sfile):
os.remove(sfile)
@staticmethod
def exists(results, _name):
''' Check to see if the results include the name '''
if not results:
return False
if Utils.find_result(results, _name):
return True
return False
@staticmethod
def find_result(results, _name):
''' Find the specified result by name'''
rval = None
for result in results:
if 'metadata' in result and result['metadata']['name'] == _name:
rval = result
break
return rval
@staticmethod
def get_resource_file(sfile, sfile_type='yaml'):
''' return the service file '''
contents = None
with open(sfile) as sfd:
contents = sfd.read()
if sfile_type == 'yaml':
# AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage
# pylint: disable=no-member
if hasattr(yaml, 'RoundTripLoader'):
contents = yaml.load(contents, yaml.RoundTripLoader)
else:
contents = yaml.safe_load(contents)
elif sfile_type == 'json':
contents = json.loads(contents)
return contents
@staticmethod
def filter_versions(stdout):
''' filter the oc version output '''
version_dict = {}
version_search = ['oc', 'openshift', 'kubernetes']
for line in stdout.strip().split('\n'):
for term in version_search:
if not line:
continue
if line.startswith(term):
version_dict[term] = line.split()[-1]
# horrible hack to get openshift version in Openshift 3.2
# By default "oc version in 3.2 does not return an "openshift" version
if "openshift" not in version_dict:
version_dict["openshift"] = version_dict["oc"]
return version_dict
@staticmethod
def add_custom_versions(versions):
''' create custom versions strings '''
versions_dict = {}
for tech, version in versions.items():
# clean up "-" from version
if "-" in version:
version = version.split("-")[0]
if version.startswith('v'):
versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
# "v3.3.0.33" is what we have, we want "3.3"
versions_dict[tech + '_short'] = version[1:4]
return versions_dict
@staticmethod
def openshift_installed():
''' check if openshift is installed '''
import rpm
transaction_set = rpm.TransactionSet()
rpmquery = transaction_set.dbMatch("name", "atomic-openshift")
return rpmquery.count() > 0
# Disabling too-many-branches. This is a yaml dictionary comparison function
# pylint: disable=too-many-branches,too-many-return-statements,too-many-statements
@staticmethod
def check_def_equal(user_def, result_def, skip_keys=None, debug=False):
''' Given a user defined definition, compare it with the results given back by our query. '''
# Currently these values are autogenerated and we do not need to check them
skip = ['metadata', 'status']
if skip_keys:
skip.extend(skip_keys)
for key, value in result_def.items():
if key in skip:
continue
# Both are lists
if isinstance(value, list):
if key not in user_def:
if debug:
print('User data does not have key [%s]' % key)
print('User data: %s' % user_def)
return False
if not isinstance(user_def[key], list):
if debug:
print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]))
return False
if len(user_def[key]) != len(value):
if debug:
print("List lengths are not equal.")
print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)))
print("user_def: %s" % user_def[key])
print("value: %s" % value)
return False
for values in zip(user_def[key], value):
if isinstance(values[0], dict) and isinstance(values[1], dict):
if debug:
print('sending list - list')
print(type(values[0]))
print(type(values[1]))
result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug)
if not result:
print('list compare returned false')
return False
elif value != user_def[key]:
if debug:
print('value should be identical')
print(user_def[key])
print(value)
return False
# recurse on a dictionary
elif isinstance(value, dict):
if key not in user_def:
if debug:
print("user_def does not have key [%s]" % key)
return False
if not isinstance(user_def[key], dict):
if debug:
print("dict returned false: not instance of dict")
return False
# before passing ensure keys match
api_values = set(value.keys()) - set(skip)
user_values = set(user_def[key].keys()) - set(skip)
if api_values != user_values:
if debug:
print("keys are not equal in dict")
print(user_values)
print(api_values)
return False
result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug)
if not result:
if debug:
print("dict returned false")
print(result)
return False
# Verify each key, value pair is the same
else:
if key not in user_def or value != user_def[key]:
if debug:
print("value not equal; user_def does not have key")
print(key)
print(value)
if key in user_def:
print(user_def[key])
return False
if debug:
print('returning true')
return True
class OpenShiftCLIConfig(object):
'''Generic Config'''
def __init__(self, rname, namespace, kubeconfig, options):
self.kubeconfig = kubeconfig
self.name = rname
self.namespace = namespace
self._options = options
@property
def config_options(self):
''' return config options '''
return self._options
def to_option_list(self, ascommalist=''):
'''return all options as a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs'''
return self.stringify(ascommalist)
def stringify(self, ascommalist=''):
''' return the options hash as cli params in a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs '''
rval = []
for key in sorted(self.config_options.keys()):
data = self.config_options[key]
if data['include'] \
and (data['value'] or isinstance(data['value'], int)):
if key == ascommalist:
val = ','.join(['{}={}'.format(kk, vv) for kk, vv in sorted(data['value'].items())])
else:
val = data['value']
rval.append('--{}={}'.format(key.replace('_', '-'), val))
return rval
# -*- -*- -*- End included fragment: lib/base.py -*- -*- -*-
# -*- -*- -*- Begin included fragment: lib/deploymentconfig.py -*- -*- -*-
# pylint: disable=too-many-public-methods
class DeploymentConfig(Yedit):
''' Class to model an openshift DeploymentConfig'''
default_deployment_config = '''
apiVersion: v1
kind: DeploymentConfig
metadata:
name: default_dc
namespace: default
spec:
replicas: 0
selector:
default_dc: default_dc
strategy:
resources: {}
rollingParams:
intervalSeconds: 1
maxSurge: 0
maxUnavailable: 25%
timeoutSeconds: 600
updatePercent: -25
updatePeriodSeconds: 1
type: Rolling
template:
metadata:
spec:
containers:
- env:
- name: default
value: default
image: default
imagePullPolicy: IfNotPresent
name: default_dc
ports:
- containerPort: 8000
hostPort: 8000
protocol: TCP
name: default_port
resources: {}
terminationMessagePath: /dev/termination-log
dnsPolicy: ClusterFirst
hostNetwork: true
nodeSelector:
type: compute
restartPolicy: Always
securityContext: {}
serviceAccount: default
serviceAccountName: default
terminationGracePeriodSeconds: 30
triggers:
- type: ConfigChange
'''
replicas_path = "spec.replicas"
env_path = "spec.template.spec.containers[0].env"
volumes_path = "spec.template.spec.volumes"
container_path = "spec.template.spec.containers"
volume_mounts_path = "spec.template.spec.containers[0].volumeMounts"
def __init__(self, content=None):
''' Constructor for deploymentconfig '''
if not content:
content = DeploymentConfig.default_deployment_config
super(DeploymentConfig, self).__init__(content=content)
def add_env_value(self, key, value):
''' add key, value pair to env array '''
rval = False
env = self.get_env_vars()
if env:
env.append({'name': key, 'value': value})
rval = True
else:
result = self.put(DeploymentConfig.env_path, {'name': key, 'value': value})
rval = result[0]
return rval
def exists_env_value(self, key, value):
''' return whether a key, value pair exists '''
results = self.get_env_vars()
if not results:
return False
for result in results:
if result['name'] == key and result['value'] == value:
return True
return False
def exists_env_key(self, key):
''' return whether a key, value pair exists '''
results = self.get_env_vars()
if not results:
return False
for result in results:
if result['name'] == key:
return True
return False
def get_env_var(self, key):
'''return a environment variables '''
results = self.get(DeploymentConfig.env_path) or []
if not results:
return None
for env_var in results:
if env_var['name'] == key:
return env_var
return None
def get_env_vars(self):
'''return a environment variables '''
return self.get(DeploymentConfig.env_path) or []
def delete_env_var(self, keys):
'''delete a list of keys '''
if not isinstance(keys, list):
keys = [keys]
env_vars_array = self.get_env_vars()
modified = False
idx = None
for key in keys:
for env_idx, env_var in enumerate(env_vars_array):
if env_var['name'] == key:
idx = env_idx
break
if idx:
modified = True
del env_vars_array[idx]
if modified:
return True
return False
def update_env_var(self, key, value):
'''place an env in the env var list'''
env_vars_array = self.get_env_vars()
idx = None
for env_idx, env_var in enumerate(env_vars_array):
if env_var['name'] == key:
idx = env_idx
break
if idx:
env_vars_array[idx]['value'] = value
else:
self.add_env_value(key, value)
return True
def exists_volume_mount(self, volume_mount):
''' return whether a volume mount exists '''
exist_volume_mounts = self.get_volume_mounts()
if not exist_volume_mounts:
return False
volume_mount_found = False
for exist_volume_mount in exist_volume_mounts:
if exist_volume_mount['name'] == volume_mount['name']:
volume_mount_found = True
break
return volume_mount_found
def exists_volume(self, volume):
''' return whether a volume exists '''
exist_volumes = self.get_volumes()
volume_found = False
for exist_volume in exist_volumes:
if exist_volume['name'] == volume['name']:
volume_found = True
break
return volume_found
def find_volume_by_name(self, volume, mounts=False):
''' return the index of a volume '''
volumes = []
if mounts:
volumes = self.get_volume_mounts()
else:
volumes = self.get_volumes()
for exist_volume in volumes:
if exist_volume['name'] == volume['name']:
return exist_volume
return None
def get_replicas(self):
''' return replicas setting '''
return self.get(DeploymentConfig.replicas_path)
def get_volume_mounts(self):
'''return volume mount information '''
return self.get_volumes(mounts=True)
def get_volumes(self, mounts=False):
'''return volume mount information '''
if mounts:
return self.get(DeploymentConfig.volume_mounts_path) or []
return self.get(DeploymentConfig.volumes_path) or []
def delete_volume_by_name(self, volume):
'''delete a volume '''
modified = False
exist_volume_mounts = self.get_volume_mounts()
exist_volumes = self.get_volumes()
del_idx = None
for idx, exist_volume in enumerate(exist_volumes):
if 'name' in exist_volume and exist_volume['name'] == volume['name']:
del_idx = idx
break
if del_idx != None:
del exist_volumes[del_idx]
modified = True
del_idx = None
for idx, exist_volume_mount in enumerate(exist_volume_mounts):
if 'name' in exist_volume_mount and exist_volume_mount['name'] == volume['name']:
del_idx = idx
break
if del_idx != None:
del exist_volume_mounts[idx]
modified = True
return modified
def add_volume_mount(self, volume_mount):
''' add a volume or volume mount to the proper location '''
exist_volume_mounts = self.get_volume_mounts()
if not exist_volume_mounts and volume_mount:
self.put(DeploymentConfig.volume_mounts_path, [volume_mount])
else:
exist_volume_mounts.append(volume_mount)
def add_volume(self, volume):
''' add a volume or volume mount to the proper location '''
exist_volumes = self.get_volumes()
if not volume:
return
if not exist_volumes:
self.put(DeploymentConfig.volumes_path, [volume])
else:
exist_volumes.append(volume)
def update_replicas(self, replicas):
''' update replicas value '''
self.put(DeploymentConfig.replicas_path, replicas)
def update_volume(self, volume):
'''place an env in the env var list'''
exist_volumes = self.get_volumes()
if not volume:
return False
# update the volume
update_idx = None
for idx, exist_vol in enumerate(exist_volumes):
if exist_vol['name'] == volume['name']:
update_idx = idx
break
if update_idx != None:
exist_volumes[update_idx] = volume
else:
self.add_volume(volume)
return True
def update_volume_mount(self, volume_mount):
'''place an env in the env var list'''
modified = False
exist_volume_mounts = self.get_volume_mounts()
if not volume_mount:
return False
# update the volume mount
for exist_vol_mount in exist_volume_mounts:
if exist_vol_mount['name'] == volume_mount['name']:
if 'mountPath' in exist_vol_mount and \
str(exist_vol_mount['mountPath']) != str(volume_mount['mountPath']):
exist_vol_mount['mountPath'] = volume_mount['mountPath']
modified = True
break
if not modified:
self.add_volume_mount(volume_mount)
modified = True
return modified
def needs_update_volume(self, volume, volume_mount):
''' verify a volume update is needed '''
exist_volume = self.find_volume_by_name(volume)
exist_volume_mount = self.find_volume_by_name(volume, mounts=True)
results = []
results.append(exist_volume['name'] == volume['name'])
if 'secret' in volume:
results.append('secret' in exist_volume)
results.append(exist_volume['secret']['secretName'] == volume['secret']['secretName'])
results.append(exist_volume_mount['name'] == volume_mount['name'])
results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
elif 'emptyDir' in volume:
results.append(exist_volume_mount['name'] == volume['name'])
results.append(exist_volume_mount['mountPath'] == volume_mount['mountPath'])
elif 'persistentVolumeClaim' in volume:
pvc = 'persistentVolumeClaim'
results.append(pvc in exist_volume)
if results[-1]:
results.append(exist_volume[pvc]['claimName'] == volume[pvc]['claimName'])
if 'claimSize' in volume[pvc]:
results.append(exist_volume[pvc]['claimSize'] == volume[pvc]['claimSize'])
elif 'hostpath' in volume:
results.append('hostPath' in exist_volume)
results.append(exist_volume['hostPath']['path'] == volume_mount['mountPath'])
return not all(results)
def needs_update_replicas(self, replicas):
''' verify whether a replica update is needed '''
current_reps = self.get(DeploymentConfig.replicas_path)
return not current_reps == replicas
# -*- -*- -*- End included fragment: lib/deploymentconfig.py -*- -*- -*-
# -*- -*- -*- Begin included fragment: lib/secret.py -*- -*- -*-
# pylint: disable=too-many-instance-attributes
class SecretConfig(object):
''' Handle secret options '''
# pylint: disable=too-many-arguments
def __init__(self,
sname,
namespace,
kubeconfig,
secrets=None,
stype=None):
''' constructor for handling secret options '''
self.kubeconfig = kubeconfig
self.name = sname
self.type = stype
self.namespace = namespace
self.secrets = secrets
self.data = {}
self.create_dict()
def create_dict(self):
''' assign the correct properties for a secret dict '''
self.data['apiVersion'] = 'v1'
self.data['kind'] = 'Secret'
self.data['type'] = self.type
self.data['metadata'] = {}
self.data['metadata']['name'] = self.name
self.data['metadata']['namespace'] = self.namespace
self.data['data'] = {}
if self.secrets:
for key, value in self.secrets.items():
self.data['data'][key] = value
# pylint: disable=too-many-instance-attributes
class Secret(Yedit):
''' Class to wrap the oc command line tools '''
secret_path = "data"
kind = 'secret'
def __init__(self, content):
'''secret constructor'''
super(Secret, self).__init__(content=content)
self._secrets = None
@property
def secrets(self):
'''secret property getter'''
if self._secrets is None:
self._secrets = self.get_secrets()
return self._secrets
@secrets.setter
def secrets(self):
'''secret property setter'''
if self._secrets is None:
self._secrets = self.get_secrets()
return self._secrets
def get_secrets(self):
''' returns all of the defined secrets '''
return self.get(Secret.secret_path) or {}
def add_secret(self, key, value):
''' add a secret '''
if self.secrets:
self.secrets[key] = value
else:
self.put(Secret.secret_path, {key: value})
return True
def delete_secret(self, key):
''' delete secret'''
try:
del self.secrets[key]
except KeyError as _:
return False
return True
def find_secret(self, key):
''' find secret'''
rval = None
try:
rval = self.secrets[key]
except KeyError as _:
return None
return {'key': key, 'value': rval}
def update_secret(self, key, value):
''' update a secret'''
if key in self.secrets:
self.secrets[key] = value
else:
self.add_secret(key, value)
return True
# -*- -*- -*- End included fragment: lib/secret.py -*- -*- -*-
# -*- -*- -*- Begin included fragment: lib/service.py -*- -*- -*-
# pylint: disable=too-many-instance-attributes
class ServiceConfig(object):
''' Handle service options '''
# pylint: disable=too-many-arguments
def __init__(self,
sname,
namespace,
ports,
selector=None,
labels=None,
cluster_ip=None,
portal_ip=None,
session_affinity=None,
service_type=None,
external_ips=None):
''' constructor for handling service options '''
self.name = sname
self.namespace = namespace
self.ports = ports
self.selector = selector
self.labels = labels
self.cluster_ip = cluster_ip
self.portal_ip = portal_ip
self.session_affinity = session_affinity
self.service_type = service_type
self.external_ips = external_ips
self.data = {}
self.create_dict()
def create_dict(self):
''' instantiates a service dict '''
self.data['apiVersion'] = 'v1'
self.data['kind'] = 'Service'
self.data['metadata'] = {}
self.data['metadata']['name'] = self.name
self.data['metadata']['namespace'] = self.namespace
if self.labels:
self.data['metadata']['labels'] = {}
for lab, lab_value in self.labels.items():
self.data['metadata']['labels'][lab] = lab_value
self.data['spec'] = {}
if self.ports:
self.data['spec']['ports'] = self.ports
else:
self.data['spec']['ports'] = []
if self.selector:
self.data['spec']['selector'] = self.selector
self.data['spec']['sessionAffinity'] = self.session_affinity or 'None'
if self.cluster_ip:
self.data['spec']['clusterIP'] = self.cluster_ip
if self.portal_ip:
self.data['spec']['portalIP'] = self.portal_ip
if self.service_type:
self.data['spec']['type'] = self.service_type
if self.external_ips:
self.data['spec']['externalIPs'] = self.external_ips
# pylint: disable=too-many-instance-attributes,too-many-public-methods
class Service(Yedit):
''' Class to model the oc service object '''
port_path = "spec.ports"
portal_ip = "spec.portalIP"
cluster_ip = "spec.clusterIP"
selector_path = 'spec.selector'
kind = 'Service'
external_ips = "spec.externalIPs"
def __init__(self, content):
'''Service constructor'''
super(Service, self).__init__(content=content)
def get_ports(self):
''' get a list of ports '''
return self.get(Service.port_path) or []
def get_selector(self):
''' get the service selector'''
return self.get(Service.selector_path) or {}
def add_ports(self, inc_ports):
''' add a port object to the ports list '''
if not isinstance(inc_ports, list):
inc_ports = [inc_ports]
ports = self.get_ports()
if not ports:
self.put(Service.port_path, inc_ports)
else:
ports.extend(inc_ports)
return True
def find_ports(self, inc_port):
''' find a specific port '''
for port in self.get_ports():
if port['port'] == inc_port['port']:
return port
return None
def delete_ports(self, inc_ports):
''' remove a port from a service '''
if not isinstance(inc_ports, list):
inc_ports = [inc_ports]
ports = self.get(Service.port_path) or []
if not ports:
return True
removed = False
for inc_port in inc_ports:
port = self.find_ports(inc_port)
if port:
ports.remove(port)
removed = True
return removed
def add_cluster_ip(self, sip):
'''add cluster ip'''
self.put(Service.cluster_ip, sip)
def add_portal_ip(self, pip):
'''add cluster ip'''
self.put(Service.portal_ip, pip)
def get_external_ips(self):
''' get a list of external_ips '''
return self.get(Service.external_ips) or []
def add_external_ips(self, inc_external_ips):
''' add an external_ip to the external_ips list '''
if not isinstance(inc_external_ips, list):
inc_external_ips = [inc_external_ips]
external_ips = self.get_external_ips()
if not external_ips:
self.put(Service.external_ips, inc_external_ips)
else:
external_ips.extend(inc_external_ips)
return True
def find_external_ips(self, inc_external_ip):
''' find a specific external IP '''
val = None
try:
idx = self.get_external_ips().index(inc_external_ip)
val = self.get_external_ips()[idx]
except ValueError:
pass
return val
def delete_external_ips(self, inc_external_ips):
''' remove an external IP from a service '''
if not isinstance(inc_external_ips, list):
inc_external_ips = [inc_external_ips]
external_ips = self.get(Service.external_ips) or []
if not external_ips:
return True
removed = False
for inc_external_ip in inc_external_ips:
external_ip = self.find_external_ips(inc_external_ip)
if external_ip:
external_ips.remove(external_ip)
removed = True
return removed
# -*- -*- -*- End included fragment: lib/service.py -*- -*- -*-
# -*- -*- -*- Begin included fragment: lib/volume.py -*- -*- -*-
class Volume(object):
''' Class to represent an openshift volume object'''
volume_mounts_path = {"pod": "spec.containers[0].volumeMounts",
"dc": "spec.template.spec.containers[0].volumeMounts",
"rc": "spec.template.spec.containers[0].volumeMounts",
}
volumes_path = {"pod": "spec.volumes",
"dc": "spec.template.spec.volumes",
"rc": "spec.template.spec.volumes",
}
@staticmethod
def create_volume_structure(volume_info):
''' return a properly structured volume '''
volume_mount = None
volume = {'name': volume_info['name']}
volume_type = volume_info['type'].lower()
if volume_type == 'secret':
volume['secret'] = {}
volume[volume_info['type']] = {'secretName': volume_info['secret_name']}
volume_mount = {'mountPath': volume_info['path'],
'name': volume_info['name']}
elif volume_type == 'emptydir':
volume['emptyDir'] = {}
volume_mount = {'mountPath': volume_info['path'],
'name': volume_info['name']}
elif volume_type == 'pvc' or volume_type == 'persistentvolumeclaim':
volume['persistentVolumeClaim'] = {}
volume['persistentVolumeClaim']['claimName'] = volume_info['claimName']
volume['persistentVolumeClaim']['claimSize'] = volume_info['claimSize']
elif volume_type == 'hostpath':
volume['hostPath'] = {}
volume['hostPath']['path'] = volume_info['path']
elif volume_type == 'configmap':
volume['configMap'] = {}
volume['configMap']['name'] = volume_info['configmap_name']
volume_mount = {'mountPath': volume_info['path'],
'name': volume_info['name']}
return (volume, volume_mount)
# -*- -*- -*- End included fragment: lib/volume.py -*- -*- -*-
# -*- -*- -*- Begin included fragment: class/oc_version.py -*- -*- -*-
# pylint: disable=too-many-instance-attributes
class OCVersion(OpenShiftCLI):
''' Class to wrap the oc command line tools '''
# pylint allows 5
# pylint: disable=too-many-arguments
def __init__(self,
config,
debug):
''' Constructor for OCVersion '''
super(OCVersion, self).__init__(None, config)
self.debug = debug
def get(self):
'''get and return version information '''
results = {}
version_results = self._version()
if version_results['returncode'] == 0:
filtered_vers = Utils.filter_versions(version_results['results'])
custom_vers = Utils.add_custom_versions(filtered_vers)
results['returncode'] = version_results['returncode']
results.update(filtered_vers)
results.update(custom_vers)
return results
raise OpenShiftCLIError('Problem detecting openshift version.')
@staticmethod
def run_ansible(params):
'''run the idempotent ansible code'''
oc_version = OCVersion(params['kubeconfig'], params['debug'])
if params['state'] == 'list':
#pylint: disable=protected-access
result = oc_version.get()
return {'state': params['state'],
'results': result,
'changed': False}
# -*- -*- -*- End included fragment: class/oc_version.py -*- -*- -*-
# -*- -*- -*- Begin included fragment: class/oc_adm_registry.py -*- -*- -*-
class RegistryException(Exception):
''' Registry Exception Class '''
pass
class RegistryConfig(OpenShiftCLIConfig):
''' RegistryConfig is a DTO for the registry. '''
def __init__(self, rname, namespace, kubeconfig, registry_options):
super(RegistryConfig, self).__init__(rname, namespace, kubeconfig, registry_options)
class Registry(OpenShiftCLI):
''' Class to wrap the oc command line tools '''
volume_mount_path = 'spec.template.spec.containers[0].volumeMounts'
volume_path = 'spec.template.spec.volumes'
env_path = 'spec.template.spec.containers[0].env'
def __init__(self,
registry_config,
verbose=False):
''' Constructor for Registry
a registry consists of 3 or more parts
- dc/docker-registry
- svc/docker-registry
Parameters:
:registry_config:
:verbose:
'''
super(Registry, self).__init__(registry_config.namespace, registry_config.kubeconfig, verbose)
self.version = OCVersion(registry_config.kubeconfig, verbose)
self.svc_ip = None
self.portal_ip = None
self.config = registry_config
self.verbose = verbose
self.registry_parts = [{'kind': 'dc', 'name': self.config.name},
{'kind': 'svc', 'name': self.config.name},
]
self.__prepared_registry = None
self.volume_mounts = []
self.volumes = []
if self.config.config_options['volume_mounts']['value']:
for volume in self.config.config_options['volume_mounts']['value']:
volume_info = {'secret_name': volume.get('secret_name', None),
'name': volume.get('name', None),
'type': volume.get('type', None),
'path': volume.get('path', None),
'claimName': volume.get('claim_name', None),
'claimSize': volume.get('claim_size', None),
}
vol, vol_mount = Volume.create_volume_structure(volume_info)
self.volumes.append(vol)
self.volume_mounts.append(vol_mount)
self.dconfig = None
self.svc = None
@property
def deploymentconfig(self):
''' deploymentconfig property '''
return self.dconfig
@deploymentconfig.setter
def deploymentconfig(self, config):
''' setter for deploymentconfig property '''
self.dconfig = config
@property
def service(self):
''' service property '''
return self.svc
@service.setter
def service(self, config):
''' setter for service property '''
self.svc = config
@property
def prepared_registry(self):
''' prepared_registry property '''
if not self.__prepared_registry:
results = self.prepare_registry()
if not results or ('returncode' in results and results['returncode'] != 0):
raise RegistryException('Could not perform registry preparation. {}'.format(results))
self.__prepared_registry = results
return self.__prepared_registry
@prepared_registry.setter
def prepared_registry(self, data):
''' setter method for prepared_registry attribute '''
self.__prepared_registry = data
def get(self):
''' return the self.registry_parts '''
self.deploymentconfig = None
self.service = None
rval = 0
for part in self.registry_parts:
result = self._get(part['kind'], name=part['name'])
if result['returncode'] == 0 and part['kind'] == 'dc':
self.deploymentconfig = DeploymentConfig(result['results'][0])
elif result['returncode'] == 0 and part['kind'] == 'svc':
self.service = Service(result['results'][0])
if result['returncode'] != 0:
rval = result['returncode']
return {'returncode': rval, 'deploymentconfig': self.deploymentconfig, 'service': self.service}
def exists(self):
'''does the object exist?'''
if self.deploymentconfig and self.service:
return True
return False
def delete(self, complete=True):
'''return all pods '''
parts = []
for part in self.registry_parts:
if not complete and part['kind'] == 'svc':
continue
parts.append(self._delete(part['kind'], part['name']))
# Clean up returned results
rval = 0
for part in parts:
# pylint: disable=invalid-sequence-index
if 'returncode' in part and part['returncode'] != 0:
rval = part['returncode']
return {'returncode': rval, 'results': parts}
def prepare_registry(self):
''' prepare a registry for instantiation '''
options = self.config.to_option_list(ascommalist='labels')
cmd = ['registry']
cmd.extend(options)
cmd.extend(['--dry-run=True', '-o', 'json'])
results = self.openshift_cmd(cmd, oadm=True, output=True, output_type='json')
# probably need to parse this
# pylint thinks results is a string
# pylint: disable=no-member
if results['returncode'] != 0 and 'items' not in results['results']:
raise RegistryException('Could not perform registry preparation. {}'.format(results))
service = None
deploymentconfig = None
# pylint: disable=invalid-sequence-index
for res in results['results']['items']:
if res['kind'] == 'DeploymentConfig':
deploymentconfig = DeploymentConfig(res)
elif res['kind'] == 'Service':
service = Service(res)
# Verify we got a service and a deploymentconfig
if not service or not deploymentconfig:
return results
# results will need to get parsed here and modifications added
deploymentconfig = DeploymentConfig(self.add_modifications(deploymentconfig))
# modify service ip
if self.svc_ip:
service.put('spec.clusterIP', self.svc_ip)
if self.portal_ip:
service.put('spec.portalIP', self.portal_ip)
# the dry-run doesn't apply the selector correctly
if self.service:
service.put('spec.selector', self.service.get_selector())
# need to create the service and the deploymentconfig
service_file = Utils.create_tmp_file_from_contents('service', service.yaml_dict)
deployment_file = Utils.create_tmp_file_from_contents('deploymentconfig', deploymentconfig.yaml_dict)
return {"service": service,
"service_file": service_file,
"service_update": False,
"deployment": deploymentconfig,
"deployment_file": deployment_file,
"deployment_update": False}
def create(self):
'''Create a registry'''
results = []
self.needs_update()
# if the object is none, then we need to create it
# if the object needs an update, then we should call replace
# Handle the deploymentconfig
if self.deploymentconfig is None:
results.append(self._create(self.prepared_registry['deployment_file']))
elif self.prepared_registry['deployment_update']:
results.append(self._replace(self.prepared_registry['deployment_file']))
# Handle the service
if self.service is None:
results.append(self._create(self.prepared_registry['service_file']))
elif self.prepared_registry['service_update']:
results.append(self._replace(self.prepared_registry['service_file']))
# Clean up returned results
rval = 0
for result in results:
# pylint: disable=invalid-sequence-index
if 'returncode' in result and result['returncode'] != 0:
rval = result['returncode']
return {'returncode': rval, 'results': results}
def update(self):
'''run update for the registry. This performs a replace if required'''
# Store the current service IP
if self.service:
svcip = self.service.get('spec.clusterIP')
if svcip:
self.svc_ip = svcip
portip = self.service.get('spec.portalIP')
if portip:
self.portal_ip = portip
results = []
if self.prepared_registry['deployment_update']:
results.append(self._replace(self.prepared_registry['deployment_file']))
if self.prepared_registry['service_update']:
results.append(self._replace(self.prepared_registry['service_file']))
# Clean up returned results
rval = 0
for result in results:
if result['returncode'] != 0:
rval = result['returncode']
return {'returncode': rval, 'results': results}
def add_modifications(self, deploymentconfig):
''' update a deployment config with changes '''
# The environment variable for REGISTRY_HTTP_SECRET is autogenerated
# We should set the generated deploymentconfig to the in memory version
# the following modifications will overwrite if needed
if self.deploymentconfig:
result = self.deploymentconfig.get_env_var('REGISTRY_HTTP_SECRET')
if result:
deploymentconfig.update_env_var('REGISTRY_HTTP_SECRET', result['value'])
# Currently we know that our deployment of a registry requires a few extra modifications
# Modification 1
# we need specific environment variables to be set
for key, value in self.config.config_options['env_vars'].get('value', {}).items():
if not deploymentconfig.exists_env_key(key):
deploymentconfig.add_env_value(key, value)
else:
deploymentconfig.update_env_var(key, value)
# Modification 2
# we need specific volume variables to be set
for volume in self.volumes:
deploymentconfig.update_volume(volume)
for vol_mount in self.volume_mounts:
deploymentconfig.update_volume_mount(vol_mount)
# Modification 3
# Edits
edit_results = []
for edit in self.config.config_options['edits'].get('value', []):
if edit['action'] == 'put':
edit_results.append(deploymentconfig.put(edit['key'],
edit['value']))
if edit['action'] == 'update':
edit_results.append(deploymentconfig.update(edit['key'],
edit['value'],
edit.get('index', None),
edit.get('curr_value', None)))
if edit['action'] == 'append':
edit_results.append(deploymentconfig.append(edit['key'],
edit['value']))
if edit_results and not any([res[0] for res in edit_results]):
return None
return deploymentconfig.yaml_dict
def needs_update(self):
''' check to see if we need to update '''
exclude_list = ['clusterIP', 'portalIP', 'type', 'protocol']
if self.service is None or \
not Utils.check_def_equal(self.prepared_registry['service'].yaml_dict,
self.service.yaml_dict,
exclude_list,
debug=self.verbose):
self.prepared_registry['service_update'] = True
exclude_list = ['dnsPolicy',
'terminationGracePeriodSeconds',
'restartPolicy', 'timeoutSeconds',
'livenessProbe', 'readinessProbe',
'terminationMessagePath',
'securityContext',
'imagePullPolicy',
'protocol', # ports.portocol: TCP
'type', # strategy: {'type': 'rolling'}
'defaultMode', # added on secrets
'activeDeadlineSeconds', # added in 1.5 for timeouts
]
if self.deploymentconfig is None or \
not Utils.check_def_equal(self.prepared_registry['deployment'].yaml_dict,
self.deploymentconfig.yaml_dict,
exclude_list,
debug=self.verbose):
self.prepared_registry['deployment_update'] = True
return self.prepared_registry['deployment_update'] or self.prepared_registry['service_update'] or False
# In the future, we would like to break out each ansible state into a function.
# pylint: disable=too-many-branches,too-many-return-statements
@staticmethod
def run_ansible(params, check_mode):
'''run idempotent ansible code'''
registry_options = {'images': {'value': params['images'], 'include': True},
'latest_images': {'value': params['latest_images'], 'include': True},
'labels': {'value': params['labels'], 'include': True},
'ports': {'value': ','.join(params['ports']), 'include': True},
'replicas': {'value': params['replicas'], 'include': True},
'selector': {'value': params['selector'], 'include': True},
'service_account': {'value': params['service_account'], 'include': True},
'mount_host': {'value': params['mount_host'], 'include': True},
'env_vars': {'value': params['env_vars'], 'include': False},
'volume_mounts': {'value': params['volume_mounts'], 'include': False},
'edits': {'value': params['edits'], 'include': False},
'tls_key': {'value': params['tls_key'], 'include': True},
'tls_certificate': {'value': params['tls_certificate'], 'include': True},
}
# Do not always pass the daemonset and enforce-quota parameters because they are not understood
# by old versions of oc.
# Default value is false. So, it's safe to not pass an explicit false value to oc versions which
# understand these parameters.
if params['daemonset']:
registry_options['daemonset'] = {'value': params['daemonset'], 'include': True}
if params['enforce_quota']:
registry_options['enforce_quota'] = {'value': params['enforce_quota'], 'include': True}
rconfig = RegistryConfig(params['name'],
params['namespace'],
params['kubeconfig'],
registry_options)
ocregistry = Registry(rconfig, params['debug'])
api_rval = ocregistry.get()
state = params['state']
########
# get
########
if state == 'list':
if api_rval['returncode'] != 0:
return {'failed': True, 'msg': api_rval}
return {'changed': False, 'results': api_rval, 'state': state}
########
# Delete
########
if state == 'absent':
if not ocregistry.exists():
return {'changed': False, 'state': state}
if check_mode:
return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a delete.'}
# Unsure as to why this is angry with the return type.
# pylint: disable=redefined-variable-type
api_rval = ocregistry.delete()
if api_rval['returncode'] != 0:
return {'failed': True, 'msg': api_rval}
return {'changed': True, 'results': api_rval, 'state': state}
if state == 'present':
########
# Create
########
if not ocregistry.exists():
if check_mode:
return {'changed': True, 'msg': 'CHECK_MODE: Would have performed a create.'}
api_rval = ocregistry.create()
if api_rval['returncode'] != 0:
return {'failed': True, 'msg': api_rval}
return {'changed': True, 'results': api_rval, 'state': state}
########
# Update
########
if not params['force'] and not ocregistry.needs_update():
return {'changed': False, 'state': state}
if check_mode:
return {'changed': True, 'msg': 'CHECK_MODE: Would have performed an update.'}
api_rval = ocregistry.update()
if api_rval['returncode'] != 0:
return {'failed': True, 'msg': api_rval}
return {'changed': True, 'results': api_rval, 'state': state}
return {'failed': True, 'msg': 'Unknown state passed. %s' % state}
# -*- -*- -*- End included fragment: class/oc_adm_registry.py -*- -*- -*-
# -*- -*- -*- Begin included fragment: ansible/oc_adm_registry.py -*- -*- -*-
def main():
'''
ansible oc module for registry
'''
module = AnsibleModule(
argument_spec=dict(
state=dict(default='present', type='str',
choices=['present', 'absent']),
debug=dict(default=False, type='bool'),
namespace=dict(default='default', type='str'),
name=dict(default=None, required=True, type='str'),
kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
images=dict(default=None, type='str'),
latest_images=dict(default=False, type='bool'),
labels=dict(default=None, type='dict'),
ports=dict(default=['5000'], type='list'),
replicas=dict(default=1, type='int'),
selector=dict(default=None, type='str'),
service_account=dict(default='registry', type='str'),
mount_host=dict(default=None, type='str'),
volume_mounts=dict(default=None, type='list'),
env_vars=dict(default={}, type='dict'),
edits=dict(default=[], type='list'),
enforce_quota=dict(default=False, type='bool'),
force=dict(default=False, type='bool'),
daemonset=dict(default=False, type='bool'),
tls_key=dict(default=None, type='str'),
tls_certificate=dict(default=None, type='str'),
),
supports_check_mode=True,
)
results = Registry.run_ansible(module.params, module.check_mode)
if 'failed' in results:
module.fail_json(**results)
module.exit_json(**results)
if __name__ == '__main__':
main()
# -*- -*- -*- End included fragment: ansible/oc_adm_registry.py -*- -*- -*-
| {
"content_hash": "07fefed3f875876e0d2b42e10fc169c5",
"timestamp": "",
"source": "github",
"line_count": 2714,
"max_line_length": 118,
"avg_line_length": 34.16691230655859,
"alnum_prop": 0.5456976781805045,
"repo_name": "twiest/openshift-tools",
"id": "c00eee381b696fe4611af9f9f9e8573cdee069ea",
"size": "93891",
"binary": false,
"copies": "7",
"ref": "refs/heads/stg",
"path": "openshift/installer/vendored/openshift-ansible-3.6.173.0.59/roles/lib_openshift/library/oc_adm_registry.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "588"
},
{
"name": "Go",
"bytes": "382164"
},
{
"name": "Groovy",
"bytes": "6322"
},
{
"name": "HTML",
"bytes": "102550"
},
{
"name": "JavaScript",
"bytes": "1580"
},
{
"name": "Makefile",
"bytes": "3324"
},
{
"name": "PHP",
"bytes": "35793"
},
{
"name": "Python",
"bytes": "27786029"
},
{
"name": "Shell",
"bytes": "1378677"
},
{
"name": "Vim script",
"bytes": "1836"
}
],
"symlink_target": ""
} |
package ru.job4j.models;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import org.junit.Before;
//import org.junit.Ignore;
import org.junit.Test;
/**
* Класс CarTest тестирует класс Car.
*
* @author Goureev Ilya (mailto:ill-jah@yandex.ru)
* @version 2019-05-30
* @since 2018-04-26
*/
public class CarTest {
/**
* Брэнд.
*/
private Brand brand;
/**
* Автомобиль.
*/
private Car car;
/**
* Действия перед тестом.
*/
@Before
public void beforeTest() {
Founder f = new Founder(0L, "ЦК КПСС", "Совет министров СССР");
this.brand = new Brand(0L, "ВАЗ", f);
this.car = new Car(0L, "Vesta", new ArrayList<>(), this.brand);
}
/**
* Тестирует public boolean equals(Object obj).
*/
@Test
public void testEquals() {
Car expected = new Car(0L, "Vesta", new ArrayList<>(), this.brand);
assertEquals(expected, this.car);
}
/**
* Тестирует public boolean equals(Object obj).
* 2 ссылки на один объект.
*/
@Test
public void testEquals2refsOfOneObject() {
Car obj = this.car;
assertEquals(obj, this.car);
}
/**
* Тестирует public boolean equals(Object obj).
* Сравнение с null.
*/
@Test
public void testEqualsWithNull() {
Car car = null;
assertFalse(this.car.equals(car));
}
/**
* Тестирует public boolean equals(Object obj).
* Сравнение объектов разных классов.
*/
@Test
public void testEqualsWithDifferentClasses() {
assertFalse(this.car.equals(""));
}
/**
* Тестирует public boolean equals(Object obj).
* Разные id.
*/
@Test
public void testEqualsDifferentIds() {
Car expected = new Car(100500L, "Vesta", new ArrayList<>(), this.brand);
assertFalse(expected.equals(this.car));
}
/**
* Тестирует public boolean equals(Object obj).
* Разные name.
*/
@Test
public void testEqualsDifferentNames() {
Car expected = new Car(0L, "NeVesta", new ArrayList<>(), this.brand);
assertFalse(expected.equals(this.car));
}
/**
* Тестирует public boolean equals(Object obj).
* Разные bodies.
*/
@Test
public void testEqualsDifferentBodies() {
List<Body> bodies = new ArrayList<>();
bodies.add(new Body(1L, "sedan"));
bodies.add(new Body(2L, "hatchback"));
Car expected = new Car(0L, "NeVesta", bodies, this.brand);
assertFalse(expected.equals(this.car));
}
/**
* Тестирует public List<Body> getBodies().
*/
@Test
public void testGetBodies() {
List<Body> bodies = new ArrayList<>();
bodies.add(new Body(1L, "sedan"));
bodies.add(new Body(2L, "hatchback"));
this.car.setBodies(bodies);
assertEquals("hatchback", this.car.getBodies().get(1).getName());
}
/**
* Тестирует public int hashCode().
*/
@Test
public void testHashCode() {
int expected = Objects.hash(0, "Vesta", new ArrayList<>(), this.brand);
int actual = this.car.hashCode();
assertEquals(expected, actual);
}
/**
* Тестирует public String toString().
*/
@Test
public void testToString() {
List<Body> bodies = new ArrayList<>();
bodies.add(new Body(1L, "sedan"));
Founder f = new Founder(0L, "ЦК КПСС", "Совет министров СССР");
Car car = new Car();
car.setId(0L);
car.setName("Vesta");
car.setBodies(bodies);
car.setBrand(new Brand(0L, "ВАЗ", f));
assertEquals("Car[id: 0, name: Vesta, bodies:[Body[id: 1, name: sedan]], brand: Brand[id: 0, name: ВАЗ, founder: Founder[id: 0, nameLast: ЦК КПСС, name: Совет министров СССР]]]", car.toString());
}
} | {
"content_hash": "81cdc8570cd190281f01c09f3cc6f9ba",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 203,
"avg_line_length": 29.192592592592593,
"alnum_prop": 0.5899517888860695,
"repo_name": "multiscripter/job4j",
"id": "c50ee0dc62c2fb8b857e2ed9cc4ef0bb6a34dacb",
"size": "4241",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "junior/pack3_pre/p2_spring/ch3_crudRepo/src/test/java/ru/job4j/models/CarTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "24873"
},
{
"name": "Java",
"bytes": "3798662"
},
{
"name": "JavaScript",
"bytes": "14668"
},
{
"name": "XSLT",
"bytes": "366"
}
],
"symlink_target": ""
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.FileProviders;
namespace Microsoft.AspNetCore.Grpc.Swagger.Tests.Infrastructure;
internal class TestWebHostEnvironment : IWebHostEnvironment
{
public IFileProvider WebRootFileProvider { get; set; }
public string WebRootPath { get; set; }
public string ApplicationName { get; set; }
public IFileProvider ContentRootFileProvider { get; set; }
public string ContentRootPath { get; set; }
public string EnvironmentName { get; set; }
}
| {
"content_hash": "6e5fd483cfffaadd41ccb9c60b68d82d",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 71,
"avg_line_length": 38.76470588235294,
"alnum_prop": 0.7663125948406677,
"repo_name": "aspnet/AspNetCore",
"id": "ecb8a5e089d6c86124e0006eb47a92ce31b7d3c5",
"size": "661",
"binary": false,
"copies": "1",
"ref": "refs/heads/darc-main-3ce916a7-9d9b-4849-8f14-6703adcb3cb2",
"path": "src/Grpc/JsonTranscoding/test/Microsoft.AspNetCore.Grpc.Swagger.Tests/Infrastructure/TestWebHostEnvironment.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "109"
},
{
"name": "Batchfile",
"bytes": "19526"
},
{
"name": "C",
"bytes": "213916"
},
{
"name": "C#",
"bytes": "47455169"
},
{
"name": "C++",
"bytes": "1900454"
},
{
"name": "CMake",
"bytes": "7955"
},
{
"name": "CSS",
"bytes": "62326"
},
{
"name": "Dockerfile",
"bytes": "3584"
},
{
"name": "F#",
"bytes": "7982"
},
{
"name": "Groovy",
"bytes": "1529"
},
{
"name": "HTML",
"bytes": "1130653"
},
{
"name": "Java",
"bytes": "297552"
},
{
"name": "JavaScript",
"bytes": "2726829"
},
{
"name": "Lua",
"bytes": "4904"
},
{
"name": "Makefile",
"bytes": "220"
},
{
"name": "Objective-C",
"bytes": "222"
},
{
"name": "PowerShell",
"bytes": "241706"
},
{
"name": "Python",
"bytes": "19476"
},
{
"name": "Roff",
"bytes": "6044"
},
{
"name": "Shell",
"bytes": "142293"
},
{
"name": "Smalltalk",
"bytes": "3"
},
{
"name": "TypeScript",
"bytes": "797435"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ltl: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.0 / ltl - 8.8.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
ltl
<small>
8.8.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-07-19 01:29:24 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-07-19 01:29:24 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.7.0 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.03.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.03.0 Official 4.03.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/ltl"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/LTL"]
depends: [
"ocaml"
"coq" {>= "8.8" & < "8.9~"}
]
tags: [ "keyword: temporal logic" "keyword: infinite transition systems" "keyword: co-induction" "category: Mathematics/Logic/Modal logic" "date: 2002-07" ]
authors: [ "Solange Coupet-Grimal" ]
bug-reports: "https://github.com/coq-contribs/ltl/issues"
dev-repo: "git+https://github.com/coq-contribs/ltl.git"
synopsis: "Linear Temporal Logic"
description: """
This contribution contains a shallow embedding of Linear
Temporal Logic (LTL) based on a co-inductive representation of program
executions. Temporal operators are implemented as inductive
(respectively co-inductive) types when they are least (respectively
greatest) fixpoints. Several general lemmas,
that correspond to LTL rules, are proved."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/ltl/archive/v8.8.0.tar.gz"
checksum: "md5=ff962e4cd2f33b0a9ed4f551fa2ce02d"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-ltl.8.8.0 coq.8.7.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.0).
The following dependencies couldn't be met:
- coq-ltl -> coq >= 8.8 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-ltl.8.8.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "4f2281848d4d943a862e07757a99b546",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 206,
"avg_line_length": 42.187134502923975,
"alnum_prop": 0.5497643471028556,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "b158bce26f3e95a3fc062fa4943a9216c8a41839",
"size": "7239",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.03.0-2.0.5/released/8.7.0/ltl/8.8.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents the root node of a structured trivia tree (for example, a preprocessor directive
/// or a documentation comment). From this root node you can traverse back up to the containing
/// trivia in the outer tree that contains it.
/// </summary>
public interface IStructuredTriviaSyntax
{
/// <summary>
/// Returns the parent trivia syntax for this structured trivia syntax.
/// </summary>
/// <returns>The parent trivia syntax for this structured trivia syntax.</returns>
SyntaxTrivia ParentTrivia { get; }
}
} | {
"content_hash": "62947b5dca907356bab09b46898b43f1",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 184,
"avg_line_length": 45.888888888888886,
"alnum_prop": 0.6912832929782082,
"repo_name": "binsys/roslyn_java",
"id": "3ffd60d5b1a8a883aefe1be401962ed89deb243e",
"size": "828",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Src/Compilers/Core/Source/Syntax/IStructuredTriviaSyntax.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5789"
},
{
"name": "C#",
"bytes": "10877035"
},
{
"name": "Java",
"bytes": "47225"
},
{
"name": "Visual Basic",
"bytes": "58529"
}
],
"symlink_target": ""
} |
package loon.font;
import loon.LSysException;
import loon.LSystem;
import loon.canvas.Canvas;
import loon.canvas.Image;
import loon.canvas.LColor;
import loon.font.Font.Style;
import loon.geom.PointF;
import loon.geom.PointI;
import loon.geom.Vector2f;
import loon.opengl.GLEx;
import loon.opengl.LSTRDictionary;
import loon.opengl.LTexturePack;
import loon.opengl.LTexturePack.PackEntry;
import loon.utils.IntMap;
import loon.utils.MathUtils;
import loon.utils.StringKeyValue;
import loon.utils.StringUtils;
/**
* Loon内置的Font实现,当用户无自定义IFont时,默认使用此类实现文字渲染
*/
public class LFont implements IFont {
public static LFont getDefaultFont() {
return newFont();
}
public static LFont newFont() {
return newFont(20);
}
public static LFont newFont(int size) {
return LFont.getFont(LSystem.getSystemGameFontName(), Style.PLAIN, size);
}
/*
* 获得一个默认的LFont.
*
* 比如:
*
* 游戏全局使用默认LFont(除log字体外,log字体需要设置setSystemLogFont)
*
* LSystem.setSystemGameFont(LFont.getDefaultFont());
*
*/
private IntMap<Vector2f> fontSizes = new IntMap<Vector2f>(50);
private final static String tmp = "H";
private String lastText = tmp;
private PointI _offset = new PointI();
private TextFormat textFormat = null;
private TextLayout textLayout = null;
private int _size = -1;
private float _ascent = -1;
private boolean useCache, closed;
public boolean isUseCache() {
return useCache;
}
public void setUseCache(boolean u) {
this.useCache = u;
}
LFont() {
this(LSystem.getSystemGameFontName(), Style.PLAIN, 20, true);
}
LFont(String name, Style style, int size, boolean antialias) {
if (StringUtils.isEmpty(name)) {
throw new LSysException("Font name is null !");
}
this.textFormat = new TextFormat(new Font(name, style, MathUtils.max(1, size)), antialias);
LSystem.pushFontPool(this);
}
public static LFont getFont(int size) {
return LFont.getFont(LSystem.getSystemGameFontName(), size);
}
public static LFont getFont(String familyName, int size) {
return new LFont(familyName, Style.PLAIN, size, true);
}
public static LFont getFont(String familyName, int styleType, int size) {
Style style = Style.PLAIN;
switch (styleType) {
default:
case 0:
style = Style.PLAIN;
break;
case 1:
style = Style.BOLD;
break;
case 2:
style = Style.ITALIC;
break;
case 3:
style = Style.BOLD_ITALIC;
break;
}
return new LFont(familyName, style, size, true);
}
public static LFont getFont(String familyName, Style style, int size) {
return new LFont(familyName, style, size, true);
}
public static LFont getFont(String familyName, Style style, int size, boolean antialias) {
return new LFont(familyName, style, size, antialias);
}
public TextFormat getFormat() {
return textFormat;
}
public TextLayout getTextLayout() {
return textLayout;
}
@Override
public void drawString(GLEx g, String chars, float tx, float ty) {
drawString(g, chars, tx, ty, LColor.white);
}
@Override
public void drawString(GLEx g, String chars, float tx, float ty, LColor c) {
drawString(g, chars, tx, ty, 0, c);
}
@Override
public void drawString(GLEx g, String chars, float tx, float ty, float angle, LColor c) {
if (c == null || c.a <= 0.01) {
return;
}
if (StringUtils.isEmpty(chars)) {
return;
}
if (useCache) {
LSTRDictionary.get().drawString(this, chars, _offset.x + tx, _offset.y + ty, angle, c);
} else {
LSTRDictionary.get().drawString(g, this, chars, _offset.x + tx, _offset.y + ty, angle, c);
}
}
@Override
public void drawString(GLEx g, String chars, float tx, float ty, float sx, float sy, float ax, float ay,
float angle, LColor c) {
if (c == null || c.a <= 0.01) {
return;
}
if (StringUtils.isEmpty(chars)) {
return;
}
if (useCache) {
LSTRDictionary.get().drawString(this, chars, _offset.x + tx, _offset.y + ty, sx, sy, ax, ay, angle, c);
} else {
LSTRDictionary.get().drawString(g, this, chars, _offset.x + tx, _offset.y + ty, sx, sy, ax, ay, angle, c);
}
}
private void initLayout(String text) {
if (LSystem.base() == null) {
return;
}
if (text == null || textLayout == null || !text.equals(lastText)) {
textLayout = LSystem.base().graphics().layoutText(tmp, this.textFormat);
}
}
@Override
public int charWidth(char ch) {
if (LSystem.base() == null) {
return 0;
}
initLayout(String.valueOf(ch));
return textLayout.bounds.width;
}
@Override
public int stringWidth(String message) {
if (LSystem.base() == null || StringUtils.isEmpty(message)) {
return 0;
}
initLayout(message);
if (message.indexOf('\n') == -1) {
return textLayout.stringWidth(message);
} else {
StringBuffer sbr = new StringBuffer();
int width = 0;
for (int i = 0, size = message.length(); i < size; i++) {
char ch = message.charAt(i);
if (ch == '\n') {
width = MathUtils.max(textLayout.stringWidth(sbr.toString()), width);
sbr.delete(0, sbr.length());
} else {
sbr.append(ch);
}
}
return width;
}
}
public int charHeight(char ch) {
if (LSystem.base() == null) {
return 0;
}
initLayout(String.valueOf(ch));
return getHeight();
}
@Override
public int stringHeight(String message) {
if (LSystem.base() == null || StringUtils.isEmpty(message)) {
return 0;
}
initLayout(message);
if (message.indexOf('\n') == -1) {
return getHeight();
} else {
String[] list = StringUtils.split(message, '\n');
return list.length * getHeight();
}
}
public boolean isBold() {
return textFormat.font.style == Style.BOLD;
}
public boolean isItalic() {
return textFormat.font.style == Style.ITALIC;
}
public boolean isPlain() {
return textFormat.font.style == Style.PLAIN;
}
@Override
public int getSize() {
return this._size == -1 ? (int) textFormat.font.size : this._size;
}
public int getStyle() {
return textFormat.font.style.ordinal();
}
public String getFontName() {
return textFormat.font.name;
}
@Override
public int getHeight() {
initLayout(tmp);
return MathUtils.max(getSize(), textLayout.bounds.height);
}
@Override
public float getAscent() {
initLayout(tmp);
return this._ascent == -1 ? textLayout.ascent() : this._ascent;
}
public float getDescent() {
initLayout(tmp);
return textLayout.descent();
}
public float getLeading() {
initLayout(tmp);
return textLayout.leading();
}
private int fontHash = 1;
@Override
public int hashCode() {
if (fontHash == 1) {
fontHash = LSystem.unite(textFormat.font.name.charAt(0), fontHash);
fontHash = LSystem.unite(textFormat.font.name.length(), fontHash);
fontHash = LSystem.unite(textFormat.font.name.hashCode(), fontHash);
fontHash = LSystem.unite(textFormat.font.style.ordinal(), fontHash);
fontHash = LSystem.unite((int) textFormat.font.size, fontHash);
}
return fontHash;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (!(o instanceof LFont)) {
return false;
}
LFont font = (LFont) o;
if (this == font) {
return true;
}
if (hashCode() == font.hashCode()) {
return true;
}
if (font.textFormat == textFormat) {
return true;
}
if (font.textFormat.font.name.equals(textFormat.font.name) && font.textFormat.font.size == textFormat.font.size
&& font.textFormat.font.style.equals(textFormat.font.style)) {
return true;
}
return false;
}
public Vector2f getOrigin(String text) {
Vector2f result = fontSizes.get(text);
if (result == null) {
result = new Vector2f(stringWidth(text) / 2f, getHeight() / 2f);
fontSizes.put(text, result);
}
return result;
}
public TextLayout getLayoutText(String text) {
return LSystem.base().graphics().layoutText(text, this.textFormat);
}
@Override
public String confineLength(String s, int width) {
int length = 0;
for (int i = 0; i < s.length(); i++) {
length += stringWidth(String.valueOf(s.charAt(i)));
if (length >= width) {
int pLength = stringWidth("...");
while (length + pLength >= width && i >= 0) {
length -= stringWidth(String.valueOf(s.charAt(i)));
i--;
}
s = s.substring(0, ++i) + "...";
break;
}
}
return s;
}
@Override
public PointI getOffset() {
return _offset;
}
@Override
public void setOffset(PointI val) {
_offset.set(val);
}
@Override
public void setOffsetX(int x) {
_offset.x = x;
}
@Override
public void setOffsetY(int y) {
_offset.y = y;
}
@Override
public void setAssent(float assent) {
this._ascent = assent;
}
@Override
public void setSize(int size) {
this._size = size;
}
@Override
public String toString() {
StringKeyValue builder = new StringKeyValue("LFont");
builder.addValue(textFormat.toString());
return builder.toString();
}
public boolean isClosed() {
return closed;
}
@Override
public void close() {
closed = true;
LSystem.popFontPool(this);
}
}
| {
"content_hash": "3ca3cbb427b72ecc7be368684ba5edf1",
"timestamp": "",
"source": "github",
"line_count": 404,
"max_line_length": 113,
"avg_line_length": 22.10891089108911,
"alnum_prop": 0.6663681146439767,
"repo_name": "cping/LGame",
"id": "e0983400df670682e69d06c2251a9ec2fe3c5f60",
"size": "9743",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Java/Loon-Lite(PureJava)/Loon-Lite-Core/src/loon/font/LFont.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1472"
},
{
"name": "C",
"bytes": "3901"
},
{
"name": "C#",
"bytes": "3682953"
},
{
"name": "C++",
"bytes": "24221"
},
{
"name": "CSS",
"bytes": "115312"
},
{
"name": "HTML",
"bytes": "1782"
},
{
"name": "Java",
"bytes": "26857190"
},
{
"name": "JavaScript",
"bytes": "177232"
},
{
"name": "Shell",
"bytes": "236"
}
],
"symlink_target": ""
} |
"""
==============================
Test for qplotutils.chart.view
==============================
Autogenerated package stub.
"""
import unittest
import logging
import sys
import os
import numpy as np
from qtpy.QtCore import *
from qtpy.QtGui import *
from qtpy.QtOpenGL import *
from qtpy.QtWidgets import *
from qplotutils.chart.view import *
__author__ = "Philipp Baust"
__copyright__ = "Copyright 2019, Philipp Baust"
__credits__ = []
__license__ = "MIT"
__version__ = "0.0.1"
__maintainer__ = "Philipp Baust"
__email__ = "philipp.baust@gmail.com"
__status__ = "Development"
_log = logging.getLogger(__name__)
class ChartAreaTests(unittest.TestCase):
app = None
@classmethod
def setUpClass(cls):
ChartAreaTests.app = QApplication([])
def setUp(self):
""" Autogenerated. """
pass
def test_instantiate(self):
""" Autogenerated. """
obj = ChartArea() # TODO: may fail!
class ChartAxisTests(unittest.TestCase):
def setUp(self):
""" Autogenerated. """
pass
def test_instantiate(self):
""" Autogenerated. """
obj = ChartAxis() # TODO: may fail!
class ChartLabelTests(unittest.TestCase):
def setUp(self):
""" Autogenerated. """
pass
def test_instantiate(self):
""" Autogenerated. """
obj = ChartLabel() # TODO: may fail!
class ChartLegendTests(unittest.TestCase):
def setUp(self):
""" Autogenerated. """
pass
def test_instantiate(self):
""" Autogenerated. """
obj = ChartLegend() # TODO: may fail!
class ChartViewTests(unittest.TestCase):
app = None
@classmethod
def setUpClass(cls):
cls.app = QApplication([])
def setUp(self):
""" Autogenerated. """
pass
def test_instantiate(self):
""" Autogenerated. """
obj = ChartView() # TODO: may fail!
class ChartWidgetTests(unittest.TestCase):
def setUp(self):
""" Autogenerated. """
pass
def test_instantiate(self):
""" Autogenerated. """
obj = ChartWidget() # TODO: may fail!
class HorizontalAxisTests(unittest.TestCase):
def setUp(self):
""" Autogenerated. """
pass
def test_instantiate(self):
""" Autogenerated. """
obj = HorizontalAxis() # TODO: may fail!
class ScaleBoxTests(unittest.TestCase):
def setUp(self):
""" Autogenerated. """
pass
def test_instantiate(self):
""" Autogenerated. """
obj = ScaleBox() # TODO: may fail!
class SecondaryHorizontalAxisTests(unittest.TestCase):
def setUp(self):
""" Autogenerated. """
pass
def test_instantiate(self):
""" Autogenerated. """
obj = SecondaryHorizontalAxis([0,1], [0, 100]) # TODO: may fail!
class SecondaryVerticalAxisTests(unittest.TestCase):
def setUp(self):
""" Autogenerated. """
pass
def test_instantiate(self):
""" Autogenerated. """
obj = SecondaryVerticalAxis([0,1], [0, 100]) # TODO: may fail!
class StyleTests(unittest.TestCase):
def setUp(self):
""" Autogenerated. """
pass
def test_instantiate(self):
""" Autogenerated. """
obj = Style() # TODO: may fail!
class VerticalAxisTests(unittest.TestCase):
def setUp(self):
""" Autogenerated. """
pass
def test_instantiate(self):
""" Autogenerated. """
obj = VerticalAxis() # TODO: may fail!
class VerticalChartLabelTests(unittest.TestCase):
def setUp(self):
""" Autogenerated. """
pass
def test_instantiate(self):
""" Autogenerated. """
obj = VerticalChartLabel() # TODO: may fail! | {
"content_hash": "14608cb4f3801a80a09f0dcd7577ce52",
"timestamp": "",
"source": "github",
"line_count": 187,
"max_line_length": 73,
"avg_line_length": 20.705882352941178,
"alnum_prop": 0.5648243801652892,
"repo_name": "unrza72/qplotutils",
"id": "4928957a2d20d839d131cb9540f6d2936874d3a9",
"size": "3919",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/qplotutils/chart/test_view.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "983"
},
{
"name": "Python",
"bytes": "294832"
},
{
"name": "Shell",
"bytes": "271"
}
],
"symlink_target": ""
} |
package com.kite9.k9server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Kite9ServerApplication {
public static void main(String[] args) {
SpringApplication.run(Kite9ServerApplication.class, args);
}
}
| {
"content_hash": "296a9cd07c4b3101b4cd0760781298c7",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 68,
"avg_line_length": 26.666666666666668,
"alnum_prop": 0.828125,
"repo_name": "kite9-org/k9",
"id": "fb3bff5084a5bbecb63842ee645f61f59c35246a",
"size": "320",
"binary": false,
"copies": "1",
"ref": "refs/heads/new_master",
"path": "src/main/java/com/kite9/k9server/Kite9ServerApplication.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "40040"
},
{
"name": "HTML",
"bytes": "13970"
},
{
"name": "Java",
"bytes": "185848"
},
{
"name": "JavaScript",
"bytes": "143660"
},
{
"name": "XSLT",
"bytes": "3549"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="iso-8859-1"?>
<sect1 id="options-debugging">
<title>Debugging the compiler</title>
<indexterm><primary>debugging options (for GHC)</primary></indexterm>
<para>HACKER TERRITORY. HACKER TERRITORY. (You were warned.)</para>
<sect2 id="dumping-output">
<title>Dumping out compiler intermediate structures</title>
<indexterm><primary>dumping GHC intermediates</primary></indexterm>
<indexterm><primary>intermediate passes, output</primary></indexterm>
<variablelist>
<varlistentry>
<term>
<option>-ddump-</option><replaceable>pass</replaceable>
<indexterm><primary><option>-ddump</option> options</primary></indexterm>
</term>
<listitem>
<para>Make a debugging dump after pass
<literal><pass></literal> (may be common enough to need
a short form…). You can get all of these at once
(<emphasis>lots</emphasis> of output) by using
<option>-v5</option>, or most of them with
<option>-v4</option>. You can prevent them from clogging up
your standard output by passing <option>-ddump-to-file</option>.
Some of the most useful ones are:</para>
<variablelist>
<varlistentry>
<term>
<option>-ddump-parsed</option>:
<indexterm><primary><option>-ddump-parsed</option></primary></indexterm>
</term>
<listitem>
<para>parser output</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-rn</option>:
<indexterm><primary><option>-ddump-rn</option></primary></indexterm>
</term>
<listitem>
<para>renamer output</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-tc</option>:
<indexterm><primary><option>-ddump-tc</option></primary></indexterm>
</term>
<listitem>
<para>typechecker output</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-splices</option>:
<indexterm><primary><option>-ddump-splices</option></primary></indexterm>
</term>
<listitem>
<para>Dump Template Haskell expressions that we splice in,
and what Haskell code the expression evaluates to.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-types</option>:
<indexterm><primary><option>-ddump-types</option></primary></indexterm>
</term>
<listitem>
<para>Dump a type signature for each value defined at
the top level of the module. The list is sorted
alphabetically. Using <option>-dppr-debug</option>
dumps a type signature for all the imported and
system-defined things as well; useful for debugging the
compiler.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-deriv</option>:
<indexterm><primary><option>-ddump-deriv</option></primary></indexterm>
</term>
<listitem>
<para>derived instances</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-ds</option>:
<indexterm><primary><option>-ddump-ds</option></primary></indexterm>
</term>
<listitem>
<para>desugarer output</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-spec</option>:
<indexterm><primary><option>-ddump-spec</option></primary></indexterm>
</term>
<listitem>
<para>output of specialisation pass</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-rules</option>:
<indexterm><primary><option>-ddump-rules</option></primary></indexterm>
</term>
<listitem>
<para>dumps all rewrite rules specified in this module;
see <xref linkend="controlling-rules"/>.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-rule-firings</option>:
<indexterm><primary><option>-ddump-rule-firings</option></primary></indexterm>
</term>
<listitem>
<para>dumps the names of all rules that fired in this module</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-rule-rewrites</option>:
<indexterm><primary><option>-ddump-rule-rewrites</option></primary></indexterm>
</term>
<listitem>
<para>dumps detailed information about all rules that fired in
this module
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-vect</option>:
<indexterm><primary><option>-ddump-vect</option></primary></indexterm>
</term>
<listitem>
<para>dumps the output of the vectoriser.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-simpl</option>:
<indexterm><primary><option>-ddump-simpl</option></primary></indexterm>
</term>
<listitem>
<para>simplifier output (Core-to-Core passes)</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-inlinings</option>:
<indexterm><primary><option>-ddump-inlinings</option></primary></indexterm>
</term>
<listitem>
<para>inlining info from the simplifier</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-stranal</option>:
<indexterm><primary><option>-ddump-stranal</option></primary></indexterm>
</term>
<listitem>
<para>strictness analyser output</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-strsigs</option>:
<indexterm><primary><option>-ddump-strsigs</option></primary></indexterm>
</term>
<listitem>
<para>strictness signatures</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-cse</option>:
<indexterm><primary><option>-ddump-cse</option></primary></indexterm>
</term>
<listitem>
<para>CSE pass output</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-worker-wrapper</option>:
<indexterm><primary><option>-ddump-worker-wrapper</option></primary></indexterm>
</term>
<listitem>
<para>worker/wrapper split output</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-occur-anal</option>:
<indexterm><primary><option>-ddump-occur-anal</option></primary></indexterm>
</term>
<listitem>
<para>`occurrence analysis' output</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-prep</option>:
<indexterm><primary><option>-ddump-prep</option></primary></indexterm>
</term>
<listitem>
<para>output of core preparation pass</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-stg</option>:
<indexterm><primary><option>-ddump-stg</option></primary></indexterm>
</term>
<listitem>
<para>output of STG-to-STG passes</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-cmm</option>:
<indexterm><primary><option>-ddump-cmm</option></primary></indexterm>
</term>
<listitem>
<para>Print the C-- code out.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-opt-cmm</option>:
<indexterm><primary><option>-ddump-opt-cmm</option></primary></indexterm>
</term>
<listitem>
<para>Dump the results of C-- to C-- optimising passes.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-asm</option>:
<indexterm><primary><option>-ddump-asm</option></primary></indexterm>
</term>
<listitem>
<para>assembly language from the
<link linkend="native-code-gen">native code generator</link></para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-llvm</option>:
<indexterm><primary><option>-ddump-llvm</option></primary></indexterm>
</term>
<listitem>
<para>LLVM code from the <link linkend="llvm-code-gen">LLVM code
generator</link></para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-bcos</option>:
<indexterm><primary><option>-ddump-bcos</option></primary></indexterm>
</term>
<listitem>
<para>byte code compiler output</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-foreign</option>:
<indexterm><primary><option>-ddump-foreign</option></primary></indexterm>
</term>
<listitem>
<para>dump foreign export stubs</para>
</listitem>
</varlistentry>
</variablelist>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-simpl-iterations</option>:
<indexterm><primary><option>-ddump-simpl-iterations</option></primary></indexterm>
</term>
<listitem>
<para>Show the output of each <emphasis>iteration</emphasis>
of the simplifier (each run of the simplifier has a maximum
number of iterations, normally 4). This outputs even more information
than <option>-ddump-simpl-phases</option>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-simpl-stats</option>
<indexterm><primary><option>-ddump-simpl-stats option</option></primary></indexterm>
</term>
<listitem>
<para>Dump statistics about how many of each kind of
transformation too place. If you add
<option>-dppr-debug</option> you get more detailed
information.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-if-trace</option>
<indexterm><primary><option>-ddump-if-trace</option></primary></indexterm>
</term>
<listitem>
<para>Make the interface loader be *real* chatty about what it is
up to.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-tc-trace</option>
<indexterm><primary><option>-ddump-tc-trace</option></primary></indexterm>
</term>
<listitem>
<para>Make the type checker be *real* chatty about what it is
up to.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-vt-trace</option>
<indexterm><primary><option>-ddump-tv-trace</option></primary></indexterm>
</term>
<listitem>
<para>Make the vectoriser be *real* chatty about what it is
up to.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-rn-trace</option>
<indexterm><primary><option>-ddump-rn-trace</option></primary></indexterm>
</term>
<listitem>
<para>Make the renamer be *real* chatty about what it is
up to.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-rn-stats</option>
<indexterm><primary><option>-dshow-rn-stats</option></primary></indexterm>
</term>
<listitem>
<para>Print out summary of what kind of information the renamer
had to bring in.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-dverbose-core2core</option>
<indexterm><primary><option>-dverbose-core2core</option></primary></indexterm>
</term>
<term>
<option>-dverbose-stg2stg</option>
<indexterm><primary><option>-dverbose-stg2stg</option></primary></indexterm>
</term>
<listitem>
<para>Show the output of the intermediate Core-to-Core and
STG-to-STG passes, respectively. (<emphasis>Lots</emphasis>
of output!) So: when we're really desperate:</para>
<screen>
% ghc -noC -O -ddump-simpl -dverbose-core2core -dcore-lint Foo.hs
</screen>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-dshow-passes</option>
<indexterm><primary><option>-dshow-passes</option></primary></indexterm>
</term>
<listitem>
<para>Print out each pass name as it happens.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-ddump-core-stats</option>
<indexterm><primary><option>-ddump-core-stats</option></primary></indexterm>
</term>
<listitem>
<para>Print a one-line summary of the size of the Core program
at the end of the optimisation pipeline.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-dfaststring-stats</option>
<indexterm><primary><option>-dfaststring-stats</option></primary></indexterm>
</term>
<listitem>
<para>Show statistics for the usage of fast strings by the
compiler.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-dppr-debug</option>
<indexterm><primary><option>-dppr-debug</option></primary></indexterm>
</term>
<listitem>
<para>Debugging output is in one of several
“styles.” Take the printing of types, for
example. In the “user” style (the default), the
compiler's internal ideas about types are presented in
Haskell source-level syntax, insofar as possible. In the
“debug” style (which is the default for
debugging output), the types are printed in with explicit
foralls, and variables have their unique-id attached (so you
can check for things that look the same but aren't). This
flag makes debugging output appear in the more verbose debug
style.</para>
</listitem>
</varlistentry>
</variablelist>
</sect2>
<sect2 id="formatting dumps">
<title>Formatting dumps</title>
<indexterm><primary>formatting dumps</primary></indexterm>
<variablelist>
<varlistentry>
<term>
<option>-dppr-user-length</option>
<indexterm><primary><option>-dppr-user-length</option></primary></indexterm>
</term>
<listitem>
<para>In error messages, expressions are printed to a
certain “depth”, with subexpressions beyond the
depth replaced by ellipses. This flag sets the
depth. Its default value is 5.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-dppr-colsNNN</option>
<indexterm><primary><option>-dppr-colsNNN</option></primary></indexterm>
</term>
<listitem>
<para>Set the width of debugging output. Use this if your code is wrapping too much.
For example: <option>-dppr-cols200</option>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-dppr-case-as-let</option>
<indexterm><primary><option>-dppr-case-as-let</option></primary></indexterm>
</term>
<listitem>
<para>Print single alternative case expressions as though they were strict
let expressions. This is helpful when your code does a lot of unboxing.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-dno-debug-output</option>
<indexterm><primary><option>-dno-debug-output</option></primary></indexterm>
</term>
<listitem>
<para>Suppress any unsolicited debugging output. When GHC
has been built with the <literal>DEBUG</literal> option it
occasionally emits debug output of interest to developers.
The extra output can confuse the testing framework and
cause bogus test failures, so this flag is provided to
turn it off.</para>
</listitem>
</varlistentry>
</variablelist>
</sect2>
<sect2 id="suppression">
<title>Suppressing unwanted information</title>
<indexterm><primary>suppression</primary></indexterm>
Core dumps contain a large amount of information. Depending on what you are doing, not all of it will be useful.
Use these flags to suppress the parts that you are not interested in.
<variablelist>
<varlistentry>
<term>
<option>-dsuppress-all</option>
<indexterm><primary><option>-dsuppress-all</option></primary></indexterm>
</term>
<listitem>
<para>Suppress everything that can be suppressed, except for unique ids as this often
makes the printout ambiguous. If you just want to see the overall structure of
the code, then start here.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-dsuppress-uniques</option>
<indexterm><primary><option>-dsuppress-uniques</option></primary></indexterm>
</term>
<listitem>
<para>Suppress the printing of uniques. This may make
the printout ambiguous (e.g. unclear where an occurrence of 'x' is bound), but
it makes the output of two compiler runs have many fewer gratuitous differences,
so you can realistically apply <command>diff</command>. Once <command>diff</command>
has shown you where to look, you can try again without <option>-dsuppress-uniques</option></para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-dsuppress-idinfo</option>
<indexterm><primary><option>-dsuppress-idinfo</option></primary></indexterm>
</term>
<listitem>
<para>Suppress extended information about identifiers where they are bound. This includes
strictness information and inliner templates. Using this flag can cut the size
of the core dump in half, due to the lack of inliner templates</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-dsuppress-module-prefixes</option>
<indexterm><primary><option>-dsuppress-module-prefixes</option></primary></indexterm>
</term>
<listitem>
<para>Suppress the printing of module qualification prefixes.
This is the <constant>Data.List</constant> in <constant>Data.List.length</constant>.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-dsuppress-type-signatures</option>
<indexterm><primary><option>-dsuppress-type-signatures</option></primary></indexterm>
</term>
<listitem>
<para>Suppress the printing of type signatures.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-dsuppress-type-applications</option>
<indexterm><primary><option>-dsuppress-type-applications</option></primary></indexterm>
</term>
<listitem>
<para>Suppress the printing of type applications.</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-dsuppress-coercions</option>
<indexterm><primary><option>-dsuppress-coercions</option></primary></indexterm>
</term>
<listitem>
<para>Suppress the printing of type coercions.</para>
</listitem>
</varlistentry>
</variablelist>
</sect2>
<sect2 id="checking-consistency">
<title>Checking for consistency</title>
<indexterm><primary>consistency checks</primary></indexterm>
<indexterm><primary>lint</primary></indexterm>
<variablelist>
<varlistentry>
<term>
<option>-dcore-lint</option>
<indexterm><primary><option>-dcore-lint</option></primary></indexterm>
</term>
<listitem>
<para>Turn on heavyweight intra-pass sanity-checking within
GHC, at Core level. (It checks GHC's sanity, not yours.)</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-dstg-lint</option>:
<indexterm><primary><option>-dstg-lint</option></primary></indexterm>
</term>
<listitem>
<para>Ditto for STG level. (NOTE: currently doesn't work).</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<option>-dcmm-lint</option>:
<indexterm><primary><option>-dcmm-lint</option></primary></indexterm>
</term>
<listitem>
<para>Ditto for C-- level.</para>
</listitem>
</varlistentry>
</variablelist>
</sect2>
<sect2>
<title>How to read Core syntax (from some <option>-ddump</option>
flags)</title>
<indexterm><primary>reading Core syntax</primary></indexterm>
<indexterm><primary>Core syntax, how to read</primary></indexterm>
<para>Let's do this by commenting an example. It's from doing
<option>-ddump-ds</option> on this code:
<programlisting>
skip2 m = m : skip2 (m+2)
</programlisting>
Before we jump in, a word about names of things. Within GHC,
variables, type constructors, etc., are identified by their
“Uniques.” These are of the form `letter' plus
`number' (both loosely interpreted). The `letter' gives some idea
of where the Unique came from; e.g., <literal>_</literal>
means “built-in type variable”; <literal>t</literal>
means “from the typechecker”; <literal>s</literal>
means “from the simplifier”; and so on. The `number'
is printed fairly compactly in a `base-62' format, which everyone
hates except me (WDP).</para>
<para>Remember, everything has a “Unique” and it is
usually printed out when debugging, in some form or another. So
here we go…</para>
<programlisting>
Desugared:
Main.skip2{-r1L6-} :: _forall_ a$_4 =>{{Num a$_4}} -> a$_4 -> [a$_4]
--# `r1L6' is the Unique for Main.skip2;
--# `_4' is the Unique for the type-variable (template) `a'
--# `{{Num a$_4}}' is a dictionary argument
_NI_
--# `_NI_' means "no (pragmatic) information" yet; it will later
--# evolve into the GHC_PRAGMA info that goes into interface files.
Main.skip2{-r1L6-} =
/\ _4 -> \ d.Num.t4Gt ->
let {
{- CoRec -}
+.t4Hg :: _4 -> _4 -> _4
_NI_
+.t4Hg = (+{-r3JH-} _4) d.Num.t4Gt
fromInt.t4GS :: Int{-2i-} -> _4
_NI_
fromInt.t4GS = (fromInt{-r3JX-} _4) d.Num.t4Gt
--# The `+' class method (Unique: r3JH) selects the addition code
--# from a `Num' dictionary (now an explicit lambda'd argument).
--# Because Core is 2nd-order lambda-calculus, type applications
--# and lambdas (/\) are explicit. So `+' is first applied to a
--# type (`_4'), then to a dictionary, yielding the actual addition
--# function that we will use subsequently...
--# We play the exact same game with the (non-standard) class method
--# `fromInt'. Unsurprisingly, the type `Int' is wired into the
--# compiler.
lit.t4Hb :: _4
_NI_
lit.t4Hb =
let {
ds.d4Qz :: Int{-2i-}
_NI_
ds.d4Qz = I#! 2#
} in fromInt.t4GS ds.d4Qz
--# `I# 2#' is just the literal Int `2'; it reflects the fact that
--# GHC defines `data Int = I# Int#', where Int# is the primitive
--# unboxed type. (see relevant info about unboxed types elsewhere...)
--# The `!' after `I#' indicates that this is a *saturated*
--# application of the `I#' data constructor (i.e., not partially
--# applied).
skip2.t3Ja :: _4 -> [_4]
_NI_
skip2.t3Ja =
\ m.r1H4 ->
let { ds.d4QQ :: [_4]
_NI_
ds.d4QQ =
let {
ds.d4QY :: _4
_NI_
ds.d4QY = +.t4Hg m.r1H4 lit.t4Hb
} in skip2.t3Ja ds.d4QY
} in
:! _4 m.r1H4 ds.d4QQ
{- end CoRec -}
} in skip2.t3Ja
</programlisting>
<para>(“It's just a simple functional language” is an
unregisterised trademark of Peyton Jones Enterprises, plc.)</para>
</sect2>
</sect1>
<!-- Emacs stuff:
;;; Local Variables: ***
;;; sgml-parent-document: ("users_guide.xml" "book" "chapter" "sect1") ***
;;; End: ***
-->
| {
"content_hash": "5a79a6064a47845d50801b880752ac58",
"timestamp": "",
"source": "github",
"line_count": 777,
"max_line_length": 116,
"avg_line_length": 31.934362934362934,
"alnum_prop": 0.6031112723169306,
"repo_name": "christiaanb/ghc",
"id": "a0fee40749f686ce52d54c51af0075fb04b2ea54",
"size": "24813",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "docs/users_guide/debugging.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "5560"
},
{
"name": "Bison",
"bytes": "62771"
},
{
"name": "C",
"bytes": "2544214"
},
{
"name": "C++",
"bytes": "46652"
},
{
"name": "CSS",
"bytes": "984"
},
{
"name": "DTrace",
"bytes": "3887"
},
{
"name": "Emacs Lisp",
"bytes": "734"
},
{
"name": "Game Maker Language",
"bytes": "14164"
},
{
"name": "Gnuplot",
"bytes": "103851"
},
{
"name": "Groff",
"bytes": "3840"
},
{
"name": "HTML",
"bytes": "6144"
},
{
"name": "Haskell",
"bytes": "17668510"
},
{
"name": "Haxe",
"bytes": "218"
},
{
"name": "Logos",
"bytes": "120476"
},
{
"name": "Makefile",
"bytes": "485959"
},
{
"name": "Objective-C",
"bytes": "19654"
},
{
"name": "Objective-C++",
"bytes": "535"
},
{
"name": "Pascal",
"bytes": "112387"
},
{
"name": "Perl",
"bytes": "197779"
},
{
"name": "Perl6",
"bytes": "240212"
},
{
"name": "PostScript",
"bytes": "63"
},
{
"name": "Python",
"bytes": "105978"
},
{
"name": "Shell",
"bytes": "70503"
},
{
"name": "TeX",
"bytes": "667"
}
],
"symlink_target": ""
} |
namespace mojo {
namespace internal {
template <typename Interface>
struct SharedRemoteTraits<AssociatedRemote<Interface>> {
static void BindDisconnected(AssociatedRemote<Interface>& remote) {
std::ignore = remote.BindNewEndpointAndPassDedicatedReceiver();
}
};
} // namespace internal
// SharedAssociatedRemote wraps a non-thread-safe AssociatedRemote and proxies
// messages to it. Unlike normal AssociatedRemote objects,
// SharedAssociatedRemote is copyable and usable from any thread, but has some
// additional overhead and latency in message transmission as a trade-off.
//
// Async calls are posted to the sequence that the underlying AssociatedRemote
// is bound to, and responses are posted back to the calling sequence. Sync
// calls are dispatched directly if the call is made on the sequence that the
// wrapped AssociatedRemote is bound to, or posted otherwise. It's important to
// be aware that sync calls block both the calling sequence and the bound
// AssociatedRemote's sequence. That means that you cannot make sync calls
// through a SharedAssociatedRemote if the underlying AssociatedRemote is bound
// to a sequence that cannot block, like the IPC thread.
template <typename Interface>
class SharedAssociatedRemote {
public:
SharedAssociatedRemote() = default;
explicit SharedAssociatedRemote(
PendingAssociatedRemote<Interface> pending_remote,
scoped_refptr<base::SequencedTaskRunner> bind_task_runner =
base::SequencedTaskRunner::GetCurrentDefault()) {
if (pending_remote.is_valid())
Bind(std::move(pending_remote), std::move(bind_task_runner));
}
bool is_bound() const { return remote_ != nullptr; }
explicit operator bool() const { return is_bound(); }
Interface* get() const { return remote_->get(); }
Interface* operator->() const { return get(); }
Interface& operator*() const { return *get(); }
void set_disconnect_handler(
base::OnceClosure handler,
scoped_refptr<base::SequencedTaskRunner> handler_task_runner) {
remote_->set_disconnect_handler(std::move(handler),
std::move(handler_task_runner));
}
// Clears this SharedAssociatedRemote. Note that this does *not* necessarily
// close the remote's endpoint as other SharedAssociatedRemote instances may
// reference the same underlying endpoint.
void reset() { remote_.reset(); }
// Disconnects the SharedAssociatedRemote. This leaves the object in a usable
// state -- i.e. it's still safe to dereference and make calls -- but severs
// the underlying connection so that no new replies will be received and all
// outgoing messages will be discarded. This is useful when you want to force
// a disconnection like with reset(), but you don't want the
// SharedAssociatedRemote to become unbound.
void Disconnect() { remote_->Disconnect(); }
// Creates a new pair of endpoints and binds this SharedAssociatedRemote to
// one of them, on `task_runner`. The other is returned as a receiver.
mojo::PendingAssociatedReceiver<Interface> BindNewEndpointAndPassReceiver(
scoped_refptr<base::SequencedTaskRunner> bind_task_runner =
base::SequencedTaskRunner::GetCurrentDefault()) {
mojo::PendingAssociatedRemote<Interface> remote;
auto receiver = remote.InitWithNewEndpointAndPassReceiver();
Bind(std::move(remote), std::move(bind_task_runner));
return receiver;
}
// Binds to `pending_remote` on `bind_task_runner`.
void Bind(PendingAssociatedRemote<Interface> pending_remote,
scoped_refptr<base::SequencedTaskRunner> bind_task_runner =
base::SequencedTaskRunner::GetCurrentDefault()) {
DCHECK(!remote_);
DCHECK(pending_remote.is_valid());
remote_ = SharedRemoteBase<AssociatedRemote<Interface>>::Create(
std::move(pending_remote), std::move(bind_task_runner));
}
private:
scoped_refptr<SharedRemoteBase<AssociatedRemote<Interface>>> remote_;
};
} // namespace mojo
#endif // MOJO_PUBLIC_CPP_BINDINGS_SHARED_ASSOCIATED_REMOTE_H_
| {
"content_hash": "84f30ce534a6f78f8005297dde38b29d",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 79,
"avg_line_length": 43.60215053763441,
"alnum_prop": 0.7336621454993835,
"repo_name": "chromium/chromium",
"id": "914a9e27ba2bd516242fc9957ddf58f55b1bba27",
"size": "4595",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "mojo/public/cpp/bindings/shared_associated_remote.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
require "cases/helper"
require "support/schema_dumping_helper"
if ActiveRecord::Base.connection.supports_check_constraints?
module ActiveRecord
class Migration
class CheckConstraintTest < ActiveRecord::TestCase
include SchemaDumpingHelper
class Trade < ActiveRecord::Base
end
setup do
@connection = ActiveRecord::Base.connection
@connection.create_table "trades", force: true do |t|
t.integer :price
t.integer :quantity
end
@connection.create_table "purchases", force: true do |t|
t.integer :price
t.integer :quantity
end
end
teardown do
@connection.drop_table "trades", if_exists: true rescue nil
@connection.drop_table "purchases", if_exists: true rescue nil
end
def test_check_constraints
check_constraints = @connection.check_constraints("products")
assert_equal 1, check_constraints.size
constraint = check_constraints.first
assert_equal "products", constraint.table_name
assert_equal "products_price_check", constraint.name
if current_adapter?(:Mysql2Adapter)
assert_equal "`price` > `discounted_price`", constraint.expression
else
assert_equal "price > discounted_price", constraint.expression
end
if current_adapter?(:PostgreSQLAdapter)
begin
# Test that complex expression is correctly parsed from the database
@connection.add_check_constraint(:trades,
"CASE WHEN price IS NOT NULL THEN true ELSE false END", name: "price_is_required")
constraint = @connection.check_constraints("trades").find { |c| c.name == "price_is_required" }
assert_includes constraint.expression, "WHEN price IS NOT NULL"
ensure
@connection.remove_check_constraint(:trades, name: "price_is_required")
end
end
end
if current_adapter?(:PostgreSQLAdapter)
def test_check_constraints_scoped_to_schemas
@connection.add_check_constraint :trades, "quantity > 0"
assert_no_changes -> { @connection.check_constraints("trades").size } do
@connection.create_schema "test_schema"
@connection.create_table "test_schema.trades" do |t|
t.integer :quantity
end
@connection.add_check_constraint "test_schema.trades", "quantity > 0"
end
ensure
@connection.drop_schema "test_schema"
end
end
def test_add_check_constraint
@connection.add_check_constraint :trades, "quantity > 0"
check_constraints = @connection.check_constraints("trades")
assert_equal 1, check_constraints.size
constraint = check_constraints.first
assert_equal "trades", constraint.table_name
assert_equal "chk_rails_2189e9f96c", constraint.name
if current_adapter?(:Mysql2Adapter)
assert_equal "`quantity` > 0", constraint.expression
else
assert_equal "quantity > 0", constraint.expression
end
end
if supports_non_unique_constraint_name?
def test_add_constraint_with_same_name_to_different_table
@connection.add_check_constraint :trades, "quantity > 0", name: "greater_than_zero"
@connection.add_check_constraint :purchases, "quantity > 0", name: "greater_than_zero"
trades_check_constraints = @connection.check_constraints("trades")
assert_equal 1, trades_check_constraints.size
trade_constraint = trades_check_constraints.first
assert_equal "trades", trade_constraint.table_name
assert_equal "greater_than_zero", trade_constraint.name
purchases_check_constraints = @connection.check_constraints("purchases")
assert_equal 1, purchases_check_constraints.size
purchase_constraint = purchases_check_constraints.first
assert_equal "purchases", purchase_constraint.table_name
assert_equal "greater_than_zero", purchase_constraint.name
end
end
def test_add_check_constraint_with_non_existent_table_raises
e = assert_raises(ActiveRecord::StatementInvalid) do
@connection.add_check_constraint :refunds, "quantity > 0", name: "quantity_check"
end
assert_match(/refunds/, e.message)
end
def test_added_check_constraint_ensures_valid_values
@connection.add_check_constraint :trades, "quantity > 0", name: "quantity_check"
assert_raises(ActiveRecord::StatementInvalid) do
Trade.create(quantity: -1)
end
end
if ActiveRecord::Base.connection.supports_validate_constraints?
def test_not_valid_check_constraint
Trade.create(quantity: -1)
@connection.add_check_constraint :trades, "quantity > 0", name: "quantity_check", validate: false
assert_raises(ActiveRecord::StatementInvalid) do
Trade.create(quantity: -1)
end
end
def test_validate_check_constraint_by_name
@connection.add_check_constraint :trades, "quantity > 0", name: "quantity_check", validate: false
assert_not_predicate @connection.check_constraints("trades").first, :validated?
@connection.validate_check_constraint :trades, name: "quantity_check"
assert_predicate @connection.check_constraints("trades").first, :validated?
end
def test_validated_check_constraint_exists
@connection.add_check_constraint :trades, "quantity > 0", name: "quantity_check", validate: false
assert_not @connection.check_constraint_exists?(:trades, name: "quantity_check", validate: true)
@connection.validate_check_constraint :trades, name: "quantity_check"
assert @connection.check_constraint_exists?(:trades, name: "quantity_check", validate: true)
end
def test_validate_non_existing_check_constraint_raises
assert_raises ArgumentError do
@connection.validate_check_constraint :trades, name: "quantity_check"
end
end
else
# Check constraint should still be created, but should not be invalid
def test_add_invalid_check_constraint
@connection.add_check_constraint :trades, "quantity > 0", name: "quantity_check", validate: false
check_constraints = @connection.check_constraints("trades")
assert_equal 1, check_constraints.size
cc = check_constraints.first
assert_predicate cc, :validated?
end
end
def test_check_constraint_exists
@connection.add_check_constraint :trades, "quantity > 0", name: "quantity_check"
assert @connection.check_constraint_exists?(:trades, name: "quantity_check")
assert_not @connection.check_constraint_exists?(:non_trades, name: "quantity_check")
assert_not @connection.check_constraint_exists?(:trades, name: "other_check")
end
def test_check_constraint_exists_ensures_required_options
@connection.add_check_constraint :trades, "quantity > 0", name: "quantity_check"
error = assert_raises(ArgumentError) do
@connection.check_constraint_exists?(:trades, something: true)
end
assert_equal "At least one of :name or :expression must be supplied", error.message
end
def test_remove_check_constraint
@connection.add_check_constraint :trades, "price > 0", name: "price_check"
@connection.add_check_constraint :trades, "quantity > 0", name: "quantity_check"
assert_equal 2, @connection.check_constraints("trades").size
@connection.remove_check_constraint :trades, name: "quantity_check"
assert_equal 1, @connection.check_constraints("trades").size
constraint = @connection.check_constraints("trades").first
assert_equal "trades", constraint.table_name
assert_equal "price_check", constraint.name
if current_adapter?(:Mysql2Adapter)
assert_equal "`price` > 0", constraint.expression
else
assert_equal "price > 0", constraint.expression
end
@connection.remove_check_constraint :trades, name: :price_check # name as a symbol
assert_empty @connection.check_constraints("trades")
end
def test_removing_check_constraint_with_if_exists_option
@connection.add_check_constraint :trades, "quantity > 0", name: "quantity_check"
@connection.remove_check_constraint :trades, name: "quantity_check"
error = assert_raises ArgumentError do
@connection.remove_check_constraint :trades, name: "quantity_check"
end
assert_equal "Table 'trades' has no check constraint for {:name=>\"quantity_check\"}", error.message
assert_nothing_raised do
@connection.remove_check_constraint :trades, name: "quantity_check", if_exists: true
end
end
def test_remove_non_existing_check_constraint
assert_raises(ArgumentError) do
@connection.remove_check_constraint :trades, name: "nonexistent"
end
end
def test_add_constraint_from_change_table_with_options
@connection.change_table :trades do |t|
t.check_constraint "price > 0", name: "price_check"
end
constraint = @connection.check_constraints("trades").first
assert_equal "trades", constraint.table_name
assert_equal "price_check", constraint.name
end
def test_remove_constraint_from_change_table_with_options
@connection.add_check_constraint :trades, "price > 0", name: "price_check"
@connection.change_table :trades do |t|
t.remove_check_constraint "price > 0", name: "price_check"
end
assert_equal 0, @connection.check_constraints("trades").size
end
end
end
end
else
module ActiveRecord
class Migration
class NoForeignKeySupportTest < ActiveRecord::TestCase
setup do
@connection = ActiveRecord::Base.connection
end
def test_add_check_constraint_should_be_noop
@connection.add_check_constraint :products, "discounted_price > 0", name: "discounted_price_check"
end
def test_remove_check_constraint_should_be_noop
@connection.remove_check_constraint :products, name: "price_check"
end
def test_check_constraints_should_raise_not_implemented
assert_raises(NotImplementedError) do
@connection.check_constraints("products")
end
end
end
end
end
end
| {
"content_hash": "24364cd074670c484acede49275d490b",
"timestamp": "",
"source": "github",
"line_count": 277,
"max_line_length": 110,
"avg_line_length": 40.018050541516246,
"alnum_prop": 0.6306720793865584,
"repo_name": "georgeclaghorn/rails",
"id": "a2eef8db874ace7f1f7cb8851f285d4c5a3a400d",
"size": "11116",
"binary": false,
"copies": "4",
"ref": "refs/heads/main",
"path": "activerecord/test/cases/migration/check_constraint_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "56339"
},
{
"name": "Dockerfile",
"bytes": "2639"
},
{
"name": "HTML",
"bytes": "93448"
},
{
"name": "JavaScript",
"bytes": "642337"
},
{
"name": "Ruby",
"bytes": "15230278"
},
{
"name": "Shell",
"bytes": "5093"
},
{
"name": "Yacc",
"bytes": "1003"
}
],
"symlink_target": ""
} |
YUI.add('io-nodejs', function (Y, NAME) {
/*global Y: false, Buffer: false, clearInterval: false, clearTimeout: false, console: false, exports: false, global: false, module: false, process: false, querystring: false, require: false, setInterval: false, setTimeout: false, __filename: false, __dirname: false */
/**
* Node.js override for IO, methods are mixed into `Y.IO`
* @module io-nodejs
* @main io-nodejs
*/
/**
* Passthru to the NodeJS <a href="https://github.com/mikeal/request">request</a> module.
* This method is return of `require('request')` so you can use it inside NodeJS without
* the IO abstraction.
* @method request
* @static
* @for IO
*/
if (!Y.IO.request) {
// Default Request's cookie jar to `false`. This way cookies will not be
// maintained across requests.
Y.IO.request = require('request').defaults({jar: false});
}
var codes = require('http').STATUS_CODES;
/**
Flatten headers object
@method flatten
@protected
@for IO
@param {Object} o The headers object
@return {String} The flattened headers object
*/
var flatten = function(o) {
var str = [];
Object.keys(o).forEach(function(name) {
str.push(name + ': ' + o[name]);
});
return str.join('\n');
};
Y.log('Loading NodeJS Request Transport', 'info', 'io');
/**
NodeJS IO transport, uses the NodeJS <a href="https://github.com/mikeal/request">request</a>
module under the hood to perform all network IO.
@method transports.nodejs
@for IO
@static
@return {Object} This object contains only a `send` method that accepts a
`transaction object`, `uri` and the `config object`.
@example
Y.io('https://somedomain.com/url', {
method: 'PUT',
data: '?foo=bar',
//Extra request module config options.
request: {
maxRedirects: 100,
strictSSL: true,
multipart: [
{
'content-type': 'application/json',
body: JSON.stringify({
foo: 'bar',
_attachments: {
'message.txt': {
follows: true,
length: 18,
'content_type': 'text/plain'
}
}
})
},
{
body: 'I am an attachment'
}
]
},
on: {
success: function(id, e) {
Y.log(e.responseText);
}
}
});
*/
Y.IO.transports.nodejs = function() {
return {
send: function (transaction, uri, config) {
Y.log('Starting Request Transaction', 'info', 'io');
config.notify('start', transaction, config);
config.method = config.method || 'GET';
config.method = config.method.toUpperCase();
var rconf = {
method: config.method,
uri: uri
};
if (config.data) {
if (Y.Lang.isString(config.data)) {
rconf.body = config.data;
}
if (rconf.body && rconf.method === 'GET') {
rconf.uri += (rconf.uri.indexOf('?') > -1 ? '&' : '?') + rconf.body;
rconf.body = '';
}
}
if (config.headers) {
rconf.headers = config.headers;
}
if (config.timeout) {
rconf.timeout = config.timeout;
}
if (config.request) {
Y.mix(rconf, config.request);
}
Y.log('Initiating ' + rconf.method + ' request to: ' + rconf.uri, 'info', 'io');
Y.IO.request(rconf, function(err, data) {
Y.log('Request Transaction Complete', 'info', 'io');
if (err) {
Y.log('An IO error occurred', 'warn', 'io');
transaction.c = err;
config.notify(((err.code === 'ETIMEDOUT') ? 'timeout' : 'failure'), transaction, config);
return;
}
if (data) {
transaction.c = {
status: data.statusCode,
statusCode: data.statusCode,
statusText: codes[data.statusCode],
headers: data.headers,
responseText: data.body || '',
responseXML: null,
getResponseHeader: function(name) {
return this.headers[name];
},
getAllResponseHeaders: function() {
return flatten(this.headers);
}
};
}
Y.log('Request Transaction Complete', 'info', 'io');
config.notify('complete', transaction, config);
config.notify(((data && (data.statusCode >= 200 && data.statusCode <= 299)) ? 'success' : 'failure'), transaction, config);
});
var ret = {
io: transaction
};
return ret;
}
};
};
Y.IO.defaultTransport('nodejs');
}, '3.14.1', {"requires": ["io-base"]});
| {
"content_hash": "f6012daeb89731f19bb17429f178e3e1",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 268,
"avg_line_length": 36.31901840490798,
"alnum_prop": 0.43158783783783783,
"repo_name": "sun-teng/bcmderFireMirrorHTML",
"id": "ed8a29d04f4b382798b8dff28006798cafda3c39",
"size": "5920",
"binary": false,
"copies": "23",
"ref": "refs/heads/master",
"path": "app/bower_components/item-mirror/node_modules/yuidocjs/node_modules/yui/io-nodejs/io-nodejs-debug.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11763"
},
{
"name": "HTML",
"bytes": "117693"
},
{
"name": "JavaScript",
"bytes": "13371"
}
],
"symlink_target": ""
} |
title: Maclaurin Series
localeTitle: Serie maclaurin
---
## Serie maclaurin
La serie Maclaurin es un caso especial de la serie Taylor, centrada en 0. Es una serie de potencia que permite calcular la aproximación de una función f (x) para valores de entrada cercanos a cero.
[Referencia de la serie maclaurin](http://mathworld.wolfram.com/MaclaurinSeries.html) . | {
"content_hash": "8e8dfa8da2393a82a0aacb4d5c1910fe",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 197,
"avg_line_length": 45.375,
"alnum_prop": 0.7878787878787878,
"repo_name": "HKuz/FreeCodeCamp",
"id": "7582721641ba1c6486fbdb6c068cb15813111d88",
"size": "369",
"binary": false,
"copies": "4",
"ref": "refs/heads/fix/JupyterNotebook",
"path": "guide/spanish/mathematics/maclaurin-series/index.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "193850"
},
{
"name": "HTML",
"bytes": "100244"
},
{
"name": "JavaScript",
"bytes": "522369"
}
],
"symlink_target": ""
} |
import NavLogin from './NavLogin'
export default NavLogin
| {
"content_hash": "b59a8d2a5afb3c1d8b8304dd75a59993",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 33,
"avg_line_length": 19.666666666666668,
"alnum_prop": 0.7966101694915254,
"repo_name": "Drathal/react-playground",
"id": "79ebbb211acb39b22840f0f7d912336ebdc01d8c",
"size": "59",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/NavLogin/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4770"
},
{
"name": "HTML",
"bytes": "4903"
},
{
"name": "JavaScript",
"bytes": "54666"
}
],
"symlink_target": ""
} |
function loadText()
{
document.getElementById("txtLang").innerHTML = "Navn";
document.getElementById("btnCancel").value = "Annuller";
document.getElementById("btnInsert").value = "Inds\u00E6t";
document.getElementById("btnApply").value = "Opdater";
document.getElementById("btnOk").value = " Ok ";
}
function writeTitle()
{
document.write("<title>Filsending</title>")
} | {
"content_hash": "a30b4fe859daaa7cf73da2e95be9ba0e",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 63,
"avg_line_length": 35,
"alnum_prop": 0.6547619047619048,
"repo_name": "studiodev/archives",
"id": "4e3b91d2db2e61f27d7b1be4a511afb3357039f1",
"size": "420",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "2009 - Team D4 (IxGamer)/include/Editor/scripts/language/danish/form_file.js",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "278127"
},
{
"name": "ApacheConf",
"bytes": "17574"
},
{
"name": "CSS",
"bytes": "947736"
},
{
"name": "ColdFusion",
"bytes": "42028"
},
{
"name": "HTML",
"bytes": "9820794"
},
{
"name": "Java",
"bytes": "30831"
},
{
"name": "JavaScript",
"bytes": "7757772"
},
{
"name": "Lasso",
"bytes": "24527"
},
{
"name": "PHP",
"bytes": "21467673"
},
{
"name": "Perl",
"bytes": "39266"
},
{
"name": "Python",
"bytes": "26247"
},
{
"name": "Smarty",
"bytes": "196757"
}
],
"symlink_target": ""
} |
require 'devise/strategies/base'
module Devise
module Strategies
class Oauth2GrantTypeStrategy < Authenticatable
def store?
false
end
def valid?
params[:controller] == 'devise/oauth2_providable/tokens' && request.post? && params[:grant_type] == grant_type
end
# defined by subclass
def grant_type
end
# defined by subclass
def authenticate_grant_type(client)
end
def authenticate!
client_id, client_secret = request.authorization ? decode_credentials : [params[:client_id], params[:client_secret]]
client = Devise::Oauth2Providable::Client.find_by_identifier client_id
if client && client.secret == client_secret
env[Devise::Oauth2Providable::CLIENT_ENV_REF] = client
authenticate_grant_type(client)
else
oauth_error! :invalid_client
end
end
def oauth_error!(error_code = :invalid_request, description = nil)
body = {:error => error_code}
description = I18n.t("devise.failure.#{error_code}") unless description
body[:error_description] = description if description
custom! [400, {'Content-Type' => 'application/json'}, [body.to_json]]
throw :warden
end
end
end
end
| {
"content_hash": "3ba686ce17d443d7272aebf83b19291e",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 124,
"avg_line_length": 30.093023255813954,
"alnum_prop": 0.6321483771251932,
"repo_name": "brycesch/devise_oauth2_providable",
"id": "eb61382c86cf9042037ec7aad9e24521e862e1e3",
"size": "1294",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/devise/oauth2_providable/strategies/oauth2_grant_type_strategy.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "350"
},
{
"name": "HTML",
"bytes": "3238"
},
{
"name": "JavaScript",
"bytes": "421"
},
{
"name": "Ruby",
"bytes": "73629"
}
],
"symlink_target": ""
} |
import React, { Component, PropTypes } from 'react';
import Box from './Box';
import Intl from '../utils/Intl';
import CSSClassnames from '../utils/CSSClassnames';
const CLASS_ROOT = CSSClassnames.TITLE;
export default class Title extends Component {
render () {
const classes = [CLASS_ROOT];
if (this.props.responsive) {
classes.push(CLASS_ROOT + "--responsive");
}
if (this.props.onClick) {
classes.push(CLASS_ROOT + "--interactive");
}
if (this.props.className) {
classes.push(this.props.className);
}
const a11yTitle = this.props.a11yTitle ||
Intl.getMessage(this.context.intl, 'Title');
let content;
if( typeof this.props.children === 'string' ) {
content = (
<span>{this.props.children}</span>
);
} else if (Array.isArray(this.props.children)) {
content = this.props.children.map((child, index) => {
if (child && typeof child === 'string') {
return <span key={`title_${index}`}>{child}</span>;
}
return child;
});
} else {
content = this.props.children;
}
return (
<Box align="center" direction="row" responsive={false}
className={classes.join(' ')} a11yTitle={a11yTitle}
onClick={this.props.onClick}>
{content}
</Box>
);
}
}
Title.propTypes = {
a11yTitle: PropTypes.string,
onClick: PropTypes.func,
responsive: PropTypes.bool
};
Title.contextTypes = {
intl: PropTypes.object
};
Title.defaultProps = {
responsive: true
};
| {
"content_hash": "436d61fb32b556c97917ab111ecb7265",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 61,
"avg_line_length": 24.125,
"alnum_prop": 0.6068652849740933,
"repo_name": "davrodpin/grommet",
"id": "89106eb377527ff80d6078cd9aca3c5a0152be6b",
"size": "1614",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/js/components/Title.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "231167"
},
{
"name": "HTML",
"bytes": "4207"
},
{
"name": "JavaScript",
"bytes": "518994"
}
],
"symlink_target": ""
} |
{-# LANGUAGE PackageImports #-}
import "hasknowledge" Application (develMain)
import Prelude (IO)
main :: IO ()
main = develMain
| {
"content_hash": "1a625791f596f9d7c853d9791bd26ce1",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 45,
"avg_line_length": 21.666666666666668,
"alnum_prop": 0.7230769230769231,
"repo_name": "quantum-dan/HasKnowledge",
"id": "6d231572f91260268525f6112c3c5fa1aedd7ff2",
"size": "130",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/devel.hs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1244"
},
{
"name": "Dart",
"bytes": "25739"
},
{
"name": "HTML",
"bytes": "1005"
},
{
"name": "Haskell",
"bytes": "55610"
},
{
"name": "JavaScript",
"bytes": "8205"
}
],
"symlink_target": ""
} |
import sys
if sys.hexversion < 0x020400f0: from sets import Set as set
typos={'feature':'features','sources':'source','targets':'target','include':'includes','export_include':'export_includes','define':'defines','importpath':'includes','installpath':'install_path',}
meths_typos=['__call__','program','shlib','stlib','objects']
from waflib import Logs,Build,Node,Task,TaskGen,ConfigSet,Errors,Utils
import waflib.Tools.ccroot
def check_same_targets(self):
mp=Utils.defaultdict(list)
uids={}
def check_task(tsk):
if not isinstance(tsk,Task.Task):
return
for node in tsk.outputs:
mp[node].append(tsk)
try:
uids[tsk.uid()].append(tsk)
except:
uids[tsk.uid()]=[tsk]
for g in self.groups:
for tg in g:
try:
for tsk in tg.tasks:
check_task(tsk)
except AttributeError:
check_task(tg)
dupe=False
for(k,v)in mp.items():
if len(v)>1:
dupe=True
msg='* Node %r is created by more than once%s. The task generators are:'%(k,Logs.verbose==1 and" (full message on 'waf -v -v')"or"")
Logs.error(msg)
for x in v:
if Logs.verbose>1:
Logs.error(' %d. %r'%(1+v.index(x),x.generator))
else:
Logs.error(' %d. %r in %r'%(1+v.index(x),x.generator.name,getattr(x.generator,'path',None)))
if not dupe:
for(k,v)in uids.items():
if len(v)>1:
Logs.error('* Several tasks use the same identifier. Please check the information on\n http://waf.googlecode.com/git/docs/apidocs/Task.html#waflib.Task.Task.uid')
for tsk in v:
Logs.error(' - object %r (%r) defined in %r'%(tsk.__class__.__name__,tsk,tsk.generator))
def check_invalid_constraints(self):
feat=set([])
for x in list(TaskGen.feats.values()):
feat.union(set(x))
for(x,y)in TaskGen.task_gen.prec.items():
feat.add(x)
feat.union(set(y))
ext=set([])
for x in TaskGen.task_gen.mappings.values():
ext.add(x.__name__)
invalid=ext&feat
if invalid:
Logs.error('The methods %r have invalid annotations: @extension <-> @feature/@before_method/@after_method'%list(invalid))
for cls in list(Task.classes.values()):
for x in('before','after'):
for y in Utils.to_list(getattr(cls,x,[])):
if not Task.classes.get(y,None):
Logs.error('Erroneous order constraint %r=%r on task class %r'%(x,y,cls.__name__))
def replace(m):
oldcall=getattr(Build.BuildContext,m)
def call(self,*k,**kw):
ret=oldcall(self,*k,**kw)
for x in typos:
if x in kw:
err=True
Logs.error('Fix the typo %r -> %r on %r'%(x,typos[x],ret))
return ret
setattr(Build.BuildContext,m,call)
def enhance_lib():
for m in meths_typos:
replace(m)
old_ant_glob=Node.Node.ant_glob
def ant_glob(self,*k,**kw):
if k:
lst=Utils.to_list(k[0])
for pat in lst:
if'..'in pat.split('/'):
Logs.error("In ant_glob pattern %r: '..' means 'two dots', not 'parent directory'"%k[0])
return old_ant_glob(self,*k,**kw)
Node.Node.ant_glob=ant_glob
old=Task.is_before
def is_before(t1,t2):
ret=old(t1,t2)
if ret and old(t2,t1):
Logs.error('Contradictory order constraints in classes %r %r'%(t1,t2))
return ret
Task.is_before=is_before
def check_err_features(self):
lst=self.to_list(self.features)
if'shlib'in lst:
Logs.error('feature shlib -> cshlib, dshlib or cxxshlib')
for x in('c','cxx','d','fc'):
if not x in lst and lst and lst[0]in[x+y for y in('program','shlib','stlib')]:
Logs.error('%r features is probably missing %r'%(self,x))
TaskGen.feature('*')(check_err_features)
def check_err_order(self):
if not hasattr(self,'rule'):
for x in('before','after','ext_in','ext_out'):
if hasattr(self,x):
Logs.warn('Erroneous order constraint %r on non-rule based task generator %r'%(x,self))
else:
for x in('before','after'):
for y in self.to_list(getattr(self,x,[])):
if not Task.classes.get(y,None):
Logs.error('Erroneous order constraint %s=%r on %r'%(x,y,self))
TaskGen.feature('*')(check_err_order)
def check_compile(self):
check_invalid_constraints(self)
try:
ret=self.orig_compile()
finally:
check_same_targets(self)
return ret
Build.BuildContext.orig_compile=Build.BuildContext.compile
Build.BuildContext.compile=check_compile
def use_rec(self,name,**kw):
try:
y=self.bld.get_tgen_by_name(name)
except Errors.WafError:
pass
else:
idx=self.bld.get_group_idx(self)
odx=self.bld.get_group_idx(y)
if odx>idx:
msg="Invalid 'use' across build groups:"
if Logs.verbose>1:
msg+='\n target %r\n uses:\n %r'%(self,y)
else:
msg+=" %r uses %r (try 'waf -v -v' for the full error)"%(self.name,name)
raise Errors.WafError(msg)
self.orig_use_rec(name,**kw)
TaskGen.task_gen.orig_use_rec=TaskGen.task_gen.use_rec
TaskGen.task_gen.use_rec=use_rec
def getattri(self,name,default=None):
if name=='append'or name=='add':
raise Errors.WafError('env.append and env.add do not exist: use env.append_value/env.append_unique')
elif name=='prepend':
raise Errors.WafError('env.prepend does not exist: use env.prepend_value')
if name in self.__slots__:
return object.__getattr__(self,name,default)
else:
return self[name]
ConfigSet.ConfigSet.__getattr__=getattri
def options(opt):
enhance_lib()
def configure(conf):
pass
| {
"content_hash": "a59cff99fd5c46902e242a0db008351a",
"timestamp": "",
"source": "github",
"line_count": 149,
"max_line_length": 195,
"avg_line_length": 34.83221476510067,
"alnum_prop": 0.666281310211946,
"repo_name": "dproc/trex_odp_porting_integration",
"id": "be501299f9ec2d1f18e181dd4bd5abb720a24e27",
"size": "5335",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "linux_odp/.waf-1.6.8-3e3391c5f23fbabad81e6d17c63a1b1e/waflib/Tools/errcheck.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "9616073"
},
{
"name": "C++",
"bytes": "3147123"
},
{
"name": "CMake",
"bytes": "8882"
},
{
"name": "HTML",
"bytes": "4523"
},
{
"name": "JavaScript",
"bytes": "1234"
},
{
"name": "Makefile",
"bytes": "129776"
},
{
"name": "Python",
"bytes": "2740100"
},
{
"name": "Shell",
"bytes": "3026"
}
],
"symlink_target": ""
} |
use crate::interface::{Compiler, Result};
use crate::passes::{self, BoxedResolver, QueryContext};
use rustc_ast as ast;
use rustc_codegen_ssa::traits::CodegenBackend;
use rustc_data_structures::svh::Svh;
use rustc_data_structures::sync::{Lrc, OnceCell, WorkerLocal};
use rustc_errors::ErrorReported;
use rustc_hir::def_id::LOCAL_CRATE;
use rustc_incremental::DepGraphFuture;
use rustc_lint::LintStore;
use rustc_middle::arena::Arena;
use rustc_middle::dep_graph::DepGraph;
use rustc_middle::ty::{GlobalCtxt, TyCtxt};
use rustc_query_impl::Queries as TcxQueries;
use rustc_serialize::json;
use rustc_session::config::{self, OutputFilenames, OutputType};
use rustc_session::{output::find_crate_name, Session};
use rustc_span::symbol::sym;
use std::any::Any;
use std::cell::{Ref, RefCell, RefMut};
use std::rc::Rc;
/// Represent the result of a query.
///
/// This result can be stolen with the [`take`] method and generated with the [`compute`] method.
///
/// [`take`]: Self::take
/// [`compute`]: Self::compute
pub struct Query<T> {
result: RefCell<Option<Result<T>>>,
}
impl<T> Query<T> {
fn compute<F: FnOnce() -> Result<T>>(&self, f: F) -> Result<&Query<T>> {
let mut result = self.result.borrow_mut();
if result.is_none() {
*result = Some(f());
}
result.as_ref().unwrap().as_ref().map(|_| self).map_err(|err| *err)
}
/// Takes ownership of the query result. Further attempts to take or peek the query
/// result will panic unless it is generated by calling the `compute` method.
pub fn take(&self) -> T {
self.result.borrow_mut().take().expect("missing query result").unwrap()
}
/// Borrows the query result using the RefCell. Panics if the result is stolen.
pub fn peek(&self) -> Ref<'_, T> {
Ref::map(self.result.borrow(), |r| {
r.as_ref().unwrap().as_ref().expect("missing query result")
})
}
/// Mutably borrows the query result using the RefCell. Panics if the result is stolen.
pub fn peek_mut(&self) -> RefMut<'_, T> {
RefMut::map(self.result.borrow_mut(), |r| {
r.as_mut().unwrap().as_mut().expect("missing query result")
})
}
}
impl<T> Default for Query<T> {
fn default() -> Self {
Query { result: RefCell::new(None) }
}
}
pub struct Queries<'tcx> {
compiler: &'tcx Compiler,
gcx: OnceCell<GlobalCtxt<'tcx>>,
queries: OnceCell<TcxQueries<'tcx>>,
arena: WorkerLocal<Arena<'tcx>>,
hir_arena: WorkerLocal<rustc_ast_lowering::Arena<'tcx>>,
dep_graph_future: Query<Option<DepGraphFuture>>,
parse: Query<ast::Crate>,
crate_name: Query<String>,
register_plugins: Query<(ast::Crate, Lrc<LintStore>)>,
expansion: Query<(Rc<ast::Crate>, Rc<RefCell<BoxedResolver>>, Lrc<LintStore>)>,
dep_graph: Query<DepGraph>,
prepare_outputs: Query<OutputFilenames>,
global_ctxt: Query<QueryContext<'tcx>>,
ongoing_codegen: Query<Box<dyn Any>>,
}
impl<'tcx> Queries<'tcx> {
pub fn new(compiler: &'tcx Compiler) -> Queries<'tcx> {
Queries {
compiler,
gcx: OnceCell::new(),
queries: OnceCell::new(),
arena: WorkerLocal::new(|_| Arena::default()),
hir_arena: WorkerLocal::new(|_| rustc_ast_lowering::Arena::default()),
dep_graph_future: Default::default(),
parse: Default::default(),
crate_name: Default::default(),
register_plugins: Default::default(),
expansion: Default::default(),
dep_graph: Default::default(),
prepare_outputs: Default::default(),
global_ctxt: Default::default(),
ongoing_codegen: Default::default(),
}
}
fn session(&self) -> &Lrc<Session> {
&self.compiler.sess
}
fn codegen_backend(&self) -> &Lrc<Box<dyn CodegenBackend>> {
self.compiler.codegen_backend()
}
fn dep_graph_future(&self) -> Result<&Query<Option<DepGraphFuture>>> {
self.dep_graph_future.compute(|| {
let sess = self.session();
Ok(sess.opts.build_dep_graph().then(|| rustc_incremental::load_dep_graph(sess)))
})
}
pub fn parse(&self) -> Result<&Query<ast::Crate>> {
self.parse.compute(|| {
passes::parse(self.session(), &self.compiler.input).map_err(|mut parse_error| {
parse_error.emit();
ErrorReported
})
})
}
pub fn register_plugins(&self) -> Result<&Query<(ast::Crate, Lrc<LintStore>)>> {
self.register_plugins.compute(|| {
let crate_name = self.crate_name()?.peek().clone();
let krate = self.parse()?.take();
let empty: &(dyn Fn(&Session, &mut LintStore) + Sync + Send) = &|_, _| {};
let (krate, lint_store) = passes::register_plugins(
self.session(),
&*self.codegen_backend().metadata_loader(),
self.compiler.register_lints.as_deref().unwrap_or_else(|| empty),
krate,
&crate_name,
)?;
// Compute the dependency graph (in the background). We want to do
// this as early as possible, to give the DepGraph maximum time to
// load before dep_graph() is called, but it also can't happen
// until after rustc_incremental::prepare_session_directory() is
// called, which happens within passes::register_plugins().
self.dep_graph_future().ok();
Ok((krate, Lrc::new(lint_store)))
})
}
pub fn crate_name(&self) -> Result<&Query<String>> {
self.crate_name.compute(|| {
Ok({
let parse_result = self.parse()?;
let krate = parse_result.peek();
// parse `#[crate_name]` even if `--crate-name` was passed, to make sure it matches.
find_crate_name(self.session(), &krate.attrs, &self.compiler.input)
})
})
}
pub fn expansion(
&self,
) -> Result<&Query<(Rc<ast::Crate>, Rc<RefCell<BoxedResolver>>, Lrc<LintStore>)>> {
tracing::trace!("expansion");
self.expansion.compute(|| {
let crate_name = self.crate_name()?.peek().clone();
let (krate, lint_store) = self.register_plugins()?.take();
let _timer = self.session().timer("configure_and_expand");
let sess = self.session();
let mut resolver = passes::create_resolver(
sess.clone(),
self.codegen_backend().metadata_loader(),
&krate,
&crate_name,
);
let krate = resolver.access(|resolver| {
passes::configure_and_expand(sess, &lint_store, krate, &crate_name, resolver)
})?;
Ok((Rc::new(krate), Rc::new(RefCell::new(resolver)), lint_store))
})
}
fn dep_graph(&self) -> Result<&Query<DepGraph>> {
self.dep_graph.compute(|| {
let sess = self.session();
let future_opt = self.dep_graph_future()?.take();
let dep_graph = future_opt
.and_then(|future| {
let (prev_graph, prev_work_products) =
sess.time("blocked_on_dep_graph_loading", || future.open().open(sess));
rustc_incremental::build_dep_graph(sess, prev_graph, prev_work_products)
})
.unwrap_or_else(DepGraph::new_disabled);
Ok(dep_graph)
})
}
pub fn prepare_outputs(&self) -> Result<&Query<OutputFilenames>> {
self.prepare_outputs.compute(|| {
let (krate, boxed_resolver, _) = &*self.expansion()?.peek();
let crate_name = self.crate_name()?.peek();
passes::prepare_outputs(
self.session(),
self.compiler,
krate,
&*boxed_resolver,
&crate_name,
)
})
}
pub fn global_ctxt(&'tcx self) -> Result<&Query<QueryContext<'tcx>>> {
self.global_ctxt.compute(|| {
let crate_name = self.crate_name()?.peek().clone();
let outputs = self.prepare_outputs()?.peek().clone();
let dep_graph = self.dep_graph()?.peek().clone();
let (krate, resolver, lint_store) = self.expansion()?.take();
Ok(passes::create_global_ctxt(
self.compiler,
lint_store,
krate,
dep_graph,
resolver,
outputs,
&crate_name,
&self.queries,
&self.gcx,
&self.arena,
&self.hir_arena,
))
})
}
pub fn ongoing_codegen(&'tcx self) -> Result<&Query<Box<dyn Any>>> {
self.ongoing_codegen.compute(|| {
let outputs = self.prepare_outputs()?;
self.global_ctxt()?.peek_mut().enter(|tcx| {
tcx.analysis(()).ok();
// Don't do code generation if there were any errors
self.session().compile_status()?;
// Hook for UI tests.
Self::check_for_rustc_errors_attr(tcx);
Ok(passes::start_codegen(&***self.codegen_backend(), tcx, &*outputs.peek()))
})
})
}
/// Check for the `#[rustc_error]` annotation, which forces an error in codegen. This is used
/// to write UI tests that actually test that compilation succeeds without reporting
/// an error.
fn check_for_rustc_errors_attr(tcx: TyCtxt<'_>) {
let def_id = match tcx.entry_fn(()) {
Some((def_id, _)) => def_id,
_ => return,
};
let attrs = &*tcx.get_attrs(def_id);
let attrs = attrs.iter().filter(|attr| attr.has_name(sym::rustc_error));
for attr in attrs {
match attr.meta_item_list() {
// Check if there is a `#[rustc_error(delay_span_bug_from_inside_query)]`.
Some(list)
if list.iter().any(|list_item| {
matches!(
list_item.ident().map(|i| i.name),
Some(sym::delay_span_bug_from_inside_query)
)
}) =>
{
tcx.ensure().trigger_delay_span_bug(def_id);
}
// Bare `#[rustc_error]`.
None => {
tcx.sess.span_fatal(
tcx.def_span(def_id),
"fatal error triggered by #[rustc_error]",
);
}
// Some other attribute.
Some(_) => {
tcx.sess.span_warn(
tcx.def_span(def_id),
"unexpected annotation used with `#[rustc_error(...)]!",
);
}
}
}
}
pub fn linker(&'tcx self) -> Result<Linker> {
let sess = self.session().clone();
let codegen_backend = self.codegen_backend().clone();
let dep_graph = self.dep_graph()?.peek().clone();
let prepare_outputs = self.prepare_outputs()?.take();
let crate_hash = self.global_ctxt()?.peek_mut().enter(|tcx| tcx.crate_hash(LOCAL_CRATE));
let ongoing_codegen = self.ongoing_codegen()?.take();
Ok(Linker {
sess,
codegen_backend,
dep_graph,
prepare_outputs,
crate_hash,
ongoing_codegen,
})
}
}
pub struct Linker {
// compilation inputs
sess: Lrc<Session>,
codegen_backend: Lrc<Box<dyn CodegenBackend>>,
// compilation outputs
dep_graph: DepGraph,
prepare_outputs: OutputFilenames,
crate_hash: Svh,
ongoing_codegen: Box<dyn Any>,
}
impl Linker {
pub fn link(self) -> Result<()> {
let (codegen_results, work_products) =
self.codegen_backend.join_codegen(self.ongoing_codegen, &self.sess)?;
self.sess.compile_status()?;
let sess = &self.sess;
let dep_graph = self.dep_graph;
sess.time("serialize_work_products", || {
rustc_incremental::save_work_product_index(sess, &dep_graph, work_products)
});
let prof = self.sess.prof.clone();
prof.generic_activity("drop_dep_graph").run(move || drop(dep_graph));
// Now that we won't touch anything in the incremental compilation directory
// any more, we can finalize it (which involves renaming it)
rustc_incremental::finalize_session_directory(&self.sess, self.crate_hash);
if !self
.sess
.opts
.output_types
.keys()
.any(|&i| i == OutputType::Exe || i == OutputType::Metadata)
{
return Ok(());
}
if sess.opts.debugging_opts.no_link {
// FIXME: use a binary format to encode the `.rlink` file
let rlink_data = json::encode(&codegen_results).map_err(|err| {
sess.fatal(&format!("failed to encode rlink: {}", err));
})?;
let rlink_file = self.prepare_outputs.with_extension(config::RLINK_EXT);
std::fs::write(&rlink_file, rlink_data).map_err(|err| {
sess.fatal(&format!("failed to write file {}: {}", rlink_file.display(), err));
})?;
return Ok(());
}
let _timer = sess.prof.verbose_generic_activity("link_crate");
self.codegen_backend.link(&self.sess, codegen_results, &self.prepare_outputs)
}
}
impl Compiler {
pub fn enter<F, T>(&self, f: F) -> T
where
F: for<'tcx> FnOnce(&'tcx Queries<'tcx>) -> T,
{
let mut _timer = None;
let queries = Queries::new(self);
let ret = f(&queries);
// NOTE: intentionally does not compute the global context if it hasn't been built yet,
// since that likely means there was a parse error.
if let Some(Ok(gcx)) = &mut *queries.global_ctxt.result.borrow_mut() {
// We assume that no queries are run past here. If there are new queries
// after this point, they'll show up as "<unknown>" in self-profiling data.
{
let _prof_timer =
queries.session().prof.generic_activity("self_profile_alloc_query_strings");
gcx.enter(rustc_query_impl::alloc_self_profile_query_strings);
}
if self.session().opts.debugging_opts.query_stats {
gcx.enter(rustc_query_impl::print_stats);
}
self.session()
.time("serialize_dep_graph", || gcx.enter(rustc_incremental::save_dep_graph));
}
_timer = Some(self.session().timer("free_global_ctxt"));
ret
}
}
| {
"content_hash": "41b7246bbdbe99b351a4aa7e9291bdf0",
"timestamp": "",
"source": "github",
"line_count": 415,
"max_line_length": 100,
"avg_line_length": 36.0722891566265,
"alnum_prop": 0.5376085504342017,
"repo_name": "graydon/rust",
"id": "f188ad35605af69e6ca4e1fcf283cd891d526a4f",
"size": "14970",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "compiler/rustc_interface/src/queries.rs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "4990"
},
{
"name": "Assembly",
"bytes": "20064"
},
{
"name": "Awk",
"bytes": "159"
},
{
"name": "Bison",
"bytes": "78848"
},
{
"name": "C",
"bytes": "725899"
},
{
"name": "C++",
"bytes": "55803"
},
{
"name": "CSS",
"bytes": "22181"
},
{
"name": "JavaScript",
"bytes": "36295"
},
{
"name": "LLVM",
"bytes": "1587"
},
{
"name": "Makefile",
"bytes": "227056"
},
{
"name": "Puppet",
"bytes": "16300"
},
{
"name": "Python",
"bytes": "142548"
},
{
"name": "RenderScript",
"bytes": "99815"
},
{
"name": "Rust",
"bytes": "18342682"
},
{
"name": "Shell",
"bytes": "269546"
},
{
"name": "TeX",
"bytes": "57"
}
],
"symlink_target": ""
} |
set -e
grunt build
grunt test:unit
grunt test:e2e
if [ $TRAVIS_TAG ]; then
grunt sauce:unit;
fi
| {
"content_hash": "fb34bf392c6e9e9c43cf16174fd4c77e",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 24,
"avg_line_length": 14,
"alnum_prop": 0.7142857142857143,
"repo_name": "itxd/angularfire",
"id": "f13aebd200b25cdb004758c0f9917a671fa5a4ed",
"size": "110",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "tests/travis.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "185"
},
{
"name": "HTML",
"bytes": "5926"
},
{
"name": "JavaScript",
"bytes": "221713"
},
{
"name": "Shell",
"bytes": "110"
}
],
"symlink_target": ""
} |
#ifndef StringObjectThatMasqueradesAsUndefined_h
#define StringObjectThatMasqueradesAsUndefined_h
#include "JSGlobalObject.h"
#include "StringObject.h"
#include "UString.h"
namespace JSC {
// WebCore uses this to make style.filter undetectable
class StringObjectThatMasqueradesAsUndefined : public StringObject {
public:
static StringObjectThatMasqueradesAsUndefined* create(ExecState* exec, const UString& string)
{
return new (exec) StringObjectThatMasqueradesAsUndefined(exec,
createStructure(exec->lexicalGlobalObject()->stringPrototype()), string);
}
private:
StringObjectThatMasqueradesAsUndefined(ExecState* exec, NonNullPassRefPtr<Structure> structure, const UString& string)
: StringObject(exec, structure, string)
{
}
static PassRefPtr<Structure> createStructure(JSValue proto)
{
return Structure::create(proto, TypeInfo(ObjectType, StructureFlags));
}
static const unsigned StructureFlags = OverridesGetOwnPropertySlot | MasqueradesAsUndefined | OverridesGetPropertyNames | StringObject::StructureFlags;
virtual bool toBoolean(ExecState*) const { return false; }
};
} // namespace JSC
#endif // StringObjectThatMasqueradesAsUndefined_h
| {
"content_hash": "c2bdbe2eec63e7d11531056828b9d265",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 159,
"avg_line_length": 33.8974358974359,
"alnum_prop": 0.7193645990922845,
"repo_name": "kzhong1991/Flight-AR.Drone-2",
"id": "69e1939635f7ff0a85bf9b03fa8c638916f601aa",
"size": "2203",
"binary": false,
"copies": "18",
"ref": "refs/heads/master",
"path": "src/3rdparty/Qt4.8.4/src/3rdparty/javascriptcore/JavaScriptCore/runtime/StringObjectThatMasqueradesAsUndefined.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "8366"
},
{
"name": "C++",
"bytes": "172001"
},
{
"name": "Objective-C",
"bytes": "7651"
},
{
"name": "QMake",
"bytes": "1293"
}
],
"symlink_target": ""
} |
using MarvelAPI.Parameters;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MarvelAPI.Requests
{
public class EventRequest : BaseRequest
{
public EventRequest(string publicApiKey, string privateApiKey, IRestClient client, bool? useGZip = null)
: base(publicApiKey, privateApiKey, client, useGZip)
{
}
/// <summary>
/// Fetches lists of events with optional filters.
/// </summary>
/// <returns>
/// Lists of events
/// </returns>
public IEnumerable<Event> GetEvents(GetEvents model)
{
var request = CreateRequest("/events");
if (!string.IsNullOrWhiteSpace(model.Name))
{
request.AddParameter("name", model.Name);
}
if (!string.IsNullOrWhiteSpace(model.NameStartsWith))
{
request.AddParameter("nameStartsWith", model.NameStartsWith);
}
if (model.ModifiedSince.HasValue)
{
request.AddParameter("modifiedSince", model.ModifiedSince.Value.ToString("yyyy-MM-dd"));
}
request.AddParameterList(model.Creators, "creators");
request.AddParameterList(model.Characters, "characters");
request.AddParameterList(model.Series, "series");
request.AddParameterList(model.Comics, "comics");
request.AddParameterList(model.Stories, "stories");
var availableOrderBy = new List<OrderBy>
{
OrderBy.Name,
OrderBy.NameDesc,
OrderBy.StartDate,
OrderBy.StartDateDesc,
OrderBy.Modified,
OrderBy.ModifiedDesc
};
request.AddOrderByParameterList(model.Order, availableOrderBy);
if (model.Limit.HasValue && model.Limit.Value > 0)
{
request.AddParameter("limit", model.Limit.Value.ToString());
}
if (model.Offset.HasValue && model.Offset.Value > 0)
{
request.AddParameter("offset", model.Offset.Value.ToString());
}
IRestResponse<Wrapper<Event>> response = Client.Execute<Wrapper<Event>>(request);
HandleResponseErrors(response);
return response.Data.Data.Results;
}
/// <summary>
/// This method fetches a single event resource. It is the canonical URI for any event resource provided by the API.
/// </summary>
/// <returns>
/// A single event resource
/// </returns>
public Event GetEvent(int eventId)
{
var request = CreateRequest($"/events/{eventId}");
IRestResponse<Wrapper<Event>> response = Client.Execute<Wrapper<Event>>(request);
HandleResponseErrors(response);
return response.Data.Data.Results.FirstOrDefault(ev => ev.Id == eventId);
}
/// <summary>
/// Fetches lists of characters which appear in a specific event, with optional filters.
/// </summary>
/// <returns>
/// Lists of characters which appear in a specific event
/// </returns>
public IEnumerable<Character> GetCharactersForEvent(GetCharactersForEvent model)
{
var request = CreateRequest($"/events/{model.EventId}/characters");
if (!string.IsNullOrWhiteSpace(model.Name))
{
request.AddParameter("name", model.Name);
}
if (!string.IsNullOrWhiteSpace(model.NameStartsWith))
{
request.AddParameter("nameStartsWith", model.NameStartsWith);
}
if (model.ModifiedSince.HasValue)
{
request.AddParameter("modifiedSince", model.ModifiedSince.Value.ToString("yyyy-MM-dd"));
}
request.AddParameterList(model.Comics, "comics");
request.AddParameterList(model.Series, "series");
request.AddParameterList(model.Stories, "stories");
var availableOrderBy = new List<OrderBy>
{
OrderBy.Name,
OrderBy.NameDesc,
OrderBy.Modified,
OrderBy.ModifiedDesc
};
request.AddOrderByParameterList(model.Order, availableOrderBy);
if (model.Limit.HasValue && model.Limit.Value > 0)
{
request.AddParameter("limit", model.Limit.Value.ToString());
}
if (model.Offset.HasValue && model.Offset.Value > 0)
{
request.AddParameter("offset", model.Offset.Value.ToString());
}
IRestResponse<Wrapper<Character>> response = Client.Execute<Wrapper<Character>>(request);
HandleResponseErrors(response);
return response.Data.Data.Results;
}
/// <summary>
/// Fetches lists of comics which take place during a specific event, with optional filters.
/// </summary>
/// <returns>
/// Lists of comics which take place during a specific event
/// </returns>
public IEnumerable<Comic> GetComicsForEvent(GetComicsForEvent model)
{
var request = CreateRequest($"/events/{model.EventId}/comics");
if (model.Format.HasValue)
{
request.AddParameter("format", model.Format.Value.ToParameter());
}
if (model.FormatType.HasValue)
{
request.AddParameter("formatType", model.FormatType.Value.ToParameter());
}
if (model.NoVariants.HasValue)
{
request.AddParameter("noVariants", model.NoVariants.Value.ToString().ToLower());
}
if (model.DateDescript.HasValue)
{
request.AddParameter("dateDescriptor", model.DateDescript.Value.ToParameter());
}
if (model.DateRangeBegin.HasValue && model.DateRangeEnd.HasValue)
{
if (model.DateRangeBegin.Value <= model.DateRangeEnd.Value)
{
request.AddParameter("dateRange", $"{model.DateRangeBegin.Value.ToString("yyyy -MM-dd")},{model.DateRangeEnd.Value.ToString("yyyy-MM-dd")}");
}
else
{
throw new ArgumentException("DateRangeBegin must be greater than DateRangeEnd");
}
}
else if (model.DateRangeBegin.HasValue || model.DateRangeEnd.HasValue)
{
throw new ArgumentException("Date Range requires both a start and end date");
}
if (model.HasDigitalIssue.HasValue)
{
request.AddParameter("hasDigitalIssue", model.HasDigitalIssue.Value.ToString().ToLower());
}
if (model.ModifiedSince.HasValue)
{
request.AddParameter("modifiedSince", model.ModifiedSince.Value.ToString("yyyy-MM-dd"));
}
request.AddParameterList(model.Creators, "creators");
request.AddParameterList(model.Characters, "characters");
request.AddParameterList(model.Series, "series");
request.AddParameterList(model.Events, "events");
request.AddParameterList(model.Stories, "stories");
request.AddParameterList(model.SharedAppearances, "sharedAppearances");
request.AddParameterList(model.Collaborators, "collaborators");
var availableOrderBy = new List<OrderBy>
{
OrderBy.FocDate,
OrderBy.FocDateDesc,
OrderBy.OnSaleDate,
OrderBy.OnSaleDateDesc,
OrderBy.Title,
OrderBy.TitleDesc,
OrderBy.IssueNumber,
OrderBy.IssueNumberDesc,
OrderBy.Modified,
OrderBy.ModifiedDesc
};
request.AddOrderByParameterList(model.Order, availableOrderBy);
if (model.Limit.HasValue && model.Limit.Value > 0)
{
request.AddParameter("limit", model.Limit.Value.ToString());
}
if (model.Offset.HasValue && model.Offset.Value > 0)
{
request.AddParameter("offset", model.Offset.Value.ToString());
}
IRestResponse<Wrapper<Comic>> response = Client.Execute<Wrapper<Comic>>(request);
HandleResponseErrors(response);
return response.Data.Data.Results;
}
/// <summary>
/// Fetches lists of comic creators whose work appears in a specific event, with optional filters.
/// </summary>
/// <returns>
/// Lists of comic creators whose work appears in a specific event
/// </returns>
public IEnumerable<Creator> GetCreatorsForEvent(GetCreatorsForEvent model)
{
var request = CreateRequest($"/events/{model.EventId}/creators");
if (!string.IsNullOrWhiteSpace(model.FirstName))
{
request.AddParameter("firstName", model.FirstName);
}
if (!string.IsNullOrWhiteSpace(model.MiddleName))
{
request.AddParameter("middleName", model.MiddleName);
}
if (!string.IsNullOrWhiteSpace(model.LastName))
{
request.AddParameter("lastName", model.LastName);
}
if (!string.IsNullOrWhiteSpace(model.Suffix))
{
request.AddParameter("suffix", model.Suffix);
}
if (!string.IsNullOrWhiteSpace(model.NameStartsWith))
{
request.AddParameter("nameStartsWith", model.NameStartsWith);
}
if (!string.IsNullOrWhiteSpace(model.FirstNameStartsWith))
{
request.AddParameter("firstNameStartsWith", model.FirstNameStartsWith);
}
if (!string.IsNullOrWhiteSpace(model.MiddleNameStartsWith))
{
request.AddParameter("middleNameStartsWith", model.MiddleNameStartsWith);
}
if (!string.IsNullOrWhiteSpace(model.LastNameStartsWith))
{
request.AddParameter("lastNameStartsWith", model.LastNameStartsWith);
}
if (model.ModifiedSince.HasValue)
{
request.AddParameter("modifiedSince", model.ModifiedSince.Value.ToString("yyyy-MM-dd"));
}
request.AddParameterList(model.Comics, "comics");
request.AddParameterList(model.Series, "series");
request.AddParameterList(model.Stories, "stories");
var availableOrderBy = new List<OrderBy>
{
OrderBy.FirstName,
OrderBy.FirstNameDesc,
OrderBy.MiddleName,
OrderBy.MiddleNameDesc,
OrderBy.LastName,
OrderBy.LastNameDesc,
OrderBy.Suffix,
OrderBy.SuffixDesc,
OrderBy.Modified,
OrderBy.ModifiedDesc
};
request.AddOrderByParameterList(model.Order, availableOrderBy);
if (model.Limit.HasValue && model.Limit.Value > 0)
{
request.AddParameter("limit", model.Limit.Value.ToString());
}
if (model.Offset.HasValue && model.Offset.Value > 0)
{
request.AddParameter("offset", model.Offset.Value.ToString());
}
IRestResponse<Wrapper<Creator>> response = Client.Execute<Wrapper<Creator>>(request);
HandleResponseErrors(response);
return response.Data.Data.Results;
}
/// <summary>
/// Fetches lists of comic series in which a specific event takes place, with optional filters.
/// </summary>
/// <returns>
/// Lists of comic series in which a specific event takes place
/// </returns>
public IEnumerable<Series> GetSeriesForEvent(GetSeriesForEvent model)
{
var request = CreateRequest($"/events/{model.EventId}/series");
if (!string.IsNullOrWhiteSpace(model.Title))
{
request.AddParameter("title", model.Title);
}
if (!string.IsNullOrWhiteSpace(model.TitleStartsWith))
{
request.AddParameter("titleStartsWith", model.TitleStartsWith);
}
if (model.ModifiedSince.HasValue)
{
request.AddParameter("modifiedSince", model.ModifiedSince.Value.ToString("yyyy-MM-dd"));
}
request.AddParameterList(model.Comics, "comics");
request.AddParameterList(model.Stories, "stories");
request.AddParameterList(model.Creators, "creators");
request.AddParameterList(model.Characters, "characters");
if (model.SeriesType.HasValue)
{
request.AddParameter("seriesType", model.SeriesType.Value.ToParameter());
}
if (model.Contains != null && model.Contains.Any())
{
var containsParameters = model.Contains.Select(contain => contain.ToParameter());
request.AddParameter("contains", string.Join(",", containsParameters));
}
var availableOrderBy = new List<OrderBy>
{
OrderBy.Title,
OrderBy.TitleDesc,
OrderBy.StartYear,
OrderBy.StartYearDesc,
OrderBy.Modified,
OrderBy.ModifiedDesc
};
request.AddOrderByParameterList(model.Order, availableOrderBy);
if (model.Limit.HasValue && model.Limit.Value > 0)
{
request.AddParameter("limit", model.Limit.Value.ToString());
}
if (model.Offset.HasValue && model.Offset.Value > 0)
{
request.AddParameter("offset", model.Offset.Value.ToString());
}
IRestResponse<Wrapper<Series>> response = Client.Execute<Wrapper<Series>>(request);
HandleResponseErrors(response);
return response.Data.Data.Results;
}
/// <summary>
/// Fetches lists of comic stories from a specific event, with optional filters.
/// </summary>
/// <returns>
/// Lists of comic stories from a specific event
/// </returns>
public IEnumerable<Story> GetStoriesForEvent(GetStoriesForEvent model)
{
var request = CreateRequest($"/events/{model.EventId}/stories");
if (model.ModifiedSince.HasValue)
{
request.AddParameter("modifiedSince", model.ModifiedSince.Value.ToString("yyyy-MM-dd"));
}
request.AddParameterList(model.Comics, "comics");
request.AddParameterList(model.Series, "series");
request.AddParameterList(model.Creators, "creators");
request.AddParameterList(model.Characters, "characters");
var availableOrderBy = new List<OrderBy>
{
OrderBy.Id,
OrderBy.IdDesc,
OrderBy.Modified,
OrderBy.ModifiedDesc
};
request.AddOrderByParameterList(model.Order, availableOrderBy);
if (model.Limit.HasValue && model.Limit.Value > 0)
{
request.AddParameter("limit", model.Limit.Value.ToString());
}
if (model.Offset.HasValue && model.Offset.Value > 0)
{
request.AddParameter("offset", model.Offset.Value.ToString());
}
IRestResponse<Wrapper<Story>> response = Client.Execute<Wrapper<Story>>(request);
HandleResponseErrors(response);
return response.Data.Data.Results;
}
}
}
| {
"content_hash": "820d8b48b4fdbd75635fc5f62765f7cc",
"timestamp": "",
"source": "github",
"line_count": 425,
"max_line_length": 161,
"avg_line_length": 38.131764705882354,
"alnum_prop": 0.5640503517215846,
"repo_name": "foilking/MarvelAPI",
"id": "133afdd1aadb2104f22e34475e3069807eff8c92",
"size": "16208",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MarvelAPI/Requests/EventRequest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "108"
},
{
"name": "C#",
"bytes": "245420"
},
{
"name": "CSS",
"bytes": "15954"
},
{
"name": "HTML",
"bytes": "5275"
},
{
"name": "JavaScript",
"bytes": "3428942"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DocStrap Source: strings/format.js</title>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">
<link type="text/css" rel="stylesheet" href="styles/site.cyborg.css">
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="index.html">DocStrap</a>
</div>
<div class="navbar-collapse">
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="modules.list.html" class="dropdown-toggle" data-toggle="dropdown">Modules<b class="caret"></b></a>
<ul class="dropdown-menu ">
<li><a href="module-base.html">base</a></li><li><a href="module-base_chains.html">base/chains</a></li><li><a href="module-documents_binder.html">documents/binder</a></li><li><a href="module-documents_model.html">documents/model</a></li><li><a href="module-documents_probe.html">documents/probe</a></li><li><a href="module-documents_schema.html">documents/schema</a></li><li><a href="module-ink_collector.html">ink/collector</a></li><li><a href="module-mixins_bussable.html">mixins/bussable</a></li><li><a href="module-mixins_signalable.html">mixins/signalable</a></li><li><a href="module-strings_format.html">strings/format</a></li><li><a href="module-utils_logger.html">utils/logger</a></li>
</ul>
</li>
<li class="dropdown">
<a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a>
<ul class="dropdown-menu ">
<li><a href="base.html">base</a></li><li><a href="base_chains.html">base/chains</a></li><li><a href="documents_model.html">documents/model</a></li><li><a href="module-documents_probe.This%252520is%252520not%252520actually%252520a%252520class,%252520but%252520an%252520artifact%252520of%252520the%252520documentation%252520system.html">documents/probe.This is not actually a class, but an artifact of the documentation system</a></li><li><a href="module-ink_collector-ACollector.html">ink/collector~ACollector</a></li><li><a href="module-ink_collector-CollectorBase.html">ink/collector~CollectorBase</a></li><li><a href="module-ink_collector-OCollector.html">ink/collector~OCollector</a></li><li><a href="module-mixins_signalable-Signal.html">mixins/signalable~Signal</a></li><li><a href="utils_logger.Logger.html">utils/logger.Logger</a></li>
</ul>
</li>
<li class="dropdown">
<a href="mixins.list.html" class="dropdown-toggle" data-toggle="dropdown">Mixins<b class="caret"></b></a>
<ul class="dropdown-menu ">
<li><a href="documents_schema.html">documents/schema</a></li><li><a href="mixins_bussable.html">mixins/bussable</a></li><li><a href="mixins_signalable.html">mixins/signalable</a></li>
</ul>
</li>
<li class="dropdown">
<a href="tutorials.list.html" class="dropdown-toggle" data-toggle="dropdown">Tutorials<b class="caret"></b></a>
<ul class="dropdown-menu ">
<li><a href="tutorial-Brush Teeth.html">Brush Teeth</a></li><li><a href="tutorial-Drive Car.html">Drive Car</a></li><li><a href="tutorial-Fence Test.html">Fence Test</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="main">
<h1 class="page-title">Source: strings/format.js</h1>
<h1 class="page-title">Source: strings/format.js</h1>
<section>
<article>
<pre
class="sunlight-highlight-javascript linenums">"use strict";
/**
* @fileOverview String helper methods
*
* @module strings/format
*/
/**
* Format a string quickly and easily using .net style format strings
* @param {string} format A string format like "Hello {0}, now take off your {1}!"
* @param {...?} args One argument per `{}` in the string, positionally replaced
* @returns {string}
*
* @example
* var strings = require("papyrus/strings");
* var s = strings.format("Hello {0}", "Madame Vastra");
* // s = "Hello Madame Vastra"
*
* @example {@lang xml}
* <span>
* <%= strings.format("Hello {0}", "Madame Vastra") %>
* </span>
*/
module.exports = function ( format ) {
var args = Array.prototype.slice.call( arguments, 1 );
return format.replace( /{(\d+)}/g, function ( match, number ) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
} );
};
</pre>
</article>
</section>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
<footer>
<span class="copyright">
DocStrap Copyright © 2012-2013 The contributors to the JSDoc3 and DocStrap projects.
</span>
<br />
<span class="jsdoc-message">
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.0-beta1</a>
on Thu Feb 5th 2015 using the <a
href="https://github.com/terryweiss/docstrap">DocStrap template</a>.
</span>
</footer>
<!--<script src="scripts/sunlight.js"></script>-->
<script src="scripts/docstrap.lib.js"></script>
<script src="scripts/bootstrap-dropdown.js"></script>
<script src="scripts/toc.js"></script>
<script>
$( function () {
$( "[id*='$']" ).each( function () {
var $this = $( this );
$this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) );
} );
$( "#toc" ).toc( {
anchorName : function ( i, heading, prefix ) {
return $( heading ).attr( "id" ) || ( prefix + i );
},
selectors : "h1,h2,h3,h4",
showAndHide : false,
scrollTo : "100px"
} );
$( "#toc>ul" ).addClass( "nav nav-pills nav-stacked" );
$( "#main span[id^='toc']" ).addClass( "toc-shim" );
$( '.dropdown-toggle' ).dropdown();
// $( ".tutorial-section pre, .readme-section pre" ).addClass( "sunlight-highlight-javascript" ).addClass( "linenums" );
$( ".tutorial-section pre, .readme-section pre" ).each( function () {
var $this = $( this );
var example = $this.find( "code" );
exampleText = example.html();
var lang = /{@lang (.*?)}/.exec( exampleText );
if ( lang && lang[1] ) {
exampleText = exampleText.replace( lang[0], "" );
example.html( exampleText );
lang = lang[1];
} else {
lang = "javascript";
}
if ( lang ) {
$this
.addClass( "sunlight-highlight-" + lang )
.addClass( "linenums" )
.html( example.html() );
}
} );
Sunlight.highlightAll( {
lineNumbers : true,
showMenu : true,
enableDoclinks : true
} );
} );
</script>
<!--Navigation and Symbol Display-->
<!--Google Analytics-->
</body>
</html>
| {
"content_hash": "896b079f104d930f5d9c91c1b3a78830",
"timestamp": "",
"source": "github",
"line_count": 210,
"max_line_length": 847,
"avg_line_length": 31.33809523809524,
"alnum_prop": 0.6445828901382769,
"repo_name": "labertasch/awesome",
"id": "a8bbdd245ef4824721d35cfea9292ad2413cdf92",
"size": "6582",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "stream/node_modules/grunt-jsdoc/node_modules/ink-docstrap/themes/cyborg/strings_format.js.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2579331"
},
{
"name": "HTML",
"bytes": "172677"
},
{
"name": "Java",
"bytes": "26469"
},
{
"name": "JavaScript",
"bytes": "2286722"
},
{
"name": "TypeScript",
"bytes": "1118"
}
],
"symlink_target": ""
} |
$DefaultPSRepositoryUrl = "https://www.powershellgallery.com/api/v2"
$global:CurrentUserModulePath = ""
function Update-PSModulePathForCI()
{
# Information on PSModulePath taken from docs
# https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_psmodulepath
# Information on Az custom module paths on hosted agents taken from
# https://github.com/microsoft/azure-pipelines-tasks/blob/c9771bc064cd60f47587c68e5c871b7cd13f0f28/Tasks/AzurePowerShellV5/Utility.ps1
if ($IsWindows) {
$hostedAgentModulePath = $env:SystemDrive + "\Modules"
$moduleSeperator = ";"
} else {
$hostedAgentModulePath = "/usr/share"
$moduleSeperator = ":"
}
$modulePaths = $env:PSModulePath -split $moduleSeperator
# Remove any hosted agent paths (needed to remove old default azure/azurerm paths which cause conflicts)
$modulePaths = $modulePaths.Where({ !$_.StartsWith($hostedAgentModulePath) })
# Add any "az_" paths from the agent which is the lastest set of azure modules
$AzModuleCachePath = (Get-ChildItem "$hostedAgentModulePath/az_*" -Attributes Directory) -join $moduleSeperator
if ($AzModuleCachePath -and $env:PSModulePath -notcontains $AzModuleCachePath) {
$modulePaths += $AzModuleCachePath
}
$env:PSModulePath = $modulePaths -join $moduleSeperator
# Find the path that is under user home directory
$homeDirectories = $modulePaths.Where({ $_.StartsWith($home) })
if ($homeDirectories.Count -gt 0) {
$global:CurrentUserModulePath = $homeDirectories[0]
if ($homeDirectories.Count -gt 1) {
Write-Verbose "Found more then one module path starting with $home so selecting the first one $global:CurrentUserModulePath"
}
# In some cases the directory might not exist so we need to create it otherwise caching an empty directory will fail
if (!(Test-Path $global:CurrentUserModulePath)) {
New-Item $global:CurrentUserModulePath -ItemType Directory > $null
}
}
else {
Write-Error "Did not find a module path starting with $home to set up a user module path in $env:PSModulePath"
}
}
# If we want to use another default repository other then PSGallery we can update the default parameters
function Install-ModuleIfNotInstalled()
{
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[string]$moduleName,
[string]$version,
[string]$repositoryUrl = $DefaultPSRepositoryUrl
)
# Check installed modules
$modules = (Get-Module -ListAvailable $moduleName)
if ($version -as [Version]) {
$modules = $modules.Where({ [Version]$_.Version -ge [Version]$version })
}
if ($modules.Count -eq 0)
{
$repositories = (Get-PSRepository).Where({ $_.SourceLocation -eq $repositoryUrl })
if ($repositories.Count -eq 0)
{
Register-PSRepository -Name $repositoryUrl -SourceLocation $repositoryUrl -InstallationPolicy Trusted
$repositories = (Get-PSRepository).Where({ $_.SourceLocation -eq $repositoryUrl })
if ($repositories.Count -eq 0) {
Write-Error "Failed to registory package repository $repositoryUrl."
return
}
}
$repository = $repositories[0]
if ($repository.InstallationPolicy -ne "Trusted") {
Set-PSRepository -Name $repository.Name -InstallationPolicy "Trusted"
}
Write-Host "Installing module $moduleName with min version $version from $repositoryUrl"
# Install under CurrentUser scope so that the end up under $CurrentUserModulePath for caching
Install-Module $moduleName -MinimumVersion $version -Repository $repository.Name -Scope CurrentUser -Force
# Ensure module installed
$modules = (Get-Module -ListAvailable $moduleName)
if ($version -as [Version]) {
$modules = $modules.Where({ [Version]$_.Version -ge [Version]$version })
}
if ($modules.Count -eq 0) {
Write-Error "Failed to install module $moduleName with version $version"
return
}
}
Write-Host "Using module $($modules[0].Name) with version $($modules[0].Version)."
return $modules[0]
}
if ($null -ne $env:SYSTEM_TEAMPROJECTID) {
Update-PSModulePathForCI
}
| {
"content_hash": "9e479571dcc3622ad3c158c3da9f85d1",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 136,
"avg_line_length": 38.79245283018868,
"alnum_prop": 0.7169260700389105,
"repo_name": "Azure/azure-sdk-for-go",
"id": "d9a5afaab1b31023651f936609cfe6fd2be556c6",
"size": "4112",
"binary": false,
"copies": "4",
"ref": "refs/heads/main",
"path": "eng/common/scripts/Helpers/PSModule-Helpers.ps1",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1629"
},
{
"name": "Bicep",
"bytes": "8394"
},
{
"name": "CSS",
"bytes": "6089"
},
{
"name": "Dockerfile",
"bytes": "1435"
},
{
"name": "Go",
"bytes": "5463500"
},
{
"name": "HTML",
"bytes": "8933"
},
{
"name": "JavaScript",
"bytes": "8137"
},
{
"name": "PowerShell",
"bytes": "504494"
},
{
"name": "Shell",
"bytes": "3893"
},
{
"name": "Smarty",
"bytes": "1723"
}
],
"symlink_target": ""
} |
<?php
/**
* This is extended cache manager with additional methods to work
* with cache tags.
*
* The most important difference from sfViewCacheManager is support to use
* sepparate cache systems for data and locks (performance reasons).
*
* By default data and lock cache system is same.
*
* @package sfCacheTaggingPlugin
* @subpackage view
* @author Ilya Sabelnikov <fruit.dev@gmail.com>
*/
class sfViewCacheTagManager extends sfViewCacheManager
{
/**
* holder's namespaces
* Namespace name should be "UpperCamelCased"
* This names is used in method patterns "call%sMethod",
* where %s is Page/Action/Partial
*/
const NAMESPACE_PAGE = 'Page';
const NAMESPACE_ACTION = 'Action';
const NAMESPACE_PARTIAL = 'Partial';
/**
* Data cache and locker cache container
*
* @var sfTaggingCache
*/
protected $taggingCache = null;
/**
* sfViewCacheTagManager option holder
*
* @var array
*/
protected $options = array();
/**
* Partial tags passed to include_partial by option "sf_cache_tag"
* Stored in temp variable due to unavailability of variables
* action and module names
*
* @var mixed
*/
protected $temporaryContentTags = null;
/**
* Returns predefined namespaces
*
* @return array Array of declared content namespaces
*/
public static function getNamespaces ()
{
return array(
self::NAMESPACE_PAGE,
self::NAMESPACE_ACTION,
self::NAMESPACE_PARTIAL,
);
}
/**
* sfViewCacheTagManager options
*
* @return array
*/
public function getOptions ()
{
return $this->options;
}
/**
* Sets options to the sfTaggingCache
*
* @param array $options
*/
public function setOptions (array $options)
{
$this->options = $options;
}
/**
* @return sfContentTagHandler
*/
public function getContentTagHandler ()
{
return $this->getTaggingCache()->getContentTagHandler();
}
/**
* @return sfEventDispatcher
*/
public function getEventDispatcher ()
{
return $this->dispatcher;
}
/**
* @param sfEventDispatcher $eventDispatcher
* @return sfViewCacheTagManager
*/
protected function setEventDispatcher (sfEventDispatcher $eventDispatcher)
{
$this->dispatcher = $eventDispatcher;
return $this;
}
/**
* Initialize cache manager
*
* @param sfContext $context
* @param sfCache $taggingCache
* @param array $options
*
* @see sfViewCacheManager::initialize()
*/
public function initialize ($context, sfCache $taggingCache, $options = array())
{
if (! $taggingCache instanceof sfTaggingCache)
{
throw new InvalidArgumentException(sprintf(
'Cache "%s" is not instanceof sfTaggingCache',
get_class($taggingCache)
));
}
$this->setTaggingCache($taggingCache);
$this->cache = $this->getTaggingCache()->getCache();
$this->setEventDispatcher($context->getEventDispatcher());
$this->context = $context;
$this->controller = $context->getController();
$this->request = $context->getRequest();
$this->routing = $context->getRouting();
$this->setOptions(array_merge(
array(
'cache_key_use_vary_headers' => true,
'cache_key_use_host_name' => true,
),
$options
));
if (sfConfig::get('sf_web_debug'))
{
$this->getEventDispatcher()->connect(
'view.cache.filter_content',
array($this, 'decorateContentWithDebug')
);
}
// empty configuration
$this->cacheConfig = array();
}
/**
* Retrieves sfTaggingCache object
*
* @return sfTaggingCache
*/
public function getTaggingCache ()
{
return $this->taggingCache;
}
/**
* Sets sfTaggingCache object
*
* @param sfTaggingCache $taggingCache
* @return sfViewCacheTagManager
*/
protected function setTaggingCache (sfTaggingCache $taggingCache)
{
$this->taggingCache = $taggingCache;
return $this;
}
/**
* @return sfController
*/
protected function getController ()
{
return $this->controller;
}
/**
* Due to an optimized version (self::_get) and compatibility
*
* @param string $internalUri
* @return mixed
*/
public function get ($internalUri)
{
return serialize($this->_get($internalUri));
}
/**
* Retrieves content in the cache.
*
* Match duplicated as a parent::get()
*
* Optimized version, does not call to serialize/unserialize when cache
* is stored as opcode
*
* @param string $internalUri Internal uniform resource identifier
* @return mixed The content in the cache
*/
protected function _get ($internalUri)
{
// no cache or no cache set for this action
if (! $this->isCacheable($internalUri) || $this->ignore())
{
return null;
}
$retval = $this->getTaggingCache()->get($this->generateCacheKey($internalUri));
$this->notify(sprintf(
'Cache for "%s" %s', $internalUri, $retval !== null ? 'exists' : 'does not exist'
));
return $retval;
}
/**
* Sets data to cache with passed tags
*
* @author Martin Schnabel <mcnilz@gmail.com>
* @author Ilya Sabelnikov <fruit.dev@gmail.com>
* @param string $internalUri
* @return mixed
*/
public function set ($data, $internalUri, $tags = array())
{
if (! $this->isCacheable($internalUri))
{
return false;
}
$this->getTaggingCache()->set(
$this->generateCacheKey($internalUri),
$data,
$this->getLifeTime($internalUri),
$tags
);
$this->notify(sprintf('Save cache for "%s"', $internalUri));
return true;
}
/**
* Returns true if there is a cache.
*
* @param string $internalUri Internal uniform resource identifier
*
* @return bool true, if there is a cache otherwise false
*/
public function has ($internalUri)
{
if (! $this->isCacheable($internalUri) || $this->ignore())
{
return null;
}
return $this->getTaggingCache()->has(
$this->generateCacheKey($internalUri)
);
}
/**
* Gets an action template from the cache.
*
* @param string $uri The internal URI
*
* @return array An array composed of the cached content and
* the view attribute holder
*/
public function getActionCache ($uri)
{
if (! $this->isCacheable($uri) || $this->withLayout($uri))
{
return null;
}
// retrieve content from cache
$cache = $this->_get($uri);
if (null === $cache)
{
return null;
}
$content = $cache['content'];
$cache['response'] = unserialize($cache['response']);
$cache['response']->setEventDispatcher($this->getEventDispatcher());
$this->getContext()->getResponse()->copyProperties($cache['response']);
if (sfConfig::get('sf_web_debug'))
{
$event = new sfEvent($this, 'view.cache.filter_content', array(
'response' => $this->getContext()->getResponse(),
'uri' => $uri,
'new' => false,
));
$content = $this
->getEventDispatcher()
->filter($event, $content)
->getReturnValue();
}
return array($content, $cache['decoratorTemplate']);
}
/**
* Sets an action template in the cache.
*
* @param string $uri The internal URI
* @param string $content The content to cache
* @param string $decoratorTemplate The view attribute holder to cache
*
* @return string The cached content
*/
public function setActionCache ($uri, $content, $decoratorTemplate)
{
if (! $this->isCacheable($uri) || $this->withLayout($uri))
{
return $content;
}
$contentTags = $this
->getContentTagHandler()
->getContentTags(self::NAMESPACE_ACTION);
$actionCacheValue = array(
'content' => $content,
'decoratorTemplate' => $decoratorTemplate,
'response' => serialize($this->getContext()->getResponse())
);
$saved = $this->set($actionCacheValue, $uri, $contentTags);
if ($saved && sfConfig::get('sf_web_debug'))
{
$event = new sfEvent($this, 'view.cache.filter_content', array(
'response' => $this->getContext()->getResponse(),
'uri' => $uri,
'new' => true,
));
$content = $this
->getEventDispatcher()
->filter($event, $content)
->getReturnValue();
}
return $content;
}
/**
* @see parent::setPageCache()
* @param string $uri
* @return null
*/
public function setPageCache ($uri)
{
if (sfView::RENDER_CLIENT != $this->getController()->getRenderMode())
{
return;
}
$contentTags = $this
->getContentTagHandler()
->getContentTags(self::NAMESPACE_PAGE);
$response = $this->getContext()->getResponse();
// save content in cache
$saved = $this->set($response, $uri, $contentTags);
if ($saved && sfConfig::get('sf_web_debug'))
{
$event = new sfEvent($this, 'view.cache.filter_content', array(
'response' => $response,
'uri' => $uri,
'new' => true,
));
$content = $this
->getEventDispatcher()
->filter($event, $response->getContent())
->getReturnValue();
$response->setContent($content);
}
}
/**
* Sets partial content with associated tags
*
* @see parent::setPartialCache()
*
* @param string $module
* @param string $action
* @param string $cacheKey
* @param string $content
* @return string
*/
public function setPartialCache ($module, $action, $cacheKey, $content)
{
$uri = $this->getPartialUri($module, $action, $cacheKey);
if (! $this->isCacheable($uri))
{
return $content;
}
$tagHandler = $this->getContentTagHandler();
$namespace = sprintf('%s-%s-%s', $module, $action, self::NAMESPACE_PARTIAL);
$contentTags = $tagHandler->getContentTags($namespace);
$response = $this->getContext()->getResponse();
$saved = $this->set(
array(
'content' => $content,
'response' => serialize($response),
),
$uri,
$contentTags
);
if ($saved && sfConfig::get('sf_web_debug'))
{
$event = new sfEvent($this, 'view.cache.filter_content', array(
'response' => $response,
'uri' => $uri,
'new' => true,
));
$content = $this
->getEventDispatcher()
->filter($event, $content)
->getReturnValue();
}
$tagHandler->removeContentTags($namespace);
return $content;
}
/**
* Listens to the 'view.cache.filter_content' event to decorate a chunk of
* HTML with cache information.
*
* Added info about linked tags
*
* @param sfEvent $event A sfEvent instance
* @param string $content The HTML content
*
* @return string The decorated HTML string
*/
public function decorateContentWithDebug (sfEvent $event, $content)
{
$updatedContent = parent::decorateContentWithDebug($event, $content);
if ($content === $updatedContent)
{
return $content;
}
$cacheMetadata = new CacheMetadata($this->getCache()->get(
$this->generateCacheKey($event['uri']))
);
if (null === $cacheMetadata->getData())
{
return $content;
}
$tags = $cacheMetadata->getTags();
ksort($tags, SORT_ASC);
$tagsCount = count($tags);
$tagsContent = sprintf('[cache tags] count: %d', $tagsCount);
if (0 != $tagsCount)
{
$tagsContent .= ', tags:';
foreach ($tags as $name => $version)
{
$tagsContent .= sprintf(
' <span title="%s">%s</span>,',
htmlspecialchars($version, ENT_QUOTES, sfConfig::get('sf_charset')),
htmlspecialchars($name, ENT_QUOTES, sfConfig::get('sf_charset'))
);
}
$tagsContent = substr($tagsContent, 0, -1) . '.';
}
$textToReplace = ' <br /> ';
return str_replace($textToReplace, $tagsContent, $updatedContent);
}
/**
* Before checking cache key - saves passed tags
*
* @see parent::checkCacheKey()
* @param array $parameters An array of parameters
* @return string The cache key
*/
public function checkCacheKey (array & $parameters)
{
$tagsKey = 'sf_cache_tags';
$this->temporaryContentTags = null;
if (isset($parameters[$tagsKey]))
{
$tags = true === sfConfig::get('sf_escaping_strategy')
? sfOutputEscaper::unescape($parameters[$tagsKey])
: $parameters[$tagsKey];
unset($parameters[$tagsKey]);
if ($tags)
{
$this->temporaryContentTags = $tags;
}
}
return parent::checkCacheKey($parameters);
}
/**
* Code is much dublicated (enough same)
* with one distinction - it work already with unserialized data
*
* @see parent::getPageCache();
* @param string $uri
* @return boolean
*/
public function getPageCache ($uri)
{
$cachedResponse = $this->_get($uri);
if (null === $cachedResponse)
{
return false;
}
$cachedResponse->setEventDispatcher($this->getEventDispatcher());
if (sfView::RENDER_VAR == $this->getController()->getRenderMode())
{
$this->getController()->getActionStack()->getLastEntry()->setPresentation(
$cachedResponse->getContent()
);
$this->getContext()->getResponse()->setContent('');
}
else
{
$this->getContext()->setResponse($cachedResponse);
$response = $this->getContext()->getResponse();
if (sfConfig::get('sf_web_debug'))
{
$event = new sfEvent($this, 'view.cache.filter_content', array(
'response' => $response,
'uri' => $uri,
'new' => false,
));
$content = $this
->getEventDispatcher()
->filter($event, $response->getContent())
->getReturnValue();
$response->setContent($content);
}
}
return true;
}
/**
* Gets a partial template from the cache.
*
* @param string $module The module name
* @param string $action The action name
* @param string $cacheKey The cache key
*
* @return string The cache content
*/
public function getPartialCache ($module, $action, $cacheKey)
{
$uri = $this->getPartialUri($module, $action, $cacheKey);
if (! $this->isCacheable($uri))
{
return null;
}
if ($this->temporaryContentTags)
{
$namespace = sprintf(
'%s-%s-%s', $module, $action, self::NAMESPACE_PARTIAL
);
$this
->getContentTagHandler()
->setContentTags($this->temporaryContentTags, $namespace)
;
$this->temporaryContentTags = null;
}
// retrieve content from cache
$cache = $this->_get($uri);
if (null === $cache)
{
return null;
}
$content = $cache['content'];
$cache['response'] = unserialize($cache['response']);
$this->getContext()->getResponse()->merge($cache['response']);
if (sfConfig::get('sf_web_debug'))
{
$event = new sfEvent($this, 'view.cache.filter_content', array(
'response' => $this->getContext()->getResponse(),
'uri' => $uri,
'new' => false,
));
$content = $this
->getEventDispatcher()
->filter($event, $content)
->getReturnValue();
}
return $content;
}
/**
* Disables cache on the fly (used in "cachable" generator)
* Solved the problem when action contains form, after form is saved
* displayed flashes are cached.
*
* @param string $moduleName
* @param string $actionName
* @return array
*/
public function disableCache ($moduleName, $actionName = null)
{
if ($moduleName && $actionName)
{
if (isset($this->cacheConfig[$moduleName][$actionName]))
{
unset($this->cacheConfig[$moduleName][$actionName]);
}
return;
}
if ($moduleName)
{
if (isset($this->cacheConfig[$moduleName]))
{
unset($this->cacheConfig[$moduleName]);
}
}
return;
}
/**
* @see parent::remove() The main difference, instead of $this->cache is
* used $this->getTaggingCache()
*/
public function remove ($internalUri, $hostName = '', $vary = '', $contextualPrefix = '**')
{
$this->notify(sprintf('Remove cache for "%s"', $internalUri));
$cacheKey = $this->generateCacheKey(
$internalUri, $hostName, $vary, $contextualPrefix
);
$taggingCache = $this->getTaggingCache();
if (strpos($cacheKey, '*'))
{
return $taggingCache->removePattern($cacheKey);
}
elseif ($taggingCache->has($cacheKey))
{
return $taggingCache->remove($cacheKey);
}
}
/**
* Appends extra cache key parameters when user is authenticated
* and there are some parameters set by user
*
* {@inheritdoc}
*/
public function generateCacheKey ($internalUri, $hostName = '', $vary = '', $contextualPrefix = '')
{
$user = $this->getContext()->getUser();
$dispatcher = $this->getEventDispatcher();
// sfSecurityUser interface has "isAuthenticated" method
if (! $user instanceof sfSecurityUser)
{
$this->notify(
sprintf(
'User class "%s" does not implements the "sfSecurityUser" interface',
get_class($user)
),
sfLogger::DEBUG
);
}
elseif (! $user->isAuthenticated())
{
$this->notify('User is not authenticated', sfLogger::DEBUG);
}
else
{
$urlInfo = parse_url($internalUri);
$sysParams = array();
if (isset($urlInfo['query']))
{
parse_str($urlInfo['query'], $sysParams);
}
$cacheType = null;
if (0 === strpos($internalUri, '@sf_cache_partial'))
{
$cacheType = self::NAMESPACE_PARTIAL;
}
elseif (! isset($sysParams['action'], $sysParams['module']))
{
// w/ layout is only pages (action+layout)
if ($this->withLayout($internalUri))
{
$cacheType = self::NAMESPACE_PAGE;
}
else // w/o layout only actions
{
$cacheType = self::NAMESPACE_ACTION;
}
}
$event = new sfEvent($user, 'cache.filter_cache_keys', array(
'view_cache' => $this,
'cache_type' => $cacheType,
'call_args' => func_get_args(),
));
$userParams = $dispatcher->filter($event, array())->getReturnValue();
if (! is_array($userParams))
{
$this->notify('Custom cache key param is not an array', sfLogger::ERR);
}
elseif (0 < count($userParams))
{
// protects @sf_cache_partial action/module name substitution
if (isset($userParams['action'])) unset($userParams['action']);
if (isset($userParams['module'])) unset($userParams['module']);
$formattedUserParams = array();
foreach ($userParams as $key => $value)
{
$key = is_numeric($key) ? sprintf('param_%d', $key) : $key;
$formattedUserParams[$key] = $value;
}
// union, do not overwrite sysParams key values
$sysParams += $formattedUserParams;
if (0 < count($sysParams))
{
$internalUri = $urlInfo['path'] . '?' . http_build_query($sysParams);
}
}
}
return parent::generateCacheKey($internalUri, $hostName, $vary, $contextualPrefix);
}
/**
* Notifies application.log listener
*
* @param string $message
* @param int $priority sfLogger::*
*/
protected function notify ($message, $priority = sfLogger::INFO)
{
if (! sfConfig::get('sf_logging_enabled'))
{
return;
}
$this->getEventDispatcher()->notify(
new sfEvent($this, 'application.log', array($message, 'priority' => $priority))
);
}
} | {
"content_hash": "0f2ca1fc53030ed42d98b19d4e49aaa1",
"timestamp": "",
"source": "github",
"line_count": 831,
"max_line_length": 103,
"avg_line_length": 25.790613718411553,
"alnum_prop": 0.5475457260171706,
"repo_name": "fruit/sfCacheTaggingPlugin",
"id": "b8084bac84edc7e2c9ac37520a81eb1f69f471a3",
"size": "21694",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/view/sfViewCacheTagManager.class.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "283425"
},
{
"name": "Shell",
"bytes": "199"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE415_Double_Free__malloc_free_long_81_bad.cpp
Label Definition File: CWE415_Double_Free__malloc_free.label.xml
Template File: sources-sinks-81_bad.tmpl.cpp
*/
/*
* @description
* CWE: 415 Double Free
* BadSource: Allocate data using malloc() and Deallocate data using free()
* GoodSource: Allocate data using malloc()
* Sinks:
* GoodSink: do nothing
* BadSink : Deallocate data using free()
* Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE415_Double_Free__malloc_free_long_81.h"
namespace CWE415_Double_Free__malloc_free_long_81
{
void CWE415_Double_Free__malloc_free_long_81_bad::action(long * data) const
{
/* POTENTIAL FLAW: Possibly freeing memory twice */
free(data);
}
}
#endif /* OMITBAD */
| {
"content_hash": "dcee9f5645306aef24a467bc71fceca6",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 101,
"avg_line_length": 28.8125,
"alnum_prop": 0.6973969631236443,
"repo_name": "maurer/tiamat",
"id": "9b1c8164fe4d9482e9bc7df0511c4c70c8914f05",
"size": "922",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE415_Double_Free/s01/CWE415_Double_Free__malloc_free_long_81_bad.cpp",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
// No direct access
defined('_HZEXEC_') or die();
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=registrations.csv");
header("Pragma: no-cache");
header("Expires: 0");
foreach ($this->rows as $row)
{
$section = \Components\Courses\Models\Section::getInstance($row->get('section_id'));
echo encodeCSVField($row->get('user_id'));
echo ',';
echo encodeCSVField($row->get('name'));
echo ',';
echo encodeCSVField($row->get('email'));
echo ',';
echo encodeCSVField($section->exists()) ? $this->escape(stripslashes($section->get('title'))) : Lang::txt('COM_COURSES_NONE');
echo ',';
if ($row->get('enrolled') && $row->get('enrolled') != '0000-00-00 00:00:00') {
echo encodeCSVField(Date::of($row->get('enrolled'))->toLocal(Lang::txt('DATE_FORMAT_HZ1')));
}
else {
echo encodeCSVField(Lang::txt('COM_COURSES_UNKNOWN'));
}
echo "\n";
}
die;
function encodeCSVField($string)
{
if (strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false)
{
$string = '"' . str_replace('"', '""', $string) . '"';
}
return $string;
}
| {
"content_hash": "309183dabcb4f41f25b0531c74b62b24",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 127,
"avg_line_length": 25.568181818181817,
"alnum_prop": 0.6257777777777778,
"repo_name": "zweidner/hubzero-cms",
"id": "f6399dc900af812b8b3c4aa7044ec2c4de5f1ddb",
"size": "1273",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "core/components/com_courses/admin/views/students/tmpl/csv.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "171251"
},
{
"name": "AngelScript",
"bytes": "1638"
},
{
"name": "CSS",
"bytes": "2725992"
},
{
"name": "HTML",
"bytes": "1103502"
},
{
"name": "JavaScript",
"bytes": "12590362"
},
{
"name": "PHP",
"bytes": "24800288"
},
{
"name": "Shell",
"bytes": "10666"
},
{
"name": "TSQL",
"bytes": "572"
}
],
"symlink_target": ""
} |
/**
* @file
* RV30 and RV40 decoder common data declarations
*/
#ifndef AVCODEC_RV34_H
#define AVCODEC_RV34_H
#include "avcodec.h"
#include "dsputil.h"
#include "mpegvideo.h"
#include "h264pred.h"
#define MB_TYPE_SEPARATE_DC 0x01000000
#define IS_SEPARATE_DC(a) ((a) & MB_TYPE_SEPARATE_DC)
/**
* RV30 and RV40 Macroblock types
*/
enum RV40BlockTypes{
RV34_MB_TYPE_INTRA, ///< Intra macroblock
RV34_MB_TYPE_INTRA16x16, ///< Intra macroblock with DCs in a separate 4x4 block
RV34_MB_P_16x16, ///< P-frame macroblock, one motion frame
RV34_MB_P_8x8, ///< P-frame macroblock, 8x8 motion compensation partitions
RV34_MB_B_FORWARD, ///< B-frame macroblock, forward prediction
RV34_MB_B_BACKWARD, ///< B-frame macroblock, backward prediction
RV34_MB_SKIP, ///< Skipped block
RV34_MB_B_DIRECT, ///< Bidirectionally predicted B-frame macroblock, no motion vectors
RV34_MB_P_16x8, ///< P-frame macroblock, 16x8 motion compensation partitions
RV34_MB_P_8x16, ///< P-frame macroblock, 8x16 motion compensation partitions
RV34_MB_B_BIDIR, ///< Bidirectionally predicted B-frame macroblock, two motion vectors
RV34_MB_P_MIX16x16, ///< P-frame macroblock with DCs in a separate 4x4 block, one motion vector
RV34_MB_TYPES
};
/**
* VLC tables used by the decoder
*
* Intra frame VLC sets do not contain some of those tables.
*/
typedef struct RV34VLC{
VLC cbppattern[2]; ///< VLCs used for pattern of coded block patterns decoding
VLC cbp[2][4]; ///< VLCs used for coded block patterns decoding
VLC first_pattern[4]; ///< VLCs used for decoding coefficients in the first subblock
VLC second_pattern[2]; ///< VLCs used for decoding coefficients in the subblocks 2 and 3
VLC third_pattern[2]; ///< VLCs used for decoding coefficients in the last subblock
VLC coefficient; ///< VLCs used for decoding big coefficients
}RV34VLC;
/** essential slice information */
typedef struct SliceInfo{
int type; ///< slice type (intra, inter)
int quant; ///< quantizer used for this slice
int vlc_set; ///< VLCs used for this slice
int start, end; ///< start and end macroblocks of the slice
int width; ///< coded width
int height; ///< coded height
int pts; ///< frame timestamp
}SliceInfo;
/** decoder context */
typedef struct RV34DecContext{
MpegEncContext s;
int8_t *intra_types_hist;///< old block types, used for prediction
int8_t *intra_types; ///< block types
int intra_types_stride;///< block types array stride
const uint8_t *luma_dc_quant_i;///< luma subblock DC quantizer for intraframes
const uint8_t *luma_dc_quant_p;///< luma subblock DC quantizer for interframes
RV34VLC *cur_vlcs; ///< VLC set used for current frame decoding
int bits; ///< slice size in bits
H264PredContext h; ///< functions for 4x4 and 16x16 intra block prediction
SliceInfo si; ///< current slice information
int *mb_type; ///< internal macroblock types
int block_type; ///< current block type
int luma_vlc; ///< which VLC set will be used for decoding of luma blocks
int chroma_vlc; ///< which VLC set will be used for decoding of chroma blocks
int is16; ///< current block has additional 16x16 specific features or not
int dmv[4][2]; ///< differential motion vectors for the current macroblock
int rv30; ///< indicates which RV variasnt is currently decoded
int rpr; ///< one field size in RV30 slice header
int cur_pts, last_pts, next_pts;
uint16_t *cbp_luma; ///< CBP values for luma subblocks
uint8_t *cbp_chroma; ///< CBP values for chroma subblocks
int *deblock_coefs; ///< deblock coefficients for each macroblock
/** 8x8 block available flags (for MV prediction) */
DECLARE_ALIGNED(8, uint32_t, avail_cache)[3*4];
int (*parse_slice_header)(struct RV34DecContext *r, GetBitContext *gb, SliceInfo *si);
int (*decode_mb_info)(struct RV34DecContext *r);
int (*decode_intra_types)(struct RV34DecContext *r, GetBitContext *gb, int8_t *dst);
void (*loop_filter)(struct RV34DecContext *r, int row);
}RV34DecContext;
/**
* common decoding functions
*/
int ff_rv34_get_start_offset(GetBitContext *gb, int blocks);
int ff_rv34_decode_init(AVCodecContext *avctx);
int ff_rv34_decode_frame(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt);
int ff_rv34_decode_end(AVCodecContext *avctx);
#endif /* AVCODEC_RV34_H */
| {
"content_hash": "18a7b63a66f2d8f085dfbb603029c697",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 104,
"avg_line_length": 42.98198198198198,
"alnum_prop": 0.6482917627331797,
"repo_name": "JREkiwi/sagetv",
"id": "24a27ce4824e17d608913ed316a795086b6c0cc7",
"size": "5637",
"binary": false,
"copies": "100",
"ref": "refs/heads/master",
"path": "third_party/ffmpeg/libavcodec/rv34.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "6736"
},
{
"name": "C",
"bytes": "3954359"
},
{
"name": "C++",
"bytes": "2507030"
},
{
"name": "Java",
"bytes": "11373865"
},
{
"name": "Makefile",
"bytes": "36179"
},
{
"name": "NSIS",
"bytes": "1224"
},
{
"name": "PowerShell",
"bytes": "29319"
},
{
"name": "Shell",
"bytes": "52911"
},
{
"name": "VBScript",
"bytes": "4339"
}
],
"symlink_target": ""
} |
""" Cloud API asynchronous "PDF To Text" job example.
Allows to avoid timeout errors when processing huge or scanned PDF documents.
"""
import os
import requests # pip install requests
import time
import datetime
# The authentication key (API Key).
# Get your own by registering at https://app.pdf.co
API_KEY = "*****************************************"
# Base URL for PDF.co Web API requests
BASE_URL = "https://api.pdf.co/v1"
# URL of web page to convert to PDF document.
SourceUrl = "http://en.wikipedia.org/wiki/Main_Page"
# Destination PDF file name
DestinationFile = ".\\result.pdf"
# (!) Make asynchronous job
Async = True
def main(args = None):
convertLinkToPDF(SourceUrl, DestinationFile)
def convertLinkToPDF(uploadedFileUrl, destinationFile):
"""Converts Link To PDF using PDF.co Web API"""
# Prepare requests params as JSON
# See documentation: https://apidocs.pdf.co
parameters = {}
parameters["async"] = Async
parameters["name"] = os.path.basename(destinationFile)
parameters["url"] = uploadedFileUrl
# Prepare URL for 'URL To PDF' API request
url = "{}/pdf/convert/from/url".format(BASE_URL)
# Execute request and get response as JSON
response = requests.post(url, data=parameters, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# Asynchronous job ID
jobId = json["jobId"]
# URL of the result file
resultFileUrl = json["url"]
# Check the job status in a loop.
# If you don't want to pause the main thread you can rework the code
# to use a separate thread for the status checking and completion.
while True:
status = checkJobStatus(jobId) # Possible statuses: "working", "failed", "aborted", "success".
# Display timestamp and status (for demo purposes)
print(datetime.datetime.now().strftime("%H:%M.%S") + ": " + status)
if status == "success":
# Download result file
r = requests.get(resultFileUrl, stream=True)
if (r.status_code == 200):
with open(destinationFile, 'wb') as file:
for chunk in r:
file.write(chunk)
print(f"Result file saved as \"{destinationFile}\" file.")
else:
print(f"Request error: {response.status_code} {response.reason}")
break
elif status == "working":
# Pause for a few seconds
time.sleep(3)
else:
print(status)
break
else:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
def checkJobStatus(jobId):
"""Checks server job status"""
url = f"{BASE_URL}/job/check?jobid={jobId}"
response = requests.get(url, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
return json["status"]
else:
print(f"Request error: {response.status_code} {response.reason}")
return None
if __name__ == '__main__':
main() | {
"content_hash": "cc83d6477ecac9c0ae9c34d4ac37b182",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 110,
"avg_line_length": 34.68,
"alnum_prop": 0.5628604382929643,
"repo_name": "bytescout/ByteScout-SDK-SourceCode",
"id": "67ac1a64851f93367116969a3518bf424e0e7e51",
"size": "3468",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PDF.co Web API/PDF from URL/Python/Convert Web Page To PDF From Link Asynchronously/ConvertWebPageToPdfFromLinkAsynchronously.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP.NET",
"bytes": "364116"
},
{
"name": "Apex",
"bytes": "243500"
},
{
"name": "Batchfile",
"bytes": "151832"
},
{
"name": "C",
"bytes": "224568"
},
{
"name": "C#",
"bytes": "12909855"
},
{
"name": "C++",
"bytes": "440474"
},
{
"name": "CSS",
"bytes": "56817"
},
{
"name": "Classic ASP",
"bytes": "46655"
},
{
"name": "Dockerfile",
"bytes": "776"
},
{
"name": "Gherkin",
"bytes": "3386"
},
{
"name": "HTML",
"bytes": "17276296"
},
{
"name": "Java",
"bytes": "1483408"
},
{
"name": "JavaScript",
"bytes": "3033610"
},
{
"name": "PHP",
"bytes": "838746"
},
{
"name": "Pascal",
"bytes": "398090"
},
{
"name": "PowerShell",
"bytes": "715204"
},
{
"name": "Python",
"bytes": "703542"
},
{
"name": "QMake",
"bytes": "880"
},
{
"name": "TSQL",
"bytes": "3080"
},
{
"name": "VBA",
"bytes": "383773"
},
{
"name": "VBScript",
"bytes": "1504410"
},
{
"name": "Visual Basic .NET",
"bytes": "9489450"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.