hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7144b61ba32a0581399b0ca5a9dcc4716c30aa18
| 7,178
|
swift
|
Swift
|
MeditationPlus/UserInterface/MeditatorList/DataSource/MeditatorDataSource.swift
|
ErikLuimes/meditation-plus-ios
|
6e654867bbc2c6c6e3824528b7b76737aa9ef0e9
|
[
"MIT"
] | 5
|
2016-05-19T08:23:44.000Z
|
2017-04-02T13:03:37.000Z
|
MeditationPlus/UserInterface/MeditatorList/DataSource/MeditatorDataSource.swift
|
ErikLuimes/meditation-plus-ios
|
6e654867bbc2c6c6e3824528b7b76737aa9ef0e9
|
[
"MIT"
] | null | null | null |
MeditationPlus/UserInterface/MeditatorList/DataSource/MeditatorDataSource.swift
|
ErikLuimes/meditation-plus-ios
|
6e654867bbc2c6c6e3824528b7b76737aa9ef0e9
|
[
"MIT"
] | null | null | null |
//
// MeditatorDataSource.swift
// MeditationPlus
//
// Created by Erik Luimes on 12/09/15.
//
// The MIT License
// Copyright (c) 2015 Maya Interactive. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Except as contained in this notice, the name of Maya Interactive and Meditation+
// shall not be used in advertising or otherwise to promote the sale, use or other
// dealings in this Software without prior written authorization from Maya Interactive.
//
import Foundation
import UIKit
import RealmSwift
public class MeditatorDataSource: NSObject, UITableViewDataSource
{
private var results: Results<Meditator>!
private var sections: [MeditatorSection]!
required public init(results: Results<Meditator>)
{
self.results = results
sections = []
// Setup sections
for i in 0..<MeditatorSectionData.numberOfSections {
let section = MeditatorSection(title: MeditatorSectionData(rawValue: i)!.title)
sections.append(section)
}
}
public func hasData() -> Bool
{
return sections.map { $0.items.count }.reduce(0, combine: +) > 0
}
public func updateSections()
{
sections[MeditatorSectionData.Meditating.rawValue].items.removeAll()
sections[MeditatorSectionData.Finished.rawValue].items.removeAll()
for meditator in results {
sections[MeditatorSectionData(meditator: meditator).rawValue].items.append(meditator)
}
}
public func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return self.sections.count
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return sections[section].items.count
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier(R.nib.meditatorCell.name, forIndexPath: indexPath)
return cell
}
public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
guard section < sections.count else {
return nil
}
return sections[section].title
}
func meditatorForIndexPath(indexPath: NSIndexPath) -> Meditator?
{
return sections[indexPath.section].items[indexPath.row]
}
func update(tableView: UITableView)
{
let previousSectionCount: [Int] = sections.map( { $0.items.count } )
guard previousSectionCount.reduce(0, combine: +) > 0 else {
updateSections()
tableView.reloadData()
return
}
updateSections()
var currentSectionCount: [Int] = sections.map( { $0.items.count } )
guard currentSectionCount.count == previousSectionCount.count else {
return
}
tableView.beginUpdates()
for (section, itemCount) in previousSectionCount.enumerate() {
if itemCount == currentSectionCount[section] {
tableView.reloadRowsAtIndexPaths(Array<Int>(0..<itemCount).map { NSIndexPath(forRow: $0, inSection: section) }, withRowAnimation: .Automatic)
} else {
tableView.reloadSections(NSIndexSet(index: section), withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
tableView.endUpdates()
}
func checkMeditatorProgress(tableView: UITableView)
{
var indexPathsToDelete: [NSIndexPath] = [NSIndexPath]()
var meditatorsToMove: [Meditator] = [Meditator]()
var indexPathsToAdd: [NSIndexPath] = [NSIndexPath]()
for (index, currentlyMeditating) in sections[0].items.enumerate() {
if currentlyMeditating.normalizedProgress >= 1.0 {
meditatorsToMove.append(currentlyMeditating)
indexPathsToDelete.append(NSIndexPath(forRow: index, inSection: 0))
}
}
for finischedMeditator in meditatorsToMove {
deleteMeditator(finischedMeditator)
insertMeditator(finischedMeditator)
}
for (index, finishedMeditating) in sections[1].items.enumerate() {
if meditatorsToMove.contains(finishedMeditating) {
indexPathsToAdd.append(NSIndexPath(forRow: index, inSection: 1))
}
}
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths(indexPathsToDelete, withRowAnimation: .Automatic)
tableView.insertRowsAtIndexPaths(indexPathsToAdd, withRowAnimation: .Automatic)
tableView.endUpdates()
}
private func insertMeditator(meditator: Meditator) -> NSIndexPath
{
let sectionIndex = MeditatorSectionData(meditator: meditator).rawValue
sections[sectionIndex].items.insert(meditator, atIndex: 0)
return NSIndexPath(forRow: 0, inSection: sectionIndex)
}
private func deleteMeditator(meditator: Meditator) -> NSIndexPath?
{
if let deletedTaskIndex = sections[0].items.indexOf(meditator) {
sections[0].items.removeAtIndex(deletedTaskIndex)
return NSIndexPath(forRow: deletedTaskIndex, inSection: 0)
}
return nil
}
}
public enum MeditatorSectionData: Int
{
case Meditating
case Finished
public var title: String
{
switch self {
case .Meditating: return NSLocalizedString("meditating.section.title", comment: "")
case .Finished: return NSLocalizedString("finished.meditating.section.title", comment: "")
}
}
public static var numberOfSections: Int
{
return 2
}
}
extension MeditatorSectionData
{
public init(meditator: Meditator)
{
self = meditator.normalizedProgress < 1.0 ? .Meditating : .Finished
}
}
private struct MeditatorSection
{
let title: String
var items: [Meditator] = [Meditator]()
private init(title: String)
{
self.title = title
}
}
| 33.078341
| 157
| 0.664531
|
61408685bc1ef7d88638f83cce55af1b8a803eda
| 181
|
sql
|
SQL
|
support-files/sql/job-analysis/0002_job_analysis_20210114-1000_V3.2.1.1_mysql.sql
|
llitfkitfk/bk-job
|
0d4dcdb943a6600bc2d4d06485143596a1937920
|
[
"MIT"
] | 1
|
2021-09-17T01:53:31.000Z
|
2021-09-17T01:53:31.000Z
|
support-files/sql/job-analysis/0002_job_analysis_20210114-1000_V3.2.1.1_mysql.sql
|
llitfkitfk/bk-job
|
0d4dcdb943a6600bc2d4d06485143596a1937920
|
[
"MIT"
] | null | null | null |
support-files/sql/job-analysis/0002_job_analysis_20210114-1000_V3.2.1.1_mysql.sql
|
llitfkitfk/bk-job
|
0d4dcdb943a6600bc2d4d06485143596a1937920
|
[
"MIT"
] | null | null | null |
SET NAMES utf8mb4;
USE job_analysis;
ALTER TABLE `statistics` ADD INDEX `idx_res_dim_dimValue_date`(`resource`(32), `dimension`(32), `dimension_value`(32),`date`(32)) USING BTREE;
| 36.2
| 142
| 0.756906
|
c0ac7aa9bc25085cca5297e0f437d227a0e8cc5e
| 6,420
|
cs
|
C#
|
mcs/class/System.ServiceModel.Web/System.ServiceModel.Syndication/AtomPub10CategoriesDocumentFormatter.cs
|
lefb766/mono
|
4f458a4ff72bc6c5e07f82aec9040d355cbb8f5c
|
[
"Apache-2.0"
] | 469
|
2019-01-23T12:21:59.000Z
|
2022-03-10T15:50:42.000Z
|
mcs/class/System.ServiceModel.Web/System.ServiceModel.Syndication/AtomPub10CategoriesDocumentFormatter.cs
|
pcc/mono
|
c64a76e3aae1bd6347f35c1c3bd1ace56247d4f1
|
[
"Apache-2.0"
] | 83
|
2015-07-16T01:31:41.000Z
|
2016-01-13T02:15:47.000Z
|
mcs/class/System.ServiceModel.Web/System.ServiceModel.Syndication/AtomPub10CategoriesDocumentFormatter.cs
|
pcc/mono
|
c64a76e3aae1bd6347f35c1c3bd1ace56247d4f1
|
[
"Apache-2.0"
] | 36
|
2019-01-23T22:17:09.000Z
|
2022-01-20T15:41:34.000Z
|
//
// AtomPub10CategoriesDocumentFormatter.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2009 Novell, Inc. http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace System.ServiceModel.Syndication
{
[XmlRoot ("categories", Namespace = Namespaces.AtomPP)]
public class AtomPub10CategoriesDocumentFormatter : CategoriesDocumentFormatter, IXmlSerializable
{
public AtomPub10CategoriesDocumentFormatter ()
: this (typeof (InlineCategoriesDocument), typeof (ReferencedCategoriesDocument))
{
}
public AtomPub10CategoriesDocumentFormatter (CategoriesDocument documentToWrite)
: base (documentToWrite)
{
}
public AtomPub10CategoriesDocumentFormatter (Type inlineDocumentType, Type referencedDocumentType)
{
if (inlineDocumentType == null)
throw new ArgumentNullException ("inlineDocumentType");
if (referencedDocumentType == null)
throw new ArgumentNullException ("referencedDocumentType");
inline_type = inlineDocumentType;
ref_type = referencedDocumentType;
}
Type inline_type, ref_type;
public override string Version {
get { return "http://www.w3.org/2007/app"; }
}
public override bool CanRead (XmlReader reader)
{
if (reader == null)
throw new ArgumentNullException ("reader");
reader.MoveToContent ();
return reader.LocalName != "categories" || reader.NamespaceURI != Version;
}
protected override InlineCategoriesDocument CreateInlineCategoriesDocument ()
{
return (InlineCategoriesDocument) Activator.CreateInstance (inline_type, new object [0]);
}
protected override ReferencedCategoriesDocument CreateReferencedCategoriesDocument ()
{
return (ReferencedCategoriesDocument) Activator.CreateInstance (ref_type, new object [0]);
}
public override void ReadFrom (XmlReader reader)
{
if (reader == null)
throw new ArgumentNullException ("reader");
reader.MoveToContent ();
bool isEmpty = reader.IsEmptyElement;
if (Document == null) {
var href = reader.GetAttribute ("href");
if (href != null) {
var doc = CreateReferencedCategoriesDocument ();
doc.Link = new Uri (href, UriKind.RelativeOrAbsolute);
SetDocument (doc);
} else {
var doc = CreateInlineCategoriesDocument ();
doc.Scheme = reader.GetAttribute ("scheme");
if (reader.GetAttribute ("fixed") == "yes")
doc.IsFixed = true;
SetDocument (doc);
}
}
var inline = Document as InlineCategoriesDocument;
// var referenced = Document as ReferencedCategoriesDocument;
reader.ReadStartElement ("categories", Version);
if (isEmpty)
return;
for (reader.MoveToContent ();
reader.NodeType != XmlNodeType.EndElement;
reader.MoveToContent ()) {
if (inline != null && reader.LocalName == "category" && reader.NamespaceURI == Namespaces.Atom10)
ReadInlineCategoriesContent (inline, reader);
// FIXME: else read element as an extension
else
reader.Skip ();
}
reader.ReadEndElement (); // </app:categories>
}
void ReadInlineCategoriesContent (InlineCategoriesDocument doc, XmlReader reader)
{
var cat = new SyndicationCategory ();
atom10_formatter.ReadCategory (reader, cat);
doc.Categories.Add (cat);
}
public override void WriteTo (XmlWriter writer)
{
if (writer == null)
throw new ArgumentNullException ("writer");
writer.WriteStartElement ("app", "categories", Version);
if (writer.LookupPrefix (Namespaces.Atom10) != "a10")
writer.WriteAttributeString ("xmlns", "a10", Namespaces.Xmlns, Namespaces.Atom10);
// xml:lang, xml:base, term, scheme, label
if (Document.Language != null)
writer.WriteAttributeString ("xml", "lang", Namespaces.Xml, Document.Language);
if (Document.BaseUri != null)
writer.WriteAttributeString ("xml", "base", Namespaces.Xml, Document.BaseUri.ToString ());
InlineCategoriesDocument inline = Document as InlineCategoriesDocument;
ReferencedCategoriesDocument referenced = Document as ReferencedCategoriesDocument;
// ... no term ?
if (inline != null) {
if (inline.IsFixed)
writer.WriteAttributeString ("fixed", "yes");
if (inline.Scheme != null)
writer.WriteAttributeString ("scheme", inline.Scheme);
} else if (referenced != null) {
if (referenced.Link != null)
writer.WriteAttributeString ("href", referenced.Link.ToString ());
}
Document.WriteAttributeExtensions (writer, Version);
Document.WriteElementExtensions (writer, Version);
if (inline != null)
WriteInlineCategoriesContent (inline, writer);
// no (non-extension) contents for out-of-line category
writer.WriteEndElement ();
}
Atom10FeedFormatter atom10_formatter = new Atom10FeedFormatter ();
void WriteInlineCategoriesContent (InlineCategoriesDocument doc, XmlWriter writer)
{
foreach (var cat in doc.Categories)
atom10_formatter.WriteCategory (cat, writer);
}
XmlSchema IXmlSerializable.GetSchema ()
{
return null;
}
void IXmlSerializable.ReadXml (XmlReader reader)
{
ReadFrom (reader);
}
void IXmlSerializable.WriteXml (XmlWriter writer)
{
WriteTo (writer);
}
}
}
| 31.625616
| 101
| 0.725545
|
1247bf89cdeaf4725fe017d10cb17ec53ac20791
| 11,202
|
cs
|
C#
|
TestsNonParallel/src/Logging/LoadProcessTasksTests.cs
|
dhiegobastos/etlbox
|
316884ee9014f725ccab71e5d70360a45c4b8715
|
[
"MIT"
] | null | null | null |
TestsNonParallel/src/Logging/LoadProcessTasksTests.cs
|
dhiegobastos/etlbox
|
316884ee9014f725ccab71e5d70360a45c4b8715
|
[
"MIT"
] | null | null | null |
TestsNonParallel/src/Logging/LoadProcessTasksTests.cs
|
dhiegobastos/etlbox
|
316884ee9014f725ccab71e5d70360a45c4b8715
|
[
"MIT"
] | 1
|
2021-05-02T14:27:43.000Z
|
2021-05-02T14:27:43.000Z
|
using ALE.ETLBox;
using ALE.ETLBox.ConnectionManager;
using ALE.ETLBox.ControlFlow;
using ALE.ETLBox.Helper;
using ALE.ETLBox.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace ALE.ETLBoxTests.Logging
{
[Collection("Logging")]
public class LoadProcessTasksTests : IDisposable
{
public SqlConnectionManager Connection => Config.SqlConnectionManager("Logging");
public LoadProcessTasksTests(LoggingDatabaseFixture dbFixture)
{
CreateLogTablesTask.CreateLog(Connection);
ControlFlow.CurrentDbConnection = Connection;
}
public void Dispose()
{
RemoveLogTablesTask.Remove(Connection);
ControlFlow.ClearSettings();
}
[Fact]
public void StartLoadProcess()
{
//Arrange
DateTime beforeTask = DateTime.Now;
Task.Delay(10).Wait(); //Sql Server datetime is not that exact
//Act
StartLoadProcessTask.Start("Test process 1");
//Assert
DateTime afterTask = DateTime.Now;
Assert.True(ControlFlow.CurrentLoadProcess != null);
Assert.Equal("Test process 1", ControlFlow.CurrentLoadProcess.ProcessName);
Assert.True(ControlFlow.CurrentLoadProcess.StartDate <= afterTask && ControlFlow.CurrentLoadProcess.StartDate >= beforeTask);
Assert.False(new RowCountTask("etl.Log") { DisableLogging = true }.Count().HasRows);
Assert.Equal(1, new RowCountTask("etl.LoadProcess",
"StartMessage is null and EndMessage is null and AbortMessage is null")
{
DisableLogging = true,
}.Count().Rows);
Assert.Equal(1, new RowCountTask("etl.LoadProcess",
"IsRunning=1 and WasSuccessful=0 and WasAborted=0")
{
DisableLogging = true,
}.Count().Rows);
}
[Fact]
public void StartLoadProcessWithMessage()
{
//Arrange
//Act
StartLoadProcessTask.Start("Test process 1", "Message 1", "SourceA");
//Assert
Assert.Equal(1, new RowCountTask("etl.LoadProcess",
"StartMessage = 'Message 1' and Source='SourceA' and EndMessage is null and AbortMessage is null")
{
DisableLogging = true
}.Count().Rows);
}
[Fact]
public void EndLoadProcess()
{
//Arrange
StartLoadProcessTask.Start("Test process 2");
Assert.True(ControlFlow.CurrentLoadProcess.IsRunning == true);
DateTime beforeTask = DateTime.Now;
Task.Delay(10).Wait(); //Sql Server datetime is not that exact
//Act
EndLoadProcessTask.End();
//Assert
DateTime afterTask = DateTime.Now;
Assert.True(ControlFlow.CurrentLoadProcess.IsRunning == false);
Assert.True(ControlFlow.CurrentLoadProcess.WasSuccessful == true);
Assert.True(ControlFlow.CurrentLoadProcess.IsFinished == true);
Assert.True(ControlFlow.CurrentLoadProcess.EndDate <= afterTask && ControlFlow.CurrentLoadProcess.EndDate >= beforeTask);
Assert.False(new SqlTask("Check if logging was disabled for end process task",
"select count(*) from etl.Log")
{ DisableLogging = true }.ExecuteScalarAsBool());
Assert.Equal(1, new RowCountTask("etl.LoadProcess ", "IsRunning=0 and WasSuccessful=1 and WasAborted=0")
{
DisableLogging = true
}.Count().Rows);
Assert.Equal(1, new RowCountTask("etl.LoadProcess",
"StartMessage is null and EndMessage is null and AbortMessage is null")
{
DisableLogging = true
}.Count().Rows);
}
[Fact]
public void AbortLoadProcess()
{
//Arrange
StartLoadProcessTask.Start("Test process 3");
Assert.True(ControlFlow.CurrentLoadProcess.IsRunning == true);
DateTime beforeTask = DateTime.Now;
Task.Delay(10).Wait(); //Sql Server datetime is not that exact
//Act
AbortLoadProcessTask.Abort(ControlFlow.CurrentLoadProcess.LoadProcessKey, "AbortMessage");
//Assert
DateTime afterTask = DateTime.Now;
Assert.True(ControlFlow.CurrentLoadProcess.IsRunning == false);
Assert.True(ControlFlow.CurrentLoadProcess.WasAborted == true);
Assert.True(ControlFlow.CurrentLoadProcess.EndDate <= afterTask && ControlFlow.CurrentLoadProcess.EndDate >= beforeTask);
Assert.True(ControlFlow.CurrentLoadProcess.AbortMessage == "AbortMessage");
Assert.False(new RowCountTask("etl.Log") { DisableLogging = true }.Count().HasRows);
Assert.Equal(1, new RowCountTask("etl.LoadProcess", "IsRunning=0 and WasSuccessful=0 and WasAborted=1")
{
DisableLogging = true
}.Count().Rows);
}
[Fact]
public void IsTransferCompletedForLoadProcess()
{
//Arrange
StartLoadProcessTask.Start("Test process 4");
Assert.True(ControlFlow.CurrentLoadProcess.IsRunning == true);
DateTime beforeTask = DateTime.Now;
Task.Delay(10).Wait(); //Sql Server datetime is not that exact
//Act
TransferCompletedForLoadProcessTask.Complete(ControlFlow.CurrentLoadProcess.LoadProcessKey);
//Assert
Assert.Equal(2, new RowCountTask("etl.Log", "TaskType='TransferCompletedForLoadProcessTask'")
{
DisableLogging = true
}.Count().Rows);
DateTime afterTask = DateTime.Now;
Assert.True(ControlFlow.CurrentLoadProcess.IsRunning == true);
Assert.True(ControlFlow.CurrentLoadProcess.TransferCompletedDate <= afterTask && ControlFlow.CurrentLoadProcess.TransferCompletedDate >= beforeTask);
}
[Fact]
public void IsLoadProcessKeyInLog()
{
//Arrange
StartLoadProcessTask.Start("Test process 5");
//Act
SqlTask.ExecuteNonQuery("Test Task", "Select 1 as test");
//Assert
Assert.Equal(2, new RowCountTask("etl.Log",
$"Message='Test Task' and LoadProcessKey = {ControlFlow.CurrentLoadProcess.LoadProcessKey}")
{
DisableLogging = true
}.Count().Rows);
}
[Fact]
public void IsControlFlowStageLogged()
{
//Arrange
StartLoadProcessTask.Start("Test process 1", "Message 1", "SourceA");
//Act
ControlFlow.STAGE = "SETUP";
SqlTask.ExecuteNonQuery("Test Task", "Select 1 as test");
//Assert
Assert.Equal(2, new RowCountTask("etl.Log",
$"Message='Test Task' and Stage = 'SETUP'")
{
DisableLogging = true
}.Count().Rows);
}
[Fact]
public void ReadLastSuccessfulProcess()
{
//Arrange
StartLoadProcessTask.Start("Test process 8");
Task.Delay(10).Wait(); //Sql Server datetime is not that exact
EndLoadProcessTask.End();
Task.Delay(10).Wait();
StartLoadProcessTask.Start("Test process 9");
Task.Delay(10).Wait(); //Sql Server datetime is not that exact
EndLoadProcessTask.End();
//Act
var lp = ReadLoadProcessTableTask.ReadWithOption(ReadOptions.ReadLastSuccessful);
//Assert
Assert.True(lp.IsFinished);
Assert.True(lp.WasSuccessful);
Assert.False(lp.WasAborted);
Assert.Equal("Test process 9", lp.ProcessName);
Assert.Equal(2, new RowCountTask("etl.LoadProcess", "IsFinished=1") { DisableLogging = true }.Count().Rows);
Assert.Equal(2, new RowCountTask("etl.LoadProcess", "WasSuccessful=1") { DisableLogging = true }.Count().Rows);
}
[Fact]
public void ReadLastAbortedProcess()
{
//Arrange
StartLoadProcessTask.Start("Test process 10");
Task.Delay(10).Wait(); //Sql Server datetime is not that exact
EndLoadProcessTask.End();
Task.Delay(10).Wait();
StartLoadProcessTask.Start("Test process 11");
Task.Delay(10).Wait(); //Sql Server datetime is not that exact
AbortLoadProcessTask.Abort();
StartLoadProcessTask.Start("Test process 12");
Task.Delay(10).Wait(); //Sql Server datetime is not that exact
EndLoadProcessTask.End();
//Act
var lp = ReadLoadProcessTableTask.ReadWithOption(ReadOptions.ReadLastAborted);
//Assert
Assert.True(lp.IsFinished);
Assert.True(lp.WasAborted);
Assert.False(lp.WasSuccessful);
Assert.Equal("Test process 11", lp.ProcessName);
Assert.Equal(3, new RowCountTask("etl.LoadProcess", "IsFinished=1") { DisableLogging = true }.Count().Rows);
Assert.Equal(2, new RowCountTask("etl.LoadProcess", "WasSuccessful=1") { DisableLogging = true }.Count().Rows);
Assert.Equal(1, new RowCountTask("etl.LoadProcess", "WasAborted=1") { DisableLogging = true }.Count().Rows);
}
[Fact]
public void IsLoadProcessKeySetIfRestarted()
{
//Arrange
StartLoadProcessTask.Start("Test process 13");
int? processKey1 = ControlFlow.CurrentLoadProcess.LoadProcessKey;
SqlTask.ExecuteNonQuery("Test Task", "Select 1 as test");
Assert.Equal(2, new RowCountTask("etl.Log", $"Message='Test Task' AND LoadProcessKey = {processKey1}")
{ DisableLogging = true }.Count().Rows);
//Act
StartLoadProcessTask.Start("Test process 14");
int? processKey2 = ControlFlow.CurrentLoadProcess.LoadProcessKey;
//Assert
Assert.NotEqual(processKey1, processKey2);
SqlTask.ExecuteNonQuery("Test Task", "Select 1 as test");
Assert.Equal(2, new RowCountTask("etl.Log", $"Message='Test Task' AND LoadProcessKey = {processKey2}")
{ DisableLogging = true }.Count().Rows);
}
[Fact]
public void IsLoadProcessKeySetForLogTask()
{
//Arrange
StartLoadProcessTask.Start("Test process 15");
int? processKey1 = ControlFlow.CurrentLoadProcess.LoadProcessKey;
//Act
LogTask.Error("Test1");
LogTask.Warn("Test2");
LogTask.Info("Test3");
//Assert
Assert.Equal(3, new RowCountTask("etl.Log",
$"Message like 'Test%' AND LoadProcessKey = {processKey1}")
{ DisableLogging = true }.Count().Rows);
}
}
}
| 39.864769
| 161
| 0.591769
|
3f5ea5a2cb569bc686a41d5f75b8aa45cc06a380
| 6,751
|
php
|
PHP
|
application/controllers/Users.php
|
rhesadaiva/silocki_new
|
fb0ee646198c3ab7c2377334d4dbfdc551228b47
|
[
"MIT"
] | null | null | null |
application/controllers/Users.php
|
rhesadaiva/silocki_new
|
fb0ee646198c3ab7c2377334d4dbfdc551228b47
|
[
"MIT"
] | null | null | null |
application/controllers/Users.php
|
rhesadaiva/silocki_new
|
fb0ee646198c3ab7c2377334d4dbfdc551228b47
|
[
"MIT"
] | null | null | null |
<?php
class Users extends CI_Controller
{
public function __construct()
{
parent::__construct();
is_logged_in();
}
// Validasi untuk ganti password
public function validateChangePass()
{
$data['title'] = 'Ganti Password';
$data['user'] = $this->db->get_where('user', ['nip' => $this->session->userdata('nip')])->row_array();
// Set validasi
$this->form_validation->set_rules('passwordlama', 'Password Lama', 'trim|required');
$this->form_validation->set_rules('passwordbaru1', 'Password Baru', 'trim|required|min_length[5]');
$this->form_validation->set_rules('passwordbaru2', 'Konfirmasi Password Baru', 'trim|required|matches[passwordbaru1]|min_length[5]');
// Jika hasil validasi = False, ambil response alert untuk dikonversi ke JSON
if ($this->form_validation->run() == FALSE) {
$response = [
'error' => true,
'passwordlama_error' => form_error(
'passwordlama',
'<div class="alert alert-danger alert-dismissible fade in" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<i class="fa fa-times-circle"></i> ',
'</div>'
),
'passwordbaru1_error' => form_error(
'passwordbaru1',
'<div class="alert alert-danger alert-dismissible fade in" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<i class="fa fa-times-circle"></i> ',
'</div>'
),
'passwordbaru2_error' => form_error(
'passwordbaru2',
'<div class="alert alert-danger alert-dismissible fade in" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<i class="fa fa-times-circle"></i> ',
'</div>'
),
];
// Kembalikan response sebagai JSON
echo json_encode($response);
// Apabila validasi benar
} else {
// Ambil data inputan
$passwordlama = md5($this->input->post('passwordlama'));
$passwordbaru = $this->input->post('passwordbaru1');
$currentpass = $data['user']['password'];
//Jika input pada form Password Sekarang tidak match pada database, ambil respon alert untuk dikonversi ke JSON
if ($passwordlama != $currentpass) {
$response = [
'notmatch' => true,
'notmatchalert' => '<div class="alert alert-danger alert-dismissible fade in" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<i class="fa fa-times-circle"></i> Password lama tidak sesuai dengan password sekarang!
</div>'
];
// Kembalikan response sebagai JSON
echo json_encode($response);
// Jika semua kondisi terpenuhi, update passwordnya
} else {
// Update Passwordnya
$this->_updatePassword($passwordbaru);
$response = [
'success' => true,
'successalert' => '<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<i class="fa fa-check-circle"></i> Password berhasil diubah! Silahkan gunakan password baru anda pada saat login.
</div>'
];
// Kembalikan response sebagai JSON
echo json_encode($response);
helper_log("edit", "Mengubah password");
}
}
}
// Private function untuk update password ke database
private function _updatePassword($passwordbaru)
{
// Convert to md5
$newpassword = md5($passwordbaru);
// Update to database
$this->db->set('password', $newpassword);
$this->db->where('nip', $this->session->userdata('nip'));
$this->db->update('user');
}
// Melakukan update foto profil serta resize
public function doUploadProfile()
{
$this->load->model('Global_model');
$nip = $this->session->userdata('nip');
$this->load->library('upload');
// Config untuk library upload
$config['upload_path'] = './assets/img/profile';
$config['allowed_types'] = 'gif|jpg|png|jpeg'; //type yang dapat diakses bisa anda sesuaikan
$config['file_name'] = $nip;
$this->upload->initialize($config);
// Jika data tidak kosong
if (!empty($_FILES['filefoto']['name'])) {
// Jika sudah upload
if ($this->upload->do_upload('filefoto')) {
// Ambil array data upload
$pic = $this->upload->data();
// Config untuk library Resize Image
$config['image_library'] = 'gd2';
$config['source_image'] = './assets/img/profile/' . $pic['file_name'];
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['quality'] = '100%';
$config['width'] = 120;
$config['height'] = 120;
$config['new_image'] = './assets/img/profile/' . $pic['file_name'];
// Do the resize process
$this->load->library('image_lib', $config);
$this->image_lib->resize();
// Ambil nama filenya
$profilePicture = $pic['file_name'];
// Insert ke Database
$updatePhoto = $this->Global_model->saveUpload($profilePicture, $nip);
echo json_decode($updatePhoto);
} else {
// Jika gagal
$errorMessage = $this->upload->display_errors();
echo json_encode($errorMessage);
}
}
}
}
| 44.124183
| 164
| 0.509258
|
15fc749cf2169098cf97d566f289a637ecb2ddaf
| 981
|
java
|
Java
|
src/test/java/flowerstore/FlowerTest.java
|
bohdaholas/Lab5_continuation
|
abd1ba7d519491477fb0f4872104833596eb85d1
|
[
"MIT"
] | null | null | null |
src/test/java/flowerstore/FlowerTest.java
|
bohdaholas/Lab5_continuation
|
abd1ba7d519491477fb0f4872104833596eb85d1
|
[
"MIT"
] | null | null | null |
src/test/java/flowerstore/FlowerTest.java
|
bohdaholas/Lab5_continuation
|
abd1ba7d519491477fb0f4872104833596eb85d1
|
[
"MIT"
] | null | null | null |
package flowerstore;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class FlowerTest {
private Flower flower;
@BeforeEach
void setUp() {
flower = new Flower(FlowerType.TULIP);
flower.setPrice(14.3);
flower.setSepalLength(5);
byte[] color = {127, 41, 45};
flower.setColor(color);
}
@Test
void getPrice() {
assertEquals(14.3, flower.getPrice());
}
@Test
void getSepalLength() {
assertEquals(5, flower.getSepalLength());
}
@Test
void getColor() {
assertArrayEquals(new byte[]{127, 41, 45}, flower.getColor());
}
@Test
void getFlowerType() {
assertEquals(FlowerType.TULIP, flower.getFlowerType());
}
@Test
void testToString() {
assertEquals("Flower(price=14.3, sepalLength=5.0, color=[127, 41, 45], flowerType=TULIP)", flower.toString());
}
}
| 22.813953
| 118
| 0.615698
|
02c0261c496b3085faa5e0d4744b03dafa15fbce
| 1,692
|
swift
|
Swift
|
Memento.playground/contents.swift
|
yinnieryou/DesignPattern
|
ac49e8cab37d0c3cf1eb957da5518d9505be3e9b
|
[
"MIT"
] | 1
|
2015-06-23T23:58:16.000Z
|
2015-06-23T23:58:16.000Z
|
Memento.playground/contents.swift
|
yinnieryou/DesignPattern
|
ac49e8cab37d0c3cf1eb957da5518d9505be3e9b
|
[
"MIT"
] | null | null | null |
Memento.playground/contents.swift
|
yinnieryou/DesignPattern
|
ac49e8cab37d0c3cf1eb957da5518d9505be3e9b
|
[
"MIT"
] | null | null | null |
// Playground - noun: a place where people can play
import UIKit
//备忘录模式
class Originator{
var state1 = ""
var state2 = ""
var state3 = ""
func createMemento() -> Memento {
return Memento(map: BeanUtils.backupProp(self))
}
func restoreMemento(memento:Memento){
BeanUtils.restoreProp(memento.stateMap,originator: self)
}
func toString() -> String{
return "state1=\(state1)+state2=\(state2)+state3=\(state3)"
}
}
class Memento {
var stateMap:Dictionary<String,AnyObject> = [:]
init(map:Dictionary<String,AnyObject>){
self.stateMap = map
}
}
class BeanUtils {
class func backupProp(obj:Originator) -> Dictionary<String,AnyObject>{
var map:Dictionary<String,AnyObject>
map = ["state1":obj.state1 as AnyObject,"state2":obj.state2 as AnyObject,"state3":obj.state3 as AnyObject]
return map
}
class func restoreProp(propMap:Dictionary<String,AnyObject> ,originator:Originator){
originator.state1 = propMap["state1"] as! String
originator.state2 = propMap["state2"] as! String
originator.state3 = propMap["state3"] as! String
}
}
class Caretaker {
var memMap:Dictionary<String,Memento> = [:]
init(){
}
}
class Client{
init(){
var ori = Originator()
var careTaker = Caretaker()
ori.state1 = "A"
ori.state2 = "B"
ori.state3 = "C"
ori
careTaker.memMap = ["001":ori.createMemento()]
ori.state1 = "D"
ori.state2 = "E"
ori.state3 = "F"
ori
ori.restoreMemento(careTaker.memMap["001"]!)
}
}
var client = Client()
| 24.882353
| 116
| 0.604019
|
556c2ff2f4e55e1d2413f3fbcfef0b12c3309e8f
| 12,683
|
lua
|
Lua
|
modules/game_healthcircle/game_healthcircle.lua
|
juninholon/tibiagun
|
1ee9c8899d79d3602aee82850fb1c2c25285312d
|
[
"Apache-2.0"
] | null | null | null |
modules/game_healthcircle/game_healthcircle.lua
|
juninholon/tibiagun
|
1ee9c8899d79d3602aee82850fb1c2c25285312d
|
[
"Apache-2.0"
] | null | null | null |
modules/game_healthcircle/game_healthcircle.lua
|
juninholon/tibiagun
|
1ee9c8899d79d3602aee82850fb1c2c25285312d
|
[
"Apache-2.0"
] | null | null | null |
mapPanel = modules.game_interface.getMapPanel()
gameRootPanel = modules.game_interface.gameBottomPanel
gameLeftPanel = modules.game_interface.getLeftPanel()
gameTopMenu = modules.client_topmenu.getTopMenu()
function currentViewMode()
return modules.game_interface.currentViewMode
end
healthCircle = nil
manaCircle = nil
expCircle = nil
skillCircle = nil
g_ui.loadUI('game_healthcircle')
healthCircleFront = nil
manaCircleFront = nil
expCircleFront = nil
skillCircleFront = nil
isExpCircle = g_settings.getBoolean('healthcircle_expcircle')
isSkillCircle = g_settings.getBoolean('healthcircle_skillcircle')
skillType = g_settings.getString('healthcircle_skilltype')
if not (skillType == 'magic' or skillType == 'fist' or skillType == 'club' or skillType == 'sword' or skillType == 'axe' or skillType == 'distance' or skillType == 'shielding' or skillType == 'fishing') then
skillType = 'magic'
end
function init()
healthCircle = g_ui.createWidget('HealthCircle', mapPanel)
manaCircle = g_ui.createWidget('ManaCircle', mapPanel)
expCircle = g_ui.createWidget('ExpCircle', mapPanel)
skillCircle = g_ui.createWidget('SkillCircle', mapPanel)
healthCircleFront = g_ui.createWidget('HealthCircleFront', mapPanel)
manaCircleFront = g_ui.createWidget('ManaCircleFront', mapPanel)
expCircleFront = g_ui.createWidget('ExpCircleFront', mapPanel)
skillCircleFront = g_ui.createWidget('SkillCircleFront', mapPanel)
whenMapResizeChange()
initOnHpAndMpChange()
initOnGeometryChange()
initOnLoginChange()
if not isExpCircle then
expCircle:setVisible(false)
expCircleFront:setVisible(false)
end
if not isSkillCircle then
skillCircle:setVisible(false)
skillCircleFront:setVisible(false)
end
end
function terminate()
healthCircle:destroy()
manaCircle:destroy()
expCircle:destroy()
skillCircle:destroy()
healthCircleFront:destroy()
manaCircleFront:destroy()
expCircleFront:destroy()
skillCircleFront:destroy()
terminateOnHpAndMpChange()
terminateOnGeometryChange()
terminateOnLoginChange()
end
-------------------------------------------------
--Scripts----------------------------------------
-------------------------------------------------
function initOnHpAndMpChange()
connect(LocalPlayer, { onHealthChange = whenHealthChange,
onManaChange = whenManaChange,
onSkillChange = whenSkillsChange,
onMagicLevelChange = whenSkillsChange,
onLevelChange = whenSkillsChange })
end
function terminateOnHpAndMpChange()
disconnect(LocalPlayer, { onHealthChange = whenHealthChange,
onManaChange = whenManaChange,
onSkillChange = whenSkillsChange,
onMagicLevelChange = whenSkillsChange,
onLevelChange = whenSkillsChange })
end
function initOnGeometryChange()
connect(gameRootPanel, { onGeometryChange = whenMapResizeChange })
end
function terminateOnGeometryChange()
disconnect(gameRootPanel, { onGeometryChange = whenMapResizeChange })
end
function initOnLoginChange()
connect(g_game, { onGameStart = whenMapResizeChange })
end
function terminateOnLoginChange()
disconnect(g_game, { onGameStart = whenMapResizeChange })
end
function whenHealthChange()
if g_game.isOnline() then
local healthPercent = math.floor(g_game.getLocalPlayer():getHealthPercent())
local Yhppc = math.floor(208 * (1 - (healthPercent / 100)))
local rect = { x = 0, y = Yhppc, width = 63, height = 208 }
healthCircleFront:setImageClip(rect)
if healthPercent > 92 then
healthCircleFront:setImageColor("#00BC00")
elseif healthPercent > 60 then
healthCircleFront:setImageColor("#50A150")
elseif healthPercent > 30 then
healthCircleFront:setImageColor("#A1A100")
elseif healthPercent > 8 then
healthCircleFront:setImageColor("#BF0A0A")
elseif healthPercent > 3 then
healthCircleFront:setImageColor("#910F0F")
else
healthCircleFront:setImageColor("#850C0C")
end
healthCircleFront:setY(healthCircle:getY() + Yhppc)
end
end
function whenManaChange()
if g_game.isOnline() then
local Ymppc = math.floor(208 * (1 - (math.floor((g_game.getLocalPlayer():getMaxMana() - (g_game.getLocalPlayer():getMaxMana() - g_game.getLocalPlayer():getMana())) * 100 / g_game.getLocalPlayer():getMaxMana()) / 100)))
local rect = { x = 0, y = Ymppc, width = 63, height = 208 }
manaCircleFront:setImageClip(rect)
manaCircleFront:setY(manaCircle:getY() + Ymppc)
end
end
function whenSkillsChange()
if g_game.isOnline() then
if isExpCircle then
local player = g_game.getLocalPlayer()
local Xexpc = math.floor(208 * (1 - player:getLevelPercent() / 100))
local rect = { x = -1 * Xexpc, y = 0, width = 208, height = 63 }
expCircleFront:setImageClip(rect)
expCircleFront:setX(expCircle:getX() - Xexpc)
end
if isSkillCircle then
local player = g_game.getLocalPlayer()
Xskillpc = 0
if skillType == 'magic' then
Xskillpc = math.floor(208 * (1 - player:getMagicLevelPercent() / 100))
skillCircleFront:setImageColor('#00ffcc')
elseif skillType == 'fist' then
Xskillpc = math.floor(208 * (1 - player:getSkillLevelPercent(0) / 100))
skillCircleFront:setImageColor('#9900cc')
elseif skillType == 'club' then
Xskillpc = math.floor(208 * (1 - player:getSkillLevelPercent(1) / 100))
skillCircleFront:setImageColor('#cc3399')
elseif skillType == 'sword' then
Xskillpc = math.floor(208 * (1 - player:getSkillLevelPercent(2) / 100))
skillCircleFront:setImageColor('#FF7F00')
elseif skillType == 'axe' then
Xskillpc = math.floor(208 * (1 - player:getSkillLevelPercent(3) / 100))
skillCircleFront:setImageColor('#696969')
elseif skillType == 'distance' then
Xskillpc = math.floor(208 * (1 - player:getSkillLevelPercent(4) / 100))
skillCircleFront:setImageColor('#A62A2A')
elseif skillType == 'shielding' then
Xskillpc = math.floor(208 * (1 - player:getSkillLevelPercent(5) / 100))
skillCircleFront:setImageColor('#663300')
elseif skillType == 'fishing' then
Xskillpc = math.floor(208 * (1 - player:getSkillLevelPercent(6) / 100))
skillCircleFront:setImageColor('#ffff33')
end
local rect = { x = -1 * Xskillpc, y = 0, width = 208, height = 63 }
skillCircleFront:setImageClip(rect)
skillCircleFront:setX(expCircle:getX() - Xskillpc)
end
end
end
function whenMapResizeChange()
if g_game.isOnline() then
local barDistance = 90
if not (math.floor(mapPanel:getHeight() / 2 * 0.2) < 100) then --0.381
barDistance = math.floor(mapPanel:getHeight() / 2 * 0.2)
end
if currentViewMode() == 2 then
healthCircleFront:setX(math.floor(mapPanel:getWidth() / 2 - barDistance - healthCircle:getWidth()))
manaCircleFront:setX(math.floor(mapPanel:getWidth() / 2 + barDistance))
healthCircle:setX(math.floor(mapPanel:getWidth() / 2 - barDistance - healthCircle:getWidth()))
manaCircle:setX(math.floor((mapPanel:getWidth() / 2 + barDistance)))
healthCircle:setY(mapPanel:getHeight() / 2 - healthCircle:getHeight() / 2 + 0)
manaCircle:setY(mapPanel:getHeight() / 2 - manaCircle:getHeight() / 2 + 0)
if isExpCircle then
expCircleFront:setY(math.floor(mapPanel:getHeight() / 2 - barDistance - expCircle:getHeight()))
expCircle:setX(math.floor(mapPanel:getWidth() / 2 - expCircle:getWidth() / 2))
expCircle:setY(math.floor(mapPanel:getHeight() / 2 - barDistance - expCircle:getHeight()))
end
if isSkillCircle then
skillCircleFront:setY(math.floor(mapPanel:getHeight() / 2 + barDistance))
skillCircle:setX(math.floor(mapPanel:getWidth() / 2 - skillCircle:getWidth() / 2))
skillCircle:setY(math.floor(mapPanel:getHeight() / 2 + barDistance))
end
elseif gameLeftPanel:isOn() then
healthCircleFront:setX(math.floor(mapPanel:getWidth() / 2 - barDistance - healthCircle:getWidth() + gameLeftPanel:getWidth()))
manaCircleFront:setX(math.floor(mapPanel:getWidth() / 2 + barDistance + gameLeftPanel:getWidth()))
healthCircle:setX(math.floor(mapPanel:getWidth() / 2 - barDistance - healthCircle:getWidth() + gameLeftPanel:getWidth()))
manaCircle:setX(math.floor((mapPanel:getWidth() / 2 + barDistance + gameLeftPanel:getWidth())))
healthCircle:setY(mapPanel:getHeight() / 2 - healthCircle:getHeight() / 2 + gameTopMenu:getHeight())
manaCircle:setY(mapPanel:getHeight() / 2 - manaCircle:getHeight() / 2 + gameTopMenu:getHeight())
if isExpCircle then
expCircleFront:setY(math.floor(mapPanel:getHeight() / 2 + gameTopMenu:getHeight() - barDistance - expCircleFront:getHeight()))
expCircle:setX(math.floor(mapPanel:getWidth() / 2 - expCircle:getWidth() / 2 + gameLeftPanel:getWidth()))
expCircle:setY(math.floor(mapPanel:getHeight() / 2 + gameTopMenu:getHeight() - barDistance - expCircle:getHeight()))
end
if isSkillCircle then
skillCircleFront:setY(math.floor(mapPanel:getHeight() / 2 + gameTopMenu:getHeight() + barDistance))
skillCircle:setX(math.floor(mapPanel:getWidth() / 2 - expCircle:getWidth() / 2 + gameLeftPanel:getWidth()))
skillCircle:setY(math.floor(mapPanel:getHeight() / 2 + gameTopMenu:getHeight() + barDistance))
end
else
healthCircleFront:setX(math.floor(mapPanel:getWidth() / 2 - barDistance - healthCircle:getWidth()))
manaCircleFront:setX(math.floor(mapPanel:getWidth() / 2 + barDistance))
healthCircle:setX(math.floor(mapPanel:getWidth() / 2 - barDistance - healthCircle:getWidth()))
manaCircle:setX(math.floor((mapPanel:getWidth() / 2 + barDistance)))
healthCircle:setY(mapPanel:getHeight() / 2 - healthCircle:getHeight() / 2 + gameTopMenu:getHeight())
manaCircle:setY(mapPanel:getHeight() / 2 - manaCircle:getHeight() / 2 + gameTopMenu:getHeight())
if isExpCircle then
expCircleFront:setY(math.floor(mapPanel:getHeight() / 2 + gameTopMenu:getHeight() - barDistance - expCircleFront:getHeight()))
expCircle:setX(math.floor(mapPanel:getWidth() / 2 - expCircle:getWidth() / 2))
expCircle:setY(math.floor(mapPanel:getHeight() / 2 + gameTopMenu:getHeight() - barDistance - expCircle:getHeight()))
end
if isSkillCircle then
skillCircleFront:setY(math.floor(mapPanel:getHeight() / 2 + gameTopMenu:getHeight() + barDistance))
skillCircle:setX(math.floor(mapPanel:getWidth() / 2 - expCircle:getWidth() / 2))
skillCircle:setY(math.floor(mapPanel:getHeight() / 2 + gameTopMenu:getHeight() + barDistance))
end
end
whenHealthChange()
whenManaChange()
if isExpCircle or isSkillCircle then
whenSkillsChange()
end
end
end
-------------------------------------------------
--Controls---------------------------------------
-------------------------------------------------
function setExpCircle(value)
value = toboolean(value)
isExpCircle = value
if value then
expCircle:setVisible(true)
expCircleFront:setVisible(true)
whenMapResizeChange()
else
expCircle:setVisible(false)
expCircleFront:setVisible(false)
end
g_settings.set('healthcircle_expcircle', value)
end
function setHealthCircle(value)
value = toboolean(value)
if value then
healthCircle:setVisible(true)
healthCircleFront:setVisible(true)
manaCircle:setVisible(true)
manaCircleFront:setVisible(true)
whenMapResizeChange()
else
healthCircle:setVisible(false)
healthCircleFront:setVisible(false)
manaCircle:setVisible(false)
manaCircleFront:setVisible(false)
end
end
function setSkillCircle(value)
value = toboolean(value)
isSkillCircle = value
if value then
skillCircle:setVisible(true)
skillCircleFront:setVisible(true)
whenMapResizeChange()
else
skillCircle:setVisible(false)
skillCircleFront:setVisible(false)
end
g_settings.set('healthcircle_skillcircle', value)
end
function setSkillType(skill)
if skill == 'magic' or skill == 'fist' or skill == 'club' or skill == 'sword' or skill == 'axe' or skill == 'distance' or skill == 'shielding' or skill == 'fishing' then
skillType = skill
whenMapResizeChange()
g_settings.set('healthcircle_skilltype', skill)
else
if not skillType then
skillType = 'magic'
whenMapResizeChange()
g_settings.set('healthcircle_skilltype', 'magic')
end
end
end
| 36.976676
| 222
| 0.686036
|
e4bfaecd9054252e271c3ef5d6606736af1de5e5
| 2,160
|
go
|
Go
|
vendor/github.com/AdguardTeam/golibs/stringutil/set.go
|
IrineSistiana/dnsproxy
|
e2fba4e244bf0c3f651a937b3d59dd1bd704c80c
|
[
"Apache-2.0"
] | 15
|
2019-02-27T17:20:03.000Z
|
2022-02-14T17:12:33.000Z
|
vendor/github.com/AdguardTeam/golibs/stringutil/set.go
|
IrineSistiana/dnsproxy
|
e2fba4e244bf0c3f651a937b3d59dd1bd704c80c
|
[
"Apache-2.0"
] | 4
|
2019-10-14T16:13:27.000Z
|
2022-03-23T12:25:26.000Z
|
vendor/github.com/AdguardTeam/golibs/stringutil/set.go
|
IrineSistiana/dnsproxy
|
e2fba4e244bf0c3f651a937b3d59dd1bd704c80c
|
[
"Apache-2.0"
] | 9
|
2019-04-04T22:12:08.000Z
|
2022-03-13T13:42:27.000Z
|
package stringutil
import "fmt"
// unit is a convenient alias for struct{}
type unit = struct{}
// Set is a set of strings.
type Set struct {
m map[string]unit
}
// NewSet returns a new string set containing strs.
func NewSet(strs ...string) (set *Set) {
set = &Set{
m: make(map[string]unit, len(strs)),
}
for _, s := range strs {
set.Add(s)
}
return set
}
// Add adds s to the set. Add panics if the set is a nil set, just like a nil
// map does.
func (set *Set) Add(s string) {
set.m[s] = unit{}
}
// Del deletes s from the set. Calling Del on a nil set has no effect, just
// like delete on an empty map doesn't.
func (set *Set) Del(s string) {
if set != nil {
delete(set.m, s)
}
}
// Equal returns true if set is equal to other.
func (set *Set) Equal(other *Set) (ok bool) {
if set == nil || other == nil {
return set == other
} else if set.Len() != other.Len() {
return false
}
for s := range set.m {
if _, ok = other.m[s]; !ok {
return false
}
}
return true
}
// Has returns true if s is in the set. Calling Has on a nil set returns false,
// just like indexing on an empty map does.
func (set *Set) Has(s string) (ok bool) {
if set != nil {
_, ok = set.m[s]
}
return ok
}
// Len returns the length of the set. A nil set has a length of zero, just like
// an empty map.
func (set *Set) Len() (n int) {
if set == nil {
return 0
}
return len(set.m)
}
// Range calls f with each value of the set in an undefined order. If cont is
// false, Range stops the iteration. Calling Range on a nil *Set has no effect.
func (set *Set) Range(f func(s string) (cont bool)) {
if set == nil {
return
}
for s := range set.m {
if !f(s) {
break
}
}
}
// String implements the fmt.Stringer interface for *Set.
func (set *Set) String() (s string) {
return fmt.Sprintf("%q", set.Values())
}
// Values returns all values in the set. The order of the values is undefined.
// Values returns nil if the set is nil.
func (set *Set) Values() (strs []string) {
if set == nil {
return nil
}
strs = make([]string, 0, len(set.m))
for s := range set.m {
strs = append(strs, s)
}
return strs
}
| 19.636364
| 80
| 0.627315
|
be5e908809f06cefa7138f2fdea03e7909d696d6
| 841
|
ts
|
TypeScript
|
packages/color/src/int/int-srgb.ts
|
ja0nz/umbrella
|
fc2d657b51d111ab548fb56b497ad4e13a2f888a
|
[
"Apache-2.0"
] | 2,293
|
2018-01-24T14:36:35.000Z
|
2022-03-29T18:44:28.000Z
|
packages/color/src/int/int-srgb.ts
|
ja0nz/umbrella
|
fc2d657b51d111ab548fb56b497ad4e13a2f888a
|
[
"Apache-2.0"
] | 283
|
2018-01-28T20:01:54.000Z
|
2022-03-31T10:00:01.000Z
|
packages/color/src/int/int-srgb.ts
|
ja0nz/umbrella
|
fc2d657b51d111ab548fb56b497ad4e13a2f888a
|
[
"Apache-2.0"
] | 118
|
2018-02-03T03:11:30.000Z
|
2022-03-22T14:38:07.000Z
|
import { setC4 } from "@thi.ng/vectors/setc";
import type { Color } from "../api.js";
import { INV8BIT } from "../api/constants.js";
export const intArgb32Srgb = (out: Color | null, src: number) =>
setC4(
out || [],
((src >>> 16) & 0xff) * INV8BIT,
((src >>> 8) & 0xff) * INV8BIT,
(src & 0xff) * INV8BIT,
(src >>> 24) * INV8BIT
);
export const intAbgr32Srgb = (out: Color | null, src: number) =>
setC4(
out || [],
(src & 0xff) * INV8BIT,
((src >>> 8) & 0xff) * INV8BIT,
((src >>> 16) & 0xff) * INV8BIT,
(src >>> 24) * INV8BIT
);
export const intRgb24Srgb = (out: Color | null, src: number) =>
intArgb32Srgb(out, src | 0xff000000);
export const intBgr24Srgb = (out: Color | null, src: number) =>
intAbgr32Srgb(out, src | 0xff000000);
| 30.035714
| 64
| 0.537455
|
0d7793c7db3fdc47e2662e8a65f4c5470ffc451a
| 1,060
|
cs
|
C#
|
contract/MAVN.Service.CrossChainTransfers.Contract/TransferToExternalProcessedEvent.cs
|
mavn-alliance/MAVN.Service.CrossChainTransfers
|
2fb449ba700839f60adc5c3ad2c3c17c6c625b9d
|
[
"MIT"
] | null | null | null |
contract/MAVN.Service.CrossChainTransfers.Contract/TransferToExternalProcessedEvent.cs
|
mavn-alliance/MAVN.Service.CrossChainTransfers
|
2fb449ba700839f60adc5c3ad2c3c17c6c625b9d
|
[
"MIT"
] | 6
|
2020-03-25T18:49:24.000Z
|
2021-12-20T00:18:57.000Z
|
contract/MAVN.Service.CrossChainTransfers.Contract/TransferToExternalProcessedEvent.cs
|
mavn-alliance/MAVN.Service.CrossChainTransfers
|
2fb449ba700839f60adc5c3ad2c3c17c6c625b9d
|
[
"MIT"
] | 5
|
2020-03-25T19:12:58.000Z
|
2020-05-06T15:18:07.000Z
|
using System.Numerics;
using MAVN.Numerics;
namespace MAVN.Service.CrossChainTransfers.Contract
{
public class TransferToExternalProcessedEvent
{
public string OperationId { get; set; }
/// <summary>
/// Id of the Customer
/// </summary>
public string CustomerId { get; set; }
/// <summary>
/// Amount of tokens to transfer, without the fee
/// </summary>
public Money18 Amount { get; set; }
/// <summary>
/// Transaction hash of the operation
/// </summary>
public string TxHash { get; set; }
/// <summary>
/// Private wallet address of the customer
/// </summary>
public string PrivateAddress { get; set; }
/// <summary>
/// Public linked address of the customer
/// </summary>
public string PublicAddress { get; set; }
/// <summary>
/// Transfer id of the transaction
/// </summary>
public BigInteger InternalTransferId { get; set; }
}
}
| 26.5
| 58
| 0.557547
|
5aebbf1d32d7df4b5f6b7bbdf8918a744159869a
| 17,011
|
cs
|
C#
|
apis/Google.Cloud.Dataflow.V1Beta3/Google.Cloud.Dataflow.V1Beta3.Snippets/JobsV1Beta3ClientSnippets.g.cs
|
anshuldavid13/google-cloud-dotnet
|
a76f461f118053f069f59c45b21251109aa70ecb
|
[
"Apache-2.0"
] | 285
|
2016-07-14T12:48:23.000Z
|
2018-09-15T23:00:47.000Z
|
apis/Google.Cloud.Dataflow.V1Beta3/Google.Cloud.Dataflow.V1Beta3.Snippets/JobsV1Beta3ClientSnippets.g.cs
|
anshuldavid13/google-cloud-dotnet
|
a76f461f118053f069f59c45b21251109aa70ecb
|
[
"Apache-2.0"
] | 1,567
|
2016-07-11T16:48:03.000Z
|
2018-09-17T15:50:12.000Z
|
apis/Google.Cloud.Dataflow.V1Beta3/Google.Cloud.Dataflow.V1Beta3.Snippets/JobsV1Beta3ClientSnippets.g.cs
|
anshuldavid13/google-cloud-dotnet
|
a76f461f118053f069f59c45b21251109aa70ecb
|
[
"Apache-2.0"
] | 134
|
2016-07-12T02:11:35.000Z
|
2018-09-15T00:10:29.000Z
|
// Copyright 2022 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dataflow.V1Beta3.Snippets
{
using Google.Api.Gax;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedJobsV1Beta3ClientSnippets
{
/// <summary>Snippet for CreateJob</summary>
public void CreateJobRequestObject()
{
// Snippet: CreateJob(CreateJobRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create();
// Initialize request argument(s)
CreateJobRequest request = new CreateJobRequest
{
ProjectId = "",
Job = new Job(),
View = JobView.Unknown,
ReplaceJobId = "",
Location = "",
};
// Make the request
Job response = jobsV1Beta3Client.CreateJob(request);
// End snippet
}
/// <summary>Snippet for CreateJobAsync</summary>
public async Task CreateJobRequestObjectAsync()
{
// Snippet: CreateJobAsync(CreateJobRequest, CallSettings)
// Additional: CreateJobAsync(CreateJobRequest, CancellationToken)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync();
// Initialize request argument(s)
CreateJobRequest request = new CreateJobRequest
{
ProjectId = "",
Job = new Job(),
View = JobView.Unknown,
ReplaceJobId = "",
Location = "",
};
// Make the request
Job response = await jobsV1Beta3Client.CreateJobAsync(request);
// End snippet
}
/// <summary>Snippet for GetJob</summary>
public void GetJobRequestObject()
{
// Snippet: GetJob(GetJobRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create();
// Initialize request argument(s)
GetJobRequest request = new GetJobRequest
{
ProjectId = "",
JobId = "",
View = JobView.Unknown,
Location = "",
};
// Make the request
Job response = jobsV1Beta3Client.GetJob(request);
// End snippet
}
/// <summary>Snippet for GetJobAsync</summary>
public async Task GetJobRequestObjectAsync()
{
// Snippet: GetJobAsync(GetJobRequest, CallSettings)
// Additional: GetJobAsync(GetJobRequest, CancellationToken)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync();
// Initialize request argument(s)
GetJobRequest request = new GetJobRequest
{
ProjectId = "",
JobId = "",
View = JobView.Unknown,
Location = "",
};
// Make the request
Job response = await jobsV1Beta3Client.GetJobAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateJob</summary>
public void UpdateJobRequestObject()
{
// Snippet: UpdateJob(UpdateJobRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create();
// Initialize request argument(s)
UpdateJobRequest request = new UpdateJobRequest
{
ProjectId = "",
JobId = "",
Job = new Job(),
Location = "",
};
// Make the request
Job response = jobsV1Beta3Client.UpdateJob(request);
// End snippet
}
/// <summary>Snippet for UpdateJobAsync</summary>
public async Task UpdateJobRequestObjectAsync()
{
// Snippet: UpdateJobAsync(UpdateJobRequest, CallSettings)
// Additional: UpdateJobAsync(UpdateJobRequest, CancellationToken)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync();
// Initialize request argument(s)
UpdateJobRequest request = new UpdateJobRequest
{
ProjectId = "",
JobId = "",
Job = new Job(),
Location = "",
};
// Make the request
Job response = await jobsV1Beta3Client.UpdateJobAsync(request);
// End snippet
}
/// <summary>Snippet for ListJobs</summary>
public void ListJobsRequestObject()
{
// Snippet: ListJobs(ListJobsRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create();
// Initialize request argument(s)
ListJobsRequest request = new ListJobsRequest
{
ProjectId = "",
Filter = ListJobsRequest.Types.Filter.Unknown,
Location = "",
};
// Make the request
PagedEnumerable<ListJobsResponse, Job> response = jobsV1Beta3Client.ListJobs(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Job item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListJobsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Job item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Job> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Job item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListJobsAsync</summary>
public async Task ListJobsRequestObjectAsync()
{
// Snippet: ListJobsAsync(ListJobsRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync();
// Initialize request argument(s)
ListJobsRequest request = new ListJobsRequest
{
ProjectId = "",
Filter = ListJobsRequest.Types.Filter.Unknown,
Location = "",
};
// Make the request
PagedAsyncEnumerable<ListJobsResponse, Job> response = jobsV1Beta3Client.ListJobsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Job item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListJobsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Job item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Job> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Job item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListJobs</summary>
public void AggregatedListJobsRequestObject()
{
// Snippet: AggregatedListJobs(ListJobsRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create();
// Initialize request argument(s)
ListJobsRequest request = new ListJobsRequest
{
ProjectId = "",
Filter = ListJobsRequest.Types.Filter.Unknown,
Location = "",
};
// Make the request
PagedEnumerable<ListJobsResponse, Job> response = jobsV1Beta3Client.AggregatedListJobs(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Job item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListJobsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Job item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Job> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Job item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListJobsAsync</summary>
public async Task AggregatedListJobsRequestObjectAsync()
{
// Snippet: AggregatedListJobsAsync(ListJobsRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync();
// Initialize request argument(s)
ListJobsRequest request = new ListJobsRequest
{
ProjectId = "",
Filter = ListJobsRequest.Types.Filter.Unknown,
Location = "",
};
// Make the request
PagedAsyncEnumerable<ListJobsResponse, Job> response = jobsV1Beta3Client.AggregatedListJobsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Job item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListJobsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Job item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Job> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Job item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for CheckActiveJobs</summary>
public void CheckActiveJobsRequestObject()
{
// Snippet: CheckActiveJobs(CheckActiveJobsRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create();
// Initialize request argument(s)
CheckActiveJobsRequest request = new CheckActiveJobsRequest { ProjectId = "", };
// Make the request
CheckActiveJobsResponse response = jobsV1Beta3Client.CheckActiveJobs(request);
// End snippet
}
/// <summary>Snippet for CheckActiveJobsAsync</summary>
public async Task CheckActiveJobsRequestObjectAsync()
{
// Snippet: CheckActiveJobsAsync(CheckActiveJobsRequest, CallSettings)
// Additional: CheckActiveJobsAsync(CheckActiveJobsRequest, CancellationToken)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync();
// Initialize request argument(s)
CheckActiveJobsRequest request = new CheckActiveJobsRequest { ProjectId = "", };
// Make the request
CheckActiveJobsResponse response = await jobsV1Beta3Client.CheckActiveJobsAsync(request);
// End snippet
}
/// <summary>Snippet for SnapshotJob</summary>
public void SnapshotJobRequestObject()
{
// Snippet: SnapshotJob(SnapshotJobRequest, CallSettings)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = JobsV1Beta3Client.Create();
// Initialize request argument(s)
SnapshotJobRequest request = new SnapshotJobRequest
{
ProjectId = "",
JobId = "",
Ttl = new Duration(),
Location = "",
SnapshotSources = false,
Description = "",
};
// Make the request
Snapshot response = jobsV1Beta3Client.SnapshotJob(request);
// End snippet
}
/// <summary>Snippet for SnapshotJobAsync</summary>
public async Task SnapshotJobRequestObjectAsync()
{
// Snippet: SnapshotJobAsync(SnapshotJobRequest, CallSettings)
// Additional: SnapshotJobAsync(SnapshotJobRequest, CancellationToken)
// Create client
JobsV1Beta3Client jobsV1Beta3Client = await JobsV1Beta3Client.CreateAsync();
// Initialize request argument(s)
SnapshotJobRequest request = new SnapshotJobRequest
{
ProjectId = "",
JobId = "",
Ttl = new Duration(),
Location = "",
SnapshotSources = false,
Description = "",
};
// Make the request
Snapshot response = await jobsV1Beta3Client.SnapshotJobAsync(request);
// End snippet
}
}
}
| 40.696172
| 120
| 0.564047
|
2d14bc423aee716713056c138175f171c8d98334
| 5,816
|
lua
|
Lua
|
main.lua
|
tes3mp-scripts/DoubleTrouble
|
91758a8c1c4ec1ab94f9da52acd74c492e87fe24
|
[
"MIT"
] | 6
|
2019-03-19T21:20:03.000Z
|
2021-03-06T15:11:17.000Z
|
main.lua
|
tes3mp-scripts/DoubleTrouble
|
91758a8c1c4ec1ab94f9da52acd74c492e87fe24
|
[
"MIT"
] | null | null | null |
main.lua
|
tes3mp-scripts/DoubleTrouble
|
91758a8c1c4ec1ab94f9da52acd74c492e87fe24
|
[
"MIT"
] | 1
|
2022-03-17T03:04:25.000Z
|
2022-03-17T03:04:25.000Z
|
local DoubleTrouble = {}
DoubleTrouble.scriptName = "DoubleTrouble"
DoubleTrouble.cellDir = tes3mp.GetModDir() .. "/cell/"
DoubleTrouble.defaultConfig = {
minimumCopies = 3,
maximumCopies = 7,
creatures = {
"ascended_sleeper", "ash_ghoul", "ash_slave", "ash_zombie", "ash_zombie_fgaz", "corprus_stalker", "corprus_stalker_morvayn", "corprus_lame", "corprus_lame_morvayn", "alit", "alit_diseased", "alit_blighted", "cliff racer", "cliff racer_diseased", "cliff racer_blighted", "dreugh", "dreugh_koal", "guar_feral", "kagouti", "kagouti_mating", "kagouti_hrk", "kagouti_diseased", "kagouti_blighted", "mudcrab", "mudcrab-Diseased", "mudcrab_hrmudcrabnest", "netch_betty", "netch_bull", "nix-hound", "nix-hound blighted", "Rat", "rat_cave_fgrh", "rat_cave_fgt", "rat_diseased", "rat_blighted", "shalk", "shalk_diseased", "shalk_diseased_hram", "shalk_blighted", "Slaughterfish_Small", "slaughterfish", "slaughterfish_hr_sfavd", "atronach_flame", "atronach_flame_az", "atronach_flame_ttmk", "atronach_frost", "atronach_frost_ttmk", "atronach_frost_gwai_uni", "atronach_storm", "atronach_storm_az", "atronach_storm_ttmk", "clannfear", "daedroth", "daedroth_az", "daedroth_baladas", "daedroth_fg_nchur", "dremora", "dremora_lord", "golden saint", "hunger", "hunger_az_01", "hunger_az_02", "ogrim", "ogrim_az", "ogrim titan", "scamp", "winged twilight", "centurion_sphere", "centurion_sphere_nchur", "centurion_shock_baladas", "centurion_spider", "centurion_spider_nchur", "centurion_steam", "centurion_steam_nchur", "centurion_steam_advance", "centurion_projectile", "centurion_steam_A_C", "centurion_steam_C_L", "centurion_projectile_C", "kwama forager", "kwama forager_tb", "kwama forager blighted", "kwama warrior", "kwama warrior blighted", "kwama warrior shurdan", "kwama worker", "kwama worker entrance", "kwama worker diseased", "kwama worker blighted", "scrib", "scrib diseased", "scrib blighted", "ancestor_ghost", "bonelord", "bonewalker", "Bonewalker_Greater", "dwarven ghost", "skeleton_weak", "skeleton", "skeleton hero dead", "dead_skeleton", "skeleton entrance", "skeleton archer", "skeleton champion", "skeleton champ_sandas00", "skeleton champ_sandas10", "skeleton warrior", "worm lord", "durzog_wild_weaker", "durzog_diseased", "durzog_wild", "durzog_war_trained", "durzog_war", "fabricant_hulking_C", "fabricant_hulkin_attack", "fabricant_hulking_ss", "fabricant_hulking", "fabricant_hulking_C_L", "fabricant_machine_1", "fabricant_verm_attack", "fabricant_verminous", "fabricant_verminous_C", "fabricant_verminous-rs", "goblin_grunt", "goblin_footsoldier", "goblin_bruiser", "goblin_handler", "goblin_officer", "goblin_officerUNI", "lich", "ancestor_ghost_greater", "Imperfect", "Rat_plague", "BM_bear_black", "BM_bear_brown", "BM_ice_troll", "BM_ice_troll_tough", "BM_icetroll_FG_Uni", "BM_horker", "BM_horker_large", "BM_riekling", "BM_riekling_be_UNIQUE1", "BM_riekling_be_UNIQUE2", "BM_riekling_be_UNIQUE3", "BM_riekling_be_UNIQUE4", "BM_riekling_be_UNIQUE5", "BM_riekling_boarmaster", "BM_riekling_mounted", "BM_spriggan", "BM_frost_boar", "BM_wolf_grey_lvl_1", "BM_wolf_grey", "BM_wolf_hroldar", "BM_wolf_red", "atronach_frost_BM", "BM_wolf_skeleton", "BM_draugr01", "BM_draugr_bloodskal", "draugr", "draugr_co_3", "draugr_valbrandr", "draugr_aesliip", "skeleton nord", "skeleton_stahl_uni", "skeleton nord_2", "bm_skeleton_pirate", "bm skeleton champion gr", "bm_sk_champ_bloodskal01", "bm_sk_champ_bloodskal02"
}
}
DoubleTrouble.config = DataManager.loadConfiguration(DoubleTrouble.scriptName, DoubleTrouble.defaultConfig)
DoubleTrouble.creatureCheck = {}
math.randomseed(os.time())
for k, v in pairs(DoubleTrouble.config.creatures) do
DoubleTrouble.creatureCheck[v] = true
end
DoubleTrouble.visited = {}
function DoubleTrouble.isCreature(refId)
return DoubleTrouble.creatureCheck[refId] ~= nil
end
function DoubleTrouble.getCopies()
return math.random(DoubleTrouble.config.minimumCopies, DoubleTrouble.config.maximumCopies)
end
function DoubleTrouble.duplicate(cellDescription)
local cellData = LoadedCells[cellDescription].data
if cellData~=nil then
local creatures = {}
for _, uniqueIndex in pairs(cellData.packets.actorList) do
if
cellData.objectData[uniqueIndex].location ~= nil and
DoubleTrouble.isCreature(cellData.objectData[uniqueIndex].refId)
then
table.insert(creatures, uniqueIndex)
end
end
tes3mp.LogMessage(
enumerations.log.INFO,
"[DoubleTrouble] Cloning "..#creatures.."("..#cellData.packets.actorList..") creatures:"
)
for _, uniqueIndex in pairs(creatures) do
local creature = cellData.objectData[uniqueIndex]
tes3mp.LogMessage(enumerations.log.INFO, creature.refId)
local copies = DoubleTrouble.getCopies()
for i=2, copies do
logicHandler.CreateObjectAtLocation(cellDescription, creature.location, creature.refId, "spawn")
end
end
end
end
function DoubleTrouble.OnCellLoadValidator(eventStatus, pid, cellDescription)
local cell = Cell(cellDescription)
local cellFilePath = DoubleTrouble.cellDir .. cell.entryFile
if tes3mp.DoesFileExist(cellFilePath) then
DoubleTrouble.visited[cellDescription] = true
end
end
function DoubleTrouble.OnActorList(eventStatus, pid, cellDescription)
if DoubleTrouble.visited[cellDescription] == nil then
DoubleTrouble.visited[cellDescription] = true
DoubleTrouble.duplicate(cellDescription)
end
end
customEventHooks.registerValidator("OnCellLoad", DoubleTrouble.OnCellLoadValidator)
customEventHooks.registerHandler("OnActorList", DoubleTrouble.OnActorList)
return DoubleTrouble
| 66.850575
| 3,234
| 0.746389
|
a4ac2d0b4d85b32bb98353f79a9cfb0d68ac4800
| 1,033
|
php
|
PHP
|
Websom/Generic/Core/Data.php
|
SomeGreatUsername/websom
|
efc3c6280c8f54213cc1d19a7c6032c8a348878a
|
[
"MIT"
] | null | null | null |
Websom/Generic/Core/Data.php
|
SomeGreatUsername/websom
|
efc3c6280c8f54213cc1d19a7c6032c8a348878a
|
[
"MIT"
] | null | null | null |
Websom/Generic/Core/Data.php
|
SomeGreatUsername/websom
|
efc3c6280c8f54213cc1d19a7c6032c8a348878a
|
[
"MIT"
] | null | null | null |
<?php
/**
* \defgroup Data Data
*
* The Data class is a new tool that will replace the Object data interfacing.
*
* This tool only contains a MySql database table structure object for now.
*
*/
/**
* \ingroup Data
*/
class Data {
/**
* This method is used to construct a Data_Structure object.
* See Data_Structure::__construct.
*/
function structure($columns) {
}
}
/**
* See Data::structure() for info about this class.
*/
class Data_Structure {
/**
* @param array $columns The $columns should be an array that is structured like so
* \code
* [
* "column name" => [ //The column name
* "type" => "type of value, for instance 'VARCHAR(123)'", //The type of information that will be stored in the column.
* "default" => "blank", //Default value
* "extra query string that will be inserted into the MySql query" => true //The key in this line is the string that will be inserted. It could be something like "NOT NULL"
* ]
* ]
* \endcode
*
*/
public function __construct($columns) {
}
}
?>
| 21.520833
| 174
| 0.660213
|
05377e2c76b1f86614cf7fd4bf94ff133376253a
| 123
|
rb
|
Ruby
|
app/helpers/application_helper.rb
|
kity-linuxero/todorails
|
dc9ab6548cae26dd98fc18e2b4d6941de0819511
|
[
"MIT"
] | null | null | null |
app/helpers/application_helper.rb
|
kity-linuxero/todorails
|
dc9ab6548cae26dd98fc18e2b4d6941de0819511
|
[
"MIT"
] | 14
|
2016-12-05T00:36:25.000Z
|
2022-03-30T22:19:27.000Z
|
app/helpers/application_helper.rb
|
kity-linuxero/todorails
|
dc9ab6548cae26dd98fc18e2b4d6941de0819511
|
[
"MIT"
] | null | null | null |
module ApplicationHelper
VERSION = "1.4.0"
YEAR = "2016"
DEVELOPERS = "Cristian Giambruni"
NAME = "Todo-Rails"
end
| 17.571429
| 35
| 0.682927
|
72b3af8c38b4b8ad9dbdd2e798e231c54269bea3
| 791
|
cs
|
C#
|
RightpointLabs.Pourcast.Application/Orchestrators/Abstract/IIdentityOrchestrator.cs
|
RightpointLabs/Pourcast
|
2b15b6eee7f0b48357281b691398b040970b659f
|
[
"MIT"
] | 5
|
2015-02-11T14:15:58.000Z
|
2016-11-21T12:53:57.000Z
|
RightpointLabs.Pourcast.Application/Orchestrators/Abstract/IIdentityOrchestrator.cs
|
Rightpoint/Pourcast
|
2b15b6eee7f0b48357281b691398b040970b659f
|
[
"MIT"
] | 12
|
2015-02-18T17:17:34.000Z
|
2016-10-26T19:15:41.000Z
|
RightpointLabs.Pourcast.Application/Orchestrators/Abstract/IIdentityOrchestrator.cs
|
Rightpoint/Pourcast
|
2b15b6eee7f0b48357281b691398b040970b659f
|
[
"MIT"
] | 3
|
2015-02-27T21:53:39.000Z
|
2018-10-11T19:37:28.000Z
|
namespace RightpointLabs.Pourcast.Application.Orchestrators.Abstract
{
using System.Collections.Generic;
using RightpointLabs.Pourcast.Domain.Models;
public interface IIdentityOrchestrator
{
bool IsUserInRole(string username, string roleName);
IEnumerable<Role> GetRolesForUser(string username);
void CreateRole(string roleName);
void DeleteRole(string roleName);
bool RoleExists(string roleName);
void CreateUser(string username);
void AddUsersToRoles(string[] usernames, string[] roleNames);
IEnumerable<User> GetUsersInRole(string roleName);
IEnumerable<Role> GetAllRoles();
void AddUserToRole(string username, string roleName);
bool UserExists(string username);
}
}
| 24.71875
| 69
| 0.705436
|
aee610d5dad11f1e1c2844637acd92cfd36f5419
| 167
|
cs
|
C#
|
Assets/Plugins/GoKit/enums/ShakeType.cs
|
Alaanor/udh-gamejam
|
0825364195512b41b4f5f0d548def8c16d341b95
|
[
"WTFPL"
] | null | null | null |
Assets/Plugins/GoKit/enums/ShakeType.cs
|
Alaanor/udh-gamejam
|
0825364195512b41b4f5f0d548def8c16d341b95
|
[
"WTFPL"
] | null | null | null |
Assets/Plugins/GoKit/enums/ShakeType.cs
|
Alaanor/udh-gamejam
|
0825364195512b41b4f5f0d548def8c16d341b95
|
[
"WTFPL"
] | null | null | null |
using UnityEngine;
using System.Collections;
[System.Flags]
public enum ShakeType
{
Position = ( 1 << 0 ),
Scale = ( 1 << 1 ),
Eulers = ( 1 << 2 )
}
| 15.181818
| 27
| 0.556886
|
93327697cc13afda82bc50265e8f1cb1a56d563d
| 3,276
|
go
|
Go
|
security/pkg/k8s/controller/casecret.go
|
waret/istio
|
d0889b74dabea59878be27202269839789a41e61
|
[
"Apache-2.0"
] | 1
|
2020-06-29T05:12:04.000Z
|
2020-06-29T05:12:04.000Z
|
security/pkg/k8s/controller/casecret.go
|
waret/istio
|
d0889b74dabea59878be27202269839789a41e61
|
[
"Apache-2.0"
] | null | null | null |
security/pkg/k8s/controller/casecret.go
|
waret/istio
|
d0889b74dabea59878be27202269839789a41e61
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2019 Istio Authors
//
// 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 controller
import (
"context"
"time"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"istio.io/pkg/log"
)
var caSecretControllerLog = log.RegisterScope("caSecretController",
"Self-signed root cert secret controller log", 0)
// CaSecretController manages the self-signed signing CA secret.
type CaSecretController struct {
client corev1.CoreV1Interface
}
// NewCaSecretController returns a pointer to a newly constructed SecretController instance.
func NewCaSecretController(core corev1.CoreV1Interface) *CaSecretController {
cs := &CaSecretController{
client: core,
}
return cs
}
// LoadCASecretWithRetry reads CA secret with retries until timeout.
func (csc *CaSecretController) LoadCASecretWithRetry(secretName, namespace string,
retryInterval, timeout time.Duration) (*v1.Secret, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
caSecret, scrtErr := csc.client.Secrets(namespace).Get(secretName, metav1.GetOptions{})
if scrtErr != nil && !errors.IsNotFound(scrtErr) {
caSecretControllerLog.Errorf("Failed to read secret that holds CA certificate: %s. "+
"Wait until secret %s:%s can be loaded", scrtErr.Error(), namespace, secretName)
ticker := time.NewTicker(retryInterval)
for scrtErr != nil {
select {
case <-ticker.C:
if caSecret, scrtErr = csc.client.Secrets(namespace).Get(secretName, metav1.GetOptions{}); scrtErr == nil {
break
}
case <-ctx.Done():
caSecretControllerLog.Errorf("Timeout on loading CA secret %s:%s.", namespace, secretName)
ticker.Stop()
break
}
}
}
return caSecret, scrtErr
}
// UpdateCASecretWithRetry updates CA secret with retries until timeout.
func (csc *CaSecretController) UpdateCASecretWithRetry(caSecret *v1.Secret,
retryInterval, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
_, scrtErr := csc.client.Secrets(caSecret.Namespace).Update(caSecret)
if scrtErr != nil {
caSecretControllerLog.Errorf("Failed to update CA secret: %s. Wait until "+
"secret %s:%s can be updated", scrtErr.Error(), caSecret.Namespace, caSecret.Name)
ticker := time.NewTicker(retryInterval)
for scrtErr != nil {
select {
case <-ticker.C:
if caSecret, scrtErr = csc.client.Secrets(caSecret.Namespace).Update(caSecret); scrtErr == nil {
break
}
case <-ctx.Done():
caSecretControllerLog.Errorf("Timeout on updating CA secret %s:%s.",
caSecret.Namespace, caSecret.Name)
ticker.Stop()
break
}
}
}
return scrtErr
}
| 33.090909
| 111
| 0.734127
|
438b70f9b46c1d3c161522ac7b66340bf29f84dc
| 237
|
ts
|
TypeScript
|
packages/benchmarks/src/state-controller.ts
|
jamesfer/incremental
|
0e3c226910033f65b8b2dac8fc86a90b13c4d19a
|
[
"MIT"
] | null | null | null |
packages/benchmarks/src/state-controller.ts
|
jamesfer/incremental
|
0e3c226910033f65b8b2dac8fc86a90b13c4d19a
|
[
"MIT"
] | 7
|
2021-03-10T01:03:34.000Z
|
2022-02-26T20:57:28.000Z
|
packages/benchmarks/src/state-controller.ts
|
jamesfer/incremental
|
0e3c226910033f65b8b2dac8fc86a90b13c4d19a
|
[
"MIT"
] | null | null | null |
import { State } from 'tree-app-incremental-core';
export interface StateController {
setName(id: string, name: string): void;
moveChild(id: string, startIndex: number, endIndex: number): void;
overwrite(newState: State): void;
}
| 29.625
| 68
| 0.729958
|
e230b4b3836d91e0ecb2b01269cbcb86b8315960
| 2,350
|
py
|
Python
|
model.py
|
clive819/DenseNet
|
d6b067c6d068c99345da950b5a83bbaf98a804dd
|
[
"MIT"
] | null | null | null |
model.py
|
clive819/DenseNet
|
d6b067c6d068c99345da950b5a83bbaf98a804dd
|
[
"MIT"
] | null | null | null |
model.py
|
clive819/DenseNet
|
d6b067c6d068c99345da950b5a83bbaf98a804dd
|
[
"MIT"
] | null | null | null |
from config import DenseNetConfig as dnc
import torch
import torch.nn as nn
class _transitionLayer(nn.Module):
def __init__(self, inChannels):
super(_transitionLayer, self).__init__()
self.outChannels = int(inChannels * dnc.compressionRate)
self.module = nn.Sequential(
nn.GroupNorm(dnc.numGroups, inChannels),
nn.ReLU(),
nn.Conv2d(inChannels, self.outChannels, 1),
nn.AvgPool2d(2)
)
def forward(self, x):
return self.module(x)
class _convBlock(nn.Module):
def __init__(self, inChannels):
super(_convBlock, self).__init__()
self.outChannels = dnc.growthRate
self.module = nn.Sequential(
nn.GroupNorm(dnc.numGroups, inChannels),
nn.ReLU(),
nn.Conv2d(inChannels, 4 * dnc.growthRate, 1),
nn.GroupNorm(dnc.numGroups, 4 * dnc.growthRate),
nn.ReLU(),
nn.Conv2d(4 * dnc.growthRate, dnc.growthRate, 3, padding=1)
)
def forward(self, x):
return self.module(x)
class _denseBlock(nn.Module):
def __init__(self, inChannels, numBlocks):
super(_denseBlock, self).__init__()
self.outChannels = inChannels
self.layers = nn.ModuleList()
for _ in range(numBlocks):
self.layers.append(_convBlock(self.outChannels))
self.outChannels += dnc.growthRate
def forward(self, x):
features = [x]
for layer in self.layers:
features.append(layer(torch.cat(features, 1)))
return torch.cat(features, 1)
class DenseNet(nn.Module):
def __init__(self):
super(DenseNet, self).__init__()
outChannels = 64
self.input = nn.Sequential(
nn.Conv2d(3, outChannels, 7, padding=3),
nn.GroupNorm(dnc.numGroups, outChannels),
nn.ReLU(),
nn.MaxPool2d(2)
)
layers = [self.input]
for num in dnc.numBlocks:
block = _denseBlock(outChannels, num)
outChannels = block.outChannels
trans = _transitionLayer(outChannels)
outChannels = trans.outChannels
layers.append(block)
layers.append(trans)
self.module = nn.Sequential(*layers)
def forward(self, x):
return self.module(x)
| 27.011494
| 71
| 0.594468
|
20bda32868abc156b6c14235b8e42bdc0125cd93
| 390
|
cs
|
C#
|
src/SolrExpress/Search/Parameter/IQueryParameter.cs
|
LivingNaturally/solr-express
|
bf868ea89eab033dafe41d8830c396d96350e868
|
[
"MIT"
] | 73
|
2015-05-25T16:20:14.000Z
|
2021-12-13T08:12:45.000Z
|
src/SolrExpress/Search/Parameter/IQueryParameter.cs
|
LivingNaturally/solr-express
|
bf868ea89eab033dafe41d8830c396d96350e868
|
[
"MIT"
] | 623
|
2015-06-09T11:33:49.000Z
|
2020-10-06T09:31:06.000Z
|
src/SolrExpress/Search/Parameter/IQueryParameter.cs
|
LivingNaturally/solr-express
|
bf868ea89eab033dafe41d8830c396d96350e868
|
[
"MIT"
] | 33
|
2015-12-21T14:07:07.000Z
|
2021-12-24T13:09:19.000Z
|
using SolrExpress.Search.Query;
namespace SolrExpress.Search.Parameter
{
/// <summary>
/// Query parameter
/// </summary>
public interface IQueryParameter<TDocument> : ISearchParameter
where TDocument : Document
{
/// <summary>
/// Parameter to include in query
/// </summary>
SearchQuery<TDocument> Value { get; set; }
}
}
| 22.941176
| 66
| 0.607692
|
b63df5be3b9c1d69f670ee7f4ae211137ee22b6a
| 331
|
kt
|
Kotlin
|
creditcardview/src/test/java/com/umut/soysal/compose/creditcardview/StringExtensionTest.kt
|
umutsoysl/ComposeCreditCardView
|
15e18c662a661e686f92b4b90c840503ffcec47a
|
[
"Apache-2.0"
] | 13
|
2022-01-20T14:23:55.000Z
|
2022-02-17T05:22:54.000Z
|
creditcardview/src/test/java/com/umut/soysal/compose/creditcardview/StringExtensionTest.kt
|
umutsoysl/ComposeCreditCardView
|
15e18c662a661e686f92b4b90c840503ffcec47a
|
[
"Apache-2.0"
] | null | null | null |
creditcardview/src/test/java/com/umut/soysal/compose/creditcardview/StringExtensionTest.kt
|
umutsoysl/ComposeCreditCardView
|
15e18c662a661e686f92b4b90c840503ffcec47a
|
[
"Apache-2.0"
] | null | null | null |
package com.umut.soysal.compose.creditcardview
import org.junit.Test
class StringExtensionTest {
@Test
fun `when string toCreditCardFormatter is true`() {
val simpleCardFormat = "1234 5678 9124 5752"
val cardNumber = "1234567891245752"
val resultData = cardNumber.toCreditCardFormatter()
}
}
| 23.642857
| 59
| 0.70997
|
4bc5f95e564ff538948f51bf28aee86c32c80d5c
| 3,200
|
h
|
C
|
libpvkernel/src/include/pvkernel/rush/PVSourceDescription.h
|
inendi-inspector/inspector
|
9b9a00222d8a73cb0817ca56790ee9155db61cc4
|
[
"MIT"
] | null | null | null |
libpvkernel/src/include/pvkernel/rush/PVSourceDescription.h
|
inendi-inspector/inspector
|
9b9a00222d8a73cb0817ca56790ee9155db61cc4
|
[
"MIT"
] | null | null | null |
libpvkernel/src/include/pvkernel/rush/PVSourceDescription.h
|
inendi-inspector/inspector
|
9b9a00222d8a73cb0817ca56790ee9155db61cc4
|
[
"MIT"
] | null | null | null |
/* * MIT License
*
* © ESI Group, 2015
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
*
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
*
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef PVSOURCEDESCRIPTION_H_
#define PVSOURCEDESCRIPTION_H_
#include <pvkernel/rush/PVFormat.h> // for PVFormat
#include <pvkernel/rush/PVSourceCreator.h> // for PVSourceCreator_p
#include <pvkernel/rush/PVInputType.h> // for PVInputType::list_inputs, etc
#include <pvkernel/core/PVSerializedSource.h>
namespace PVRush
{
class PVSourceDescription
{
public:
PVSourceDescription() : _inputs(), _source_creator_p(), _format() {}
PVSourceDescription(PVRush::PVInputType::list_inputs inputs,
PVRush::PVSourceCreator_p source_creator_p,
PVRush::PVFormat format)
: _inputs(std::move(inputs))
, _source_creator_p(std::move(source_creator_p))
, _format(std::move(format))
{
}
explicit PVSourceDescription(PVCore::PVSerializedSource const& s)
: _source_creator_p(LIB_CLASS(PVRush::PVSourceCreator)::get().get_class_by_name(
QString::fromStdString(s.sc_name)))
, _format(QString::fromStdString(s.format_name), QString::fromStdString(s.format_path))
{
PVRush::PVInputType_p input_type_p = _source_creator_p->supported_type_lib();
for (auto const& p : s.input_desc) {
_inputs << input_type_p->load_input_from_string(p, s.input_desc.size() > 1);
}
}
bool operator==(const PVSourceDescription& other) const;
bool operator!=(const PVSourceDescription& other) const { return !operator==(other); }
void set_inputs(const PVRush::PVInputType::list_inputs inputs) { _inputs = inputs; }
void set_source_creator(PVRush::PVSourceCreator_p source_creator_p)
{
_source_creator_p = source_creator_p;
}
void set_format(PVRush::PVFormat format) { _format = format; }
const PVRush::PVInputType::list_inputs& get_inputs() const { return _inputs; }
PVRush::PVSourceCreator_p get_source_creator() const { return _source_creator_p; }
PVRush::PVFormat get_format() const { return _format; }
private:
PVRush::PVInputType::list_inputs _inputs;
PVRush::PVSourceCreator_p _source_creator_p;
PVRush::PVFormat _format;
};
} // namespace PVRush
#endif /* PVSOURCEDESCRIPTION_H_ */
| 38.095238
| 92
| 0.74625
|
b720dbccc6530f5a6a59ff24cf8e240d9967e9fe
| 13,700
|
cs
|
C#
|
CS/Properties/Settings.Designer.cs
|
Excel-projects/Script-Help
|
a3db9f3660792cc1bb1a7b777df5fd7122a91030
|
[
"MIT"
] | 50
|
2018-12-23T01:13:02.000Z
|
2022-03-27T01:09:40.000Z
|
CS/Properties/Settings.Designer.cs
|
Excel-projects/Script-Help
|
a3db9f3660792cc1bb1a7b777df5fd7122a91030
|
[
"MIT"
] | 1
|
2018-11-16T07:19:10.000Z
|
2020-09-27T23:39:04.000Z
|
CS/Properties/Settings.Designer.cs
|
Excel-projects/Script-Help
|
a3db9f3660792cc1bb1a7b777df5fd7122a91030
|
[
"MIT"
] | 13
|
2018-10-29T13:47:10.000Z
|
2021-10-01T12:14:58.000Z
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ScriptHelp.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("Anthony Duguid")]
public string App_Author {
get {
return ((string)(this["App_Author"]));
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("SkyBlue")]
public global::System.Drawing.Color Table_ColumnCleanedColour {
get {
return ((global::System.Drawing.Color)(this["Table_ColumnCleanedColour"]));
}
set {
this["Table_ColumnCleanedColour"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("tbl")]
public string Table_ColumnTableAlias {
get {
return ((string)(this["Table_ColumnTableAlias"]));
}
set {
this["Table_ColumnTableAlias"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("2")]
public int Column_TypeDate {
get {
return ((int)(this["Column_TypeDate"]));
}
set {
this["Column_TypeDate"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("dd-mmm-yyyy")]
public string Table_ColumnFormatDate {
get {
return ((string)(this["Table_ColumnFormatDate"]));
}
set {
this["Table_ColumnFormatDate"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("h:mm:ss AM/PM")]
public string Table_ColumnFormatTime {
get {
return ((string)(this["Table_ColumnFormatTime"]));
}
set {
this["Table_ColumnFormatTime"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("NULL")]
public string Table_ColumnScriptNull {
get {
return ((string)(this["Table_ColumnScriptNull"]));
}
set {
this["Table_ColumnScriptNull"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("1")]
public int Column_TypeNumeric {
get {
return ((int)(this["Column_TypeNumeric"]));
}
set {
this["Column_TypeNumeric"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("\'")]
public string Table_ColumnScriptQuote {
get {
return ((string)(this["Table_ColumnScriptQuote"]));
}
set {
this["Table_ColumnScriptQuote"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("0")]
public int Column_TypeText {
get {
return ((int)(this["Column_TypeText"]));
}
set {
this["Column_TypeText"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool Visible_grpClipboard {
get {
return ((bool)(this["Visible_grpClipboard"]));
}
set {
this["Visible_grpClipboard"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("SCRIPT")]
public string Table_ColumnName {
get {
return ((string)(this["Table_ColumnName"]));
}
set {
this["Table_ColumnName"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute(";")]
public char Table_ColumnSeparateValuesDelimiter {
get {
return ((char)(this["Table_ColumnSeparateValuesDelimiter"]));
}
set {
this["Table_ColumnSeparateValuesDelimiter"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("https://raw.githubusercontent.com/Excel-projects/Script-Help/master/publish/")]
public string App_PathDeploy {
get {
return ((string)(this["App_PathDeploy"]));
}
set {
this["App_PathDeploy"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string App_PathLocalData {
get {
return ((string)(this["App_PathLocalData"]));
}
set {
this["App_PathLocalData"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool Visible_mnuScriptType_DQL {
get {
return ((bool)(this["Visible_mnuScriptType_DQL"]));
}
set {
this["Visible_mnuScriptType_DQL"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool Visible_mnuScriptType_TSQL {
get {
return ((bool)(this["Visible_mnuScriptType_TSQL"]));
}
set {
this["Visible_mnuScriptType_TSQL"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool Visible_mnuScriptType_PLSQL {
get {
return ((bool)(this["Visible_mnuScriptType_PLSQL"]));
}
set {
this["Visible_mnuScriptType_PLSQL"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool Visible_mnuScriptType_Markdown {
get {
return ((bool)(this["Visible_mnuScriptType_Markdown"]));
}
set {
this["Visible_mnuScriptType_Markdown"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool Visible_mnuScriptType_Markup {
get {
return ((bool)(this["Visible_mnuScriptType_Markup"]));
}
set {
this["Visible_mnuScriptType_Markup"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("https://github.com/Excel-projects/Script-Help/blob/master/README.md")]
public string App_PathReadMe {
get {
return ((string)(this["App_PathReadMe"]));
}
set {
this["App_PathReadMe"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string App_PathDeployData {
get {
return ((string)(this["App_PathDeployData"]));
}
set {
this["App_PathDeployData"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("TableStyleMedium15")]
public string Table_StyleName {
get {
return ((string)(this["Table_StyleName"]));
}
set {
this["Table_StyleName"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("07/31/2017 13:05:00")]
public global::System.DateTime App_ReleaseDate {
get {
return ((global::System.DateTime)(this["App_ReleaseDate"]));
}
set {
this["App_ReleaseDate"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("https://github.com/Excel-projects/Script-Help/issues/new")]
public string App_PathNewIssue {
get {
return ((string)(this["App_PathNewIssue"]));
}
set {
this["App_PathNewIssue"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool Visible_grpAnnotation {
get {
return ((bool)(this["Visible_grpAnnotation"]));
}
set {
this["Visible_grpAnnotation"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("mm:ss.0")]
public string Table_ColumnFormatDatePaste {
get {
return ((string)(this["Table_ColumnFormatDatePaste"]));
}
set {
this["Table_ColumnFormatDatePaste"] = value;
}
}
}
}
| 39.367816
| 151
| 0.578394
|
3f971695599cc3558339a18a91317be1687045d2
| 1,588
|
php
|
PHP
|
web/app/themes/Divi/includes/builder/plugin-compat/divi-module-code-snippet.php
|
ashajida/wp_ajicom
|
1f59fe13dbc5d193b61d60fc8bc4ba00d504ca28
|
[
"MIT"
] | 1
|
2021-01-29T19:39:06.000Z
|
2021-01-29T19:39:06.000Z
|
web/app/themes/Divi/includes/builder/plugin-compat/divi-module-code-snippet.php
|
ashajida/wp_ajicom
|
1f59fe13dbc5d193b61d60fc8bc4ba00d504ca28
|
[
"MIT"
] | 87
|
2021-01-20T10:44:56.000Z
|
2021-11-02T09:22:21.000Z
|
themes/Divi/includes/builder/plugin-compat/divi-module-code-snippet.php
|
dis-moi/www.dismoi.io
|
18332c8d2c329e732399b5460c1c91a3018548d2
|
[
"MIT"
] | 2
|
2020-11-09T15:29:52.000Z
|
2022-01-10T15:11:58.000Z
|
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* Plugin compatibility for Divi Code Snippet Module
*
* @since 3.17.3
*/
class ET_Builder_Plugin_Compat_Divi_Code_Snippet_Module extends ET_Builder_Plugin_Compat_Base {
protected $posts = '';
/**
* Constructor
*/
public function __construct() {
$this->plugin_id = 'divi-module-code-snippet/divi-module-code-snippet.php';
$this->init_hooks();
}
/**
* Hook methods to WordPress
*
* @return void
*/
public function init_hooks() {
// Bail if there's no version found
if ( ! $this->get_plugin_version() ) {
return;
}
if ( function_exists( 'load_DMB_Module_Code_Snippet' ) && function_exists( 'load_db_cs_ET_Builder_Module' ) ) {
remove_action( 'wp_loaded', 'load_db_cs_ET_Builder_Module' );
remove_action( 'wp_loaded', 'load_DMB_Module_Code_Snippet' );
add_action( 'et_builder_ready', array( $this, 'et_builder_ready' ) );
add_filter( 'the_posts', array( $this, 'the_posts' ) );
}
}
/**
* Saves filter value for later use.
*
* @return array
*/
public function the_posts( $posts ) {
$this->posts = $posts;
return $posts;
}
/**
* Runs when the builder is ready.
*
* @return void
*/
public function et_builder_ready() {
load_db_cs_ET_Builder_Module();
load_DMB_Module_Code_Snippet();
$instance = et_()->array_get( ET_Builder_Module::get_modules(), 'et_pb_dmb_code_snippet', false );
if ( $instance ) {
$instance->module_used_in_post( $this->posts );
}
}
}
new ET_Builder_Plugin_Compat_Divi_Code_Snippet_Module();
| 22.055556
| 113
| 0.68136
|
9a164c2b57ca5f34431a7bb0a4ad8410b2d100c0
| 785
|
dart
|
Dart
|
lib/repository/trending_repository.dart
|
drow19/Wallpaper
|
7851c95b9a803e2b51cd75e6aee2c0c87379835c
|
[
"Apache-2.0"
] | null | null | null |
lib/repository/trending_repository.dart
|
drow19/Wallpaper
|
7851c95b9a803e2b51cd75e6aee2c0c87379835c
|
[
"Apache-2.0"
] | null | null | null |
lib/repository/trending_repository.dart
|
drow19/Wallpaper
|
7851c95b9a803e2b51cd75e6aee2c0c87379835c
|
[
"Apache-2.0"
] | null | null | null |
import 'dart:convert';
import 'package:flutterwallpaper/helper/base_url.dart';
import 'package:flutterwallpaper/model/wallpaper_model.dart';
import 'package:http/http.dart' as http;
class TrendingRepo {
Future<List<WallpaperModel>> getData(String max) async {
String _url = baseUrl + max;
final response = await http.get(_url, headers: {"Authorization": api_key});
print(_url);
if (response.statusCode == 200) {
return jsonParse(response.body);
} else {
throw Exception();
}
}
List<WallpaperModel> jsonParse(final response) {
final json = jsonDecode(response);
final data = json['photos'];
print("response data : $data");
return new List<WallpaperModel>.from(
data.map((e) => WallpaperModel.fromJson(e)));
}
}
| 25.322581
| 79
| 0.677707
|
ef8d2a84a54ccc37f82f311f84b9a24b0004f63b
| 1,065
|
h
|
C
|
leviathan/leviathan/utility/memory_leak.h
|
Stopmale/Leviathan_Project
|
247b2fa87c7e6e1238385328556b82e517b62c83
|
[
"Apache-2.0"
] | null | null | null |
leviathan/leviathan/utility/memory_leak.h
|
Stopmale/Leviathan_Project
|
247b2fa87c7e6e1238385328556b82e517b62c83
|
[
"Apache-2.0"
] | null | null | null |
leviathan/leviathan/utility/memory_leak.h
|
Stopmale/Leviathan_Project
|
247b2fa87c7e6e1238385328556b82e517b62c83
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#ifdef _MSC_VER
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifndef _CONSOLE
#include <cstdlib>
#endif
namespace Leviathan
{
class cMemoryLeack
{
public:
cMemoryLeack()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#ifdef _CONSOLE
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);
#define DEBUG_NORMALBLOCK new(_NORMAL_BLOCK, __FILE__, __LINE__)
#ifdef new
#undef new
#endif
#define new DEBUG_NORMALBLOCK
#else
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
#endif
#ifdef malloc
#undef malloc
#endif
#define malloc(s) (_malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__))
}
};
static cMemoryLeack gMemoryLeack;
}
#endif
#endif
| 20.480769
| 69
| 0.80939
|
9778400e6dd3c041536a6bcac194fc168caadc12
| 1,538
|
tsx
|
TypeScript
|
packages/cube-vue/src/icons/byted-increase.tsx
|
iq9891/icon
|
feee74568e556fb654197b62951854a2fad41f9f
|
[
"MIT"
] | null | null | null |
packages/cube-vue/src/icons/byted-increase.tsx
|
iq9891/icon
|
feee74568e556fb654197b62951854a2fad41f9f
|
[
"MIT"
] | null | null | null |
packages/cube-vue/src/icons/byted-increase.tsx
|
iq9891/icon
|
feee74568e556fb654197b62951854a2fad41f9f
|
[
"MIT"
] | 1
|
2021-10-14T01:00:08.000Z
|
2021-10-14T01:00:08.000Z
|
/** @format */
import { ISvgIconProps, IconWrapper } from '../runtime';
export default IconWrapper('byted-increase', false, (props: ISvgIconProps) => (
<svg width={props.size} height={props.size} viewBox="0 0 48 48" fill="none">
<path
d="M41 25C41 34.9411 32.9411 43 23 43C13.0589 43 5 34.9411 5 25C5 15.0589 13.0589 7 23 7"
stroke={props.colors[0]}
stroke-width={props.strokeWidth}
stroke-linecap={props.strokeLinecap}
stroke-linejoin={props.strokeLinejoin}
/>
<path
d="M12 28.5C20.5 28.5 24 28 31 19"
stroke={props.colors[0]}
stroke-width={props.strokeWidth}
stroke-linecap={props.strokeLinecap}
stroke-linejoin={props.strokeLinejoin}
/>
<path
d="M23 19H31V27"
stroke={props.colors[0]}
stroke-width={props.strokeWidth}
stroke-linecap={props.strokeLinecap}
stroke-linejoin={props.strokeLinejoin}
/>
<path
d="M31 5V9.5"
stroke={props.colors[0]}
stroke-width={props.strokeWidth}
stroke-linecap={props.strokeLinecap}
stroke-linejoin={props.strokeLinejoin}
/>
<path
d="M43.5 17L39 17"
stroke={props.colors[0]}
stroke-width={props.strokeWidth}
stroke-linecap={props.strokeLinecap}
stroke-linejoin={props.strokeLinejoin}
/>
<path
d="M40.8892 7L37.0001 10.8891"
stroke={props.colors[0]}
stroke-width={props.strokeWidth}
stroke-linecap={props.strokeLinecap}
stroke-linejoin={props.strokeLinejoin}
/>
</svg>
));
| 30.156863
| 95
| 0.637841
|
b0b5dcd5a5d7039e3099557dd21a9171aa6ed377
| 416
|
swift
|
Swift
|
Sources/Card/ConfirmPaymentSourceResponse.swift
|
turlodales/iOS-SDK-1
|
f772c94e1ce9db4a8adb65c6e4a6772dcdcc0e08
|
[
"MIT"
] | 16
|
2021-08-03T15:06:31.000Z
|
2022-03-09T01:46:02.000Z
|
Sources/Card/ConfirmPaymentSourceResponse.swift
|
turlodales/iOS-SDK-1
|
f772c94e1ce9db4a8adb65c6e4a6772dcdcc0e08
|
[
"MIT"
] | 20
|
2021-08-03T15:51:56.000Z
|
2022-03-24T21:26:28.000Z
|
Sources/Card/ConfirmPaymentSourceResponse.swift
|
turlodales/iOS-SDK-1
|
f772c94e1ce9db4a8adb65c6e4a6772dcdcc0e08
|
[
"MIT"
] | 5
|
2021-10-21T21:18:28.000Z
|
2022-03-07T20:13:53.000Z
|
// swiftlint:disable space_after_main_type
import Foundation
#if canImport(PaymentsCore)
import PaymentsCore
#endif
struct ConfirmPaymentSourceResponse: Decodable {
let id: String
let paymentSource: PaymentSource
}
struct PaymentSource: Decodable {
let card: PaymentSource.Card
struct Card: Decodable {
let lastDigits: String?
let brand: String?
let type: String?
}
}
| 18.909091
| 48
| 0.71875
|
69ab62dd06d9d6be8b1bef076ee883882634bdf9
| 678
|
swift
|
Swift
|
Weather-For-Three-Days-Reactor/Cities/CitiesDataSource.swift
|
menabebawy/-Weather-For-Three-Days-Reactor
|
5036dec5dcbaeb7d1aaf9af7f4b6e9ba7fc84bd6
|
[
"MIT"
] | null | null | null |
Weather-For-Three-Days-Reactor/Cities/CitiesDataSource.swift
|
menabebawy/-Weather-For-Three-Days-Reactor
|
5036dec5dcbaeb7d1aaf9af7f4b6e9ba7fc84bd6
|
[
"MIT"
] | null | null | null |
Weather-For-Three-Days-Reactor/Cities/CitiesDataSource.swift
|
menabebawy/-Weather-For-Three-Days-Reactor
|
5036dec5dcbaeb7d1aaf9af7f4b6e9ba7fc84bd6
|
[
"MIT"
] | 1
|
2020-03-27T16:25:09.000Z
|
2020-03-27T16:25:09.000Z
|
//
// CitiesDataSource.swift
// Weather-For-Three-Days-Reactor
//
// Created by Mena Bebawy on 3/18/20.
// Copyright © 2020 Mena. All rights reserved.
//
import RxDataSources
final class CitiesDataSource: RxTableViewSectionedReloadDataSource<CitiesSection> {
init() {
super.init(configureCell: { (_, tableView, indexPath, city) -> UITableViewCell in
guard let cell = tableView.dequeueReusableCell(
withIdentifier: CityTableViewCell.identifier, for: indexPath) as? CityTableViewCell else {
return UITableViewCell()
}
cell.configure(city: city)
return cell
})
}
}
| 27.12
| 106
| 0.641593
|
1aaebc56b865f8e05ef858be750a0a85b74fc987
| 7,723
|
cs
|
C#
|
src/Networking/MultiplayerManager.cs
|
mahgo/CSM
|
c779a0468d4b5e288dcf111efa0414a8553a9638
|
[
"MIT"
] | 241
|
2020-06-03T01:07:58.000Z
|
2022-03-31T21:28:54.000Z
|
src/Networking/MultiplayerManager.cs
|
mahgo/CSM
|
c779a0468d4b5e288dcf111efa0414a8553a9638
|
[
"MIT"
] | 78
|
2020-06-02T11:10:46.000Z
|
2022-03-21T13:24:24.000Z
|
src/Networking/MultiplayerManager.cs
|
mahgo/CSM
|
c779a0468d4b5e288dcf111efa0414a8553a9638
|
[
"MIT"
] | 68
|
2020-07-13T22:25:14.000Z
|
2022-03-17T22:48:03.000Z
|
using ColossalFramework.Threading;
using ColossalFramework.UI;
using CSM.Networking.Config;
using CSM.Panels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using CSM.Networking.Status;
namespace CSM.Networking
{
public class MultiplayerManager
{
/// <summary>
/// The current player list as server or client.
/// </summary>
public HashSet<string> PlayerList { get; } = new HashSet<string>();
/// <summary>
/// The current role of the game.
/// </summary>
public MultiplayerRole CurrentRole { get; private set; }
/// <summary>
/// The current game server (Use only when this game acts as server!)
/// </summary>
public Server CurrentServer { get; } = new Server();
/// <summary>
/// The current client (Use only when this game acts as client!)
/// </summary>
public Client CurrentClient { get; } = new Client();
public bool GameBlocked { get; private set; } = false;
public void ProcessEvents()
{
switch (CurrentRole)
{
case MultiplayerRole.Client:
CurrentClient.ProcessEvents();
break;
case MultiplayerRole.Server:
CurrentServer.ProcessEvents();
break;
case MultiplayerRole.None:
if (CurrentClient.Status == Status.ClientStatus.Connecting)
{
CurrentClient.ProcessEvents();
}
break;
}
}
/// <summary>
/// Starts the client and tries to connect to the given server.
/// </summary>
/// <param name="ipAddress">The server ip address.</param>
/// <param name="port">The server port.</param>
/// <param name="username">The username to connect with.</param>
/// <param name="password">The password to use.</param>
/// <param name="callback">This callback returns if the connection was successful.</param>
public void ConnectToServer(string ipAddress, int port, string username, string password, Action<bool> callback)
{
if (CurrentRole == MultiplayerRole.Server)
{
callback.Invoke(false);
return;
}
new Thread(() =>
{
// Try connect
bool isConnected = CurrentClient.Connect(new ClientConfig(ipAddress, port, username, password));
// Set the current role
CurrentRole = isConnected ? MultiplayerRole.Client : MultiplayerRole.None;
// Return the status
callback.Invoke(isConnected);
}).Start();
}
/// <summary>
/// Starts the game server on the given port.
/// </summary>
/// <param name="config">The ServerConfig</param>
/// <param name="callback">This callback returns if the server was started successfully.</param>
public void StartGameServer(ServerConfig config, Action<bool> callback)
{
if (CurrentRole == MultiplayerRole.Client)
{
callback.Invoke(false);
return;
}
new Thread(() =>
{
// Create the server and start it
bool isConnected = CurrentServer.StartServer(config);
// Set the current role
CurrentRole = isConnected ? MultiplayerRole.Server : MultiplayerRole.None;
callback.Invoke(isConnected);
}).Start();
}
/// <summary>
/// Stops the client or server, depending on the current role
/// </summary>
public void StopEverything()
{
switch (CurrentRole)
{
case MultiplayerRole.Client:
CurrentClient.Disconnect();
ChatLogPanel.PrintGameMessage("Disconnected from server.");
break;
case MultiplayerRole.Server:
CurrentServer.StopServer();
ChatLogPanel.PrintGameMessage("Server stopped.");
break;
}
CurrentRole = MultiplayerRole.None;
}
public bool IsConnected()
{
return CurrentRole == MultiplayerRole.Server || (CurrentRole == MultiplayerRole.Client &&
CurrentClient.Status == ClientStatus.Connected);
}
public void BlockGameReSync()
{
BlockGame(true, CurrentClient.Config.Username, false);
}
public void BlockGame(string JoiningUsername)
{
BlockGame(false, JoiningUsername, false);
}
public void BlockGameFirstJoin()
{
BlockGame(false, CurrentClient.Config.Username, true);
}
private void BlockGame(bool IsSelf, string JoiningUsername, bool IsFirstJoin)
{
if (GameBlocked)
return;
QueueMainThread(() =>
{
ClientJoinPanel clientJoinPanel = UIView.GetAView().FindUIComponent<ClientJoinPanel>("ClientJoinPanel");
if (clientJoinPanel == null)
{
clientJoinPanel = (ClientJoinPanel)UIView.GetAView().AddUIComponent(typeof(ClientJoinPanel));
}
clientJoinPanel.IsSelf = IsSelf;
clientJoinPanel.JoiningUsername = JoiningUsername;
clientJoinPanel.IsFirstJoin = IsFirstJoin;
clientJoinPanel.ShowPanel();
});
if (!IsFirstJoin)
GameBlocked = true;
}
public void UnblockGame(bool RemoveFromUI = false)
{
if (!GameBlocked)
return;
QueueMainThread(() =>
{
ClientJoinPanel clientJoinPanel = UIView.GetAView().FindUIComponent<ClientJoinPanel>("ClientJoinPanel");
if (clientJoinPanel != null)
{
clientJoinPanel.HidePanel(RemoveFromUI);
}
});
GameBlocked = false;
}
private static void QueueMainThread(Action action)
{
if (Dispatcher.currentSafe == ThreadHelper.dispatcher)
{
action();
}
else
{
ThreadHelper.dispatcher.Dispatch(action);
}
}
private static MultiplayerManager _multiplayerInstance;
public static MultiplayerManager Instance => _multiplayerInstance ?? (_multiplayerInstance = new MultiplayerManager());
}
/// <summary>
/// What state our game is in.
/// </summary>
public enum MultiplayerRole
{
/// <summary>
/// The game is not connected to a server acting
/// as a server. In this state we leave all game mechanics
/// alone.
/// </summary>
None,
/// <summary>
/// The game is connect to a server and must broadcast
/// it's update to the server and update internal values
/// from the server.
/// </summary>
Client,
/// <summary>
/// The game is acting as a server, it will send out updates to all connected
/// clients and receive information about the game from the clients.
/// </summary>
Server
}
}
| 33.288793
| 127
| 0.531141
|
8de6bf4426fdbf14abfc9681ef917eae79037c36
| 2,813
|
js
|
JavaScript
|
src/odata-client/sfo-data-service/EmployeeProfileSectionConfigRequestBuilder.js
|
robypag/sdk-gen-sfsf
|
ce9b613ee3e85dd8ed4e42ffe200df1a2decf835
|
[
"MIT"
] | null | null | null |
src/odata-client/sfo-data-service/EmployeeProfileSectionConfigRequestBuilder.js
|
robypag/sdk-gen-sfsf
|
ce9b613ee3e85dd8ed4e42ffe200df1a2decf835
|
[
"MIT"
] | null | null | null |
src/odata-client/sfo-data-service/EmployeeProfileSectionConfigRequestBuilder.js
|
robypag/sdk-gen-sfsf
|
ce9b613ee3e85dd8ed4e42ffe200df1a2decf835
|
[
"MIT"
] | null | null | null |
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
/*
* Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved.
*
* This is a generated file powered by the SAP Cloud SDK for JavaScript.
*/
var core_1 = require("@sap-cloud-sdk/core");
var EmployeeProfileSectionConfig_1 = require("./EmployeeProfileSectionConfig");
/**
* Request builder class for operations supported on the [[EmployeeProfileSectionConfig]] entity.
*/
var EmployeeProfileSectionConfigRequestBuilder = /** @class */ (function (_super) {
__extends(EmployeeProfileSectionConfigRequestBuilder, _super);
function EmployeeProfileSectionConfigRequestBuilder() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Returns a request builder for retrieving one `EmployeeProfileSectionConfig` entity based on its keys.
* @param employeeProfilePageConfigCode Key property. See [[EmployeeProfileSectionConfig.employeeProfilePageConfigCode]].
* @param code Key property. See [[EmployeeProfileSectionConfig.code]].
* @returns A request builder for creating requests to retrieve one `EmployeeProfileSectionConfig` entity based on its keys.
*/
EmployeeProfileSectionConfigRequestBuilder.prototype.getByKey = function (employeeProfilePageConfigCode, code) {
return new core_1.GetByKeyRequestBuilder(EmployeeProfileSectionConfig_1.EmployeeProfileSectionConfig, {
EmployeeProfilePageConfig_code: employeeProfilePageConfigCode,
code: code
});
};
/**
* Returns a request builder for querying all `EmployeeProfileSectionConfig` entities.
* @returns A request builder for creating requests to retrieve all `EmployeeProfileSectionConfig` entities.
*/
EmployeeProfileSectionConfigRequestBuilder.prototype.getAll = function () {
return new core_1.GetAllRequestBuilder(EmployeeProfileSectionConfig_1.EmployeeProfileSectionConfig);
};
return EmployeeProfileSectionConfigRequestBuilder;
}(core_1.RequestBuilder));
exports.EmployeeProfileSectionConfigRequestBuilder = EmployeeProfileSectionConfigRequestBuilder;
//# sourceMappingURL=EmployeeProfileSectionConfigRequestBuilder.js.map
| 53.075472
| 128
| 0.722005
|
4394c87d163a4cf4cc483694c6acc4df4626b0ad
| 6,573
|
ts
|
TypeScript
|
ts-demos/src/lesson-03/calculator.ts
|
csdoker/typescript-learning
|
e00cbe864817c83cff3dba2ceeebd9f3d8b8481e
|
[
"MIT"
] | null | null | null |
ts-demos/src/lesson-03/calculator.ts
|
csdoker/typescript-learning
|
e00cbe864817c83cff3dba2ceeebd9f3d8b8481e
|
[
"MIT"
] | null | null | null |
ts-demos/src/lesson-03/calculator.ts
|
csdoker/typescript-learning
|
e00cbe864817c83cff3dba2ceeebd9f3d8b8481e
|
[
"MIT"
] | null | null | null |
{
class Calculator {
public n1: string = ''
public n2: string = ''
public operator: string = ''
public result: string = ''
public span: HTMLSpanElement
public container: HTMLDivElement
public textLists: Array<Array<string | number>> = [
['Clear', '÷'],
[7, 8, 9, '×'],
[4, 5, 6, '-'],
[1, 2, 3, '+'],
[0, '.', '='],
]
constructor() {
this.createContainer()
this.createElements()
this.createButtons()
this.bindEvents()
}
createContainer() {
let calc = document.createElement('div')
calc.classList.add('calc')
document.body.appendChild(calc)
this.container = calc
}
createElements() {
let output = document.createElement('div')
output.classList.add('output')
let span = document.createElement('span')
output.appendChild(span)
span.textContent = '0'
this.span = span
this.container.appendChild(output)
}
createButtons() {
this.textLists.forEach((textList: Array<number | string>) => {
let div = document.createElement('div')
div.classList.add('row')
textList.forEach((text: number | string) => {
this.createButton(text, div, `text-${text}`)
})
this.container.appendChild(div)
})
}
bindEvents() {
this.container.addEventListener('click', (event) => {
if (event.target instanceof HTMLButtonElement) {
const text = event.target.textContent
this.updateNumbersOrOperator(text)
}
})
}
updateNumbersOrOperator(text: string) {
if ('0123456789.'.indexOf(text) >= 0) {
this.updateNumbers(text)
} else if ('+-×÷'.indexOf(text) >= 0) {
this.updateOperator(text)
} else if ('='.indexOf(text) >= 0) {
this.updateResult()
} else if (text === 'Clear') {
this.clearResult()
}
console.log(this.n1, this.operator, this.n2)
}
updateNumbers(text: string) {
if (this.operator) {
this.n2 += text
this.span.textContent = this.n2
} else {
this.result = ''
this.n1 += text
this.span.textContent = this.n1
}
}
updateOperator(text: string) {
if (this.result) {
this.n1 = this.result
this.result = ''
}
this.operator = text
}
updateResult() {
this.result = this.removeZero(
this.getResult(this.n1, this.n2, this.operator)
)
this.span.textContent = this.result
this.n1 = ''
this.n2 = ''
this.operator = ''
}
clearResult() {
this.n1 = ''
this.n2 = ''
this.operator = ''
this.result = ''
this.span.textContent = '0'
}
removeZero(string: string) {
return string.replace(/.0+$/g, '').replace(/\.0+e/, 'e')
}
getResult(n1: string, n2: string, operator: string): string {
let numberN1: number = parseFloat(n1)
let numberN2: number = parseFloat(n2)
if (operator === '+') {
return (numberN1 + numberN2).toPrecision(12)
} else if (operator === '-') {
return (numberN1 - numberN2).toPrecision(12)
} else if (operator === '×') {
return (numberN1 * numberN2).toPrecision(12)
} else if (operator === '÷') {
if (numberN2 === 0) {
return '不是数字'
} else {
return (numberN1 / numberN2).toPrecision(12)
}
}
}
createButton(
text: string | number,
container: HTMLElement,
className?: string
) {
let button = document.createElement('button')
button.textContent = text.toString()
className && button.classList.add(className)
container.appendChild(button)
}
}
new Calculator()
}
// {
// //初始化数据
// let n1: string = '';
// let n2: string = '';
// let operator: string = '';
// let result: string = '';
// //创建容器
// let calc = document.createElement('div');
// calc.classList.add('calc');
// document.body.appendChild(calc);
// // 创建界面
// let output = document.createElement('div');
// output.classList.add('output');
// let span = document.createElement('span');
// output.appendChild(span);
// span.textContent = '0';
// calc.appendChild(output);
// // 定义getResult
// let getResult = (n1: string, n2: string, operator: string): string => {
// let numberN1: number = parseInt(n1);
// let numberN2: number = parseInt(n2);
// if (operator === '+') {
// return (numberN1 + numberN2).toString();
// } else if (operator === '-') {
// return (numberN1 - numberN2).toString();
// } else if (operator === '×') {
// return (numberN1 * numberN2).toString();
// } else if (operator === '÷') {
// return (numberN1 / numberN2).toString();
// }
// };
// //添加事件监听
// calc.addEventListener('click', event => {
// if (event.target instanceof HTMLButtonElement) {
// const text = event.target.textContent;
// if ('0123456789'.indexOf(text) >= 0) {
// if (operator) {
// n2 += text;
// span.textContent = n2;
// } else {
// result = '';
// n1 += text;
// span.textContent = n1;
// }
// } else if ('+-×÷'.indexOf(text) >= 0) {
// if (result) {
// n1 = result;
// result = '';
// }
// operator = text;
// } else if ('='.indexOf(text) >= 0) {
// result = getResult(n1, n2, operator);
// span.textContent = result;
// n1 = '';
// n2 = '';
// operator = '';
// } else {
// console.log('不晓得');
// }
// console.log(n1, operator, n2);
// }
// });
// //定义createButton
// let createButton = (text: string | number, container: HTMLElement, className?: string) => {
// let button = document.createElement('button');
// button.textContent = text.toString();
// className && button.classList.add(className);
// container.appendChild(button);
// };
// // 初始化按钮
// let textLists: Array<Array<string | number>> = [
// ['Clear', '÷'],
// [7, 8, 9, '×'],
// [4, 5, 6, '-'],
// [1, 2, 3, '+'],
// [0, '.', '='],
// ];
// // 循环创建按钮
// textLists.forEach((textList: Array<number | string>) => {
// let div = document.createElement('div');
// div.classList.add('row');
// textList.forEach((text: number | string) => {
// createButton(text, div, `text-${text}`);
// });
// calc.appendChild(div);
// });
// }
| 28.955947
| 96
| 0.526548
|
d053cde7f47f41ecae161805137b82bd4fdc4c9a
| 1,439
|
cpp
|
C++
|
tests/stopwatch_test.cpp
|
cameronbroe/libstopwatch
|
e050a2f20caf66d18c9473d2a31f501e783ab679
|
[
"MIT"
] | null | null | null |
tests/stopwatch_test.cpp
|
cameronbroe/libstopwatch
|
e050a2f20caf66d18c9473d2a31f501e783ab679
|
[
"MIT"
] | null | null | null |
tests/stopwatch_test.cpp
|
cameronbroe/libstopwatch
|
e050a2f20caf66d18c9473d2a31f501e783ab679
|
[
"MIT"
] | null | null | null |
#include <catch2/catch.hpp>
#include <iostream>
#include "stopwatch.h"
TEST_CASE("Testing single task stopwatch", "[multi-file:stopwatch]") {
stopwatch::Stopwatch stopwatch;
SECTION("should execute a task at 5 ticks") {
bool five_ticks_ran = false;
auto five_ticks = [&five_ticks_ran]() {
five_ticks_ran = true;
};
stopwatch.add_single_task(5, five_ticks);
stopwatch.start();
std::this_thread::sleep_for(std::chrono::seconds(6));
stopwatch.stop();
REQUIRE(five_ticks_ran);
}
SECTION("should execute a task at 10 ticks") {
bool ten_ticks_ran = false;
auto ten_ticks = [&ten_ticks_ran]() {
ten_ticks_ran = true;
};
stopwatch.add_single_task(10, ten_ticks);
stopwatch.start();
std::this_thread::sleep_for(std::chrono::seconds(11));
stopwatch.stop();
REQUIRE(ten_ticks_ran);
}
}
TEST_CASE("Testing recurring task stopwatch", "[multi-file:stopwatch]") {
stopwatch::Stopwatch stopwatch;
SECTION("should execute 5 times in 5 ticks") {
int tick_count = 0;
auto increment_tick = [&tick_count]() {
tick_count++;
};
stopwatch.add_recurring_task(1, increment_tick);
stopwatch.start();
std::this_thread::sleep_for(std::chrono::seconds(5));
stopwatch.stop();
REQUIRE(tick_count == 5);
}
}
| 30.617021
| 73
| 0.608756
|
83478c292b59bef22761d09bd853c4a74f017a74
| 53,028
|
asm
|
Assembly
|
ls.asm
|
brian19991119/changbri_project4_frq
|
f75cdb1a35fdf98800b1aa7c269c23aa41b26ff5
|
[
"MIT-0"
] | null | null | null |
ls.asm
|
brian19991119/changbri_project4_frq
|
f75cdb1a35fdf98800b1aa7c269c23aa41b26ff5
|
[
"MIT-0"
] | null | null | null |
ls.asm
|
brian19991119/changbri_project4_frq
|
f75cdb1a35fdf98800b1aa7c269c23aa41b26ff5
|
[
"MIT-0"
] | null | null | null |
_ls: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
close(fd);
}
int
main(int argc, char *argv[])
{
0: 8d 4c 24 04 lea 0x4(%esp),%ecx
4: 83 e4 f0 and $0xfffffff0,%esp
7: ff 71 fc pushl -0x4(%ecx)
a: 55 push %ebp
b: 89 e5 mov %esp,%ebp
d: 56 push %esi
e: 53 push %ebx
f: 51 push %ecx
10: 83 ec 0c sub $0xc,%esp
13: 8b 01 mov (%ecx),%eax
15: 8b 51 04 mov 0x4(%ecx),%edx
int i;
if(argc < 2){
18: 83 f8 01 cmp $0x1,%eax
1b: 7e 24 jle 41 <main+0x41>
1d: 8d 5a 04 lea 0x4(%edx),%ebx
20: 8d 34 82 lea (%edx,%eax,4),%esi
23: 90 nop
24: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
ls(".");
exit();
}
for(i=1; i<argc; i++)
ls(argv[i]);
28: 83 ec 0c sub $0xc,%esp
2b: ff 33 pushl (%ebx)
2d: 83 c3 04 add $0x4,%ebx
30: e8 cb 00 00 00 call 100 <ls>
for(i=1; i<argc; i++)
35: 83 c4 10 add $0x10,%esp
38: 39 f3 cmp %esi,%ebx
3a: 75 ec jne 28 <main+0x28>
exit();
3c: e8 81 05 00 00 call 5c2 <exit>
ls(".");
41: 83 ec 0c sub $0xc,%esp
44: 68 c0 0a 00 00 push $0xac0
49: e8 b2 00 00 00 call 100 <ls>
exit();
4e: e8 6f 05 00 00 call 5c2 <exit>
53: 66 90 xchg %ax,%ax
55: 66 90 xchg %ax,%ax
57: 66 90 xchg %ax,%ax
59: 66 90 xchg %ax,%ax
5b: 66 90 xchg %ax,%ax
5d: 66 90 xchg %ax,%ax
5f: 90 nop
00000060 <fmtname>:
{
60: 55 push %ebp
61: 89 e5 mov %esp,%ebp
63: 56 push %esi
64: 53 push %ebx
65: 8b 5d 08 mov 0x8(%ebp),%ebx
for(p=path+strlen(path); p >= path && *p != '/'; p--)
68: 83 ec 0c sub $0xc,%esp
6b: 53 push %ebx
6c: e8 7f 03 00 00 call 3f0 <strlen>
71: 83 c4 10 add $0x10,%esp
74: 01 d8 add %ebx,%eax
76: 73 0f jae 87 <fmtname+0x27>
78: eb 12 jmp 8c <fmtname+0x2c>
7a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
80: 83 e8 01 sub $0x1,%eax
83: 39 c3 cmp %eax,%ebx
85: 77 05 ja 8c <fmtname+0x2c>
87: 80 38 2f cmpb $0x2f,(%eax)
8a: 75 f4 jne 80 <fmtname+0x20>
p++;
8c: 8d 58 01 lea 0x1(%eax),%ebx
if(strlen(p) >= DIRSIZ)
8f: 83 ec 0c sub $0xc,%esp
92: 53 push %ebx
93: e8 58 03 00 00 call 3f0 <strlen>
98: 83 c4 10 add $0x10,%esp
9b: 83 f8 0d cmp $0xd,%eax
9e: 77 4a ja ea <fmtname+0x8a>
memmove(buf, p, strlen(p));
a0: 83 ec 0c sub $0xc,%esp
a3: 53 push %ebx
a4: e8 47 03 00 00 call 3f0 <strlen>
a9: 83 c4 0c add $0xc,%esp
ac: 50 push %eax
ad: 53 push %ebx
ae: 68 4c 0e 00 00 push $0xe4c
b3: e8 d8 04 00 00 call 590 <memmove>
memset(buf+strlen(p), ' ', DIRSIZ-strlen(p));
b8: 89 1c 24 mov %ebx,(%esp)
bb: e8 30 03 00 00 call 3f0 <strlen>
c0: 89 1c 24 mov %ebx,(%esp)
c3: 89 c6 mov %eax,%esi
return buf;
c5: bb 4c 0e 00 00 mov $0xe4c,%ebx
memset(buf+strlen(p), ' ', DIRSIZ-strlen(p));
ca: e8 21 03 00 00 call 3f0 <strlen>
cf: ba 0e 00 00 00 mov $0xe,%edx
d4: 83 c4 0c add $0xc,%esp
d7: 05 4c 0e 00 00 add $0xe4c,%eax
dc: 29 f2 sub %esi,%edx
de: 52 push %edx
df: 6a 20 push $0x20
e1: 50 push %eax
e2: e8 39 03 00 00 call 420 <memset>
return buf;
e7: 83 c4 10 add $0x10,%esp
}
ea: 8d 65 f8 lea -0x8(%ebp),%esp
ed: 89 d8 mov %ebx,%eax
ef: 5b pop %ebx
f0: 5e pop %esi
f1: 5d pop %ebp
f2: c3 ret
f3: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000100 <ls>:
{
100: 55 push %ebp
101: 89 e5 mov %esp,%ebp
103: 57 push %edi
104: 56 push %esi
105: 53 push %ebx
106: 81 ec 64 02 00 00 sub $0x264,%esp
10c: 8b 7d 08 mov 0x8(%ebp),%edi
if((fd = open(path, 0)) < 0){
10f: 6a 00 push $0x0
111: 57 push %edi
112: e8 eb 04 00 00 call 602 <open>
117: 83 c4 10 add $0x10,%esp
11a: 85 c0 test %eax,%eax
11c: 78 52 js 170 <ls+0x70>
if(fstat(fd, &st) < 0){
11e: 8d b5 d4 fd ff ff lea -0x22c(%ebp),%esi
124: 83 ec 08 sub $0x8,%esp
127: 89 c3 mov %eax,%ebx
129: 56 push %esi
12a: 50 push %eax
12b: e8 ea 04 00 00 call 61a <fstat>
130: 83 c4 10 add $0x10,%esp
133: 85 c0 test %eax,%eax
135: 0f 88 c5 00 00 00 js 200 <ls+0x100>
switch(st.type){
13b: 0f b7 85 d4 fd ff ff movzwl -0x22c(%ebp),%eax
142: 66 83 f8 01 cmp $0x1,%ax
146: 0f 84 84 00 00 00 je 1d0 <ls+0xd0>
14c: 66 83 f8 02 cmp $0x2,%ax
150: 74 3e je 190 <ls+0x90>
close(fd);
152: 83 ec 0c sub $0xc,%esp
155: 53 push %ebx
156: e8 8f 04 00 00 call 5ea <close>
15b: 83 c4 10 add $0x10,%esp
}
15e: 8d 65 f4 lea -0xc(%ebp),%esp
161: 5b pop %ebx
162: 5e pop %esi
163: 5f pop %edi
164: 5d pop %ebp
165: c3 ret
166: 8d 76 00 lea 0x0(%esi),%esi
169: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
printf(2, "ls: cannot open %s\n", path);
170: 83 ec 04 sub $0x4,%esp
173: 57 push %edi
174: 68 78 0a 00 00 push $0xa78
179: 6a 02 push $0x2
17b: e8 a0 05 00 00 call 720 <printf>
return;
180: 83 c4 10 add $0x10,%esp
}
183: 8d 65 f4 lea -0xc(%ebp),%esp
186: 5b pop %ebx
187: 5e pop %esi
188: 5f pop %edi
189: 5d pop %ebp
18a: c3 ret
18b: 90 nop
18c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
printf(1, "%s %d %d %d\n", fmtname(path), st.type, st.ino, st.size);
190: 83 ec 0c sub $0xc,%esp
193: 8b 95 e4 fd ff ff mov -0x21c(%ebp),%edx
199: 8b b5 dc fd ff ff mov -0x224(%ebp),%esi
19f: 57 push %edi
1a0: 89 95 b4 fd ff ff mov %edx,-0x24c(%ebp)
1a6: e8 b5 fe ff ff call 60 <fmtname>
1ab: 8b 95 b4 fd ff ff mov -0x24c(%ebp),%edx
1b1: 59 pop %ecx
1b2: 5f pop %edi
1b3: 52 push %edx
1b4: 56 push %esi
1b5: 6a 02 push $0x2
1b7: 50 push %eax
1b8: 68 a0 0a 00 00 push $0xaa0
1bd: 6a 01 push $0x1
1bf: e8 5c 05 00 00 call 720 <printf>
break;
1c4: 83 c4 20 add $0x20,%esp
1c7: eb 89 jmp 152 <ls+0x52>
1c9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf){
1d0: 83 ec 0c sub $0xc,%esp
1d3: 57 push %edi
1d4: e8 17 02 00 00 call 3f0 <strlen>
1d9: 83 c0 10 add $0x10,%eax
1dc: 83 c4 10 add $0x10,%esp
1df: 3d 00 02 00 00 cmp $0x200,%eax
1e4: 76 42 jbe 228 <ls+0x128>
printf(1, "ls: path too long\n");
1e6: 83 ec 08 sub $0x8,%esp
1e9: 68 ad 0a 00 00 push $0xaad
1ee: 6a 01 push $0x1
1f0: e8 2b 05 00 00 call 720 <printf>
break;
1f5: 83 c4 10 add $0x10,%esp
1f8: e9 55 ff ff ff jmp 152 <ls+0x52>
1fd: 8d 76 00 lea 0x0(%esi),%esi
printf(2, "ls: cannot stat %s\n", path);
200: 83 ec 04 sub $0x4,%esp
203: 57 push %edi
204: 68 8c 0a 00 00 push $0xa8c
209: 6a 02 push $0x2
20b: e8 10 05 00 00 call 720 <printf>
close(fd);
210: 89 1c 24 mov %ebx,(%esp)
213: e8 d2 03 00 00 call 5ea <close>
return;
218: 83 c4 10 add $0x10,%esp
}
21b: 8d 65 f4 lea -0xc(%ebp),%esp
21e: 5b pop %ebx
21f: 5e pop %esi
220: 5f pop %edi
221: 5d pop %ebp
222: c3 ret
223: 90 nop
224: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
strcpy(buf, path);
228: 83 ec 08 sub $0x8,%esp
22b: 57 push %edi
22c: 8d bd e8 fd ff ff lea -0x218(%ebp),%edi
232: 57 push %edi
233: e8 38 01 00 00 call 370 <strcpy>
p = buf+strlen(buf);
238: 89 3c 24 mov %edi,(%esp)
23b: e8 b0 01 00 00 call 3f0 <strlen>
240: 01 f8 add %edi,%eax
while(read(fd, &de, sizeof(de)) == sizeof(de)){
242: 83 c4 10 add $0x10,%esp
*p++ = '/';
245: 8d 48 01 lea 0x1(%eax),%ecx
p = buf+strlen(buf);
248: 89 85 a8 fd ff ff mov %eax,-0x258(%ebp)
*p++ = '/';
24e: c6 00 2f movb $0x2f,(%eax)
251: 89 8d a4 fd ff ff mov %ecx,-0x25c(%ebp)
257: 89 f6 mov %esi,%esi
259: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
while(read(fd, &de, sizeof(de)) == sizeof(de)){
260: 8d 85 c4 fd ff ff lea -0x23c(%ebp),%eax
266: 83 ec 04 sub $0x4,%esp
269: 6a 10 push $0x10
26b: 50 push %eax
26c: 53 push %ebx
26d: e8 68 03 00 00 call 5da <read>
272: 83 c4 10 add $0x10,%esp
275: 83 f8 10 cmp $0x10,%eax
278: 0f 85 d4 fe ff ff jne 152 <ls+0x52>
if(de.inum == 0)
27e: 66 83 bd c4 fd ff ff cmpw $0x0,-0x23c(%ebp)
285: 00
286: 74 d8 je 260 <ls+0x160>
memmove(p, de.name, DIRSIZ);
288: 8d 85 c6 fd ff ff lea -0x23a(%ebp),%eax
28e: 83 ec 04 sub $0x4,%esp
291: 6a 0e push $0xe
293: 50 push %eax
294: ff b5 a4 fd ff ff pushl -0x25c(%ebp)
29a: e8 f1 02 00 00 call 590 <memmove>
p[DIRSIZ] = 0;
29f: 8b 85 a8 fd ff ff mov -0x258(%ebp),%eax
2a5: c6 40 0f 00 movb $0x0,0xf(%eax)
if(stat(buf, &st) < 0){
2a9: 58 pop %eax
2aa: 5a pop %edx
2ab: 56 push %esi
2ac: 57 push %edi
2ad: e8 4e 02 00 00 call 500 <stat>
2b2: 83 c4 10 add $0x10,%esp
2b5: 85 c0 test %eax,%eax
2b7: 78 5f js 318 <ls+0x218>
printf(1, "%s %d %d %d\n", fmtname(buf), st.type, st.ino, st.size);
2b9: 0f bf 85 d4 fd ff ff movswl -0x22c(%ebp),%eax
2c0: 83 ec 0c sub $0xc,%esp
2c3: 8b 8d e4 fd ff ff mov -0x21c(%ebp),%ecx
2c9: 8b 95 dc fd ff ff mov -0x224(%ebp),%edx
2cf: 57 push %edi
2d0: 89 8d ac fd ff ff mov %ecx,-0x254(%ebp)
2d6: 89 95 b0 fd ff ff mov %edx,-0x250(%ebp)
2dc: 89 85 b4 fd ff ff mov %eax,-0x24c(%ebp)
2e2: e8 79 fd ff ff call 60 <fmtname>
2e7: 5a pop %edx
2e8: 8b 95 b0 fd ff ff mov -0x250(%ebp),%edx
2ee: 59 pop %ecx
2ef: 8b 8d ac fd ff ff mov -0x254(%ebp),%ecx
2f5: 51 push %ecx
2f6: 52 push %edx
2f7: ff b5 b4 fd ff ff pushl -0x24c(%ebp)
2fd: 50 push %eax
2fe: 68 a0 0a 00 00 push $0xaa0
303: 6a 01 push $0x1
305: e8 16 04 00 00 call 720 <printf>
30a: 83 c4 20 add $0x20,%esp
30d: e9 4e ff ff ff jmp 260 <ls+0x160>
312: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
printf(1, "ls: cannot stat %s\n", buf);
318: 83 ec 04 sub $0x4,%esp
31b: 57 push %edi
31c: 68 8c 0a 00 00 push $0xa8c
321: 6a 01 push $0x1
323: e8 f8 03 00 00 call 720 <printf>
continue;
328: 83 c4 10 add $0x10,%esp
32b: e9 30 ff ff ff jmp 260 <ls+0x160>
00000330 <init_lock>:
#include "user.h"
#include "x86.h"
#include "spinlock.h"
void
init_lock(struct spinlock * lk) {
330: 55 push %ebp
331: 89 e5 mov %esp,%ebp
lk->locked = 0;
333: 8b 45 08 mov 0x8(%ebp),%eax
336: c7 00 00 00 00 00 movl $0x0,(%eax)
}
33c: 5d pop %ebp
33d: c3 ret
33e: 66 90 xchg %ax,%ax
00000340 <lock>:
void lock(struct spinlock * lk) {
340: 55 push %ebp
xchg(volatile uint *addr, uint newval)
{
uint result;
// The + in "+m" denotes a read-modify-write operand.
asm volatile("lock; xchgl %0, %1" :
341: b9 01 00 00 00 mov $0x1,%ecx
346: 89 e5 mov %esp,%ebp
348: 8b 55 08 mov 0x8(%ebp),%edx
34b: 90 nop
34c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
350: 89 c8 mov %ecx,%eax
352: f0 87 02 lock xchg %eax,(%edx)
while(xchg(&lk->locked, 1) != 0)
355: 85 c0 test %eax,%eax
357: 75 f7 jne 350 <lock+0x10>
;
}
359: 5d pop %ebp
35a: c3 ret
35b: 90 nop
35c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
00000360 <unlock>:
void unlock(struct spinlock * lk) {
360: 55 push %ebp
361: 31 c0 xor %eax,%eax
363: 89 e5 mov %esp,%ebp
365: 8b 55 08 mov 0x8(%ebp),%edx
368: f0 87 02 lock xchg %eax,(%edx)
xchg(&lk->locked, 0);
}
36b: 5d pop %ebp
36c: c3 ret
36d: 8d 76 00 lea 0x0(%esi),%esi
00000370 <strcpy>:
char*
strcpy(char *s, const char *t)
{
370: 55 push %ebp
371: 89 e5 mov %esp,%ebp
373: 53 push %ebx
374: 8b 45 08 mov 0x8(%ebp),%eax
377: 8b 4d 0c mov 0xc(%ebp),%ecx
char *os;
os = s;
while((*s++ = *t++) != 0)
37a: 89 c2 mov %eax,%edx
37c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
380: 83 c1 01 add $0x1,%ecx
383: 0f b6 59 ff movzbl -0x1(%ecx),%ebx
387: 83 c2 01 add $0x1,%edx
38a: 84 db test %bl,%bl
38c: 88 5a ff mov %bl,-0x1(%edx)
38f: 75 ef jne 380 <strcpy+0x10>
;
return os;
}
391: 5b pop %ebx
392: 5d pop %ebp
393: c3 ret
394: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
39a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
000003a0 <strcmp>:
int
strcmp(const char *p, const char *q)
{
3a0: 55 push %ebp
3a1: 89 e5 mov %esp,%ebp
3a3: 53 push %ebx
3a4: 8b 55 08 mov 0x8(%ebp),%edx
3a7: 8b 4d 0c mov 0xc(%ebp),%ecx
while(*p && *p == *q)
3aa: 0f b6 02 movzbl (%edx),%eax
3ad: 0f b6 19 movzbl (%ecx),%ebx
3b0: 84 c0 test %al,%al
3b2: 75 1c jne 3d0 <strcmp+0x30>
3b4: eb 2a jmp 3e0 <strcmp+0x40>
3b6: 8d 76 00 lea 0x0(%esi),%esi
3b9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
p++, q++;
3c0: 83 c2 01 add $0x1,%edx
while(*p && *p == *q)
3c3: 0f b6 02 movzbl (%edx),%eax
p++, q++;
3c6: 83 c1 01 add $0x1,%ecx
3c9: 0f b6 19 movzbl (%ecx),%ebx
while(*p && *p == *q)
3cc: 84 c0 test %al,%al
3ce: 74 10 je 3e0 <strcmp+0x40>
3d0: 38 d8 cmp %bl,%al
3d2: 74 ec je 3c0 <strcmp+0x20>
return (uchar)*p - (uchar)*q;
3d4: 29 d8 sub %ebx,%eax
}
3d6: 5b pop %ebx
3d7: 5d pop %ebp
3d8: c3 ret
3d9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
3e0: 31 c0 xor %eax,%eax
return (uchar)*p - (uchar)*q;
3e2: 29 d8 sub %ebx,%eax
}
3e4: 5b pop %ebx
3e5: 5d pop %ebp
3e6: c3 ret
3e7: 89 f6 mov %esi,%esi
3e9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
000003f0 <strlen>:
uint
strlen(const char *s)
{
3f0: 55 push %ebp
3f1: 89 e5 mov %esp,%ebp
3f3: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
for(n = 0; s[n]; n++)
3f6: 80 39 00 cmpb $0x0,(%ecx)
3f9: 74 15 je 410 <strlen+0x20>
3fb: 31 d2 xor %edx,%edx
3fd: 8d 76 00 lea 0x0(%esi),%esi
400: 83 c2 01 add $0x1,%edx
403: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1)
407: 89 d0 mov %edx,%eax
409: 75 f5 jne 400 <strlen+0x10>
;
return n;
}
40b: 5d pop %ebp
40c: c3 ret
40d: 8d 76 00 lea 0x0(%esi),%esi
for(n = 0; s[n]; n++)
410: 31 c0 xor %eax,%eax
}
412: 5d pop %ebp
413: c3 ret
414: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
41a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000420 <memset>:
void*
memset(void *dst, int c, uint n)
{
420: 55 push %ebp
421: 89 e5 mov %esp,%ebp
423: 57 push %edi
424: 8b 55 08 mov 0x8(%ebp),%edx
asm volatile("cld; rep stosb" :
427: 8b 4d 10 mov 0x10(%ebp),%ecx
42a: 8b 45 0c mov 0xc(%ebp),%eax
42d: 89 d7 mov %edx,%edi
42f: fc cld
430: f3 aa rep stos %al,%es:(%edi)
stosb(dst, c, n);
return dst;
}
432: 89 d0 mov %edx,%eax
434: 5f pop %edi
435: 5d pop %ebp
436: c3 ret
437: 89 f6 mov %esi,%esi
439: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000440 <strchr>:
char*
strchr(const char *s, char c)
{
440: 55 push %ebp
441: 89 e5 mov %esp,%ebp
443: 53 push %ebx
444: 8b 45 08 mov 0x8(%ebp),%eax
447: 8b 5d 0c mov 0xc(%ebp),%ebx
for(; *s; s++)
44a: 0f b6 10 movzbl (%eax),%edx
44d: 84 d2 test %dl,%dl
44f: 74 1d je 46e <strchr+0x2e>
if(*s == c)
451: 38 d3 cmp %dl,%bl
453: 89 d9 mov %ebx,%ecx
455: 75 0d jne 464 <strchr+0x24>
457: eb 17 jmp 470 <strchr+0x30>
459: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
460: 38 ca cmp %cl,%dl
462: 74 0c je 470 <strchr+0x30>
for(; *s; s++)
464: 83 c0 01 add $0x1,%eax
467: 0f b6 10 movzbl (%eax),%edx
46a: 84 d2 test %dl,%dl
46c: 75 f2 jne 460 <strchr+0x20>
return (char*)s;
return 0;
46e: 31 c0 xor %eax,%eax
}
470: 5b pop %ebx
471: 5d pop %ebp
472: c3 ret
473: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
479: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000480 <gets>:
char*
gets(char *buf, int max)
{
480: 55 push %ebp
481: 89 e5 mov %esp,%ebp
483: 57 push %edi
484: 56 push %esi
485: 53 push %ebx
int i, cc;
char c;
for(i=0; i+1 < max; ){
486: 31 f6 xor %esi,%esi
488: 89 f3 mov %esi,%ebx
{
48a: 83 ec 1c sub $0x1c,%esp
48d: 8b 7d 08 mov 0x8(%ebp),%edi
for(i=0; i+1 < max; ){
490: eb 2f jmp 4c1 <gets+0x41>
492: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
cc = read(0, &c, 1);
498: 8d 45 e7 lea -0x19(%ebp),%eax
49b: 83 ec 04 sub $0x4,%esp
49e: 6a 01 push $0x1
4a0: 50 push %eax
4a1: 6a 00 push $0x0
4a3: e8 32 01 00 00 call 5da <read>
if(cc < 1)
4a8: 83 c4 10 add $0x10,%esp
4ab: 85 c0 test %eax,%eax
4ad: 7e 1c jle 4cb <gets+0x4b>
break;
buf[i++] = c;
4af: 0f b6 45 e7 movzbl -0x19(%ebp),%eax
4b3: 83 c7 01 add $0x1,%edi
4b6: 88 47 ff mov %al,-0x1(%edi)
if(c == '\n' || c == '\r')
4b9: 3c 0a cmp $0xa,%al
4bb: 74 23 je 4e0 <gets+0x60>
4bd: 3c 0d cmp $0xd,%al
4bf: 74 1f je 4e0 <gets+0x60>
for(i=0; i+1 < max; ){
4c1: 83 c3 01 add $0x1,%ebx
4c4: 3b 5d 0c cmp 0xc(%ebp),%ebx
4c7: 89 fe mov %edi,%esi
4c9: 7c cd jl 498 <gets+0x18>
4cb: 89 f3 mov %esi,%ebx
break;
}
buf[i] = '\0';
return buf;
}
4cd: 8b 45 08 mov 0x8(%ebp),%eax
buf[i] = '\0';
4d0: c6 03 00 movb $0x0,(%ebx)
}
4d3: 8d 65 f4 lea -0xc(%ebp),%esp
4d6: 5b pop %ebx
4d7: 5e pop %esi
4d8: 5f pop %edi
4d9: 5d pop %ebp
4da: c3 ret
4db: 90 nop
4dc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
4e0: 8b 75 08 mov 0x8(%ebp),%esi
4e3: 8b 45 08 mov 0x8(%ebp),%eax
4e6: 01 de add %ebx,%esi
4e8: 89 f3 mov %esi,%ebx
buf[i] = '\0';
4ea: c6 03 00 movb $0x0,(%ebx)
}
4ed: 8d 65 f4 lea -0xc(%ebp),%esp
4f0: 5b pop %ebx
4f1: 5e pop %esi
4f2: 5f pop %edi
4f3: 5d pop %ebp
4f4: c3 ret
4f5: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
4f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000500 <stat>:
int
stat(const char *n, struct stat *st)
{
500: 55 push %ebp
501: 89 e5 mov %esp,%ebp
503: 56 push %esi
504: 53 push %ebx
int fd;
int r;
fd = open(n, O_RDONLY);
505: 83 ec 08 sub $0x8,%esp
508: 6a 00 push $0x0
50a: ff 75 08 pushl 0x8(%ebp)
50d: e8 f0 00 00 00 call 602 <open>
if(fd < 0)
512: 83 c4 10 add $0x10,%esp
515: 85 c0 test %eax,%eax
517: 78 27 js 540 <stat+0x40>
return -1;
r = fstat(fd, st);
519: 83 ec 08 sub $0x8,%esp
51c: ff 75 0c pushl 0xc(%ebp)
51f: 89 c3 mov %eax,%ebx
521: 50 push %eax
522: e8 f3 00 00 00 call 61a <fstat>
close(fd);
527: 89 1c 24 mov %ebx,(%esp)
r = fstat(fd, st);
52a: 89 c6 mov %eax,%esi
close(fd);
52c: e8 b9 00 00 00 call 5ea <close>
return r;
531: 83 c4 10 add $0x10,%esp
}
534: 8d 65 f8 lea -0x8(%ebp),%esp
537: 89 f0 mov %esi,%eax
539: 5b pop %ebx
53a: 5e pop %esi
53b: 5d pop %ebp
53c: c3 ret
53d: 8d 76 00 lea 0x0(%esi),%esi
return -1;
540: be ff ff ff ff mov $0xffffffff,%esi
545: eb ed jmp 534 <stat+0x34>
547: 89 f6 mov %esi,%esi
549: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000550 <atoi>:
int
atoi(const char *s)
{
550: 55 push %ebp
551: 89 e5 mov %esp,%ebp
553: 53 push %ebx
554: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
n = 0;
while('0' <= *s && *s <= '9')
557: 0f be 11 movsbl (%ecx),%edx
55a: 8d 42 d0 lea -0x30(%edx),%eax
55d: 3c 09 cmp $0x9,%al
n = 0;
55f: b8 00 00 00 00 mov $0x0,%eax
while('0' <= *s && *s <= '9')
564: 77 1f ja 585 <atoi+0x35>
566: 8d 76 00 lea 0x0(%esi),%esi
569: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
n = n*10 + *s++ - '0';
570: 8d 04 80 lea (%eax,%eax,4),%eax
573: 83 c1 01 add $0x1,%ecx
576: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax
while('0' <= *s && *s <= '9')
57a: 0f be 11 movsbl (%ecx),%edx
57d: 8d 5a d0 lea -0x30(%edx),%ebx
580: 80 fb 09 cmp $0x9,%bl
583: 76 eb jbe 570 <atoi+0x20>
return n;
}
585: 5b pop %ebx
586: 5d pop %ebp
587: c3 ret
588: 90 nop
589: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000590 <memmove>:
void*
memmove(void *vdst, const void *vsrc, int n)
{
590: 55 push %ebp
591: 89 e5 mov %esp,%ebp
593: 56 push %esi
594: 53 push %ebx
595: 8b 5d 10 mov 0x10(%ebp),%ebx
598: 8b 45 08 mov 0x8(%ebp),%eax
59b: 8b 75 0c mov 0xc(%ebp),%esi
char *dst;
const char *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
59e: 85 db test %ebx,%ebx
5a0: 7e 14 jle 5b6 <memmove+0x26>
5a2: 31 d2 xor %edx,%edx
5a4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
*dst++ = *src++;
5a8: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx
5ac: 88 0c 10 mov %cl,(%eax,%edx,1)
5af: 83 c2 01 add $0x1,%edx
while(n-- > 0)
5b2: 39 d3 cmp %edx,%ebx
5b4: 75 f2 jne 5a8 <memmove+0x18>
return vdst;
}
5b6: 5b pop %ebx
5b7: 5e pop %esi
5b8: 5d pop %ebp
5b9: c3 ret
000005ba <fork>:
name: \
movl $SYS_ ## name, %eax; \
int $T_SYSCALL; \
ret
SYSCALL(fork)
5ba: b8 01 00 00 00 mov $0x1,%eax
5bf: cd 40 int $0x40
5c1: c3 ret
000005c2 <exit>:
SYSCALL(exit)
5c2: b8 02 00 00 00 mov $0x2,%eax
5c7: cd 40 int $0x40
5c9: c3 ret
000005ca <wait>:
SYSCALL(wait)
5ca: b8 03 00 00 00 mov $0x3,%eax
5cf: cd 40 int $0x40
5d1: c3 ret
000005d2 <pipe>:
SYSCALL(pipe)
5d2: b8 04 00 00 00 mov $0x4,%eax
5d7: cd 40 int $0x40
5d9: c3 ret
000005da <read>:
SYSCALL(read)
5da: b8 05 00 00 00 mov $0x5,%eax
5df: cd 40 int $0x40
5e1: c3 ret
000005e2 <write>:
SYSCALL(write)
5e2: b8 10 00 00 00 mov $0x10,%eax
5e7: cd 40 int $0x40
5e9: c3 ret
000005ea <close>:
SYSCALL(close)
5ea: b8 15 00 00 00 mov $0x15,%eax
5ef: cd 40 int $0x40
5f1: c3 ret
000005f2 <kill>:
SYSCALL(kill)
5f2: b8 06 00 00 00 mov $0x6,%eax
5f7: cd 40 int $0x40
5f9: c3 ret
000005fa <exec>:
SYSCALL(exec)
5fa: b8 07 00 00 00 mov $0x7,%eax
5ff: cd 40 int $0x40
601: c3 ret
00000602 <open>:
SYSCALL(open)
602: b8 0f 00 00 00 mov $0xf,%eax
607: cd 40 int $0x40
609: c3 ret
0000060a <mknod>:
SYSCALL(mknod)
60a: b8 11 00 00 00 mov $0x11,%eax
60f: cd 40 int $0x40
611: c3 ret
00000612 <unlink>:
SYSCALL(unlink)
612: b8 12 00 00 00 mov $0x12,%eax
617: cd 40 int $0x40
619: c3 ret
0000061a <fstat>:
SYSCALL(fstat)
61a: b8 08 00 00 00 mov $0x8,%eax
61f: cd 40 int $0x40
621: c3 ret
00000622 <link>:
SYSCALL(link)
622: b8 13 00 00 00 mov $0x13,%eax
627: cd 40 int $0x40
629: c3 ret
0000062a <mkdir>:
SYSCALL(mkdir)
62a: b8 14 00 00 00 mov $0x14,%eax
62f: cd 40 int $0x40
631: c3 ret
00000632 <chdir>:
SYSCALL(chdir)
632: b8 09 00 00 00 mov $0x9,%eax
637: cd 40 int $0x40
639: c3 ret
0000063a <dup>:
SYSCALL(dup)
63a: b8 0a 00 00 00 mov $0xa,%eax
63f: cd 40 int $0x40
641: c3 ret
00000642 <getpid>:
SYSCALL(getpid)
642: b8 0b 00 00 00 mov $0xb,%eax
647: cd 40 int $0x40
649: c3 ret
0000064a <sbrk>:
SYSCALL(sbrk)
64a: b8 0c 00 00 00 mov $0xc,%eax
64f: cd 40 int $0x40
651: c3 ret
00000652 <sleep>:
SYSCALL(sleep)
652: b8 0d 00 00 00 mov $0xd,%eax
657: cd 40 int $0x40
659: c3 ret
0000065a <uptime>:
SYSCALL(uptime)
65a: b8 0e 00 00 00 mov $0xe,%eax
65f: cd 40 int $0x40
661: c3 ret
00000662 <cv_signal>:
SYSCALL(cv_signal)
662: b8 16 00 00 00 mov $0x16,%eax
667: cd 40 int $0x40
669: c3 ret
0000066a <cv_wait>:
66a: b8 17 00 00 00 mov $0x17,%eax
66f: cd 40 int $0x40
671: c3 ret
672: 66 90 xchg %ax,%ax
674: 66 90 xchg %ax,%ax
676: 66 90 xchg %ax,%ax
678: 66 90 xchg %ax,%ax
67a: 66 90 xchg %ax,%ax
67c: 66 90 xchg %ax,%ax
67e: 66 90 xchg %ax,%ax
00000680 <printint>:
write(fd, &c, 1);
}
static void
printint(int fd, int xx, int base, int sgn)
{
680: 55 push %ebp
681: 89 e5 mov %esp,%ebp
683: 57 push %edi
684: 56 push %esi
685: 53 push %ebx
686: 83 ec 3c sub $0x3c,%esp
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
689: 85 d2 test %edx,%edx
{
68b: 89 45 c0 mov %eax,-0x40(%ebp)
neg = 1;
x = -xx;
68e: 89 d0 mov %edx,%eax
if(sgn && xx < 0){
690: 79 76 jns 708 <printint+0x88>
692: f6 45 08 01 testb $0x1,0x8(%ebp)
696: 74 70 je 708 <printint+0x88>
x = -xx;
698: f7 d8 neg %eax
neg = 1;
69a: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp)
} else {
x = xx;
}
i = 0;
6a1: 31 f6 xor %esi,%esi
6a3: 8d 5d d7 lea -0x29(%ebp),%ebx
6a6: eb 0a jmp 6b2 <printint+0x32>
6a8: 90 nop
6a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
do{
buf[i++] = digits[x % base];
6b0: 89 fe mov %edi,%esi
6b2: 31 d2 xor %edx,%edx
6b4: 8d 7e 01 lea 0x1(%esi),%edi
6b7: f7 f1 div %ecx
6b9: 0f b6 92 cc 0a 00 00 movzbl 0xacc(%edx),%edx
}while((x /= base) != 0);
6c0: 85 c0 test %eax,%eax
buf[i++] = digits[x % base];
6c2: 88 14 3b mov %dl,(%ebx,%edi,1)
}while((x /= base) != 0);
6c5: 75 e9 jne 6b0 <printint+0x30>
if(neg)
6c7: 8b 45 c4 mov -0x3c(%ebp),%eax
6ca: 85 c0 test %eax,%eax
6cc: 74 08 je 6d6 <printint+0x56>
buf[i++] = '-';
6ce: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1)
6d3: 8d 7e 02 lea 0x2(%esi),%edi
6d6: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi
6da: 8b 7d c0 mov -0x40(%ebp),%edi
6dd: 8d 76 00 lea 0x0(%esi),%esi
6e0: 0f b6 06 movzbl (%esi),%eax
write(fd, &c, 1);
6e3: 83 ec 04 sub $0x4,%esp
6e6: 83 ee 01 sub $0x1,%esi
6e9: 6a 01 push $0x1
6eb: 53 push %ebx
6ec: 57 push %edi
6ed: 88 45 d7 mov %al,-0x29(%ebp)
6f0: e8 ed fe ff ff call 5e2 <write>
while(--i >= 0)
6f5: 83 c4 10 add $0x10,%esp
6f8: 39 de cmp %ebx,%esi
6fa: 75 e4 jne 6e0 <printint+0x60>
putc(fd, buf[i]);
}
6fc: 8d 65 f4 lea -0xc(%ebp),%esp
6ff: 5b pop %ebx
700: 5e pop %esi
701: 5f pop %edi
702: 5d pop %ebp
703: c3 ret
704: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
neg = 0;
708: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp)
70f: eb 90 jmp 6a1 <printint+0x21>
711: eb 0d jmp 720 <printf>
713: 90 nop
714: 90 nop
715: 90 nop
716: 90 nop
717: 90 nop
718: 90 nop
719: 90 nop
71a: 90 nop
71b: 90 nop
71c: 90 nop
71d: 90 nop
71e: 90 nop
71f: 90 nop
00000720 <printf>:
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, const char *fmt, ...)
{
720: 55 push %ebp
721: 89 e5 mov %esp,%ebp
723: 57 push %edi
724: 56 push %esi
725: 53 push %ebx
726: 83 ec 2c sub $0x2c,%esp
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
729: 8b 75 0c mov 0xc(%ebp),%esi
72c: 0f b6 1e movzbl (%esi),%ebx
72f: 84 db test %bl,%bl
731: 0f 84 b3 00 00 00 je 7ea <printf+0xca>
ap = (uint*)(void*)&fmt + 1;
737: 8d 45 10 lea 0x10(%ebp),%eax
73a: 83 c6 01 add $0x1,%esi
state = 0;
73d: 31 ff xor %edi,%edi
ap = (uint*)(void*)&fmt + 1;
73f: 89 45 d4 mov %eax,-0x2c(%ebp)
742: eb 2f jmp 773 <printf+0x53>
744: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
748: 83 f8 25 cmp $0x25,%eax
74b: 0f 84 a7 00 00 00 je 7f8 <printf+0xd8>
write(fd, &c, 1);
751: 8d 45 e2 lea -0x1e(%ebp),%eax
754: 83 ec 04 sub $0x4,%esp
757: 88 5d e2 mov %bl,-0x1e(%ebp)
75a: 6a 01 push $0x1
75c: 50 push %eax
75d: ff 75 08 pushl 0x8(%ebp)
760: e8 7d fe ff ff call 5e2 <write>
765: 83 c4 10 add $0x10,%esp
768: 83 c6 01 add $0x1,%esi
for(i = 0; fmt[i]; i++){
76b: 0f b6 5e ff movzbl -0x1(%esi),%ebx
76f: 84 db test %bl,%bl
771: 74 77 je 7ea <printf+0xca>
if(state == 0){
773: 85 ff test %edi,%edi
c = fmt[i] & 0xff;
775: 0f be cb movsbl %bl,%ecx
778: 0f b6 c3 movzbl %bl,%eax
if(state == 0){
77b: 74 cb je 748 <printf+0x28>
state = '%';
} else {
putc(fd, c);
}
} else if(state == '%'){
77d: 83 ff 25 cmp $0x25,%edi
780: 75 e6 jne 768 <printf+0x48>
if(c == 'd'){
782: 83 f8 64 cmp $0x64,%eax
785: 0f 84 05 01 00 00 je 890 <printf+0x170>
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
78b: 81 e1 f7 00 00 00 and $0xf7,%ecx
791: 83 f9 70 cmp $0x70,%ecx
794: 74 72 je 808 <printf+0xe8>
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
796: 83 f8 73 cmp $0x73,%eax
799: 0f 84 99 00 00 00 je 838 <printf+0x118>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
79f: 83 f8 63 cmp $0x63,%eax
7a2: 0f 84 08 01 00 00 je 8b0 <printf+0x190>
putc(fd, *ap);
ap++;
} else if(c == '%'){
7a8: 83 f8 25 cmp $0x25,%eax
7ab: 0f 84 ef 00 00 00 je 8a0 <printf+0x180>
write(fd, &c, 1);
7b1: 8d 45 e7 lea -0x19(%ebp),%eax
7b4: 83 ec 04 sub $0x4,%esp
7b7: c6 45 e7 25 movb $0x25,-0x19(%ebp)
7bb: 6a 01 push $0x1
7bd: 50 push %eax
7be: ff 75 08 pushl 0x8(%ebp)
7c1: e8 1c fe ff ff call 5e2 <write>
7c6: 83 c4 0c add $0xc,%esp
7c9: 8d 45 e6 lea -0x1a(%ebp),%eax
7cc: 88 5d e6 mov %bl,-0x1a(%ebp)
7cf: 6a 01 push $0x1
7d1: 50 push %eax
7d2: ff 75 08 pushl 0x8(%ebp)
7d5: 83 c6 01 add $0x1,%esi
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
7d8: 31 ff xor %edi,%edi
write(fd, &c, 1);
7da: e8 03 fe ff ff call 5e2 <write>
for(i = 0; fmt[i]; i++){
7df: 0f b6 5e ff movzbl -0x1(%esi),%ebx
write(fd, &c, 1);
7e3: 83 c4 10 add $0x10,%esp
for(i = 0; fmt[i]; i++){
7e6: 84 db test %bl,%bl
7e8: 75 89 jne 773 <printf+0x53>
}
}
}
7ea: 8d 65 f4 lea -0xc(%ebp),%esp
7ed: 5b pop %ebx
7ee: 5e pop %esi
7ef: 5f pop %edi
7f0: 5d pop %ebp
7f1: c3 ret
7f2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
state = '%';
7f8: bf 25 00 00 00 mov $0x25,%edi
7fd: e9 66 ff ff ff jmp 768 <printf+0x48>
802: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
printint(fd, *ap, 16, 0);
808: 83 ec 0c sub $0xc,%esp
80b: b9 10 00 00 00 mov $0x10,%ecx
810: 6a 00 push $0x0
812: 8b 7d d4 mov -0x2c(%ebp),%edi
815: 8b 45 08 mov 0x8(%ebp),%eax
818: 8b 17 mov (%edi),%edx
81a: e8 61 fe ff ff call 680 <printint>
ap++;
81f: 89 f8 mov %edi,%eax
821: 83 c4 10 add $0x10,%esp
state = 0;
824: 31 ff xor %edi,%edi
ap++;
826: 83 c0 04 add $0x4,%eax
829: 89 45 d4 mov %eax,-0x2c(%ebp)
82c: e9 37 ff ff ff jmp 768 <printf+0x48>
831: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
s = (char*)*ap;
838: 8b 45 d4 mov -0x2c(%ebp),%eax
83b: 8b 08 mov (%eax),%ecx
ap++;
83d: 83 c0 04 add $0x4,%eax
840: 89 45 d4 mov %eax,-0x2c(%ebp)
if(s == 0)
843: 85 c9 test %ecx,%ecx
845: 0f 84 8e 00 00 00 je 8d9 <printf+0x1b9>
while(*s != 0){
84b: 0f b6 01 movzbl (%ecx),%eax
state = 0;
84e: 31 ff xor %edi,%edi
s = (char*)*ap;
850: 89 cb mov %ecx,%ebx
while(*s != 0){
852: 84 c0 test %al,%al
854: 0f 84 0e ff ff ff je 768 <printf+0x48>
85a: 89 75 d0 mov %esi,-0x30(%ebp)
85d: 89 de mov %ebx,%esi
85f: 8b 5d 08 mov 0x8(%ebp),%ebx
862: 8d 7d e3 lea -0x1d(%ebp),%edi
865: 8d 76 00 lea 0x0(%esi),%esi
write(fd, &c, 1);
868: 83 ec 04 sub $0x4,%esp
s++;
86b: 83 c6 01 add $0x1,%esi
86e: 88 45 e3 mov %al,-0x1d(%ebp)
write(fd, &c, 1);
871: 6a 01 push $0x1
873: 57 push %edi
874: 53 push %ebx
875: e8 68 fd ff ff call 5e2 <write>
while(*s != 0){
87a: 0f b6 06 movzbl (%esi),%eax
87d: 83 c4 10 add $0x10,%esp
880: 84 c0 test %al,%al
882: 75 e4 jne 868 <printf+0x148>
884: 8b 75 d0 mov -0x30(%ebp),%esi
state = 0;
887: 31 ff xor %edi,%edi
889: e9 da fe ff ff jmp 768 <printf+0x48>
88e: 66 90 xchg %ax,%ax
printint(fd, *ap, 10, 1);
890: 83 ec 0c sub $0xc,%esp
893: b9 0a 00 00 00 mov $0xa,%ecx
898: 6a 01 push $0x1
89a: e9 73 ff ff ff jmp 812 <printf+0xf2>
89f: 90 nop
write(fd, &c, 1);
8a0: 83 ec 04 sub $0x4,%esp
8a3: 88 5d e5 mov %bl,-0x1b(%ebp)
8a6: 8d 45 e5 lea -0x1b(%ebp),%eax
8a9: 6a 01 push $0x1
8ab: e9 21 ff ff ff jmp 7d1 <printf+0xb1>
putc(fd, *ap);
8b0: 8b 7d d4 mov -0x2c(%ebp),%edi
write(fd, &c, 1);
8b3: 83 ec 04 sub $0x4,%esp
putc(fd, *ap);
8b6: 8b 07 mov (%edi),%eax
write(fd, &c, 1);
8b8: 6a 01 push $0x1
ap++;
8ba: 83 c7 04 add $0x4,%edi
putc(fd, *ap);
8bd: 88 45 e4 mov %al,-0x1c(%ebp)
write(fd, &c, 1);
8c0: 8d 45 e4 lea -0x1c(%ebp),%eax
8c3: 50 push %eax
8c4: ff 75 08 pushl 0x8(%ebp)
8c7: e8 16 fd ff ff call 5e2 <write>
ap++;
8cc: 89 7d d4 mov %edi,-0x2c(%ebp)
8cf: 83 c4 10 add $0x10,%esp
state = 0;
8d2: 31 ff xor %edi,%edi
8d4: e9 8f fe ff ff jmp 768 <printf+0x48>
s = "(null)";
8d9: bb c2 0a 00 00 mov $0xac2,%ebx
while(*s != 0){
8de: b8 28 00 00 00 mov $0x28,%eax
8e3: e9 72 ff ff ff jmp 85a <printf+0x13a>
8e8: 66 90 xchg %ax,%ax
8ea: 66 90 xchg %ax,%ax
8ec: 66 90 xchg %ax,%ax
8ee: 66 90 xchg %ax,%ax
000008f0 <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
8f0: 55 push %ebp
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
8f1: a1 5c 0e 00 00 mov 0xe5c,%eax
{
8f6: 89 e5 mov %esp,%ebp
8f8: 57 push %edi
8f9: 56 push %esi
8fa: 53 push %ebx
8fb: 8b 5d 08 mov 0x8(%ebp),%ebx
bp = (Header*)ap - 1;
8fe: 8d 4b f8 lea -0x8(%ebx),%ecx
901: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
908: 39 c8 cmp %ecx,%eax
90a: 8b 10 mov (%eax),%edx
90c: 73 32 jae 940 <free+0x50>
90e: 39 d1 cmp %edx,%ecx
910: 72 04 jb 916 <free+0x26>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
912: 39 d0 cmp %edx,%eax
914: 72 32 jb 948 <free+0x58>
break;
if(bp + bp->s.size == p->s.ptr){
916: 8b 73 fc mov -0x4(%ebx),%esi
919: 8d 3c f1 lea (%ecx,%esi,8),%edi
91c: 39 fa cmp %edi,%edx
91e: 74 30 je 950 <free+0x60>
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
920: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
923: 8b 50 04 mov 0x4(%eax),%edx
926: 8d 34 d0 lea (%eax,%edx,8),%esi
929: 39 f1 cmp %esi,%ecx
92b: 74 3a je 967 <free+0x77>
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
92d: 89 08 mov %ecx,(%eax)
freep = p;
92f: a3 5c 0e 00 00 mov %eax,0xe5c
}
934: 5b pop %ebx
935: 5e pop %esi
936: 5f pop %edi
937: 5d pop %ebp
938: c3 ret
939: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
940: 39 d0 cmp %edx,%eax
942: 72 04 jb 948 <free+0x58>
944: 39 d1 cmp %edx,%ecx
946: 72 ce jb 916 <free+0x26>
{
948: 89 d0 mov %edx,%eax
94a: eb bc jmp 908 <free+0x18>
94c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
bp->s.size += p->s.ptr->s.size;
950: 03 72 04 add 0x4(%edx),%esi
953: 89 73 fc mov %esi,-0x4(%ebx)
bp->s.ptr = p->s.ptr->s.ptr;
956: 8b 10 mov (%eax),%edx
958: 8b 12 mov (%edx),%edx
95a: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
95d: 8b 50 04 mov 0x4(%eax),%edx
960: 8d 34 d0 lea (%eax,%edx,8),%esi
963: 39 f1 cmp %esi,%ecx
965: 75 c6 jne 92d <free+0x3d>
p->s.size += bp->s.size;
967: 03 53 fc add -0x4(%ebx),%edx
freep = p;
96a: a3 5c 0e 00 00 mov %eax,0xe5c
p->s.size += bp->s.size;
96f: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
972: 8b 53 f8 mov -0x8(%ebx),%edx
975: 89 10 mov %edx,(%eax)
}
977: 5b pop %ebx
978: 5e pop %esi
979: 5f pop %edi
97a: 5d pop %ebp
97b: c3 ret
97c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
00000980 <malloc>:
return freep;
}
void*
malloc(uint nbytes)
{
980: 55 push %ebp
981: 89 e5 mov %esp,%ebp
983: 57 push %edi
984: 56 push %esi
985: 53 push %ebx
986: 83 ec 0c sub $0xc,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
989: 8b 45 08 mov 0x8(%ebp),%eax
if((prevp = freep) == 0){
98c: 8b 15 5c 0e 00 00 mov 0xe5c,%edx
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
992: 8d 78 07 lea 0x7(%eax),%edi
995: c1 ef 03 shr $0x3,%edi
998: 83 c7 01 add $0x1,%edi
if((prevp = freep) == 0){
99b: 85 d2 test %edx,%edx
99d: 0f 84 9d 00 00 00 je a40 <malloc+0xc0>
9a3: 8b 02 mov (%edx),%eax
9a5: 8b 48 04 mov 0x4(%eax),%ecx
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
9a8: 39 cf cmp %ecx,%edi
9aa: 76 6c jbe a18 <malloc+0x98>
9ac: 81 ff 00 10 00 00 cmp $0x1000,%edi
9b2: bb 00 10 00 00 mov $0x1000,%ebx
9b7: 0f 43 df cmovae %edi,%ebx
p = sbrk(nu * sizeof(Header));
9ba: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi
9c1: eb 0e jmp 9d1 <malloc+0x51>
9c3: 90 nop
9c4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
9c8: 8b 02 mov (%edx),%eax
if(p->s.size >= nunits){
9ca: 8b 48 04 mov 0x4(%eax),%ecx
9cd: 39 f9 cmp %edi,%ecx
9cf: 73 47 jae a18 <malloc+0x98>
p->s.size = nunits;
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
9d1: 39 05 5c 0e 00 00 cmp %eax,0xe5c
9d7: 89 c2 mov %eax,%edx
9d9: 75 ed jne 9c8 <malloc+0x48>
p = sbrk(nu * sizeof(Header));
9db: 83 ec 0c sub $0xc,%esp
9de: 56 push %esi
9df: e8 66 fc ff ff call 64a <sbrk>
if(p == (char*)-1)
9e4: 83 c4 10 add $0x10,%esp
9e7: 83 f8 ff cmp $0xffffffff,%eax
9ea: 74 1c je a08 <malloc+0x88>
hp->s.size = nu;
9ec: 89 58 04 mov %ebx,0x4(%eax)
free((void*)(hp + 1));
9ef: 83 ec 0c sub $0xc,%esp
9f2: 83 c0 08 add $0x8,%eax
9f5: 50 push %eax
9f6: e8 f5 fe ff ff call 8f0 <free>
return freep;
9fb: 8b 15 5c 0e 00 00 mov 0xe5c,%edx
if((p = morecore(nunits)) == 0)
a01: 83 c4 10 add $0x10,%esp
a04: 85 d2 test %edx,%edx
a06: 75 c0 jne 9c8 <malloc+0x48>
return 0;
}
}
a08: 8d 65 f4 lea -0xc(%ebp),%esp
return 0;
a0b: 31 c0 xor %eax,%eax
}
a0d: 5b pop %ebx
a0e: 5e pop %esi
a0f: 5f pop %edi
a10: 5d pop %ebp
a11: c3 ret
a12: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
if(p->s.size == nunits)
a18: 39 cf cmp %ecx,%edi
a1a: 74 54 je a70 <malloc+0xf0>
p->s.size -= nunits;
a1c: 29 f9 sub %edi,%ecx
a1e: 89 48 04 mov %ecx,0x4(%eax)
p += p->s.size;
a21: 8d 04 c8 lea (%eax,%ecx,8),%eax
p->s.size = nunits;
a24: 89 78 04 mov %edi,0x4(%eax)
freep = prevp;
a27: 89 15 5c 0e 00 00 mov %edx,0xe5c
}
a2d: 8d 65 f4 lea -0xc(%ebp),%esp
return (void*)(p + 1);
a30: 83 c0 08 add $0x8,%eax
}
a33: 5b pop %ebx
a34: 5e pop %esi
a35: 5f pop %edi
a36: 5d pop %ebp
a37: c3 ret
a38: 90 nop
a39: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
base.s.ptr = freep = prevp = &base;
a40: c7 05 5c 0e 00 00 60 movl $0xe60,0xe5c
a47: 0e 00 00
a4a: c7 05 60 0e 00 00 60 movl $0xe60,0xe60
a51: 0e 00 00
base.s.size = 0;
a54: b8 60 0e 00 00 mov $0xe60,%eax
a59: c7 05 64 0e 00 00 00 movl $0x0,0xe64
a60: 00 00 00
a63: e9 44 ff ff ff jmp 9ac <malloc+0x2c>
a68: 90 nop
a69: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
prevp->s.ptr = p->s.ptr;
a70: 8b 08 mov (%eax),%ecx
a72: 89 0a mov %ecx,(%edx)
a74: eb b1 jmp a27 <malloc+0xa7>
| 35.211155
| 73
| 0.413461
|
f62931072abe30397a2b46e3eac694ac8d57fd71
| 48,597
|
cc
|
C++
|
components/payments/core/journey_logger_unittest.cc
|
metux/chromium-deb
|
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
components/payments/core/journey_logger_unittest.cc
|
metux/chromium-deb
|
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
components/payments/core/journey_logger_unittest.cc
|
metux/chromium-deb
|
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/payments/core/journey_logger.h"
#include "base/metrics/metrics_hashes.h"
#include "base/test/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "components/metrics/proto/ukm/entry.pb.h"
#include "components/ukm/test_ukm_recorder.h"
#include "components/ukm/ukm_source.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::ContainerEq;
namespace payments {
// Tests the canMakePayment stats for the case where the merchant does not use
// it and does not show the PaymentRequest to the user.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentNotCalled_NoShow) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
logger.SetCompleted();
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_NOT_USED,
1);
// There should be no completion stats since PR was not shown to the user
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.CanMakePayment.NotUsed.WithShowEffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
}
// Tests the canMakePayment stats for the case where the merchant does not use
// it and the transaction is aborted.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentNotCalled_ShowAndUserAbort) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The merchant does not query CanMakePayment, show the PaymentRequest and the
// user aborts it.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_NOT_USED,
1);
// There should be a record for an abort when CanMakePayment is not used but
// the PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.NotUsed.WithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
}
// Tests the canMakePayment stats for the case where the merchant does not use
// it and the transaction is aborted.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentNotCalled_ShowAndOtherAbort) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The merchant does not query CanMakePayment, show the PaymentRequest and
// there is an abort not initiated by the user.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_NOT_USED,
1);
// There should be a record for an abort when CanMakePayment is not used but
// the PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.NotUsed.WithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
}
// Tests the canMakePayment stats for the case where the merchant does not use
// it and the transaction is completed.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentNotCalled_ShowAndComplete) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The merchant does not query CanMakePayment, show the PaymentRequest and the
// user completes it.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCompleted();
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_NOT_USED,
1);
// There should be a record for an abort when CanMakePayment is not used but
// the PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.NotUsed.WithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns false and show is not called.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_FalseAndNoShow) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetCanMakePaymentValue(false);
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being false and not
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_COULD_NOT_MAKE_PAYMENT_AND_DID_NOT_SHOW,
1);
// There should be no completion stats since PR was not shown to the user.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.CanMakePayment.NotUsed.WithShowEffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns true and show is not called.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_TrueAndNoShow) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetCanMakePaymentValue(true);
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being true and not
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_COULD_MAKE_PAYMENT, 1);
// There should be no completion stats since PR was not shown to the user.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.CanMakePayment.NotUsed.WithShowEffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns false, show is called but the transaction is aborted by the user.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_FalseShowAndUserAbort) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCanMakePaymentValue(false);
logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being false and
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_DID_SHOW, 1);
// There should be a record for an abort when CanMakePayment is false but the
// PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.FalseWithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns false, show is called but the transaction is aborted.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_FalseShowAndOtherAbort) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCanMakePaymentValue(false);
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being false and
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_DID_SHOW, 1);
// There should be a record for an abort when CanMakePayment is false but the
// PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.FalseWithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns false, show is called and the transaction is completed.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_FalseShowAndComplete) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCanMakePaymentValue(false);
logger.SetCompleted();
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being false and
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_DID_SHOW, 1);
// There should be a record for an completion when CanMakePayment is false but
// the PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.FalseWithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns true, show is called but the transaction is aborted by the user.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_TrueShowAndUserAbort) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCanMakePaymentValue(true);
logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being true and not
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_DID_SHOW |
JourneyLogger::CMP_EFFECT_ON_SHOW_COULD_MAKE_PAYMENT,
1);
// There should be a record for an abort when CanMakePayment is true and the
// PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.TrueWithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns true, show is called but the transaction is aborted.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_TrueShowAndOtherAbort) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCanMakePaymentValue(true);
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being true and not
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_DID_SHOW |
JourneyLogger::CMP_EFFECT_ON_SHOW_COULD_MAKE_PAYMENT,
1);
// There should be a record for an abort when CanMakePayment is true and the
// PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.TrueWithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
}
// Tests the canMakePayment stats for the case where the merchant uses it,
// returns true, show is called and the transaction is completed.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePaymentCalled_TrueShowAndComplete) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCanMakePaymentValue(true);
logger.SetCompleted();
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
// The CanMakePayment effect on show should be recorded as being true and not
// shown.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.EffectOnShow",
JourneyLogger::CMP_EFFECT_ON_SHOW_DID_SHOW |
JourneyLogger::CMP_EFFECT_ON_SHOW_COULD_MAKE_PAYMENT,
1);
// There should be a record for a completion when CanMakePayment is true and
// the PR is shown to the user.
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.TrueWithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
}
// Tests the canMakePayment metrics are not logged if the Payment Request was
// done in an incognito tab.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CanMakePayment_IncognitoTab) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// The user cannot make payment and the PaymentRequest is not shown.
logger.SetShowCalled();
logger.SetRequestedInformation(true, false, false, false);
logger.SetCanMakePaymentValue(true);
logger.SetCompleted();
// Expect no log for CanMakePayment.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix("PaymentRequest.CanMakePayment"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_SuggestionsForEverything_Completed) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for all the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 1,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the user completes the checkout.
logger.SetCompleted();
// Make sure that the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserHadSuggestionsForEverything.EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
// Make sure the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_SuggestionsForEverything_UserAborted) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for all the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 1,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the user aborts the checkout.
logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
// Make sure the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserHadSuggestionsForEverything.EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
// Make sure the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_SuggestionsForEverything_OtherAborted) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for all the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 1,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the checkout is aborted.
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
// Make sure the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserHadSuggestionsForEverything.EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
// Make sure that the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly, even in
// incognito mode.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_SuggestionsForEverything_Incognito) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for all the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 1,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the user completes the checkout.
logger.SetCompleted();
// Make sure the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserHadSuggestionsForEverything.EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
// Make sure the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_NoSuggestionsForEverything_Completed) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for none of the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 0,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the user completes the checkout.
logger.SetCompleted();
// Make sure the expected metrics was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
// Make sure the opposite metrics was not logged.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserHadSuggestionsForEverything.EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_NoSuggestionsForEverything_UserAborted) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for none of the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 0,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the user aborts the checkout.
logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
// Make sure the metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
// Make sure the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserHadSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_NoSuggestionsForEverything_OtherAborted) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for none of the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 0,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the the checkout is aborted.
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
// Make sure the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
// Make sure the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserHadSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly, even in
// incognito mode.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_NoSuggestionsForEverything_Incognito) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had suggestions for none of the requested sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 0,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the user aborts the checkout.
logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
// Make sure the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
// Make sure the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserHadSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(
JourneyLoggerTest,
RecordJourneyStatsHistograms_NoCompleteSuggestionsForEverything_OtherAborted) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/false, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had incomplete suggestions for the requested
// sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 2,
/*has_complete_suggestion=*/false);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the the checkout is aborted.
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
// Make sure the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserDidNotHaveCompleteSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
// Makes sure the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserHadCompleteSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(
JourneyLoggerTest,
RecordJourneyStatsHistograms_NoCompleteSuggestionsForEverything_SomeComplete_OtherAborted) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/true, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had incomplete suggestions for one of the requested
// sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 2,
/*has_complete_suggestion=*/false);
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_SHIPPING_ADDRESS, 1,
/*has_complete_suggestion=*/true);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the the checkout is aborted.
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
// Make sure that the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserDidNotHaveCompleteSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
// Make sure that the opposite metric was not logged.
EXPECT_THAT(histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserHadCompleteSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_FALSE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
}
// Tests that the completion status metrics based on whether the user had
// suggestions for all the requested sections are logged as correctly.
TEST(
JourneyLoggerTest,
RecordJourneyStatsHistograms_CompleteSuggestionsForEverything_OtherAborted) {
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// The merchant only requests payment information.
logger.SetRequestedInformation(
/*requested_shipping=*/true, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
// Simulate that the user had incomplete suggestions for one of the requested
// sections.
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 2,
/*has_complete_suggestion=*/true);
logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_SHIPPING_ADDRESS, 1,
/*has_complete_suggestion=*/true);
// Simulate that the Payment Request was shown to the user.
logger.SetShowCalled();
// Simulate that the the checkout is aborted.
logger.SetAborted(JourneyLogger::ABORT_REASON_OTHER);
// Make sure that the expected metric was logged.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserHadCompleteSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_OTHER_ABORTED, 1);
// Make sure that the opposite metric was not logged.
EXPECT_THAT(
histogram_tester.GetTotalCountsForPrefix(
"PaymentRequest.UserDidNotHaveCompleteSuggestionsForEverything."
"EffectOnCompletion"),
testing::ContainerEq(base::HistogramTester::CountsMap()));
// Make sure the correct events were logged.
std::vector<base::Bucket> buckets =
histogram_tester.GetAllSamples("PaymentRequest.Events");
ASSERT_EQ(1U, buckets.size());
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_NECESSARY_COMPLETE_SUGGESTIONS);
EXPECT_TRUE(buckets[0].min &
JourneyLogger::EVENT_HAD_INITIAL_FORM_OF_PAYMENT);
EXPECT_TRUE(buckets[0].min & JourneyLogger::EVENT_OTHER_ABORTED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_COMPLETED);
EXPECT_FALSE(buckets[0].min & JourneyLogger::EVENT_USER_ABORTED);
}
// Tests that the metrics are logged correctly for two simultaneous Payment
// Requests.
TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_TwoPaymentRequests) {
base::HistogramTester histogram_tester;
JourneyLogger logger1(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
JourneyLogger logger2(/*is_incognito=*/false, /*url=*/GURL(""),
/*ukm_recorder=*/nullptr);
// Make the two loggers have different data.
logger1.SetShowCalled();
logger1.SetRequestedInformation(
/*requested_shipping=*/true, /*requested_email=*/true,
/*requested_phone=*/false, /*requested_name=*/false);
logger2.SetShowCalled();
logger2.SetRequestedInformation(
/*requested_shipping=*/true, /*requested_email=*/false,
/*requested_phone=*/false, /*requested_name=*/false);
logger1.SetCanMakePaymentValue(true);
logger1.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 1,
/*has_complete_suggestion=*/false);
logger2.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_PAYMENT_METHOD, 0,
/*has_complete_suggestion=*/false);
// Simulate that the user completes one checkout and aborts the other.
logger1.SetCompleted();
logger2.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
// Make sure the appropriate metrics were logged for logger1.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserHadSuggestionsForEverything.EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_USED, 1);
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.Used.TrueWithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_COMPLETED, 1);
// Make sure the appropriate metrics were logged for logger2.
histogram_tester.ExpectBucketCount(
"PaymentRequest.UserDidNotHaveSuggestionsForEverything."
"EffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
histogram_tester.ExpectBucketCount("PaymentRequest.CanMakePayment.Usage",
JourneyLogger::CAN_MAKE_PAYMENT_NOT_USED,
1);
histogram_tester.ExpectBucketCount(
"PaymentRequest.CanMakePayment.NotUsed.WithShowEffectOnCompletion",
JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1);
}
// Tests that the Payment Request UKMs are logged correctly when the user aborts
// the Payment Request.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CheckoutFunnelUkm_UserAborted) {
ukm::TestAutoSetUkmRecorder ukm_recorder;
char test_url[] = "http://www.google.com/";
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(test_url),
/*ukm_recorder=*/&ukm_recorder);
// Simulate that the user aborts after being shown the Payment Request and
// clicking pay.
logger.SetEventOccurred(JourneyLogger::EVENT_SHOWN);
logger.SetEventOccurred(JourneyLogger::EVENT_PAY_CLICKED);
logger.SetAborted(JourneyLogger::ABORT_REASON_ABORTED_BY_USER);
// Make sure the UKM was logged correctly.
ASSERT_EQ(1U, ukm_recorder.sources_count());
const ukm::UkmSource* source = ukm_recorder.GetSourceForUrl(test_url);
ASSERT_NE(nullptr, source);
ASSERT_EQ(1U, ukm_recorder.entries_count());
const ukm::mojom::UkmEntry* entry = ukm_recorder.GetEntry(0);
EXPECT_EQ(source->id(), entry->source_id);
EXPECT_EQ(base::HashMetricName(internal::kUKMCheckoutEventsEntryName),
entry->event_hash);
const ukm::mojom::UkmMetric* status_metric = ukm::TestUkmRecorder::FindMetric(
entry, internal::kUKMCompletionStatusMetricName);
ASSERT_NE(nullptr, status_metric);
EXPECT_EQ(JourneyLogger::COMPLETION_STATUS_USER_ABORTED,
status_metric->value);
const ukm::mojom::UkmMetric* step_metric =
ukm::TestUkmRecorder::FindMetric(entry, internal::kUKMEventsMetricName);
ASSERT_NE(nullptr, step_metric);
EXPECT_EQ(JourneyLogger::EVENT_SHOWN | JourneyLogger::EVENT_PAY_CLICKED,
step_metric->value);
}
// Tests that the Payment Request UKMs are logged correctly when the user
// completes the Payment Request.
TEST(JourneyLoggerTest,
RecordJourneyStatsHistograms_CheckoutFunnelUkm_Completed) {
ukm::TestAutoSetUkmRecorder ukm_recorder;
char test_url[] = "http://www.google.com/";
base::HistogramTester histogram_tester;
JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(test_url),
/*ukm_recorder=*/&ukm_recorder);
// Simulate that the user aborts after being shown the Payment Request.
logger.SetEventOccurred(JourneyLogger::EVENT_SHOWN);
logger.SetCompleted();
// Make sure the UKM was logged correctly.
ASSERT_EQ(1U, ukm_recorder.sources_count());
const ukm::UkmSource* source = ukm_recorder.GetSourceForUrl(test_url);
ASSERT_NE(nullptr, source);
ASSERT_EQ(1U, ukm_recorder.entries_count());
const ukm::mojom::UkmEntry* entry = ukm_recorder.GetEntry(0);
EXPECT_EQ(source->id(), entry->source_id);
EXPECT_EQ(base::HashMetricName(internal::kUKMCheckoutEventsEntryName),
entry->event_hash);
const ukm::mojom::UkmMetric* status_metric = ukm::TestUkmRecorder::FindMetric(
entry, internal::kUKMCompletionStatusMetricName);
ASSERT_NE(nullptr, status_metric);
EXPECT_EQ(JourneyLogger::COMPLETION_STATUS_COMPLETED, status_metric->value);
const ukm::mojom::UkmMetric* step_metric =
ukm::TestUkmRecorder::FindMetric(entry, internal::kUKMEventsMetricName);
ASSERT_NE(nullptr, step_metric);
EXPECT_EQ(JourneyLogger::EVENT_SHOWN, step_metric->value);
}
} // namespace payments
| 44.05893
| 96
| 0.73558
|
2c38fc6e13a1316e29407c0b76a005669e1970c4
| 1,180
|
py
|
Python
|
phc/easy/patients/__init__.py
|
taylordeatri/phc-sdk-py
|
8f3ec6ac44e50c7194f174fd0098de390886693d
|
[
"MIT"
] | 1
|
2020-07-22T12:46:58.000Z
|
2020-07-22T12:46:58.000Z
|
phc/easy/patients/__init__.py
|
taylordeatri/phc-sdk-py
|
8f3ec6ac44e50c7194f174fd0098de390886693d
|
[
"MIT"
] | 54
|
2019-10-09T16:19:04.000Z
|
2022-01-19T20:28:59.000Z
|
phc/easy/patients/__init__.py
|
taylordeatri/phc-sdk-py
|
8f3ec6ac44e50c7194f174fd0098de390886693d
|
[
"MIT"
] | 2
|
2019-10-30T19:54:43.000Z
|
2020-12-03T18:57:15.000Z
|
import pandas as pd
from phc.easy.frame import Frame
from phc.easy.abstract.fhir_service_item import FhirServiceItem
from phc.easy.patients.address import expand_address_column
from phc.easy.patients.name import expand_name_column
class Patient(FhirServiceItem):
@staticmethod
def table_name():
return "patient"
@staticmethod
def code_fields():
return [
"extension.valueCodeableConcept.coding",
"identifier.type.coding",
"maritalStatus.coding",
"meta.tag",
]
@staticmethod
def transform_results(data_frame: pd.DataFrame, **expand_args):
args = {
**expand_args,
"code_columns": [
*expand_args.get("code_columns", []),
"contained",
"maritalStatus",
],
"custom_columns": [
*expand_args.get("custom_columns", []),
Frame.codeable_like_column_expander("managingOrganization"),
("address", expand_address_column),
("name", expand_name_column),
],
}
return Frame.expand(data_frame, **args)
| 28.780488
| 76
| 0.588136
|
9fed9867e7bbf41082dd266ceb35674fe5ec853f
| 5,828
|
py
|
Python
|
data.py
|
accelsao/MusicBox
|
d06a30c681f2d817f0aaecf0d6bc2f0dfffff5af
|
[
"MIT"
] | null | null | null |
data.py
|
accelsao/MusicBox
|
d06a30c681f2d817f0aaecf0d6bc2f0dfffff5af
|
[
"MIT"
] | null | null | null |
data.py
|
accelsao/MusicBox
|
d06a30c681f2d817f0aaecf0d6bc2f0dfffff5af
|
[
"MIT"
] | null | null | null |
import argparse
import json
import os
import glob
import re
from time import sleep
from math import cos, sin, radians, degrees, asin, atan2
import numpy as np
if __name__ == '__main__':
# https://www.google.com/maps/d/u/0/viewer?mid=1Kn1r0J6jdb6VR1tRXt7dIrJN3LA&ll=24.9682276%2C121.19437649999998&z=17
gate3 = [(24.96715, 121.18766), (24.96822, 121.19437), (24.97154, 121.19268)]
file3 = [None] * 3
file_dict = set()
file_sz = 0
sec = 1
earthR = 6371
while True:
for fn in glob.glob('testData/*.txt'):
# testData\\107522xxx_008000000000e331_1_3_7_5.txt
# get ↑
loc = int(re.search(r'[a-zA-Z0-9]+\\[a-zA-Z0-9]+_[a-zA-Z0-9]+_(\d).*', fn).group(1))
if file3[loc - 1] is None:
file3[loc - 1] = fn
# compare time, get the latest file
elif os.path.getatime(fn) > os.path.getatime(file3[loc - 1]):
file3[loc - 1] = fn
file_dict.add(fn)
if len(file_dict) > file_sz:
file_sz = len(file_dict)
if None not in file3:
point3 = []
dis3 = []
for i, fn in enumerate(file3):
with open(fn, 'r') as f:
line = json.load(f)
rssi = line['result']['uplinkFrames'][0]['rxInfo'][0]['rssi']
# RSSI = -(10.η.log(d) + A), η = 3 , A = 9
# 2^(-rssi - 9) / 30 = d
dis = pow(2, (-rssi - 9) / 30)
dis /= 10.0
x = earthR * cos(radians(gate3[i][0])) * cos(radians(gate3[i][1]))
y = earthR * cos(radians(gate3[i][0])) * sin(radians(gate3[i][1]))
z = earthR * sin(radians(gate3[i][0]))
point3.append(np.array([x, y, z]))
dis3.append(dis)
print(point3)
# ref: https://gis.stackexchange.com/questions/66/trilateration-using-3-latitude-longitude-points-and-3-distances
# ref: https://www.wikiwand.com/en/True_range_multilateration
# ref: https://www.wikiwand.com/en/Geographic_coordinate_conversion
p1 = point3[0]
p2 = point3[1]
p3 = point3[2]
d1 = dis3[0]
d2 = dis3[1]
d3 = dis3[2]
# print(dis3)
# pt3 = []
# for i in range(3):
# j = (i + 1) % 3
# pq = np.linalg.norm(point3[j] - point3[i])
# print(pow(dis3[i], 2))
# pc = pq / 2.0 + (pow(dis3[i], 2) - pow(dis3[j], 2)) / (pq * 2)
# print('pc: {}'.format(pc))
# print('pq: {}'.format(pq))
# print('(pow(dis3[i], 2) - pow(dis3[j], 2)): {}'.format((pow(dis3[i], 2) - pow(dis3[j], 2))))
# print('point3[i] + pc: {}'.format(point3[i] + pc))
# c = point3[i] + (point3[j] - point3[i]) * pc / pq
# pt3.append(c)
# print('pt3: {}'.format(pt3))
# pt = np.sum(pt3, axis=0) / 3.0
# print('pt: {}'.format(pt))
# lat = degrees(asin(pt[2] / earthR))
# lng = degrees(atan2(pt[1], pt[0]))
# print(lat, lng)
norm_x = (p2 - p1) / np.linalg.norm(p2 - p1)
Vx = np.dot(norm_x, p3 - p1)
norm_y = (p3 - p1 - Vx * norm_x) / np.linalg.norm(p3 - p1 - Vx * norm_x)
norm_z = np.cross(norm_x, norm_y)
Vy = np.dot(norm_y, p3 - p1)
U = np.linalg.norm(p2 - p1)
x = (pow(d1, 2) - pow(d2, 2) + pow(U, 2)) / (U * 2)
y = (pow(d1, 2) - pow(d3, 2) + pow(Vx, 2) + pow(Vy, 2) - 2 * Vx * x) / (2 * Vy)
z = np.sqrt(abs(pow(d1, 2) - pow(x, 2) - pow(y, 2)))
triPt = p1 + x * norm_x + y * norm_y + z * norm_z
print(triPt)
lat = degrees(asin(triPt[2] / earthR))
lng = degrees(atan2(triPt[1], triPt[0]))
print(lat, lng)
points = []
if os.path.exists('web/position.json'):
with open('web/position.json') as f:
points = json.load(f)
else:
points = []
pt = dict([('lat', lat), ('lng', lng)])
if pt not in points:
points.append(pt)
res = json.dumps(points)
with open('web/position.json', 'w') as f:
f.write(res)
else:
print('miss some locations for positioning')
sec = 1
else:
sleep(sec)
sec = max(sec + sec, 32)
# parser = argparse.ArgumentParser()
# parser.add_argument('-m', '--mode', type=str, help='set action mode, [add, remove, clear]', required=True)
# parser.add_argument('--lat', type=float, help='lat', required=True)
# parser.add_argument('--lng', type=float, help='lng', required=True)
# args = parser.parse_args()
#
# if os.path.exists('web/position.json'):
# with open('web/position.json') as f:
# points = json.load(f)
# else:
# points = []
#
# if args.mode == 'add':
# pt = dict([('lat', args.lat), ('lng', args.lng)])
# if pt not in points:
# points.append(pt)
#
# res = json.dumps(points)
# with open('web/position.json', 'w') as f:
# f.write(res)
# [{"lat": 24.9689352201779, "lng": 121.191933011529}, {"lat": 24.967277, "lng": 121.187729}]
| 38.853333
| 129
| 0.443377
|
25eb058139840f30207072ad1b9349455977d5b6
| 338
|
cs
|
C#
|
AzusaERP.OldStuff/PsxDatacenter/Entity/PsxDatacenterPreview.cs
|
feyris-tan/azusa
|
a34475e9d15b09c2bc82219496908b09246a0bfd
|
[
"BSD-2-Clause"
] | null | null | null |
AzusaERP.OldStuff/PsxDatacenter/Entity/PsxDatacenterPreview.cs
|
feyris-tan/azusa
|
a34475e9d15b09c2bc82219496908b09246a0bfd
|
[
"BSD-2-Clause"
] | 1
|
2021-07-25T10:28:04.000Z
|
2021-07-25T10:28:04.000Z
|
AzusaERP.OldStuff/PsxDatacenter/Entity/PsxDatacenterPreview.cs
|
feyris-tan/azusa
|
a34475e9d15b09c2bc82219496908b09246a0bfd
|
[
"BSD-2-Clause"
] | null | null | null |
namespace moe.yo3explorer.azusa.OfflineReaders.PsxDatacenter.Entity
{
public class PsxDatacenterPreview
{
public int Id { get; set; }
public string Platform { get; set; }
public string SKU { get; set; }
public string Title { get; set; }
public bool HasAdditionalData { get; set; }
}
}
| 28.166667
| 68
| 0.627219
|
45a6caa57f52335bc42e5b0eebfca6086e461be5
| 3,652
|
py
|
Python
|
main.py
|
Guiaochino/contact-simulation
|
85c0ba74a416b45e3632481ec10de4bbcbbd44a8
|
[
"MIT"
] | null | null | null |
main.py
|
Guiaochino/contact-simulation
|
85c0ba74a416b45e3632481ec10de4bbcbbd44a8
|
[
"MIT"
] | null | null | null |
main.py
|
Guiaochino/contact-simulation
|
85c0ba74a416b45e3632481ec10de4bbcbbd44a8
|
[
"MIT"
] | null | null | null |
from contacts import Contacts
import time
import os
# Simulate the PhoneBook functions
# - Display Contacts
# - Add Contacts
# - Delete Contacts
# - Search Contacts
# - Exit
# Declare an empty list
contactList = list()
# validate the input of the user if a number
def input_validation(num):
try:
int(num)
except:
print('Invalid Input')
get_input('Input: ')
return num
# get input
def get_input(message):
return input(message)
# display the possible options that simulates a contacts
def display_options():
print("*"*30 +
"\nWelcome to Phonebook Master" +
"\n\t[1] Display All Contacts" +
"\n\t[2] Add to Contacts" +
"\n\t[3] Delete Contacts" +
"\n\t[4] Search Contacts" +
"\n\t[5] Exit\n" +
"*"*30)
# get user input for choice
choice = input_validation(get_input('Input: '))
# execute a respective function depending on the user input
if choice == '1':
os.system('cls')
time.sleep(0.5)
display_contact()
elif choice == '2':
os.system('cls')
time.sleep(0.5)
add_contact()
elif choice == '3':
os.system('cls')
time.sleep(0.5)
delete_contact()
elif choice == '4':
os.system('cls')
time.sleep(0.5)
search_contact()
elif choice == '5':
pass
else:
print('Invalid Input')
os.system('cls')
time.sleep(0.5)
display_options()
# lets the user display all contacts
def display_contact():
if len(contactList) == 0:
print('No Contacts Found')
display_options()
else:
for c in contactList:
c.display_details()
display_options()
# lets the user add contact by appending to the list
def add_contact():
print('Input Details')
time.sleep(5)
name = input('Enter Name: ')
number = input('Enter Number: ')
# validates whether the user has entered a detail of not
if name == '' or number == '':
print('Please Enter the needed details!')
time.sleep(2)
os.system('cls')
add_contact()
else:
newContact = Contacts(name, number)
contactList.append(newContact)
os.system('cls')
print('Adding to Contacts...')
time.sleep(2)
display_options()
# lets the user delete a specific person in a contact
def delete_contact():
not_found = False
to_delete = input('Enter Name: ')
for names in contactList:
if names.name.lower() == to_delete.lower():
contactList.remove(names)
else:
not_found = True
# validates whether the input is in the list or not
if not_found == True:
print(f'{to_delete} Not Found')
time.sleep(1)
os.system('cls')
display_options()
else:
time.sleep(2)
display_options()
# searches through the list if the input is already in the list or not
def search_contact():
not_found = False
search_for = input('Search for: ')
for names in contactList:
if names.name.lower() == search_for.lower():
names.display_details()
else:
not_found = True
if not_found == True:
print(f'{search_for} Not Found')
time.sleep(1)
os.system('cls')
display_options()
else:
time.sleep(2)
display_options()
pass
if __name__ == "__main__":
display_options()
| 25.013699
| 71
| 0.559146
|
6f49e218774f7cedc19fde0066884acfd8ccbac7
| 337
|
sh
|
Shell
|
Testing/observables_load_test.sh
|
zeptolife/zcoap-server
|
0187c589bc7a7c3f10c9dd8431f6e2ce2d5f8b40
|
[
"MIT"
] | 3
|
2019-10-21T17:49:17.000Z
|
2021-04-19T14:38:04.000Z
|
Testing/observables_load_test.sh
|
zcoap/zcoap-server
|
002ce936cad6dbf15eaa21fa651251cec443a2cb
|
[
"MIT"
] | 1
|
2019-10-18T05:33:01.000Z
|
2019-10-18T22:37:29.000Z
|
Testing/observables_load_test.sh
|
zeptolife/zcoap-server
|
0187c589bc7a7c3f10c9dd8431f6e2ce2d5f8b40
|
[
"MIT"
] | 1
|
2021-03-08T18:15:10.000Z
|
2021-03-08T18:15:10.000Z
|
#!/bin/bash
sudo apt install libcoap2 # as distasteful as libcoap is...
make clean
make
sleep 1
./example-server-linux &
if [[ $? -ne 0 ]]; then
echo "hmmm the server is cranky and gave up..."
exit 1
fi
count=$1
for i in `seq 1 $count`; do
echo $@
coap-client -m GET coap://127.0.0.1/telemetry/temperature -B0 -s0 &
done
| 18.722222
| 71
| 0.649852
|
7b2c1003b495e20a0fc7e8f2b4e1c205254fdc78
| 9,304
|
lua
|
Lua
|
black metal suit script - Copy.lua
|
xVoid-xyz/Roblox-Scripts
|
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
|
[
"BSD-3-Clause"
] | 70
|
2021-02-09T17:21:32.000Z
|
2022-03-28T12:41:42.000Z
|
black metal suit script - Copy.lua
|
xVoid-xyz/Roblox-Scripts
|
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
|
[
"BSD-3-Clause"
] | 4
|
2021-08-19T22:05:58.000Z
|
2022-03-19T18:58:01.000Z
|
black metal suit script - Copy.lua
|
xVoid-xyz/Roblox-Scripts
|
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
|
[
"BSD-3-Clause"
] | 325
|
2021-02-26T22:23:41.000Z
|
2022-03-31T19:36:12.000Z
|
print(time'')
if script then if game.PlaceId~=0 then script.Parent=a end end
waitingFor=function(instance,stuff)
while not instance[stuff]do
instance.Changed:wait''
end
return instance[stuff]
end
Removes={'Hat','Pants','Shirt','ShirtGraphic','BodyColors'}
WaitingForObjectum=function(instance,p,name)
if p:lower''=='name'then
p='Name'
elseif p:lower''=='class'then
p='ClassName'
end
if p~='ClassName'and p~='Name'then return nil end
while 0 do
for i,v in pairs(instance:children'')do
if v[p]:lower''==name:lower''then
return v
end
end
wait''
end
end
GetAll=function(Start)
local AllObj={}
InsertObjectToList=function(obj)
pcall(function()
for lol,child in pairs(obj:children())do
if script~=nil then
if child~=script then
InsertObjectToList(child)
table.insert(AllObj,child)
end
else
InsertObjectToList(child)
table.insert(AllObj,child)
end
end
end)
end
InsertObjectToList(Start)
return AllObj
end
X=function(f)
local CreatedFunction=coroutine.create(f)
coroutine.resume(CreatedFunction)
end
Rot=CFrame.fromEulerAnglesXYZ
Player=game.Players.LocalPlayer
Status='None'
CreatePart=function(Size,Parent)
local Part=Instance.new'Part'
Part.formFactor=3
Part.BottomSurface=0
Part.TopSurface=0
Part.Size=Size
Part.Parent=Parent
return Part
end
LoadCheck=function(Character)
for i,v in pairs(Character:children'')do
if v.Name=='Black Metal Set'or v:IsA'Hat'then
v:remove''
end
end
local BlackMetalSet=Instance.new'Model'
BlackMetalSet.Name='Black Metal Set'
BlackMetalSet.Parent=Character
end
LoadBlackMetalSetAnimate=function(Character)
local Humanoid=WaitingForObjectum(Character,'class','Humanoid')
Humanoid.Died:connect(onDied)
Humanoid.Running:connect(function()Status='run'end)
Humanoid.Jumping:connect(function()Status='jump'end)
Humanoid.Climbing:connect(function()Status='climb'end)
Humanoid.GettingUp:connect(function()Status='getup'end)
Humanoid.FreeFalling:connect(function()Status='freefall'end)
Humanoid.FallingDown:connect(function()Status='falldown'end)
Humanoid.Seated:connect(function()Status='sit'end)
Humanoid.PlatformStanding:connect(function()Status='stand'end)
end
LoadHeadSet=function(Character)
for i,v in pairs(Head:children'')do
if v.Name=='face'then
v.Texture='rbxassetid://55668987'
end
end
local HeadSet=Instance.new'Model'
HeadSet.Name='Head Set'
HeadSet.Parent=WaitingForObjectum(Character,'Name','Black Metal Set')
local Horn=Instance.new'Part'
Horn.formFactor=0
Horn.Size=Vector3.new(1,1,1)
Horn.CFrame=Head.CFrame
Horn.CanCollide=false
Horn.Parent=HeadSet
local HornWeld=Instance.new'Motor'
HornWeld.Parent=Head
HornWeld.Part0=Head
HornWeld.Part1=Horn
HornWeld.C0=Rot(-.3,0,0)+Vector3.new(0,.3,-.2)
local HornMesh=Instance.new'SpecialMesh'
HornMesh.MeshId='http://www.roblox.com/asset/?id=2264333'
HornMesh.TextureId='http://www.roblox.com/asset/?id=2264330'
HornMesh.VertexColor=Vector3.new(.3,0,0)
HornMesh.Scale=Vector3.new(.3,.3,.3)
HornMesh.Parent=Horn
local Hood=Instance.new'Part'
Hood.formFactor=0
Hood.Size=Vector3.new(2,2,1)
Hood.CFrame=Head.CFrame
Hood.CanCollide=false
Hood.BrickColor=BrickColor.new'1003'
Hood.Parent=HeadSet
local HoodMesh=Instance.new'SpecialMesh'
HoodMesh.Scale=Vector3.new(1.05,1.05,1.05)
HoodMesh.VertexColor=Vector3.new(.2,0,0)
HoodMesh.MeshId='http://www.roblox.com/asset/?id=16952952'
HoodMesh.TextureId='http://www.roblox.com/asset/?id=34495525'
HoodMesh.Parent=Hood
local HoodWeld=Instance.new'Motor'
HoodWeld.Parent=Head
HoodWeld.Part0=Head
HoodWeld.Part1=Hood
HoodWeld.C0=CFrame.new(0,.25,-.12)
local Mask=Instance.new'Part'
Mask.formFactor=3
Mask.Size=Vector3.new(2,.4,1)
Mask.CFrame=Head.CFrame
Mask.CanCollide=false
Mask.BrickColor=BrickColor.new'1003'
Mask.Parent=HeadSet
local MaskMesh=Instance.new'SpecialMesh'
MaskMesh.Scale=Vector3.new(.13,.15,.09)
MaskMesh.MeshId='http://www.roblox.com/asset/?id=5158270'
MaskMesh.TextureId='http://www.roblox.com/asset/?id=43098386'
MaskMesh.Parent=Mask
local MaskWeld=Instance.new'Motor'
MaskWeld.Parent=Head
MaskWeld.Part0=Head
MaskWeld.Part1=Mask
MaskWeld.C0=Rot(-math.rad(100),0,0)+Vector3.new(0,-.08,-.6)
X(function()
while MaskMesh do
for i=1,10 do
MaskMesh.VertexColor=Vector3.new(i/10,0,0)
wait'.1'
end
for i=1,9 do
MaskMesh.VertexColor=Vector3.new(1-i/10,0,0)
wait'.1'
end
end
end)
local Eye1=Instance.new'Part'
Eye1.formFactor=3
Eye1.Size=Vector3.new(1,.4,1)
Eye1.CFrame=Head.CFrame
Eye1.CanCollide=false
Eye1.BrickColor=BrickColor.new'1003'
Eye1.Parent=HeadSet
local Eye1Mesh=Instance.new'SpecialMesh'
Eye1Mesh.Scale=Vector3.new(.8,.7,.5)
Eye1Mesh.MeshId='http://www.roblox.com/asset/?id=1185246'
Eye1Mesh.TextureId='http://www.roblox.com/asset/?id=32763014'
Eye1Mesh.Parent=Eye1
local Eye1Weld=Instance.new'Motor'
Eye1Weld.Parent=Head
Eye1Weld.Part0=Head
Eye1Weld.Part1=Eye1
Eye1Weld.C0=CFrame.new(.2,0,-.5)
local Eye2=Instance.new'Part'
Eye2.formFactor=3
Eye2.Size=Vector3.new(1,.4,1)
Eye2.CFrame=Head.CFrame
Eye2.CanCollide=false
Eye2.BrickColor=BrickColor.new'1003'
Eye2.Parent=HeadSet
local Eye2Mesh=Instance.new'SpecialMesh'
Eye2Mesh.Scale=Vector3.new(.8,.7,.5)
Eye2Mesh.MeshId='http://www.roblox.com/asset/?id=1185246'
Eye2Mesh.TextureId='http://www.roblox.com/asset/?id=32763014'
Eye2Mesh.Parent=Eye2
local Eye2Weld=Instance.new'Motor'
Eye2Weld.Parent=Head
Eye2Weld.Part0=Head
Eye2Weld.Part1=Eye2
Eye2Weld.C0=CFrame.new(-.2,0,-.5)
X(function()
while 0 do
wait(math.random(1,11))
if Eye1Mesh then
Eye1Mesh.VertexColor=Vector3.new(0,0,0)
end
if Eye2Mesh then
Eye2Mesh.VertexColor=Vector3.new(0,0,0)
end
wait(math.random(1,5)/50)
if Eye1Mesh then
Eye1Mesh.VertexColor=Vector3.new(1,0,0)
end
if Eye2Mesh then
Eye2Mesh.VertexColor=Vector3.new(1,0,0)
end
end
end)
end
LoadArmSet=function(Character)
wait'.2'
local RS,LR,RightArm,LeftArm
--RS=waitingFor(Torso,'Right Shoulder')
--LS=waitingFor(Torso,'Left Shoulder')
RightArm=WaitingForObjectum(Character,'Name','Right Arm')
LeftArm=WaitingForObjectum(Character,'Name','Left Arm')
RightArm.BrickColor=BrickColor.new'1003'
LeftArm.BrickColor=BrickColor.new'1003'
local ArmSet=Instance.new'Model'
ArmSet.Name='Arm Set'
ArmSet.Parent=WaitingForObjectum(Character,'name','Black Metal Set')
local RightArmArmor=Instance.new'CharacterMesh'
RightArmArmor.Name='Black Metal Set'
RightArmArmor.MeshId='33308774'
RightArmArmor.BaseTextureId='50903886'
RightArmArmor.OverlayTextureId='48610054'
RightArmArmor.BodyPart='RightArm'
RightArmArmor.Parent=Character
local LeftArmArmor=Instance.new'CharacterMesh'
LeftArmArmor.Name='Black Metal Set'
LeftArmArmor.MeshId='33308496'
LeftArmArmor.BaseTextureId='50903886'
LeftArmArmor.OverlayTextureId='48610054'
LeftArmArmor.BodyPart='LeftArm'
LeftArmArmor.Parent=Character
end
LoadTorsoSet=function(Character,Stuff)
for i,v in pairs(Character:children'')do
if v:IsA'Pants'or v:IsA'Shirt'or v:IsA'ShirtGraphic'then
v:remove''
end
if v:IsA'BasePart'then
v.BrickColor=BrickColor.new'1003'
end
end
for i,v in pairs(Torso:children'')do
if v:IsA'Decal'then
v:remove''
end
end
local TorsoSet=Instance.new'Model'
TorsoSet.Name='Torso Set'
TorsoSet.Parent=WaitingForObjectum(Character,'Name','Black Metal Set')
if Stuff:lower''=='cape'then
local Cape=Instance.new'Part'
Cape.formFactor=0
Cape.Size=Vector3.new(1,1,1)
Cape.CFrame=Torso.CFrame
Cape.BrickColor=BrickColor.new'1003'
Cape.Parent=TorsoSet
local CapeMesh=Instance.new'SpecialMesh'
CapeMesh.MeshId='http://www.roblox.com/asset/?id=57480731'
CapeMesh.TextureId='rbxassetid://59662291'
CapeMesh.Scale=Vector3.new(1.3,2.1,1)
CapeMesh.Parent=Cape
local CapeWeld=Instance.new'Motor'
CapeWeld.Parent=Torso
CapeWeld.Part0=Torso
CapeWeld.Part1=Cape
CapeWeld.C1=Rot(math.rad(90),math.rad(90),0)+Vector3.new(0,1.2,-.2)
CapeWeld.C0=Rot(math.rad(90),math.rad(90),0)+Vector3.new(0,.4,.1)
CapeWeld.MaxVelocity=.3
CapeWeld.DesiredAngle=-.3
X(function()
while CapeWeld do
wait''
if Status=='run'then
CapeWeld.MaxVelocity=.3
CapeWeld.DesiredAngle=-.3
elseif Status=='stand'then
CapeWeld.MaxVelocity=.3
CapeWeld.DesiredAngle=0
end
end
end)
elseif Stuff:lower''=='wings'then
end
end
ReLoad=function(Character)
Character=waitingFor(Player,'Character')
Head=WaitingForObjectum(Character,'Name','Head')
Torso=WaitingForObjectum(Character,'Name','Torso')
Character.ChildAdded:connect(function(Child)
for i,v in pairs(Removes)do
if Child:IsA(v)then
Child:remove''
end
end
end)
for ii,Child in pairs(Character:children'')do
for i,v in pairs(Removes)do
if Child:IsA(v)then
Child:remove''
end
end
X(function()
if not Child:IsA'BasePart'then return end
Child.BrickColor=BrickColor.new'1003'
Child.Changed:connect(function()
Child.BrickColor=BrickColor.new'1003'
end)
end)
end
Head.Transparency=1
LoadCheck(Character)
LoadHeadSet(Character)
LoadTorsoSet(Character,'cape')
LoadArmSet(Character)
LoadBlackMetalSetAnimate(Character)
end
Player.CharacterAdded:connect(ReLoad)
ReLoad(waitingFor(Player,'Character'))
print(time'')
--lego
| 26.507123
| 71
| 0.750322
|
1b08a43fcde7b460ea86ee37fe04b60673918437
| 4,307
|
cs
|
C#
|
Ui/TicTacToe.WPFClient/ViewModel/GameBoardViewModel.cs
|
MK-NEUKO/TicTacToeOOP
|
9b794881364d1a2a890ce5ed23a72b121464f8f8
|
[
"MIT"
] | 2
|
2021-06-20T14:18:16.000Z
|
2021-12-13T23:42:28.000Z
|
Ui/TicTacToe.WPFClient/ViewModel/GameBoardViewModel.cs
|
MK-NEUKO/TicTacToeOOP
|
9b794881364d1a2a890ce5ed23a72b121464f8f8
|
[
"MIT"
] | 1
|
2020-10-23T17:26:34.000Z
|
2021-06-20T00:30:31.000Z
|
Ui/TicTacToe.WPFClient/ViewModel/GameBoardViewModel.cs
|
MK-NEUKO/TicTacToeOOP
|
9b794881364d1a2a890ce5ed23a72b121464f8f8
|
[
"MIT"
] | 1
|
2022-02-22T18:25:54.000Z
|
2022-02-22T18:25:54.000Z
|
using System;
using System.Text;
using System.Windows.Input;
using System.Collections.Generic;
using MichaelKoch.TicTacToe.CrossCutting.DataClasses;
using MichaelKoch.TicTacToe.Logik.TicTacToeCore.Contract;
namespace MichaelKoch.TicTacToe.Ui.TicTacToe.WPFClient
{
public class GameBoardViewModel : ViewModelBase, IGameBoardViewModel
{
private readonly IGameBoard _gameBoard;
private readonly IGamePlay _gamePlay;
private readonly IReadOnlyList<GameBoardArea> _gameBoardAreaList;
private List<PlaceATokenCommand> _placeATokenCommands;
private bool _isAnimationCompleted;
private bool _isGameDecided;
private bool _userWantsToContinue = true;
public GameBoardViewModel(IGameBoard gameBoard, IGamePlay gamePlay)
{
_gameBoard = gameBoard ?? throw new ArgumentNullException(nameof(gameBoard));
_gamePlay = gamePlay ?? throw new ArgumentNullException(nameof(gamePlay));
_gameBoardAreaList = _gameBoard.GameBoardAreaList;
_placeATokenCommands = CreatePlaceATokenCommands();
ContinueCommand = new RelayCommand(ContinueExecute, ContinueCanExecute);
}
public IReadOnlyList<GameBoardArea> GameBoardAreaList => _gameBoardAreaList;
public IReadOnlyList<PlaceATokenCommand> PlaceATokenCommands => _placeATokenCommands.AsReadOnly();
public ICommand ContinueCommand { get; }
public bool IsGameDecided
{
get => _isGameDecided;
set
{
_isGameDecided = value;
OnPropertyChanged();
}
}
public bool UserWantsToContinue
{
get => _userWantsToContinue;
set
{
_userWantsToContinue = value;
OnPropertyChanged();
}
}
private List<PlaceATokenCommand> CreatePlaceATokenCommands()
{
_placeATokenCommands = new List<PlaceATokenCommand>();
int numberOfCommands = 9;
for (int areaID = 0; areaID < numberOfCommands; areaID++)
{
_placeATokenCommands.Add(new PlaceATokenCommand(areaID, PlaceATokenExecute, PlaceATokenCanExecute));
_placeATokenCommands[areaID].RowIndex = _gameBoardAreaList[areaID].RowIndex;
_placeATokenCommands[areaID].ColumnIndex = _gameBoardAreaList[areaID].ColumnIndex;
}
return _placeATokenCommands;
}
private bool ContinueCanExecute()
{
return true;
}
private void ContinueExecute(object obj)
{
_gamePlay.SetupNextGame();
IsGameDecided = false;
CheckHowItIsPlayed();
}
private bool PlaceATokenCanExecute(int areaID)
{
var canExecute = _isAnimationCompleted
&& !(_gameBoard.IsPlayerXWinner || _gameBoard.IsPlayerOWinner)
&& !_gameBoard.IsGameTie
&& !_gameBoardAreaList[areaID].IsOccupied;
if (canExecute)
{
return true;
}
return false;
}
private void PlaceATokenExecute(int areaID)
{
_gamePlay.MakeAMove(areaID);
_gamePlay.MakePossibleNextMove();
if (_gameBoard.IsPlayerXWinner || _gameBoard.IsPlayerOWinner || _gameBoard.IsGameTie)
{
IsGameDecided = true;
}
}
public void InitializeNewGameBoard()
{
_isAnimationCompleted = true;
CommandManager.InvalidateRequerySuggested();
CheckHowItIsPlayed();
}
public void InitializeLastGameBoard()
{
throw new NotImplementedException();
}
private void CheckHowItIsPlayed()
{
if (_gamePlay.IsAIBattle())
{
_gamePlay.EnterAIBattleLoop();
IsGameDecided = true;
}
else
{
_gamePlay.MakePossibleNextMove();
}
}
public void ShowStartAnimation()
{
_gameBoard.ShowStartAnimation();
}
}
}
| 32.141791
| 116
| 0.591595
|
257ed0cbada3d9372125a4156b71b570edce46c6
| 61
|
js
|
JavaScript
|
src/js/index.js
|
Jaehoo-dev/js-calculator
|
94cd24b1193b21920628883f50ec3e1a7a5e09a2
|
[
"MIT"
] | null | null | null |
src/js/index.js
|
Jaehoo-dev/js-calculator
|
94cd24b1193b21920628883f50ec3e1a7a5e09a2
|
[
"MIT"
] | null | null | null |
src/js/index.js
|
Jaehoo-dev/js-calculator
|
94cd24b1193b21920628883f50ec3e1a7a5e09a2
|
[
"MIT"
] | null | null | null |
import Calculator from './calculator.js';
new Calculator();
| 15.25
| 41
| 0.737705
|
b0124eeb58beed3ef75927edf3cb479fa5698423
| 12,472
|
py
|
Python
|
python3/util.freshdns.py
|
cdluminate/MyNotes
|
cf28f2a3fa72723153147e21fed5e7b598baf44f
|
[
"CC0-1.0"
] | null | null | null |
python3/util.freshdns.py
|
cdluminate/MyNotes
|
cf28f2a3fa72723153147e21fed5e7b598baf44f
|
[
"CC0-1.0"
] | null | null | null |
python3/util.freshdns.py
|
cdluminate/MyNotes
|
cf28f2a3fa72723153147e21fed5e7b598baf44f
|
[
"CC0-1.0"
] | null | null | null |
#!/usr/bin/python3
'''
NAME
freshdns - Boost DNS lookup speed by writing records into hosts
SYNOPSYS
freshdns --help
DESCRIPTION
NOTE: Run this script as root. Python >= 3.6 is required.
This script can be used to (1) configure your resolv.conf via terminal
version of dialog; (2) maintain a static lookup table in /etc/hosts.
DNS cache of BIND and DNSMASQ could be polluted by attackers. However,
the attackers cannot change your static lookup table. If a safe DNS
server is not always accessible, this script could be a nice workaround
for you to obtain clean lookup results.
(1) Confiugre resolv.conf
$ sudo freshdns -n
The list of dns server candidates is stored in the _HOSTS_ string.
They are identified by the '-dns' and the '-dns6' substrings.
(2) Maintain the static lookup table
This functionality features a fancy terminal output. If you choose
to dryrun instead of automatically write results into /etc/hosts,
you can also directly copy the screen output into /etc/hosts manually.
The -j option specifies the number of workers for dns lookup. Default
is 0. However with several workers you generally get a significant
speed up.
Reset the hosts file. The default content of hosts is exactly _HOSTS_.
$ sudo freshdns -i
Refresh the hosts file in serial mode.
$ sudo freshdns -r
If you would like to check the result and update hosts by yourself
$ freshdns -v > output
$ sudo mv output /etc/hosts
Grab my firefox histroy and cache all of them with 10 workers
$ freshdns -fv -j10 > output
FILES
~/.freshdnsrc
A plain text file storing a list of your favorite domains. One domain
per line.
VERSION
4.1 (April 1 2018)
SEEALSO
bind(?), dnsmasq(?), dig(?), nslookup(?)
COPYRIGHT
Copyright (C) 2018 Mo Zhou <cdluminate@gmail.com>
MIT LICENSE
TODO
1. how to dump chromium history?
'''
import os
import re
import sys
import time
import socket
import sqlite3
import argparse
import multiprocessing as mp
from glob import glob
from typing import *
from dialog import Dialog
# Apologize. No support for python3 < 3.6
assert(sys.version_info[0] == 3)
assert(sys.version_info[1] >= 6)
_HOSTS_ = f'''# Automatically generated by {__file__} at {time.asctime()}
127.0.0.1 localhost {socket.gethostname()}
# The following lines are desirable for IPv6 capable hosts
::1 localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
# [ IPv4 DNS Servers ]
1.0.0.1 cloudflare-dns-2
1.1.1.1 cloudflare-dns-1
8.8.4.4 google-dns-2
8.8.8.8 google-dns-1
9.9.9.9 quad9-dns-1
74.82.42.42 he-dns-1
208.67.222.222 opendns-dns-1
208.67.220.220 opendns-dns-2
202.38.64.1 ustc-dns-1
202.112.20.131 ustc-dns-2
202.141.160.95 ustc-dns-3
202.141.176.95 ustc-dns-4
114.114.114.114 114-dns-1
# [ IPv6 DNS Servers ]
2001:4860:4860::8888 google-dns6-1
2001:4860:4860::8844 google-dns6-2
2620:0:ccc::2 opendns-dns6-1
'''
class Spinner(object):
'''
spinner
'''
def __init__(self):
self.chars = '|/-\\'
self.iter = 0
def get(self):
self.iter += 1
return self.chars[self.iter % len(self.chars)]
def setResolvConf() -> None:
'''
Note, <resolv.h> :: MAXNS is 3
'''
global _HOSTS_
NS_ALL = [line.strip().split() for line in _HOSTS_.split('\n')
if not line.startswith('#') and '-dns' in line]
#NS_v4 = [t for t in NS_ALL if '-dns-' in t[1]]
#NS_v6 = [t for t in NS_ALL if '-dns6-' in t[1]]
ns_choices = [(t[0], t[1], False) for t in NS_ALL]
d = Dialog(dialog='dialog')
d.set_background_title('Setting Up Name Servers')
# select name servers
code, tags = 'ok', []
while code == 'ok' and not tags:
code, tags = d.checklist("Select your favorite DNS servers.",
height=0, width=0, list_height=0,
choices=ns_choices,
title='resolv.conf',
backtitle='Setting Up Name Servers',
)
if code == 'cancel':
exit(0)
if not tags:
d.msgbox("Note, at least one name server should be specified.")
# write resolv.conf
resolv = [f'# Auto-generated by {__file__} at {time.ctime()}\n']
for tag in tags:
resolv.append(f'nameserver {tag.rjust(64-11)}\n')
try:
with open(ag.resolv, 'w') as f:
f.writelines(resolv)
except PermissionError as e:
print('Error: Are you root? resolv.conf unchanged.')
exit(1)
print('<> Updated resolv.conf')
def getFirefoxPlaces() -> List[str]:
'''
Retrieve a list of places from your firefox histroy (stored in sqlite3).
'''
dbpaths = glob(os.path.expanduser('~/.mozilla/firefox/**/places.sqlite'))
ffplaces = []
for dbpath in dbpaths:
# read data from sqlite3
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
cursor.execute('select url from moz_places;')
places = cursor.fetchall()
conn.close()
# filter results
places = [x[0].split('/') for x in places]
places = [x[2] for x in places if len(x) > 2] # get hostname
places = [x.split(':')[0] for x in places if len(x) > 0] # remove port
places = [x for x in places if not
re.match('([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9])', x)]
# don't lookup an IP address
ffplaces += places
return list(set(ffplaces))
def getChromiumPlaces() -> List[str]:
raise NotImplementedError
def getAddrs(domain: str):
'''
This implementation is somewhat questionable. Anyway it works.
'''
#print(socket.getaddrinfo(domain, 80))
addrinfo = []
try:
addrinfo = socket.getaddrinfo(domain, 80)
except socket.gaierror as e:
pass
if len(addrinfo) == 0:
try:
addrinfo = socket.getaddrinfo(domain, 443)
except socket.gaierror as e:
pass
if len(addrinfo) == 0:
return None # Give up trying
addrs = set(addrinfo[i][-1][0] for i in range(len(addrinfo)))
return addrs
def freshDNS(domains: List[str]) -> None:
'''
Refresh the DNS lookup results in /etc/hosts
'''
global _HOSTS_
if ag.verbose:
print(_HOSTS_)
if ag.reset or ag.refresh:
with open(ag.hosts, 'w') as f:
f.write(_HOSTS_)
if ag.reset:
raise SystemExit()
print(f'\0337\x1b[1;36m# Found {len(domains)} domains.\x1b[m',
file=sys.stderr)
alladdrs = [] # List[Tuple(addr, domain)]
if 0 == ag.workers:
# Serial lookup
for i, domain in enumerate(sorted(domains), 1):
print(f'\033[K\0337\x1b[1;36m# Progress',
f' {i} / {len(domains)} ({i*100./len(domains):.1f}%)',
f'| \033[1;33m{domain}', end='\x1b[m\0338',
file=sys.stderr)
sys.stderr.flush()
addrs = getAddrs(domain)
if addrs is None: continue
for addr in addrs:
alladdrs.append((addr, domain))
if ag.verbose:
print(f'{addr}' + str(domain).rjust(79-len(addr)))
else:
# Parallel lookup
Qin, Qout = mp.Queue(), mp.Queue()
#Lin, Lout = mp.Lock(), mp.Lock()
for domain in sorted(domains):
Qin.put(domain)
def worker_wrapper(qin: mp.Queue, qout: mp.Queue) -> None:
try:
while True:
if qin.empty(): return
domain = qin.get()
addrinfo = getAddrs(domain)
qout.put([addrinfo, domain])
except KeyboardInterrupt as e:
os._exit(1)
# spawn workers
workers = [mp.Process(target=worker_wrapper,
args=(Qin, Qout)) for _ in range(ag.workers)]
for worker in workers: worker.start()
outctr = len(alladdrs)
spinner = Spinner()
# wait for workers to get things done
while True:
if outctr == len(domains) or not any([w.is_alive() for w in workers]):
print(f'\033[K\x1b[1;36m# Lookup finished.',
f'Pulling down the workers.', end='\x1b[m\n',
file=sys.stderr)
for w in workers:
w.join(timeout=0.1)
w.terminate()
break
else:
while Qout.qsize() > 0:
addrs, domain = Qout.get()
if addrs is None: continue
for addr in addrs:
alladdrs.append((addr, domain))
if ag.verbose:
print(f'{addr}' + str(domain).rjust(79-len(addr)))
if outctr < len(alladdrs):
outctr = len(set([name for _, name in alladdrs]))
print(f'\033[K\0337\x1b[1;36m# Progress',
f' {outctr} / {len(domains)} ({outctr*100./len(domains):.1f}%)',
f'\033[1;33m', spinner.get(), end='\x1b[m\0338',
file=sys.stderr)
sys.stderr.flush()
time.sleep(1e-3)
# write the results to disk
for addr, name in alladdrs:
_HOSTS_ += f'{addr}' + str(name).rjust(79-len(addr)) + '\n'
if ag.write or ag.refresh:
with open(ag.hosts, 'w') as f:
f.write(_HOSTS_)
if __name__ == '__main__':
ag = argparse.ArgumentParser()
ag.add_argument('-w', '--write', default=False,
action='store_true', help='write result to /etc/hosts')
ag.add_argument('-i', '--reset', default=False,
action='store_true', help='reset /etc/hosts')
ag.add_argument('-r', '--refresh', default=False,
action='store_true', help='refresh /etc/hosts')
ag.add_argument('-v', '--verbose', default=False,
action='store_true', help='verbose')
ag.add_argument('-H', '--hosts', type=str, default='/etc/hosts')
ag.add_argument('-d', '--domains', type=str,
default=f'{os.getenv("HOME")}/.freshdnsrc')
ag.add_argument('-f', '--firefox', default=False, action='store_true')
ag.add_argument('-n', '--ns', default=False, action='store_true',
help='Change name servers in resolv.conf')
ag.add_argument('--resolv', type=str, default='/etc/resolv.conf')
ag.add_argument('-j', '--workers', type=int, default=0)
# we don't explicitly pass ag to functions, but ag is used by them.
ag = ag.parse_args()
if ag.ns:
# if -n is specified, setup resolv.conf and exit
setResolvConf()
else:
# do straightforward dns cacheing
domains = []
# Read configuration file for domain list
if os.path.exists(ag.domains):
with open(ag.domains, 'r') as f:
domains += [line.strip() for line in f.readlines()]
# Get more domains from firefox history
if ag.firefox:
domains += getFirefoxPlaces()
# FIXME: if ag.chromium:
# de-dup and remove totally invalid ones
domains = list(set(domains))
domains = [x for x in domains if len(x) > 0]
domains = [x for x in domains if '.' in x]
try:
freshDNS(domains)
except KeyboardInterrupt:
exit(1)
| 32.563969
| 90
| 0.532152
|
7959912b076a6feb9926ab801e3763a6bf66d098
| 924
|
php
|
PHP
|
application/views/test.php
|
rickyrivaldo98/sistemBMKG
|
e987fef7dc27479bb398b270368dca2fc9673238
|
[
"MIT"
] | 5
|
2020-02-14T16:54:52.000Z
|
2020-05-12T14:55:43.000Z
|
application/views/test.php
|
rickyrivaldo98/sistemBMKG
|
e987fef7dc27479bb398b270368dca2fc9673238
|
[
"MIT"
] | null | null | null |
application/views/test.php
|
rickyrivaldo98/sistemBMKG
|
e987fef7dc27479bb398b270368dca2fc9673238
|
[
"MIT"
] | 3
|
2020-03-20T13:14:04.000Z
|
2020-12-11T08:22:23.000Z
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<br>
<button id="tombol">
klik
</button>
<script>
var base_url = '<?php echo base_url(); ?>';
document.querySelector("#tombol").addEventListener('click', function() {
swal.fire({
icon: 'success',
title: 'Your work has been saved',
text: 'kontolll',
showConfirmButton: true,
});
window.setTimeout(function() {
window.location.replace(base_url)
}, 3000);
});
</script>
<script src="<?php echo base_url() . 'assets/js/package/dist/sweetalert2.all.min.js' ?>"></script>
</body>
</html>
| 20.086957
| 102
| 0.528139
|
a90d312dc9b5b770411f430e471d6d4d37a20c67
| 1,638
|
swift
|
Swift
|
Feature/Auth/Sources/Classes/AuthViewController.swift
|
SunnyDayDev/Rich-Harvest
|
4b112eba658aa4f847f2522183444e283b40d9c5
|
[
"Apache-2.0"
] | null | null | null |
Feature/Auth/Sources/Classes/AuthViewController.swift
|
SunnyDayDev/Rich-Harvest
|
4b112eba658aa4f847f2522183444e283b40d9c5
|
[
"Apache-2.0"
] | null | null | null |
Feature/Auth/Sources/Classes/AuthViewController.swift
|
SunnyDayDev/Rich-Harvest
|
4b112eba658aa4f847f2522183444e283b40d9c5
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by Александр Цикин on 2018-11-20.
//
import Foundation
import RxSwift
import RxCocoa
import RichHarvest_Core_Core
public class AuthViewController: NSViewController {
@IBOutlet weak var personalTokenTextField: NSTextField!
@IBOutlet weak var accountIdTextField: NSTextField!
@IBOutlet weak var applyButton: NSButton!
var viewModel: AuthViewModel!
private let dispose = DisposeBag()
deinit {
Log.debug("Deinited")
}
public override func viewDidLoad() {
super.viewDidLoad()
guard let viewModel = self.viewModel else { return }
applyButton.rx.tap.bind(to: viewModel.applyTap).disposed(by: dispose)
personalTokenTextField.rx.text
.map { $0 ?? "" }
.filter { viewModel.personalToken.value != $0 }
.bind(to: viewModel.personalToken)
.disposed(by: dispose)
viewModel.personalToken
.filter { [weak self] in self?.personalTokenTextField.stringValue != $0 }
.bind(to: personalTokenTextField.rx.text)
.disposed(by: dispose)
accountIdTextField.rx.text
.map { $0 ?? "" }
.filter { viewModel.accountId.value != $0 }
.bind(to: viewModel.accountId)
.disposed(by: dispose)
viewModel.accountId
.filter { [weak self] in self?.accountIdTextField.stringValue != $0 }
.bind(to: accountIdTextField.rx.text)
.disposed(by: dispose)
}
}
extension AuthViewController {
func inject(viewModel: AuthViewModel) {
self.viewModel = viewModel
}
}
| 24.818182
| 85
| 0.623321
|
96e140b811ac9bf18c3e866196c5875b54854212
| 385
|
sh
|
Shell
|
sys/path-add-cmd.sh
|
fxtaoo/cmd
|
195ba62a0a2bc48b69b44f1ebf79e4e8531e2cf6
|
[
"MIT"
] | null | null | null |
sys/path-add-cmd.sh
|
fxtaoo/cmd
|
195ba62a0a2bc48b69b44f1ebf79e4e8531e2cf6
|
[
"MIT"
] | null | null | null |
sys/path-add-cmd.sh
|
fxtaoo/cmd
|
195ba62a0a2bc48b69b44f1ebf79e4e8531e2cf6
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env bash
# 指定文件夹路径添加到 PATH (递归),文件添加可执行权限
# $1 为指定 cmd 绝对路径
function add_path(){
local cmd_path=$1
if [[ ! $PATH =~ $cmd_path ]] ; then
PATH="$PATH:$cmd_path"
fi
for e in "$cmd_path"/* ; do
if [[ -d $e && ! $PATH =~ $e ]] ; then
PATH="$PATH:$e"
add_path $e
else
if [[ ! -x $e ]] ; then
chmod u+x $e
fi
fi
done
}
| 19.25
| 43
| 0.493506
|
146322136723877d6af453523f18245cad44c75c
| 380
|
ts
|
TypeScript
|
src/middlewares/session.ts
|
delta-kor/xhat
|
bd308bf305f5d86c8929ddb8acbbc9b1d66c86ad
|
[
"MIT"
] | 1
|
2020-10-09T06:24:36.000Z
|
2020-10-09T06:24:36.000Z
|
src/middlewares/session.ts
|
delta-kor/xhat
|
bd308bf305f5d86c8929ddb8acbbc9b1d66c86ad
|
[
"MIT"
] | null | null | null |
src/middlewares/session.ts
|
delta-kor/xhat
|
bd308bf305f5d86c8929ddb8acbbc9b1d66c86ad
|
[
"MIT"
] | null | null | null |
import { Application, NextFunction } from 'express';
import { ExpressRequest, ExpressResponse } from '@interfaces/express';
export default class Session {
static mount(express: Application): Application {
express.use((req: ExpressRequest, res: ExpressResponse, next: NextFunction) => {
req.ticket = req.session.ticket;
next();
});
return express;
}
}
| 29.230769
| 84
| 0.694737
|
a3d147d5557684f357a0af5de135653a66b76815
| 1,755
|
ps1
|
PowerShell
|
scripting/switch.ps1
|
bheckel/code
|
98309e8aa145901e49460546643c911eaaff54e6
|
[
"Apache-2.0"
] | 1
|
2019-08-11T00:39:34.000Z
|
2019-08-11T00:39:34.000Z
|
scripting/switch.ps1
|
bheckel/code
|
98309e8aa145901e49460546643c911eaaff54e6
|
[
"Apache-2.0"
] | null | null | null |
scripting/switch.ps1
|
bheckel/code
|
98309e8aa145901e49460546643c911eaaff54e6
|
[
"Apache-2.0"
] | 1
|
2020-07-28T05:58:47.000Z
|
2020-07-28T05:58:47.000Z
|
##############################################################################
# Name: switch.ps1
#
# Summary: Powershell switch control (i.e. non-cmdlet) statement
#
# Adapted: Fri 15 Jan 2010 10:32:46 (Bob Heckel -- Windows PowerShell in Action)
##############################################################################
# Scalars:
switch ( 4 ) {
1 { "One" }
2 { "two" }
2 { "also two" } # both 2s print
3 { "Three" }
4 { "four" }
{$_ -gt 3} { 'large' }
default {"none of the above"}
}
switch ( 'abc' ) {
a { 'just a' }
ABC { 'abc case insensitive, use -c(ase) if needed' }
# silent exit if no match anything
}
switch -wildcard ( 'NFL' ) {
a { 'just a' }
ABC { 'abc case insensitive, use -c(ase) if needed' }
n* { "$_ starts with n" }
}
# See regex.ps1 for capturing, etc.
switch -regex ( 'NFL' ) {
a { 'just a' }
ABC { 'abc case insensitive, use -c(ase) if needed' }
'..l$' { "$_ three chars ends with l" }
}
# Collections:
switch ( 1,2,3,4,5,6 ) {
###{$_ % 2} {"Odd $_"; continue} # stop matching, go to top of loop
{$_ % 2} {"Odd $_"; break} # exit switch
4 {"FOUR"}
default {"Even $_"}
}
$dll=$txt=$log=0
switch -wildcard (dir c:\temp) {
*.dll {$dll+=$_.length; continue}
*.txt {$txt+=$_.length; continue}
*.log {$log+=$_.length; continue}
}
"found DLL: $dll TXT: $txt LOG: $log"
switch -regex -file c:\windows\windowsupdate.log { # -file gives non-slurp, may be more efficient
'START.*Finding updates.*AutomaticUpdates' {$au++}
'START.*Finding updates.*Defender' {$du++}
'START.*Finding updates.*SMS' {$su++}
}
"Automatic:$au Defender:$du SMS:$su"
| 24.71831
| 100
| 0.492877
|
c581881724d7d57456379dfafba7149773c62420
| 4,883
|
css
|
CSS
|
ChromeExtension/calendar/styles/wannianli-common.css
|
sun2dan/toolkit
|
09f2dc3d3dc845aded0a3a995aedcbb5f4a8e4fd
|
[
"MIT"
] | null | null | null |
ChromeExtension/calendar/styles/wannianli-common.css
|
sun2dan/toolkit
|
09f2dc3d3dc845aded0a3a995aedcbb5f4a8e4fd
|
[
"MIT"
] | null | null | null |
ChromeExtension/calendar/styles/wannianli-common.css
|
sun2dan/toolkit
|
09f2dc3d3dc845aded0a3a995aedcbb5f4a8e4fd
|
[
"MIT"
] | null | null | null |
/* icon */
.lunar-box {
background:url(../images/sx.png) no-repeat;
}
.field-botton .arrow{
background:url(../images/date_nav.png) no-repeat;
}
/* 表单元素 */
.field-input{border:1px solid;border-color: silver #D9D9D9 #D9D9D9;height:14px;line-height:14px;width:100%;padding:2px;}
.field-textarea{border:1px solid;border-color: silver #D9D9D9 #D9D9D9;height:200px;width:100%;padding:2px;resize:none;}
.field-botton{border:1px solid rgba(0,0,0,0.1);border-radius:2px;background-color:#f5f5f5;color:#444;cursor:pointer;display:inline-block;font-weight:bold;height:25px;line-height:25px;padding:0 8px;vertical-align:middle;}
.field-botton:hover{border:1px solid #c6c6c6;background-color:#f8f8f8;box-shadow:0px 1px 1px rgba(0,0,0,0.1);}
.field-botton .arrow{height:15px;width:9px;display:block;margin-top:5px;}
/* content */
#content{width:783px;margin:15px;}
.wnl-wrap {background:#fff;float:left;margin-right:10px;}
.wnl-wrap .hd {position:relative;}
.wnl-wrap .hd .lunar-box{width:256px;float:left;padding-left:96px;height:62px;padding-top:23px;font-size:20px;color:#ff6600;font-weight:bold;}
.wnl-wrap .hd .lunar-box #sm {font-size:24px;display:inline-block;vertical-align:baseline;}
.wnl-wrap .hd .date-nav {width:191px;float:right;margin-top:29px;}
.wnl-wrap .hd .date-nav .pre-year .arrow{background-position:0 0;width:14px;}
.wnl-wrap .hd .date-nav .next-year .arrow{background-position:0 -15px;width:14px;}
.wnl-wrap .hd .date-nav .pre-month .arrow{background-position:0 -30px;}
.wnl-wrap .hd .date-nav .next-month .arrow{background-position:0 -45px;}
.wnl-wrap .hd .date-nav .pre-year{border-radius:2px 0 0 2px;}
.wnl-wrap .hd .date-nav .next-year{border-radius:0 2px 2px 0;margin-left:-5px;margin-right:5px;}
.wnl-wrap .hd .date-nav .pre-month{border-radius:2px 0 0 2px;}
.wnl-wrap .hd .date-nav .next-month{border-radius:0 2px 2px 0;margin-left:-5px;margin-right:5px;}
.wnl-wrap .hd .date-nav .cur-day {background-position:-91px 0;}
.wnl-wrap .bd {width:560px;}
.wnl-wrap .bd .week .weekend {color:#ff6600;}
.wnl-wrap .bd .week tr td {width:86px;height:30px;color:#555;font-size:12px;text-align:left;}
.wnl-wrap .bd .date-box li {width:79px;height:54px;float:left;border:1px solid #DDD;margin:-1px 0 0 -1px;cursor:pointer;}
.wnl-wrap .bd .date-box li em {font-weight:bold;font-family:Arial;color:#4d4d4d;font-size:20px;padding-left:12px;}
.wnl-wrap .bd .date-box li p {padding-left:5px;}
.wnl-wrap .bd .date-box li .inner {height:54px;position:relative;}
.wnl-wrap .bd .date-box li .note-icon{background-color:#ff6600;height:5px;width:5px;top:2px;right:2px;}
.wnl-wrap .bd .date-box .mouseover {border:1px solid #ffe186;}
.wnl-wrap .bd .date-box .mouseover .inner {outline:1px solid #ffe186;background:#fff8e8;}
.wnl-wrap .bd .date-box .selected .inner {background-color:#fff8e8;outline:1px solid #ffe186;}
.wnl-wrap .bd .date-box .today .inner {outline:1px solid #ffce39;background:#ffe186;}
.wnl-wrap .bd .date-box .note .note-icon{position:absolute;}
.sx0 {background-position:0 0;}
.sx1 {background-position:0 -105px;}
.sx2 {background-position:0 -214px;}
.sx3 {background-position:0 -328px;}
.sx4 {background-position:0 -448px;}
.sx5 {background-position:0 -590px;}
.sx6 {background-position:0 -727px;}
.sx7 {background-position:0 -879px;}
.sx8 {background-position:0 -1018px;}
.sx9 {background-position:0 -1168px;}
.sx10 {background-position:0 -1314px;}
.sx11 {background-position:0 -1453px;}
.pop-common {position:absolute;left:20px;top:-9999px;visibility:hidden;}
.pop-common .content {position:relative;border:1px solid #ccc;background:#fff;box-shadow: 0 2px 4px rgba(0,0,0,.2);width:290px;}
.pop-wnl .jieri-info {height:24px;line-height:24px;background:#fffaec;text-align:center;color:#e65b16;border-bottom:1px solid #DDD;}
.pop-wnl .date-infos {margin:0 3px;padding:0;}
.pop-wnl .day {float:left;width:55px;height:48px;line-height:48px;text-align:center;color:#1b7ca6;font-size:30px;font-weight:bold;}
.pop-wnl .guolli {font-weight:bold;display:inline-block;padding-top:5px;}
.pop-wnl .info {line-height:28px;padding:6px;}
.pop-wnl .info dt {float:left;}
.pop-wnl .info dd {margin-left:20px;clear:right;}
.pop-arr-wrap .arr-top-bg {height:0;width:0;overflow:hidden;border-left:6px dashed transparent;border-right:6px dashed transparent;border-top:6px solid #ccc;border-bottom:6px dashed transparent;position:absolute;left:36px;bottom:-12px;}
.pop-arr-wrap .arr-top {height:0;width:0;overflow:hidden;border-left:6px dashed transparent;border-right:6px dashed transparent;border-top:6px solid #fff;border-bottom:6px dashed transparent;position:absolute;left:36px;bottom:-11px;}
.notes-wrap{float:left;background-color:rgba(243,243,243,.85);border:1px solid #DDD;height:339px;padding:10px;margin-top:29px;width:182px;}
.notes-wrap .title{font-size:16px;margin-bottom:10px;}
.notes-wrap td{padding:5px 0;}
.notes-wrap .note-key{width:36px;vertical-align:top;}
| 61.0375
| 236
| 0.74831
|
6afa3961aaa975d02416a760e9f65e1e6375cdf2
| 1,800
|
c
|
C
|
src/Technosoftware/Server/System/OpcSdk_i.c
|
AkatorMr/opc-daae-server
|
7d56e4603064b53476d3c0971a4d873066fba65f
|
[
"Info-ZIP"
] | null | null | null |
src/Technosoftware/Server/System/OpcSdk_i.c
|
AkatorMr/opc-daae-server
|
7d56e4603064b53476d3c0971a4d873066fba65f
|
[
"Info-ZIP"
] | null | null | null |
src/Technosoftware/Server/System/OpcSdk_i.c
|
AkatorMr/opc-daae-server
|
7d56e4603064b53476d3c0971a4d873066fba65f
|
[
"Info-ZIP"
] | 1
|
2021-04-15T01:08:29.000Z
|
2021-04-15T01:08:29.000Z
|
/*
* Copyright (c) 2020 Technosoftware GmbH. All rights reserved
* Web: https://technosoftware.com
*
* The source code in this file is covered under a dual-license scenario:
* - Owner of a purchased license: SCLA 1.0
* - GPL V3: everybody else
*
* SCLA license terms accompanied with this source code.
* See https://technosoftware.com/license/Source_Code_License_Agreement.pdf
*
* GNU General Public License as published by the Free Software Foundation;
* version 3 of the License are accompanied with this source code.
* See https://technosoftware.com/license/GPLv3License.txt
*
* This source code is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifndef __OPCSDK_I_C_
#define __OPCSDK_I_C_
#ifdef _WIN32
#include "inc32\opccomn_i.c" // IIDs and CLSIDs for OPC Common Definitions
#include "inc32\OpcEnum_i.c" // IIDs and CLSIDs for OPC Server List / Enumerator
#include "inc32\opcauto10a_i.c" // IIDs and CLSIDs for OPC 1.0A Automation Data Access
#include "inc32\opcda_i.c" // IIDs and CLSIDs for OPC Data Access
#include "inc32\opc_ae_i.c" // IIDs and CLSIDs for OPC Alarsm & Events
#else
#ifdef _WIN64
#include "inc64\opccomn_i.c" // IIDs and CLSIDs for OPC Common Definitions
#include "inc64\OpcEnum_i.c" // IIDs and CLSIDs for OPC Server List / Enumerator
#include "inc64\opcda_i.c" // IIDs and CLSIDs for OPC Data Access
#include "inc64\opc_ae_i.c" // IIDs and CLSIDs for OPC Alarsm & Events
#else
#error "Platform not supported"
#endif // _WIN64
#endif // _WIN32
#endif // __OPCSDK_I_C_
| 36.734694
| 97
| 0.688333
|
58c14c871e792deeae0111fcee066a758cfc1320
| 1,687
|
css
|
CSS
|
public/dist/css/login.css
|
pubsajib/inventory
|
f37de2385c4f30742ca41b6d8db7cfbadf285696
|
[
"MIT"
] | null | null | null |
public/dist/css/login.css
|
pubsajib/inventory
|
f37de2385c4f30742ca41b6d8db7cfbadf285696
|
[
"MIT"
] | null | null | null |
public/dist/css/login.css
|
pubsajib/inventory
|
f37de2385c4f30742ca41b6d8db7cfbadf285696
|
[
"MIT"
] | null | null | null |
.login-page,.register-page{background: #355D7E;}
.login-box-body .form-control-feedback, .register-box-body .form-control-feedback {
color: #fff;
}
.login-intro {
color: #e0e0e0;
font-size: 25px;
text-align: center;
line-height: 1.2;
font-family: 'Titillium Web', sans-serif;
}
.login-box{
position: relative;
width: 400px;
}
.login-top-logo {
max-width: 150px;
margin: 0 auto;
display: block;
}
.signIn-intro{
color: #e0e0e0;
margin-bottom: 25px;
font-size: 20px;
font-family: 'Roboto', sans-serif;
margin-top: 30px;
text-align: center;
}
.login-box-body, .register-box-body {
background: transparent;
}
.login-box-body .form-control {
border-radius: 0;
box-shadow: none;
border-color: #c7c7c7 !important;
background: transparent !important;
border-top: 0;
border-right: 0;
border-left: 0;
color: #fff;
}
/* Change Autocomplete styles in Chrome*/
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus
input:-webkit-autofill,
textarea:-webkit-autofill,
textarea:-webkit-autofill:hover
textarea:-webkit-autofill:focus,
select:-webkit-autofill,
select:-webkit-autofill:hover,
select:-webkit-autofill:focus {
transition: background-color 5000s ease-in-out 0s;
-webkit-text-fill-color: #fff;
}
.login-btn{
margin-top: 25px;
}
.login-box-body .form-control::-webkit-input-placeholder { /* Chrome/Opera/Safari */
color: #fff;
}
.login-box-body .form-control::-moz-placeholder { /* Firefox 19+ */
color: #fff;
}
.login-box-body .form-control:-ms-input-placeholder { /* IE 10+ */
color: #fff;
}
.login-box-body .form-control:-moz-placeholder { /* Firefox 18- */
color: #fff;
}
| 22.493333
| 84
| 0.687018
|
a3d3462450f9299dcb15da2e51856f94d531028c
| 663
|
java
|
Java
|
src/ueshooting/system/Deg.java
|
tinaxd/ueshooting
|
9868647101a7c3e2f841cb9f498c3556c716cb6a
|
[
"BSD-3-Clause"
] | 1
|
2019-06-25T14:13:24.000Z
|
2019-06-25T14:13:24.000Z
|
src/ueshooting/system/Deg.java
|
tinaxd/ueshooting
|
9868647101a7c3e2f841cb9f498c3556c716cb6a
|
[
"BSD-3-Clause"
] | 1
|
2020-01-02T08:20:58.000Z
|
2020-01-02T08:20:58.000Z
|
src/ueshooting/system/Deg.java
|
tinaxd/ueshooting
|
9868647101a7c3e2f841cb9f498c3556c716cb6a
|
[
"BSD-3-Clause"
] | 1
|
2019-06-25T14:14:50.000Z
|
2019-06-25T14:14:50.000Z
|
package ueshooting.system;
/**
* trigonometric functions for degree
*
*/
public class Deg {
public static double sin(double theta){
return Math.sin(toRad(theta));
}
public static double cos(double theta){
return Math.cos(toRad(theta));
}
public static double tan(double theta){
return Math.tan(toRad(theta));
}
public static double atan(double value){
return toDeg(Math.atan(value));
}
public static double atan2(double y, double x){
return toDeg(Math.atan2(y,x));
}
public static double toRad(double value) {
return value / 360 * Math.PI * 2;
}
public static double toDeg(double value) {
return value * 360 / Math.PI / 2;
}
}
| 20.71875
| 48
| 0.692308
|
a920ff5d07d6ea8a3c55c16ec47115f4096a9c83
| 1,850
|
css
|
CSS
|
css/style.css
|
wastedideas/evklid-site
|
e954f89efca06bd7138771b46076948697ac80e4
|
[
"MIT"
] | null | null | null |
css/style.css
|
wastedideas/evklid-site
|
e954f89efca06bd7138771b46076948697ac80e4
|
[
"MIT"
] | null | null | null |
css/style.css
|
wastedideas/evklid-site
|
e954f89efca06bd7138771b46076948697ac80e4
|
[
"MIT"
] | null | null | null |
html {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
body {
min-width: 320px;
margin: 0;
background-color: #FFFFFF; /* под проект */
font-family: 'Montserrat', sans-serif; /* в "" свой шрифт под проект*/
color: #333333;
font-size: 16px;
font-weight: 400;
line-height: 1;
}
button, input {
font: inherit;
}
img {
max-width: 100%;
height: auto;
}
a {
text-decoration: none;
color: inherit;
}
ul {
list-style: none;
}
h1, h2, h3, p, ul {
padding: 0;
margin: 0;
}
/* container */
.container {
max-width: 1770px; /*под проект*/
margin: 0 auto;
}
.visually-hidden {
position: absolute !important;
clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
clip: rect(1px, 1px, 1px, 1px);
padding: 0 !important;
border: 0 !important;
height: 1px !important;
width: 1px !important;
overflow: hidden;
}
/* при работе с float */
.clearfix::after {
content: "";
display: table;
clear: both;
}
.section-header {
font-weight: 400;
font-size: 48px;
line-height: 59px;
color: #333333;
}
/* Состояние focus для элементов */
a:focus,
input:focus,
textarea:focus,
button:focus {
outline: 2px solid #c2c2c2;
}
/* Отключение outline для состояния active элементов: */
a:active ,
input:active ,
textarea:active ,
button:active {
outline: none;
}
@media (max-width: 1800px) {
.container {
max-width: 1600px;
}
}
@media (max-width: 1650px) {
.container {
max-width: 1250px;
}
}
@media (max-width: 1300px) {
.container {
max-width: 1076px;
}
}
@media (max-width: 1140px) {
.container {
max-width: 924px;
}
}
@media (max-width: 992px) {
.container {
max-width: 768px;
}
}
@media (max-width: 767px) {
.container {
max-width: calc(100% - 30px);
}
.section-header {
font-size: 24px;
line-height: 30px;
}
}
| 13.703704
| 72
| 0.610811
|
5afb57daa6134e68f2ae7898d4deb4c87c1b5cb2
| 4,162
|
cs
|
C#
|
XMLCLRLib/XmlClrLan/Container/Config/ModuleMethodCallElement.cs
|
ridgew/practicemakesperfect
|
8b8f00e7564a502b24550e47ecf21eb7d238a0e1
|
[
"MIT"
] | 1
|
2019-06-16T14:22:06.000Z
|
2019-06-16T14:22:06.000Z
|
XMLCLRLib/XmlClrLan/Container/Config/ModuleMethodCallElement.cs
|
ridgew/practicemakesperfect
|
8b8f00e7564a502b24550e47ecf21eb7d238a0e1
|
[
"MIT"
] | null | null | null |
XMLCLRLib/XmlClrLan/Container/Config/ModuleMethodCallElement.cs
|
ridgew/practicemakesperfect
|
8b8f00e7564a502b24550e47ecf21eb7d238a0e1
|
[
"MIT"
] | 1
|
2020-10-19T17:43:21.000Z
|
2020-10-19T17:43:21.000Z
|
using System;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
namespace XmlClrLan
{
[Serializable]
[XmlRoot(ElementName = "Call")]
public class ModuleMethodCallElement : ModuleBuildStepElement
{
public ModuleMethodCallElement()
{
}
public ModuleMethodCallElement(string name, TypeValueElement[] args)
{
MethodName = name;
Parameters = new ModuleConstructorElement
{
Arguments = args
};
}
[XmlAttribute(AttributeName = "fun")]
public string MethodName { get; set; }
[XmlElement(ElementName = "arg")]
public ModuleConstructorElement Parameters { get; set; }
/// <summary>
/// 当绑定为静态类型时全称
/// </summary>
[XmlAttribute(AttributeName = "staticType")]
public string StaticType { get; set; }
/// <summary>
/// 在作用域下执行
/// </summary>
/// <param name="instanceType">实例类型</param>
/// <param name="instance">The instance.</param>
/// <param name="scope">执行代码作用区间</param>
public override bool InvokeInScope(Type instanceType, object instance, ModuleRunScope scope = null)
{
if (!string.IsNullOrEmpty(StaticType))
{
instanceType = TypeCache.GetRuntimeType(StaticType);
instance = null;
}
Type[] argTypes = new Type[0];
if (Parameters != null)
argTypes = Parameters.GetArgumentTypes();
MethodInfo fun = instanceType.GetMethod(MethodName, argTypes);
if (fun == null)
{
throw new System.Configuration.ConfigurationErrorsException("方法[" + MethodName + "]在类型(" + instanceType.FullName + ")中未找到,请确保系统配置正确!");
}
else
{
object[] args = (Parameters == null) ? null : Parameters.GetArguments(scope);
object ret = fun.Invoke(instance, args);
scope.StepSwap = ret;
}
return false;
}
/// <summary>
/// 从对象的 XML 表示形式生成该对象。
/// </summary>
/// <param name="reader">从中对对象进行反序列化的 <see cref="T:System.Xml.XmlReader" /> 流。</param>
public override void ReadXml(XmlReader reader)
{
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
if (reader.Name == "fun")
{
MethodName = reader.Value;
}
else if (reader.Name == "staticType")
{
StaticType = reader.Value;
}
}
}
int entDepth = reader.Depth;
while (reader.Read() && reader.Depth >= entDepth)
{
Parameters = reader.ObjectReadXml<ModuleConstructorElement>();
}
}
/// <summary>
/// 将对象转换为其 XML 表示形式。
/// </summary>
/// <param name="writer">对象要序列化为的 <see cref="T:System.Xml.XmlWriter" /> 流。</param>
public override void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("fun", MethodName);
if (!string.IsNullOrEmpty(StaticType))
{
writer.WriteAttributeString("staticType", StaticType.ToString());
}
if (Parameters != null)
Parameters.ObjectWriteXml(writer);
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
if (base.Module != null)
return string.Format("Type:{0}, MethodName:{1}", base.Module.Type, MethodName);
return string.Format("Type:{0}, MethodName:{1}", typeof(ModuleMethodCallElement).FullName, MethodName);
}
}
}
| 32.263566
| 151
| 0.51802
|
0d6f95e6d3bb3234149def516d018711ce1e2f46
| 584
|
h
|
C
|
scipy/signal/S_bspline_util.h
|
jasonmccampbell/scipy-refactor
|
52708e04bca51e7043248d56383780b1e51e0d8f
|
[
"BSD-3-Clause"
] | 8
|
2015-10-07T00:37:32.000Z
|
2022-01-21T17:02:33.000Z
|
scipy/signal/S_bspline_util.h
|
enthought/scipy-refactor
|
52708e04bca51e7043248d56383780b1e51e0d8f
|
[
"BSD-3-Clause"
] | null | null | null |
scipy/signal/S_bspline_util.h
|
enthought/scipy-refactor
|
52708e04bca51e7043248d56383780b1e51e0d8f
|
[
"BSD-3-Clause"
] | 8
|
2015-05-09T14:23:57.000Z
|
2018-11-15T05:56:00.000Z
|
#include <npy_math.h>
#if defined(__cplusplus)
extern "C" {
#endif
int S_cubic_spline2D(float*, float*, int, int, double, npy_intp*, npy_intp*, float);
int S_quadratic_spline2D(float*, float*, int, int, double, npy_intp*, npy_intp*, float);
int S_IIR_forback1(float, float, float*, float*, int, int, int, float);
int S_IIR_forback2(double, double, float*, float*, int, int, int, float);
int S_separable_2Dconvolve_mirror(float*, float*, int, int, float*, float*,
int, int, npy_intp*, npy_intp*);
#if defined(__cplusplus)
} /* extern "C" */
#endif
| 34.352941
| 88
| 0.671233
|
453a1d3ca2b0c7f3f1c03404de20630512f74973
| 3,208
|
go
|
Go
|
whparse/query.go
|
go-webhelp/webhelp
|
3f30213e4c4905711afccf9916cfed6d04c68f5f
|
[
"Apache-2.0"
] | 36
|
2017-01-12T04:03:56.000Z
|
2019-11-22T08:30:26.000Z
|
whparse/query.go
|
jtolds/webhelp
|
3f30213e4c4905711afccf9916cfed6d04c68f5f
|
[
"Apache-2.0"
] | null | null | null |
whparse/query.go
|
jtolds/webhelp
|
3f30213e4c4905711afccf9916cfed6d04c68f5f
|
[
"Apache-2.0"
] | 5
|
2017-01-05T07:13:19.000Z
|
2018-07-13T19:23:36.000Z
|
// Copyright (C) 2016 JT Olds
// See LICENSE for copying information
// Package whparse provides some convenient input parsing helpers.
package whparse // import "gopkg.in/webhelp.v1/whparse"
import (
"strconv"
"strings"
)
// ParseBool is like strconv.ParseBool but also understands yes/no
func ParseBool(val string) (bool, error) {
val = strings.ToLower(val)
switch val {
case "no", "n":
return false, nil
case "yes", "y":
return true, nil
}
return strconv.ParseBool(val)
}
// OptInt64 parses val and returns the integer value in question, unless
// parsing fails, in which case the default def is returned.
func OptInt64(val string, def int64) int64 {
if val == "" {
return def
}
rv, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return def
}
return rv
}
// OptUint64 parses val and returns the integer value in question, unless
// parsing fails, in which case the default def is returned.
func OptUint64(val string, def uint64) uint64 {
if val == "" {
return def
}
rv, err := strconv.ParseUint(val, 10, 64)
if err != nil {
return def
}
return rv
}
// OptInt32 parses val and returns the integer value in question, unless
// parsing fails, in which case the default def is returned.
func OptInt32(val string, def int32) int32 {
if val == "" {
return def
}
rv, err := strconv.ParseInt(val, 10, 32)
if err != nil {
return def
}
return int32(rv)
}
// OptUint32 parses val and returns the integer value in question, unless
// parsing fails, in which case the default def is returned.
func OptUint32(val string, def uint32) uint32 {
if val == "" {
return def
}
rv, err := strconv.ParseUint(val, 10, 32)
if err != nil {
return def
}
return uint32(rv)
}
// OptInt parses val and returns the integer value in question, unless
// parsing fails, in which case the default def is returned.
func OptInt(val string, def int) int {
if val == "" {
return def
}
rv, err := strconv.ParseInt(val, 10, 0)
if err != nil {
return def
}
return int(rv)
}
// OptUint parses val and returns the integer value in question, unless
// parsing fails, in which case the default def is returned.
func OptUint(val string, def uint) uint {
if val == "" {
return def
}
rv, err := strconv.ParseUint(val, 10, 0)
if err != nil {
return def
}
return uint(rv)
}
// OptBool parses val and returns the bool value in question, unless
// parsing fails, in which case the default def is returned.
func OptBool(val string, def bool) bool {
if val == "" {
return def
}
rv, err := ParseBool(val)
if err != nil {
return def
}
return rv
}
// OptFloat64 parses val and returns the float value in question, unless
// parsing fails, in which case the default def is returned.
func OptFloat64(val string, def float64) float64 {
if val == "" {
return def
}
rv, err := strconv.ParseFloat(val, 64)
if err != nil {
return def
}
return rv
}
// OptFloat32 parses val and returns the float value in question, unless
// parsing fails, in which case the default def is returned.
func OptFloat32(val string, def float32) float32 {
if val == "" {
return def
}
rv, err := strconv.ParseFloat(val, 32)
if err != nil {
return def
}
return float32(rv)
}
| 22.914286
| 73
| 0.686721
|
444d0ec567924a1b176effbbb8a848e7c64f069d
| 4,208
|
py
|
Python
|
onestandard/models.py
|
oxhacks/onestandard
|
15d18e2022f7ac1d7041f13cd4c453baa276eebb
|
[
"MIT"
] | 10
|
2019-03-22T14:23:40.000Z
|
2021-09-26T22:31:50.000Z
|
onestandard/models.py
|
oxhacks/onestandard
|
15d18e2022f7ac1d7041f13cd4c453baa276eebb
|
[
"MIT"
] | 1
|
2020-01-06T15:57:55.000Z
|
2021-11-26T23:21:06.000Z
|
onestandard/models.py
|
jaykwon/onestandard
|
15d18e2022f7ac1d7041f13cd4c453baa276eebb
|
[
"MIT"
] | 2
|
2019-12-28T06:01:09.000Z
|
2020-04-01T01:09:52.000Z
|
"""Models representing Standard File based objects."""
import json
from uuid import uuid4
from datetime import datetime
ALLOWED_TYPES = ('tag', 'note')
def link(standard1, standard2):
"""Create bi-directional references linking the two Standard-based objects.
:param standard1: the first `Standard` object to be linked
:param standard2: another `Standard` object to be linked
:returns: `None`
"""
standard1.references.append(standard2.reference)
standard2.references.append(standard1.reference)
return
class WrongTypeException(Exception):
"""An exception to throw if the Standard object isn't an allowed type."""
pass
class Standard(object):
"""The base object from which the others shall derive."""
def __init__(self, title, content_type, guid=None):
self.content_type = content_type.lower()
self._validate_type()
self.title = title
self.guid = guid if guid else str(uuid4())
self.created_at = self.updated_at = datetime.utcnow().isoformat() + 'Z'
self.references = []
self.model = {
"uuid": self.guid,
"content_type": self.content_type,
"content": {
"title": self.title,
"references": self.references
},
"created_at": self.created_at,
"updated_at": self.updated_at
}
def __repr__(self):
return '<{}: {}>'.format(self.content_type, self.guid)
@property
def reference(self):
"""Get a reference object for use in linking objects together.
:returns: a dict with the guid and content type
"""
return {
'uuid': self.guid,
'content_type': 'Tag'
}
def _validate_type(self, allowed=ALLOWED_TYPES):
"""Ensure that the type specified is valid.
:param allowed: an iterable of the allowed types
:raises: `onestandard.models.OneTypeException` if not a valid type
"""
if self.content_type not in allowed:
allowed = ', '.join(allowed)
error_message = "Type '{}' not one of {}".format(self.content_type, allowed)
raise WrongTypeException(error_message)
def json(self, *args, **kwargs):
"""Dump the Standard model into JSON format.
:param *args: positional arguments to pass to `json.dumps`
:param **kwargs: keyword arguments to pass to `json.dumps`
:returns: a JSON-ified string of the object model
"""
return json.dumps(self.model, indent=4, *args, **kwargs)
class Tag(Standard):
"""A Standard Notes Tag object, used to sort notes."""
def __init__(self, title, guid=None):
super().__init__(title=title, content_type='Tag')
class Note(Standard):
"""A Standard Notes Note object, used to define notes."""
def __init__(self, title, text, guid=None):
super().__init__(title=title, content_type='Note')
self.text = text
self.model['content']['text'] = self.text
class Package(object):
"""A Standard Notes file containing tags and notes."""
def __init__(self):
self.items = []
self.model = {
'items': self.items
}
def add(self, item):
"""Add a `Standard` based object to the package.
:param item: a `Standard`-based object to add
:returns: `None`
"""
self.items.append(item.model)
def json(self, *args, **kwargs):
"""Dump a JSON string of the package data model.
:param *args: the positional arguments to pass to `json.dumps`
:param **kwargs: the keyword arguments to pass to `json.dumps`
:returns: the JSON string version of the object model
"""
return json.dumps(self.model, *args, **kwargs)
def write(self, filepath):
"""Dump the JSON version of the object to disk.
:param *args: the positional arguments to pass to `json.dumps`
:param **kwargs: the keyword arguments to pass to `json.dumps`
:returns: None
"""
with open(filepath, 'w') as outfile:
json.dump(self.model, outfile, indent=4)
return
| 30.057143
| 88
| 0.613118
|
d001dd42f4cacea2c7ccf8b534f0567164614c83
| 1,410
|
gemspec
|
Ruby
|
polyline-normalizer.gemspec
|
amaabca/polyline-normalizer
|
4f23e255b0b9207f0df8abe319c1e93384e73dfe
|
[
"MIT"
] | 1
|
2021-11-26T12:57:41.000Z
|
2021-11-26T12:57:41.000Z
|
polyline-normalizer.gemspec
|
amaabca/polyline-normalizer
|
4f23e255b0b9207f0df8abe319c1e93384e73dfe
|
[
"MIT"
] | null | null | null |
polyline-normalizer.gemspec
|
amaabca/polyline-normalizer
|
4f23e255b0b9207f0df8abe319c1e93384e73dfe
|
[
"MIT"
] | null | null | null |
# frozen_string_literal: true
require_relative 'lib/polyline/normalizer/version'
Gem::Specification.new do |spec|
spec.name = 'polyline-normalizer'
spec.version = Polyline::Normalizer::VERSION
spec.authors = [
'Jesse Doyle',
'Michael van den Beuken',
'Darko Dosenovic',
'Zoie Carnegie'
]
spec.email = [
'jesse.doyle@ama.ab.ca',
'michael.vandenbeuken@ama.ab.ca',
'darko.dosenovic@ama.ab.ca',
'zoie.carnegie@ama.ab.ca'
]
spec.summary = 'Normalize paths encoded with the Google Polyline Algorithm'
spec.description = <<~SUMMARY
Sort and scale the points of a path encoded with the Google Polyline
Algorithm by distance to one another.
SUMMARY
spec.homepage = 'https://github.com/amaabca/polyline-normalizer'
spec.license = 'MIT'
spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')
spec.metadata['allowed_push_host'] = 'https://rubygems.org/'
spec.metadata['homepage_uri'] = spec.homepage
spec.metadata['source_code_uri'] = spec.homepage
spec.metadata['rubygems_mfa_required'] = 'true'
spec.files = Dir.chdir(File.expand_path(__dir__)) do
`git ls-files -z`
.split("\x0")
.reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
end
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.add_dependency 'fast-polylines', '~> 2.0'
end
| 33.571429
| 77
| 0.686525
|
e28dee8a9bdca650dbc4b2db7f6475f38085f7a8
| 2,040
|
py
|
Python
|
teszt/test_feladat01.py
|
python-feladatok-tesztekkel/07-01-05-osszefoglalas
|
95b5ff6c2e7020ca71cb2c577d793d3920f938a6
|
[
"CC0-1.0"
] | null | null | null |
teszt/test_feladat01.py
|
python-feladatok-tesztekkel/07-01-05-osszefoglalas
|
95b5ff6c2e7020ca71cb2c577d793d3920f938a6
|
[
"CC0-1.0"
] | null | null | null |
teszt/test_feladat01.py
|
python-feladatok-tesztekkel/07-01-05-osszefoglalas
|
95b5ff6c2e7020ca71cb2c577d793d3920f938a6
|
[
"CC0-1.0"
] | null | null | null |
from unittest import TestCase
import os,sys,inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)
import feladatok
class TestMegtatlahtoMegye(TestCase):
def test_feladat_ures(self):
megyek=[]
keresett="Baranya"
aktualis = feladatok.megtalalhato(megyek,keresett)
elvart = False
print(megyek)
self.assertEqual(elvart, aktualis, "Rosszul határozta meg, hogy "+ keresett+" megye megtalálható-e a a listába.")
def test_feladat_elso(self):
megyek=["Bács-Kiskun","Csongrád-Csanád","Fejér","Nógrád","Pest","Tolna"]
keresett="Bács-Kiskun"
aktualis = feladatok.megtalalhato(megyek,keresett)
elvart = True
print(megyek)
self.assertEqual(elvart, aktualis, "Rosszul határozta meg, hogy "+ keresett+" megye megtalálható-e a a listába.")
def test_feladat_utolso(self):
megyek=["Bács-Kiskun","Csongrád-Csanád","Fejér","Nógrád","Pest","Tolna"]
keresett="Tolna"
aktualis = feladatok.megtalalhato(megyek,keresett)
elvart = True
print(megyek)
self.assertEqual(elvart, aktualis, "Rosszul határozta meg, hogy "+ keresett+" megye megtalálható-e a a listába.")
def test_feladat_kozepe(self):
megyek=["Bács-Kiskun","Csongrád-Csanád","Fejér","Nógrád","Pest","Tolna"]
keresett="Nógrád"
aktualis = feladatok.megtalalhato(megyek,keresett)
elvart = True
print(megyek)
self.assertEqual(elvart, aktualis, "Rosszul határozta meg, hogy "+ keresett+" megye megtalálható-e a a listába.")
def test_feladat_nincs(self):
megyek=["Bács-Kiskun","Csongrád-Csanád","Fejér","Nógrád","Pest","Tolna"]
keresett="Vas"
aktualis = feladatok.megtalalhato(megyek,keresett)
elvart = False
print(megyek)
self.assertEqual(elvart, aktualis, "Rosszul határozta meg, hogy "+ keresett+" megye megtalálható-e a a listába.")
| 46.363636
| 121
| 0.67598
|
9c6f9740ee3fb0fc95c31852454974c0b77c4faf
| 2,037
|
rs
|
Rust
|
runtime-sdk-macros/src/test_utils.rs
|
anonymousGiga/oasis-sdk
|
29f23658153dfc0acded405ae3b0613e45fc8a6a
|
[
"Apache-2.0"
] | 38
|
2021-03-02T14:39:20.000Z
|
2022-03-11T07:25:42.000Z
|
runtime-sdk-macros/src/test_utils.rs
|
anonymousGiga/oasis-sdk
|
29f23658153dfc0acded405ae3b0613e45fc8a6a
|
[
"Apache-2.0"
] | 781
|
2021-02-11T19:14:42.000Z
|
2022-03-31T13:56:36.000Z
|
runtime-sdk-macros/src/test_utils.rs
|
knkgun/oasis-sdk
|
70f6d4fbc5460a3a2bf84ecd9813454f82832eb9
|
[
"Apache-2.0"
] | 19
|
2021-03-06T14:46:31.000Z
|
2022-02-26T10:14:46.000Z
|
pub fn rustfmt(code: &str) -> String {
use std::{
io::Write,
process::{Command, Stdio},
};
let mut cp = Command::new("rustfmt")
.args(&["--emit", "stdout", "--quiet"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("unable to spawn rustfmt. Do you need to install it?");
cp.stdin
.as_mut()
.unwrap()
.write_all(format!("const _: () = {{ {}; }};", code).as_bytes())
.expect("unable to communicate with rustfmt");
let output = cp.wait_with_output().unwrap();
if !output.status.success() {
panic!(
"unable to rustfmt\n{}",
String::from_utf8(output.stderr).unwrap_or_default()
);
}
String::from_utf8(output.stdout).unwrap()
}
#[macro_export]
macro_rules! assert_empty_diff {
($actual:expr, $expected:expr) => {{
use quote::ToTokens;
let actual_code = crate::test_utils::rustfmt(&$actual.to_token_stream().to_string());
let expected_code = crate::test_utils::rustfmt(&$expected.to_token_stream().to_string());
let diffs = diff::lines(&actual_code, &expected_code);
let mut has_diff = false;
let mut actual_lines = actual_code.split('\n');
let mut expected_lines = expected_code.split('\n');
for (i, diff) in diffs.iter().enumerate() {
match diff {
diff::Result::Left(l) => {
eprintln!("non-empty diff on line {}", i);
eprintln!("+ {}", l);
eprintln!("- {}", expected_lines.next().unwrap());
has_diff = true;
}
diff::Result::Right { .. } => {
actual_lines.next();
has_diff = true;
}
diff::Result::Both { .. } => {
actual_lines.next();
expected_lines.next();
}
}
}
assert!(!has_diff);
}};
}
| 31.338462
| 97
| 0.494845
|
af5c59f4a50fa50306c9644ab98f5c6678064a5e
| 262
|
py
|
Python
|
1st_100/problem053.py
|
takekoputa/project-euler
|
6f434be429bd26f5d0f84f5ab0f5fa2bd677c790
|
[
"MIT"
] | null | null | null |
1st_100/problem053.py
|
takekoputa/project-euler
|
6f434be429bd26f5d0f84f5ab0f5fa2bd677c790
|
[
"MIT"
] | null | null | null |
1st_100/problem053.py
|
takekoputa/project-euler
|
6f434be429bd26f5d0f84f5ab0f5fa2bd677c790
|
[
"MIT"
] | 1
|
2021-11-02T12:08:46.000Z
|
2021-11-02T12:08:46.000Z
|
# Question: https://projecteuler.net/problem=53
from sage.all import binomial
N = 100
count = 0
for i in range(23, N+1):
for j in range(2, i//2 + 2):
if binomial(i, j) > 10**6:
count = count + i - 2*j + 1
break
print(count)
| 20.153846
| 47
| 0.557252
|
be72d059d676ca5ed3e2ef9ec837bd09a4270c45
| 5,890
|
ts
|
TypeScript
|
packages/rax/src/index.d.ts
|
GGICE/rax
|
424d253c0cd8880418b26faaed64239e7bbaef0a
|
[
"BSD-3-Clause"
] | 1
|
2021-12-02T15:00:25.000Z
|
2021-12-02T15:00:25.000Z
|
packages/rax/src/index.d.ts
|
GGICE/rax
|
424d253c0cd8880418b26faaed64239e7bbaef0a
|
[
"BSD-3-Clause"
] | 1
|
2019-05-16T12:07:57.000Z
|
2019-05-16T12:07:57.000Z
|
packages/rax/src/index.d.ts
|
GGICE/rax
|
424d253c0cd8880418b26faaed64239e7bbaef0a
|
[
"BSD-3-Clause"
] | 1
|
2019-06-25T06:30:39.000Z
|
2019-06-25T06:30:39.000Z
|
import "./jsx";
export declare namespace Rax {
//
// Rax Element
// -----------------------------------
interface RaxElement<P> {
type: string | Component<P> | ReactiveComponent<P>;
props: P;
key: Key | null;
ref: Ref<any> | null;
}
function createElement(
type: string,
props: JSX.HTMLAttributes & JSX.SVGAttributes & Record<string, any> | null,
...children: ElementChildren[]
): RaxElement<any>;
function createElement<P>(
type: ComponentFactory<P>,
props: Attributes & P | null,
...children: ElementChildren[]
): RaxElement<any>;
function cloneElement(RaxElement: JSX.Element, props: any, ...children: ElementChildren[]): JSX.Element;
//
// Component interface
// -----------------------------------
type Key = string | number | any;
type RefObject<T> = { current?: T | null }
type RefCallback<T> = (instance: T | null) => void;
type Ref<T> = RefObject<T> | RefCallback<T>;
type ElementChild = RaxElement<any> | object | string | number | boolean | null | undefined;
type ElementChildren = ElementChild[] | ElementChild;
interface Attributes {
key?: Key;
jsx?: boolean;
}
interface ClassAttributes<T> extends Attributes {
ref?: Ref<T>;
}
interface RaxDOMAttributes {
children?: ElementChildren;
dangerouslySetInnerHTML?: {
__html: string;
};
}
type RenderableProps<P, RefType = any> = Readonly<
P & Attributes & { children?: ElementChildren; ref?: Ref<RefType> }
>;
type ComponentFactory<P = {}> = ComponentConstructor<P> | ReactiveComponent<P>;
interface ReactiveComponent<P = {}> {
(props: RenderableProps<P>, context?: any): RaxElement<any> | null;
displayName?: string;
defaultProps?: Partial<P>;
}
interface ComponentConstructor<P = {}, S = {}> {
new (props: P, context?: any): Component<P, S>;
displayName?: string;
defaultProps?: Partial<P>;
getDerivedStateFromProps?(props: Readonly<P>, state: Readonly<S>): Partial<S>;
getDerivedStateFromError?(error: any): Partial<S>;
}
interface Component<P = {}, S = {}> {
componentWillMount?(): void;
componentDidMount?(): void;
componentWillUnmount?(): void;
getChildContext?(): object;
componentWillReceiveProps?(nextProps: Readonly<P>, nextContext: any): void;
shouldComponentUpdate?(nextProps: Readonly<P>, nextState: Readonly<S>, nextContext: any): boolean;
componentWillUpdate?(nextProps: Readonly<P>, nextState: Readonly<S>, nextContext: any): void;
getSnapshotBeforeUpdate?(oldProps: Readonly<P>, oldState: Readonly<S>): any;
componentDidUpdate?(previousProps: Readonly<P>, previousState: Readonly<S>, snapshot: any): void;
componentDidCatch?(error: any): void;
}
abstract class Component<P, S> {
constructor(props?: P, context?: any);
static displayName?: string;
static defaultProps?: any;
static contextType?: RaxContext<any>;
static getDerivedStateFromProps?(props: Readonly<object>, state: Readonly<object>): object;
static getDerivedStateFromError?(error: any): object;
state: Readonly<S>;
props: RenderableProps<P>;
context: any;
base?: HTMLElement;
setState<K extends keyof S>(
state: ((prevState: Readonly<S>, props: Readonly<P>) => (Pick<S, K> | S | null)) | (Pick<S, K> | S | null),
callback?: () => void
): void;
forceUpdate(callback?: () => void): void;
abstract render(props?: RenderableProps<P>, state?: Readonly<S>, context?: any): ElementChildren;
}
//
// Hooks
// ----------------------------------------------------------------------
function useContext<T>(context: RaxContext<T>): T;
type SetStateAction<S> = (value: S | ((prevState: S) => S)) => void;
function useState<S>(initialState: S | (() => S)): [S, SetStateAction<S>];
function useState<S = undefined>(): [S | undefined, SetStateAction<S | undefined>];
type Reducer<S, A> = (prevState: S, action: A) => S;
function useReducer<S, A>(reducer: Reducer<S, A>, initialState: S): [S, (action: A) => void];
function useReducer<S, A, I>(reducer: Reducer<S, A>, initialArg: I, init: (arg: I) => S): [S, (action: A) => void];
type MutableRefObject<T> = { readonly current?: T; }
function useRef<T>(initialValue: T|null): RefObject<T>;
function useRef<T = unknown>(): MutableRefObject<T>;
type EffectCallback = () => (void | (() => void));
type DependencyList = ReadonlyArray<unknown>;
function useLayoutEffect(effect: EffectCallback, deps?: DependencyList): void;
function useEffect(effect: EffectCallback, deps?: DependencyList): void;
function useImperativeHandle<T, R extends T>(ref: Ref<T>|undefined, init: () => R, deps?: DependencyList): void;
function useCallback<T extends (...args: any[]) => any>(callback: T, deps: DependencyList): T;
function useMemo<T>(factory: () => T, deps: DependencyList | undefined): T;
//
// Fragment
// -----------------------------------
const Fragment: ComponentConstructor<{}, {}>;
//
// Ref
// -----------------------------------
function createRef<T = any>(): RefObject<T>;
function forwardRef<T, P = {}>(Component: ComponentFactory<P>): ComponentFactory<P>;
//
// Context
// -----------------------------------
interface RaxConsumer<T> extends ReactiveComponent<{
children: (value: T) => ElementChildren
}> {}
interface RaxProvider<T> extends ReactiveComponent<{
value: T,
children: ElementChildren
}> {}
interface RaxContext<T> {
Consumer: RaxConsumer<T>;
Provider: RaxProvider<T>;
}
function createContext<T>(defaultValue: T): RaxContext<T>;
//
// render
// -----------------------------------
type RenderOption<T> = { driver?: T | null }
function render(element: ElementChildren, parent: Element | Document | DocumentFragment, options?: RenderOption<T>, callback?: () => void): void
}
| 32.722222
| 146
| 0.624618
|
1e670794876cec657f38b4f0df41c1e9b2dab0bc
| 8,473
|
ps1
|
PowerShell
|
PSHR/Onboard User/Create-ADUser.ps1
|
itokamak/PowerShell
|
8543979812fc9f5283d58a10afa26d0da4ce24ff
|
[
"MIT"
] | 2
|
2017-07-26T19:30:02.000Z
|
2019-05-19T04:34:17.000Z
|
PSHR/Onboard User/Create-ADUser.ps1
|
itokamak/PowerShell
|
8543979812fc9f5283d58a10afa26d0da4ce24ff
|
[
"MIT"
] | null | null | null |
PSHR/Onboard User/Create-ADUser.ps1
|
itokamak/PowerShell
|
8543979812fc9f5283d58a10afa26d0da4ce24ff
|
[
"MIT"
] | null | null | null |
#Load Incoming JSON
param (
[string]$upn = 'defaultUPN',
[string]$name = 'Firstname Lastname',
[string]$firstname = 'default firstname',
[string]$lastname = ' default lastname',
[string]$title = 'default title',
[string]$description = ' default description',
[string]$script = 'defaultscript.bat',
[string]$department = 'default department',
[string]$manager = 'default manager',
[string]$adpath = 'CN=Users,DC=COMPANY,DC=COM',
[string]$issue = 'SD-000',
[string]$toc = 'permanent',
[string]$end_date = '12/08/2017'
)
#Load Functions
Function Write-Log
{
Param ([string]$Msg)
$dateTime = Get-Date -UFormat "%c"
$Msg = $dateTime + ":" + $Msg
Add-Content $logPath "$Msg"
}
$logPath = "C:\scripts\ps\PSHR-Issue-Logs\" + $Issue + ".log"
$saved=$global:ErrorActionPreference
$global:ErrorActionPreference = 'SilentlyContinue'
function JiraComment
{
param( [string]$issue, [string]$comment)
"Calling JiraComment with variables | issue = " + $issue + " And Text = " + $comment
[string]$cmd1 = '.\curl --% -D- -u user:password -X PUT -d "{\"update\": {\"comment\": [{\"add\": {\"body\":\"' + $comment+ '\"}}]}}"'
[string]$cmd2 = ' -H "Content-Type: application/json" https://jira.company.com/rest/api/2/issue/{0}' -f $issue;
$all_cmds = "$cmd1 $cmd2 "
$all_cmds
Invoke-Expression $all_cmds
}
function CustomFieldUpdate
{
param( [string]$issue, [string]$customfield, [string]$customfield_value)
"Calling CustomFieldUpdate with variables | issue = " + $issue + " And Text = " + $comment
#[string]$cmd1 = '.\curl --% -D- -u user:password -X PUT -d "{ \"update\": {\"comment\": [{\"add\": {\"body\":\"' + $comment+ '\"}}]}}"'
[string]$cmd1 = '.\curl --% -D- -u user:password -X PUT -d "{ \"fields\": { \"' + $customfield + '\":\"' + $customfield_value + '\"}}"'
[string]$cmd2 = ' -H "Content-Type: application/json" https://jira.company.com/rest/api/2/issue/{0}' -f $issue;
$all_cmds = "$cmd1 $cmd2 "
$all_cmds
Invoke-Expression $all_cmds
}
function SendToError
{
New-JiraSession -Credential $Jira_Cred
Invoke-JiraIssueTransition -Issue $issue -Transition 261
Get-JiraSession | Remove-JiraSession
}
#Load Jira Session
$Jira_Username = "jiraps"
$Jira_Password = Get-Content c:\scripts\ps\PSHR-Credentials\jira.txt | convertto-securestring
$Jira_Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $Jira_Username, $Jira_Password
Set-JiraConfigServer -Server 'https://jira.company.com'
Write-Log " | Starting create_ad_user.ps1 // AD Account Creation | "
#Import-Module ActiveDirectory
$env:ADPS_LoadDefaultDrive = 0
Import-Module ActiveDirectory -Cmdlet Get-ADUser,Set-ADUser,Set-ADAccountExpiration
"0: lastname = $lastname"
"AD Path: $adpath"
#Load session variables
$upnsufix="company.com"
$userprincipal="$upn@$upnsufix"
$password = "password"
$name = "$firstname $lastname"
# Have these as_enter'd variables to be able to keep firstname / lastname case
$firstname_as_entered=$firstname
$lastname_as_entered=$lastname
$firstname=$firstname.toLower()
$lastname=$lastname.toLower()
$firstname=$firstname -replace "\s", ""
$lastname=$lastname -replace "\s", ""
$firstname=$firstname -replace " ", ""
$lastname=$lastname -replace " ", ""
"2: lastname = $lastname"
"Checking for free username for firstname: $firstname lastname: $lastname"
$attempt_user=$lastname
$attempt_user+=$firstname.subString(0,1)
"Checking if username is in use: $attempt_user"
$User = Get-ADUser -LDAPFilter "(sAMAccountName=$attempt_user)" -server DC
If ($User -eq $Null) {
$User=$attempt_user
"Found free username: $attempt_user"
}
Else {
"username in use: $attempt_user"
$attempt_user=""
$attempt_user=$lastname
$attempt_user+=$firstname.substring(0,2)
$User = Get-ADUser -LDAPFilter "(sAMAccountName=$attempt_user)" -server DC
If ($User -eq $Null) {
$User=$attempt_user
"Found free username: $attempt_user"
}
else {
$attempt_user=""
$attempt_user=$lastname
$attempt_user+=$firstname.substring(0,3)
"Last attempt on username: $attempt_user"
$User = $attempt_user
}
}
Write-Log "Username set as $attempt_user"
#Create-AD-User
Write-Log "Starting New-ADUser with user: $User"
Try {
$global:ErrorActionPreference = 'stop'
New-ADUser -Verbose -Name "$name" -GivenName "$firstname_as_entered" -Surname "$lastname_as_entered" -SamAccountName $User -UserPrincipalName "$User@$upnsufix" -title "$title" -description "$title" -ScriptPath "$script" -department "$department" -email $email -manager "$manager" -Path "$adpath" -Enabled 1 -AccountPassword (ConvertTo-SecureString $password -AsPlainText -force) -server dc -ErrorAction 'stop'
}
Catch {
$ErrorMessage = $_.Exception.InnerException
}
Finally {
if (!$error) {
Write-Log "New-ADUser: No Error Occured"
JiraComment -issue $issue -Comment "User sucessfully created $User"
CustomFieldUpdate -issue $issue -customfield "customfield_11404" -customfield_value "$User"
}
else {
$Reply = "Issue caught while attempting to create AD Account: $ErrorMessage "
JiraComment -issue $issue -comment "$Reply"
Write-Log "$Reply"
SendToError
exit
}
$global:ErrorActionPreference=$saved
}
#Set Password change at next logon
$error.clear()
Try {
Set-ADUser -Identity $User -ChangePasswordAtLogon $true -server dc
}
Catch {
$ErrorMessage = $_.Exception.InnerException
}
Finally {
if (!$error) {
Write-Log "ChangePasswordAtLogon: No Error Occured"
}
else {
$Reply = "Issue caught while attempting to assign ChangePasswordAtLogon: $ErrorMessage "
JiraComment -issue $issue -comment "$Reply"
Write-Log "$Reply"
#No transition to Error status here as it's not a critical error./
}
}
#Map H:Drive in AD
$error.clear()
Try {
Set-ADUser -Identity $User -HomeDirectory \\FSPServer\Users\$User -HomeDrive H: -server dc
}
Catch {
$ErrorMessage = $_.Exception.InnerException
}
Finally {
if (!$error) {
Write-Log "HomeDirectory: No Error Occured"
}
else {
$Reply = "Issue caught while attempting to map H:Drive: $ErrorMessage - However automation Process was not stopped, please fix manually"
JiraComment -issue $issue -comment "$Reply"
Write-Log "$Reply"
#No transition to Error status here as it's not a critical error./
}
}
#Create User's Folder
$error.clear()
Try {
New-item -Path \\FSPServer\Users\$User -type directory -Force
}
Catch {
$ErrorMessage = $_.Exception.InnerException
}
Finally {
if (!$error) {
Write-Log "Create Home Folder on FSPServer: No Error Occured"
$Reply = "Created Home Folder for $User"
JiraComment -issue $issue -comment "$Reply"
}
else {
$Reply = "Issue caught while attempting to create H:Drive: $ErrorMessage - However automation Process was not stopped, please fix manually"
JiraComment -issue $issue -comment "$Reply"
Write-Log "$Reply"
#No transition to Error status here as it's not a critical error./
}
}
#Set expiry on non FTE contract types
if (($toc -eq "Contractor" ) -or ($toc -eq "Work Experience Student" ) -or ($toc -eq "External Contractor" ))
{
$User = Get-ADUser -LDAPFilter "(sAMAccountName=$attempt_user)" -server DC
#Transform Jira Date Format to AD ready format
$expiry = Get-Date $end_date -Format 'dd/MM/yyyy'
Write-Log " | Setting Active Directory Expiry | "
#Set expiry
$error.clear()
Try {
Set-ADAccountExpiration -identity $User -dateTime $expiry
}
Catch {
$ErrorMessage = $_.Exception.InnerException
}
Finally {
if (!$error) {
Write-Log "Account expiry: No Error Occured"
$setexpiry = (Get-ADUser -Identity $User -Properties AccountExpirationDate | Select-Object -Property SamAccountName, AccountExpirationDate)
$Reply = "Set expiry as $setexpiry"
JiraComment -issue $issue -comment "$Reply"
}
else {
$Reply = "Issue caught while attempting to set account expiry: $ErrorMessage - However automation Process was not stopped, please fix manually"
JiraComment -issue $issue -comment "$Reply"
Write-Log "$Reply"
#No transition to Error status here as it's not a critical error./
}
}
}
#Bypass Exchange/365/Lync if external contractor
if ($toc -eq "External Contractor" ) {
New-JiraSession -Credential $Jira_Cred
Invoke-JiraIssueTransition -Issue $issue -Transition 61
Get-JiraSession | Remove-JiraSession
}
else
{
" **************** Done **************** "
New-JiraSession -Credential $Jira_Cred
Invoke-JiraIssueTransition -Issue $issue -Transition 381
Get-JiraSession | Remove-JiraSession
}
| 32.339695
| 411
| 0.701522
|
fdc3bea3630b85115cb54a98e37122d3c3532a3b
| 221
|
css
|
CSS
|
JavaEE-Practicum-2020/web/asset/css/register_login.css
|
yjzzjy4/2020-HUC-SE-JavaEE-Practicum
|
79bcd0b9e36700b3acae8dffa25146fa5e916b3e
|
[
"MIT"
] | null | null | null |
JavaEE-Practicum-2020/web/asset/css/register_login.css
|
yjzzjy4/2020-HUC-SE-JavaEE-Practicum
|
79bcd0b9e36700b3acae8dffa25146fa5e916b3e
|
[
"MIT"
] | null | null | null |
JavaEE-Practicum-2020/web/asset/css/register_login.css
|
yjzzjy4/2020-HUC-SE-JavaEE-Practicum
|
79bcd0b9e36700b3acae8dffa25146fa5e916b3e
|
[
"MIT"
] | null | null | null |
body {
position: relative;
background: url("../img/background/ps-bg-image.jpeg") repeat-y center;
margin: 0 0;
}
#validateBoxContainer {
width: 36%;
position: relative;
top: 10vh;
left: 32%;
}
| 18.416667
| 74
| 0.615385
|
26ac8cc2c68fe593a558a44df40443b93aeda8f6
| 247
|
sql
|
SQL
|
src/SFA.DAS.EAS.Employer_Financial.Database/Scripts/PostDeployment/CreateTopUpPercentages.sql
|
uk-gov-mirror/SkillsFundingAgency.das-employerapprenticeshipsservice
|
b6778ed20b0438acab7c1a14600288a250db8d23
|
[
"MIT"
] | 8
|
2016-09-14T08:31:59.000Z
|
2021-08-19T11:13:59.000Z
|
src/SFA.DAS.EAS.Employer_Financial.Database/Scripts/PostDeployment/CreateTopUpPercentages.sql
|
uk-gov-mirror/SkillsFundingAgency.das-employerapprenticeshipsservice
|
b6778ed20b0438acab7c1a14600288a250db8d23
|
[
"MIT"
] | 319
|
2016-07-20T07:52:08.000Z
|
2022-03-31T18:07:09.000Z
|
src/SFA.DAS.EAS.Employer_Financial.Database/Scripts/PostDeployment/CreateTopUpPercentages.sql
|
uk-gov-mirror/SkillsFundingAgency.das-employerapprenticeshipsservice
|
b6778ed20b0438acab7c1a14600288a250db8d23
|
[
"MIT"
] | 8
|
2016-11-08T16:30:23.000Z
|
2022-03-23T19:45:38.000Z
|
IF (NOT EXISTS(SELECT * FROM [employer_financial].[TopUpPercentage] WHERE Id = 1 AND DateFrom = '2015-01-01 00:00:00.000'))
BEGIN
INSERT INTO [employer_financial].[TopUpPercentage]
(DateFrom,Amount)
VALUES
('2015-01-01 00:00:00.000',0.1)
END
| 35.285714
| 124
| 0.728745
|
93b034b611c6045bd1fa346f3390e777894dc1e2
| 2,213
|
cs
|
C#
|
Assets/BOXOPHOBIC/Utils/Editor/StyledInspector/StyledIMaskDrawer.cs
|
Game-Bubble/Run-Transformer
|
40d27922bf1f50d2a24bf28ec54193ee1efe7a05
|
[
"Apache-2.0"
] | 1
|
2021-06-27T10:24:37.000Z
|
2021-06-27T10:24:37.000Z
|
Assets/BOXOPHOBIC/Utils/Editor/StyledInspector/StyledIMaskDrawer.cs
|
Game-Bubble/Run-Transformer
|
40d27922bf1f50d2a24bf28ec54193ee1efe7a05
|
[
"Apache-2.0"
] | null | null | null |
Assets/BOXOPHOBIC/Utils/Editor/StyledInspector/StyledIMaskDrawer.cs
|
Game-Bubble/Run-Transformer
|
40d27922bf1f50d2a24bf28ec54193ee1efe7a05
|
[
"Apache-2.0"
] | null | null | null |
// Cristian Pop - https://boxophobic.com/
using UnityEngine;
using UnityEditor;
namespace Boxophobic.StyledGUI
{
[CustomPropertyDrawer(typeof(StyledMask))]
public class StyledMaskAttributeDrawer : PropertyDrawer
{
StyledMask a;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
a = (StyledMask)attribute;
GUIStyle styleLabel = new GUIStyle(EditorStyles.label)
{
richText = true,
alignment = TextAnchor.MiddleCenter,
wordWrap = true
};
string[] masks = new string[] { a.mask0, a.mask1 };
if (a.index == 3)
{
masks = new string[] { a.mask0, a.mask1, a.mask2 };
}
else if (a.index == 4)
{
masks = new string[] { a.mask0, a.mask1, a.mask2, a.mask3 };
}
else if (a.index == 5)
{
masks = new string[] { a.mask0, a.mask1, a.mask2, a.mask3, a.mask4 };
}
else if (a.index == 6)
{
masks = new string[] { a.mask0, a.mask1, a.mask2, a.mask3, a.mask4, a.mask5 };
}
else if (a.index == 7)
{
masks = new string[] { a.mask0, a.mask1, a.mask2, a.mask3, a.mask4, a.mask5, a.mask6 };
}
else if (a.index == 8)
{
masks = new string[] { a.mask0, a.mask1, a.mask2, a.mask3, a.mask4, a.mask5, a.mask6, a.mask7 };
}
GUILayout.Space(a.top);
int mask = (int)property.intValue;
mask = EditorGUILayout.MaskField(property.displayName, mask, masks);
if (Mathf.Abs(mask) > 32000)
{
mask = -1;
}
// Debug Value
//EditorGUILayout.LabelField(mask.ToString());
property.intValue = mask;
GUI.enabled = true;
GUILayout.Space(a.down);
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return -2;
}
}
}
| 28.371795
| 112
| 0.487573
|
dbdaa23fc077fd87dd63fa4c6629e23416012c34
| 2,504
|
php
|
PHP
|
src/Providers/LayoutServiceProvider.php
|
sabineabele/arbory
|
7596ed0068a4c7c14495647af265458303fdaf5d
|
[
"MIT"
] | 39
|
2017-07-25T08:57:48.000Z
|
2022-01-29T14:53:13.000Z
|
src/Providers/LayoutServiceProvider.php
|
sabineabele/arbory
|
7596ed0068a4c7c14495647af265458303fdaf5d
|
[
"MIT"
] | 133
|
2017-07-26T06:22:31.000Z
|
2022-03-28T10:24:21.000Z
|
src/Providers/LayoutServiceProvider.php
|
sabineabele/arbory
|
7596ed0068a4c7c14495647af265458303fdaf5d
|
[
"MIT"
] | 40
|
2017-07-26T10:52:41.000Z
|
2021-09-13T12:09:03.000Z
|
<?php
namespace Arbory\Base\Providers;
use Arbory\Base\Services\AssetPipeline;
use Illuminate\View\View;
use Arbory\Base\Menu\Menu;
use Arbory\Base\Admin\Admin;
use Arbory\Base\Menu\MenuFactory;
use Arbory\Base\Menu\MenuItemFactory;
use Illuminate\Support\ServiceProvider;
use Arbory\Base\Admin\Layout\LayoutManager;
use Illuminate\Contracts\View\Factory as ViewFactory;
class LayoutServiceProvider extends ServiceProvider
{
protected const GOOGLE_MAPS_SRC = 'https://maps.googleapis.com/maps/api/js?libraries=places&key=';
/**
* @param ViewFactory $view
* @param Admin $admin
*/
public function boot(ViewFactory $view, Admin $admin): void
{
$assets = $admin->assets();
$view->composer('arbory::layout.main', function (View $view) use ($assets, $admin) {
$assets->css(mix('css/application.css', 'vendor/arbory'));
$assets->css(mix('css/material-icons.css', 'vendor/arbory'));
$assets->prependJs(mix('js/application.js', 'vendor/arbory'));
$assets->prependJs(mix('js/includes.js', 'vendor/arbory'));
$assets->prependJs(mix('js/vendor.js', 'vendor/arbory'));
$assets->prependJs(mix('js/manifest.js', 'vendor/arbory'));
$this->loadThirdPartyAssets($assets);
$view->with([
'assets' => $assets,
'user' => $admin->sentinel()->getUser(),
'menu' => $this->buildMenu()->render(),
]);
});
$view->composer('arbory::layout.public', function (View $view) use ($assets) {
$assets->css(mix('css/application.css', 'vendor/arbory'));
$assets->css(mix('css/controllers/sessions.css', 'vendor/arbory'));
$view->with([
'assets' => $assets,
]);
});
$this->app->singleton(LayoutManager::class);
}
/**
* @param AssetPipeline $assets
* @return void
*/
protected function loadThirdPartyAssets(AssetPipeline $assets): void
{
$googleMapsAPIKey = config('arbory.services.google.maps_api_key');
if ($googleMapsAPIKey) {
$assets->prependJs(self::GOOGLE_MAPS_SRC . $googleMapsAPIKey);
}
}
/**
* @return Menu
*/
protected function buildMenu(): Menu
{
$itemFactory = $this->app->make(MenuItemFactory::class);
$factory = new MenuFactory($itemFactory);
return $factory->build(config('arbory.menu'));
}
}
| 30.91358
| 102
| 0.600639
|
25742a28c5fbedf3424ac71cd0596770dbf90aff
| 2,223
|
js
|
JavaScript
|
test/parallel/test-debug-signal-cluster.js
|
AngeldsWang/io.js
|
545959468fbc878e7f0a486264eebbdf06a57bea
|
[
"Artistic-2.0"
] | 2
|
2021-02-13T08:39:17.000Z
|
2021-02-19T13:44:11.000Z
|
test/parallel/test-debug-signal-cluster.js
|
AngeldsWang/io.js
|
545959468fbc878e7f0a486264eebbdf06a57bea
|
[
"Artistic-2.0"
] | null | null | null |
test/parallel/test-debug-signal-cluster.js
|
AngeldsWang/io.js
|
545959468fbc878e7f0a486264eebbdf06a57bea
|
[
"Artistic-2.0"
] | null | null | null |
var common = require('../common');
var assert = require('assert');
var spawn = require('child_process').spawn;
var port = common.PORT + 42;
var args = ['--debug-port=' + port,
common.fixturesDir + '/clustered-server/app.js'];
var options = { stdio: ['inherit', 'inherit', 'pipe', 'ipc'] };
var child = spawn(process.execPath, args, options);
var outputLines = [];
var outputTimerId;
var waitingForDebuggers = false;
var pids = null;
child.stderr.on('data', function(data) {
var lines = data.toString().replace(/\r/g, '').trim().split('\n');
var line = lines[0];
lines.forEach(function(ln) { console.log('> ' + ln) } );
if (outputTimerId !== undefined)
clearTimeout(outputTimerId);
if (waitingForDebuggers) {
outputLines = outputLines.concat(lines);
outputTimerId = setTimeout(onNoMoreLines, 800);
} else if (line === 'all workers are running') {
child.on('message', function(msg) {
if (msg.type !== 'pids')
return;
pids = msg.pids;
console.error('got pids %j', pids);
waitingForDebuggers = true;
process._debugProcess(child.pid);
});
child.send({
type: 'getpids'
});
}
});
function onNoMoreLines() {
assertOutputLines();
process.exit();
}
setTimeout(function testTimedOut() {
assert(false, 'test timed out.');
}, 6000);
process.on('exit', function onExit() {
// Kill processes in reverse order to avoid timing problems on Windows where
// the parent process is killed before the children.
pids.reverse().forEach(function(pid) {
process.kill(pid);
});
});
function assertOutputLines() {
var expectedLines = [
'Starting debugger agent.',
'Debugger listening on port ' + (port + 0),
'Starting debugger agent.',
'Debugger listening on port ' + (port + 1),
'Starting debugger agent.',
'Debugger listening on port ' + (port + 2),
];
// Do not assume any particular order of output messages,
// since workers can take different amout of time to
// start up
outputLines.sort();
expectedLines.sort();
assert.equal(outputLines.length, expectedLines.length);
for (var i = 0; i < expectedLines.length; i++)
assert.equal(outputLines[i], expectedLines[i]);
}
| 26.464286
| 78
| 0.646874
|
e40981bbf91805b32bba24d359c13298c6db9938
| 476
|
cs
|
C#
|
MiX.Integrate.Shared/Entities/Messages/MessageStateHistoryItem.cs
|
mateuszligeza/MiX.Integrate.Api.Client
|
1e2b0c8d4954357eaaf9b34ef6beb863784007df
|
[
"MIT"
] | 5
|
2017-11-08T17:22:17.000Z
|
2020-10-06T22:09:07.000Z
|
MiX.Integrate.Shared/Entities/Messages/MessageStateHistoryItem.cs
|
ktngoykalolo/MiX.Integrate.Api.Client
|
2b34b1f1107203de92b5badff49e24e340dfd613
|
[
"MIT"
] | 3
|
2020-03-09T22:26:13.000Z
|
2021-04-22T18:41:51.000Z
|
MiX.Integrate.Shared/Entities/Messages/MessageStateHistoryItem.cs
|
ktngoykalolo/MiX.Integrate.Api.Client
|
2b34b1f1107203de92b5badff49e24e340dfd613
|
[
"MIT"
] | 4
|
2018-03-13T07:06:10.000Z
|
2021-03-04T18:31:19.000Z
|
using System;
namespace MiX.Integrate.Shared.Entities.Messages
{
public class MessageStateHistoryItem
{
public MessageStateHistoryItem() { }
public int MessageID { get; set; }
public MessageStates State { get; set; }
public DateTime DateEntered { get; set; }
public string Notes { get; set; }
public string Description { get; set; }
public int ActiveMessageID { get; set; }
public DateTime TimeStamp { get; set; }
public bool FromUnit { get; set; }
}
}
| 26.444444
| 48
| 0.707983
|
20a56dfac1cb657d7d669b6450c077e7730a891b
| 1,755
|
py
|
Python
|
api/migrations/0092_auto_20201123_1025.py
|
IFRCGo/ifrcgo-api
|
c1c3e0cf1076ab48d03db6aaf7a00f8485ca9e1a
|
[
"MIT"
] | 11
|
2018-06-11T06:05:12.000Z
|
2022-03-25T09:31:44.000Z
|
api/migrations/0092_auto_20201123_1025.py
|
IFRCGo/ifrcgo-api
|
c1c3e0cf1076ab48d03db6aaf7a00f8485ca9e1a
|
[
"MIT"
] | 498
|
2017-11-07T21:20:13.000Z
|
2022-03-31T14:37:18.000Z
|
api/migrations/0092_auto_20201123_1025.py
|
IFRCGo/ifrcgo-api
|
c1c3e0cf1076ab48d03db6aaf7a00f8485ca9e1a
|
[
"MIT"
] | 6
|
2018-04-11T13:29:50.000Z
|
2020-07-16T16:52:11.000Z
|
# Generated by Django 2.2.13 on 2020-11-23 10:25
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0091_auto_20201120_1118'),
]
operations = [
migrations.RemoveField(
model_name='country',
name='nsi_annual_fdrs_reporting',
),
migrations.RemoveField(
model_name='country',
name='nsi_branches',
),
migrations.RemoveField(
model_name='country',
name='nsi_cmc_dashboard_compliance',
),
migrations.RemoveField(
model_name='country',
name='nsi_domestically_generated_income',
),
migrations.RemoveField(
model_name='country',
name='nsi_expenditures',
),
migrations.RemoveField(
model_name='country',
name='nsi_gov_financial_support',
),
migrations.RemoveField(
model_name='country',
name='nsi_income',
),
migrations.RemoveField(
model_name='country',
name='nsi_policy_implementation',
),
migrations.RemoveField(
model_name='country',
name='nsi_risk_management_framework',
),
migrations.RemoveField(
model_name='country',
name='nsi_staff',
),
migrations.RemoveField(
model_name='country',
name='nsi_trained_in_first_aid',
),
migrations.RemoveField(
model_name='country',
name='nsi_volunteers',
),
migrations.RemoveField(
model_name='country',
name='nsi_youth',
),
]
| 26.590909
| 53
| 0.540741
|
96eac0c0b02bee4b007a8b824b72f33c5e80c0b4
| 3,394
|
cs
|
C#
|
GAPPSF/UIControls/FormulaSolver/UserHelpWindow.xaml.cs
|
RH-Code/GAPP
|
0a882e8cbaa23c18f952bbdccfb9f95e371d4fd4
|
[
"MIT"
] | 2
|
2015-10-27T13:52:37.000Z
|
2021-06-15T11:31:27.000Z
|
GAPPSF/UIControls/FormulaSolver/UserHelpWindow.xaml.cs
|
RH-Code/GAPP
|
0a882e8cbaa23c18f952bbdccfb9f95e371d4fd4
|
[
"MIT"
] | 2
|
2015-08-17T18:08:22.000Z
|
2019-03-14T07:34:06.000Z
|
GAPPSF/UIControls/FormulaSolver/UserHelpWindow.xaml.cs
|
RH-Code/GAPP
|
0a882e8cbaa23c18f952bbdccfb9f95e371d4fd4
|
[
"MIT"
] | 10
|
2015-02-19T22:09:25.000Z
|
2022-01-20T07:41:07.000Z
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace GAPPSF.UIControls.FormulaSolver
{
/// <summary>
/// Interaction logic for UserHelpWindow.xaml
/// </summary>
public partial class UserHelpWindow : Window
{
public UserHelpWindow()
{
InitializeComponent();
string defaultLanguage = "en";
if (Localization.TranslationManager.Instance.CurrentLanguage != null)
{
if (Localization.TranslationManager.Instance.CurrentLanguage.Name.Length > 1)
{
defaultLanguage = Localization.TranslationManager.Instance.CurrentLanguage.Name.Substring(0, 2).ToLower();
if (defaultLanguage != "de" &&
defaultLanguage != "nl" &&
defaultLanguage != "fr")
{
defaultLanguage = "en";
}
}
}
try
{
string tmpFolder = System.IO.Path.Combine(Core.Settings.Default.SettingsFolder, "FormulaSolverHelp");
if (!System.IO.Directory.Exists(tmpFolder))
{
System.IO.Directory.CreateDirectory(tmpFolder);
}
if (ExtractHelpFiles(defaultLanguage, tmpFolder))
{
Uri uri = new System.Uri(System.IO.Path.Combine(tmpFolder, "formulasolverdocs.html"));
webHelp.Navigate(uri);
}
}
catch(Exception e)
{
Core.ApplicationData.Instance.Logger.AddLog(this, e);
}
}
private bool ExtractHelpFiles(string language, string folder)
{
string prefix = "GAPPSF.UIControls.FormulaSolver.Documentation." + language.Replace('-', '_') + ".";
var resourceNames = Assembly.GetExecutingAssembly()
.GetManifestResourceNames()
.Where(name => name.StartsWith(prefix));
bool written = true;
foreach (string r in resourceNames)
{
written = written && WriteResourceToFile(r, System.IO.Path.Combine(folder, r.Substring(prefix.Length)));
}
return written;
}
private bool WriteResourceToFile(string resourceName, string fileName)
{
using (System.IO.Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
if (s == null)
{
throw new Exception("Cannot find embedded resource '" + resourceName + "'");
}
byte[] buffer = new byte[s.Length];
s.Read(buffer, 0, buffer.Length);
using (System.IO.BinaryWriter sw = new System.IO.BinaryWriter(System.IO.File.Open(fileName, System.IO.FileMode.Create)))
{
sw.Write(buffer);
}
}
return true;
}
}
}
| 34.282828
| 136
| 0.549499
|
4bd15b4cbe36600c6229f6218be02de7839d2ce6
| 2,552
|
rs
|
Rust
|
src/lattice.rs
|
faisalron/sudachirs-python
|
7bdc7ef0c21e50f1b34ab048ca997cd4bef1e70e
|
[
"MIT"
] | 9
|
2020-07-06T01:52:00.000Z
|
2021-09-29T10:34:30.000Z
|
src/lattice.rs
|
faisalron/sudachirs-python
|
7bdc7ef0c21e50f1b34ab048ca997cd4bef1e70e
|
[
"MIT"
] | null | null | null |
src/lattice.rs
|
faisalron/sudachirs-python
|
7bdc7ef0c21e50f1b34ab048ca997cd4bef1e70e
|
[
"MIT"
] | null | null | null |
pub mod node;
use std::i32;
use self::node::Node;
use crate::dic::grammar::Grammar;
use pyo3::prelude::*;
#[pyclass]
pub struct Lattice {
size: usize,
pub end_lists: Vec<Vec<Node>>,
}
#[pymethods]
impl Lattice {
#[new]
pub fn new(size: usize) -> Self {
let mut end_lists = vec![Vec::<Node>::new(); size + 1];
let bos_node = Node::new_bos();
end_lists[0].push(bos_node);
Lattice {
size,
end_lists,
}
}
fn connect_node(&self, r_node: &mut Node, grammar: &Grammar) {
let begin = r_node.begin;
r_node.total_cost = i32::MAX;
for (i, l_node) in self.end_lists[begin].iter().enumerate() {
if !l_node.is_connected_to_bos {
continue;
}
let connect_cost = grammar
.get_connect_cost(l_node.right_id, r_node.left_id);
let cost = l_node.total_cost + connect_cost as i32;
if cost < r_node.total_cost {
r_node.total_cost = cost;
r_node.best_previous_node_index = Some((begin, i));
}
}
r_node.total_cost += r_node.cost as i32;
r_node.is_connected_to_bos = match r_node.best_previous_node_index {
Some(_) => true,
None => false,
};
}
pub fn insert(&mut self, begin: usize, end: usize, mut node: Node, grammar: &Grammar) {
node.set_range(begin, end);
self.connect_node(&mut node, grammar);
self.end_lists[end].push(node);
}
pub fn connect_eos_node(&mut self, grammar: &Grammar) {
let eos_node = Node::new_eos(self.size);
self.insert(eos_node.begin, eos_node.end, eos_node, grammar);
}
pub fn get_best_path(&self) -> Vec<Node> {
// TODO: reference of eos_node in struct `Lattice` ?
let eos_node = self.end_lists[self.size].last().unwrap();
if !eos_node.is_connected_to_bos {
panic!("EOS isn't connected to BOS");
}
let mut path = Vec::new();
let mut node = eos_node;
// todo
let (i, j) = node.best_previous_node_index.unwrap();
let mut i = i;
let mut j = j;
while (i, j) != (0, 0) {
path.push((*node).clone());
// todo
let (a, b) = node.best_previous_node_index.unwrap();
i = a;
j = b;
node = &self.end_lists[i][j];
}
path.reverse();
path.pop(); // EOS
path
}
}
| 25.777778
| 91
| 0.532524
|
87db74db08b0bee206c6435d920cd127a94dd427
| 548
|
rb
|
Ruby
|
config/routes.rb
|
Donnadieu/rails-miner-game
|
d17cbd11d771b56828d1076a52a99c42aa7463a2
|
[
"MIT"
] | null | null | null |
config/routes.rb
|
Donnadieu/rails-miner-game
|
d17cbd11d771b56828d1076a52a99c42aa7463a2
|
[
"MIT"
] | null | null | null |
config/routes.rb
|
Donnadieu/rails-miner-game
|
d17cbd11d771b56828d1076a52a99c42aa7463a2
|
[
"MIT"
] | null | null | null |
Rails.application.routes.draw do
devise_for :users, controllers: { omniauth_callbacks: 'my_devise/omniauth_callbacks', registrations: 'my_devise/registrations' }
get '/', to: 'application#index'
# patch '/mining_rig/:id/miners', to: 'miners#mining'
get '/users/highest_balance', to: 'users#highest_balance', as: 'highest_balance'
resources :energy_packs
resources :coins
resources :users do
resources :wallets, only: [:show, :update]
resources :mining_rigs
end
patch '/mining_rig/:id/miners', to: 'miners#update'
end
| 28.842105
| 130
| 0.726277
|
5cd4976e3066c3ffc336bea621afbd3d1ded32e0
| 984
|
sql
|
SQL
|
bp2/vjezbe_pdf/bp2_vj09pdf_zadatak05.sql
|
jasarsoft/fit-src
|
d9b963be3afbd4494de9d0289c947b0a41ad91d7
|
[
"MIT"
] | null | null | null |
bp2/vjezbe_pdf/bp2_vj09pdf_zadatak05.sql
|
jasarsoft/fit-src
|
d9b963be3afbd4494de9d0289c947b0a41ad91d7
|
[
"MIT"
] | null | null | null |
bp2/vjezbe_pdf/bp2_vj09pdf_zadatak05.sql
|
jasarsoft/fit-src
|
d9b963be3afbd4494de9d0289c947b0a41ad91d7
|
[
"MIT"
] | null | null | null |
/*
Vjezbe 9 Zadatak 5
Kreirati view (pogled) nad podacima koji ce sadrzavati sljedeca polja: ime i prezime, jmbg,
telefon i email kandidata, zatim datum, naziv, oznaku, oblast i max. broj bodova na testu, te
polje polozio, osvojene bodove i procentualni rezultat testa.
*/
USE Edin
CREATE VIEW vKandidatTest
AS
SELECT K.Ime + ' ' + K.Prezime AS 'Ime prezime',
K.JMBG AS 'JMBG kandidata',
K.Telefon AS 'Telefon kandidata',
K.Email AS 'Email kandidata',
T.Datum AS 'Datum testa',
T.Naziv AS 'Naziv testa',
T.Oznaka AS 'Oznaka testa',
T.Oblast AS 'Oblast testa',
T.MaxBrojBodova AS 'MaxBroj Bodova testa',
RT.Polozio AS 'Polozio rezultat',
RT.OsvojeniBodovi AS 'Osvojeni bodovi',
CONVERT(NVARCHAR, CONVERT(decimal(5, 2), (RT.OsvojeniBodovi/T.MaxBrojBodova)*100)) + '%' AS 'Postotak bodova'
FROM Kandidati AS K
INNER JOIN RezultatiTesta AS RT
ON K.KandidatID = RT.KandidatID
INNER JOIN Testovi AS T
ON T.TestID = RT.TestID
SELECT * FROM vKandidatTest
| 31.741935
| 111
| 0.728659
|
2fbda5160192b16dbab4f8b51861e2156b45fb01
| 2,750
|
py
|
Python
|
pymemcache/test/benchmark.py
|
methane/pymemcache
|
0ff5430cdcef7ed52fb3edc2a90c1c7d208ad77f
|
[
"Apache-2.0"
] | 1
|
2015-11-05T15:16:55.000Z
|
2015-11-05T15:16:55.000Z
|
pymemcache/test/benchmark.py
|
methane/pymemcache
|
0ff5430cdcef7ed52fb3edc2a90c1c7d208ad77f
|
[
"Apache-2.0"
] | null | null | null |
pymemcache/test/benchmark.py
|
methane/pymemcache
|
0ff5430cdcef7ed52fb3edc2a90c1c7d208ad77f
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2012 Pinterest.com
#
# 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.
import argparse
import time
def test_client(name, client, size, count):
client.flush_all()
value = 'X' * size
start = time.time()
for i in range(count):
client.set(str(i), value)
for i in range(count):
client.get(str(i))
duration = time.time() - start
print("{0}: {1}".format(name, duration))
def test_pylibmc(host, port, size, count):
try:
import pylibmc
except Exception:
print("Could not import pylibmc, skipping test...")
return
client = pylibmc.Client(['{0}:{1}'.format(host, port)])
client.behaviors = {"tcp_nodelay": True}
test_client('pylibmc', client, size, count)
def test_memcache(host, port, size, count):
try:
import memcache
except Exception:
print("Could not import pymemcache.client, skipping test...")
return
client = memcache.Client(['{0}:{1}'.format(host, port)])
test_client('memcache', client, size, count)
def test_pymemcache(host, port, size, count):
try:
import pymemcache.client
except Exception:
print("Could not import pymemcache.client, skipping test...")
return
client = pymemcache.client.Client((host, port))
test_client('pymemcache', client, size, count)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--server',
metavar='HOST',
required=True)
parser.add_argument('-p', '--port',
metavar='PORT',
type=int,
required=True)
parser.add_argument('-z', '--size',
metavar='SIZE',
default=1024,
type=int)
parser.add_argument('-c', '--count',
metavar='COUNT',
default=10000,
type=int)
args = parser.parse_args()
test_pylibmc(args.server, args.port, args.size, args.count)
test_memcache(args.server, args.port, args.size, args.count)
test_pymemcache(args.server, args.port, args.size, args.count)
if __name__ == '__main__':
main()
| 28.350515
| 74
| 0.606545
|
a13384343a0281d19d48f98096da518473635e43
| 2,222
|
ts
|
TypeScript
|
src/bot/commands/factory/CommandFactory.ts
|
psyKomicron/Julie
|
794217ca52b62dba1678d2323bc654068fac74d5
|
[
"MIT"
] | 1
|
2020-05-16T02:01:26.000Z
|
2020-05-16T02:01:26.000Z
|
src/bot/commands/factory/CommandFactory.ts
|
psyKomicron/DesmoBot
|
794217ca52b62dba1678d2323bc654068fac74d5
|
[
"MIT"
] | 3
|
2019-04-21T23:02:22.000Z
|
2022-01-22T11:37:25.000Z
|
src/bot/commands/factory/CommandFactory.ts
|
psyKomicron/Julie
|
794217ca52b62dba1678d2323bc654068fac74d5
|
[
"MIT"
] | null | null | null |
import { Message } from 'discord.js';
import { Bot } from '../../Bot';
import { Command } from '../Command';
import { DownloadCommand } from '../commands/DownloadCommand';
import { DeleteCommand } from '../commands/DeleteCommand';
import { HelpCommand } from '../commands/HelpCommand';
import { VoteCommand } from '../commands/VoteCommand';
import { EmbedCommand } from '../commands/EmbedCommand';
import { DefaultCommand } from '../commands/DefaultCommand';
import { TestCommand } from '../commands/TestCommand';
import { ReplyCommand } from '../commands/ReplyCommand';
import { ExploreCommand } from '../commands/ExploreCommand';
import { PlayCommand } from '../commands/PlayCommand';
export class CommandFactory
{
// a b c d e f g h i j k l m n o p q r s t u v w x y z
public static create(type: string, message: Message, bot: Bot): Command
{
let command: Command = undefined;
switch (type)
{
case "dl":
case "download":
command = new DownloadCommand(message, bot);
break;
case "d":
case "delete":
command = new DeleteCommand(message, bot);
break;
case "embed":
command = new EmbedCommand(message, bot);
break;
case "e":
case "explore":
command = new ExploreCommand(message, bot);
break;
case "p":
case "play":
command = new PlayCommand(message, bot);
break;
case "h":
case "help":
command = new HelpCommand(message, bot);
break;
case "r":
case "reply":
command = new ReplyCommand(message, bot);
break;
case "t":
case "test":
command = new TestCommand(message, bot);
break;
case "v":
case "vote":
command = new VoteCommand(message, bot);
break;
default:
command = new DefaultCommand(message, bot);
break;
}
return command;
}
}
| 34.71875
| 75
| 0.519352
|
efa3970c2243877a4e7f78024e7c5784b711fb2d
| 2,284
|
dart
|
Dart
|
lib/app/modules/user/components/foto_perfil_widget.dart
|
GabrielDimaa/strapen_app
|
ccfe58a3f4491090d8de35f64d4fab99feda26e6
|
[
"MIT"
] | 2
|
2021-08-14T12:21:03.000Z
|
2021-12-29T15:26:06.000Z
|
lib/app/modules/user/components/foto_perfil_widget.dart
|
GabrielDimaa/strapen_app
|
ccfe58a3f4491090d8de35f64d4fab99feda26e6
|
[
"MIT"
] | null | null | null |
lib/app/modules/user/components/foto_perfil_widget.dart
|
GabrielDimaa/strapen_app
|
ccfe58a3f4491090d8de35f64d4fab99feda26e6
|
[
"MIT"
] | 1
|
2021-11-24T17:06:20.000Z
|
2021-11-24T17:06:20.000Z
|
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:strapen_app/app/app_widget.dart';
import 'package:strapen_app/app/modules/live/models/live_model.dart';
import 'package:transparent_image/transparent_image.dart';
class FotoPerfilWidget extends StatelessWidget {
final dynamic foto;
final double? radiusSize;
final LiveModel? liveModel;
final VoidCallback? onTap;
const FotoPerfilWidget({required this.foto, this.radiusSize, this.liveModel, this.onTap});
@override
Widget build(BuildContext context) {
double radius = radiusSize ?? 70;
return Builder(
builder: (_) {
ImageProvider<Object>? image;
if (foto != null) {
if (foto is File)
image = Image.file(foto).image;
else
image = FadeInImage.memoryNetwork(
placeholder: kTransparentImage,
image: foto,
).image;
}
return GestureDetector(
onTap: !(liveModel?.finalizada ?? true) ? onTap : null,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
CircleAvatar(
radius: radius,
backgroundColor: !(liveModel?.finalizada ?? true) ? AppColors.error : AppColors.primary,
child: CircleAvatar(
radius: radius - 3,
backgroundColor: AppColors.background,
child: image != null
? CircleAvatar(
radius: radius - 8,
backgroundImage: image,
)
: Container(),
),
),
Visibility(
visible: !(liveModel?.finalizada ?? true),
child: Card(
margin: const EdgeInsets.only(top: 4),
color: AppColors.error,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
child: Padding(
padding: const EdgeInsets.all(4),
child: const Text("AO VIVO"),
),
),
),
],
),
);
},
);
}
}
| 31.287671
| 104
| 0.515324
|
bd177115c745b9b32a717ef5b4b38943de218042
| 347
|
rb
|
Ruby
|
lib/fog/openstack/orchestration/models/resource_schemas.rb
|
achevalet/fog-openstack
|
79116756ab04058a4bd970f3f1944886210221ed
|
[
"MIT"
] | 72
|
2016-02-29T15:07:51.000Z
|
2022-03-31T15:05:31.000Z
|
lib/fog/openstack/orchestration/models/resource_schemas.rb
|
achevalet/fog-openstack
|
79116756ab04058a4bd970f3f1944886210221ed
|
[
"MIT"
] | 447
|
2016-02-24T13:26:17.000Z
|
2022-03-29T01:17:53.000Z
|
lib/fog/openstack/orchestration/models/resource_schemas.rb
|
achevalet/fog-openstack
|
79116756ab04058a4bd970f3f1944886210221ed
|
[
"MIT"
] | 152
|
2016-02-23T13:00:40.000Z
|
2022-03-11T17:23:17.000Z
|
require 'fog/openstack/models/collection'
module Fog
module OpenStack
class Orchestration
class ResourceSchemas < Fog::OpenStack::Collection
def get(resource_type)
service.show_resource_schema(resource_type).body
rescue Fog::OpenStack::Compute::NotFound
nil
end
end
end
end
end
| 21.6875
| 58
| 0.67147
|
b89dac183c470cec30337e81ce0eb4d086eb9952
| 2,469
|
lua
|
Lua
|
tower_defense_server.lua
|
paulthegreat/tower_defense
|
ed7d1e60478a7bc0238e1d4ad22b4534ff7e13f4
|
[
"MIT"
] | null | null | null |
tower_defense_server.lua
|
paulthegreat/tower_defense
|
ed7d1e60478a7bc0238e1d4ad22b4534ff7e13f4
|
[
"MIT"
] | null | null | null |
tower_defense_server.lua
|
paulthegreat/tower_defense
|
ed7d1e60478a7bc0238e1d4ad22b4534ff7e13f4
|
[
"MIT"
] | null | null | null |
tower_defense = {}
local service_creation_order = {
'game',
'tower'
}
local monkey_patches = {
combat_service = 'stonehearth.services.server.combat.combat_service',
game_creation_service = 'stonehearth.services.server.game_creation.game_creation_service',
combat_state_component = 'stonehearth.components.combat_state.combat_state_component',
ace_buffs_component = 'stonehearth.components.buffs.buffs_component',
ace_buff = 'stonehearth.components.buffs.buff',
population_faction = 'stonehearth.services.server.population.population_faction',
projectile_component = 'stonehearth.components.projectile.projectile_component',
--ai_service = 'stonehearth.services.server.ai.ai_service',
--destroy_entity_action = 'stonehearth.ai.actions.destroy_entity_action',
--kill_entity = 'stonehearth.ai.actions.kill_entity'
}
local function monkey_patching()
for from, into in pairs(monkey_patches) do
local monkey_see = require('monkey_patches.' .. from)
local monkey_do = radiant.mods.require(into)
radiant.mixin(monkey_do, monkey_see)
end
end
local function create_service(name)
local path = string.format('services.server.%s.%s_service', name, name)
local service = require(path)()
local saved_variables = tower_defense._sv[name]
if not saved_variables then
saved_variables = radiant.create_datastore()
tower_defense._sv[name] = saved_variables
end
service.__saved_variables = saved_variables
service._sv = saved_variables:get_data()
saved_variables:set_controller(service)
saved_variables:set_controller_name('tower_defense:' .. name)
service:initialize()
tower_defense[name] = service
end
function tower_defense:_on_init()
tower_defense._sv = tower_defense.__saved_variables:get_data()
for _, name in ipairs(service_creation_order) do
create_service(name)
end
radiant.events.trigger_async(radiant, 'tower_defense:server:init')
radiant.log.write_('tower_defense', 0, 'SH:TD server initialized')
end
function tower_defense:_on_required_loaded()
monkey_patching()
radiant.events.trigger_async(radiant, 'tower_defense:server:required_loaded')
end
radiant.events.listen(tower_defense, 'radiant:init', tower_defense, tower_defense._on_init)
radiant.events.listen(radiant, 'radiant:required_loaded', tower_defense, tower_defense._on_required_loaded)
return tower_defense
| 36.308824
| 108
| 0.756582
|
4d9d7c15b54d03df7985da53b1586d73cc6cfc9f
| 3,809
|
cshtml
|
C#
|
App/App.Web/Views/Testimonials/List.cshtml
|
nzhul/garderob
|
eea0fefb51abe8f1d3b792912f0c0c1d52c50291
|
[
"MIT"
] | null | null | null |
App/App.Web/Views/Testimonials/List.cshtml
|
nzhul/garderob
|
eea0fefb51abe8f1d3b792912f0c0c1d52c50291
|
[
"MIT"
] | null | null | null |
App/App.Web/Views/Testimonials/List.cshtml
|
nzhul/garderob
|
eea0fefb51abe8f1d3b792912f0c0c1d52c50291
|
[
"MIT"
] | null | null | null |
@using App.Models.Testimonials
@using App.Models.Pages
@model IEnumerable<TestimonialViewModel>
@{
ViewBag.Title = "Атестати";
}
<section class="breadcrumbs">
<div class="container">
<div class="text-center breadcrumbs-item">
<h1>Галерия</h1><a href="@Url.Action("Index", "Home")">начало</a><i class="fa fa-angle-right"></i><a href="/testimonials/list">Галерия</a>
</div>
</div>
</section>
<!-- ! breadcrumbs end-->
<!-- content-->
<div class="container mt-40 pb-60">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h2 class="title-section mb-0 mt-0 text-center">Разгледайте нашите завършени проекти</h2>
<div class="cws_divider with-plus short-3 center mb-20 mt-10"></div>
<p class="text-center mb-0">Вижте какво казват за нашата услуга клиентите ни. Също така разгледайте как от вашите скици успяваме да направим завършени и качествени гардероби и мебели.</p>
</div>
</div>
@foreach (TestimonialViewModel testimonial in Model)
{
<div class="row gallery-row">
<div class="col-md-2">
<div class="gallery-row-image-wrapper">
@if (testimonial.OrderSketch != null)
{
var base64 = Convert.ToBase64String(testimonial.OrderSketch.Big);
var bigImgSrc = String.Format("data:image/jpg;base64,{0}", base64);
<div class="pic">
@Html.ByteImage(testimonial.OrderSketch.Small, "Скица на продукта")
<a href="@bigImgSrc" class="hover-effect alt fancy"><span class="plus fa fa-expand"></span></a>
</div>
}
else
{
<img src="~/Content/img/missing-photo-fe.jpg" alt="Липсваща снимка" />
}
<i class="fa fa-angle-double-right"></i>
<span>Скица</span>
</div>
</div>
<div class="col-md-2">
<div class="gallery-row-image-wrapper">
@if (testimonial.OrderDesign != null)
{
var base64 = Convert.ToBase64String(testimonial.OrderDesign.Big);
var bigImgSrc = String.Format("data:image/jpg;base64,{0}", base64);
<div class="pic">
@Html.ByteImage(testimonial.OrderDesign.Small, "Дизайн на продукта")
<a href="@bigImgSrc" class="hover-effect alt fancy"><span class="plus fa fa-expand"></span></a>
</div>
}
else
{
<img src="~/Content/img/missing-photo-fe.jpg" alt="Липсваща снимка" />
}
<i class="fa fa-angle-double-right"></i>
<span>Модел</span>
</div>
</div>
<div class="col-md-2">
<div class="gallery-row-image-wrapper">
@if (testimonial.OrderResult != null)
{
var base64 = Convert.ToBase64String(testimonial.OrderResult.Big);
var bigImgSrc = String.Format("data:image/jpg;base64,{0}", base64);
<div class="pic">
@Html.ByteImage(testimonial.OrderResult.Small, "Краен резултат")
<a href="@bigImgSrc" class="hover-effect alt fancy"><span class="plus fa fa-expand"></span></a>
</div>
}
else
{
<img src="~/Content/img/missing-photo-fe.jpg" alt="Липсваща снимка" />
}
<span>Резултат</span>
</div>
</div>
<div class="col-sm-6">
<div class="widget_wrapper">
<div class="testimonial">
<div class="quote">@testimonial.Text</div>
<div class="author">
@Html.ByteImage(testimonial.ClientPhoto, "Снимка на доволен клиент", "testimonial-client-photo")
<figure>
<figcaption>
@testimonial.ClientFullName @if (!string.IsNullOrEmpty(testimonial.ClientJobTitle)) { <span>[ @testimonial.ClientJobTitle ]</span> }
<div>@Html.Partial("Rating", testimonial.Rating)</div>
</figcaption>
</figure>
</div>
</div>
</div>
</div>
</div>
<div class="cws_divider with-plus long color-line-1 mt-40"></div>
}
<div class="row">
<div class="col-md-12">
@Html.Partial("_Pager", ViewBag.PagingData as PagingData)
</div>
</div>
</div>
| 33.707965
| 190
| 0.632449
|
a3d66047ff32ade7a9de089bc13ab7e284b411c5
| 2,745
|
java
|
Java
|
src/main/java/com/softb/system/repository/config/RepositoryConfig.java
|
erikpaulo/ipocket
|
3cb56fda85392f788c207d81d0271d1d48966b11
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/softb/system/repository/config/RepositoryConfig.java
|
erikpaulo/ipocket
|
3cb56fda85392f788c207d81d0271d1d48966b11
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/softb/system/repository/config/RepositoryConfig.java
|
erikpaulo/ipocket
|
3cb56fda85392f788c207d81d0271d1d48966b11
|
[
"Apache-2.0"
] | null | null | null |
package com.softb.system.repository.config;
import liquibase.integration.spring.SpringLiquibase;
import org.apache.commons.dbcp2.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import javax.sql.DataSource;
import java.net.URI;
import java.net.URISyntaxException;
@Configuration
@EnableJpaRepositories(basePackages = {
"com.softb.system.security.repository",
"com.softb.ipocket.account.repository",
"com.softb.ipocket.investment.repository",
"com.softb.ipocket.bill.repository",
"com.softb.ipocket.budget.repository",
"com.softb.ipocket.categorization.repository"
})
@EntityScan(basePackages = {
"com.softb.system.security.model",
"com.softb.ipocket.account.model",
"com.softb.ipocket.investment.model",
"com.softb.ipocket.bill.model",
// "com.softb.ipocket.dashboard.model",
"com.softb.ipocket.budget.model",
"com.softb.ipocket.general.model",
"com.softb.ipocket.categorization.model"
})
public class RepositoryConfig {
private final Logger logger = LoggerFactory.getLogger(RepositoryConfig.class);
@Autowired
private Environment environment;
@Bean
public SpringLiquibase liquibase(DataSource datasource) {
SpringLiquibase liquibase = null;
// if (!environment.acceptsProfiles(Constants.SPRING_PROFILE_PRODUCTION)) {
// logger.debug("Configuring Liquibase");
// liquibase = new SpringLiquibase();
// liquibase.setDataSource(datasource);
// liquibase.setChangeLog("classpath:config/liquibase/master.xml");
// liquibase.setContexts("development");
// }
return liquibase;
}
@Bean
public BasicDataSource dataSource() throws URISyntaxException {
URI dbUri = new URI(environment.getProperty("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = (dbUri.getUserInfo().split(":").length > 1 ? dbUri.getUserInfo().split(":")[1] : "");
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setUrl(dbUrl);
basicDataSource.setUsername(username);
basicDataSource.setPassword(password);
basicDataSource.setDriverClassName("org.postgresql.Driver");
return basicDataSource;
}
}
| 35.649351
| 111
| 0.725319
|
a31f5de3cf48e39c5b6b7417d10720c583babee5
| 6,432
|
java
|
Java
|
sourcedata/camel-camel-1.6.0/camel-core/src/main/java/org/apache/camel/builder/DataFormatClause.java
|
DXYyang/SDP
|
6ad0daf242d4062888ceca6d4a1bd4c41fd99b63
|
[
"Apache-2.0"
] | 6
|
2020-10-27T06:11:59.000Z
|
2021-09-09T13:52:42.000Z
|
sourcedata/camel-camel-1.6.0/camel-core/src/main/java/org/apache/camel/builder/DataFormatClause.java
|
DXYyang/SDP
|
6ad0daf242d4062888ceca6d4a1bd4c41fd99b63
|
[
"Apache-2.0"
] | 8
|
2020-11-16T20:41:38.000Z
|
2022-02-01T01:05:45.000Z
|
sourcedata/camel-camel-1.6.0/camel-core/src/main/java/org/apache/camel/builder/DataFormatClause.java
|
DXYyang/SDP
|
6ad0daf242d4062888ceca6d4a1bd4c41fd99b63
|
[
"Apache-2.0"
] | null | null | null |
/**
* 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.
*/
package org.apache.camel.builder;
import java.util.zip.Deflater;
import org.w3c.dom.Node;
import org.apache.camel.model.ProcessorType;
import org.apache.camel.model.dataformat.ArtixDSContentType;
import org.apache.camel.model.dataformat.ArtixDSDataFormat;
import org.apache.camel.model.dataformat.CsvDataFormat;
import org.apache.camel.model.dataformat.DataFormatType;
import org.apache.camel.model.dataformat.HL7DataFormat;
import org.apache.camel.model.dataformat.JaxbDataFormat;
import org.apache.camel.model.dataformat.JsonDataFormat;
import org.apache.camel.model.dataformat.SerializationDataFormat;
import org.apache.camel.model.dataformat.StringDataFormat;
import org.apache.camel.model.dataformat.TidyMarkupDataFormat;
import org.apache.camel.model.dataformat.XMLBeansDataFormat;
import org.apache.camel.model.dataformat.XStreamDataFormat;
import org.apache.camel.model.dataformat.ZipDataFormat;
import org.apache.camel.spi.DataFormat;
/**
* An expression for constructing the different possible {@link DataFormat}
* options.
*
* @version $Revision$
*/
public class DataFormatClause<T extends ProcessorType> {
private final T processorType;
private final Operation operation;
/**
* {@link DataFormat} operations.
*/
public enum Operation {
Marshal, Unmarshal
}
public DataFormatClause(T processorType, Operation operation) {
this.processorType = processorType;
this.operation = operation;
}
/**
* Uses the
* <a href="http://activemq.apache.org/camel/artix-data-services.html">Artix Data Services</a>
* data format for dealing with lots of different message formats such as SWIFT etc.
*/
public T artixDS() {
return dataFormat(new ArtixDSDataFormat());
}
/**
* Uses the
* <a href="http://activemq.apache.org/camel/artix-data-services.html">Artix Data Services</a>
* data format with the specified type of ComplexDataObject
* for marshalling and unmarshalling messages using the dataObject's default Source and Sink.
*/
public T artixDS(Class<?> dataObjectType) {
return dataFormat(new ArtixDSDataFormat(dataObjectType));
}
/**
* Uses the
* <a href="http://activemq.apache.org/camel/artix-data-services.html">Artix Data Services</a>
* data format with the specified type of ComplexDataObject
* for marshalling and unmarshalling messages using the dataObject's default Source and Sink.
*/
public T artixDS(Class<?> elementType, ArtixDSContentType contentType) {
return dataFormat(new ArtixDSDataFormat(elementType, contentType));
}
/**
* Uses the
* <a href="http://activemq.apache.org/camel/artix-data-services.html">Artix Data Services</a>
* data format with the specified content type
* for marshalling and unmarshalling messages
*/
public T artixDS(ArtixDSContentType contentType) {
return dataFormat(new ArtixDSDataFormat(contentType));
}
/**
* Uses the CSV data format
*/
public T csv() {
return dataFormat(new CsvDataFormat());
}
/**
* Uses the HL7 data format
*/
public T hl7() {
return dataFormat(new HL7DataFormat());
}
/**
* Uses the JAXB data format
*/
public T jaxb() {
return dataFormat(new JaxbDataFormat());
}
/**
* Uses the JAXB data format turning pretty printing on or off
*/
public T jaxb(boolean prettyPrint) {
return dataFormat(new JaxbDataFormat(prettyPrint));
}
/**
* Uses the Java Serialization data format
*/
public T serialization() {
return dataFormat(new SerializationDataFormat());
}
/**
* Uses the String data format
*/
public T string() {
return string(null);
}
/**
* Uses the String data format supporting encoding using given charset
*/
public T string(String charset) {
StringDataFormat sdf = new StringDataFormat();
sdf.setCharset(charset);
return dataFormat(sdf);
}
/**
* Uses the JAXB data format
*/
public T xmlBeans() {
return dataFormat(new XMLBeansDataFormat());
}
/**
* Return WellFormed HTML (an XML Document) either
* {@link java.lang.String} or {@link org.w3c.dom.Node}
*/
public T tidyMarkup(Class<?> dataObjectType) {
return dataFormat(new TidyMarkupDataFormat(dataObjectType));
}
/**
* Return TidyMarkup in the default format
* as {@link org.w3c.dom.Node}
*/
public T tidyMarkup() {
return dataFormat(new TidyMarkupDataFormat(Node.class));
}
/**
* Uses the XStream data format
*/
public T xstream() {
return dataFormat(new XStreamDataFormat());
}
/**
* Uses the JSON data format
*/
public T json() {
return dataFormat(new JsonDataFormat());
}
private T dataFormat(DataFormatType dataFormatType) {
switch (operation) {
case Unmarshal:
return (T)processorType.unmarshal(dataFormatType);
case Marshal:
return (T)processorType.marshal(dataFormatType);
default:
throw new IllegalArgumentException("Unknown DataFormat operation: " + operation);
}
}
public T zip() {
ZipDataFormat zdf = new ZipDataFormat(Deflater.DEFAULT_COMPRESSION);
return dataFormat(zdf);
}
public T zip(int compressionLevel) {
ZipDataFormat zdf = new ZipDataFormat(compressionLevel);
return dataFormat(zdf);
}
}
| 30.483412
| 98
| 0.676461
|
1a664001e1816ab0348f8b0f05002cc402c9854a
| 1,916
|
cs
|
C#
|
Funcky.Test/Extensions/EnumerableExtensions/MemoizeTest.cs
|
FreeApophis/Funcky
|
9340ed26badf9bef6901dc12f2d4371addf929f2
|
[
"Apache-2.0",
"MIT"
] | 4
|
2019-03-12T09:58:35.000Z
|
2020-02-10T23:19:19.000Z
|
Funcky.Test/Extensions/EnumerableExtensions/MemoizeTest.cs
|
FreeApophis/Funcky
|
9340ed26badf9bef6901dc12f2d4371addf929f2
|
[
"Apache-2.0",
"MIT"
] | 1
|
2019-04-02T08:47:57.000Z
|
2019-04-04T11:42:23.000Z
|
Funcky.Test/Extensions/EnumerableExtensions/MemoizeTest.cs
|
FreeApophis/Funcky
|
9340ed26badf9bef6901dc12f2d4371addf929f2
|
[
"Apache-2.0",
"MIT"
] | 2
|
2019-08-12T17:49:31.000Z
|
2019-09-07T16:54:36.000Z
|
using Funcky.Test.TestUtils;
namespace Funcky.Test;
public sealed class MemoizeTest
{
[Fact]
public void MemoizeIsEnumeratedLazily()
{
var doNotEnumerate = new FailOnEnumerationSequence<object>();
using var memoized = doNotEnumerate.Memoize();
}
[Fact]
public void TheUnderlyingEnumerableIsOnlyEnumeratedOnce()
{
var enumerateOnce = EnumerateOnce.Create(Sequence.Return("Alpha", "Beta"));
using var memoized = enumerateOnce.Memoize();
Assert.Equal("Alpha", memoized.First());
Assert.Equal("Alpha", memoized.First());
Assert.Equal("Beta", memoized.Last());
Assert.Equal("Beta", memoized.Last());
}
[Fact]
public void MemoizingAnEmptyListIsEmpty()
{
var empty = Enumerable.Empty<string>();
using var memoized = empty.Memoize();
Assert.Empty(memoized);
}
[Fact]
public void OutOfOrderMoveNextReturnsItemsInTheRightOrder()
{
using var memoizedRange = Enumerable.Range(1, 10).Memoize();
using var enumerator1 = memoizedRange.GetEnumerator();
Assert.True(enumerator1.MoveNext());
Assert.True(enumerator1.MoveNext());
Assert.Equal(2, enumerator1.Current);
using var enumerator2 = memoizedRange.GetEnumerator();
Assert.True(enumerator2.MoveNext());
Assert.Equal(1, enumerator2.Current);
Assert.True(enumerator1.MoveNext());
Assert.True(enumerator1.MoveNext());
Assert.Equal(4, enumerator1.Current);
Assert.True(enumerator2.MoveNext());
Assert.Equal(2, enumerator2.Current);
Assert.True(enumerator2.MoveNext());
Assert.Equal(3, enumerator2.Current);
Assert.True(enumerator2.MoveNext());
Assert.Equal(4, enumerator2.Current);
Assert.True(enumerator2.MoveNext());
Assert.Equal(5, enumerator2.Current);
}
}
| 27.768116
| 83
| 0.649269
|
af37cfe26572c1d05ce2aede9ddb92cb081b1bd0
| 565
|
py
|
Python
|
Project1/toFrames.py
|
vinitkumawat/uta-machine-learning
|
1337a03ab0c0683839761a9fc7d2be8b496a9442
|
[
"MIT"
] | null | null | null |
Project1/toFrames.py
|
vinitkumawat/uta-machine-learning
|
1337a03ab0c0683839761a9fc7d2be8b496a9442
|
[
"MIT"
] | null | null | null |
Project1/toFrames.py
|
vinitkumawat/uta-machine-learning
|
1337a03ab0c0683839761a9fc7d2be8b496a9442
|
[
"MIT"
] | null | null | null |
import cv2
import numpy as np
import imutils
import shutil,os
shutil.rmtree('frames')
try:
os.makedirs('frames')
except OSError as e:
pass
video='2.mp4'
cap = cv2.VideoCapture(video)
cnt=0
if (cap.isOpened()== False):
print("Error opening video stream or file")
ret,first_frame = cap.read()
while(cap.isOpened()):
ret, frame = cap.read()
if ret == True:
cv2.imshow("image",frame)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
cv2.imwrite('frames/'+str(cnt)+'.png',frame)
cnt=cnt+1
else:
break
cv2.destroyAllWindows()
| 17.65625
| 48
| 0.653097
|
e7651a39df675abb10e8964f92a06f7464a06e95
| 1,381
|
php
|
PHP
|
src/DataFixtures/CategoryFixtures.php
|
robert611/store
|
cf7de44e7ef514d55768237572081e43492cd9e7
|
[
"MIT"
] | null | null | null |
src/DataFixtures/CategoryFixtures.php
|
robert611/store
|
cf7de44e7ef514d55768237572081e43492cd9e7
|
[
"MIT"
] | null | null | null |
src/DataFixtures/CategoryFixtures.php
|
robert611/store
|
cf7de44e7ef514d55768237572081e43492cd9e7
|
[
"MIT"
] | null | null | null |
<?php
namespace App\DataFixtures;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use App\Entity\Category;
class CategoryFixtures extends Fixture
{
public function load(ObjectManager $manager)
{
$categories = $this->getCategories();
foreach ($categories as $key => $data) {
$category = new Category();
$category->setName($data['name']);
$category->setIcon($data['icon']);
$manager->persist($category);
$manager->flush();
$this->addReference('category.' . $key, $category);
}
}
public function getCategories()
{
return [
['name' => 'Elektronika', 'icon' => 'computer'],
['name' => 'Moda', 'icon' => 'style'],
['name' => 'Dom i ogród', 'icon' => 'home'],
['name' => 'Supermarket', 'icon' => 'shopping_basket'],
['name' => 'Dziecko', 'icon' => 'child_friendly'],
['name' => 'Uroda', 'icon' => 'face'],
['name' => 'Zdrowie', 'icon' => 'healing'],
['name' => 'Kultura i rozrywka', 'icon' => 'panorama'],
['name' => 'Sport i turystyka', 'icon' => 'directions_run'],
['name' => 'Motoryzacja', 'icon' => 'directions_car'],
['name' => 'Nieruchomości', 'icon' => 'home'],
];
}
}
| 30.688889
| 72
| 0.511948
|
40bc212e61e7d007da4887713b0d425a0665f70d
| 1,939
|
tsx
|
TypeScript
|
packages-web/datagrid/src/components/Pagination.tsx
|
Robinfr/widgets-resources
|
b489d4a3a3afad8a6cc466695bc249b02d30a3b0
|
[
"Apache-2.0"
] | null | null | null |
packages-web/datagrid/src/components/Pagination.tsx
|
Robinfr/widgets-resources
|
b489d4a3a3afad8a6cc466695bc249b02d30a3b0
|
[
"Apache-2.0"
] | null | null | null |
packages-web/datagrid/src/components/Pagination.tsx
|
Robinfr/widgets-resources
|
b489d4a3a3afad8a6cc466695bc249b02d30a3b0
|
[
"Apache-2.0"
] | null | null | null |
import { createElement, ReactElement } from "react";
export interface PaginationProps {
canNextPage: boolean;
canPreviousPage: boolean;
gotoPage: (page: number) => void;
nextPage: () => void;
numberOfItems?: number;
page: number;
pageSize: number;
previousPage: () => void;
}
export function Pagination({
gotoPage,
previousPage,
page,
nextPage,
canNextPage,
canPreviousPage,
pageSize,
numberOfItems
}: PaginationProps): ReactElement {
const numberOfPages = numberOfItems !== undefined ? Math.ceil(numberOfItems / pageSize) : undefined;
const lastPage = numberOfPages !== undefined ? numberOfPages - 1 : 0;
const hasLastPage = numberOfPages !== undefined;
const initialItem = page * pageSize + 1;
const lastItem = canNextPage || !numberOfItems ? (page + 1) * pageSize : numberOfItems;
return (
<div className="pagination">
<button className="btn" onClick={() => gotoPage(0)} disabled={page === 0}>
<span className="glyphicon glyphicon-step-backward" />
</button>
<button className="btn" onClick={() => previousPage()} disabled={!canPreviousPage}>
<span className="glyphicon glyphicon-backward" />
</button>
<div className="paging-status">
{initialItem} to {lastItem}{" "}
{hasLastPage ? `of ${numberOfItems ?? (numberOfPages ?? 1) * pageSize}` : ""}
</div>
<button className="btn" onClick={() => nextPage()} disabled={!canNextPage}>
<span className="glyphicon glyphicon-forward" />
</button>
{hasLastPage && (
<button className="btn" onClick={() => gotoPage(lastPage)} disabled={page === lastPage}>
<span className="glyphicon glyphicon-step-forward" />
</button>
)}
</div>
);
}
| 37.288462
| 104
| 0.585353
|
0d2438b0520bca68a76069ad6b61ed924c47ad88
| 769
|
cs
|
C#
|
UWP/Forms/Renderers/UWPVerticalSliderRenderer.cs
|
hyvart/Unjamm
|
c5e6aa0ff8d2976732246ac94ef3d11a738ba615
|
[
"MIT"
] | 2
|
2020-06-15T04:25:41.000Z
|
2021-08-24T13:27:08.000Z
|
UWP/Forms/Renderers/UWPVerticalSliderRenderer.cs
|
aosodosoa/Unjammit
|
3e58ad154bc60051a4cf5e42721246e15f5c26ed
|
[
"MIT"
] | 11
|
2019-10-05T14:22:34.000Z
|
2021-10-02T11:25:41.000Z
|
UWP/Forms/Renderers/UWPVerticalSliderRenderer.cs
|
aosodosoa/Unjammit
|
3e58ad154bc60051a4cf5e42721246e15f5c26ed
|
[
"MIT"
] | 5
|
2019-10-05T14:55:45.000Z
|
2022-02-12T04:36:40.000Z
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Platform.UWP;
[assembly: ExportRenderer(typeof(Jammit.Forms.Views.VerticalSlider), typeof(Jammit.Forms.Renderers.UWPVerticalSliderRenderer))]
namespace Jammit.Forms.Renderers
{
public class UWPVerticalSliderRenderer : SliderRenderer
{
public UWPVerticalSliderRenderer() { }
#region ViewRenderer overrides
protected override void OnElementChanged(ElementChangedEventArgs<Slider> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.Orientation = Windows.UI.Xaml.Controls.Orientation.Vertical;
}
}
#endregion ViewRenderer overrides
}
}
| 24.03125
| 127
| 0.747724
|
af4c0a277bab67f4a9c349b32c90ece9ed175395
| 10,527
|
rs
|
Rust
|
src/bub/metadata.rs
|
kurotakazuki/Floaout
|
3f7643e4a5aeb3fdc9c57e7e23165d32a7ee82b4
|
[
"Apache-2.0",
"MIT"
] | 5
|
2020-01-25T05:40:48.000Z
|
2020-02-14T22:38:41.000Z
|
src/bub/metadata.rs
|
kurotakazuki/floaout
|
a1eb58fa205f23c69a62539b63da26286715922f
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
src/bub/metadata.rs
|
kurotakazuki/floaout
|
a1eb58fa205f23c69a62539b63da26286715922f
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
use crate::bub::{
functions::{parse, BubFns, BubFnsAST, BubFnsVariable},
BubID,
};
use crate::io::{ReadExt, WriteExt};
use crate::utils::{read_crc, write_crc};
use crate::{LpcmKind, Metadata, CRC_32K_4_2};
use mycrc::CRC;
use std::io::{ErrorKind, Read, Result, Write};
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum BubState {
Head,
Body,
Stopped,
Ended,
}
impl BubState {
pub fn is_head(&self) -> bool {
matches!(self, Self::Head)
}
pub fn is_body(&self) -> bool {
matches!(self, Self::Body)
}
pub fn is_stopped(&self) -> bool {
matches!(self, Self::Stopped)
}
pub fn is_ended(&self) -> bool {
matches!(self, Self::Ended)
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum BubSampleKind {
Lpcm,
Expr(BubFnsAST),
}
impl From<BubFnsAST> for BubSampleKind {
fn from(ast: BubFnsAST) -> Self {
Self::Expr(ast)
}
}
impl BubSampleKind {
pub fn default_expr() -> Self {
parse("0".as_bytes(), &BubFnsVariable::Sum).unwrap().into()
}
pub fn read<R: Read>(reader: &mut R) -> Result<Self> {
let value: u8 = reader.read_le()?;
Ok(match value {
0 => Self::Lpcm,
1 => Self::default_expr(),
_ => return Err(ErrorKind::InvalidData.into()),
})
}
pub fn read_and_calc_bytes<R: Read>(reader: &mut R, crc: &mut CRC<u32>) -> Result<Self> {
let value: u8 = reader.read_le_and_calc_bytes(crc)?;
Ok(match value {
0 => Self::Lpcm,
1 => Self::default_expr(),
_ => return Err(ErrorKind::InvalidData.into()),
})
}
pub fn write<W: Write>(&self, writer: &mut W) -> Result<()> {
writer.write_le(self.to_u8())
}
pub fn write_and_calc_bytes<W: Write>(&self, writer: &mut W, crc: &mut CRC<u32>) -> Result<()> {
writer.write_le_and_calc_bytes(self.to_u8(), crc)
}
pub fn from_u8(value: u8) -> Self {
match value {
0 => Self::Lpcm,
1 => Self::default_expr(),
_ => unimplemented!(),
}
}
pub const fn to_u8(&self) -> u8 {
match self {
Self::Lpcm => 0,
Self::Expr(_) => 1,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct BubMetadata {
// In File Header
/// Version of Bubble File Format Specification.
pub spec_version: u8,
/// Bubble ID
pub bub_id: BubID,
/// Version of Bubble
pub bub_version: u16,
/// Number of frames
pub frames: u64,
/// Samples Per Sec
pub samples_per_sec: f64,
/// Bits Per Sample
pub lpcm_kind: LpcmKind,
/// Bubble LPCM Kind
pub bub_sample_kind: BubSampleKind,
/// Name of Bubble
pub name: String,
/// Bubble State
pub bub_state: BubState,
/// Head Absolute Frame
pub head_absolute_frame: u64,
/// Bubble Functions
pub bub_fns: BubFns,
/// Foot Absolute Frame Plus One
pub foot_absolute_frame_plus_one: u64,
/// Next Head Absolute Frame
/// `None` if 0.
pub next_head_absolute_frame: Option<u64>,
}
impl BubMetadata {
pub const fn new(
frames: u64,
first_head_absolute_frame: u64,
samples_per_sec: f64,
lpcm_kind: LpcmKind,
bub_sample_kind: BubSampleKind,
name: String,
) -> Self {
Self {
spec_version: 0,
bub_id: BubID::new(0, None),
bub_version: 0,
frames,
samples_per_sec,
lpcm_kind,
bub_sample_kind,
name,
bub_state: BubState::Stopped,
head_absolute_frame: first_head_absolute_frame,
bub_fns: BubFns::new(),
foot_absolute_frame_plus_one: 0,
// TODO: Value must not be 0
next_head_absolute_frame: Some(first_head_absolute_frame),
}
}
pub const fn frames(&self) -> u64 {
self.frames
}
pub const fn lpcm_kind(&self) -> LpcmKind {
self.lpcm_kind
}
pub const fn samples_per_sec(&self) -> f64 {
self.samples_per_sec
}
pub const fn secs(&self) -> u64 {
self.frames() / self.samples_per_sec() as u64
}
pub const fn millis(&self) -> u128 {
self.frames() as u128 * 1_000 / self.samples_per_sec() as u128
}
pub const fn micros(&self) -> u128 {
self.frames() as u128 * 1_000_000 / self.samples_per_sec() as u128
}
pub const fn nanos(&self) -> u128 {
self.frames() as u128 * 1_000_000_000 / self.samples_per_sec() as u128
}
pub fn set_as_head(&mut self, pos: u64) {
self.head_absolute_frame = pos;
self.bub_state = BubState::Head;
}
pub fn set_as_body(&mut self) {
self.bub_state = BubState::Body;
}
pub fn set_as_stopped(&mut self) {
self.bub_state = BubState::Stopped;
}
pub fn set_as_ended(&mut self) {
self.bub_state = BubState::Ended;
}
pub(crate) fn set_bub_state_from_connected_and_ended(&mut self, pos: u64) {
// TODO: Create closures method
match self.next_head_absolute_frame {
Some(next_head_absolute_frame) => {
if next_head_absolute_frame == pos {
self.set_as_head(pos)
} else {
self.set_as_stopped()
}
}
None => self.set_as_ended(),
}
}
pub fn init_with_pos(&mut self, pos: u64) {
match self.bub_state {
BubState::Head => {
if self.foot_absolute_frame_plus_one == pos {
self.set_bub_state_from_connected_and_ended(pos);
} else {
self.set_as_body();
}
}
BubState::Body => {
if self.foot_absolute_frame_plus_one == pos {
self.set_bub_state_from_connected_and_ended(pos);
}
}
BubState::Stopped => {
if self.next_head_absolute_frame.expect("Some") == pos {
self.set_as_head(pos);
}
}
BubState::Ended => (),
}
}
pub(crate) fn next_head_absolute_frame_from_relative(
next_head_relative_frame: u64,
pos: u64,
) -> Option<u64> {
if next_head_relative_frame != 0 {
Some(next_head_relative_frame + pos - 1)
} else {
None
}
}
pub(crate) fn set_next_head_absolute_frame_from_relative(
&mut self,
next_head_relative_frame: u64,
pos: u64,
) {
self.next_head_absolute_frame =
Self::next_head_absolute_frame_from_relative(next_head_relative_frame, pos);
}
// IO
/// TODO: Refactoring
pub(crate) fn read_next_head_absolute_frame_from_relative<R: std::io::Read>(
&mut self,
reader: &mut R,
pos: u64,
crc: &mut CRC<u32>,
) -> Result<()> {
let next_head_relative_frame: u64 = reader.read_le_and_calc_bytes(crc)?;
self.set_next_head_absolute_frame_from_relative(next_head_relative_frame, pos);
Ok(())
}
pub fn read<R: std::io::Read>(reader: &mut R) -> Result<(Self, CRC<u32>)> {
let mut crc = CRC_32K_4_2;
let spec_version = reader.read_le_and_calc_bytes(&mut crc)?;
let bub_id = BubID::read_and_calc_bytes(reader, &mut crc)?;
let bub_version = reader.read_le_and_calc_bytes(&mut crc)?;
let frames = reader.read_le_and_calc_bytes(&mut crc)?;
let first_head_absolute_frame: u64 = reader.read_le_and_calc_bytes(&mut crc)?;
let next_head_absolute_frame =
Self::next_head_absolute_frame_from_relative(first_head_absolute_frame, 1);
let samples_per_sec = reader.read_le_and_calc_bytes(&mut crc)?;
let lpcm_kind = LpcmKind::read_and_calc_bytes(reader, &mut crc)?;
let bub_sample_kind = BubSampleKind::read_and_calc_bytes(reader, &mut crc)?;
let name_size: u8 = reader.read_le_and_calc_bytes(&mut crc)?;
let name = reader.read_string_for_and_calc_bytes(name_size as usize, &mut crc)?;
// CRC
read_crc(reader, &mut crc)?;
Ok((
Self {
spec_version,
bub_id,
bub_version,
frames,
samples_per_sec,
lpcm_kind,
bub_sample_kind,
name,
bub_state: BubState::Stopped,
head_absolute_frame: first_head_absolute_frame,
bub_fns: BubFns::new(),
foot_absolute_frame_plus_one: 0,
next_head_absolute_frame,
},
crc,
))
}
// fn next_head_absolute_frame_into_relative(&self, pos: u64) -> u64 {
// match self.next_head_absolute_frame {
// Some(n) => 1 + n - pos,
// None => 0,
// }
// }
pub fn write<W: std::io::Write>(&self, writer: &mut W) -> Result<CRC<u32>> {
let mut crc = CRC_32K_4_2;
writer.write_le_and_calc_bytes(self.spec_version, &mut crc)?;
self.bub_id.write_and_calc_bytes(writer, &mut crc)?;
writer.write_le_and_calc_bytes(self.bub_version, &mut crc)?;
writer.write_le_and_calc_bytes(self.frames, &mut crc)?;
writer.write_le_and_calc_bytes(self.head_absolute_frame, &mut crc)?;
writer.write_le_and_calc_bytes(self.samples_per_sec, &mut crc)?;
self.lpcm_kind.write_and_calc_bytes(writer, &mut crc)?;
self.bub_sample_kind
.write_and_calc_bytes(writer, &mut crc)?;
writer.write_le_and_calc_bytes(self.name.len() as u8, &mut crc)?;
writer.write_str_and_calc_bytes(&self.name, &mut crc)?;
// CRC
write_crc(writer, &mut crc)?;
Ok(crc)
}
}
impl Metadata for BubMetadata {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn write_and_read() -> Result<()> {
let bub_metadata = BubMetadata::new(
96000,
1,
96000.0,
LpcmKind::F32LE,
BubSampleKind::Lpcm,
String::from("Vocal"),
);
let expected = bub_metadata.clone();
let mut v: Vec<u8> = Vec::new();
bub_metadata.write(&mut v)?;
let val = BubMetadata::read(&mut &v[..])?.0;
assert_eq!(val, expected);
Ok(())
}
}
| 27.99734
| 100
| 0.564453
|
9f4d7f96544e2facea7e971dfeb5e5fe17d2c3e4
| 1,335
|
lua
|
Lua
|
state-machines/state-machines-du.lua
|
jasondelaat/pico8-tools
|
2164aa5b80a79f565172ef62a5be3ec0e8917a56
|
[
"MIT"
] | 1
|
2022-01-25T13:51:36.000Z
|
2022-01-25T13:51:36.000Z
|
state-machines/state-machines-du.lua
|
jasondelaat/pico8-tools
|
2164aa5b80a79f565172ef62a5be3ec0e8917a56
|
[
"MIT"
] | null | null | null |
state-machines/state-machines-du.lua
|
jasondelaat/pico8-tools
|
2164aa5b80a79f565172ef62a5be3ec0e8917a56
|
[
"MIT"
] | null | null | null |
-- state-machines-du -------------------------------------------------------
-- copyright (c) 2021 jason delaat
-- mit license: https://github.com/jasondelaat/pico8-tools/blob/release/license
----------------------------------------------------------------------------
-- simple state machine manager with draw and update functions.
-- token count: 107
------------------------------------------------------------------------
state_machine = {}
function state_machine:new()
return {
_current_state=nil,
add_state=state_machine.add_state,
set_state=state_machine.set_state,
get_state=state_machine.get_state,
update=state_machine.update,
draw=state_machine.draw
}
end
function state_machine:add_state(name, transition, update, draw)
self[name] = {transition=transition, update=update, draw=draw}
end
function state_machine:set_state(name)
self._current_state = name
end
function state_machine:get_state()
return self[self._current_state]
end
function state_machine:update()
local new_state = self:get_state().transition()
if new_state != self._current_state then
self:set_state(new_state)
end
self:get_state().update()
end
function state_machine:draw()
self:get_state().draw()
end
-- end state-machines-du ---------------------------------------------------
| 29.666667
| 79
| 0.6
|
421d6bd5bdbb8d70672cc12beb9020178446e4fd
| 518
|
dart
|
Dart
|
tests/compiler/dart2js/rti/data/generic_method_tearoff.dart
|
annagrin/sdk
|
dfce72bbf9bf359ecd810964259978e24c55e237
|
[
"BSD-3-Clause"
] | 2
|
2020-03-09T11:45:05.000Z
|
2021-06-08T12:06:05.000Z
|
tests/compiler/dart2js/rti/data/generic_method_tearoff.dart
|
annagrin/sdk
|
dfce72bbf9bf359ecd810964259978e24c55e237
|
[
"BSD-3-Clause"
] | 1
|
2021-01-21T14:45:59.000Z
|
2021-01-21T14:45:59.000Z
|
tests/compiler/dart2js/rti/data/generic_method_tearoff.dart
|
annagrin/sdk
|
dfce72bbf9bf359ecd810964259978e24c55e237
|
[
"BSD-3-Clause"
] | 3
|
2020-02-13T02:08:04.000Z
|
2020-08-09T07:49:55.000Z
|
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
T method1a<T>() => null;
T method1b<T>() => null;
class Class {
T method2a<T>() => null;
T method2b<T>() => null;
}
main() {
method1a();
T Function<T>() f1 = method1b;
Class c = new Class();
c.method2a();
T Function<T>() f2 = c.method2b;
print(f1.runtimeType == f2.runtimeType);
}
| 22.521739
| 77
| 0.646718
|
75317e1f85628bec699117b8e2e3500b3bf7ab9b
| 2,166
|
css
|
CSS
|
public/stylesheets/landing.css
|
ckylek/yelp-camp
|
7ebb7bacde652526aecb39f3ea25fbb815ada8d2
|
[
"MIT"
] | null | null | null |
public/stylesheets/landing.css
|
ckylek/yelp-camp
|
7ebb7bacde652526aecb39f3ea25fbb815ada8d2
|
[
"MIT"
] | 1
|
2020-03-03T15:57:31.000Z
|
2020-03-03T15:57:31.000Z
|
public/stylesheets/landing.css
|
ckylek/yelp-camp
|
7ebb7bacde652526aecb39f3ea25fbb815ada8d2
|
[
"MIT"
] | null | null | null |
body {
background-color: #000;
}
#landing-header {
z-index: 1;
position: relative;
text-align: center;
padding-top: 40vh;
}
#landing-header h1 {
display: table;
color: #fff;
background-color: hsla(0, 0%, 0%, 0.5);
margin: 0px auto 10px auto;
padding: 1vw;
}
.slideshow {
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: 0;
list-style: none;
margin: 0;
padding: 0;
}
.slideshow li {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background-size: cover;
background-position: 50% 50%;
background-repeat: no-repeat;
opacity: 0;
z-index: 0;
animation: imageAnimation 60s linear infinite;
}
.slideshow li:nth-child(1) {
background-image: url(https://images.unsplash.com/photo-1521223619409-8085d2607891?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1867&q=80)
}
.slideshow li:nth-child(2) {
background-image: url(https://images.unsplash.com/photo-1520950237264-dfe336995c34?ixlib=rb-1.2.1&auto=format&fit=crop&w=1867&q=80);
animation-delay: 10s;
}
.slideshow li:nth-child(3) {
background-image: url(https://images.unsplash.com/photo-1494086719471-68358638b028?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80);
animation-delay: 20s;
}
.slideshow li:nth-child(4) {
background-image: url(https://images.unsplash.com/photo-1526486302639-778115f9b298?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1951&q=80);
animation-delay: 30s;
}
.slideshow li:nth-child(5) {
background-image: url(https://images.unsplash.com/photo-1558864255-eced94afc9ec?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1952&q=80);
animation-delay: 40s;
}
.slideshow li:nth-child(6) {
background-image: url(https://images.unsplash.com/photo-1563096334-79fc11eaadd8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80);
animation-delay: 50s;
}
@keyframes imageAnimation {
0% {
opacity: 0;
animation-timing-function: ease-in;
}
10% {
opacity: 1;
animation-timing-function: ease-out;
}
20% {
opacity: 1
}
30% {
opacity: 0
}
}
| 25.482353
| 160
| 0.693906
|
4352f8e7a301e40c2b265d3dfb15d4423760eab4
| 6,094
|
tsx
|
TypeScript
|
src/Containers/Home/Home.tsx
|
tap0212/mastermind-game
|
c078963326aa50cb3f1ba42681f16a52617844e5
|
[
"MIT"
] | 1
|
2021-07-23T11:29:00.000Z
|
2021-07-23T11:29:00.000Z
|
src/Containers/Home/Home.tsx
|
tap0212/mastermind-game
|
c078963326aa50cb3f1ba42681f16a52617844e5
|
[
"MIT"
] | null | null | null |
src/Containers/Home/Home.tsx
|
tap0212/mastermind-game
|
c078963326aa50cb3f1ba42681f16a52617844e5
|
[
"MIT"
] | null | null | null |
import ColorPicker from '@/Components/ColorPicker/ColorPicker';
import GameBoardRow from '@/Components/GameBoardRow/GameBoardRow';
import { HomeCreators } from '@/store/reducers/homeReducer';
import { makeSelectHome, selectColor, selectGameMap } from '@/store/selectors/homeSelectors';
import { COLORS } from '@/styling/colors';
import { ChooseColorPayload, SetResultPayload } from '@/types/types';
import { GameStep } from '@/utils/GameInitiator';
import React, { memo, useState } from 'react';
import { useMemo } from 'react';
import { connect } from 'react-redux';
import { RouteComponentProps } from 'react-router-dom';
import { compose } from 'redux';
import { Button, Modal, Collapse } from 'antd';
const { Panel } = Collapse;
import { createStructuredSelector } from 'reselect';
import { AccordianWrapper, GameBoard, Wrapper } from './Home.styles';
import { useCallback } from 'react';
import { useEffect } from 'react';
interface StateProps {
selectedColor: string;
gameMap: GameStep[];
}
interface DispatchProps {
dispatchSetColor: (e: string) => void;
dispatchSubmitColor: (s: ChooseColorPayload) => void;
dispatchCheckResult: (s: SetResultPayload) => void;
dispatchReset: () => void;
}
type Props = RouteComponentProps;
export type PropsType = StateProps & DispatchProps & Props;
const Home = (props: PropsType) => {
const {
dispatchSetColor,
dispatchReset,
selectedColor,
gameMap,
dispatchSubmitColor,
dispatchCheckResult,
} = props;
const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
useEffect(() => {
if (!gameMap.filter((e) => e.resultChecked === false).length) {
setIsModalVisible(true);
}
}, [gameMap]);
const handleOk = () => {
setIsModalVisible(false);
};
const handleCancel = () => {
setIsModalVisible(false);
};
const colors = useMemo(
() => [
COLORS.YELLOW,
COLORS.PINK,
COLORS.GREEN,
COLORS.TERQUISH,
COLORS.OLIVE,
COLORS.MERGENTA,
],
[],
);
const handleChangeColor = (e: string) => {
dispatchSetColor(e);
};
const handleChangeChoosenColor = (rowId: number, color: string, columnId: number) => {
dispatchSubmitColor({ rowId, color, columnId });
};
const checkResult = (rowId: number) => {
const rowToBeChecked = gameMap.find((e) => e.id === rowId);
const results: boolean[] = [];
for (let i = 0; i < 4; i++) {
results.push(rowToBeChecked?.hiddenColors[i] === rowToBeChecked?.choosenColors[i]);
}
dispatchCheckResult({ results, rowId });
};
const isRowEnabled = useCallback(
(rowId: number): boolean => {
const prevRow = gameMap[rowId - 1];
if (prevRow) {
return prevRow.resultChecked;
}
return true;
},
[gameMap],
);
const handleStartOver = () => {
dispatchReset();
handleCancel();
};
return (
<>
<AccordianWrapper>
<Collapse defaultActiveKey={['1']}>
<Panel header="Rules" key="1">
<p>
Try to guess the pattern, in both order and color, within ten turns.
After submitting a row, a small black peg is placed for each code peg
from the guess which is correct in both color and position. A white peg
indicates the existence of a correct color code peg placed in the wrong
position.{' '}
</p>
</Panel>
</Collapse>
</AccordianWrapper>
<Wrapper>
<GameBoard>
{gameMap.map((e) => (
<GameBoardRow
key={e.id}
rowId={e.id}
scores={e.scores}
colors={e.choosenColors}
submitColor={handleChangeChoosenColor}
selectedColor={selectedColor}
checkResult={checkResult}
resultChecked={e.resultChecked}
isRowEnabled={isRowEnabled}
/>
))}
</GameBoard>
<ColorPicker
selectedColor={selectedColor}
setSelectedColor={handleChangeColor}
colors={colors}
/>
<Modal
title={null}
footer={null}
visible={isModalVisible}
onOk={handleOk}
onCancel={handleCancel}
>
<div
style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
}}
>
<h1>Game Over</h1>
<Button onClick={handleStartOver}>Start Over</Button>
</div>
</Modal>
</Wrapper>
</>
);
};
const mapStateToProps = createStructuredSelector({
home: makeSelectHome,
selectedColor: selectColor(),
gameMap: selectGameMap(),
});
const mapDispatchToProps = {
dispatchSetColor: (e: string) => HomeCreators.setColor(e),
dispatchSubmitColor: (e: ChooseColorPayload) => HomeCreators.submitColor(e),
dispatchCheckResult: (s: SetResultPayload) => HomeCreators.checkResult(s),
dispatchReset: () => HomeCreators.reset(),
};
const withConnect = connect<StateProps, DispatchProps, Props>(mapStateToProps, mapDispatchToProps);
export default compose<React.FC<PropsType>>(withConnect, memo)(Home);
| 36.27381
| 99
| 0.528224
|
1a8fdaf80cf4aba6d1741b304c2a63706951e504
| 559
|
py
|
Python
|
Python/chapter02_variable.py
|
stayteef/learningpython
|
d4e997a6e6f6a4994f1932a728045f512964725a
|
[
"MIT"
] | null | null | null |
Python/chapter02_variable.py
|
stayteef/learningpython
|
d4e997a6e6f6a4994f1932a728045f512964725a
|
[
"MIT"
] | null | null | null |
Python/chapter02_variable.py
|
stayteef/learningpython
|
d4e997a6e6f6a4994f1932a728045f512964725a
|
[
"MIT"
] | null | null | null |
# this is to learn what 'variable' is.
#i did the followings in termial with a python shell. so this is what a alist is
#a = 15
#print (a)
#a = [1, 2, 3, 4]
#a [2]
#type (a) - to show a is a int
#10 ==10 is to ask if 10 equals to 10, so it will return 'true"
#10 != 11 is asking if 11 equals to 10 and of course it will print false
# python does not let us mix between strings and integers. so we can convert interger into a string by typing 'str(1)' and 1 is now a string
# lists work as well.
# questions above works for strings too
import turtle
| 29.421053
| 141
| 0.68873
|
a370a0ad6650691e705849bcceb52d14a129d58a
| 4,732
|
ts
|
TypeScript
|
integration-tests/runtime-tests/src/tests/tx/crowdloanRewards/txCrowdloanRewardsTests.ts
|
ArturoFinance/composable
|
8ea2468b3ea955cf12dc98a0fbd4979788c67864
|
[
"Unlicense"
] | null | null | null |
integration-tests/runtime-tests/src/tests/tx/crowdloanRewards/txCrowdloanRewardsTests.ts
|
ArturoFinance/composable
|
8ea2468b3ea955cf12dc98a0fbd4979788c67864
|
[
"Unlicense"
] | null | null | null |
integration-tests/runtime-tests/src/tests/tx/crowdloanRewards/txCrowdloanRewardsTests.ts
|
ArturoFinance/composable
|
8ea2468b3ea955cf12dc98a0fbd4979788c67864
|
[
"Unlicense"
] | null | null | null |
/* eslint-disable no-trailing-spaces */
import R from 'ramda';
import { PalletCrowdloanRewardsModelsRemoteAccount } from '@composable/types/interfaces';
import { sendAndWaitForSuccess, sendUnsignedAndWaitForSuccess } from '@composable/utils/polkadotjs';
import { u128, u32 } from '@polkadot/types-codec';
import { expect } from 'chai';
import { IKeyringPair } from '@polkadot/types/types';
import {KeyringPair} from "@polkadot/keyring/types";
const toHexString = bytes =>
Array.prototype.map.call(bytes, x => ('0' + (x & 0xFF).toString(16)).slice(-2)).join('');
// The prefix is defined as pallet config
const proofMessage = (account: IKeyringPair, isEth=false) =>
(isEth ? "picasso-" : "<Bytes>picasso-") + toHexString(account.publicKey) + (isEth ? "" : "</Bytes>");
const ethAccount = (seed: number) =>
web3.eth.accounts.privateKeyToAccount("0x" + seed.toString(16).padStart(64, '0'))
export class TxCrowdloanRewardsTests {
/**
* Task order list:
* * Populate the list of contributors
* * Initialize the crowdloan
* * Associate a picassso account
*/
public static runTxCrowdloanRewardsTests() {
describe('CrowdloanRewards Tests', function() {
// 2 minutes timeout
this.timeout(60 * 2 * 1000);
it('Can populate the list of contributors', async function() {
const sudoWallet = walletAlice;
const { data: [result], } = await TxCrowdloanRewardsTests.txCrowdloanRewardsPopulateTest(sudoWallet);
expect(result.isOk).to.be.true;
});
it('Can initialize the crowdloan', async function() {
const sudoWallet = walletAlice;
const { data: [result], } = await TxCrowdloanRewardsTests.txCrowdloanRewardsInitializeTest(sudoWallet);
expect(result.isOk).to.be.true;
});
it('Can associate a picasso account', async function() {
const wallet = walletAlice;
await Promise.all([
TxCrowdloanRewardsTests.txCrowdloanRewardsEthAssociateTests(wallet),
TxCrowdloanRewardsTests.txCrowdloanRewardsRelayAssociateTests(wallet),
]);
});
});
}
/**
* tx.crowdloanRewards.populate
*/
private static txCrowdloanRewardsInitializeTest(sudoKey:KeyringPair) {
return sendAndWaitForSuccess(
api,
sudoKey,
api.events.sudo.Sudid.is,
api.tx.sudo.sudo(
api.tx.crowdloanRewards.initialize()
)
);
}
/**
*
*/
private static async txCrowdloanRewardsPopulateTest(sudoKey:KeyringPair) {
const vesting48weeks = api.createType('u32', 100800);
const reward = api.createType('u128', 1_000_000_000_000);
const relay_accounts =
R.unfold<number, [PalletCrowdloanRewardsModelsRemoteAccount, u128, u32]>(n => n > 50 ? false : [[
api.createType(
'PalletCrowdloanRewardsModelsRemoteAccount',
{ RelayChain: walletAlice.derive("/contributor-" + n.toString()).publicKey }
),
reward,
vesting48weeks,
], n + 1], 1);
const eth_accounts =
R.unfold<number, [PalletCrowdloanRewardsModelsRemoteAccount, u128, u32]>(n => n > 50 ? false : [[
api.createType(
'PalletCrowdloanRewardsModelsRemoteAccount',
{ Ethereum: ethAccount(n).address }
),
reward,
vesting48weeks,
], n + 1], 1);
const accounts = relay_accounts.concat(eth_accounts);
return await sendAndWaitForSuccess(
api,
sudoKey,
api.events.sudo.Sudid.is, api.tx.sudo.sudo(
api.tx.crowdloanRewards.populate(accounts)
)
);
}
private static async txCrowdloanRewardsRelayAssociateTests(wallet:KeyringPair) {
const contributor = wallet.derive("/contributor-1");
// arbitrary, user defined reward account
const contributorRewardAccount = contributor.derive("/reward");
const proof = contributor.sign(proofMessage(contributorRewardAccount));
return await sendUnsignedAndWaitForSuccess(
api,
api.events.crowdloanRewards.Associated.is,
api.tx.crowdloanRewards.associate(
contributorRewardAccount.publicKey,
{ RelayChain: [contributor.publicKey, { Sr25519: proof }] }
)
);
}
private static async txCrowdloanRewardsEthAssociateTests(wallet:KeyringPair) {
const contributor = ethAccount(1);
// arbitrary, user defined reward account
const contributorRewardAccount = wallet.derive("/reward-eth-1");
const proof = contributor.sign(proofMessage(contributorRewardAccount, true));
return await sendUnsignedAndWaitForSuccess(
api,
api.events.crowdloanRewards.Associated.is,
api.tx.crowdloanRewards.associate(
contributorRewardAccount.publicKey,
{ Ethereum: proof.signature }
)
);
}
}
| 36.122137
| 111
| 0.676458
|
b271cf05893fa9e9deafa4b051bb2b2e5c947747
| 950
|
lua
|
Lua
|
Server/Plugins/APIDump/Hooks/OnPlayerRightClickingEntity.lua
|
wbrbr/MCServer
|
a7bbca30c560c581127f7b6c49ca427c3e96a1da
|
[
"Apache-2.0"
] | 4,126
|
2015-06-12T21:56:49.000Z
|
2022-03-31T06:33:12.000Z
|
Server/Plugins/APIDump/Hooks/OnPlayerRightClickingEntity.lua
|
wbrbr/MCServer
|
a7bbca30c560c581127f7b6c49ca427c3e96a1da
|
[
"Apache-2.0"
] | 2,931
|
2015-06-11T17:13:15.000Z
|
2022-03-31T22:46:31.000Z
|
Server/Plugins/APIDump/Hooks/OnPlayerRightClickingEntity.lua
|
wbrbr/MCServer
|
a7bbca30c560c581127f7b6c49ca427c3e96a1da
|
[
"Apache-2.0"
] | 917
|
2015-06-11T21:47:41.000Z
|
2022-03-30T10:32:55.000Z
|
return
{
HOOK_PLAYER_RIGHT_CLICKING_ENTITY =
{
CalledWhen = "A player has right-clicked an entity. Plugins may override / refuse.",
DefaultFnName = "OnPlayerRightClickingEntity", -- also used as pagename
Desc = [[
This hook is called when the {{cPlayer|player}} right-clicks an {{cEntity|entity}}. Plugins may
override the default behavior or even cancel the default processing.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has right-clicked the entity" },
{ Name = "Entity", Type = "{{cEntity}} descendant", Notes = "The entity that has been right-clicked" },
},
Returns = [[
If the functino returns false or no value, Cuberite calls other plugins' callbacks and finally does
the default processing for the right-click. If the function returns true, no other callbacks are
called and the default processing is skipped.
]],
}, -- HOOK_PLAYER_RIGHT_CLICKING_ENTITY
}
| 33.928571
| 106
| 0.705263
|
458e9868759b0feae1682dc3ba2ec40393f30c97
| 129
|
py
|
Python
|
tests/test_api_preprocess/test_biolink_preproces.py
|
luluricketts/biothings_explorer
|
ae2009ff285f96a08e0145f242846ca613b5069c
|
[
"Apache-2.0"
] | 21
|
2017-07-22T10:08:03.000Z
|
2022-01-11T08:53:14.000Z
|
tests/test_api_preprocess/test_biolink_preproces.py
|
luluricketts/biothings_explorer
|
ae2009ff285f96a08e0145f242846ca613b5069c
|
[
"Apache-2.0"
] | 127
|
2017-07-22T10:19:45.000Z
|
2021-11-04T01:23:43.000Z
|
tests/test_api_preprocess/test_biolink_preproces.py
|
luluricketts/biothings_explorer
|
ae2009ff285f96a08e0145f242846ca613b5069c
|
[
"Apache-2.0"
] | 18
|
2017-04-27T17:02:06.000Z
|
2021-07-25T18:13:56.000Z
|
# -*- coding: utf-8 -*-
"""
Test the api preprocess module for biolink.
.. moduleauthor:: Jiwen Xin <kevinxin@scripps.edu>
"""
| 16.125
| 50
| 0.651163
|
a1dd92c98de058667b22a3b32f212d5688613fdb
| 4,960
|
lua
|
Lua
|
main.lua
|
LJNIC/Collaborogue
|
9c333e790f043087045d9236ccde0e496ebfc96b
|
[
"MIT"
] | 4
|
2020-11-09T23:33:48.000Z
|
2021-04-19T23:14:50.000Z
|
main.lua
|
LJNIC/Collaborogue
|
9c333e790f043087045d9236ccde0e496ebfc96b
|
[
"MIT"
] | 1
|
2021-11-13T15:53:53.000Z
|
2021-11-13T15:53:53.000Z
|
main.lua
|
LJNIC/Collaborogue
|
9c333e790f043087045d9236ccde0e496ebfc96b
|
[
"MIT"
] | 2
|
2021-11-11T03:25:30.000Z
|
2022-02-13T13:05:00.000Z
|
ROT = require 'src.rot'
MusicManager = require "musicmanager"
vector22 = require "vector"
conditions = {}
reactions = {}
actions = {}
components = {}
actors = {}
effects = require "effects"
love.graphics.setDefaultFilter("nearest", "nearest")
local function loadItems(directoryName, items, recurse)
local info = {}
for k, item in pairs(love.filesystem.getDirectoryItems(directoryName)) do
local fileName = directoryName .. "/" .. item
love.filesystem.getInfo(fileName, info)
if info.type == "file" then
fileName = string.gsub(fileName, ".lua", "")
local name = string.gsub(item:sub(1, 1):upper()..item:sub(2), ".lua", "")
items[name] = require(fileName)
elseif info.type == "directory" and recurse then
loadItems(fileName, items, recurse)
end
end
end
loadItems("components", components)
targets = require "target"
loadItems("actions", actions, false)
loadItems("actions/reactions", reactions, true)
loadItems("conditions", conditions, true)
loadItems("actors", actors, true)
Loot = require "loot"
local Level = require "level"
local Interface = require "interface"
local Display = require "display.display"
local Start = require "panels.start"
------
-- Global
game = {}
function love.load()
min_dt = 1/30 --fps
next_time = love.timer.getTime()
local scale = 1
local w, h = math.floor(81/scale), math.floor(49/scale)
local w2, h2 = math.floor(81/2), math.floor(49/2)
local display = Display:new(w, h, scale, nil, {1, 1, 1, 0}, nil, nil, true)
local viewDisplay2x = Display:new(w2, h2, 2, nil, {.09, .09, .09}, nil, nil, true)
local viewDisplay1x = Display:new(w, h, 1, nil, {.09, .09, .09}, nil, nil, true)
local map = ROT.Map.Brogue(display:getWidth() - 11, 44)
game.music = MusicManager()
game.display = display
game.viewDisplay1x = viewDisplay1x
game.viewDisplay2x = viewDisplay2x
game.viewDisplay = viewDisplay2x
game.Player = actors.Player()
local interface = Interface(display)
interface:push(Start(display, interface))
local level = Level(map)
game.level = level
game.interface = interface
local player = game.Player
game.curActor = player
table.insert(player.inventory, actors.Wand_of_displacement())
table.insert(player.inventory, actors.Robe_of_wonders())
table.insert(player.inventory, actors.Circlet_of_channeling())
table.insert(player.inventory, actors.Prism())
table.insert(player.inventory, actors.Axe())
table.insert(player.inventory, actors.Potion_of_focus())
love.keyboard.setKeyRepeat(true)
end
function love.draw()
if not game.display then return end
game.viewDisplay:clear()
game.display:clear()
game.interface:draw(game.display)
game.viewDisplay:draw()
game.display:draw("UI")
end
local storedKeypress
local updateCoroutine
game.waiting = false
local animations = true
function love.update(dt)
game.level:updateEffectLighting(dt)
game.music:update(dt)
game.interface:update(dt, game.level)
if not updateCoroutine then
updateCoroutine = coroutine.create(game.level.update)
end
local awaitedAction = game.interface:getAction()
-- we're waiting and there's no input so stop advancing
if game.waiting and not awaitedAction then return end
game.waiting = false
-- don't advance game state while we're rendering effects please
if #game.level.effects ~= 0 then return end
local success, ret, effect = coroutine.resume(updateCoroutine, game.level, awaitedAction)
if not game.interface.animating and success and ret == "effect" then
while success and ret == "effect" do
success, ret = coroutine.resume(updateCoroutine, game.level, awaitedAction)
end
end
if success == false then
error(ret .. debug.traceback(updateCoroutine))
end
game.interface.effects = {}
if coroutine.status(updateCoroutine) == "suspended" then
-- if level update returns a table we know we've got out guy so we set
-- curActor to let the interface know to unlock input
if type(ret) == "table" then
game.curActor = ret
game.waiting = true
if storedKeypress then
love.keypressed(storedKeypress[1], storedKeypress[2])
end
game.level.effects = {}
game.interface.animating = true
end
end
if coroutine.status(updateCoroutine) == "dead" then
-- The coroutine has not stopped running and returned "descend".
-- It's time for us to load a new level.
if ret == "descend" then
local map = ROT.Map.Brogue(game.display:getWidth() - 11, 44)
game.level = Level(map)
game.Player.explored = {}
end
updateCoroutine = coroutine.create(game.level.update)
end
end
function love.keypressed(key, scancode)
if not game.waiting then
game.interface.animating = false
game.interface.effects = {}
storedKeypress = {key, scancode}
return
end
storedKeypress = nil
-- if there is no current actor than we freeze input
game.interface:handleKeyPress(key, scancode)
end
| 29.005848
| 91
| 0.705645
|
a36106944c3b9176a3fc36deb991177b397f9981
| 372
|
java
|
Java
|
virtdata-lib-curves4/src/main/java/io/virtdata/continuous/long_double/Pareto.java
|
jeromatron/virtdata-java
|
7f2b56ea5cd61328a20b8d65f39cd9d5c4fc2b5f
|
[
"Apache-2.0"
] | null | null | null |
virtdata-lib-curves4/src/main/java/io/virtdata/continuous/long_double/Pareto.java
|
jeromatron/virtdata-java
|
7f2b56ea5cd61328a20b8d65f39cd9d5c4fc2b5f
|
[
"Apache-2.0"
] | null | null | null |
virtdata-lib-curves4/src/main/java/io/virtdata/continuous/long_double/Pareto.java
|
jeromatron/virtdata-java
|
7f2b56ea5cd61328a20b8d65f39cd9d5c4fc2b5f
|
[
"Apache-2.0"
] | null | null | null |
package io.virtdata.continuous.long_double;
import io.virtdata.annotations.ThreadSafeMapper;
import org.apache.commons.statistics.distribution.ParetoDistribution;
@ThreadSafeMapper
public class Pareto extends LongToDoubleContinuousCurve {
public Pareto(double scale, double shape, String... mods) {
super(new ParetoDistribution(scale, shape), mods);
}
}
| 31
| 69
| 0.790323
|