code
stringlengths 0
29.6k
| language
stringclasses 9
values | AST_depth
int64 3
30
| alphanumeric_fraction
float64 0.2
0.86
| max_line_length
int64 13
399
| avg_line_length
float64 5.02
139
| num_lines
int64 7
299
| source
stringclasses 4
values |
---|---|---|---|---|---|---|---|
using FritzBot.Database;
using FritzBot.DataModel;
using System.Linq;
namespace FritzBot.Plugins
{
[Name("unignore")]
[Help("Die betroffene Person wird von der ignore Liste gestrichen, Operator Befehl: z.b. !unignore Testnick")]
[ParameterRequired]
[Authorize]
class unignore : PluginBase, ICommand
{
public void Run(IrcMessage theMessage)
{
using (var context = new BotContext())
{
string nickname = theMessage.CommandArgs.FirstOrDefault();
if (context.TryGetUser(nickname) is { } u)
{
u.Ignored = false;
context.SaveChanges();
theMessage.Answer($"Ignoranz für {nickname} aufgehoben");
return;
}
theMessage.Answer("Oh... Dieser User ist mir nicht bekannt");
}
}
}
} | c# | 17 | 0.551913 | 114 | 30.586207 | 29 | starcoderdata |
def singlecast(self, size: int, target: Node) -> bool:
"""transmit several bits"""
if self.is_alive():
dist = distance(self.position, target.position)
self.energy -= self.energy_tx(size, dist)
if target.is_alive():
target.energy -= target.energy_rx(size)
return True
return False
return False | python | 11 | 0.542929 | 59 | 38.7 | 10 | inline |
// https://atcoder.jp/contests/abc138/tasks/abc138
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <map>
#include <stack>
#include <queue>
#include <iomanip>
#include <set>
#include <bitset>
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
int main()
{
int N, Q;
cin >> N >> Q;
vector<int> a(N), b(N);
for (int i = 0; i < N - 1; ++i) cin >> a[i] >> b[i], --a[i], --b[i];
vector<int> p(Q), x(Q);
for (int i = 0; i < Q; ++i) cin >> p[i] >> x[i], --p[i];
vector<vector<int>> G(N);
for (int i = 0; i < N - 1; ++i)
{
G[a[i]].push_back(b[i]);
G[b[i]].push_back(a[i]);
}
vector<int> parent(N, -1); // 頂点 i の親
queue<int> que;
que.push(0);
while(!que.empty())
{
int v = que.front();
que.pop();
for (const auto& nv : G[v])
{
if (parent[v] == nv) continue;
parent[nv] = v;
que.push(nv);
}
}
vector<int> res(N, 0);
for (int j = 0; j < Q; ++j)
{
res[p[j]] += x[j];
}
que.push(0);
while(!que.empty())
{
int v = que.front();
que.pop();
for (const auto& nv : G[v])
{
if (parent[v] == nv) continue;
res[nv] += res[v];
que.push(nv);
}
}
for (int i = 0; i < N; ++i)
{
cout << res[i];
if (i != N - 1) cout << " ";
else cout << endl;
}
return 0;
} | c++ | 12 | 0.444945 | 72 | 20.287671 | 73 | codenet |
#include <stdio.h>
#include <queue>
#include <stack>
using namespace std;
typedef long long ll;
int main(void) {
ll i, j, k, n, r = 0, a, b, now, t;
scanf("%lld", &n);
vector<ll> vec[n];
ll p[n], m[n][2];
for(i = 0; i < n; ++i) m[i][0] = m[i][1] = 0;
for(i = 1; i < n; ++i) {
scanf("%lld%lld", &a, &b);
vec[--a].push_back(--b);
vec[b].push_back(a);
}
queue<ll> q;
stack<ll> s;
q.push(0);
p[0] = 0;
while(q.size()) {
now = q.front(), q.pop();
s.push(now);
for(i = 0; i < vec[now].size(); ++i) if(p[now] != vec[now][i]) {
p[vec[now][i]] = now;
q.push(vec[now][i]);
}
}
while(s.size()) {
now = s.top(), s.pop();
for(i = 0; i < vec[now].size(); ++i) if(p[now] != vec[now][i]) {
t = vec[now][i];
if(m[now][0] < m[t][0] + 1) m[now][1] = m[now][0], m[now][0] = m[t][0] + 1;
else if(m[now][1] < m[t][0] + 1) m[now][1] = m[t][0] + 1;
}
if(m[now][0] + m[now][1] + 1 > r) r = m[now][0] + m[now][1] + 1;
}
printf("%s", r % 3 == 2 ? "Second" : "First");
return 0;
} | c++ | 17 | 0.435438 | 81 | 24.902439 | 41 | codenet |
using MoneyFox.Presentation.Groups;
using MoneyFox.Presentation.ViewModels;
using System;
using System.Diagnostics.CodeAnalysis;
using MoneyFox.Domain.Exceptions;
using Xunit;
namespace MoneyFox.Presentation.Tests.Groups
{
[ExcludeFromCodeCoverage]
public class DateListGroupCollectionTests
{
[Fact]
public void CreateGroups_Null_ArgumentNullExceptionThrown()
{
// Arrange
// Act / Assert
Assert.Throws => DateListGroupCollection s => "", s => DateTime.Now));
}
}
} | c# | 18 | 0.6976 | 155 | 28.761905 | 21 | starcoderdata |
//
// HudInputStream.h
// HudControl
//
// Created by scpark on 2016. 8. 30..
// Copyright © 2016년 kivic. All rights reserved.
//
#import
@interface HudInputStream : NSObject
+(nullable id) initWithNSData:(nonnull NSData*)data;
+(nullable id) initWithBytes:(nonnull const void *)bytes length:(NSUInteger)length;
-(NSInteger) available;
-(void) read:(nonnull void *)buffer length:(NSUInteger)length;
-(uint8_t) directRead;
-(uint8_t) readByte;
-(int16_t) readShort;
-(int32_t) readInt;
-(int64_t) readLong;
-(float) readFloat;
-(double) readDouble;
-(BOOL) readBoolean;
-(nonnull NSString*) readUTF;
@end | c | 6 | 0.718553 | 83 | 24.44 | 25 | starcoderdata |
#region Usings
using System;
#endregion
namespace Stomp.Net.Stomp.Commands
{
///
/// Summary description for Destination.
///
public abstract class Destination : BaseDataStructure, IDestination
{
#region Properties
///
/// Indicates if the Destination was created by this client or was provided
/// by the broker, most commonly the Destinations provided by the broker
/// are those that appear in the ReplyTo field of a Message.
///
private Boolean RemoteDestination { get; set; }
#endregion
#region Ctor
///
/// Initializes a new instance of the <see cref="Destination" /> class with the given physical name.
///
/// <param name="name">The physical name of the destination.
/// <param name="skipDesinationNameFormatting">
/// A value indicating whether the destination name formatting will be skipped
/// or not.
///
protected Destination( String name, Boolean skipDesinationNameFormatting )
{
PhysicalName = name;
SkipDesinationNameFormatting = skipDesinationNameFormatting;
}
#endregion
public abstract DestinationType DestinationType { get; }
public Boolean IsQueue
{
get
{
var destinationType = GetDestinationType();
return StompQueue == destinationType
|| StompTemporaryQueue == destinationType;
}
}
public Boolean IsTemporary
{
get
{
var destinationType = GetDestinationType();
return StompTemporaryQueue == destinationType
|| StompTemporaryTopic == destinationType;
}
}
public Boolean IsTopic
{
get
{
var destinationType = GetDestinationType();
return StompTopic == destinationType
|| StompTemporaryTopic == destinationType;
}
}
public String PhysicalName { get; }
///
/// Gets or sets a value indicating whether the destination name formatting should be skipped or not.
/// If set to true the physical name property will be used as stomp destination string without adding prefixes such as
/// queue or topic. This to support JMS brokers listening for queue/topic names in a different format.
///
public Boolean SkipDesinationNameFormatting { get; }
public override Object Clone()
{
// Since we are a derived class use the base's Clone()
// to perform the shallow copy. Since it is shallow it
// will include our derived class. Since we are derived,
// this method is an override.
var o = (Destination) base.Clone();
// Now do the deep work required
// If any new variables are added then this routine will
// likely need updating
return o;
}
///
///
/// <param name="text">The name of the destination
/// <param name="skipDesinationNameFormatting">
/// A value indicating whether the destination name formatting will be skipped
/// or not.
///
///
public static Destination ConvertToDestination( String text, Boolean skipDesinationNameFormatting )
{
if ( text == null )
return null;
var type = StompQueue;
var lowertext = text.ToLower();
var remote = false;
if ( lowertext.StartsWith( "/queue/", StringComparison.Ordinal ) )
text = text.Substring( "/queue/".Length );
else if ( lowertext.StartsWith( "/topic/", StringComparison.Ordinal ) )
{
text = text.Substring( "/topic/".Length );
type = StompTopic;
}
else if ( lowertext.StartsWith( "/temp-topic/", StringComparison.Ordinal ) )
{
text = text.Substring( "/temp-topic/".Length );
type = StompTemporaryTopic;
}
else if ( lowertext.StartsWith( "/temp-queue/", StringComparison.Ordinal ) )
{
text = text.Substring( "/temp-queue/".Length );
type = StompTemporaryQueue;
}
else if ( lowertext.StartsWith( "/remote-temp-topic/", StringComparison.Ordinal ) )
{
text = text.Substring( "/remote-temp-topic/".Length );
type = StompTemporaryTopic;
remote = true;
}
else if ( lowertext.StartsWith( "/remote-temp-queue/", StringComparison.Ordinal ) )
{
text = text.Substring( "/remote-temp-queue/".Length );
type = StompTemporaryQueue;
remote = true;
}
return CreateDestination( type, text, remote, skipDesinationNameFormatting );
}
public String ConvertToStompString()
{
if ( SkipDesinationNameFormatting )
return PhysicalName;
var result = DestinationType switch
{
DestinationType.Topic => "/topic/" + PhysicalName,
DestinationType.TemporaryTopic => ( RemoteDestination ? "/remote-temp-topic/" : "/temp-topic/" ) + PhysicalName,
DestinationType.TemporaryQueue => ( RemoteDestination ? "/remote-temp-queue/" : "/temp-queue/" ) + PhysicalName,
_ => "/queue/" + PhysicalName
};
return result;
}
///
/// If the object passed in is equivalent, return true
///
/// <param name="obj">the object to compare
/// if this instance and obj are equivalent
public override Boolean Equals( Object obj )
{
var result = this == obj;
if ( result || obj is not Destination other )
return result;
result = GetDestinationType() == other.GetDestinationType()
&& PhysicalName.Equals( other.PhysicalName );
return result;
}
///
///
/// for this instance
public override Int32 GetHashCode()
{
var answer = 37;
if ( PhysicalName != null )
answer = PhysicalName.GetHashCode();
if ( IsTopic )
answer ^= 0xfabfab;
return answer;
}
///
///
/// representation of this instance
public override String ToString()
{
return DestinationType switch
{
DestinationType.Topic => "topic://" + PhysicalName,
DestinationType.TemporaryTopic => "temp-topic://" + PhysicalName,
DestinationType.TemporaryQueue => "temp-queue://" + PhysicalName,
_ => "queue://" + PhysicalName
};
}
public static Destination Transform( IDestination destination ) =>
destination switch
{
Destination dest => dest,
ITemporaryQueue tempQueue => new TempQueue( tempQueue.QueueName, tempQueue.SkipDesinationNameFormatting ),
ITemporaryTopic tempTopic => new TempTopic( tempTopic.TopicName, tempTopic.SkipDesinationNameFormatting ),
IQueue queue => new Queue( queue.QueueName, queue.SkipDesinationNameFormatting ),
_ => destination is ITopic topic ? new Topic( topic.TopicName, topic.SkipDesinationNameFormatting ) : null
};
///
///
/// the Destination type
protected abstract Int32 GetDestinationType();
///
/// Create a Destination using the name given, the type is determined by the
/// value of the type parameter.
///
/// <param name="type">
/// <param name="pyhsicalName">
/// <param name="remote">
/// <param name="skipDesinationNameFormatting">
/// A value indicating whether the destination name formatting will be skipped
/// or not.
///
///
private static Destination CreateDestination( Int32 type, String pyhsicalName, Boolean remote, Boolean skipDesinationNameFormatting )
{
if ( pyhsicalName == null )
return null;
Destination result = type switch
{
StompTopic => new Topic( pyhsicalName, skipDesinationNameFormatting ),
StompTemporaryTopic => new TempTopic( pyhsicalName, skipDesinationNameFormatting ),
StompQueue => new Queue( pyhsicalName, skipDesinationNameFormatting ),
_ => new TempQueue( pyhsicalName, skipDesinationNameFormatting )
};
result.RemoteDestination = remote;
return result;
}
#region Constants
///
/// Queue Destination object
///
protected const Int32 StompQueue = 3;
///
/// Temporary Queue Destination object
///
protected const Int32 StompTemporaryQueue = 4;
///
/// Temporary Topic Destination object
///
protected const Int32 StompTemporaryTopic = 2;
///
/// Topic Destination object
///
protected const Int32 StompTopic = 1;
#endregion
}
} | c# | 21 | 0.53869 | 141 | 35.750903 | 277 | starcoderdata |
import requests
# Makes a call to the google api and returns a json response format
def g_search(api_key, isbn):
url = "https://www.googleapis.com/books/v1/volumes?q=+isbn:" + isbn + "&key=" + api_key
resp = requests.get(url)
json = resp.json()
return json
def main():
api_key = "AIzaSyBe5hasKj4f6lckw15uMEL7xQacHTAiAcQ"
js_mill_isbn = '9780199670802'
data_structures = '9780132576277'
aquarium = '9780793820788'
petit_pays = '9782246857334'
buildings = '9781564588852'
cinderella_murder = '9781476763699'
print(g_search(api_key, js_mill_isbn))
# main() | python | 9 | 0.682464 | 91 | 25.375 | 24 | starcoderdata |
<?php
namespace App\Controller;
use Knp\Snappy\Pdf;
use App\Entity\Main\Users;
use Symfony\Component\Mime\Email;
use App\Repository\Main\FAQRepository;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
/**
* @IsGranted("ROLE_USER")
*/
class PdfController extends AbstractController
{
/**
* @Route("/pdf/faq/{id}", name="app_send_pdf_faq")
*/
public function SendFaqPdf($id , MailerInterface $mailer, Pdf $pdf, FAQRepository $repo): Response
{
$faq = $repo->findOneBy(['id' => $id]);
$user = $this->getUser()->getPseudo();
$htmlPdf = $this->renderView('pdf/pdfFaq.html.twig', ['faq' => $faq]);
$html = $this->renderView('mails/MailFaq.html.twig', ['faq' => $faq, 'user' => $user]);
$pdf = $pdf->getOutputFromHtml($htmlPdf);
$email = (new Email())
->from('
->to($this->getUser()->getEmail())
->subject('Tutoriel PDF : ' . $faq->getTitle())
->html($html)
->attach($pdf, 'Tutoriel'. $faq->getTitle() .'.pdf');
$mailer->send($email);
$this->addFlash('message', 'Le Tutoriel vous a été envoyé par mail en version PDF !');
return $this->redirectToRoute('app_faq');
}
} | php | 16 | 0.608668 | 102 | 32.404255 | 47 | starcoderdata |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GeneticSharp.Domain.Chromosomes;
using GeneticSharp.Domain.Crossovers;
using GeneticSharp.Domain.Fitnesses;
using GeneticSharp.Domain.Mutations;
using GeneticSharp.Domain.Populations;
using GeneticSharp.Domain.Selections;
using GeneticSharp.Domain.Terminations;
namespace ExtensionLibrary.GeneticAlgorithm
{
public class GA
{
private GA()
{
// Prevent outside instantiation
}
private static readonly GA _singleton = new GA();
private ISelection _selection;
private ICrossover _crossover;
private IMutation _mutation;
private ClosestToMillion _fittness;
private PlayPatternChromosome _playPatternChromosome;
private Population _population;
private GeneticSharp.Domain.GeneticAlgorithm _geneticAlgorithm;
public static GA GetSingleton()
{
return _singleton;
}
public object GetInstance(string strFullyQualifiedName)
{
Type t = Type.GetType(strFullyQualifiedName);
return Activator.CreateInstance(t);
}
public void Init(int patternLength, List choices, int populationSize, int maxGenerations,
Selection selection, Crossover crossover, Mutation mutation)
{
string selectionname = Enum.GetName(typeof(Selection), selection);
_selection = (ISelection)Activator.CreateInstance("GeneticSharp.Domain", "GeneticSharp.Domain.Selections." + selectionname).Unwrap(); //new EliteSelection();
_crossover = (ICrossover)Activator.CreateInstance("GeneticSharp.Domain", "GeneticSharp.Domain.Crossovers." + crossover).Unwrap(); //new TwoPointCrossover();
_mutation = (IMutation)Activator.CreateInstance("GeneticSharp.Domain", "GeneticSharp.Domain.Mutations." + mutation).Unwrap(); //new PartialShuffleMutation();
_fittness = new ClosestToMillion();
_playPatternChromosome = new PlayPatternChromosome(patternLength, choices);
//var bestPattern = BestPattern.Get(context);
_population = new Population(populationSize, populationSize, _playPatternChromosome);
_geneticAlgorithm = new GeneticSharp.Domain.GeneticAlgorithm(_population, _fittness, _selection,
_crossover, _mutation);
_geneticAlgorithm.Termination = new GenerationNumberTermination(maxGenerations);
_geneticAlgorithm.Init();
}
public void SetScore(string p, int s)
{
var c = (PlayPatternChromosome)_geneticAlgorithm.Population.Generations[_geneticAlgorithm.GenerationsNumber-1].Chromosomes.Where(x=>(x as PlayPatternChromosome).PatternKeys==p).First();
c.Score = s;
}
public List GetPatternsKeys()
{
var r = new List
foreach (var item in _geneticAlgorithm.Population.Generations[_geneticAlgorithm.GenerationsNumber-1].Chromosomes)
{
r.Add((item as PlayPatternChromosome).PatternKeys);
}
return r;
}
public void EvolveNextGeneration()
{
_geneticAlgorithm.EvolveNextGeneration();
}
}
public class PlayPatternChromosome : ChromosomeBase
{
public int PatternLength { get; set; }
// Change the argument value passed to base construtor to change the length
// of your chromosome.
public double Score { get; set; }
public List Choices { get; set; }
public string Pattern
{
get
{
StringBuilder s = new StringBuilder(PatternLength);
for (int i = 0; i < GetGenes().Length; i++)
{
s.Append(ExtensionLibrary.LeftExtension.Left(GetGene(i).ToString(), 1));
}
return s.ToString();
}
}
public string PatternKeys
{
get
{
StringBuilder keys = new StringBuilder();
for (int i = 0; i < GetGenes().Length; i++)
{
keys.Append("[k(" + GetGene(i) + ")]");
}
return keys.ToString();
}
}
public PlayPatternChromosome(int patternLength, List choices)
: base(patternLength)
{
PatternLength = patternLength;
Choices = choices;
//Score = new Random(0).NextDouble();
CreateGenes();
}
public override Gene GenerateGene(int geneIndex)
{
return new Gene(PickRandomExtension.PickRandom(Choices));
}
public override IChromosome CreateNew()
{
return new PlayPatternChromosome(PatternLength, Choices);
}
}
public class ClosestToMillion : IFitness
{
public double Evaluate(IChromosome chromosome)
{
var timeoutTime = DateTime.Now.AddMinutes(10);
// Evaluate the fitness of chromosome.
var c = chromosome as PlayPatternChromosome;
if (c != null)
return c.Score - 1000000f;
else
{
return 0.0f;
}
}
}
} | c# | 23 | 0.601626 | 197 | 34.372549 | 153 | starcoderdata |
def __init__(self, src, ax, label="", dims="xyz", bones=None):
"""
:param src:
:param label:
:param dims: xyz if 3D, xy if 2D
bones - array of (markerA, markerB), bones that connect individual markers
"""
if bones is None: bones = []
self.data, self.metadata = load_qtm_data(src, multi_index=True)
self.label = label
self.dims = dims
self.marker_names = self.metadata["marker_names"]
self.frame = -1 # for moving through frames
self.markers = []
for marker_name in self.marker_names:
marker = Marker(ax, data=[self.data[marker_name][dim].values for dim in self.dims], name=marker_name,
dims=self.dims)
self.markers.append(marker)
self.get_bounds() | python | 15 | 0.663793 | 104 | 28.041667 | 24 | inline |
def _determine_upcoming_trash_day(self) -> datetime:
"""
Trash comes every Tuesday unless that Tuesday is a holiday, then it
comes on Wednesday.
:return: The upcoming trash day
:rtype: datetime
"""
if TODAY.weekday() == TUESDAY:
# today is a trash day - but it might be a holiday
return self._holiday_adjust(TODAY)
elif TODAY.weekday() == WEDNESDAY:
# today is the day after a trash day - it could be a holiday
# makeup day if yesterday was an observed holiday
yesterday = TODAY - rel.relativedelta(days=1)
if self._is_observed_holiday(yesterday):
return TODAY
# otherwise just use next tuesday
return self._holiday_adjust(
TODAY + rel.relativedelta(days=1, weekday=rel.TU)) | python | 12 | 0.597418 | 75 | 39.619048 | 21 | inline |
import Browser from '@base-cms/marko-web/browser';
// Register custom Vue components here...
/*
import SomeComponent from './some-component.vue';
Browser.register('SomeComponentName', SomeComponent);
This component would now be loadable within server-side templates via.
<cms-browser-component name="SomeComponentName" props={ someProp: 'someValue' } />
If you need to access Vue or jQuery within a browser component you may
do so by importing them from the core web library:
import Vue from '@base-cms/marko-web/browser/vue';
import $ from '@base-cms/marko-web/browser/jquery';
*/
export default Browser; | javascript | 3 | 0.763458 | 82 | 29.65 | 20 | starcoderdata |
<?php
namespace magtiny\framework;
final class globals
{
public static $globals=[];
public static function input ($key = "", $filters = [])
{
if (!isset(static::$globals[__FUNCTION__])) {
$input = json_decode(file_get_contents("php://input"), true);
$input = $input ? $input : [];
$filters= $filters ? $filters : config::config('safeFiltersFuncs');
$input = filter::handle($input, $filters);
static::$globals[__FUNCTION__] = array_merge($input, static::post());
}
if (!$key) {
return static::$globals[__FUNCTION__];
}
if (isset(static::$globals[__FUNCTION__][$key])) {
return static::$globals[__FUNCTION__][$key];
}
return null;
}
public static function __callStatic($method='', $argument=[])
{
$globalKey = '_' . strtoupper($method);
if ('_SERVER' === $globalKey and !isset($GLOBALS[$globalKey])) {
$_SERVER;
}
$paramKey = current($argument);
if (!isset(static::$globals[$globalKey])) {
if (!isset($GLOBALS[$globalKey])) {
debugger::throwException(104, $globalKey);
}
$customFilters = next($argument);
$filters = $customFilters ? $customFilters : config::config('safeFiltersFuncs');
static::$globals[$globalKey] = filter::handle($GLOBALS[$globalKey], $filters);
}
if (!$paramKey) {
return static::$globals[$globalKey];
}
if (isset(static::$globals[$globalKey][$paramKey])) {
return static::$globals[$globalKey][$paramKey];
}
return null;
}
} | php | 16 | 0.624566 | 83 | 26.711538 | 52 | starcoderdata |
using System;
namespace SinglyLinkedList
{
class Program
{
static void Main(string[] args)
{
SinglyLinkedList myList = new SinglyLinkedList();
myList.insertFirst(100);
myList.insertFirst(5);
myList.insertFirst(7);
myList.insertFirst(8);
myList.insertFirst(1);
myList.printList();
myList.deleteFirst();
myList.printList();
}
// singlyLinkedList class points from left to right in one direction
public class SinglyLinkedList
{
private Node first;
// method to check if the node is empty
public bool isEmpty()
{
return (first == null);
}
// method to insert data into the list
public void insertFirst(int data)
{
// create a new Node
Node newNode = new Node
{
data = data,// assign the data to the node data
next = first // newNode.next is equal to Node.first
};
first = newNode; //
}
public Node deleteFirst()
{
// deleting is as simple as just re-pointing to our new Node.head
Node temp = first;
first = first.next; // assign new first node after deleting
return temp;
}
public void printList()
{
Console.Write("List (first -- last) ");
Node current = first;
while (current != null)
{
current.displaynode();
current = current.next;
}
Console.WriteLine();
}
}
public class Node
{
public int data;
public Node next; // recursive as we are using the Node class itself
// method to display node
public void displaynode()
{
Console.Write("(" + data + ") --->");
}
}
}
} | c# | 17 | 0.456454 | 83 | 26.641975 | 81 | starcoderdata |
package parser.regex;
import utils.Tree;
import java.io.InputStream;
import java.text.ParseException;
public class RegexParser {
private RegexLexer lex;
public Tree parse(InputStream input) throws ParseException {
lex = new RegexLexer(input);
lex.nextToken();
var re = re();
if (lex.getCurToken() != RegexToken.END) {
throw new ParseException("expected end symbol at pos: ", lex.getCurPos() - 1);
}
return re;
}
private Tree cnct() throws ParseException {
Tree tree = null;
switch (lex.getCurToken()) {
case LPAREN: {
Tree part = part();
Tree cnct = cnct();
tree = new Tree("CNCT", part, cnct);
break;
}
case EPS: {
tree = new Tree("CNCT", new Tree("EPS"));
break;
}
case VBAR: {
tree = new Tree("CNCT", new Tree("EPS"));
break;
}
case ALPHA: {
Tree part = part();
Tree cnct = cnct();
tree = new Tree("CNCT", part, cnct);
break;
}
case END: {
tree = new Tree("CNCT", new Tree("EPS"));
break;
}
case RPAREN: {
tree = new Tree("CNCT", new Tree("EPS"));
break;
}
default:
throw new ParseException("unexpected symbol at pos: ", lex.getCurPos() - 1);
}
return tree;
}
private Tree re() throws ParseException {
Tree tree = null;
switch (lex.getCurToken()) {
case LPAREN: {
Tree cnct = cnct();
Tree re_ = re_();
tree = new Tree("RE", cnct, re_);
break;
}
case EPS: {
Tree re_ = re_();
tree = new Tree("RE", re_);
break;
}
case VBAR: {
Tree re_ = re_();
tree = new Tree("RE", re_);
break;
}
case ALPHA: {
Tree cnct = cnct();
Tree re_ = re_();
tree = new Tree("RE", cnct, re_);
break;
}
case END: {
Tree re_ = re_();
tree = new Tree("RE", re_);
break;
}
case RPAREN: {
Tree re_ = re_();
tree = new Tree("RE", re_);
break;
}
default:
throw new ParseException("unexpected symbol at pos: ", lex.getCurPos() - 1);
}
return tree;
}
private Tree part() throws ParseException {
Tree tree = null;
switch (lex.getCurToken()) {
case LPAREN: {
Tree group = group();
Tree kln = kln();
tree = new Tree("PART", group, kln);
break;
}
case ALPHA: {
Tree group = group();
Tree kln = kln();
tree = new Tree("PART", group, kln);
break;
}
default:
throw new ParseException("unexpected symbol at pos: ", lex.getCurPos() - 1);
}
return tree;
}
private Tree kln() throws ParseException {
Tree tree = null;
switch (lex.getCurToken()) {
case PLUS: {
lex.nextToken();
Tree kln = kln();
tree = new Tree("KLN", new Tree("+"));
break;
}
case LPAREN: {
tree = new Tree("KLN", new Tree("EPS"));
break;
}
case EPS: {
tree = new Tree("KLN", new Tree("EPS"));
break;
}
case VBAR: {
tree = new Tree("KLN", new Tree("EPS"));
break;
}
case ALPHA: {
tree = new Tree("KLN", new Tree("EPS"));
break;
}
case QMARK: {
lex.nextToken();
Tree kln = kln();
tree = new Tree("KLN", new Tree("?"));
break;
}
case END: {
tree = new Tree("KLN", new Tree("EPS"));
break;
}
case STAR: {
lex.nextToken();
Tree kln = kln();
tree = new Tree("KLN", new Tree("*"));
break;
}
case RPAREN: {
tree = new Tree("KLN", new Tree("EPS"));
break;
}
default:
throw new ParseException("unexpected symbol at pos: ", lex.getCurPos() - 1);
}
return tree;
}
private Tree re_() throws ParseException {
Tree tree = null;
switch (lex.getCurToken()) {
case EPS: {
tree = new Tree("RE'", new Tree("EPS"));
break;
}
case VBAR: {
lex.nextToken();
Tree re = re();
tree = new Tree("RE'", new Tree("|"), re);
break;
}
case END: {
tree = new Tree("RE'", new Tree("EPS"));
break;
}
case RPAREN: {
tree = new Tree("RE'", new Tree("EPS"));
break;
}
default:
throw new ParseException("unexpected symbol at pos: ", lex.getCurPos() - 1);
}
return tree;
}
private Tree group() throws ParseException {
Tree tree = null;
switch (lex.getCurToken()) {
case LPAREN: {
lex.nextToken();
Tree re = re();
tree = new Tree("GROUP", new Tree("("), re, new Tree(")"));
lex.nextToken();
break;
}
case ALPHA: {
tree = new Tree("GROUP", new Tree(lex.getCurString()));
lex.nextToken();
break;
}
default:
throw new ParseException("unexpected symbol at pos: ", lex.getCurPos() - 1);
}
return tree;
}
} | java | 17 | 0.374944 | 92 | 26.970588 | 238 | starcoderdata |
function LRUCache(size) {
var _this = this;
// * Clears the cache back to original state
this.clear = function () {
_this.memory = {};
_this.queue = new queue_1["default"]();
_this.allocatedMemory = 0;
};
// * Gets the value from the cache using the key.
// * If the key does not exist in cache null is returned.
// * O(1) access time just accessing JS Object
this.get = function (key) {
return _this.memory[key] ? _this.memory[key] : null;
};
// * Sets the value in the cache at this key with this value.
// * If we are full and not updating an existing entry
// * then evict the oldest (front of queue)
// * Regardless, add this data to our queue and set the value in memory.
// * Also check to see if we are full and set the full flag.
this.set = function (key, value) {
// * O(1) to call get and check if full
var existingValue = _this.get(key);
if (_this.allocatedMemory === _this.maxSize && existingValue === null) {
var evicted = _this.queue.dequeue();
delete _this.memory[evicted.key];
console.log("Evicted: " + evicted.key + " -> " + evicted.value);
}
// * Add new data to back of queue
_this.queue.enqueue({ key: key, value: value });
_this.memory[key] = value;
// * If we added a new entry to cache, update allocated
if (_this.allocatedMemory < _this.maxSize && existingValue === null) {
_this.allocatedMemory++;
}
};
// * Print out the contents of memory
this.print = function () {
console.log("Cache -- Size: " +
_this.maxSize +
" Allocated: " +
_this.allocatedMemory +
"\n------------------------\n");
// * O(N) where N is size of the cache
Object.entries(_this.memory).forEach(function (data) {
console.log(data);
});
};
this.memory = {};
this.queue = new queue_1["default"]();
this.maxSize = size;
this.allocatedMemory = 0;
} | javascript | 16 | 0.505461 | 84 | 43.038462 | 52 | inline |
public static Constructor getConstructor( Class o_clazz, Class[] arg_clazz, boolean[] arg_is_null)
throws SecurityException, NoSuchMethodException {
if (o_clazz == null)
return null;
Constructor cons = null ;
/* if there is no argument, try to find a direct match */
if (arg_clazz == null || arg_clazz.length == 0) {
cons = o_clazz.getConstructor( (Class[] )null );
return cons ;
}
/* try to find an exact match */
try {
cons = o_clazz.getConstructor(arg_clazz);
if (cons != null)
return cons ;
} catch (NoSuchMethodException e) {
/* we catch this one because we want to further search */
}
/* ok, no exact match was found - we have to walk through all methods */
cons = null;
Constructor[] candidates = o_clazz.getConstructors();
for (int k = 0; k < candidates.length; k++) {
Constructor c = candidates[k];
Class[] param_clazz = c.getParameterTypes();
if (arg_clazz.length != param_clazz.length) // number of parameters must match
continue;
int n = arg_clazz.length;
boolean ok = true;
for (int i = 0; i < n; i++) {
if( arg_is_null[i] ){
/* then the class must not be a primitive type */
if( isPrimitive(arg_clazz[i]) ){
ok = false ;
break ;
}
} else{
if (arg_clazz[i] != null && !param_clazz[i].isAssignableFrom(arg_clazz[i])) {
ok = false;
break;
}
}
}
// it must be the only match so far or more specific than the current match
if (ok && (cons == null || isMoreSpecific(c, cons)))
cons = c;
}
if( cons == null ){
throw new NoSuchMethodException( "No constructor matching the given parameters" ) ;
}
return cons;
} | java | 16 | 0.611633 | 99 | 27.864407 | 59 | inline |
const {post} = require('request-promise')
const validateAssertions = require('../../lib/validators/validateAssertions')
module.exports = async (dvf, token, amount, path, nonce, signature) => {
validateAssertions(dvf, {amount, token})
const tempVaultId = dvf.config.DVF.tempStarkVaultId || '1'
const depositAmount = dvf.util.prepareDepositAmount(amount, token)
const starkDeposit = await dvf.stark.ledger.createDepositData(path, token, depositAmount, tempVaultId, nonce, signature)
const data = {
token,
amount: depositAmount,
nonce: starkDeposit.nonce,
expireTime: starkDeposit.expireTime,
starkVaultId: starkDeposit.starkVaultId,
starkSignature: starkDeposit.starkSignature,
starkPublicKey: starkDeposit.starkPublicKey
}
const url = dvf.config.api + '/v1/trading/w/deposit'
const deposit = await post(url, {json: data})
const ctDeposit = await dvf.contract.deposit(tempVaultId, token, amount, `0x${starkDeposit.starkPublicKey.x}`)
return {...deposit, ...ctDeposit}
} | javascript | 14 | 0.740451 | 122 | 38.269231 | 26 | starcoderdata |
<div class="row">
<div class="col-md-offset-1 col-md-10">
<a href="<?php echo base_url(). "hdd/add"; ?>" role="button" class="btn btn-default"><span class="glyphicon glyphicon-plus" aria-hidden="true"> new
<div class="row">
<div class="col-md-offset-1 col-md-10">
<table id="hdd_table" class="table table-bordered table-striped" cellspacing="0" width="100%">
<?php if($hdd_list) : ?>
<?php foreach($hdd_list as $hdd): ?>
<?php
# switch status
/* colors are cool, but don't know if this is needed
switch ($hdd['status'])
{
case "RMA":
$status = '<span style="color:#d1d1d1">RMA
break;
case "cold":
$status = '<span style="color:#75bdbd">cold
break;
default :
}
*/
$status = $hdd['status'];
printf(
'
%s
',
(!empty($hdd['serial']) ? $hdd['serial'] : '-'),
(!empty($hdd['brand']) ? $hdd['brand'] : '-'),
(!empty($hdd['capacity']) ? $hdd['capacity'] : '-'),
(!empty($hdd['warranty']) ? $hdd['warranty'] : '-'),
$status,
(!empty($hdd['vendor']) ? $hdd['vendor'] : '-'),
(isset($hdd['devices']['name']) ? $hdd['devices']['name'] : '-'),
(!empty($hdd['notes']) ? $hdd['notes'] : '-')
);
?>
<a href="<?php echo base_url(). 'hdd/edit/' . $hdd['id']; ?>" role="button" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-edit" aria-hidden="true">
<a href="<?php echo base_url(). 'hdd/remove/' . $hdd['id']; ?>" role="button" class="btn btn-default btn-sm"><span class="glyphicon glyphicon-remove" aria-hidden="true">
<?php endforeach; ?>
<?php endif; ?>
$(document).ready(function() {
$('#hdd_table').DataTable({
"iDisplayLength": 50,
"bLengthChange": false,
"stateSave": true,
"dom": "
});
$("div.selections").append(
'Show : ' +
<?php if(!$filter): ?>
'<a href="<?php echo base_url(). "hdd/index/hot"; ?>" role="button" class="btn btn-default btn-sm" style="margin-right:3px;">hot only +
'<a href="<?php echo base_url(). "hdd/index/cold"; ?>" role="button" class="btn btn-default btn-sm" style="margin-right:3px;">cold only +
'<a href="<?php echo base_url(). "hdd/index/backup"; ?>" role="button" class="btn btn-default btn-sm" style="margin-right:3px;">backup only +
'<a href="<?php echo base_url(). "hdd/index/lost"; ?>" role="button" class="btn btn-default btn-sm" style="margin-right:3px;">lost
<?php else : ?>
'<button class="btn btn-default btn-sm disabled" type="button" style="margin-right:3px;"><?php echo $filter_text; ?> +
'<a href="<?php echo base_url(). "hdd/"; ?>" role="button" class="btn btn-default btn-sm" style="margin-right:3px;">all
<?php endif; ?>
);
} ); | php | 17 | 0.52955 | 185 | 34.810526 | 95 | starcoderdata |
[Route("api/avatar")]
[HttpGet]
public async Task Get()
{
var authToken = HttpContext.Request.Headers["Authorization"].ToString();
var token = new tokens();
if (authToken != "")
{
authToken = authToken.Remove(0, 7);
token = await _dbService.GetAsync(authToken);
}
if (token == null)
{
string _reply = "";
_reply += "{\"message:\": \"invalid combination\"}";
byte[] _bytes = Encoding.UTF8.GetBytes(_reply);
HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
await HttpContext.Response.Body.WriteAsync(_bytes);
await HttpContext.Response.CompleteAsync();
Console.WriteLine("UNAUTH");
}
else
{
//Send users avatars
var body = "[";
List<avatarClass> avatars = new List<avatarClass>();
List<avatarClassStripped> avatarStripped = new List<avatarClassStripped>();
avatars = await _dbService.GetAvatarAsync(token.userid);
foreach (var avatar in avatars)
{
body += JsonConvert.SerializeObject(avatar);
body += "\n";
}
body += "]";
byte[] bytes = Encoding.UTF8.GetBytes(body);
HttpContext.Response.StatusCode = StatusCodes.Status200OK;
await HttpContext.Response.Body.WriteAsync(bytes);
await HttpContext.Response.CompleteAsync();
}
} | c# | 14 | 0.497354 | 91 | 38.581395 | 43 | inline |
package com.google.android.DemoKit;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class BaseActivity extends DemoKitActivity {
private InputController mInputController;
public BaseActivity() {
super();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mAccessory != null) {
showControls();
} else {
hideControls();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("Simulate");
menu.add("Quit");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getTitle() == "Simulate") {
showControls();
} else if (item.getTitle() == "Quit") {
finish();
System.exit(0);
}
return true;
}
protected void enableControls(boolean enable) {
if (enable) {
showControls();
} else {
hideControls();
}
}
protected void hideControls() {
setContentView(R.layout.no_device);
mInputController = null;
}
protected void showControls() {
setContentView(R.layout.main);
mInputController = new InputController(this);
mInputController.accessoryAttached();
}
protected void handleJoyMessage(JoyMsg j) {
if (mInputController != null) {
mInputController.joystickMoved(j.getX(), j.getY());
}
}
protected void handleLightMessage(LightMsg l) {
if (mInputController != null) {
mInputController.setLightValue(l.getLight());
}
}
protected void handleTemperatureMessage(TemperatureMsg t) {
if (mInputController != null) {
mInputController.setTemperature(t.getTemperature());
}
}
protected void handleSwitchMessage(SwitchMsg o) {
if (mInputController != null) {
byte sw = o.getSw();
if (sw >= 0 && sw < 4) {
mInputController.switchStateChanged(sw, o.getState() != 0);
} else if (sw == 4) {
mInputController
.joystickButtonSwitchStateChanged(o.getState() != 0);
}
}
}
} | java | 14 | 0.695085 | 63 | 20.223404 | 94 | starcoderdata |
import math
var = [6.57,6.77,5.60,6.05,6.31,7.98,6.96]
var2 = [45,25,35,50,25,15,40]
total = 0
dpvar = 0
dpvar2 = 0
for m in range(len(var)):
dpvar += (var[m] - 6,60)**2
for n in range(len(var2)):
dpvar2 += (var2[n] - 33.57)**2
dpvar2 = math.sqrt(dpvar2/6)
dpvar = math.sqrt(dpvar/6)
print(dpvar,dpvar2)
for i in range(len(var)):
print("(" + str(var[i]) + " - 6,60)(" + str(var2[i]) + " - 33.57)")
total += (var[i] - 6,60)*(var2[i] - 33.57)
print(total)
print(total/(6*dpvar*dpvar2))
import math
var = [6.57,6.77,5.60,6.05,6.31,7.98,6.96]
var2 = [45,25,35,50,25,15,40]
total = 0
dpvar = 0
dpvar2 = 0
for m in range(len(var)):
dpvar += (var[m] - 66.60)**2
for n in range(len(var2)):
dpvar2 += (var2[n] - 33.57)**2
dpvar2 = math.sqrt(dpvar2/6)
dpvar = math.sqrt(dpvar/6)
print(dpvar,dpvar2)
for i in range(len(var)):
print("(" + str(var[i]) + " - 6.60)(" + str(var2[i]) + " - 33.57)")
total += (var[i] - 6.60)*(var2[i] - 33.57)
print(total)
print(total/(6*dpvar*dpvar2)) | python | 13 | 0.579208 | 72 | 21.954545 | 44 | starcoderdata |
import CRUDL from '@/index';
import * as executors from '@/executors/index';
describe('modifiers', () => {
let posts;
beforeEach(() => {
posts = new CRUDL('post');
});
it('should return all the default modifiers correctly', () => {
expect(Object.keys(posts.modifiers)).toEqual(
Object.values(posts.constants.create)
.concat(Object.values(posts.constants.read))
.concat(Object.values(posts.constants.update))
.concat(Object.values(posts.constants.delete))
.concat(Object.values(posts.constants.list)),
);
});
it('should return modifiers for included operations only', () => {
posts = new CRUDL('post', { include: ['create', 'update'] });
expect(Object.keys(posts.modifiers)).toEqual(
Object.values(posts.constants.create)
.concat(Object.values(posts.constants.update)),
);
});
it('should call the default modifier executors correctly', () => {
const data = { list: { items: { 1: { a: 'b' } }, loading: false, failure: null } };
const response = { data: { posts: [{ id: 1, a: 'b' }] } };
const error = new Error('foo bar');
const cleanSpy = jest.spyOn(executors, 'clean');
const startSpy = jest.spyOn(executors, 'start');
const successSpy = jest.spyOn(executors, 'success');
const failureSpy = jest.spyOn(executors, 'failure');
posts.modifiers[posts.constants.list.clean](data);
expect(cleanSpy).toHaveBeenLastCalledWith(posts.keys.list, posts.operations.list, posts.config, data);
posts.modifiers[posts.constants.list.start](data, response);
expect(startSpy).toHaveBeenLastCalledWith(posts.keys.list, posts.operations.list, posts.config, data, response);
posts.modifiers[posts.constants.list.success](data, response);
expect(successSpy).toHaveBeenLastCalledWith(posts.keys.list, posts.operations.list, posts.config, data, response);
posts.modifiers[posts.constants.list.failure](data, error);
expect(failureSpy).toHaveBeenLastCalledWith(posts.keys.list, posts.operations.list, posts.config, data, error);
});
it('should call custom modifier executors correctly', () => {
const customExecutors = {
clean: jest.fn(),
start: jest.fn(),
success: jest.fn(),
failure: jest.fn(),
};
posts = new CRUDL('post', { executors: customExecutors });
const data = { list: { items: { 1: { a: 'b' } }, loading: false, failure: null } };
const response = { data: { posts: [{ id: 1, a: 'b' }] } };
const error = new Error('foo bar');
posts.modifiers[posts.constants.list.clean](data);
expect(customExecutors.clean).toHaveBeenLastCalledWith(posts.keys.list, posts.operations.list, posts.config, data);
posts.modifiers[posts.constants.list.start](data, response);
expect(customExecutors.start).toHaveBeenLastCalledWith(posts.keys.list, posts.operations.list, posts.config, data, response);
posts.modifiers[posts.constants.list.success](data, response);
expect(customExecutors.success).toHaveBeenLastCalledWith(posts.keys.list, posts.operations.list, posts.config, data, response);
posts.modifiers[posts.constants.list.failure](data, error);
expect(customExecutors.failure).toHaveBeenLastCalledWith(posts.keys.list, posts.operations.list, posts.config, data, error);
});
it('should handle responses with no keys', () => {
let result;
posts = new CRUDL('post', {
keys: {
list: '',
read: '',
},
});
const data = {
list: { items: {}, loading: false, failure: null, config: {} },
read: { item: {}, loading: false, failure: null, config: {} }
};
result = posts.modifiers[posts.constants.list.success](data, { data: [{ id: 123 }] });
expect(result.list).toEqual({ items: { 123: { id: 123 } }, loading: false, failure: null, config: {} });
result = posts.modifiers[posts.constants.read.success](data, { data: { id: 123 } });
expect(result.read).toEqual({ item: { id: 123 }, loading: false, failure: null, config: {} });
});
it('should not modify the original data when the "spread" config is present', () => {
let data;
let result;
const response = { data: { posts: [{ id: 1, a: 'b' }] } };
posts = new CRUDL('post');
data = { list: { items: {}, loading: false, failure: null, config: {} } };
result = posts.modifiers[posts.constants.list.success](data, response);
expect(result).toEqual({ list: { items: { 1: { id: 1, a: 'b' } }, loading: false, failure: null, config: {} } });
expect(data).toEqual({ list: { items: { 1: { id: 1, a: 'b' } }, loading: false, failure: null, config: {} } });
posts = new CRUDL('post', { spread: true });
data = { list: { items: {}, loading: false, failure: null, config: {} } };
result = posts.modifiers[posts.constants.list.success](data, response);
expect(result).toEqual({ list: { items: { 1: { id: 1, a: 'b' } }, loading: false, failure: null, config: {} } });
expect(data).toEqual({ list: { items: {}, loading: false, failure: null, config: {} } });
});
}); | javascript | 27 | 0.641398 | 131 | 41.082645 | 121 | starcoderdata |
package com.algorithm.space.hancock.offer.solution;
import com.algorithm.space.hancock.common.ListNode;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
class SolutionOf06Test {
@Test
void reversePrint_shouldReturn321_givenHeadOf1() {
// given
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
node1.next = node2;
node2.next = node3;
// when
int[] result = new SolutionOf06().reversePrint(node1);
// then
Assertions.assertThat(result).containsExactly(3,2,1);
}
} | java | 10 | 0.706081 | 58 | 23.666667 | 24 | starcoderdata |
import Modal from '../Modal';
import React from 'react';
import { storiesOf } from '@storybook/react';
import {
withKnobs
} from '@storybook/addon-knobs';
storiesOf('Components|Modal', module)
.addDecorator(withKnobs)
.add('Default', () => (
<Modal show title='Product Added'>
new product have been added to your catalog.
Product ID:
date:
))
.add('disable styles', () => (
<Modal disableStyles show
title='Product Added'>
new product have been added to your catalog.
Product ID:
date:
))
.add('custom styles', () => (
<Modal customStyles={require('../../utils/WithStyles/customStylesTest.css')} show
title='Product Added'>
new product have been added to your catalog.
Product ID:
date:
)); | javascript | 14 | 0.552588 | 89 | 36.4375 | 32 | starcoderdata |
#include
#include
#include
#include
#include
#include
#include
MenuState::MenuState(StateStack& stack, Context context)
: State(stack, context)
, mGUIContainer()
{
sf::Texture& texture = context.textures->get(Textures::TitleScreen);
mBackgroundSprite.setTexture(texture);
auto playButton = std::make_shared
playButton->setPosition(100, 300);
playButton->setText("Play");
playButton->setCallback([this] ()
{
requestStackPop();
requestStackPush(States::Game);
});
auto settingsButton = std::make_shared
settingsButton->setPosition(100, 350);
settingsButton->setText("Settings");
settingsButton->setCallback([this] ()
{
requestStackPush(States::Settings);
});
auto exitButton = std::make_shared
exitButton->setPosition(100, 400);
exitButton->setText("Exit");
exitButton->setCallback([this] ()
{
requestStackPop();
});
mGUIContainer.pack(playButton);
mGUIContainer.pack(settingsButton);
mGUIContainer.pack(exitButton);
// Play menu theme
context.music->play(Music::MenuTheme);
}
void MenuState::draw()
{
sf::RenderWindow& window = *getContext().window;
window.setView(window.getDefaultView());
window.draw(mBackgroundSprite);
window.draw(mGUIContainer);
}
bool MenuState::update(sf::Time)
{
return true;
}
bool MenuState::handleEvent(const sf::Event& event)
{
mGUIContainer.handleEvent(event);
return false;
} | c++ | 12 | 0.742424 | 69 | 22.239437 | 71 | starcoderdata |
<?php
namespace Admin\Controller;
use Admin\Common\AdminController;
use Think\Page;
class DataController extends AdminController{
protected $autoCheckFields =false;
/*
* 数据字典展示
*/
public function data_list() {
$model_data = M('datadictionary');
//获取总数
$data_count = $model_data->count();
//倒入分页类
import('Think.Page');
$page_class = new Page($data_count,8);
$page_class->setConfig('prev', '«');
$page_class->setConfig('next', '»');
$page_class->setConfig('theme', '<div class="pagin"><ul class="paginList"><li class="paginItem">%UP_PAGE% class="paginItem">%LINK_PAGE% class="paginItem">%DOWN_PAGE%
$page = $page_class->show();
//获取列表
$data_list = $model_data->limit($page_class->firstRow.','.$page_class->listRows)->select();
//为权限加上
$actionName1["auth_a"]="add_show";
$add_show = $this->checkAuth($actionName1);
$actionName2["auth_a"]="editor_show";
$editor_show = $this->checkAuth($actionName2);
$actionName3["auth_a"]="data_del";
$data_del = $this->checkAuth($actionName3);
$this->assign('editor_show',$editor_show);
$this->assign('data_del',$data_del);
$this->assign('add_show',$add_show);
$this->assign('page',$page);
$this->assign('data_list',$data_list);
$this->display();
}
/**
* 添加前展示
*/
public function add_show(){
$model_dictype_list = M('dictype');
$dictype_list = $model_dictype_list->limit($page_class->firstRow.','.$page_class->listRows)->select();
$this->assign('dictype_list',$dictype_list);
$this->display();
}
/**
* 进行保存
*/
public function data_add(){
$model_data = M('datadictionary');
$result = $model_data->add($_POST);
if($result){
//添加日志
$type = 1;
$title = "添加";
$viewurl = "/admin/data/data_add";
$username = $_SESSION['admin_name'];
$res = $this->log_add($type, $title, $viewurl, $username);
$this->success('添加成功',U("admin/data/data_list"));
}else{
$this->error('添加失败',U("admin/data/add_show"));
}
}
/**
* 修改前
*/
public function editor_show(){
$model_dictype_list = M('dictype');
$dictype_list = $model_dictype_list->select();
$this->assign('dictype_list',$dictype_list);
$model_dictype = M('datadictionary');
$array = array();
$array['id'] = $_GET['id'];
$data_info = $model_dictype->where(array('id'=>$_GET['id']))->find();
$this->assign('data_info',$data_info);
$this->display();
}
/**
* 更新、保存
*/
public function data_update(){
$model_data = M('datadictionary');
$result = $model_data->save($_POST);
if($result){
$this->success('修改成功',U("admin/data/data_list"));
}else{
$this->error('修改失败',U("admin/data/editor_show",array('id'=>$_POST['id'])));
}
}
/**
* 根据id进行删除
*/
public function data_del(){
$model_data = M('datadictionary');
$result = $model_data->where(array('id'=>$_GET['id']))->delete();
if($result){
$this->success('操作成功!',U("admin/data/data_list"));
}else{
$this->error('操作失败',U("admin/data/data_list"));
}
}
} | php | 19 | 0.507259 | 212 | 30 | 112 | starcoderdata |
#include
#include
#include
#define NMAX 100
#define QMAX 100
struct horse {
unsigned long int /* Ei */ distance;
unsigned int /* Si */ speed;
};
struct path {
char /* Uk */ from;
char /* Vk */ to;
};
double solve(struct horse *horses, size_t matrix[NMAX][NMAX], size_t n,
struct path *paths, size_t q)
{
size_t city, i;
size_t distance, total;
double best[NMAX];
double try;
/* Focus on the small dataset ; q = 1 */
assert(q == 1);
/* Fill with the highest score possible */
for(i = 0; i < NMAX; i++)
best[i] = 1e99;
best[0] = 0;
/* Find where we can go from each horse */
for(city = 0; city < n; city++) {
distance = 0;
assert(best[city] != -1);
for(i = city + 1; i < n; i++) {
assert(matrix[i - 1][i] != -1);
distance += matrix[i - 1][i];
/* Horse ran out of stamina */
if(distance > horses[city].distance)
break;
/* Is it better to leave city with its horse ? */
try = (double)distance / horses[city].speed;
if(best[i] > try + best[city])
best[i] = try + best[city];
}
}
return (double)best[n - 1];
}
int main(int argc, char *argv[])
{
size_t T, i;
size_t N, j, Q, k;
double answer;
struct horse horses[NMAX];
size_t cities[NMAX][NMAX];
struct path paths[QMAX];
scanf("%llu", &T);
for(i = 0; i < T; i++) {
scanf("%llu %llu", &N, &Q);
/* Read each horses */
for(j = 0; j < N; j++)
scanf("%llu %u", &horses[j].distance,
&horses[j].speed);
/* Read each cities */
for(j = 0; j < N; j++)
for(k = 0; k < N; k++)
scanf("%llu", &cities[j][k]);
for(j = 0; j < Q; j++)
scanf("%u %u", &paths[j].from, &paths[j].to);
answer = solve(horses, cities, N, paths, Q);
printf("Case #%u: %.6f\n", i + 1, answer);
}
return EXIT_SUCCESS;
} | c | 14 | 0.548283 | 71 | 19.053763 | 93 | starcoderdata |
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::IOError(err) => write!(f, "{}", err),
Self::Serialization(err) => write!(f, "{}", err),
// Deal with more variants here
}
} | rust | 10 | 0.463035 | 61 | 35.857143 | 7 | inline |
#ifndef CD_NuclearInteractionFinder_H_
#define CD_NuclearInteractionFinder_H_
//----------------------------------------------------------------------------
//! \class NuclearInteractionFinder
//! \brief Class used to obtain vector of all compatible TMs associated to a trajectory to be used by the NuclearTester.
//!
//!
//! \description The method run gets all compatible TMs of all TMs associated of a trajectory.
//! Then it uses the NuclearTester class to decide whether the trajectory has interacted nuclearly or not.
//! It finally returns a pair of the TM where the nuclear interaction occurs and all compatible TMs associated.
//-----------------------------------------------------------------------------
#include "TrackingTools/GeomPropagators/interface/Propagator.h"
#include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h"
#include "TrackingTools/TrajectoryState/interface/FreeTrajectoryState.h"
#include "TrackingTools/PatternTools/interface/TrajectoryStateUpdator.h"
#include "TrackingTools/PatternTools/interface/Trajectory.h"
#include "TrackingTools/TrackFitters/interface/TrajectoryFitter.h"
#include "TrackingTools/PatternTools/interface/TrajectoryMeasurement.h"
#include "TrackingTools/DetLayers/interface/MeasurementEstimator.h"
#include "TrackingTools/MeasurementDet/interface/LayerMeasurements.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "RecoTracker/MeasurementDet/interface/MeasurementTracker.h"
#include "RecoTracker/MeasurementDet/interface/MeasurementTrackerEvent.h"
#include "RecoTracker/TkDetLayers/interface/GeometricSearchTracker.h"
#include "MagneticField/Engine/interface/MagneticField.h"
#include "DataFormats/TrajectorySeed/interface/TrajectorySeedCollection.h"
#include "RecoTracker/NuclearSeedGenerator/interface/NuclearTester.h"
#include "RecoTracker/NuclearSeedGenerator/interface/SeedFromNuclearInteraction.h"
#include "RecoTracker/NuclearSeedGenerator/interface/TangentHelix.h"
#include "TrackingTools/DetLayers/interface/NavigationSchool.h"
#include
class NuclearInteractionFinder {
private:
typedef TrajectoryStateOnSurface TSOS;
typedef FreeTrajectoryState FTS;
typedef TrajectoryMeasurement TM;
typedef std::vector TrajectoryContainer;
typedef TrajectoryMeasurement::ConstRecHitPointer ConstRecHitPointer;
/// get the seeds at the interaction point
void fillSeeds( const std::pair<TrajectoryMeasurement, std::vector >& tmPairs );
/// Find compatible TM of a TM with error rescaled by rescaleFactor
std::vector
findCompatibleMeasurements( const TM& lastMeas, double rescaleFactor, const LayerMeasurements & layerMeasurements) const;
std::vector
findMeasurementsFromTSOS(const TSOS& currentState, DetId detid, const LayerMeasurements & layerMeasurements) const;
/// Calculate the parameters of the circle representing the primary track at the interaction point
void definePrimaryHelix(std::vector it_meas);
public:
NuclearInteractionFinder(){}
NuclearInteractionFinder(const edm::EventSetup& es, const edm::ParameterSet& iConfig);
virtual ~NuclearInteractionFinder();
/// Run the Finder
bool run(const Trajectory& traj, const MeasurementTrackerEvent &event );
/// Improve the seeds with a third RecHit
void improveSeeds( const MeasurementTrackerEvent &event );
/// Fill 'output' with persistent nuclear seeds
std::unique_ptr getPersistentSeeds();
TrajectoryStateOnSurface rescaleError(float rescale, const TSOS& state) const;
const NavigationSchool* nav() const { return theNavigationSchool; }
private:
const Propagator* thePropagator;
const MeasurementEstimator* theEstimator;
const MeasurementTracker* theMeasurementTracker;
const GeometricSearchTracker* theGeomSearchTracker;
const NavigationSchool* theNavigationSchool;
edm::ESHandle theMagField;
NuclearTester* nuclTester;
SeedFromNuclearInteraction *currentSeed;
std::vector< SeedFromNuclearInteraction > allSeeds;
TangentHelix* thePrimaryHelix;
// parameters
double ptMin;
unsigned int maxHits;
double rescaleErrorFactor;
bool checkCompletedTrack; /**< If set to true check all the tracks, even those reaching the edge of the tracker */
std::string navigationSchoolName;
};
#endif | c | 11 | 0.758308 | 130 | 41.513761 | 109 | starcoderdata |
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
public function scopeType($query,$type='menu'){
return $query->where('category_type',$type);
}
public static function fieldRows($row){
return [
'id' => $row->id ,
'ref_id' => $row->ref_id ,
'subject' => @json_decode($row->subject) ,
'category_type' => $row->category_type ,
'category_sort' => $row->category_sort ,
'created_at' => date('Y-m-d H:i:s', strtotime( $row->created_at) ),
'updated_at' => date('Y-m-d H:i:s', strtotime( $row->updated_at) )
];
}
public static function option($lang = '',$selected=''){
$rows = Category::orderBy('category_sort')->get();
$opt = '';
if( $rows ){
foreach( $rows as $row){
$subject = @json_decode( $row->subject);
$opt .= '<option value="'. $row->id .'" '. ( $row->id == $selected ? 'selected' : '' ) .'>'. $subject->$lang .'
}
}
return $opt;
}
} | php | 20 | 0.489609 | 138 | 29.075 | 40 | starcoderdata |
/*
* 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.struts2.el.parser;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.el.ELException;
import org.apache.struts2.el.lang.EvaluationContext;
/**
* @author [
* @version $Change: 181177 $$DateTime: 2001/06/26 08:45:09 $$Author: markt $
*/
public final class AstNegative extends SimpleNode {
public AstNegative(int id) {
super(id);
}
public Class getType(EvaluationContext ctx)
throws ELException {
return Number.class;
}
public Object getValue(EvaluationContext ctx)
throws ELException {
Object obj = this.children[0].getValue(ctx);
if (obj == null) {
return new Long(0);
}
if (obj instanceof BigDecimal) {
return ((BigDecimal) obj).negate();
}
if (obj instanceof BigInteger) {
return ((BigInteger) obj).negate();
}
if (obj instanceof String) {
if (isStringFloat((String) obj)) {
return new Double(-Double.parseDouble((String) obj));
}
return new Long(-Long.parseLong((String) obj));
}
if (obj instanceof Long) {
return new Long(-((Long) obj).longValue());
}
if (obj instanceof Double) {
return new Double(-((Double) obj).doubleValue());
}
if (obj instanceof Integer) {
return new Integer(-((Integer) obj).intValue());
}
if (obj instanceof Float) {
return new Float(-((Float) obj).floatValue());
}
if (obj instanceof Short) {
return new Short((short) -((Short) obj).shortValue());
}
if (obj instanceof Byte) {
return new Byte((byte) -((Byte) obj).byteValue());
}
Long num = (Long) coerceToNumber(obj, Long.class);
return new Long(-num.longValue());
}
} | java | 16 | 0.617302 | 77 | 32.268293 | 82 | starcoderdata |
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_sort.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lyuri-go +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/23 09:54:55 by lyuri-go #+# #+# */
/* Updated: 2021/10/25 18:37:57 by lyuri-go ### ########.fr */
/* */
/* ************************************************************************** */
#include
static int ft_should_swap(t_list *list)
{
t_list swap_b;
t_list swap_a;
int without_swap;
int with_swap;
int should_swap;
swap_b.next = &swap_a;
swap_b.content = malloc(sizeof(t_info));
(swap_b.content)->index = list->next->content->index;
swap_a.next = list->next->next;
swap_a.content = malloc(sizeof(t_info));
(swap_a.content)->index = list->content->index;
without_swap = ft_biggest_seq_tag(list, 0);
with_swap = ft_biggest_seq_tag(&swap_b, 0);
should_swap = with_swap > without_swap;
free(swap_b.content);
free(swap_a.content);
return (should_swap);
}
static void ft_actions(t_content *content, int top_distance)
{
if (content->list_a && ft_should_swap(content->list_a))
{
ft_sa(content, 1);
content->biggest_sequence = ft_biggest_seq_tag(content->list_a, 1);
}
else if (content->list_a && !content->list_a->content->tag_keep
&& top_distance == 0)
{
ft_pb(content, 1);
(content->length)--;
}
else if (content->groups == 1)
ft_rr(content, 1);
else
ft_rotate(content, ft_min(1, ft_max(-1, top_distance)), 0);
}
static void ft_improve(t_content *content)
{
if (content->length == 5 && content->biggest_sequence == 2
&& ft_should_swap(content->list_a)
&& content->list_a->content->index == 1)
ft_rra(content, 1);
}
static void ft_refill_a_from_b(t_content *content)
{
int a_rot;
int b_rot;
while (content->list_b)
{
ft_set_rotation(content, MAX_INT, &a_rot, &b_rot);
ft_rotate(content, a_rot, b_rot);
ft_pa(content, 1);
(content->length)++;
}
ft_rotate(content, ft_distance_to_index(content->list_a, 0), 0);
}
void ft_sort(t_content *content)
{
int top_distance;
int actual_group;
actual_group = 1;
ft_improve(content);
while (content->length >= content->biggest_sequence
&& actual_group <= (content->groups + 1))
{
content->list_a_ref = ft_get_closest_group(
content->list_a, actual_group, content->groups_len);
if (content->list_a_ref == NULL && ++actual_group)
continue ;
top_distance = ft_distance_to_index(
content->list_a, content->list_a_ref->content->index);
ft_actions(content, top_distance);
}
ft_refill_a_from_b(content);
} | c | 16 | 0.493729 | 80 | 29.918367 | 98 | starcoderdata |
inline void version_info::init_()
{
#if !defined(STLSOFT_CF_EXCEPTION_SUPPORT) || \
!defined(STLSOFT_CF_THROW_BAD_ALLOC)
if(NULL == m_hdr)
{
return;
}
#else /* ? exceptions */
WINSTL_ASSERT(NULL != m_hdr);
#endif /* !STLSOFT_CF_EXCEPTION_SUPPORT || !STLSOFT_CF_THROW_BAD_ALLOC */
#ifdef _DEBUG
// Check that ffi is the same as the pointer returned from VerQueryValue("\\");
VS_FIXEDFILEINFO *ffi = NULL;
UINT cchInfo = 0;
WINSTL_ASSERT(::VerQueryValueA(const_cast<VS_VERSIONINFO_hdr*>(m_hdr), "\\", reinterpret_cast<void**>(&ffi), &cchInfo));
WINSTL_ASSERT(ffi == m_ffi);
#endif /* _DEBUG */
// Now we must parse the children.
void const * pv = m_children;
void const *const end = rounded_ptr(m_hdr, m_hdr->wLength, 4);
WINSTL_ASSERT(ptr_byte_diff(end, pv) >= 0);
for(; pv != end; )
{
union
{
void const *pv_;
StringFileInfo_hdr const *psfi;
VarFileInfo_hdr const *pvfi;
} u;
u.pv_ = pv;
WINSTL_ASSERT(ptr_byte_diff(pv, m_hdr) < m_hdr->wLength);
if(0 == ::wcsncmp(u.psfi->szKey, L"StringFileInfo", 15))
{
WINSTL_ASSERT(NULL == m_sfi);
m_sfi = u.psfi;
pv = rounded_ptr(pv, u.psfi->wLength, 4);
}
else if(0 == ::wcsncmp(u.psfi->szKey, L"VarFileInfo", 12))
{
WINSTL_ASSERT(NULL == m_vfi);
m_vfi = u.pvfi;
pv = rounded_ptr(pv, u.pvfi->wLength, 4);
}
else
{
#ifdef STLSOFT_UNITTEST
::wprintf(L"Unexpected contents of VS_VERSIONINFO children. pv: 0x%08x; Key: %.*s\n", pv, 20, u.psfi->szKey);
#endif /* STLSOFT_UNITTEST */
WINSTL_MESSAGE_ASSERT("Unexpected contents of VS_VERSIONINFO children", NULL == m_vfi);
break;
}
WINSTL_ASSERT(ptr_byte_diff(pv, end) <= 0);
}
WINSTL_ASSERT(ptr_byte_diff(pv, m_hdr) == m_hdr->wLength);
#ifdef _DEBUG
fixed_file_info fixedInfo = FixedFileInfo();
ws_uint16_t j = fixedInfo.FileVerMajor();
ws_uint16_t n = fixedInfo.FileVerMinor();
ws_uint16_t r = fixedInfo.FileVerRevision();
ws_uint16_t b = fixedInfo.FileVerBuild();
STLSOFT_SUPPRESS_UNUSED(j);
STLSOFT_SUPPRESS_UNUSED(n);
STLSOFT_SUPPRESS_UNUSED(r);
STLSOFT_SUPPRESS_UNUSED(b);
#endif /* _DEBUG */
} | c++ | 16 | 0.549091 | 124 | 27.45977 | 87 | inline |
void OpenGLTexture::LoadTexture(unsigned char* data, int width, int height, int channels)
{
m_IsLoaded = true;
m_Width = width;
m_Height = height;
GLenum internalFormat = 0, dataFormat = 0;
if (channels == 4)
{
internalFormat = GL_RGBA8;
dataFormat = GL_RGBA;
}
else if (channels == 3)
{
internalFormat = GL_RGB8;
dataFormat = GL_RGB;
}
else if (channels == 1)
{
internalFormat = GL_R8;
dataFormat = GL_RED;
}
m_InternalFormat = internalFormat;
m_DataFormat = dataFormat;
// Guarding against this on linux due to stb_image, including Log.h after stb could work
#ifdef LL_PLATFORM_WINDOWS
//LL_CORE_ASSERT(internalFormat & dataFormat, "Format not supported!");
#endif
if (m_TextureID != NULL) DeleteTexture();
glCreateTextures(GL_TEXTURE_2D, 1, &m_TextureID);
glTextureStorage2D(m_TextureID, 1, m_InternalFormat, m_Width, m_Height);
glTextureParameteri(m_TextureID, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTextureParameteri(m_TextureID, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTextureParameteri(m_TextureID, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTextureParameteri(m_TextureID, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
if (channels == 1)
{
glTextureParameteri(m_TextureID, GL_TEXTURE_SWIZZLE_G, GL_RED);
glTextureParameteri(m_TextureID, GL_TEXTURE_SWIZZLE_B, GL_RED);
}
glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // THIS FIXED THE STRETCHING ISSUE
glTextureSubImage2D(m_TextureID, 0, 0, 0, m_Width, m_Height, m_DataFormat, GL_UNSIGNED_BYTE, data);
} | c++ | 11 | 0.702738 | 101 | 27.425926 | 54 | inline |
package com.hust.edu.cn.dp;
import org.junit.Test;
public class _152 {
@Test
public void test() {
int[] nums = {-2, 0, -1};
System.out.print(maxProduct(nums));
}
//使用max和min分别表示数组中乘积的最大值和最小值,初始化为1,表示此时没有元素相乘。
//如果当前的nums[i]为负数,此时min与max交换,因为当a
//
private int maxProduct(int[] nums) {
int Max = Integer.MIN_VALUE, max = 1, min = 1;
for (int num : nums) {
if (num < 0) {
int temp = max;
max = min;
min = temp;
}
max = Math.max(num, max * num);
min = Math.min(num, min * num);
Max = Math.max(max, Max);
}
return Max;
}
} | java | 12 | 0.48183 | 55 | 23.766667 | 30 | starcoderdata |
import functools
import tkinter
from tkinter import ttk
def print_hello_number(number):
print("hello", number)
root = tkinter.Tk()
big_frame = ttk.Frame(root)
big_frame.pack(fill='both', expand=True)
for i in range(1, 6):
button = ttk.Button(big_frame, text="Hello %d" % i,
command=functools.partial(print_hello_number, i))
button.pack()
root.mainloop() | python | 10 | 0.659091 | 73 | 19.842105 | 19 | starcoderdata |
'use strict'
const walk = require('./walk')
const hrefs = (node) => {
const hrefs = []
walk(node, (n) => {
const d = n.data || null
if (n.data) {
const d = n.data
const href = (
d.href || d['xlink:href']
|| (d.attrs && (d.attrs.href || d.attrs['xlink:href']))
|| null
)
if (href) hrefs.push(href)
}
return !(n.sel && n.sel === 'defs')
})
return hrefs
}
module.exports = hrefs | javascript | 21 | 0.498952 | 63 | 16.666667 | 27 | starcoderdata |
/*
* JBoss, Home of Professional Open Source
* Copyright 2014, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* 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 org.jboss.as.test.integration.auditlog;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ENABLED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROTOCOL;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SYSTEM_PROPERTY;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.TLS;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.integration.security.common.CoreUtils;
import org.jboss.as.test.shared.TimeoutUtil;
import org.jboss.as.test.syslogserver.BlockedSyslogServerEventHandler;
import org.jboss.as.test.syslogserver.TCPSyslogServerConfig;
import org.jboss.dmr.ModelNode;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.productivity.java.syslog4j.SyslogConstants;
import org.productivity.java.syslog4j.server.SyslogServerConfigIF;
import org.productivity.java.syslog4j.server.SyslogServerEventIF;
import org.productivity.java.syslog4j.server.SyslogServerIF;
import org.wildfly.core.testrunner.ManagementClient;
import org.wildfly.core.testrunner.ServerSetup;
import org.wildfly.core.testrunner.WildflyTestRunner;
/**
* Tests that plain TCP messages are not sent when TLS syslog-handler is selected in Audit Log settings.
* Regression test for WFCORE-190.
*
* @author:
*/
@RunWith(WildflyTestRunner.class)
@ServerSetup(TLSAuditLogToTCPSyslogTestCase.AuditLogToTCPSyslogTestCaseSetup.class)
public class TLSAuditLogToTCPSyslogTestCase {
private static final int ADJUSTED_SECOND = TimeoutUtil.adjust(1000);
@Inject
private ManagementClient managementClient;
protected static SyslogServerIF server;
private List properties = new ArrayList
@Test
public void testAuditLoggingToSyslog() throws Exception {
final BlockingQueue queue = BlockedSyslogServerEventHandler.getQueue();
queue.clear();
SyslogServerEventIF syslogEvent = null;
try {
setAuditlogEnabled(true);
// enabling audit-log is auditable event
syslogEvent = queue.poll(1 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
// but we don't expect a message in TCP syslog server
Assert.assertNull("No message was expected in the syslog, because TCP syslog server is used", syslogEvent);
} finally {
setAuditlogEnabled(false);
}
for (Long property : properties) {
CoreUtils.applyUpdate(
Util.createRemoveOperation(PathAddress.pathAddress().append(SYSTEM_PROPERTY, Long.toString(property))),
managementClient.getControllerClient());
}
properties.clear();
}
/**
* Enables/disables the auditlog.
*
* @throws Exception
*/
private void setAuditlogEnabled(boolean value) throws Exception {
ModelNode op = Util.getWriteAttributeOperation(AuditLogToSyslogSetup.AUDIT_LOG_LOGGER_ADDR, ENABLED, value);
CoreUtils.applyUpdate(op, managementClient.getControllerClient());
}
/**
* {@link org.jboss.as.arquillian.api.ServerSetupTask} implementation which configures syslog server and auditlog-to-syslog
* handler for this test.
*/
static class AuditLogToTCPSyslogTestCaseSetup extends AuditLogToSyslogSetup {
@Override
protected String getSyslogProtocol() {
return SyslogConstants.TCP;
}
@Override
protected SyslogServerConfigIF getSyslogConfig() {
return new TCPSyslogServerConfig();
}
@Override
protected ModelNode addAuditlogSyslogProtocol(PathAddress syslogHandlerAddress) {
ModelNode op = Util.createAddOperation(syslogHandlerAddress.append(PROTOCOL, TLS));
op.get("message-transfer").set("OCTET_COUNTING");
return op;
}
}
} | java | 16 | 0.737208 | 127 | 36.875969 | 129 | starcoderdata |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Unicodeveloper\Paystack\Paystack;
class PaymentController extends Controller
{
private $paystack;
public function __construct()
{
$this->paystack = new Paystack();
}
/**
* Redirect the User to Paystack Payment Page
* @return Url
*/
public function redirectToGateway()
{
return $this->paystack->getAuthorizationUrl()->redirectNow();
}
} | php | 10 | 0.656442 | 69 | 18.56 | 25 | starcoderdata |
from automation_framework.driver.driver import get_driver
class Page:
def __init__(self):
self.driver = get_driver() | python | 9 | 0.727778 | 57 | 24.714286 | 7 | starcoderdata |
pub fn disconnect(
mut self,
disposition: Disposition,
) -> Result<(), (Card, Error)> {
unsafe {
let err = ffi::SCardDisconnect(
self.handle,
disposition.into_raw(),
);
if err != ffi::SCARD_S_SUCCESS {
return Err((self, Error::from_raw(err)));
}
// Skip the drop, we did it "manually".
std::ptr::drop_in_place(&mut self._context);
forget(self);
Ok(())
}
} | rust | 16 | 0.434381 | 57 | 26.1 | 20 | inline |
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
import os
import six
import texttable
from compose.cli import colors
def get_tty_width():
tty_size = os.popen('stty size 2> /dev/null', 'r').read().split()
if len(tty_size) != 2:
return 0
_, width = tty_size
return int(width)
class Formatter:
"""Format tabular data for printing."""
@staticmethod
def table(headers, rows):
table = texttable.Texttable(max_width=get_tty_width())
table.set_cols_dtype(['t' for h in headers])
table.add_rows([headers] + rows)
table.set_deco(table.HEADER)
table.set_chars(['-', '|', '+', '-'])
return table.draw()
class ConsoleWarningFormatter(logging.Formatter):
"""A logging.Formatter which prints WARNING and ERROR messages with
a prefix of the log level colored appropriate for the log level.
"""
def get_level_message(self, record):
separator = ': '
if record.levelno == logging.WARNING:
return colors.yellow(record.levelname) + separator
if record.levelno == logging.ERROR:
return colors.red(record.levelname) + separator
return ''
def format(self, record):
if isinstance(record.msg, six.binary_type):
record.msg = record.msg.decode('utf-8')
message = super(ConsoleWarningFormatter, self).format(record)
return '{0}{1}'.format(self.get_level_message(record), message) | python | 13 | 0.63792 | 71 | 27.12963 | 54 | starcoderdata |
package com.designre.blog.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.designre.blog.model.dto.ArchiveDto;
import com.designre.blog.model.dto.ArticleDetailDto;
import com.designre.blog.model.dto.ArticleInfoDto;
import com.designre.blog.model.param.ArticleQuery;
import com.designre.blog.model.param.SaveArticleParam;
import com.designre.blog.model.entity.Article;
import java.util.Collection;
import java.util.List;
public interface ArticleService extends IService {
IPage pageArticleFront(Integer current, Integer size, List sort);
ArticleDetailDto getArticleFront(Integer id);
IPage pageArticleAdmin(Integer current, Integer size, ArticleQuery query);
ArticleDetailDto getArticleAdmin(Integer id);
ArticleDetailDto createOrUpdate(SaveArticleParam param);
void delete(Integer id);
void visitArticle(Integer id);
void increaseHits(Integer id, Integer increaseHits);
List getArchives();
List listArticleHeader();
List listByIds(Collection ids, boolean isFront);
} | java | 8 | 0.80384 | 96 | 41.785714 | 28 | starcoderdata |
package com.tokelon.toktales.core.engine.log;
import javax.inject.Inject;
public class SLF4JLoggingFactory implements ILoggingFactory {
private final ILoggerNamer loggerNamer;
@Inject
public SLF4JLoggingFactory(ILoggerNamer loggerNamer) { // Use provider?
this.loggerNamer = loggerNamer;
}
@Override
public ILogging create() {
return new Logging(
new SLF4JLoggerFactory(org.slf4j.LoggerFactory.getILoggerFactory(), loggerNamer),
org.slf4j.LoggerFactory.getILoggerFactory(),
loggerNamer
);
}
} | java | 13 | 0.771429 | 85 | 20.875 | 24 | starcoderdata |
package com.pallycon.cpix.dto;
import com.pallycon.cpix.mapper.CpixNamespaceMapper;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
public class ContentKeyDTO {
//optional
private String id;
//optional
private String algorithm;
//content key id . UUID
private String kid;
private String explicitIV;
private DataDTO data;
public ContentKeyDTO() {}
public ContentKeyDTO(String kid) {
this.kid = kid;
}
@XmlAttribute(name="id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlAttribute(name="algorithm")
public String getAlgorithm() {
return algorithm;
}
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
}
@XmlAttribute(name="kid")
public String getKid() {
return kid;
}
public void setKid(String kid) {
this.kid = kid;
}
@XmlAttribute(name="explicitIV")
public String getExplicitIV() {
return explicitIV;
}
public void setExplicitIV(String explicitIV) {
this.explicitIV = explicitIV;
}
@XmlElement(name="Data", type=DataDTO.class, namespace=CpixNamespaceMapper.CPIX_URI)
public DataDTO getData() {
return data;
}
public void setData(DataDTO data) {
this.data = data;
}
} | java | 9 | 0.632796 | 88 | 19.098592 | 71 | starcoderdata |
import React from 'react'
import {
ThemeProvider as StyledComponentsThemeProvider,
css,
} from 'styled-components'
export { GlobalStyle } from './GlobalStyle'
const breakpoints = {
sm: 425,
md: 868, // 768 + 100
lg: 1124, // 1024 + 100
xl: 1440,
}
const mediaQuery = Object.keys(breakpoints).reduce((accumulator, label) => {
accumulator[label] = (...args) => css`
@media (min-width: ${breakpoints[label]}px) {
${css(...args)}
}
`
return accumulator
}, {})
const black = '#000000'
const white = '#FFFFFF'
const theme = {
mediaQuery,
fontFamilies: {
notoSans: 'Noto Sans TC',
barlow: 'Barlow',
roboto: 'Roboto',
},
colors: {
black,
white,
offWhite: '#FAFCFF',
gray: '#E1E8F2',
textColor: '#334E68',
backgroundColor: '#EEF2F8',
overlayColor: 'rgba(211, 221, 235, 0.8)',
blue900: '#1B3C6B',
blue800: '#2A538C',
blue700: '#335E9B',
blue600: '#3F6EAF',
blue500: '#4E7EC2',
blue400: '#6796D7',
blue300: '#84AEE8',
blue200: '#A1C4F4',
blue100: '#C9DFFE',
blue50: '#E4EEFB',
blueGray900: '#102A43',
blueGray800: '#243B53',
blueGray700: '#243B53',
blueGray600: '#486581',
blueGray500: '#627D98',
blueGray400: '#829AB1',
blueGray300: '#9FB3C8',
blueGray200: '#BCCCDC',
blueGray100: '#D9E2EC',
blueGray50: '#F0F4F8',
ultramarineBlue: '#3F7FFF', // accent blue
perano: '#A6C4FF', // accent light blue
dullLime: '#31B237', // accent green
blackSqueeze: '#F0FCF7', // accentlight green
mahogany: '#D64545', // accentdark red
sunglo: '#E66A6A', // accent light red
indigo: '#647ACB', // blue
jordyBlue: '#98AEEB', // lighter blue
lavender: '#E0E8F9', // lightest blue
reefGold: '#A27C1A', // dark yellow
anzac: '#E9B949', // yellow
oasis: '#FCEFC7', //light yellow
},
}
export default function ThemeProvider({ children }) {
return (
<StyledComponentsThemeProvider theme={theme}>
{children}
)
} | javascript | 16 | 0.607422 | 76 | 23.380952 | 84 | starcoderdata |
package acasa_23_10_19;
public class Triunghiuri {
int a = 5, cat1 = 3, cat2 = 4, h = 7;
public double Oarecare() {
double ar5 = a*h/2;
return ar5;
}
public double Dreptunghic() {
double ar6 = cat1*cat2/2;
return ar6;
}
public double Echilateral() {
double ar7 = Math.pow(a, 2) * Math.sqrt(3) / 4;
return ar7;
}
} | java | 11 | 0.60221 | 48 | 15.285714 | 21 | starcoderdata |
package org.enso.table.data.table.problems;
import java.util.ArrayList;
import java.util.List;
public class AggregatedProblems {
private final List problems;
private final int maxSize;
private int count;
private AggregatedProblems(List problems, int count) {
this.problems = problems;
this.maxSize = problems.size();
this.count = count;
}
public AggregatedProblems() {
this(10);
}
public AggregatedProblems(int maxSize) {
this.problems = new ArrayList<>();
this.maxSize = maxSize;
this.count = 0;
}
public Problem[] getProblems() {
if (count == 0) {
return new Problem[0];
}
return problems.toArray(Problem[]::new);
}
public int getCount() {
return count;
}
public void add(Problem problem) {
if (problem instanceof ColumnAggregatedProblems) {
for (Problem p : problems) {
if (p instanceof ColumnAggregatedProblems &&
((ColumnAggregatedProblems) p).merge((ColumnAggregatedProblems)problem)) {
return;
}
}
}
if (problems.size() < maxSize) {
problems.add(problem);
}
count++;
}
public static AggregatedProblems merge(AggregatedProblems[] problems) {
List merged = new ArrayList<>();
int count = 0;
for (AggregatedProblems p : problems) {
if (p != null && p.count > 0) {
merged.addAll(p.problems);
count += p.getCount();
}
}
return new AggregatedProblems(merged, count);
}
} | java | 13 | 0.634951 | 86 | 21.391304 | 69 | starcoderdata |
/**
* Wrapper for SVGPolygonElement native interface
*
* It can wrap SVGPolygonElement elements
*
* If svgDOMNode is wrapped by Vector.Polygon's super class then
* it removes that wrapper and returns a new Vector.Polygon wrapper.
* To get a appropriate wrapper please use Vector.wrap() method.
*
* @type {Vector.Polygon}
*/
var Polygon = Vector.Polygon = function Polygon(points, svgDOMNode) {
var wrappedInstance = Geometry.call(this, svgDOMNode),
attrs = {
points: points
};
if (wrappedInstance) {
wrappedInstance.attr(attrs, null);
return wrappedInstance;
}
this.attr(attrs, null);
};
setPrototypeOf(Polygon, Geometry);
Polygon.prototype = Object.create(Geometry.prototype);
Polygon.prototype.constructor = Polygon;
Vector.merge(Polygon, {
domInterface: window.SVGPolygonElement
});
Vector.merge(Polygon.prototype, {
tag: "polygon",
// Namespace of all the attributes is null
_defaultAttrValues: Vector.merge(Vector.merge({}, Polygon.prototype._defaultAttrValues), {
points: ""
}),
points: function (points) {
return this._setAttrGetterSetter("points", points);
}
}); | javascript | 12 | 0.680301 | 94 | 22.057692 | 52 | starcoderdata |
using LuisBotSample.Extensions;
using Microsoft.Bot.Builder.FormFlow;
using System;
namespace LuisBotSample.Dialogs
{
[Serializable]
public sealed class RestaurantReservation
{
public DayOfWeek Weekday
{
get => Day?.DayOfWeek ?? DayOfWeek.Sunday;
set => Day = DateTime.Today.AddDays(value.DaysUntilNext());
}
[Prompt("Please enter the {&} for the reservation")]
public DateTime? Day { get; set; }
[Prompt("Please enter the {&}")]
public DateTime? Time { get; set; }
[Numeric(1, 50)]
[Prompt("For how many people should be reserved?")]
public int? Number { get; set; }
public override string ToString() => $"Reservation for {Number} people on {Day:d} at {Time:t}";
public const string Reservation_Day = "Reservation.Day";
public const string Reservation_Number = "Reservation.Number";
public const string Reservation_Time = "Reservation.Time";
public const string Reservation_Weekday = "Reservation.Weekday";
}
} | c# | 15 | 0.632653 | 103 | 31.69697 | 33 | starcoderdata |
fn end_era(active_era: ActiveEraInfo, _session_index: SessionIndex) {
if !T::AppchainInterface::is_activated() || <EraPayout<T>>::get() == 0 {
return
}
// Note: active_era_start can be None if end era is called during genesis config.
if let Some(active_era_start) = active_era.start {
if <ErasValidatorReward<T>>::get(&active_era.index).is_some() {
log!(warn, "era reward {:?} has already been paid", active_era.index);
return
}
let now_as_millis_u64 = T::UnixTime::now().as_millis().saturated_into::<u64>();
let _era_duration = (now_as_millis_u64 - active_era_start).saturated_into::<u64>();
let validator_payout = Self::era_payout();
// Set ending era reward.
<ErasValidatorReward<T>>::insert(&active_era.index, validator_payout);
let excluded_validators = Self::get_exclude_validators(active_era.index);
let excluded_validators_str = excluded_validators
.iter()
.map(|validator| {
let prefix = String::from("0x");
let hex_validator = prefix + &hex::encode(validator.encode());
hex_validator
})
.collect::<Vec<String>>();
log!(debug, "Exclude validators: {:?}", excluded_validators_str.clone());
let message = EraPayoutPayload {
end_era: active_era.set_id,
excluded_validators: excluded_validators_str.clone(),
};
let amount = validator_payout.checked_into().ok_or(Error::<T>::AmountOverflow).unwrap();
T::Currency::deposit_creating(&Self::account_id(), amount);
log!(debug, "Will send EraPayout message, era_payout is {:?}", <EraPayout<T>>::get());
let res = T::UpwardMessagesInterface::submit(
&T::AccountId::default(),
PayloadType::EraPayout,
&message.try_to_vec().unwrap(),
);
log!(info, "UpwardMessage::EraPayout: {:?}", res);
if res.is_ok() {
Self::deposit_event(Event::<T>::EraPayout {
era_index: active_era.set_id,
excluded_validators,
});
} else {
Self::deposit_event(Event::<T>::EraPayoutFailed { era_index: active_era.set_id });
}
}
} | rust | 21 | 0.646971 | 91 | 34.350877 | 57 | inline |
<?php
namespace App\Problems\AddTwoNumbers;
/**
* ListNodeクラス
* (実際のleetcodeではclassではなくobjectとして渡されている)
*/
class ListNode {
/** @var int $val */
public $val = 0;
/** @var ListNode|null $next */
public $next = null;
/**
* ListNode constract
* @param integer $val
* @param ListNode|null $next
*/
public function __construct(int $val = 0, ?ListNode $next = null) {
$this->val = $val;
$this->next = $next;
}
}
/**
* AddTwoNumbers Solution
*/
class Solution {
/**
* @param ListNode $l1
* @param ListNode $l2
* @return ListNode
*/
public function addTwoNumbers(ListNode $l1, ListNode $l2) {
$node1 = $l1;
$node2 = $l2;
$carryValue = 0;
$resultNode = $currentNode = new ListNode(0);
while (true) {
$totalValue = $this->getNodeValue($node1) + $this->getNodeValue($node2) + $currentNode->val;
$currentNode->val = (int)($totalValue % 10);
$carryValue = (int)($totalValue / 10);
$node1 = $this->getNextNode($node1);
$node2 = $this->getNextNode($node2);
if ($node1 !== null || $node2 !== null) {
$currentNode->next = new ListNode($carryValue);
$currentNode = $currentNode->next;
}
if ($node1 === null && $node2 === null) {
if ($carryValue > 0) {
$currentNode->next = new ListNode($carryValue);
$currentNode = $currentNode->next;
}
break;
}
}
return $resultNode;
}
/**
* 次のnodeを返す
* @param ListNode|null $node
* @return ListNode|null
*/
private function getNextNode(?ListNode $node): ?ListNode
{
if ($node === null) {
return null;
}
return $node->next;
}
/**
* nodeの値を返す。nullの場合0を返す
* @param ListNode|null $node
* @return integer
*/
private function getNodeValue(?ListNode $node): int
{
if ($node === null) {
return 0;
}
return $node->val;
}
} | php | 17 | 0.500231 | 104 | 23.908046 | 87 | starcoderdata |
--TEST--
Test that a notice is emitted when the tentative return type of the overridden method is omitted
--FILE--
<?php
class MyDateTimeZone extends DateTimeZone
{
public static function listIdentifiers(int $timezoneGroup = DateTimeZone::ALL, ?string $countryCode = null)
{
}
}
?>
--EXPECTF--
Deprecated: Declaration of MyDateTimeZone::listIdentifiers(int $timezoneGroup = DateTimeZone::ALL, ?string $countryCode = null) should be compatible with DateTimeZone::listIdentifiers(int $timezoneGroup = DateTimeZone::ALL, ?string $countryCode = null): array in %s on line %d | php | 9 | 0.759863 | 276 | 43.846154 | 13 | starcoderdata |
void put_calendar_without_timezone(Calendar cal, boolean writememo) throws IOException {
// Note that we can't use the 2-arg representation of a datetime here.
// Python 3 uses the SHORT_BINBYTES opcode to encode the first argument,
// but python 2 uses SHORT_BINSTRING instead. This causes encoding problems
// if you want to send the pickle to either a Python 2 or 3 receiver.
// So instead, we use the full 7 (or 8 with timezone) constructor representation.
out.write(Opcodes.GLOBAL);
out.write("datetime\ndatetime\n".getBytes());
out.write(Opcodes.MARK);
save(cal.get(Calendar.YEAR));
save(cal.get(Calendar.MONTH)+1); // months start at 0 in java
save(cal.get(Calendar.DAY_OF_MONTH));
save(cal.get(Calendar.HOUR_OF_DAY));
save(cal.get(Calendar.MINUTE));
save(cal.get(Calendar.SECOND));
save(cal.get(Calendar.MILLISECOND)*1000);
// this method by design does NOT pickle the tzinfo argument:
// if(cal.getTimeZone()!=null)
// save(cal.getTimeZone());
out.write(Opcodes.TUPLE);
out.write(Opcodes.REDUCE);
if(writememo)
writeMemo(cal);
} | java | 10 | 0.723915 | 88 | 44.166667 | 24 | inline |
public async Task<T> Get<T>()
{
System.Threading.Thread.Sleep(2000);//wait for 1 second and check flags
if(typeof(T) == typeof(FileSystemEventArgs ))
return (T) Convert.ChangeType(a1, typeof(T));
else if(typeof(T) == typeof(RenamedEventArgs ))
return (T) Convert.ChangeType(a2, typeof(T));
else if(typeof(T) == typeof(ErrorEventArgs ))
return (T) Convert.ChangeType(a3, typeof(T));
else throw new NotImplementedException();
} | c# | 13 | 0.559928 | 83 | 49 | 11 | inline |
/*******************************************************************************
* This file is part of CMacIonize
* Copyright (C) 2016 Bert Vandenbroucke ([email protected])
*
* CMacIonize is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CMacIonize is distributed in the hope that it will be useful,
* but WITOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with CMacIonize. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
/**
* @file testCommandLineParser.cpp
*
* @brief Unit test for the CommandLineParser class.
*
* @author Bert Vandenbroucke ([email protected])
*/
#include "Assert.hpp"
#include "CommandLineOption.hpp"
#include "CommandLineParser.hpp"
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
/**
* @brief Convert a given string of command line options to the argc and argv
* variables passed on to the main function of a program.
*
* The string is split based on spaces. Multiple consecutive spaces are treated
* as a single space. Arguments enclosed within quotation marks are not split;
* they can contain spaces.
*
* @param argc Number of command line arguments found.
* @param argv Command line arguments.
* @param command_line String to parse.
*/
void generate_arguments(int &argc, char **&argv, std::string command_line) {
// parse the arguments and store them in a vector
std::istringstream command_stream(command_line);
std::string argument;
std::vector< std::string > commands;
while (command_stream >> argument) {
if (argument.c_str()[0] == '"') {
argument = argument.substr(1, argument.size());
while (argument.c_str()[argument.size() - 1] != '"') {
std::string argument2;
command_stream >> argument2;
argument += std::string(" ") + argument2;
}
argument = argument.substr(0, argument.size() - 1);
}
commands.push_back(argument);
}
// copy the contents of the vector into the argc and argv variables
// the first entry is the name of the program
argc = commands.size() + 1;
argv = new char *[argc];
argv[0] = new char[1];
for (int_fast32_t i = 0; i < argc - 1; ++i) {
argv[i + 1] = new char[commands[i].size() + 1];
strcpy(argv[i + 1], commands[i].c_str());
}
}
/**
* @brief Free the memory associated with the argv array.
*
* @param argc Number of command line arguments.
* @param argv Command line arguments.
*/
void delete_arguments(int &argc, char **&argv) {
for (int_fast32_t i = 0; i < argc; ++i) {
delete[] argv[i];
}
delete[] argv;
argc = 0;
}
/**
* @brief Unit test for the CommandLineParser class.
*
* @param argc Number of command line arguments.
* @param argv Command line arguments.
* @return Exit code: 0 on success
*/
int main(int argc, char **argv) {
// generate command line arguments
int test_argc;
char **test_argv;
// an example command line input, containing string literals, superfluous
// spaces and various types of options
generate_arguments(test_argc, test_argv,
"--test --more \"andmore\" --less=2.1 -c \"and this?\"");
CommandLineParser parser("testCommandLineParser");
parser.add_option< int_fast32_t >(
"test", 't', "A parameter to test the CommandLineParser.", 42);
parser.add_required_option< std::string >(
"more", 'm', "A parameter taking a string argument.");
parser.add_option< double >(
"less", 'l', "A parameter taking a floating point argument.", 3.14);
parser.add_option< std::string >(
"complicated", 'c',
"A parameter taking a string containing a whitespace character.", "42");
parser.add_option< double >(
"double_default", 'd', "A parameter for which the default value is used.",
3.14);
parser.add_option< bool >(
"bool_default", 'b', "A boolean parameter for which the default is used.",
false);
parser.print_description(std::cout);
parser.parse_arguments(test_argc, test_argv);
assert_condition(parser.get_value< int_fast32_t >("test") == 42);
assert_condition(parser.get_value< std::string >("more") == "andmore");
assert_condition(parser.get_value< double >("less") == 2.1);
assert_condition(parser.get_value< std::string >("complicated") ==
"and this?");
assert_condition(parser.get_value< double >("double_default") == 3.14);
assert_condition(parser.get_value< bool >("bool_default") == false);
parser.print_contents(std::cout);
delete_arguments(test_argc, test_argv);
return 0;
}
| c++ | 15 | 0.64995 | 80 | 33.756944 | 144 | research_code |
static int
StringLastCmd(
ClientData dummy, /* Not used. */
Tcl_Interp *interp, /* Current interpreter. */
int objc, /* Number of arguments. */
Tcl_Obj *const objv[]) /* Argument objects. */
{
Tcl_UniChar *needleStr, *haystackStr, *p;
int match, start, needleLen, haystackLen;
if (objc < 3 || objc > 4) {
Tcl_WrongNumArgs(interp, 1, objv,
"needleString haystackString ?startIndex?");
return TCL_ERROR;
}
/*
* We are searching haystackString for the sequence needleString.
*/
match = -1;
start = 0;
haystackLen = -1;
needleStr = Tcl_GetUnicodeFromObj(objv[1], &needleLen);
haystackStr = Tcl_GetUnicodeFromObj(objv[2], &haystackLen);
if (objc == 4) {
/*
* If a startIndex is specified, we will need to restrict the string
* range to that char index in the string
*/
if (TclGetIntForIndexM(interp, objv[3], haystackLen-1,
&start) != TCL_OK){
return TCL_ERROR;
}
/*
* Reread to prevent shimmering problems.
*/
needleStr = Tcl_GetUnicodeFromObj(objv[1], &needleLen);
haystackStr = Tcl_GetUnicodeFromObj(objv[2], &haystackLen);
if (start < 0) {
goto str_last_done;
} else if (start < haystackLen) {
p = haystackStr + start + 1 - needleLen;
} else {
p = haystackStr + haystackLen - needleLen;
}
} else {
p = haystackStr + haystackLen - needleLen;
}
/*
* If the length of the needle is more than the length of the haystack, it
* cannot be contained in there so we can avoid searching. [Bug 2960021]
*/
if (needleLen > 0 && needleLen <= haystackLen) {
for (; p >= haystackStr; p--) {
/*
* Scan backwards to find the first character.
*/
if ((*p == *needleStr) && !memcmp(needleStr, p,
sizeof(Tcl_UniChar) * (size_t)needleLen)) {
match = p - haystackStr;
break;
}
}
}
str_last_done:
Tcl_SetObjResult(interp, Tcl_NewIntObj(match));
return TCL_OK;
} | c | 16 | 0.619754 | 78 | 23.746835 | 79 | inline |
import random
from collections import deque
import numpy as np
import gym
import torch
from insomnia import models
def main():
seed = 42
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
env = gym.make('CartPole-v0')
dqn = models.dqn.DQN(env, cuda=True) # if use gpu, cuda = False
dqn.target_update()
recent_10_episodes = deque(maxlen=10)
for episode in range(3000):
state = env.reset()
episode_count = 0
for timestep in range(200):
action = dqn.decide_action(torch.tensor(state), episode)
next_state, reward, done, _ = env.step(action)
terminal = 0
episode_count += 1
if done:
terminal = 1
if timestep < 195:
reward = -1
dqn.store_transition(state, action, reward, next_state, terminal)
state = next_state
dqn.model_update()
if done:
recent_10_episodes.append(episode_count+1)
if episode % 10 == 0:
print('epoch:{}, timestep:{}, mean of recent 10 time steps:{}'.format(
episode, timestep, sum(list(recent_10_episodes)) / 10))
break
if sum(list(recent_10_episodes)) / 10 >= 200:
print("Train Completed")
# uncomment when save
# dqn.save_model("PATH")
break
if episode % 10 == 0:
dqn.target_update()
if __name__ == '__main__':
main() | python | 21 | 0.538892 | 90 | 25.783333 | 60 | starcoderdata |
#include
#include
#include
#include "inline.h"
typedef struct {
uint64_t start;
uint64_t stop;
uint64_t elapsed;
} watch_t;
Inline watch_t * watch_create (int nTimer) {
return (watch_t *) malloc (sizeof(watch_t) * nTimer);
}
Inline void watch_destroy (watch_t * timer) {
free (timer);
}
Inline void watch_start (watch_t * timer) {
unsigned a, d;
asm volatile("rdtsc" : "=a" (a), "=d" (d));
timer->start = ((uint64_t)a) | (((uint64_t)d) << 32);
timer->elapsed=0;
}
Inline void watch_stop (watch_t * timer) {
unsigned a, d;
asm volatile("rdtsc" : "=a" (a), "=d" (d));
timer->stop = (((uint64_t)a) | (((uint64_t)d) << 32)) ;
timer->elapsed = timer->elapsed + (timer->stop - timer->start);
}
Inline void watch_pause (watch_t *timer) {
unsigned a, d;
asm volatile("rdtsc" : "=a" (a), "=d" (d));
timer->stop = (((uint64_t)a) | (((uint64_t)d) <<32));
timer->elapsed = timer->elapsed + (timer->stop-timer->start);
timer->start = timer->stop;
}
Inline void watch_restart(watch_t *timer) {
unsigned a, d;
asm volatile("rdtsc" : "=a" (a), "=d" (d));
timer->start = ((uint64_t)a) | (((uint64_t)d) <<32 );
}
Inline void wait_ticks(uint64_t ticks) {
uint64_t current_time;
uint64_t time;
unsigned a, d;
asm volatile("rdtsc" : "=a" (a), "=d" (d));
time = (((uint64_t)a) | (((uint64_t)d) << 32)) ;
time += ticks;
do {
asm volatile("rdtsc" : "=a" (a), "=d" (d));
current_time = (((uint64_t)a) | (((uint64_t)d) << 32)) ;
} while (current_time < time);
} | c | 14 | 0.568678 | 65 | 25.40678 | 59 | starcoderdata |
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Subscriber;
use Brian2694\Toastr\Facades\Toastr;
class SubscriberController extends Controller
{
public function store(Request $request){
$this->validate($request,[
'subscribeEmail' => 'required|email|unique:subscribers', //working unique by using this subscribeEmail name from
// subscribers table. if replace this name , dont work
]);
$subscriber = new Subscriber();
$subscriber->subscribeEmail = $request->subscribeEmail;
$subscriber->save();
Toastr::success('You are Successfully added to our Subscriber list','Subscribe');
return redirect()->back();
}
} | php | 12 | 0.62341 | 126 | 33.173913 | 23 | starcoderdata |
/*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.models.jpa.relationships.manyToMany;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.TableGenerator;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.GenerationType;
import java.util.Collection;
import java.util.HashSet;
@Entity
@Table(name="CMP3_ENTITYC")
public class EntityC
{
private int id;
private String name;
private Collection ds = new HashSet
public EntityC() {
}
@Id
@GeneratedValue(strategy= GenerationType.TABLE, generator="ENTITYC_TABLE_GENERATOR")
@TableGenerator(
name="ENTITYC_TABLE_GENERATOR",
table="CMP3_ENTITYC_SEQ",
pkColumnName="SEQ_NAME",
valueColumnName="SEQ_COUNT",
pkColumnValue="ENTITYC_SEQ"
)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// From what I can see there are no tests against this model (it looks
// like it was built for processing testing actually) therefore,
// no one depends on the cascade setting so I am commenting out the
// @OneToMany annotation to test our defaulting of that annotation.
//@OneToMany(cascade={CascadeType.ALL})
@JoinTable(
name="CMP3_UNIDIR_ENTITYC_ENTITYD",
joinColumns=
@JoinColumn(name="ENTITYC_ID", referencedColumnName="ID"),
inverseJoinColumns=
@JoinColumn(name="ENTITYD_ID", referencedColumnName="ID")
)
public Collection getDs() {
return ds;
}
public void setDs(Collection ds) {
this.ds = ds;
}
} | java | 12 | 0.628843 | 88 | 32.1625 | 80 | starcoderdata |
package nl.utwente.sekhmet.jpa.service;
import nl.utwente.sekhmet.api.StringChecker;
import nl.utwente.sekhmet.jpa.model.Conversation;
import nl.utwente.sekhmet.jpa.model.Message;
import nl.utwente.sekhmet.jpa.model.Test;
import nl.utwente.sekhmet.jpa.model.User;
import nl.utwente.sekhmet.jpa.repositories.ConversationRepository;
import nl.utwente.sekhmet.jpa.repositories.MessageRepository;
import org.json.JSONArray;
import nl.utwente.sekhmet.jpa.repositories.UserRepository;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
public class MessageService {
//POST-create
public static void postMessage(String jsonMessage, UserRepository userRepository, ConversationRepository conversationRepository, MessageRepository messageRepository)
throws JSONException, NumberFormatException, NoSuchElementException {
String jsonMessageAfter = StringChecker.escapeString(jsonMessage);
JSONObject json = new JSONObject(jsonMessageAfter);
JSONArray ja = null;
if (json.has("messages")) {
ja = json.getJSONArray("messages");
messageRepository.saveAll(MessageService.postMessage(ja, userRepository, conversationRepository));
} else {
messageRepository.save(MessageService.postMessage(json, null, null, userRepository, conversationRepository));
}
}
/*
* postMessage can be called with User AND Conversation,
* Only User (c == null),
* Only Conversation (user == null),
* Or neither (user & c == null)
*/
public static Message postMessage(JSONObject jo, User user, Conversation c, UserRepository userRepository, ConversationRepository conversationRepository)
throws JSONException, NumberFormatException, NoSuchElementException {
User tempUser = user;
if (user == null) {
tempUser = UserService.getUser(jo.getLong("sender_id"), userRepository);
}
Conversation tempConversation = c;
if (c == null) {
tempConversation = ConversationService.getConversationById(jo.getLong("chat_id"), conversationRepository);
}
Long mid = jo.getLong("message_id");
Long timestamp = jo.getLong("timestamp");
String content = jo.getString("content");
Message message = new Message(mid, timestamp, tempUser, tempConversation, content);
return message;
}
public static List postMessage(JSONArray jo, UserRepository userRepository, ConversationRepository conversationRepository)
throws JSONException, NumberFormatException, NoSuchElementException {
int len = jo.length();
List res = new ArrayList<>();
Map<Long, User> prevUsers = new HashMap<>();
Map<Long, Conversation> prevConversations = new HashMap<>();
for (int i = 0; i < len; i ++) {
JSONObject temp = jo.getJSONObject(i);
Long pid = temp.getLong("sender_id");
User tu = prevUsers.get(pid);
if (tu == null) {
tu = UserService.getUser(pid, userRepository);
prevUsers.put(pid, tu);
}
Long cid = temp.getLong("chat_id");
Conversation tc = prevConversations.get(cid);
if (tc == null) {
tc = ConversationService.getConversationById(cid, conversationRepository);
prevConversations.put(cid, tc);
}
res.add(MessageService.postMessage(temp, tu, tc, userRepository, conversationRepository));
}
return res;
}
//GET-retrieve
public static Message getMessage(Long id, MessageRepository messageRepository){
return messageRepository.findById(id).get();
}
public static List getMessageByConversation(Conversation conversation, MessageRepository messageRepository) {
List messageList = messageRepository.findMessageByMessageId_ConversationId(conversation.getId());
return messageList;
}
public static List getMessageByTest(Test test, MessageRepository messageRepository) {
List mesList = messageRepository.findMessagesByConversationTest(test);
return mesList;
}
//PUT-update
public static void putMessage(Long mid, MessageRepository messageRepository){
}
//DELETE
public static void deleteMessage(Message message, MessageRepository messageRepository){
messageRepository.delete(message);
}
} | java | 12 | 0.69015 | 169 | 41.192661 | 109 | starcoderdata |
const removeDeclaration = (astRoot) => {
if (typeof astRoot === 'object') {
const rules = astRoot.stylesheet.rules
rules.forEach((rule) => {
if (rule.type === 'rule') {
rule.declarations.forEach(() => {
rule.removeDeclaration = function (index) {
rule.declarations.splice(index, 1)
}
})
}
})
}
}
module.exports = removeDeclaration | javascript | 27 | 0.469979 | 63 | 29.25 | 16 | starcoderdata |
#pragma once
#include
#include
#include "IncludeDeps.hpp"
#include "Core/Vulkan/Vk.hpp"
#include "Core/Vulkan/VulkanInstance.hpp"
#include "Core/Vulkan/CommandBufferPool.hpp"
#include "Core/Object.hpp"
#include VULKAN_INCLUDE
#include STB_INCLUDE_IMAGE
#include GLM_INCLUDE
namespace LWGC
{
class Texture : public Object
{
protected:
int width;
int height;
int depth;
int arraySize;
VkFormat format;
bool autoGenerateMips;
int usage;
bool allocated;
int maxMipLevel;
VkImage image;
VkDeviceMemory memory;
VkImageView view;
VulkanInstance * instance;
VkDevice device;
CommandBufferPool * graphicCommandBufferPool;
VkImageLayout layout;
void AllocateImage(VkImageViewType viewType);
void UploadImage(stbi_uc * pixels, VkDeviceSize deviceSize, glm::ivec3 imageSize, glm::ivec3 offset = {0, 0, 0});
void UploadImageWithMips(VkImage image, VkFormat format, void * pixels, VkDeviceSize deviceSize, glm::ivec3 imageSize, glm::ivec3 offset = {0, 0, 0});
void TransitionImageLayout(VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout);
void TransitionImageLayout(VkCommandBuffer cmd, VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout);
stbi_uc * LoadFromFile(const std::string & fileName, int & width, int & height);
void GenerateMipMaps(VkImage image, VkFormat format, int32_t width, int32_t height);
public:
Texture(void);
Texture(const Texture&);
virtual ~Texture(void);
virtual Texture & operator=(Texture const & src);
int GetWidth(void) const noexcept;
int GetHeight(void) const noexcept;
int GetDepth(void) const noexcept;
int GetArraySize(void) const noexcept;
VkImageView GetView(void) const noexcept;
VkImage GetImage(void) const noexcept;
bool GetAutoGenerateMips(void) const noexcept;
void ChangeLayout(VkCommandBuffer cmd, VkImageLayout targetLayout);
void ChangeLayout(VkImageLayout targetLayout);
VkImageLayout GetLayout(void) const noexcept;
void Destroy(void) noexcept;
};
std::ostream & operator<<(std::ostream & o, Texture const & r);
} | c++ | 11 | 0.721163 | 155 | 31.865672 | 67 | starcoderdata |
// Created by on 30-01-17.
// Copyright © 2017 Bohemian Coding.
#import "SCKObject.h"
@class SCKShareVersion;
@class SCKUser;
/// A Cloud share for a Sketch document.
NS_SWIFT_NAME(Share)
@interface SCKShare : SCKObject
/// The shortID that's used within the public URL to represent this share.
@property (nonatomic, nullable, readonly) NSString *shortID;
/// The URL that the user can visit with the browser to view the share.
@property (nonatomic, nullable, readonly) NSURL *publicURL;
/// Whether the share requires a password to be shown for unauthorized users.
@property (nonatomic, readonly) BOOL isPrivate;
/// The latest share revision.
@property (nonatomic, nullable, readonly) SCKShareVersion *currentVersion;
/// Whether the current user has permissions to update the share.
@property (nonatomic, assign, readonly) BOOL canUpdate;
/// A copy of the receiver, but by changing the canUpdate property to 'NO'.
- (nonnull instancetype)readOnlyCopy;
/// The user that owns this share, usually the one that originally created it.
@property (nonatomic, nullable, readonly) SCKUser *owner;
@end | c | 6 | 0.754245 | 78 | 31.911765 | 34 | starcoderdata |
<?php
namespace GSoares\CweTop25;
use Symfony\Component\HttpFoundation\Request;
abstract class AbstractSample implements SampleInterface
{
/**
* @var Request
*/
private $request;
/**
* @param Request $request
* @return array
*/
public function processRequest(Request $request)
{
$this->request = $request;
return $this->internalProcess();
}
/**
* @return array
*/
public function getFileContent()
{
$classPath = str_replace(['GSoares\CweTop25\\', '\\'], ['', '/'], get_called_class());
return file_get_contents(__DIR__ . "/$classPath.php");
}
/**
* @return array
*/
abstract protected function internalProcess();
/**
* @param $parameter
* @return string
*/
protected function getRequestParameter($parameter)
{
return $this->request->get($parameter);
}
/**
* @return bool
*/
protected function isPost()
{
return $this->request->getMethod() == 'POST';
}
/**
* @return bool
*/
protected function isSafeSubmit()
{
return $this->request->get('submit') == 'Safe submit';
}
/**
* @return bool
*/
protected function isUnSafeSubmit()
{
return $this->request->get('submit') == 'Unsafe submit';
}
} | php | 13 | 0.547915 | 94 | 17.726027 | 73 | starcoderdata |
define(["exports", "./index-61bbd0a6.js"], function (_exports, _index61bbd0a) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.defineCustomElements = void 0;
/*
Stencil Client Patch Esm v2.11.0 | MIT Licensed | https://stenciljs.com
*/
var patchEsm = function patchEsm() {
return (0, _index61bbd0a.p)();
};
var defineCustomElements = function defineCustomElements(win, options) {
if (typeof window === 'undefined') return Promise.resolve();
return patchEsm().then(function () {
return (0, _index61bbd0a.b)([["web-social-share", [[1, "web-social-share", {
"show": [1028],
"share": [16]
}]]]], options);
});
};
_exports.defineCustomElements = defineCustomElements;
}); | javascript | 26 | 0.624531 | 82 | 27.571429 | 28 | starcoderdata |
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 io.gravitee.am.gateway.handler.oauth2.service.request;
import io.gravitee.am.gateway.handler.oauth2.exception.InvalidScopeException;
import io.gravitee.am.model.Client;
import io.gravitee.am.model.Role;
import io.gravitee.am.model.User;
import io.reactivex.observers.TestObserver;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
/**
* @author (titouan.compiegne at graviteesource.com)
* @author GraviteeSource Team
*/
public class AuthorizationRequestResolverTest {
private final AuthorizationRequestResolver authorizationRequestResolver = new AuthorizationRequestResolver();
@Test
public void shouldNotResolveAuthorizationRequest_unknownScope() {
final String scope = "read";
final String redirectUri = "http://localhost:8080/callback";
AuthorizationRequest authorizationRequest = new AuthorizationRequest();
authorizationRequest.setScopes(Collections.singleton(scope));
authorizationRequest.setRedirectUri(redirectUri);
Client client = new Client();
TestObserver testObserver = authorizationRequestResolver.resolve(authorizationRequest, client, null).test();
testObserver.assertNotComplete();
testObserver.assertError(InvalidScopeException.class);
}
@Test
public void shouldResolveAuthorizationRequest_emptyScope() {
final String redirectUri = "http://localhost:8080/callback";
AuthorizationRequest authorizationRequest = new AuthorizationRequest();
authorizationRequest.setRedirectUri(redirectUri);
Client client = new Client();
TestObserver testObserver = authorizationRequestResolver.resolve(authorizationRequest, client, null).test();
testObserver.assertComplete();
testObserver.assertNoErrors();
}
@Test
public void shouldResolveAuthorizationRequest_noRequestedScope() {
final String scope = "read";
final String redirectUri = "http://localhost:8080/callback";
AuthorizationRequest authorizationRequest = new AuthorizationRequest();
authorizationRequest.setRedirectUri(redirectUri);
Client client = new Client();
client.setScopes(Collections.singletonList(scope));
TestObserver testObserver = authorizationRequestResolver.resolve(authorizationRequest, client, null).test();
testObserver.assertComplete();
testObserver.assertNoErrors();
testObserver.assertValue(request -> request.getScopes().iterator().next().equals(scope));
}
@Test
public void shouldResolveAuthorizationRequest_invalidScope() {
final String scope = "read";
final String redirectUri = "http://localhost:8080/callback";
AuthorizationRequest authorizationRequest = new AuthorizationRequest();
authorizationRequest.setScopes(Collections.singleton(scope));
authorizationRequest.setRedirectUri(redirectUri);
Client client = new Client();
client.setScopes(Collections.singletonList("write"));
TestObserver testObserver = authorizationRequestResolver.resolve(authorizationRequest, client, null).test();
testObserver.assertNotComplete();
testObserver.assertError(InvalidScopeException.class);
}
@Test
public void shouldResolveAuthorizationRequest_invalidScope_withUser() {
final String scope = "read";
final String redirectUri = "http://localhost:8080/callback";
AuthorizationRequest authorizationRequest = new AuthorizationRequest();
authorizationRequest.setScopes(Collections.singleton(scope));
authorizationRequest.setRedirectUri(redirectUri);
Client client = new Client();
client.setScopes(Collections.singletonList("write"));
User user = new User();
Role role = new Role();
role.setPermissions(Collections.singletonList("user"));
user.setRolesPermissions(Collections.singleton(role));
TestObserver testObserver = authorizationRequestResolver.resolve(authorizationRequest, client, user).test();
testObserver.assertNotComplete();
testObserver.assertError(InvalidScopeException.class);
}
@Test
public void shouldResolveAuthorizationRequest_userPermissions() {
final String scope = "read";
final String userScope = "user";
final String redirectUri = "http://localhost:8080/callback";
AuthorizationRequest authorizationRequest = new AuthorizationRequest();
authorizationRequest.setRedirectUri(redirectUri);
authorizationRequest.setScopes(new HashSet<>(Arrays.asList(scope, userScope)));
Client client = new Client();
client.setScopes(Collections.singletonList(scope));
client.setEnhanceScopesWithUserPermissions(true);
User user = new User();
Role role = new Role();
role.setPermissions(Collections.singletonList(userScope));
user.setRolesPermissions(Collections.singleton(role));
TestObserver testObserver = authorizationRequestResolver.resolve(authorizationRequest, client, user).test();
testObserver.assertComplete();
testObserver.assertNoErrors();
}
} | java | 14 | 0.732408 | 138 | 43.318519 | 135 | starcoderdata |
// load google map and enable drawing a polygon
var map, infoWindow, drawingManager;
var selectedPolygon, selectedPolygonCoordinates, polygonGeoJson = {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: []
},
properties: {}
};
function showMap() {
map = new google.maps.Map(document.getElementById('map'), {
center : {
lat : 6.8663995510754265,
lng : 79.87099776560672
},
zoom : 15,
// mapTypeId: 'terrain',
});
enablePolygonDrawing(map);
}
function enablePolygonDrawing(map) {
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode : google.maps.drawing.OverlayType.POLYGON,
drawingControl : true,
drawingControlOptions : {
position : google.maps.ControlPosition.TOP_CENTER,
drawingModes : [ google.maps.drawing.OverlayType.POLYGON ]
},
// markerOptions: {icon:
// 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'},
polygonOptions : {
// clickable: false,
editable : true,
zIndex : 1,
strokeWeight: 0,
fillOpacity: 0.45,
draggable: true,
}
});
drawingManager.setMap(map);
var onPolygonComplete = google.maps.event.addListener(drawingManager,
'polygoncomplete', function(polygon) {
selectedPolygonCoordinates = polygon.getPath().getArray();
createGeoJSON(selectedPolygonCoordinates);
// let polygonEncoded =
// google.maps.geometry.encoding.encodePath(polygon.getPath())
// let polygonDecoded =
// google.maps.geometry.encoding.decodePath(polygonEncoded)
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
// Switch back to non-drawing mode after drawing a shape.
//drawingManager.setDrawingMode(null);
drawingManager.setOptions({
// drawingControl: false
});
//selectedPolygon = null;
if (e.type == 'polygon') {
selectedPolygon = e.overlay;
selectedPolygon.type = e.type;
}
});
return drawingManager;
}
function clearPolygonSelection(){
if (selectedPolygon) {
selectedPolygon.setEditable(false);
selectedPolygon.setMap(null);
selectedPolygon = null;
//map.data.remove(map.data.getFeatureById(selectedPolygon.feature.getId()));
$( "#geometry" ).empty();
}
}
function createGeoJSON(polygonCoordinates){
let disp='',lng, lat;
polygonGeoJson.geometry.coordinates = [];
for (let point of polygonCoordinates) {
lng=parseFloat(point.lng());
lat=parseFloat(point.lat());
//polygonGeoJson.geometry.coordinates.push([point.lng(), point.lat()]);
polygonGeoJson.geometry.coordinates.push([lng, lat]);
disp = disp.concat(' Longitude: '+point.lng()+' Lattitude: '+point.lat()+'
}
$('#geometry').append('
// return polygonGeoJson
}
function setCurrentPosition() {
// default position
var defaultPos = {
lat : 6.8663995510754265,
lng : 79.87099776560672
};
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat : position.coords.latitude,
lng : position.coords.longitude
};
map.setCenter(pos);
}, function() {
map.setCenter(defaultPos);
// handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
// handleLocationError(false, infoWindow, map.getCenter());
map.setCenter(defaultPos);
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow
.setContent(browserHasGeolocation ? 'Error: The Geolocation service failed.'
: 'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
} | javascript | 16 | 0.670656 | 103 | 23.176101 | 159 | starcoderdata |
/************************************************************************
* Source filename: AccessControl.java
*
* Creation date: Sep 6, 2013
*
* Author: zhengg
*
* Project: WDE
*
* Objective:
*
* Developer's notes:
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
***********************************************************************/
package wde.security;
import org.apache.catalina.realm.GenericPrincipal;
import javax.servlet.http.HttpServletRequest;
public class AccessControl {
public static boolean isSuperUser(HttpServletRequest request) {
return hasRole(request, "wde_admin");
}
public static boolean hasRole(HttpServletRequest request, String role) {
boolean flag = false;
GenericPrincipal principal = (GenericPrincipal) request.getUserPrincipal();
if (principal != null) {
String[] roles = principal.getRoles();
for (String arole : roles)
if (arole.equals(role)) {
flag = true;
break;
}
}
return flag;
}
} | java | 12 | 0.537563 | 83 | 26.227273 | 44 | starcoderdata |
uint16_t CRCCCITT(uint8_t *data, uint32_t length) {
uint32_t count;
uint32_t crc = CRC_SEED;
uint32_t temp;
if (!data) {
COM_ASSERT(0);
return COM_NULL_POINTER; // Technically not a valid return
}
for (count = 0; count < length; ++count) {
temp = (*data++ ^ (crc >> 8)) & 0xff;
crc = crc_table[temp] ^ (crc << 8);
}
return (uint16_t)(crc ^ CRC_FINAL);
} | c++ | 12 | 0.602151 | 60 | 20.941176 | 17 | inline |
using System.Reflection;
using NUnit.Framework;
namespace Unity.MeshSync.Editor.Tests {
public class PropertyExistenceTests {
//----------------------------------------------------------------------------------------------------------------------
[Test]
public void CheckSceneCacheImporterProperties() {
VerifyMemberExists(typeof(SceneCacheImporter), SceneCacheImporter.IMPORTER_SETTINGS_PROP);
}
[Test]
public void CheckModelImporterSettingsProperties() {
VerifyMemberExists(typeof(ModelImporterSettings), ModelImporterSettings.CREATE_MATERIALS_PROP);
VerifyMemberExists(typeof(ModelImporterSettings), ModelImporterSettings.MATERIAL_SEARCH_MODE_PROP);
}
static void VerifyMemberExists(System.Type type, string memberName) {
MemberInfo[] m = type.GetMember(memberName, BindingFlags.NonPublic | BindingFlags.Instance);
Assert.Greater(m.Length, 0);
Assert.IsNotNull(m[0]);
}
}
} //end namespace | c# | 16 | 0.620388 | 120 | 31.290323 | 31 | starcoderdata |
using System;
namespace Brew.Patterns;
public class Singleton : IBrew
{
public void Before()
{
Person person1 = new Person();
person1.Speak();
person1 = new Person();
person1.Speak();
}
public void After()
{
SingletonPerson person = SingletonPerson.Me;
person.Speak();
person = SingletonPerson.Me; // Grab same single instance
person.Speak(); // will be same age as first one
}
public class Person
{
public DateTime Age { get; } = DateTime.Now;
public Person()
{
}
public void Speak()
{
Console.WriteLine($"Born: {Age}");
}
}
public class SingletonPerson : Person
{
private static SingletonPerson? _me;
public static SingletonPerson Me => _me ??= new SingletonPerson();
// Cannot create
private SingletonPerson()
{
}
}
} | c# | 14 | 0.539896 | 74 | 16.87037 | 54 | starcoderdata |
package com.donnarumma.ciro.volumecontrol.utils;
/**
* Questa interfaccia contiene le costanti utilizzate per accedere alle Shared Preferences.
*/
public interface SharedPreferencesName {
//Nome delle preferenze
final static String SHARED_PREFERENCES_NAME = "volume_control_preferences";
//Chiavi identificative delle preferenze
final static String KEY_MINIMUM_VOLUME = "minimum_volume";
final static String KEY_MAXIMUM_VOLUME = "maximum_volume";
final static String KEY_TRIGGER_INTERVAL = "trigger_interval";
final static String KEY_ADJUSTING_VOLUME = "adjusting_volume";
final static String KEY_FLASH_BLINKING = "flash_blinking";
//Valori di default delle preferenze
final static int DEFAULT_MINIMUM_VOLUME = 0;
final static int DEFAULT_MAXIMUM_VOLUME = 7;
final static int DEFAULT_TRIGGER_INTERVAL = 5;
final static boolean DEFAULT_ADJUSTING_VOLUME = false;
final static boolean DEFAULT_FLASH_BLINKING = false;
//final static String KEY_SAMPLING_PERIOD = "sampling_period"; //TODO: Controllare
// final static int DEFAULT_SAMPLING_PERIOD = 500;
} | java | 6 | 0.785179 | 120 | 37.741935 | 31 | starcoderdata |
// @flow
const buildCDNUrl = (path: string) => `https://static.odycdn.com/stickers/${path}`;
const buildSticker = (name: string, path: string, price?: number) => ({
name: `:${name}:`,
url: buildCDNUrl(path),
price: price,
});
const CAT_BORDER = 'CAT/PNG/cat_with_border.png';
const FAIL_BORDER = 'FAIL/PNG/fail_with_border.png';
const HYPE_BORDER = 'HYPE/PNG/hype_with_border.png';
const PANTS_1_WITH_FRAME = 'PANTS/PNG/PANTS_1_with_frame.png';
const PISS = 'PISS/PNG/piss_with_frame.png';
const PREGNANT_MAN_BLONDE_WHITE_BORDER = 'pregnant%20man/png/Pregnant%20man_white%20border_blondie.png';
const PREGNANT_WOMAN_BROWN_HAIR_WHITE_BORDER = 'pregnant%20woman/png/Pregnant%20woman_white_border_brown%20hair.png';
const ROCKET_SPACEMAN_WITH_BORDER = 'ROCKET%20SPACEMAN/PNG/rocket-spaceman_with-border.png';
const SALTY = 'SALTY/PNG/salty.png';
const SICK_2_WITH_BORDER = 'SICK/PNG/sick2_with_border.png';
const SICK_1_WITH_BORDERDARK_WITH_FRAME = 'SICK/PNG/with%20borderdark%20with%20frame.png';
const SLIME_WITH_FRAME = 'SLIME/PNG/slime_with_frame.png';
const FIRE_WITH_FRAME = 'MISC/PNG/fire.png';
const SPHAGETTI_BATH_WITH_FRAME = 'SPHAGETTI%20BATH/PNG/sphagetti%20bath_with_frame.png';
const THUG_LIFE_WITH_BORDER = 'THUG%20LIFE/PNG/thug_life_with_border_clean.png';
const WHUUT_WITH_FRAME = 'WHUUT/PNG/whuut_with-frame.png';
const EGIRL = 'EGIRL/PNG/e-girl.png';
const BULL_RIDE = 'BULL/PNG/bull-ride.png';
const TRAP = 'TRAP/PNG/trap.png';
// const XMAS = 'SEASONAL/PNG/xmas.png';
const ELIMINATED = 'ELIMINATED/PNG/eliminated.png';
const TRASH = 'TRASH/PNG/trash.png';
const BAN = 'BAN/PNG/ban.png';
const KANYE_WEST = 'MISC/PNG/kanye_west.png';
const CHE_GUEVARA = 'MISC/PNG/che_guevara.png';
const BILL_COSBY = 'MISC/PNG/bill_cosby.png';
const KURT_COBAIN = 'MISC/PNG/kurt_cobain.png';
const BILL_CLINTON = 'MISC/PNG/bill_clinton.png';
const CHRIS_CHAN = 'MISC/PNG/chris_chan.png';
const TAYLOR_SWIFT = 'MISC/PNG/taylor_swift.png';
const EPSTEIN_ISLAND = 'MISC/PNG/epstein_island.png';
const DONALD_TRUMP = 'MISC/PNG/donald_trump.png';
const EGG_CARTON = 'MISC/PNG/egg_carton.png';
const MOUNT_RUSHMORE = 'MISC/PNG/mount_rushmore.png';
const MONEY_PRINTER = 'MISC/PNG/money_printer.png';
const COMET_TIP = 'TIPS/png/$%20comet%20tip%20with%20border.png';
const BIG_LBC_TIP = 'TIPS/png/big_LBC_TIPV.png';
const BIG_TIP = 'TIPS/png/with%20borderbig$tip.png';
const BITE_TIP = 'TIPS/png/bite_$tip_with%20border.png';
const BITE_TIP_CLOSEUP = 'TIPS/png/bite_$tip_closeup.png';
const FORTUNE_CHEST_LBC = 'TIPS/png/with%20borderfortunechest_LBC_tip.png';
const FORTUNE_CHEST = 'TIPS/png/with%20borderfortunechest$_tip.png';
const LARGE_LBC_TIP = 'TIPS/png/with%20borderlarge_LBC_tip%20.png';
const LARGE_TIP = 'TIPS/png/with%20borderlarge$tip.png';
const BITE_LBC_CLOSEUP = 'TIPS/png/LBC%20bite.png';
const LBC_COMET_TIP = 'TIPS/png/LBC%20comet%20tip%20with%20border.png';
const MEDIUM_LBC_TIP = 'TIPS/png/with%20bordermedium_LBC_tip%20%20%20%20%20%20%20%20%20%20.png';
const MEDIUM_TIP = 'TIPS/png/with%20bordermedium$_%20tip.png';
const SILVER_ODYSEE_COIN = 'TIPS/png/with%20bordersilver_odysee_coinv.png';
const SMALL_LBC_TIP = 'TIPS/png/with%20bordersmall_LBC_tip%20.png';
const SMALL_TIP = 'TIPS/png/with%20bordersmall$_tip.png';
const TIP_HAND_FLIP = 'TIPS/png/tip_hand_flip_$%20_with_border.png';
const TIP_HAND_FLIP_COIN = 'TIPS/png/tip_hand_flip_coin_with_border.png';
const TIP_HAND_FLIP_LBC = 'TIPS/png/tip_hand_flip_lbc_with_border.png';
const DOGE = 'MISC/PNG/doge.png';
const TWITCH = 'MISC/PNG/twitch.png';
export const FREE_GLOBAL_STICKERS = [
buildSticker('CAT', CAT_BORDER),
buildSticker('FAIL', FAIL_BORDER),
buildSticker('HYPE', HYPE_BORDER),
buildSticker('PANTS_1', PANTS_1_WITH_FRAME),
buildSticker('DOGE', DOGE),
// buildSticker('XMAS', XMAS),
buildSticker('FIRE', FIRE_WITH_FRAME),
buildSticker('SLIME', SLIME_WITH_FRAME),
buildSticker('PISS', PISS),
buildSticker('TWITCH', TWITCH),
buildSticker('BULL_RIDE', BULL_RIDE),
buildSticker('ELIMINATED', ELIMINATED),
buildSticker('EGG_CARTON', EGG_CARTON),
buildSticker('BAN', BAN),
buildSticker('MONEY_PRINTER', MONEY_PRINTER),
buildSticker('MOUNT_RUSHMORE', MOUNT_RUSHMORE),
buildSticker('EGIRL', EGIRL),
buildSticker('KANYE_WEST', KANYE_WEST),
buildSticker('TAYLOR_SWIFT', TAYLOR_SWIFT),
buildSticker('DONALD_TRUMP', DONALD_TRUMP),
buildSticker('BILL_CLINTON', BILL_CLINTON),
buildSticker('EPSTEIN_ISLAND', EPSTEIN_ISLAND),
buildSticker('KURT_COBAIN', KURT_COBAIN),
buildSticker('BILL_COSBY', BILL_COSBY),
buildSticker('CHE_GUEVARA', CHE_GUEVARA),
buildSticker('CHRIS_CHAN', CHRIS_CHAN),
buildSticker('PREGNANT_MAN_BLONDE', PREGNANT_MAN_BLONDE_WHITE_BORDER),
buildSticker('PREGNANT_WOMAN_BROWN_HAIR', PREGNANT_WOMAN_BROWN_HAIR_WHITE_BORDER),
buildSticker('ROCKET_SPACEMAN', ROCKET_SPACEMAN_WITH_BORDER),
buildSticker('SALTY', SALTY),
buildSticker('SICK_FLAME', SICK_2_WITH_BORDER),
buildSticker('SICK_SKULL', SICK_1_WITH_BORDERDARK_WITH_FRAME),
buildSticker('SPHAGETTI_BATH', SPHAGETTI_BATH_WITH_FRAME),
buildSticker('THUG_LIFE', THUG_LIFE_WITH_BORDER),
buildSticker('TRAP', TRAP),
buildSticker('TRASH', TRASH),
buildSticker('WHUUT', WHUUT_WITH_FRAME),
];
export const PAID_GLOBAL_STICKERS = [
buildSticker('TIP_HAND_FLIP', TIP_HAND_FLIP, 1),
buildSticker('TIP_HAND_FLIP_COIN', TIP_HAND_FLIP_COIN, 1),
buildSticker('TIP_HAND_FLIP_LBC', TIP_HAND_FLIP_LBC, 1),
buildSticker('COMET_TIP', COMET_TIP, 5),
buildSticker('SILVER_ODYSEE_COIN', SILVER_ODYSEE_COIN, 5),
buildSticker('LBC_COMET_TIP', LBC_COMET_TIP, 25),
buildSticker('SMALL_TIP', SMALL_TIP, 25),
buildSticker('SMALL_LBC_TIP', SMALL_LBC_TIP, 25),
buildSticker('BITE_TIP', BITE_TIP, 50),
buildSticker('BITE_TIP_CLOSEUP', BITE_TIP_CLOSEUP, 50),
buildSticker('BITE_LBC_CLOSEUP', BITE_LBC_CLOSEUP, 50),
buildSticker('MEDIUM_TIP', MEDIUM_TIP, 50),
buildSticker('MEDIUM_LBC_TIP', MEDIUM_LBC_TIP, 50),
buildSticker('LARGE_TIP', LARGE_TIP, 100),
buildSticker('LARGE_LBC_TIP', LARGE_LBC_TIP, 100),
buildSticker('BIG_TIP', BIG_TIP, 150),
buildSticker('BIG_LBC_TIP', BIG_LBC_TIP, 150),
buildSticker('FORTUNE_CHEST', FORTUNE_CHEST, 200),
buildSticker('FORTUNE_CHEST_LBC', FORTUNE_CHEST_LBC, 200),
]; | javascript | 9 | 0.728174 | 117 | 47.48062 | 129 | starcoderdata |
package com.dev.user.dao;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.dev.base.enums.MsgType;
import com.dev.base.enums.UserRole;
import com.dev.base.mybatis.dao.BaseMybatisDao;
import com.dev.base.util.Pager;
import com.dev.user.entity.UserMsg;
/**
*
* 用户消息
* 描述(简要描述类的职责、实现方式、使用注意事项等)
* 2015年9月30日下午3:30:20
*/
public interface UserMsgDao extends BaseMybatisDao {
/**
*
*@name 查询用户消息列表
*@Description
*@CreateDate 2015年9月12日上午11:33:40
*/
List listByUserId(@Param("userId")Long userId,@Param("title")String title,@Param("msgType")MsgType msgType,
@Param("sys")Boolean sys,@Param("deal")Boolean deal,@Param("pager")Pager pager);
/**
*
*@name 查询用户消息总数
*@Description
*@CreateDate 2015年9月12日上午11:41:56
*/
int countByUserId(@Param("userId")Long userId,@Param("title")String title,@Param("msgType")MsgType msgType,
@Param("sys")Boolean sys,@Param("deal")Boolean deal);
/**
*
*@name 获取最新的系统消息插入到用户消息中
*@Description
*@CreateDate 2015年10月19日下午4:33:16
*/
void fetchSysMsg(@Param("userId")Long userId,@Param("userRole")UserRole userRole,
@Param("lastFetchDate")Date lastFetchDate);
/**
*
*@name 获取未读消息数目
*@Description
*@CreateDate 2015年10月19日下午5:48:35
*/
int countUnread(@Param("userId")Long userId);
/**
*
*@name 设置消息已读
*@Description
*@CreateDate 2015年10月19日下午5:49:36
*/
void setReadByUserId(@Param("userId")Long userId,@Param("msgId")Long msgId);
/**
*
*@name 删除消息
*@Description
*@CreateDate 2015年10月19日下午5:50:04
*/
void delByUserId(@Param("userId")Long userId,@Param("msgId")Long msgId);
} | java | 10 | 0.685259 | 117 | 23.746479 | 71 | starcoderdata |
const { getFunctionSigs } = require("./contracts");
module.exports = {
noSelectorClashes(prism, implementation) {
let prismSigs = getFunctionSigs(prism.interface);
let impSigs = getFunctionSigs(implementation.interface);
let noClashes = true;
for (const impSig of impSigs) {
for (const prismSig of prismSigs) {
if (impSig.sig == prismSig.sig) {
noClashes = false;
console.log("Function: " + impSig.name + " in implementation contract clashes with " + prismSig.name + " in prism contract (signature: " + impSig.sig + ")");
console.log("Change function name and/or params for " + impSig.name);
}
}
}
return noClashes;
}
} | javascript | 19 | 0.578692 | 177 | 40.35 | 20 | starcoderdata |
from websocket import create_connection
import urllib.request
import inspect
import json
import responses
from responses import *
import sys
# Check to make sure we're in Python 3!
if ( sys.version_info < (3,0) ):
print("You must be using Python 3!")
exit()
# Setup URLs
urls = {
"auth" : "https://slack.com/api/rtm.start",
"socket" : "",
}
# Slack Access Token (https://api.slack.com/bot-users)
token = "<your token here>"
# Get the websocket URL
print("Connecting to Slack...")
response = ""
url = "%s?token=%s" % (urls['auth'], token)
with urllib.request.urlopen( url ) as req:
response = req.read()
slackinfo = json.loads( (response.decode('utf-8')) )
# Check that the response has been received
if ( not slackinfo['ok'] ):
print("Request to Slack Failed.")
print("Error: %s" % slackinfo['error'])
exit()
else:
print("Connection to Slack Successful")
# Store the important things from slack info object
urls['socket'] = slackinfo['url']
# Open the websocket to slack
print("Opening connection to Slack Websocket Engine...")
socket = create_connection(urls['socket'])
run = True
print("Monitoring...")
# Load all the response modules
responseClasses = []
for moduleName in responses.__all__:
for name, obj in inspect.getmembers(sys.modules["responses." + moduleName]):
if name == moduleName and inspect.isclass(obj):
responseClasses.append(obj(socket, slackinfo))
# Listen on the websocket
try:
while run:
result = socket.recv()
jsonresult = json.loads(result)
if "reply_to" in jsonresult: print("Received Message Confirmation (#%s)" % jsonresult['reply_to'])
if "type" in jsonresult: print("Received %s" % str(jsonresult['type']))
# Start up response modules
for responseClass in responseClasses:
if len(responseClass.accept) == 0 or len([x for x in responseClass.accept if x.upper() == jsonresult['type'].upper()]) > 0:
if "type" in jsonresult:
responseClass.receive_message(jsonresult)
except KeyboardInterrupt as interrupt:
print("")
print("Stopping Server...")
socket.close() | python | 19 | 0.703793 | 126 | 25.367089 | 79 | starcoderdata |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using BenchmarkDotNet.Attributes;
using Microsoft.Extensions.DependencyInjection;
using MicroBenchmarks;
namespace Microsoft.Extensions.Logging
{
[BenchmarkCategory(Categories.Libraries)]
public class FormattingOverhead : LoggingBenchmarkBase
{
private ILogger _logger;
[GlobalSetup]
public void Setup()
{
var services = new ServiceCollection();
services.AddLogging();
services.AddSingleton<ILoggerProvider, LoggerProvider
_logger = services.BuildServiceProvider().GetService
}
[Benchmark]
public void TwoArguments_DefineMessage()
{
TwoArgumentErrorMessage(_logger, 1, "string", Exception);
}
[Benchmark]
public void FourArguments_DefineMessage()
{
FourArgumentErrorMessage(_logger, 1, "string", 2, "string", Exception);
}
[Benchmark]
public void NoArguments()
{
_logger.LogError(Exception, "Message");
}
[Benchmark]
public void TwoArguments()
{
_logger.LogError(Exception, "Message {Argument1} {Argument2}", 1, "string");
}
[Benchmark]
public void FourArguments_EnumerableArgument()
{
_logger.LogError(Exception, "Message {Argument1} {Argument2} {Argument3} {Argument4}", 1, "string", new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 1);
}
}
} | c# | 15 | 0.620392 | 156 | 30.563636 | 55 | starcoderdata |
package com.lantanagroup.link.config.api;
import com.lantanagroup.link.config.YamlPropertySourceFactory;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotNull;
import java.util.List;
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "api")
@Validated
@PropertySource(value = "classpath:application.yml", factory = YamlPropertySourceFactory.class)
public class ApiConfig {
/**
* public endpoint address for the API (i.e. https://dev.nhsnlink.org/api)
*/
@Getter
private String publicAddress;
/**
* if HTTPS is required for submission urls.
*/
@Getter
private boolean requireHttps;
/**
* information to be included in all MeasureReport resources exported/sent from the system
*/
@Getter
ApiMeasureLocationConfig measureLocation;
/**
* true, init processes (loading measure bundles and resources into the internal FHIR server) should be skipped
*/
private Boolean skipInit = false;
/**
* where the FHIR server is that is used for storage
*/
@NotNull
private String fhirServerStore;
/**
* measure evaluation service (CQF-Ruler) installation that is to be used to evaluate patient data against measure logic.
*/
@Getter @Setter @NotNull
private String evaluationService;
/**
* FHIR terminology service to use for storing ValueSet and CodeSystem resources, passed to the evaluation-service for use during measure evaluation.
*/
@Getter @Setter @NotNull
private String terminologyService;
/**
* url endpoint for certs from the identity provider, which is used to verify any JSON Web Token (JWT)
*/
@Getter @Setter
private String authJwksUrl;
/**
* issuer is used during token validation to ensure that the JWT has been issued by a trusted system
*/
@Getter @Setter
private String issuer;
/**
* class used to download reports
*/
@NotNull
private String downloader;
/**
* class used to send reports
*/
@NotNull
private String sender;
/**
* used to determine if the full Bundle is sent or just the MeasureReport. True to send full bundle and false to send just the MeasureReport
*/
private Boolean sendWholeBundle;
/**
* to remove contained evaluated resources from patient measure reports
*/
private boolean removeGeneratedObservations = true;
/**
* class used to determine the list of patient ids that should be queried for
*/
private String patientIdResolver;
/**
* "system" value of identifiers for DocumentReference resources created to index reports generated
*/
private String documentReferenceSystem;
/**
* configuration used for browser interaction with the API
*/
@Getter
private ApiCorsConfig cors;
/**
* for measures supported by the system
*/
@Getter
private ApiReportDefsConfig reportDefs;
/**
* for how queries should be executed. If local, will run queries within the API. If remote,
* will request that a remote query agent perform the queries and respond to the API with the results.
*/
@Getter
@NotNull
private ApiQueryConfig query;
/**
* related to the user that is responsible for running the installation of Link, such as timezone settings.
*/
@Getter
private UserConfig user;
/**
* configuration to indicate one or more ConceptMaps to apply to patient data
*/
@Getter
private List conceptMaps;
@Getter
private Boolean deleteAfterSubmission;
} | java | 6 | 0.714024 | 201 | 33.843972 | 141 | starcoderdata |
<?php
return [
'welcome_login'=>'Connexion',
'welcome_register'=>"S'inscrire",
'welcome_home'=>'Hogar',
'sidebar_dashboard'=>'Tableau de bord',
'sidebar_location'=>'Emplacements',
'common_listing'=>'Référencement',
'common_add'=>'Ajouter',
'sidebar_order_qr'=>'Commander QR',
'sidebar_order_menu_qr'=>'Menu QR',
'sidebar_reports'=>'Rapports',
'sidebar_help'=>'Aidez-moi',
'save_changes_btn'=>'Sauvegarder les modifications',
'cancel_btn'=>'Annuler',
'top_menu_dropdown_profile'=>'Profil',
'top_menu_dropdown_settings'=>'Paramètres',
'top_menu_dropdown_help'=>'Aidez-moi',
'top_menu_dropdown_logout'=>'Se déconnecter',
'table_list_actions'=>'Actions',
'close_btn_txt'=>'Fermer',
'save_btn_txt'=>'sauver',
'common_warning'=>'avertissement',
'sidebar_setup'=>'Installer',
'sidebar_menus'=>'Les menus',
'sidebar_taxes'=>'Les impôts',
'edit_label'=>'Éditer',
'sidebar_payouts_label'=>'Paiements',
'sidebar_payments_label'=>'Paiements',
];
?> | php | 5 | 0.65893 | 54 | 30.967742 | 31 | starcoderdata |
// Keep track of the top-level state object during cloning so that getters can access it later
const ROOT = '__statezero__root';
export function getRoot(obj) {
return obj ? obj[ROOT] : undefined;
}
export function setRoot(obj, rootState) {
Object.defineProperty(obj, ROOT, {
enumerable: false,
value: rootState,
});
} | javascript | 9 | 0.703593 | 94 | 24.692308 | 13 | starcoderdata |
package com.google.android.cameraview.demo;
import android.graphics.PointF;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public class MyGLRenderer2 implements GLSurfaceView.Renderer {
private static final String TAG = "PolySample";
// Camera field of view angle, in degrees (vertical).
private static final float FOV_Y = 60;
// Near clipping plane.
private static final float NEAR_CLIP = 0.1f;
// Far clipping plane.
private static final float FAR_CLIP = 1000f;
// Model spin speed in degrees per second.
private static final float MODEL_ROTATION_SPEED_DPS = 45.0f;
// Camera position and orientation:
private static final float EYE_X = 0;
private static final float EYE_Y = 3;
private static final float EYE_Z = -10;
private static final float TARGET_X = 0;
private static final float TARGET_Y = 0;
private static final float TARGET_Z = 0;
private static final float UP_X = 0;
private static final float UP_Y = 1;
private static final float UP_Z = 0;
public float[] getModelMatrix() {
return modelMatrix;
}
public float[] getViewMatrix() {
return viewMatrix;
}
public float[] getProjMatrix() {
return projMatrix;
}
public float[] getMvpMatrix() {
return mvpMatrix;
}
public float[] getTmpMatrix() {
return tmpMatrix;
}
// Model matrix. Transforms object space into world space.
public float[] modelMatrix = new float[16];
// View matrix. Transforms world space into eye space.
public float[] viewMatrix = new float[16];
// Projection matrix. Transforms eye space into clip space.
public float[] projMatrix = new float[16];
// Model View Projection matrix (product of projection, view and model matrices).
public float[] mvpMatrix = new float[16];
// Temporary matrix for calculations.
public float[] tmpMatrix = new float[16];
// Scale matrix for calculation
public float[] scaleMatrix = new float[16];
// Translation matrix for calculation
public float[] translationMatrix = new float[16];
// Rotation matrix for calculation
public float[] rotationMatrix = new float[16];
// The shader we use to draw the object.
private MyShader myShader;
// If true, we are ready to render the object. If false, the object isn't available yet.
private boolean readyToRender = false;
// Handle of the VBO that stores the vertex positions of the object.
private int positionsVbo;
// Handle of the VBO that stores the color information for the object.
private int colorsVbo;
// Handle of the IBO that stores the sequence of indices we use to draw the object.
private int ibo;
// Number of indices present in the IBO.
private int indexCount;
// Time (as given by System.currentTimeMillis) when the last frame was rendered.
private long lastFrameTime;
// The current model rotation angle, in degrees. This angle is increased each frame to create
// the spinning animation.
private float angleDegrees;
// The RawObject to render. This is set by the main thread when the object is ready to render,
// and is consumed by the GL thread. Once set, this is never modified.
private volatile RawObject objectToRender;
public volatile float mAngle;
public float getmPosX() {
return mPosX;
}
public void setmPosX(float mPosX) {
this.mPosX = mPosX;
}
public float getmPosY() {
return mPosY;
}
public void setmPosY(float mPosY) {
this.mPosY = mPosY;
}
public float getmScale() {
return mScale;
}
public void setmScale(float mScale) {
this.mScale = mScale;
}
public volatile float mPosX = 0.0f;
public volatile float mPosY = 0.0f;
public volatile float mScale = 1.0f;
public float getAngle() {
return mAngle;
}
public void setAngle(float angle) {
mAngle = angle;
}
@Override
public void onSurfaceCreated(GL10 unused, EGLConfig config) {
// GLES20.glClearColor(0.0f, 0.15f, 0.15f, 1.0f);
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
myShader = new MyShader();
}
@Override
public void onDrawFrame(GL10 unused) {
// Draw background color.
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
Matrix.setIdentityM(modelMatrix, 0);
// Matrix.translateM(modelMatrix, 0, mPosX, mPosY, 0);
// Make a model matrix that rotates the model about the Y axis so it appears to spin.
Matrix.setRotateM(modelMatrix, 0, mAngle, 0, 1, 0);
// Matrix.scaleM(modelMatrix, 0, mScale, mScale, 1);
// Set the camera position (View matrix)
Matrix.setLookAtM(viewMatrix, 0,
// Camera position.
EYE_X, EYE_Y, EYE_Z,
// Point that the camera is looking at.
TARGET_X, TARGET_Y, TARGET_Z,
// The vector that defines which way is up.
UP_X, UP_Y, UP_Z);
// Calculate the MVP matrix (model-view-projection) by multiplying the model, view, and
// projection matrices together.
Matrix.multiplyMM(tmpMatrix, 0, viewMatrix, 0, modelMatrix, 0); // V * M
Matrix.multiplyMM(mvpMatrix, 0, projMatrix, 0, tmpMatrix, 0); // P * V * M
// objectToRender is volatile, so we capture it in a local variable.
RawObject obj = objectToRender;
if (readyToRender) {
// We're ready to render, so just render using our existing VBOs and IBO.
myShader.render(mvpMatrix, indexCount, ibo, positionsVbo, colorsVbo);
} else if (obj != null) {
// The object is ready, but we haven't consumed it yet. We need to create the VBOs and IBO
// to render the object.
indexCount = obj.indexCount;
ibo = MyGLUtils.createIbo(obj.indices);
positionsVbo = MyGLUtils.createVbo(obj.positions);
colorsVbo = MyGLUtils.createVbo(obj.colors);
// Now we're ready to render the object.
readyToRender = true;
Log.d(TAG, "VBOs/IBO created. Now ready to render object.");
}
}
@Override
public void onSurfaceChanged(GL10 unused, int width, int height) {
GLES20.glViewport(0, 0, width, height);
float aspectRatio = (float) width / height;
// Recompute the projection matrix, because it depends on the aspect ration of the display.
Matrix.perspectiveM(projMatrix, 0, FOV_Y, aspectRatio, NEAR_CLIP, FAR_CLIP);
}
// Can be called on any thread.
public void setRawObjectToRender(RawObject rawObject) {
if (objectToRender != null) throw new RuntimeException("Already had object.");
// It's safe to set objectToRender from a different thread. It's marked as volatile, and
// the GL thread will notice it on the next frame.
objectToRender = rawObject;
Log.d(TAG, "Received raw object to render.");
}
public void SetPositionMatrix()
{
// Build Translation Matrix
Matrix.setIdentityM(translationMatrix, 0);
Matrix.translateM(translationMatrix, 0, mPosX, mPosY, 1f);
}
public void setScaleMatrix()
{
// Build Scale Matrix
Matrix.setIdentityM(scaleMatrix, 0);
Matrix.scaleM(scaleMatrix, 0, mScale, mScale, mScale);
}
} | java | 5 | 0.655177 | 102 | 31.622407 | 241 | starcoderdata |
using System;
using System.Diagnostics;
using System.Windows.Forms;
namespace Shrinklet
{
public class Program
{
private static TraceSwitch m_ShrinkletSwitch = new TraceSwitch("Shrinklet", string.Empty);
private static bool IsAlreadyRunning()
{
#region Tracing . . .
#line hidden
if (Program.m_ShrinkletSwitch.TraceVerbose)
{
Trace.WriteLine("Entering Program.IsAlreadyRunning().");
}
#line default
#endregion
bool alreadyRunning = false;
Process[] processes = Process.GetProcessesByName("Shrinklet");
if (processes.Length > 1)
{
alreadyRunning = true;
}
#region Tracing . . .
#line hidden
if (Program.m_ShrinkletSwitch.TraceVerbose)
{
Trace.WriteLine("Leaving Program.IsAlreadyRunning().");
}
#line default
#endregion
return alreadyRunning;
}
[STAThread()]
public static void Main()
{
#region Tracing . . .
#line hidden
if (Program.m_ShrinkletSwitch.TraceVerbose)
{
Trace.WriteLine("Entering Program.Main().");
}
#line default
#endregion
bool alreadyRunning = IsAlreadyRunning();
if (!alreadyRunning)
{
MainForm mainForm = new MainForm();
Application.EnableVisualStyles();
Application.Run(mainForm);
}
#region Tracing . . .
#line hidden
if (Program.m_ShrinkletSwitch.TraceVerbose)
{
Trace.WriteLine("Leaving Program.Main().");
}
#line default
#endregion
}
}
} | c# | 15 | 0.680441 | 92 | 18.105263 | 76 | starcoderdata |
<?php
namespace App\Repository;
use App\Kelas;
class KelasRepository{
public function getAll()
{
return Kelas::paginate(3);
}
public function getAllWithoutPage()
{
return Kelas::get();
}
public function insert($data)
{
$kelas = new Kelas();
$kelas->name = $data['name'];
$kelas->save();
return $kelas;
}
public function show($id)
{
$kelas = Kelas::with('siswa')->findOrFail($id);
return $kelas;
}
public function update($data,$id)
{
$kelas = Kelas::findOrFail($id);
$kelas->name = $data['name'];
$kelas->save();
return $kelas;
}
public function destroy($id)
{
$kelas = Kelas::findOrFail($id);
$kelas->siswa()->delete();
$kelas->delete();
return $kelas;
}
} | php | 12 | 0.532609 | 55 | 17.795918 | 49 | starcoderdata |
class Solution {
public boolean isValid(String s) {
if(s==null || s.length()==0)
return true;
if(s.length()%2 == 1)
return false;
Stack st = new Stack
char[] c = s.toCharArray();
for(int i=0; i<c.length; i++){
switch(c[i]){
case '(':
case '[':
case '{':
st.push(c[i]);
break;
case ')':
if(st.empty())
return false;
if(st.peek()=='(')
st.pop();
else if(st.peek()=='[' || st.peek()=='{')
st.push(c[i]);
else
return false;
break;
case ']':
if(st.empty())
return false;
if(st.peek()=='[')
st.pop();
else if(st.peek()=='(' || st.peek()=='{')
st.push(c[i]);
else
return false;
break;
case '}':
if(st.empty())
return false;
if(st.peek()=='{')
st.pop();
else if(st.peek()=='[' || st.peek()=='(')
st.push(c[i]);
else
return false;
break;
default:
return false;
}
}
return st.empty();
}
} | java | 17 | 0.278473 | 61 | 30.641509 | 53 | starcoderdata |
#================================
# RESEARCH GROUP PROJECT [RGP]
#================================
# This file is part of the COMP3096 Research Group Project.
#
# MultistepAgent is the base class for an agent that can perform multiple actions per timestep.
# A multi-action agent must implement the `multistep` function and return an array of actions to take.
#
# The step() function is *ignored* and any action taken there will be silently discarded.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from pysc2.agents import base_agent
from pysc2.lib import actions
FUNCTIONS = actions.FUNCTIONS
class MultistepAgent(base_agent.BaseAgent):
"""Base class for an agent that can perform multiple actions per timestep.
"""
# Return an array of actions.
def multistep(self, obs):
self.steps += 1
self.reward += obs.reward
return [FUNCTIONS.no_op()] | python | 9 | 0.69938 | 102 | 32.37931 | 29 | starcoderdata |
# input
P1 = list(map(int, input().split()))
P2 = list(map(int, input().split()))
P3 = list(map(int, input().split()))
P1_P2 = set(P1) & set(P2)
P2_P3 = set(P2) & set(P3)
P3_P1 = set(P3) & set(P1)
if P1_P2 == P2_P3:
print('NO')
else:
print('YES') | python | 11 | 0.554688 | 36 | 18.769231 | 13 | codenet |
void wxStdRenderer::DrawFrame(wxDC& dc,
const wxString& label,
const wxRect& rect,
int flags,
int alignment,
int indexAccel)
{
wxCoord height = 0; // of the label
wxRect rectFrame = rect;
if ( !label.empty() )
{
// the text should touch the top border of the rect, so the frame
// itself should be lower
dc.GetTextExtent(label, NULL, &height);
rectFrame.y += height / 2;
rectFrame.height -= height / 2;
// we have to draw each part of the frame individually as we can't
// erase the background beyond the label as it might contain some
// pixmap already, so drawing everything and then overwriting part of
// the frame with label doesn't work
// TODO: the +5 shouldn't be hard coded
wxRect rectText;
rectText.x = rectFrame.x + 5;
rectText.y = rect.y;
rectText.width = rectFrame.width - 7; // +2 border width
rectText.height = height;
DrawFrameWithLabel(dc, label, rectFrame, rectText, flags,
alignment, indexAccel);
}
else // no label
{
DrawBoxBorder(dc, &rectFrame);
}
} | c++ | 10 | 0.539045 | 77 | 34.675676 | 37 | inline |
func (c *Client) AddLocalCharm(curl *charm.URL, ch charm.Charm, force bool) (*charm.URL, error) {
if curl.Schema != "local" {
return nil, errors.Errorf("expected charm URL with local: schema, got %q", curl.String())
}
if err := c.validateCharmVersion(ch); err != nil {
return nil, errors.Trace(err)
}
if err := lxdprofile.ValidateLXDProfile(lxdCharmProfiler{Charm: ch}); err != nil {
if !force {
return nil, errors.Trace(err)
}
}
// Package the charm for uploading.
var archive *os.File
switch ch := ch.(type) {
case *charm.CharmDir:
var err error
if archive, err = ioutil.TempFile("", "charm"); err != nil {
return nil, errors.Annotate(err, "cannot create temp file")
}
defer os.Remove(archive.Name())
defer archive.Close()
if err := ch.ArchiveTo(archive); err != nil {
return nil, errors.Annotate(err, "cannot repackage charm")
}
if _, err := archive.Seek(0, 0); err != nil {
return nil, errors.Annotate(err, "cannot rewind packaged charm")
}
case *charm.CharmArchive:
var err error
if archive, err = os.Open(ch.Path); err != nil {
return nil, errors.Annotate(err, "cannot read charm archive")
}
defer archive.Close()
default:
return nil, errors.Errorf("unknown charm type %T", ch)
}
anyHooksOrDispatch, err := hasHooksOrDispatch(archive.Name())
if err != nil {
return nil, errors.Trace(err)
}
if !anyHooksOrDispatch {
return nil, errors.Errorf("invalid charm %q: has no hooks nor dispatch file", curl.Name)
}
curl, err = c.UploadCharm(curl, archive)
if err != nil {
return nil, errors.Trace(err)
}
return curl, nil
} | go | 12 | 0.672285 | 97 | 28.685185 | 54 | inline |
var Home = Vue.component("Home", {
template: html`
<div class="list-group">
<a
v-for="c in channel"
v-on:click="clickChannel(c)"
class="list-group-item list-group-item-action"
>
<pre
display="inline"
class="mb-0"
> {{ c }}
<div class="list-group mt-3">
<a
v-for="m in menu"
v-on:click="clickMenu(m)"
class="list-group-item list-group-item-action"
>
<pre display="inline" class="mb-0">Menu {{ m }}
<div class="border mt-3 p-3">
<form v-on:submit.prevent>
<div class="form-group row">
<label for="source" class="col-sm-2 col-form-label">Source
<div class="col-sm-10">
<input
v-model="source"
type="text"
class="form-control"
id="source"
name="source"
placeholder="/home/steve/Downloads/kubectl.yaml"
/>
<div class="d-flex flex-row-reverse">
<button
type="submit"
v-on:click="clickIngest()"
class="btn btn-primary"
>
Ingest Menu
<pre display="inline" class="p-3">Version {{ version }}
`,
data() {
return {
version: "",
channel: [],
menu: [],
source: ""
};
},
created() {
axios
.get("/version")
.then(response => (this.version = response.data.version));
axios.get("/channel").then(response => (this.channel = response.data.list));
axios.get("/menu").then(response => (this.menu = response.data.list));
},
methods: {
clickChannel(c) {
this.$router.push(`channel/${c}`);
},
clickMenu(m) {
window.open(`menu/${m}`, "_blank");
},
clickIngest() {
const source = this.source;
axios.post("/menu", { source }).then(() => (window.location = "/"));
}
}
}); | javascript | 17 | 0.459838 | 80 | 26.358025 | 81 | starcoderdata |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[MyAttribute]
public class TestScriptableObject : ScriptableObject {
[System.Serializable]
public class MyClass
{
public string stringData;
}
public bool boolean;
public int integer;
public MyClass myClass;
} | c# | 8 | 0.721713 | 54 | 19.4375 | 16 | starcoderdata |
using assign_netcore31.Models;
using System;
namespace assign_netcore31
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World from .NET Core 3.1!");
// create a new patientInfo object
var patientInfo = new PatientInfo
{
Id = 12345,
LastName = "Doe",
FirstName = "John",
IsWell = true
};
Console.WriteLine($"ID={patientInfo.Id}");
Console.WriteLine($"Full Name={patientInfo.FirstName} {patientInfo.LastName}");
Console.WriteLine($"Sick? {!patientInfo.IsWell}");
// try to change id: C# allows this before v9's init
patientInfo.Id = 99999;
Console.WriteLine($"New Id={patientInfo.Id}");
// try to change last name: C# allows this before v9's init
patientInfo.LastName = "Smith3000";
Console.WriteLine($"New last name={patientInfo.LastName}");
// create a new patientInfoWithId object
var patientInfoWithId = new PatientInfoWithId(67890);
patientInfoWithId.LastName = "Smith";
patientInfoWithId.FirstName = "Joe";
patientInfoWithId.IsWell = false;
Console.WriteLine($"ID={patientInfoWithId.Id}");
Console.WriteLine($"Full Name={patientInfoWithId.FirstName} {patientInfoWithId.LastName}");
Console.WriteLine($"Sick? {!patientInfoWithId.IsWell}");
// UNCOMMENT BELOW to change Id: doesn't work
//patientInfoWithId.Id = 99999;
Console.WriteLine($"New Id={patientInfoWithId.Id}");
}
}
} | c# | 15 | 0.573504 | 103 | 34.854167 | 48 | starcoderdata |
package de.otto.rx.composer.thymeleaf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ThymeleafConfiguration {
@Bean
RxComposerDialect rxcDialect() {
return new RxComposerDialect();
}
} | java | 8 | 0.767296 | 60 | 21.714286 | 14 | starcoderdata |
// @flow strict
import type Body from '@core/physics/Body';
import type Group from '@core/physics/Group';
class Component<Props: {}> {
props: Props;
children: Array<Body | Group>;
isActive: boolean;
constructor(props: Props) {
this.props = props;
this.children = [];
// flags
this.isActive = true;
// get children from props
Object.keys(props).forEach(name => {
const child = props[name];
if (child.isBody === true || child.isGroup === true) {
this.children.push(child);
}
});
}
update(deltaTime: number) {
// fill in subclass
}
validate(body: Body) {
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
if (child.isGroup === true) {
this.validateGroup(child, body);
} else if (child === body) {
this.isActive = !!body.alive;
}
}
}
validateGroup(group: Group, body: Body) {
if (this.isActive) {
// disable component with empty group
if (group.remove(body) && group.isEmpty()) {
this.isActive = false;
}
} else {
// enable component with non-empty group
if (!group.isEmpty()) {
this.isActive = true;
}
}
}
destroy() {
this.isActive = false;
}
}
export default Component; | javascript | 13 | 0.569031 | 60 | 19.809524 | 63 | starcoderdata |
package _global
import "log"
// SetPlaceholder
//
// English:
//
// The placeholder attribute is a string that provides a brief hint to the user as to what kind of
// information is expected in the field. It should be a word or short phrase that provides a hint
// as to the expected type of data, rather than an explanation or prompt. The text must not include
// carriage returns or line feeds. So for example if a field is expected to capture a user's first
// name, and its label is "First Name", a suitable placeholder might be "e.g. Mustafa".
//
// Note:
// * The placeholder attribute is not as semantically useful as other ways to explain your form,
// and can cause unexpected technical issues with your content. See Labels for more information.
//
// Português:
//
// O atributo placeholder é uma string que fornece uma breve dica ao usuário sobre que tipo de
// informação é esperada no campo. Deve ser uma palavra ou frase curta que forneça uma dica sobre o
// tipo de dados esperado, em vez de uma explicação ou prompt. O texto não deve incluir retornos de
// carro ou feeds de linha. Assim, por exemplo, se espera-se que um campo capture o primeiro nome de
// um usuário e seu rótulo for "Nome", um espaço reservado adequado pode ser "por exemplo, Mustafa".
//
// Nota:
// * O atributo placeholder não é tão semanticamente útil quanto outras formas de explicar seu
// formulário e pode causar problemas técnicos inesperados com seu conteúdo. Consulte Rótulos
// para obter mais informações.
func (e *GlobalAttributes) SetPlaceholder(placeholder string) (ref *GlobalAttributes) {
switch e.tag {
case KTagInput:
default:
log.Printf("tag " + e.tag.String() + " does not support placeholder property")
}
e.selfElement.Set("placeholder", placeholder)
return e
} | go | 13 | 0.736004 | 102 | 44.55 | 40 | starcoderdata |
#include "Alumnos.h"
Alumnos::Alumnos(SuperPersona *_jugador)
{
contPedestrian = 0;
srand(time(0));
bezieres = new Bezier*[4];
pedestrians = new Pedestrian*[ALUMNOS];
jugador = _jugador;
generateBeziers();
nRuta = 0;
for(int i = 1; i < ALUMNOS; i++) {
printf("entra al for\n");
nRuta = rand() % 4;
printf("%d", nRuta);
Point* tempPoint = new Point(bezieres[nRuta]->ctrlPoints[0]);
pedestrians[i-1] = new Pedestrian(tempPoint, bezieres, nRuta);
}
}
Alumnos::~Alumnos(){}
void Alumnos::update() {
waitFrames++;
if (waitFrames%120==0 && (contPedestrian+1) < ALUMNOS) {
contPedestrian++;
}
for (int i = 0; i < contPedestrian; i++) {
pedestrians[i]->update();
}
jugador->update();
}
void Alumnos::draw() {
jugador->draw();
for (int i = 0; i < contPedestrian; i++) {
pedestrians[i]->draw();
if(pedestrians[i]->choco!=true)
for (int f = 0; f < contPedestrian; f++) {
//pedestrians[i]->draw();
//jugador->collide(pedestrians[f]);
if (f != i && pedestrians[f]->choco != true) {
pedestrians[i]->collide(pedestrians[f]);
}
}
}
}
void Alumnos::generateBeziers() {
Point** ctrlPoints = new Point*[10];
for (int i = 0; i < 10; i++) {
ctrlPoints[i] = new Point(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
}
for (int i = 0; i < 4; i++)
{
switch (i)
{
case 0:
ctrlPoints[0]->x = 10.0;
ctrlPoints[0]->z = 5.0;
ctrlPoints[1]->x = 8.5;
ctrlPoints[1]->z = 3.0;
ctrlPoints[2]->x = 6.5;
ctrlPoints[2]->z = 1.0;
ctrlPoints[3]->x = 4.0;
ctrlPoints[3]->z = -1.0;
ctrlPoints[4]->x = 2.6;
ctrlPoints[4]->z = -2.4;
ctrlPoints[5]->x = 1.3;
ctrlPoints[5]->z = -3.4;
ctrlPoints[6]->x = -0.5;
ctrlPoints[6]->z = -4.5;
ctrlPoints[7]->x = -2.9;
ctrlPoints[7]->z = -5.3;
ctrlPoints[8]->x = -3.2;
ctrlPoints[8]->z = -6.0;
ctrlPoints[9]->x = -4.9;
ctrlPoints[9]->z = -7.0;
break;
case 1:
ctrlPoints[0]->x = -5.7;
ctrlPoints[0]->z = 1.3;
ctrlPoints[1]->x = -6.0;
ctrlPoints[1]->z = 0.2;
ctrlPoints[2]->x = -6.0;
ctrlPoints[2]->z = -1.0;
ctrlPoints[3]->x = -6.4;
ctrlPoints[3]->z = -1.7;
ctrlPoints[4]->x = -6.0;
ctrlPoints[4]->z = -2.6;
ctrlPoints[5]->x = -5.8;
ctrlPoints[5]->z = -3.3;
ctrlPoints[6]->x = -5.8;
ctrlPoints[6]->z = -4.0;
ctrlPoints[7]->x = -5.6;
ctrlPoints[7]->z = -4.8;
ctrlPoints[8]->x = -5.0;
ctrlPoints[8]->z = -5.3;
ctrlPoints[9]->x = -4.8;
ctrlPoints[9]->z = -6.0;
break;
case 2:
ctrlPoints[0]->x = -10.5;
ctrlPoints[0]->z = -0.3;
ctrlPoints[1]->x = -9.0;
ctrlPoints[1]->z = -2.6;
ctrlPoints[2]->x = -8.6;
ctrlPoints[2]->z = -3.0;
ctrlPoints[3]->x = -8.3;
ctrlPoints[3]->z = -3.4;
ctrlPoints[4]->x = -8.0;
ctrlPoints[4]->z = -3.8;
ctrlPoints[5]->x = -7.6;
ctrlPoints[5]->z = -4.1;
ctrlPoints[6]->x = -7.3;
ctrlPoints[6]->z = -4.5;
ctrlPoints[7]->x = -7.0;
ctrlPoints[7]->z = -4.8;
ctrlPoints[8]->x = -6.4;
ctrlPoints[8]->z = -5.3;
ctrlPoints[9]->x = -6.0;
ctrlPoints[9]->z = -6.0;
break;
case 3:
ctrlPoints[0]->x = -3.2;
ctrlPoints[0]->z = -2.0;
ctrlPoints[1]->x = -3.4;
ctrlPoints[1]->z = -2.8;
ctrlPoints[2]->x = -3.6;
ctrlPoints[2]->z = -3.5;
ctrlPoints[3]->x = -3.8;
ctrlPoints[3]->z = -4.0;
ctrlPoints[4]->x = -4.0;
ctrlPoints[4]->z = -4.5;
ctrlPoints[5]->x = -4.2;
ctrlPoints[5]->z = -5.0;
ctrlPoints[6]->x = -4.4;
ctrlPoints[6]->z = -5.5;
ctrlPoints[7]->x = -4.6;
ctrlPoints[7]->z = -6.0;
ctrlPoints[8]->x = -4.8;
ctrlPoints[8]->z = -6.5;
ctrlPoints[9]->x = -5.0;
ctrlPoints[9]->z = -7.0;
break;
default:
break;
}
Point** ctrlPointsAux = ctrlPoints;
bezieres[i] = new Bezier(9, ctrlPointsAux);
}
} | c++ | 15 | 0.539512 | 64 | 22.626582 | 158 | starcoderdata |
TEST(fbvector, clause_23_3_6_2_6) {
fbvector<int> v;
auto const n = random(0U, 10000U);
v.reserve(n);
auto const n1 = random(0U, 10000U);
auto const obj = randomObject<int>();
v.assign(n1, obj);
v.shrink_to_fit();
// Nothing to verify except that the call made it through
} | c++ | 9 | 0.657439 | 59 | 28 | 10 | inline |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.