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
package top.jfunc.common.http.component.jdk; import top.jfunc.common.http.component.AbstractStreamExtractor; import top.jfunc.common.http.request.HttpRequest; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import static top.jfunc.common.http.base.HttpStatus.HTTP_BAD_REQUEST; import static top.jfunc.common.http.base.HttpStatus.HTTP_OK; /** * @author xiongshiyan at 2020/1/6 , contact me with email or phone 15208384257 */ public class DefaultJdkStreamExtractor extends AbstractStreamExtractor { /** * 注释的是Spring的方式,本方法在error的时候兼容性更好 * 200(包含)-400(不包含)之间的响应码,可以调用{@link HttpURLConnection#getInputStream()}, * 否则只能调用{@link HttpURLConnection#getErrorStream()} */ @Override public InputStream doExtract(HttpURLConnection connection, HttpRequest httpRequest) throws IOException { /// /*InputStream errorStream = connection.getErrorStream(); return null != errorStream ? errorStream : connection.getInputStream();*/ int statusCode = connection.getResponseCode(); boolean hasInputStream = statusCode >= HTTP_OK && statusCode < HTTP_BAD_REQUEST; return hasInputStream ? connection.getInputStream() : connection.getErrorStream(); } public static void main(String[] args) { } }
java
9
0.741238
108
36.25
36
starcoderdata
using System.Threading; using FluentAssertions; namespace NRun.Common.Testing { public static class TestExtensions { public static void ShouldWait(this SemaphoreSlim semaphore, int count) { int actualCount = 0; while (semaphore.Wait(actualCount == count ? 100 : 1000)) actualCount++; actualCount.Should().Be(count, "semaphore.Release() should have been called {0} times", count); } } }
c#
13
0.691589
98
23.176471
17
starcoderdata
package br.com.zup.ot6.izabel.casadocodigo.dto; import javax.validation.constraints.NotBlank; import com.fasterxml.jackson.annotation.JsonProperty; import br.com.zup.ot6.izabel.casadocodigo.entidades.Autor; public class DetalheAutorResponseDTO { @NotBlank @JsonProperty("nome") private String nome; @NotBlank @JsonProperty("descricao") private String descricao; public DetalheAutorResponseDTO(Autor autorLivro) { nome = autorLivro.getNome(); descricao = autorLivro.getDescricao(); } public String getNome() { return nome; } public String getDescricao() { return descricao; } }
java
9
0.762295
58
17.484848
33
starcoderdata
<?php return [ /* |-------------------------------------------------------------------------- | Application & Admin Template Lines |-------------------------------------------------------------------------- | | The following language lines are the default lines which will be rendered | within the 'app' and 'admin' blade templates/layouts. | */ // Navigation links "login_link" => "Inloggen", "register_link" => "Registreren", "dashboard_link" => "Dashboard", "tasks_link" => "Werkpakketten", "projects_link" => "Projecten", "members_link" => "Leden", "profile_link" => " "reviews_link" => "Mijn reviews", "edit_profile_link" => "Profiel aanpassen", "messages_link" => "Berichten", "notifications_link" => "Notificaties", "settings_link" => "Instellingen", "admin_link" => "Administratie", "logout_link" => "Uitloggen", "community_link" => "Community", "forum_link" => "Forum", "ministries_link" => "Ministeries", "organizations_link" => "Organisaties", "groups_link" => "Groepen", "polls_link" => "Polls", // Footer "footer_first_column_title" => "HNNW", "footer_press_link" => "Pers", "footer_partners_link" => "Partners", "footer_about_link" => "Over HNNW", "footer_do_more_link" => "Doe meer", "footer_faq_link" => "Veelgestelde vragen", "footer_contact_link" => "Contact", "footer_second_column_title" => "Voor medewerkers", "footer_financial_link" => "Financiele bijdragen", "footer_employer_downloads_link" => "Downloads", "footer_employer_do_more_link" => "Doe meer als werkgevers", "footer_third_column_title" => "Voor werknemers", "footer_group_link" => "Meedoen als groep", "footer_employee_downloads_link" => "Downloads", "footer_employee_do_more_link" => "Meer doen als vrijwilliger", "footer_newsletter_title" => "Nieuwsbrief", "footer_newsletter_text" => "Meld je aan voor de maandelijkse digitale nieuwsbrief.", "footer_copyright" => "&copy; Copyrighted by SSC-ICT. 2020 - &infin;", "footer_cookies_link" => "Cookies en Privacy", "footer_disclaimer_link" => "Voorwaarden", // Newsletter signup "newsletter_signup_submit" => "Inschrijven", "newsletter_signed_up" => "Bedankt voor je inschrijving!", ];
php
5
0.581346
89
36.269841
63
starcoderdata
def setup_combo_gen(parent, width=20, variable=None, def_list=None, def_value=None, l_text="Side text", start=0): """Set up generic combobox with default list.""" combo = ttk.Combobox(parent, textvariable=variable, width=width) combo.grid(row=start, column=0, sticky=tk.W + tk.E) combo["values"] = def_list combo.set(def_value) label = ttk.Label(parent, text=l_text) label.grid(row=start, column=1, sticky=tk.W, padx=2) return combo, label
python
9
0.500778
56
32.894737
19
inline
using DotFramework.Core; using DotFramework.Core.Configuration; using DotFramework.Infra.Security; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.DataProtection; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Claims; using System.Text; namespace DotFramework.Infra.Web.API.Auth.Providers { public class DataProtector { private readonly IDataProtectionProvider _dataProtectionProvider; private readonly List _purpose = new List { "TokenMiddleware", "Access_Token", "v2" }; private readonly string _TicketRepositoryPath = Path.Combine(Directory.GetCurrentDirectory(), "Identity"); private readonly bool _CompressTicket; public DataProtector(IDataProtectionProvider dataProtectionProvider, bool compressTicket, string ticketRepositoryPath) { if (_dataProtectionProvider == null) { _dataProtectionProvider = dataProtectionProvider.CreateProtector(_purpose); } _CompressTicket = compressTicket; _TicketRepositoryPath = ticketRepositoryPath; if (_CompressTicket) { if (String.IsNullOrEmpty(_TicketRepositoryPath)) { throw new ArgumentNullException("TicketRepositoryPath"); } else { if (!Directory.Exists(_TicketRepositoryPath)) { Directory.CreateDirectory(_TicketRepositoryPath); } } } } public string Protect(AuthenticationTicket ticket) { if (_dataProtectionProvider == null) { throw new Exception("IDataProtectionProvider is not provided through initialization"); } var sticket = TicketSerializer.Default.Serialize(CompressTicket(ticket)); var protector = _dataProtectionProvider.CreateProtector(_purpose); return protector.Protect(Encoding.UTF8.GetString(sticket)); } public AuthenticationTicket UnProtect(string token) { if (_dataProtectionProvider == null) { throw new Exception("IDataProtectionProvider is not provided through initialization"); } var protector = _dataProtectionProvider.CreateProtector(_purpose); try { string decryptedToken = protector.Unprotect(token); AuthenticationTicket ticket = TicketSerializer.Default.Deserialize(Encoding.UTF8.GetBytes(decryptedToken)); if (ticket.Properties.ExpiresUtc < DateTime.UtcNow) { RemoveIdentity(ticket); throw new UnauthorizedHttpException(); } return ExtractTicket(ticket); } catch (Exception) { throw new UnauthorizedHttpException(); } } public void Revoke(string token) { if (_dataProtectionProvider == null) { throw new Exception("IDataProtectionProvider is not provided through initialization"); } var protector = _dataProtectionProvider.CreateProtector(_purpose); try { string decryptedToken = protector.Unprotect(token); AuthenticationTicket ticket = TicketSerializer.Default.Deserialize(Encoding.UTF8.GetBytes(decryptedToken)); RemoveIdentity(ticket); } catch (Exception) { throw; } } private AuthenticationTicket CompressTicket(AuthenticationTicket ticket) { if (!_CompressTicket) { return ticket; } else { var groupTokenClaim = ticket.Principal.Claims.FirstOrDefault(c => c.Type == CustomClaimTypes.GroupToken) ?? new Claim(CustomClaimTypes.GroupToken, CreateShortGuid()); var tokenIdentifier = CreateShortGuid(); var tokenIdentifierClaim = new Claim(CustomClaimTypes.TokenIdentifier, tokenIdentifier); ClaimsIdentity oAuthIdentity_compressed = new ClaimsIdentity(new List { groupTokenClaim, tokenIdentifierClaim }, ticket.AuthenticationScheme); ClaimsPrincipal claimsPrincipal_compressed = new ClaimsPrincipal(oAuthIdentity_compressed); AuthenticationTicket ticket_compressed = new AuthenticationTicket(claimsPrincipal_compressed, ticket.Properties, ticket.AuthenticationScheme); SaveIdentityClaims(ticket, groupTokenClaim.Value, tokenIdentifier); return ticket_compressed; } } private AuthenticationTicket ExtractTicket(AuthenticationTicket ticket) { if (!_CompressTicket) { return ticket; } else { ClaimsIdentity oAuthIdentity = new ClaimsIdentity(RetrieveIdentityClaims(ticket), ticket.AuthenticationScheme); ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(oAuthIdentity); AuthenticationTicket new_ticket = new AuthenticationTicket(claimsPrincipal, ticket.Properties, ticket.AuthenticationScheme); return new_ticket; } } private void RemoveIdentity(AuthenticationTicket ticket) { if (ticket.Principal.Claims.Any(c => c.Type == CustomClaimTypes.GroupToken)) { var groupTokenClaim = ticket.Principal.Claims.First(c => c.Type == CustomClaimTypes.GroupToken); if (!String.IsNullOrEmpty(groupTokenClaim.Value)) { string groupIdentityPath = Path.Combine(_TicketRepositoryPath, groupTokenClaim.Value); if (Directory.Exists(groupIdentityPath)) { Directory.Delete(groupIdentityPath, true); } } } } private void SaveIdentityClaims(AuthenticationTicket ticket, string groupHandler, string fileHandle) { var sticket = CustomTicketSerializer.Default.Serialize(ticket); var protector = _dataProtectionProvider.CreateProtector(_purpose); var protectedTicket = protector.Protect(Encoding.UTF8.GetString(sticket)); string identityFileDirPath = Path.Combine(_TicketRepositoryPath, groupHandler); var identityFilePath = Path.Combine(identityFileDirPath, $"{fileHandle}.dat"); Directory.CreateDirectory(identityFileDirPath); File.WriteAllText(identityFilePath, protectedTicket); } private IEnumerable RetrieveIdentityClaims(AuthenticationTicket ticket) { if (!ticket.Principal.Claims.Any(c => c.Type == CustomClaimTypes.GroupToken)) { throw new NullReferenceException("Group Token Claim cannot be empty."); } else if (!ticket.Principal.Claims.Any(c => c.Type == CustomClaimTypes.TokenIdentifier)) { throw new NullReferenceException("Token Identifier Claim cannot be empty."); } else { var groupTokenClaim = ticket.Principal.Claims.First(c => c.Type == CustomClaimTypes.GroupToken); var tokenIdentifierClaim = ticket.Principal.Claims.First(c => c.Type == CustomClaimTypes.TokenIdentifier); var identityFilePath = Path.Combine(_TicketRepositoryPath, groupTokenClaim.Value, $"{tokenIdentifierClaim.Value}.dat"); string token = File.ReadAllText(identityFilePath); var protector = _dataProtectionProvider.CreateProtector(_purpose); string decryptedToken = protector.Unprotect(token); AuthenticationTicket new_ticket = CustomTicketSerializer.Default.Deserialize(Encoding.UTF8.GetBytes(decryptedToken)); return new_ticket.Principal.Claims; } } private string CreateShortGuid() { var ticks = new DateTime(2016, 1, 1).Ticks; var ans = DateTime.Now.Ticks - ticks; return ans.ToString("x"); } } }
c#
20
0.609807
182
38.288991
218
starcoderdata
'use strict'; const assert = require('./../assert'); describe('Mod loader', function () { it('should work fine in any order', function () { { const Dex = require('./../../build/sim/dex').Dex; assert.equal(Dex.mod('gen2').getLearnsetData('nidoking').learnset.bubblebeam.join(','), '1M'); assert.equal(Dex.mod('gen2').getMove('crunch').secondaries[0].boosts.def, undefined); } { const Dex = require('./../../build/sim/dex').Dex; Dex.mod('gen2').getLearnsetData('nidoking'); Dex.mod('gen4').getMove('crunch'); assert.equal(Dex.mod('gen2').getLearnsetData('nidoking').learnset.bubblebeam.join(','), '1M'); assert.equal(Dex.mod('gen2').getMove('crunch').secondaries[0].boosts.def, undefined); } }); }); describe('Dex#getEffect', function () { it('returns the same object for the same id', function () { assert.equal(Dex.getEffect('Stealth Rock'), Dex.getEffect('stealthrock')); assert.notStrictEqual(Dex.getEffect('move: Stealth Rock'), Dex.getEffect('stealthrock')); }); it('does not return elements from the Object prototype', function () { assert.false(Dex.getEffect('constructor').exists); }); }); describe('Dex#getSpecies', function () { it('should handle cosmetic Flabébé formes', function () { assert.equal(Dex.getSpecies('Flabébé-yellow').name, 'Flabébé-Yellow'); }); it('should handle Minior-Meteor formes', function () { assert(Dex.getSpecies('Minior-Meteor').isNonstandard); assert(!Dex.forGen(7).getSpecies('Minior-Meteor').isNonstandard); }); it.skip('should handle Rockruff-Dusk', function () { assert.equal(Dex.getSpecies('rockruffdusk').name, 'Rockruff-Dusk'); }); it('should handle Pikachu forme numbering', function () { assert.deepEqual( Dex.forGen(6).getSpecies('Pikachu').formeOrder.slice(0, 7), ["Pikachu", "Pikachu-Rock-Star", "Pikachu-Belle", "Pikachu-Pop-Star", "Pikachu-PhD", "Pikachu-Libre", "Pikachu-Cosplay"] ); assert.deepEqual( Dex.forGen(7).getSpecies('Pikachu').formeOrder.slice(0, 9), ["Pikachu", "Pikachu-Original", "Pikachu-Hoenn", "Pikachu-Sinnoh", "Pikachu-Unova", "Pikachu-Kalos", "Pikachu-Alola", "Pikachu-Partner", "Pikachu-Starter"] ); }); }); describe('Dex#getItem', function () { it('should not mark Gems as as Nonstandard in Gens 5-7', function () { assert(!Dex.forGen(5).getItem('Rock Gem').isNonstandard); assert(!Dex.forGen(5).getItem('Normal Gem').isNonstandard); assert(Dex.forGen(6).getItem('Rock Gem').isNonstandard === 'Unobtainable'); assert(!Dex.forGen(6).getItem('Normal Gem').isNonstandard); assert(Dex.forGen(8).getItem('Rock Gem').isNonstandard === 'Past'); }); });
javascript
20
0.676259
158
36.728571
70
starcoderdata
@SuppressWarnings("unchecked") @Override public void toXml(Map p, Xml_IOWriterContext context) { I_XMLBuilder builder = context.getBuilder(); Set<Entry> entries = p.entrySet(); context.appendTagHeaderStart(Xml_IOConstants.MAP_TAG_SUFFIX); context.appendSchemaInfoToFirstTag(); String nameValue = context.getNextTagNameAttribute(); if (nameValue != null) { builder.appendAttribute(Xml_IOConstants.N_NAME_ATTRIBUTE, nameValue); //clear this for child objects context.setNextTagNameAttribute(null); } builder.appendTagHeaderEnd(true); builder.addIndentLevel(); for (Entry e: entries) { context.appendTagHeaderStart(Xml_IOConstants.KEY_VALUE_TAG_SUFFIX); builder.appendTagHeaderEnd(true); //indent the key and value builder.addIndentLevel(); Object key = e.getKey(); context.writeXml(key); Object value = e.getValue(); context.writeXml(value); builder.removeIndentLevel(); context.appendEndTag(Xml_IOConstants.KEY_VALUE_TAG_SUFFIX); } builder.removeIndentLevel(); context.appendEndTag(Xml_IOConstants.MAP_TAG_SUFFIX); }
java
9
0.725157
72
30.055556
36
inline
#include #include void OpenSQL(const char * mysql_host, const char * mysql_user, const char * mysql_passwd, const char * mysql_db, unsigned int mysql_port, const char * mysql_unix_socket); bool rSQL(const char * q, ...); unsigned long wSQL(const char * q, ...); unsigned long lastidSQL(void); bool aSQL(void); void * rfSQL(const char * q, ...); bool rnSQL(void * res, ...); void sqlerror(void); void CloseSQL(void);
c
7
0.701031
74
33.642857
14
starcoderdata
package com.groupname.game.scene; import org.junit.Test; import test.util.MockFX; import static org.junit.Assert.*; public class SceneManagerTests { @Test(expected = NullPointerException.class) public void primaryStageCannotBeNull() { SceneManager.INSTANCE.setPrimaryStage(null); } @Test(expected = NullPointerException.class) public void sceneNameCannotBeNull() { SceneManager.navigate(null); } }
java
9
0.726862
52
22.315789
19
starcoderdata
import React from "react" import FooterAddress from "./FooterAddress" import FooterContact from "./FooterContact" import FooterLinks from "./FooterLinks" import FooterSocial from "./FooterSocial" import { FooterContainer } from "./footerStyles" const Footer = () => { return ( <FooterAddress /> <FooterContact /> <FooterLinks /> <FooterSocial /> ) } export default Footer
javascript
7
0.706237
48
22.666667
21
starcoderdata
import React, { useContext } from 'react'; import styled from "styled-components"; import { ColorContext } from '../Context/Context'; export default function Format() { const { format, setFormat } = useContext(ColorContext); return ( <Container className="typeNav"> <input type="radio" id="hsl" value="hsl" name="format" checked={format === 'hsl'} onClick={e => setFormat(e.target.value)} /> <label htmlFor="hsl" className="hover"> Hsl <input type="radio" id="rgb" value="rgb" name="format" checked={format === 'rgb'} onClick={e => setFormat(e.target.value)} /> <label htmlFor="rgb" className="hover"> Rgb <input type="radio" id="hex" value="hex" name="format" checked={format === 'hex'} onClick={e => setFormat(e.target.value)} /> <label htmlFor="hex" className="hover"> Hex ); } const Container = styled.ul` position:fixed; right: 32px; top: 32px; display: flex; z-index: 200; li { margin-left: 6px; } input { display: none; } label { cursor: pointer; padding: 4px 12px; text-transform: uppercase; font-size: 14px; font-weight: 600; } input { &:checked { & + label { color: #181D3D; background: #180C2420; } } } `
javascript
16
0.489634
141
27.293103
58
starcoderdata
from __future__ import print_function import optparse import os import subprocess import sys if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest def get_irods_root_directory(): return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def run_irodsctl_with_arg(arg): irodsctl = os.path.join(get_irods_root_directory(), 'iRODS', 'irodsctl') subprocess.check_call([irodsctl, arg]) def restart_irods_server(): run_irodsctl_with_arg('restart') def run_devtesty(): print('devtesty is currently disabled', file=sys.stderr) # run_irodsctl_with_arg('devtesty') def run_fastswap_test(): subprocess.check_call('rulebase_fastswap_test_2276.sh') def optparse_callback_catch_keyboard_interrupt(*args, **kwargs): unittest.installHandler() def optparse_callback_use_ssl(*args, **kwargs): import configuration configuration.USE_SSL = True def optparse_callback_topology_test(option, opt_str, value, parser): import configuration configuration.RUN_IN_TOPOLOGY = True configuration.TOPOLOGY_FROM_RESOURCE_SERVER = value == 'resource' configuration.HOSTNAME_1 = 'resource1.example.org' configuration.HOSTNAME_2 = 'resource2.example.org' configuration.HOSTNAME_3 = 'resource3.example.org' configuration.ICAT_HOSTNAME = 'icat.example.org' def run_tests_from_names(names, buffer_test_output, xml_output): loader = unittest.TestLoader() suites = [loader.loadTestsFromName(name) for name in names] super_suite = unittest.TestSuite(suites) if xml_output: import xmlrunner runner = xmlrunner.XMLTestRunner(output='test-reports', verbosity=2) else: runner = unittest.TextTestRunner(verbosity=2, failfast=True, buffer=buffer_test_output, resultclass=RegisteredTestResult) results = runner.run(super_suite) return results class RegisteredTestResult(unittest.TextTestResult): def __init__(self, *args, **kwargs): super(RegisteredTestResult, self).__init__(*args, **kwargs) unittest.registerResult(self) def startTest(self, test): # TextTestResult's impl prints as "test (module.class)" which prevents copy/paste print('{0} ... '.format(test.id()), end='', file=self.stream) unittest.TestResult.startTest(self, test) if __name__ == '__main__': parser = optparse.OptionParser() parser.add_option('--run_specific_test', metavar='dotted name') parser.add_option('--run_python_suite', action='store_true') parser.add_option('--include_auth_tests', action='store_true') parser.add_option('--include_fuse_tests', action='store_true') parser.add_option('--run_devtesty', action='store_true') parser.add_option('--topology_test', type='choice', choices=['icat', 'resource'], action='callback', callback=optparse_callback_topology_test, metavar=' parser.add_option('--catch_keyboard_interrupt', action='callback', callback=optparse_callback_catch_keyboard_interrupt) parser.add_option('--use_ssl', action='callback', callback=optparse_callback_use_ssl) parser.add_option('--no_buffer', action='store_false', dest='buffer_test_output', default=True) parser.add_option('--xml_output', action='store_true', dest='xml_output', default=False) options, _ = parser.parse_args() if len(sys.argv) == 1: parser.print_help() sys.exit(0) test_identifiers = [] if options.run_specific_test: test_identifiers.append(options.run_specific_test) if options.run_python_suite: test_identifiers.extend(['test_xmsg', 'test_iadmin', 'test_mso_suite', 'test_resource_types', 'test_catalog', 'test_rulebase', 'test_resource_tree', 'test_load_balanced_suite', 'test_icommands_file_operations', 'test_imeta_set', 'test_all_rules', 'test_iscan', 'test_ichmod', 'test_iput_options', 'test_irsync', 'test_control_plane', 'test_iticket', 'test_irodsctl']) if options.include_auth_tests: test_identifiers.append('test_auth') if options.include_fuse_tests: test_identifiers.append('test_fuse') results = run_tests_from_names(test_identifiers, options.buffer_test_output, options.xml_output) print(results) if not results.wasSuccessful(): sys.exit(1) if options.run_devtesty: run_devtesty()
python
13
0.683703
173
40.691589
107
starcoderdata
package invoice.xsd; import javax.xml.bind.annotation.XmlElement; public class SurchargexXsd { private String name; private double cost; private String industryType; public String getName() { return name; } @XmlElement public void setName(String name) { this.name = name; } public double getCost() { return cost; } @XmlElement public void setCost(double cost) { this.cost = cost; } public String getIndustryType() { return industryType; } @XmlElement public void setIndustryType(String industryType) { this.industryType = industryType; } }
java
8
0.756757
50
14
37
starcoderdata
package swarm_wars_library.network; import io.netty.channel.Channel; import org.json.JSONObject; import java.io.IOException; import java.io.ObjectInput; import java.util.*; public class MessageHandlerMulti{ private static TerminalLogger tlogger = TerminalLogger.getInstance(); public static Queue<Map<String, Object>> serverBuffer = new LinkedList<Map<String, Object>>(); private static Queue<Map<String, Object>> clientSendBuffer = new LinkedList<Map<String, Object>>(); public static volatile Map<Integer, Queue<Map<String, Object>>> clientReceiveBuffer = new HashMap<Integer, Queue<Map<String, Object>>>(); private static Map<Integer, Map<String, Object>> setupBuffer = new HashMap<Integer, Map<String, Object>>(); public static volatile Map<Integer, Integer> Frames = new HashMap(); public static volatile boolean gameStarted = false; public static volatile int readyPlayers = 0; public static Map<String, Object> getPackage(int playerNumber, int frame){ Queue<Map<String, Object>> q = clientReceiveBuffer.get(playerNumber); Map<String, Object> tmp = null; while(q != null && q.size() != 0) { tmp = q.peek(); tlogger.log("Player Number: " + playerNumber + " , Frame Number: " + tmp.get(Headers.FRAME)); int frameNow = (Integer) tmp.get(Headers.FRAME); if (frameNow < frame){ tlogger.log("Current package frame is less than wanted"); q.poll(); }else if (frameNow == frame){ tlogger.log("Successfully got one frame package, frame: " + tmp.get(Headers.FRAME)); tmp = q.poll(); break; }else if (frameNow > frame) { tlogger.log("No package found"); break; } } return tmp; } public static boolean isBufferExist(int playerNumber) { return clientReceiveBuffer.get(playerNumber) != null; } public static void clientReceivePackage(int playerNumber, Map<String, Object> m) { // TODO: About starting tlogger.log("Received player: " + m.get(Headers.PLAYER) + " frame: " + m.get(Headers.FRAME)); clientReceiveBuffer.get(playerNumber).offer(m); } public static synchronized void createNewBuffer(int playerNumber) throws Exception{ if (clientReceiveBuffer.get(playerNumber) != null){ throw new Exception("Already exists player"); } // Create a new queue Queue<Map<String, Object>> q = new LinkedList<Map<String, Object>>(); clientReceiveBuffer.put(playerNumber, q); tlogger.log("New player buffer created, player ID:" + playerNumber); } public static synchronized void putPackage(Map<String, Object> pack){ clientSendBuffer.offer(pack); } public static void sendpackage() throws InterruptedException{ if (serverBuffer.size() == 0) { // tlogger.log("No message in sending buffer"); // TODO: 决定发送频率 Thread.sleep(Constants.ServerSleep); return; } JSONObject j = new JSONObject(serverBuffer.poll()); GameProtocol g = new GameProtocol(j.toString().length(), j.toString().getBytes()); for (Channel channel : LobbyManager.getLobbyManager().getConnectionManager().values()) { // Synchronized way, if one player lagged, everyone will be blocked channel.writeAndFlush(g); } try { Logger.getInstance().log("Sent package successfully", "Server"); }catch (IOException e){ e.printStackTrace(); } Thread.sleep(Constants.ServerSleep); } public static void refreshClientReceiveBuffer() { clientReceiveBuffer = new HashMap<Integer, Queue<Map<String, Object>>>(); tlogger.log("Refreshed client receiving buffer"); } public static void serverReceivePackage(Map<String, Object> pack){ // TODO: Add logic // If the package is START, then the frame counter starts switch ((Integer) pack.get(Headers.TYPE)) { case Constants.OPERATION: tlogger.log("Case: OPERATION"); // Add a new header frame pack.put(Headers.FRAME, Frames.get((Integer)pack.get(Headers.PLAYER))); int frame = Frames.get((Integer)pack.get(Headers.PLAYER)); Frames.put((Integer)pack.get(Headers.PLAYER), ++frame); serverBuffer.offer(pack); break; case Constants.SETUP: // Receiving all setup packages means all ready, game starts tlogger.log("Case: SETUP"); pack.put(Headers.FRAME, 0); setupBuffer.put((Integer) pack.get(Headers.PLAYER), pack); readyPlayers++; break; case Constants.START: tlogger.log("Case: START"); if (readyPlayers == Frames.size() && Frames.size() > 1){ ArrayList startingLocations = TurretLocations.getInstance().getStartLocations(); ArrayList startingHealthPackLocations = TurretLocations.getInstance().getHealthPackStartLocations(); for (Map<String, Object> m : setupBuffer.values()) { m.put(Headers.TURRETS, startingLocations); m.put(Headers.HEALTH_PACKS, startingHealthPackLocations); serverBuffer.offer(m); } pack.put(Headers.RANDOM_SEED, (int) Math.round(Math.random()*Integer.MAX_VALUE)); serverBuffer.offer(pack); setupBuffer = new HashMap<Integer, Map<String, Object>>(); try { Logger.getInstance().log("All game starts", "Server"); }catch (Exception e){ e.printStackTrace(); } } break; case Constants.UPDATE_TURRET: tlogger.log("Case: UPDATE_TURRET"); int turretId = (Integer) pack.get(Headers.TURRET_ID); int turretVersion = (Integer) pack.get(Headers.TURRET_VERSION); if (TurretLocations.getInstance().updateTurretLocation(turretId, turretVersion)) { Map<String, Object> m = new HashMap<>(); m.put(Headers.TURRET_ID, turretId); m.put(Headers.TYPE, Constants.UPDATE_TURRET); m.put(Headers.TURRET_VERSION, TurretLocations.getInstance().getTurretVersionWithId(turretId)); m.put(Headers.TURRET_LOCATION, TurretLocations.getInstance().getTurretLocationWithId(turretId)); serverBuffer.offer(m); } break; case Constants.UPDATE_HEALTHPACK: tlogger.log("Case: UPDATE_HEALTH_PACK"); int hpId = (Integer) pack.get(Headers.HEALTH_PACK_ID); int hpVersion = (Integer) pack.get(Headers.HEALTH_PACK_VERSION); if (TurretLocations.getInstance().updateHPLocation(hpId, hpVersion)) { Map<String, Object> m = new HashMap<>(); m.put(Headers.HEALTH_PACK_ID, hpId); m.put(Headers.TYPE, Constants.UPDATE_HEALTHPACK); m.put(Headers.HEALTH_PACK_VERSION, TurretLocations.getInstance().getHealthPackVersionWithId(hpId)); m.put(Headers.HEALTH_PACK_LOCATION, TurretLocations.getInstance().getHealthPackLocationWithId(hpId)); serverBuffer.offer(m); } break; case Constants.CONNECT: tlogger.log("Case: CONNECT"); Frames.put((Integer)pack.get(Headers.PLAYER), 1); break; case Constants.END: tlogger.log("Case: END"); TurretLocations.getInstance().refreshTurrets(); Frames.remove((Integer)pack.get(Headers.PLAYER)); readyPlayers--; serverBuffer.offer(pack); break; } } public static void sendPackageClient() throws InterruptedException{ if (clientSendBuffer.size() == 0){ // tlogger.log("No message in sending buffer"); // TODO: 确定发送频率 Thread.sleep(Constants.ClientSleep); return; } JSONObject j = new JSONObject(clientSendBuffer.poll()); GameProtocol g = new GameProtocol(j.toString().length(), j.toString().getBytes()); LobbyManager.getChannelToServer().writeAndFlush(g); Thread.sleep(Constants.ClientSleep); } }
java
17
0.586102
128
44.44898
196
starcoderdata
from . import base class QuantileLoss(base.RegressionLoss): """Quantile loss. Parameters: alpha (float): Desired quantile to attain. Example: :: >>> from creme import optim >>> loss = optim.QuantileLoss(0.5) >>> loss(1, 3) 1.0 >>> loss.gradient(1, 3) 0.5 >>> loss.gradient(3, 1) -0.5 References: 1. `Wikipedia article on quantile regression 2. `Derivative from WolframAlpha """ def __init__(self, alpha): self.alpha = alpha def __call__(self, y_true, y_pred): diff = y_pred - y_true return (self.alpha - (diff < 0)) * diff def gradient(self, y_true, y_pred): return (y_true < y_pred) - self.alpha
python
11
0.531151
132
22.675
40
starcoderdata
public HttpWebRequest Sign(HttpWebRequest request) { // Create the nonce and timestamp timestamp = oAuth.GenerateTimeStamp(); nonce = oAuth.GenerateNonce(); // Build the oAuth parameter header var oauthParams = BuildOAuthParameterMap(); string urlOut, paramsOut; // Generate a signature with the passed parameters string signature = oAuth.GenerateSignature(request.RequestUri, consumerKey, consumerSecret, token, tokenSecret, request.Method, timestamp, nonce, out urlOut, out paramsOut); // Add the oAuth authorisation header to the HttpWebRequest request.Headers.Add(OAuthBase.HTTP_AUTHORIZATION_HEADER, BuildOAuthHeader(oauthParams, signature)); return request; }
c#
12
0.753482
176
38.944444
18
inline
#include "pipeline.hpp" Pipeline::Pipeline(vk::Device device, vk::RenderPass renderPass, Shader&& shader) : m_Layout(std::move(shader.m_Layout)) { vk::PipelineVertexInputStateCreateInfo vertexInputStateCreateInfo( {}, shader.m_VertexInputBindingDescriptors.size(), shader.m_VertexInputBindingDescriptors.data(), shader.m_VertexInputAttributeDescriptors.size(), shader.m_VertexInputAttributeDescriptors.data() ); vk::PipelineInputAssemblyStateCreateInfo inputAssemblyStateCreateInfo({}, vk::PrimitiveTopology::eTriangleList, VK_FALSE); vk::PipelineViewportStateCreateInfo viewportStateCreateInfo({}, 1, nullptr, 1, nullptr); vk::PipelineRasterizationStateCreateInfo rasterizationStateCreateInfo( {}, VK_FALSE, VK_FALSE, vk::PolygonMode::eFill, vk::CullModeFlagBits::eNone, vk::FrontFace::eCounterClockwise, VK_FALSE, {}, {}, {}, 1.0f ); vk::PipelineMultisampleStateCreateInfo multisampleStateCreateInfo({}, vk::SampleCountFlagBits::e1, VK_FALSE); vk::PipelineColorBlendAttachmentState colorBlendAttachmentState( VK_TRUE, vk::BlendFactor::eSrcAlpha, vk::BlendFactor::eOneMinusSrcAlpha, vk::BlendOp::eAdd, vk::BlendFactor::eOne, vk::BlendFactor::eZero, vk::BlendOp::eAdd, {vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA} ); vk::PipelineColorBlendStateCreateInfo colorBlendStateCreateInfo({}, VK_FALSE, vk::LogicOp::eClear, 1, &colorBlendAttachmentState); std::array<vk::DynamicState, 2> dynamicStates = {vk::DynamicState::eViewport, vk::DynamicState::eScissor}; vk::PipelineDynamicStateCreateInfo dynamicStateCreateInfo({}, dynamicStates.size(), dynamicStates.data()); vk::GraphicsPipelineCreateInfo pipelineCreateInfo( {}, shader.m_ShaderStageCreateInfo.size(), shader.m_ShaderStageCreateInfo.data(), &vertexInputStateCreateInfo, &inputAssemblyStateCreateInfo, nullptr, &viewportStateCreateInfo, &rasterizationStateCreateInfo, &multisampleStateCreateInfo, nullptr, &colorBlendStateCreateInfo, &dynamicStateCreateInfo, *m_Layout, renderPass ); m_Pipeline = device.createGraphicsPipelineUnique({}, pipelineCreateInfo); }
c++
12
0.652643
143
38.5
68
starcoderdata
def twist(input_size, eval_fun, regulariser, regulariser_function=None, thresholding_function=None, initial_x=0, alpha=0, beta=0, lmbda1=1e-4, max_eigval=2., monotone=True, verbose=1, verbose_output=0): """ TwIST (Two Steps Iterative Shrinkage Thresholding) is an algorithm to solve the convex minimization of y = f(x) + regulariser * g(x) with g(x) can be a continuous and non-differentiable function, such as L1 norm or total variation in compressed sensing. If f(x) = || Ax - b ||^2, then the gradient is Df(x) = 2 * A.T * (Ax - b). This is from J. M. Bioucas-Dias and M. A. T. Figueiredo's paper in 2007: A New TwIST: Two-Step Iterative Shrinkage/Thresholding Algorithms for Image Restoration. Arguments --------- input_size: (int or tuple of ints) shape of the signal eval_fun: (function with two outputs) evaluation function to calculate f(x) and its gradient, Df(x) regulariser: (float) regulariser weights to be multiplied with the regulariser function, g(x) regulariser_function: (function or string) the regulariser function, g(x), or string to specify the regulariser, such as "l1" or "tv" (default: reg_l1) thresholding_function: (function) function to apply thresholding (or denoising) to the signal in the gradient descent. This is ignored if regulariser function is a string (default: soft_threshold_l1) initial_x: (int or array) 0 for zeros, 1 for random, or array with shape = input_size to specify the initial guess of the signal (default: 0) alpha: (float between 0 and 1) a step size in the algorithm (see eq. 16) (default: 2. / (1. + np.sqrt(1. - rho0^2))) beta: (float between 0 and 1) a step size in the algorithm (see eq. 16) (default: alpha * 2. / (lmbda1 + 1)) lmbda1: (float) chi parameter in the algorithm (see eq. 20). Set lmbda1 = 1e-4 for severely ill conditioned problem, 1e-2 for mildly ill, and 1 for unitary operator (default: 1e-4) max_eigval: (float) the guessed largest eigenvalue of A.T*T which equals to the inverse of the step size (default: 2) monotone: (bool or int) indicate whether to enforce monotonic function's value decrease in every iteration (default: True) verbose: (bool or int) flag to show the iteration update (default: True) verbose_output: (bool or int) indicate whether the function should return the full information or just the signal (default: False) Returns ------- The signal if (verbose_output == False) or a dictionary with the output signal (x), number of iterations (n_iter), evaluation function (fx), gradient (gradx), and regulariser function (gx) values """ ############################### argument check ############################### # twist parameters lmbdaN = 1. rho0 = (1. - lmbda1/lmbdaN) / (1. + lmbda1/lmbdaN) if alpha == 0: alpha = 2. / (1. + np.sqrt(1. - rho0*rho0)) if beta == 0: beta = alpha * 2. / (lmbda1 + lmbdaN) initial_x = _get_initial_x(initial_x, input_size) regulariser_fun, thresholding_fun = _get_regulariser(regulariser, regulariser_function, thresholding_function) ############################### initialisation ############################### regulariser = float(regulariser) x = initial_x x_mid = initial_x # calculate the initial objective function y, grad_y = eval_fun(x) F_prev = y + regulariser_fun(x) ############################### main iteration ############################### n_iter = 1 twist_iter = 0 while True: while True: y_mid, grad_y_mid = eval_fun(x_mid) thresholding_x_mid = thresholding_fun(x_mid - grad_y_mid/max_eigval, regulariser/max_eigval) if twist_iter == 0: # do an IST iteration y_next, grad_y_next = eval_fun(thresholding_x_mid) F = y_next + regulariser_fun(thresholding_x_mid) # if not decreasing, then increase the max_eigval by 2 if F > F_prev: max_eigval *= 2. if max_eigval > 1e10: break # print(max_eigval) else: twist_iter = 1 x = x_mid x_mid = thresholding_x_mid break else: # perform TwIST z = (1 - alpha) * x + (alpha - beta) * x_mid + beta * thresholding_x_mid y_next, grad_y_next = eval_fun(z) F = y_next + regulariser_fun(z) # if F > F_prev and enforcing monotone, do an IST iteration with double eigenvalue if (F > F_prev) and monotone: twist_iter = 0 else: x = x_mid x_mid = z break if max_eigval > 1e10: break # print the message if verbose == 1: if printHeader(n_iter): print(header) if printContent(n_iter): print(contentFormat % (n_iter, y_next, F-y_next, F, np.sum(np.abs(grad_y_next)), np.sum(x_mid > 0))) # check convergence and update F_prev if F_prev != None and np.abs(F - F_prev) / (1e-10+np.abs(F_prev)) < 1e-6: break F_prev = F # prepare the variables for the next iteration n_iter += 1 ############################### output ############################### if verbose_output: return {"x": x_mid, "n_iter": n_iter, "fx": y_next, "gradx": grad_y_next, "gx": F-y_next} else: return x_mid
python
18
0.561272
165
51.788991
109
inline
package fr.AleksGirardey.Listeners; import fr.AleksGirardey.Objects.Channels.CityChannel; import fr.AleksGirardey.Objects.City.InfoCity; import fr.AleksGirardey.Objects.Core; import fr.AleksGirardey.Objects.DBObject.DBPlayer; import fr.AleksGirardey.Objects.Utilitaires.Utils; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.Transform; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; import org.spongepowered.api.event.cause.entity.damage.source.EntityDamageSource; import org.spongepowered.api.event.entity.DamageEntityEvent; import org.spongepowered.api.event.entity.DestructEntityEvent; import org.spongepowered.api.event.entity.living.humanoid.player.RespawnPlayerEvent; import org.spongepowered.api.event.network.ClientConnectionEvent; import org.spongepowered.api.text.channel.MessageChannel; import org.spongepowered.api.world.World; import java.sql.SQLException; public class PlayerListener { @Listener(order = Order.FIRST) public void onPlayerDeath(DestructEntityEvent.Death event) { EntityDamageSource source = event.getCause().first(EntityDamageSource.class).orElse(null); Entity check; if (source == null) return; if (event.getTargetEntity() instanceof Player) { event.setChannel(MessageChannel.TO_ALL); Core.getPlayerHandler().setReincarnation(Core.getPlayerHandler().get((Player) event.getTargetEntity())); } check = source.getSource(); if (check instanceof Player && event.getTargetEntity() instanceof Player) { DBPlayer victim = Core.getPlayerHandler().get((Player) event.getTargetEntity()), killer = Core.getPlayerHandler().get((Player) check); if (Core.getWarHandler().Contains(killer) && Core.getWarHandler().Contains(victim)) Core.getWarHandler().AddPoints(killer, victim); /* Add personnal points && money transfer */ } } @Listener(order = Order.FIRST) public void onPlayerDamaged(DamageEntityEvent event) { if (event.getTargetEntity() instanceof Player) { DBPlayer player = Core.getPlayerHandler().get((Player) event.getTargetEntity()); if (player.isInReincarnation()) event.setBaseDamage(100); } } @Listener(order = Order.FIRST) public void onPlayerListener(RespawnPlayerEvent event) { DBPlayer player = Core.getPlayerHandler().get(event.getTargetEntity()); Transform transform; if (player.getCity() != null) { transform = new Transform event.setToTransform(transform); } } @Listener(order = Order.FIRST) public void onPlayerLogin(ClientConnectionEvent.Join event) throws SQLException { DBPlayer player = Core.getPlayerHandler().get(event.getTargetEntity()); event.setChannel(MessageChannel.TO_ALL); if (player == null) Core.getPlayerHandler().add(event.getTargetEntity()); player = Core.getPlayerHandler().get(event.getTargetEntity()); if (player.getCity() != null) { InfoCity ic = Core.getInfoCityMap().get(player.getCity()); if (ic.getChannel() == null) ic.setChannel(new CityChannel(player.getCity())); ic.getChannel().addMember(player.getUser().getPlayer().get()); Core.getLogger().info("Player '" + player.getDisplayName() + "' added to city channel (" + player.getCity().getDisplayName() + ")"); } Core.getBroadcastHandler().getGlobalChannel().addMember(player.getUser().getPlayer().get()); player.getUser().getPlayer().get().setMessageChannel(Core.getBroadcastHandler().getGlobalChannel()); } @Listener(order = Order.FIRST) public void onPlayerLogout(ClientConnectionEvent.Disconnect event) { event.setChannel(MessageChannel.TO_ALL); } }
java
14
0.692752
144
40.118812
101
starcoderdata
#include #include"Child.h" /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { //create objects Child c1 , c2 , c3; //set values to objects c1.setChildDetails(1 , "Oliver" , "Toddler" , "Bryan" , "710342901"); c2.setChildDetails(2 , "Cody" , "Elder" , "Joel" , "770343290"); c3.setChildDetails(3 , "Kaden" , "Young" , "Jessica" , "771212070"); //set new contact number c1.setCotactNo(); c2.setCotactNo(); c3.setCotactNo(); //display details c1.displayChildDetails(); c2.displayChildDetails(); c3.displayChildDetails(); return 0; }
c++
7
0.670149
100
22.928571
28
starcoderdata
private void readRows(ClientMessageUnpacker in) { int size = in.unpackArrayHeader(); int rowSize = metadata.columns().size(); var res = new ArrayList<SqlRow>(size); for (int i = 0; i < size; i++) { var row = new ArrayList<>(rowSize); for (int j = 0; j < rowSize; j++) { // TODO: IGNITE-17052 Unpack according to metadata type. row.add(in.unpackObjectWithType()); } res.add(new ClientSqlRow(row)); } rows = Collections.unmodifiableList(res); }
java
12
0.537133
72
29.526316
19
inline
<?php use GuzzleHttp\Client; use GuzzleHttp\Psr7\Response; use Mockery\Mock; use Noergaard\ServerPilot\Entities\SystemUserEntity; use Noergaard\ServerPilot\Resources\SystemUsers; use Psr\Http\Message\StreamInterface; class SystemUserUnitTest extends PHPUnit_Framework_TestCase { /** * @var Mock */ private $client; /** * @var Mock */ private $contents; /** * @var Mock */ private $response; /** * @var SystemUsers */ private $systemUser; public function setUp() { parent::setUp(); $this->client = Mockery::mock(Client::class); $this->contents = Mockery::mock(StreamInterface::class); $this->response = Mockery::mock(Response::class)->shouldReceive('getBody')->andReturn($this->contents)->getMock(); $this->systemUser = new SystemUsers($this->client); } public function tearDown() { parent::tearDown(); } /** * @test */ public function it_lists_all_system_users() { $apiResponse = '{ "data": [ { "id": "PdmHhsb3fnaZ2r5f", "name": "serverpilot", "serverid": "FqHWrrcUfRI18F0l" }, { "id": "RvnwAIfuENyjUVnl", "name": "serverpilot", "serverid": "4zGDDO2xg30yEeum" }] }'; $this->contents->shouldReceive('getContents')->andReturn($apiResponse)->getMock(); $this->client->shouldReceive('get')->with('/v1/sysusers', [])->andReturn($this->response)->getMock(); $result = $this->systemUser->all(); $this->assertInstanceOf(SystemUserEntity::class, $result[0]); $this->assertInstanceOf(SystemUserEntity::class, $result[1]); $this->assertEquals('FqHWrrcUfRI18F0l', $result[0]->serverId); $this->assertEquals('4zGDDO2xg30yEeum', $result[1]->serverId); } /** *@test */ public function it_creates_a_system_user() { $apiResponse = '{ "actionid": "nnpgQoNzSK11fuTe", "data": { "id": "PPkfc1NECzvwiEBI", "name": "derek", "serverid": "FqHWrrcUfRI18F0l" } }'; $serverId = 'FqHWrrcUfRI18F0l'; $name = 'derek'; $password = ' $this->contents->shouldReceive('getContents')->andReturn($apiResponse)->getMock(); $this->client->shouldReceive('post')->with('/v1/sysusers', [ 'json' => [ 'serverid' => $serverId, 'name' => $name, 'password' => $password ] ])->andReturn($this->response)->getMock(); $result = $this->systemUser->create($serverId, $name, $password); $this->assertInstanceOf(SystemUserEntity::class, $result); $this->assertEquals($name, $result->name); } /** *@test */ public function it_gets_a_user_by_id() { $apiResponse = '{ "data": { "id": "PPkfc1NECzvwiEBI", "name": "derek", "serverid": "FqHWrrcUfRI18F0l" } }'; $this->contents->shouldReceive('getContents')->andReturn($apiResponse)->getMock(); $this->client->shouldReceive('get')->with('/v1/sysusers/PPkfc1NECzvwiEBI', [])->andReturn($this->response)->getMock(); $result = $this->systemUser->get('PPkfc1NECzvwiEBI'); $this->assertInstanceOf(SystemUserEntity::class, $result); $this->assertEquals('derek', $result->name); } /** *@test */ public function it_deletes_a_system_user_by_id() { $apiResponse = '{ "actionid": "9tvygrrXZulYuizz", "data": {} }'; $this->contents->shouldReceive('getContents')->andReturn($apiResponse)->getMock(); $this->client->shouldReceive('delete')->with('/v1/sysusers/PPkfc1NECzvwiEBI', [])->andReturn($this->response)->getMock(); $result = $this->systemUser->delete('PPkfc1NECzvwiEBI'); $this->assertInstanceOf(SystemUserEntity::class, $result); $this->assertEquals('9tvygrrXZulYuizz', $result->getActionId()); } /** *@test */ public function it_updates_system_user() { $apiResponse = '{ "actionid": "OF42xCWkKcaX3qG2", "data": { "id": "RvnwAIfuENyjUVnl", "name": "serverpilot", "serverid": "4zGDDO2xg30yEeum" } }'; $password = ' $this->contents->shouldReceive('getContents')->andReturn($apiResponse)->getMock(); $this->client->shouldReceive('post')->with('/v1/sysusers/RvnwAIfuENyjUVnl', [ 'json' => [ 'password' => $password ] ])->andReturn($this->response)->getMock(); $result = $this->systemUser->update('RvnwAIfuENyjUVnl', $password); $this->assertInstanceOf(SystemUserEntity::class, $result); } }
php
16
0.581425
129
25.795455
176
starcoderdata
import networkx as nx from PDFSegmenter.clustering.Agglomerative_Clustering import AgglomerativeGraphCluster from GraphConverter import GraphConverter from PDFSegmenter.util import constants from PDFSegmenter.util import StorageUtil from PDFSegmenter.util import GraphUtil import ast import numpy as np class BaseClassifier(object): def __init__(self, file, merge_boxes=False, regress_parameters=False, use_font=True, use_width=True, use_rect=True, use_horizontal_overlap=False, use_vertical_overlap=False, page_ratio_x=2, page_ratio_y=2, x_eps=2, y_eps=2, font_eps_h=1, font_eps_v=1, width_pct_eps=.4, width_page_eps=.5): if file is None: return self.file = file self.file_name = StorageUtil.get_file_name(self.file) self.graph_converter = GraphConverter(self.file, merge_boxes, regress_parameters, use_font, use_width, use_rect, use_horizontal_overlap, use_vertical_overlap, page_ratio_x, page_ratio_y, x_eps, y_eps, font_eps_h, font_eps_v, width_pct_eps, width_page_eps) res = self.graph_converter.convert() self.graphs = res["graphs"] self.media_box = self.graph_converter.get_media_boxes() self.graphs = AgglomerativeGraphCluster(self.graphs, self.file).assign_clusters() self.meta = self.graph_converter.meta def get_result(self, classify_table): """ :param classify_table: :return: """ result = {} media_box = self.media_box for page, graph in enumerate(self.graphs): result[page + 1] = {} result[page + 1]["bounding_box"] = (media_box[page]["x0page"], media_box[page]["x1page"], media_box[page]["y0page"], media_box[page]["y1page"]) for i, sg in enumerate(GraphUtil.connected_component_subgraphs(graph.to_undirected())): clusters = list(set(nx.get_node_attributes(sg, "cluster_label").values())) for cluster in clusters: cid = str(i) + "_" + str(cluster) graph_cluster = sg.subgraph([x for x, y in sg.nodes(data=True) if y['cluster_label'] == cluster]) result[page + 1][cid] = {} result[page + 1][cid]["bounding_box"] = \ GraphUtil.get_graph_bounding_box(graph_cluster) result[page + 1][cid]["element"] = self.classify_cluster_element(page, self.meta, graph_cluster, graph, result[page + 1][cid][ "bounding_box"], classify_table) result[page + 1][cid]["content"] = list(map(lambda x: x[1], graph_cluster.nodes(data=True))) return result @staticmethod def classify_cluster_element(page, meta, graph_cluster, graph, res_bounding, classify_table): """ :param page: :param meta: :param graph_cluster: :param graph: :param res_bounding: :param classify_table: :return: """ if constants.CLASSIFY_LIST and BaseClassifier.classify_list(graph_cluster): return "list" elif constants.CLASSIFY_PLOT and BaseClassifier.classify_plot(graph_cluster): return "plot" elif constants.CLASSIFY_TEXT and BaseClassifier.classify_text(graph_cluster, meta, page): return "text" elif classify_table(graph_cluster=graph_cluster, bounding_box=res_bounding, graph=graph): return "table" else: return "none" @staticmethod def classify_list(graph_cluster): """ :param graph_cluster: :return: """ x0s = GraphUtil.get_unique_rounded_attr(graph_cluster, "x_0") x1s = GraphUtil.get_unique_rounded_attr(graph_cluster, "x_1") xcs = GraphUtil.get_unique_rounded_attr(graph_cluster, "pos_x") return (BaseClassifier.classify_list_on_x_set(graph_cluster, x0s, align="x_0") or BaseClassifier.classify_list_on_x_set(graph_cluster, x1s, align="x_1") or BaseClassifier.classify_list_on_x_set(graph_cluster, xcs, align="pos_x")) @staticmethod def classify_list_on_x_set(graph_cluster, xs, align): """ :param graph_cluster: :param xs: :param align: :return: """ if len(xs) != 2: return False text_left = GraphUtil.get_unique_attr_from_filter(graph_cluster, "masked", filter_attr=align, filter_value=min(xs)) return len(text_left) == 1 @staticmethod def classify_text(graph_cluster, meta, page): """ :param graph_cluster: :param meta: :param page: :return: """ x0s = list(map(lambda x: round(x), list(nx.get_node_attributes(graph_cluster, "x_0").values()))) x1s = list(map(lambda x: round(x), list(nx.get_node_attributes(graph_cluster, "x_1").values()))) widths = [i - j for i, j in zip(x1s, x0s)] avg_width = meta.avg_widths[page] if np.mean(widths) > avg_width: rgbs = list(nx.get_node_attributes(graph_cluster, "rgb").values()) if len(rgbs) > 0 and type(rgbs[0]) is not tuple: rgbs = list(map(lambda x: ast.literal_eval(x), rgbs)) avg_rgb = (np.mean(list(map(lambda x: x[0], rgbs))), np.mean(list(map(lambda x: x[1], rgbs))), np.mean(list(map(lambda x: x[2], rgbs))), np.mean(list(map(lambda x: x[3], rgbs)))) # test if RGB is primary textual return abs(max(avg_rgb) - avg_rgb[0]) < constants.FLOAT_EPS and avg_rgb[3] > 0 return False @staticmethod def classify_plot(graph_cluster): """ :param graph_cluster: :return: """ # TODO return False def get_graphs(self): """ :return: """ return self.graphs
python
20
0.50799
116
41.493827
162
starcoderdata
def Query(tree):#main function of finding common buyers temp=raw_input("Please input two items: ") a=temp[0] b=temp[1] for element in sample_list:#swap the sequence of user's input, make it fit the OFI sequence if(element==a): break elif(element==b): temp=a a=b b=temp break result=0 A_list=[] B_list=[] FindA(tree,a,A_list) for node in A_list: FindB(node,b,B_list) for node in B_list: result+=node.times return result
python
10
0.676991
92
20.571429
21
inline
func (p *Path) Apply(data map[string]interface{}) (err error) { defer trapError(&err) pat, err := jsonpath.Compile(p.JsonPath) if err != nil { return err } res, err := pat.Lookup(data) if err != nil { return err } resV := reflect.ValueOf(res) targetV := reflect.ValueOf(p.Target).Elem() if !targetV.CanAddr() || !targetV.CanSet() { return errors.New("Cannot set value for path " + p.JsonPath) } if targetV.Kind() != resV.Kind() { return errors.New("Cannot set value because its kind is incorrect") } // Slices must be handled specially. if targetV.Kind() == reflect.Slice { setAllInSlice(targetV, resV) return nil } targetV.Set(resV) return nil }
go
11
0.666179
69
19.727273
33
inline
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using VideoIndexerOrchestrationWeb.Models; namespace VideoIndexerOrchestrationWeb.Controllers { public class JobHistoryController : Controller { // GET: JobHistory [ActionName("Index")] public async Task Index() { var items = await DocDbRepository => q.VIId != null); return View(items); } } }
c#
18
0.678899
88
25
21
starcoderdata
#include "pixelboost/debug/assert.h" #include "pixelboost/logic/entity.h" #include "pixelboost/logic/message/update.h" #include "pixelboost/logic/scene.h" #include "pixelboost/logic/system.h" #include "pixelboost/scripting/lua.h" using namespace pb; Scene::Scene() { _NextFreeUid = (1<<24) + 1; } Scene::~Scene() { for (EntityMap::iterator it = _Entities.begin(); it != _Entities.end(); ++it) { Entity* entity = it->second; it->second = 0; delete entity; } for (EntityMap::iterator it = _NewEntities.begin(); it != _NewEntities.end(); ++it) { Entity* entity = it->second; it->second = 0; delete entity; } for (SystemMap::iterator it = _Systems.begin(); it != _Systems.end(); ++it) { delete it->second; } } void Scene::RegisterLuaClass(lua_State* state) { luabridge::getGlobalNamespace(state) .beginNamespace("pb") .beginClass .endClass() .endNamespace(); } void Scene::Update(float timeDelta, float gameDelta) { for (EntitySet::iterator it = _PurgeSet.begin(); it != _PurgeSet.end(); ++it) { (*it)->Purge(); } _PurgeSet.clear(); for (EntityMap::iterator it = _Entities.begin(); it != _Entities.end();) { if (it->second->GetState() == Entity::kEntityDestroyed) { delete it->second; _PurgeSet.erase(it->second); _Entities.erase(it++); } else { ++it; } } for (EntityMap::iterator it = _NewEntities.begin(); it != _NewEntities.end(); ++it) { PbAssert(_Entities.find(it->first) == _Entities.end()); _Entities[it->first] = it->second; } _NewEntities.clear(); for (SystemMap::iterator it = _Systems.begin(); it != _Systems.end(); ++it) { it->second->Update(this, timeDelta, gameDelta); } BroadcastMessage(UpdateMessage(timeDelta, gameDelta)); BroadcastMessage(PostUpdateMessage()); } void Scene::Render(Viewport* viewport, RenderPass renderPass) { for (SystemMap::iterator it = _Systems.begin(); it != _Systems.end(); ++it) { it->second->Render(this, viewport, renderPass); } } bool Scene::AddSystem(SceneSystem* system) { SystemMap::iterator it = _Systems.find(system->GetType()); if (it != _Systems.end()) return false; _Systems[system->GetType()] = system; return true; } void Scene::RemoveSystem(SceneSystem* system) { SystemMap::iterator it = _Systems.find(system->GetType()); if (it != _Systems.end()) { _Systems.erase(it); } } pb::Uid Scene::GenerateEntityId() { return _NextFreeUid++; } void Scene::AddEntity(Entity* entity) { PbAssert(_NewEntities.find(entity->GetUid()) == _NewEntities.end()); _NewEntities[entity->GetUid()] = entity; } void Scene::AddEntityPurge(Entity* entity) { _PurgeSet.insert(entity); } void Scene::DestroyEntity(Entity* entity) { if (entity) { entity->Destroy(); } } void Scene::DestroyAllEntities() { for (EntityMap::iterator it = _Entities.begin(); it != _Entities.end(); ++it) { it->second->Destroy(); } } Entity* Scene::GetEntityById(Uid uid) { EntityMap::iterator it = _Entities.find(uid); if (it != _Entities.end()) return it->second; it = _NewEntities.find(uid); if (it != _NewEntities.end()) return it->second; return 0; } const Scene::EntityMap& Scene::GetEntities() const { return _Entities; } void Scene::BroadcastMessage(const Message& message) { for (EntityMap::iterator it = _Entities.begin(); it != _Entities.end(); ++it) { if (it->second->GetState() != Entity::kEntityDestroyed) it->second->SendMessage(message); } for (SystemMap::iterator it = _Systems.begin(); it != _Systems.end(); ++it) { it->second->HandleMessage(this, message); } } void Scene::SendMessage(Uid uid, const Message& message) { Entity* entity = GetEntityById(uid); if (entity && entity->GetState() != Entity::kEntityDestroyed) entity->SendMessage(message); }
c++
14
0.589002
87
21.682796
186
starcoderdata
void CameraWUP::SetMinimumTimeFromNow(int additional_milliseconds) { LARGE_INTEGER ElapsedNanoseconds; QueryPerformanceCounter(&mMinTime); mMinTime.QuadPart *= (1'000'000'000 / 100); // SystemRelativeTime from MediaReferenceFrame is in 100ns intervals mMinTime.QuadPart += additional_milliseconds * 1'000'000 / 100; mMinTime.QuadPart /= mQPCFrequency.QuadPart; }
c++
7
0.798365
113
45
8
inline
public List<Record> secondLookup(String strParam, Integer intParam, QueryParams queryParams) { assertParams(strParam, intParam); if (queryParams != null) { assertQueryParams(queryParams); } Record record1 = new Record(); record1.setValue(MULTI_LOOKUP_VAL_1); Record record2 = new Record(); record2.setValue(MULTI_LOOKUP_VAL_2); // reverse if query params passed return (queryParams != null) ? asList(record2, record1) : asList(record1, record2); }
java
8
0.589347
95
37.866667
15
inline
using System; using FluentValidation; using Incoding.Core.Block.IoC; namespace Incoding.Web.MvcContrib { #region << Using >> #endregion public class IncValidatorFactory : IValidatorFactory { ////ncrunch: no coverage start #region Constructors public IncValidatorFactory() { //FluentValidationModelValidatorProvider.Configure(); } #endregion ////ncrunch: no coverage end #region IValidatorFactory Members public IValidator GetValidator { return IoCFactory.Instance.TryResolve } public IValidator GetValidator(Type type) { IValidator validator; try { var genericType = typeof(IValidator<>).MakeGenericType(new[] {type}); validator = IoCFactory.Instance.TryResolve } catch (InvalidOperationException) { validator = new ValidateNothingDecorator(); } return validator; } internal sealed class ValidateNothingDecorator : AbstractValidator { } #endregion } }
c#
18
0.576433
85
22.277778
54
starcoderdata
/* * Copyright (C) 2018 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ package com.github.joumenharzli.shop.web; import java.util.Map; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; import org.springframework.kafka.listener.KafkaMessageListenerContainer; import org.springframework.kafka.listener.MessageListener; import org.springframework.kafka.listener.config.ContainerProperties; import org.springframework.kafka.test.rule.KafkaEmbedded; import org.springframework.kafka.test.utils.ContainerTestUtils; import org.springframework.kafka.test.utils.KafkaTestUtils; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.joumenharzli.shop.ShopApplication; import com.github.joumenharzli.shop.data.ProductAccessLog; import com.github.joumenharzli.shop.service.AccessLogService; import com.github.joumenharzli.shop.service.KafkaAccessLogService; import com.github.joumenharzli.shop.service.dto.ProductDTO; import com.github.joumenharzli.shop.service.dto.builder.ProductDTOBuilder; import static org.junit.Assert.assertEquals; /** * Access Log Service Test * * @author */ @RunWith(SpringRunner.class) @SpringBootTest(classes = ShopApplication.class) @DirtiesContext @ActiveProfiles("test") public class AccessLogServiceTest { @ClassRule public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, KafkaAccessLogService.PRODUCT_ACCESS_LOG_TOPIC); private KafkaMessageListenerContainer<String, Object> container; private BlockingQueue<ConsumerRecord<String, Object>> records; @Autowired private AccessLogService accessLogService; @Before public void setUp() throws Exception { // set up the Kafka consumer properties Map<String, Object> consumerProperties = KafkaTestUtils.consumerProps("consumerGroup", "false", embeddedKafka); DefaultKafkaConsumerFactory<String, Object> consumerFactory = new DefaultKafkaConsumerFactory<>(consumerProperties); ContainerProperties containerProperties = new ContainerProperties(KafkaAccessLogService.PRODUCT_ACCESS_LOG_TOPIC); container = new KafkaMessageListenerContainer<>(consumerFactory, containerProperties); records = new LinkedBlockingQueue<>(); container.setupMessageListener((MessageListener<String, Object>) record -> records.add(record)); // start the container and underlying message listener container.start(); // wait until the container has the required number of assigned partitions ContainerTestUtils.waitForAssignment(container, embeddedKafka.getPartitionsPerTopic()); } @After public void tearDown() { // stop the container container.stop(); } @Test @WithAnonymousUser public void testSend() throws InterruptedException, JsonProcessingException { // send the message ProductDTO productDTO = ProductDTOBuilder.aProductDTO().withId(UUID.randomUUID().toString()).build(); Object user = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); ProductAccessLog payload = accessLogService.logProductAccess(user, productDTO); // check that the message was received ConsumerRecord<String, Object> received = records.poll(10, TimeUnit.SECONDS); ObjectMapper objectMapper = new ObjectMapper(); assertEquals(received.value(), objectMapper.writeValueAsString(payload)); } }
java
13
0.801663
121
37.434426
122
starcoderdata
// +build !gtk_3_6,!gtk_3_8,!gtk_3_10,!gtk_3_12,!gtk_3_14,!gtk_3_16,!gtk_3_18 // not use this: go build -tags gtk_3_8'. Otherwise, if no build tags are used, GDK 3.20 // Go bindings for GDK 3. Supports version 3.6 and later. package gdk // #cgo pkg-config: gdk-3.0 // #include // #include "gdk.go.h" // #include "gdk_since_3_20.go.h" import "C" import ( "runtime" "unsafe" "github.com/romychs/gotk3/glib" ) func init() { tm := []glib.TypeMarshaler{ // Enums {glib.Type(C.gdk_seat_capabilities_get_type()), marshalSeatCapabilities}, // {glib.Type(C.gdk_event_type_get_type()), marshalEventType}, // {glib.Type(C.gdk_interp_type_get_type()), marshalInterpType}, // {glib.Type(C.gdk_modifier_type_get_type()), marshalModifierType}, // {glib.Type(C.gdk_pixbuf_alpha_mode_get_type()), marshalPixbufAlphaMode}, // {glib.Type(C.gdk_event_mask_get_type()), marshalEventMask}, // {glib.Type(C.gdk_rectangle_get_type()), marshalRectangle}, // Objects/Interfaces {glib.Type(C.gdk_seat_get_type()), marshalSeat}, } glib.RegisterGValueMarshalers(tm) } /* * Constants */ // SeatCapabilities is a representation of GDK's GdkSeatCapabilities. type SeatCapabilities int const ( SEAT_CAPABILITY_NONE SeatCapabilities = C.GDK_SEAT_CAPABILITY_NONE SEAT_CAPABILITY_POINTER SeatCapabilities = C.GDK_SEAT_CAPABILITY_POINTER SEAT_CAPABILITY_TOUCH SeatCapabilities = C.GDK_SEAT_CAPABILITY_TOUCH SEAT_CAPABILITY_TABLET_STYLUS SeatCapabilities = C.GDK_SEAT_CAPABILITY_TABLET_STYLUS SEAT_CAPABILITY_KEYBOARD SeatCapabilities = C.GDK_SEAT_CAPABILITY_KEYBOARD SEAT_CAPABILITY_ALL_POINTING SeatCapabilities = C.GDK_SEAT_CAPABILITY_ALL_POINTING SEAT_CAPABILITY_ALL SeatCapabilities = C.GDK_SEAT_CAPABILITY_ALL ) func marshalSeatCapabilities(p uintptr) (interface{}, error) { c := C.g_value_get_enum((*C.GValue)(unsafe.Pointer(p))) return SeatCapabilities(c), nil } // native returns the underlying GdkAtom. func (v SeatCapabilities) native() C.GdkSeatCapabilities { return C.GdkSeatCapabilities(v) } /* * GdkSeat */ // Seat is a representation of GDK's GdkSeat. type Seat struct { *glib.Object } // native returns a pointer to the underlying GdkSeat. func (v *Seat) native() *C.GdkSeat { if v == nil { return nil } ptr := unsafe.Pointer(v.Object.Native()) return C.toGdkSeat(ptr) } func marshalSeat(p uintptr) (interface{}, error) { c := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p))) obj := glib.ToObject(unsafe.Pointer(c)) return &Seat{obj}, nil } func wrapSeat(obj *glib.Object) *Seat { return &Seat{obj} } // GetDisplay is a wrapper around gdk_seat_get_display(). func (v *Seat) GetDisplay() (*Display, error) { c := C.gdk_seat_get_display(v.native()) if c == nil { return nil, nilPtrErr } return &Display{glib.Take(unsafe.Pointer(c))}, nil } // GetCapabilities is a wrapper around gdk_seat_get_capabilities(). func (v *Seat) GetCapabilities() SeatCapabilities { c := C.gdk_seat_get_capabilities(v.native()) return SeatCapabilities(c) } // GetPointer is a wrapper around gdk_seat_get_pointer(). func (v *Seat) GetPointer() (*Device, error) { c := C.gdk_seat_get_pointer(v.native()) if c == nil { return nil, nilPtrErr } return &Device{glib.Take(unsafe.Pointer(c))}, nil } // GetKeyboard is a wrapper around gdk_seat_get_keyboard(). func (v *Seat) GetKeyboard() (*Device, error) { c := C.gdk_seat_get_keyboard(v.native()) if c == nil { return nil, nilPtrErr } return &Device{glib.Take(unsafe.Pointer(c))}, nil } // GetSlaves is a wrapper around gdk_seat_get_slaves(). // Returned list is wrapped to return *gdk.Device elements. func (v *Seat) GetSlaves(capabilities SeatCapabilities) *glib.List { clist := C.gdk_seat_get_slaves(v.native(), capabilities.native()) glist := glib.WrapList(uintptr(unsafe.Pointer(clist))) glist.DataWrapper(func(ptr unsafe.Pointer) interface{} { d := wrapDevice(glib.Take(ptr)) return d }) if glist != nil { runtime.SetFinalizer(glist, func(glist *glib.List) { glist.Free() }) } return glist } /* * GdkDisplay */ // GetDefaultSeat is a wrapper around gdk_display_get_default_seat(). func (v *Display) GetDefaultSeat() (*Seat, error) { c := C.gdk_display_get_default_seat(v.native()) if c == nil { return nil, nilPtrErr } return &Seat{glib.Take(unsafe.Pointer(c))}, nil } // ListSeats is a wrapper around gdk_display_list_seats(). // Returned list is wrapped to return *gdk.Seat elements. func (v *Display) ListSeats() *glib.List { clist := C.gdk_display_list_seats(v.native()) glist := glib.WrapList(uintptr(unsafe.Pointer(clist))) glist.DataWrapper(func(ptr unsafe.Pointer) interface{} { d := wrapSeat(glib.Take(ptr)) return d }) if glist != nil { runtime.SetFinalizer(glist, func(glist *glib.List) { glist.Free() }) } return glist }
go
14
0.696197
88
26.027778
180
starcoderdata
var searchData= [ ['v_5feq_5fcheck_5flegacy_5fbmc_2eh',['v_eq_check_legacy_bmc.h',['../v__eq__check__legacy__bmc_8h.html',1,'']]], ['v_5feq_5fcheck_5frefinement_2eh',['v_eq_check_refinement.h',['../v__eq__check__refinement_8h.html',1,'']]], ['verilog_5fconst_5fparser_2eh',['verilog_const_parser.h',['../verilog__const__parser_8h.html',1,'']]], ['verilog_5fgen_2eh',['verilog_gen.h',['../verilog__gen_8h.html',1,'']]], ['verilog_5fparse_2eh',['verilog_parse.h',['../verilog__parse_8h.html',1,'']]] ];
javascript
8
0.616438
114
62.875
8
starcoderdata
import React, { useState } from 'react' import AudioPlayer from 'react-h5-audio-player' import PlayButton from '../../../images/playButton.png' import PauseButton from '../../../images/pauseButton.png' import ForwardButton from '../../../images/forwardButton.png' import BackButton from '../../../images/backButton.png' import 'react-h5-audio-player/lib/styles.css' import './audioPanel.css' const NO_HEADER_TITLE = ' ' const AUDIO_BUTTON_HEIGHT = '30px' const AUDIO_BUTTON_WIDTH = '30px' const MAXIMUM_AUDIO_HEADER_LENGTH = 20 const NO_IMAGE_REPLACEMENT_COLOR = '#faebd7' const AudioPlaybackInfo = { displayTitle: '', displayImage: '', audioSourceURL: '', audioType: '', } /** * @param {{ * customClass: String?, * audioPlaylistIndex: Number?, * audioPlaylist: [AudioPlaybackInfo], * shouldPlayNextItem: (index: Number) => void, * shouldPlayPreviousItem: (index: Number) => void, * hasStoppedPlayingItem: (item: AudioPlaybackInfo, index: Number) => void, * hasPausedPlayingItem: (item: AudioPlaybackInfo, index: Number) => void, * hasStartedPlayingItem: (item: AudioPlaybackInfo, index: Number) => void * }} props */ const AudioPanel = props => { const customClass = props.customClass ?? '' const [isAudioPlayerInSession, setIsAudioPlayerInSession] = useState(false) const [headerTitle, setHeaderTitle] = useState(NO_HEADER_TITLE) const audioPlayerOnPlay = () => { setIsAudioPlayerInSession(true) setHeaderTitleOnPlay() props.hasStartedPlayingItem({ audioSourceURL: audioPlaybackSource() }, props.audioPlaylistIndex) } const audioPlayerOnEnd = () => { props.hasStoppedPlayingItem({ audioSourceURL: audioPlaybackSource() }, props.audioPlaylistIndex) setHeaderTitle(NO_HEADER_TITLE) setIsAudioPlayerInSession(false) } const audioPlayerOnPause = () => { props.hasPausedPlayingItem({ audioSourceURL: audioPlaybackSource() }, props.audioPlaylistIndex) setIsAudioPlayerInSession(false) } const audioPlayerOnNext = () => { const { audioPlaylistIndex } = props props.shouldPlayNextItem(audioPlaylistIndex) } const audioPlayerOnPrevious = () => { const { audioPlaylistIndex } = props props.shouldPlayPreviousItem(audioPlaylistIndex) } const audioPlaybackSource = () => { const { audioPlaylist, audioPlaylistIndex } = props if (audioPlaylistIndex == null || audioPlaylistIndex == undefined) { return '' } if (audioPlaylistIndex >= audioPlaylist.length || audioPlaylistIndex < 0) { return '' } return audioPlaylist[audioPlaylistIndex].audioSourceURL } const setHeaderTitleOnPlay = () => { const { audioPlaylist, audioPlaylistIndex } = props if ( audioPlaylistIndex == null || audioPlaylistIndex == undefined || audioPlaylistIndex >= audioPlaylist.length || audioPlaylistIndex < 0 ) { return } const givenHeader = audioPlaylist[audioPlaylistIndex].displayTitle const truncatedHeader = givenHeader.length >= MAXIMUM_AUDIO_HEADER_LENGTH ? givenHeader.substring(0, MAXIMUM_AUDIO_HEADER_LENGTH) + '...' : givenHeader setHeaderTitle(truncatedHeader) } const audioPlaybackImage = () => { const { audioPlaylist, audioPlaylistIndex } = props const audioPlaybackImageClasses = 'AudioPlayerImage' const noBackgroundStyle = { backgroundColor: NO_IMAGE_REPLACEMENT_COLOR } const emptyImage = <div src="" className={audioPlaybackImageClasses} style={noBackgroundStyle}> if (audioPlaylistIndex == null || audioPlaylistIndex == undefined) { return emptyImage } if (audioPlaylistIndex >= audioPlaylist.length || audioPlaylistIndex < 0) { return emptyImage } const audioPlaybackImageSource = audioPlaylist[audioPlaylistIndex].displayImage if (audioPlaybackImageSource == null || audioPlaybackImageSource == undefined) { return emptyImage } return <img src={audioPlaybackImageSource} className={audioPlaybackImageClasses}> } return ( <div className={`AudioPlayerSection ${customClass}`}> <div className={`AudioPlayerImageContainer ${isAudioPlayerInSession ? 'GlowingBorder' : ''}`}> {audioPlaybackImage()} <AudioPlayer header={headerTitle} src={audioPlaybackSource()} showSkipControls={true} showJumpControls={false} customVolumeControls={[]} customAdditionalControls={[]} autoPlayAfterSrcChange={true} onPlay={audioPlayerOnPlay} onPause={audioPlayerOnPause} onEnded={audioPlayerOnEnd} onClickNext={audioPlayerOnNext} onClickPrevious={audioPlayerOnPrevious} customIcons={{ play: <img src={PlayButton} height={AUDIO_BUTTON_HEIGHT} width={AUDIO_BUTTON_WIDTH}> pause: <img src={PauseButton} height={AUDIO_BUTTON_HEIGHT} width={AUDIO_BUTTON_WIDTH}> next: <img src={ForwardButton} height={AUDIO_BUTTON_HEIGHT} width={AUDIO_BUTTON_WIDTH}> previous: <img src={BackButton} height={AUDIO_BUTTON_HEIGHT} width={AUDIO_BUTTON_WIDTH}> }} /> ) } export { AudioPanel, AudioPlaybackInfo }
javascript
13
0.696773
105
35.368056
144
starcoderdata
package de.can.sockenschach.gui.subgui; import de.can.sockenschach.Sockenschach; import de.can.sockenschach.figur.Bauer; import de.can.sockenschach.gui.sprite.Sprite; import de.can.sockenschach.gui.subgui.key.MouseAndKeyListener; import de.can.sockenschach.util.Point; import java.awt.*; import java.awt.event.MouseEvent; import java.util.ArrayList; public class BauerChangeSubGui extends SubGui{ ArrayList sprites = new ArrayList Point hoveredPixelPos; int changeindex = -1; boolean iswhite; Point from; Point to; int margin = 5; public BauerChangeSubGui(boolean iswhite, Point from, Point to){ this.iswhite = iswhite; this.from = from; this.to = to; if(iswhite){ sprites.add(Sockenschach.instance.spriteHandler.getSpriteByName("dame")); sprites.add(Sockenschach.instance.spriteHandler.getSpriteByName("springer")); sprites.add(Sockenschach.instance.spriteHandler.getSpriteByName("laeufer")); sprites.add(Sockenschach.instance.spriteHandler.getSpriteByName("turm")); }else{ sprites.add(Sockenschach.instance.spriteHandler.getSpriteByName("dame").getDarkerVersion(150)); sprites.add(Sockenschach.instance.spriteHandler.getSpriteByName("springer").getDarkerVersion(150)); sprites.add(Sockenschach.instance.spriteHandler.getSpriteByName("laeufer").getDarkerVersion(150)); sprites.add(Sockenschach.instance.spriteHandler.getSpriteByName("turm").getDarkerVersion(150)); } this.mklistener = new MouseAndKeyListener(){ @Override public void mouseMoved(MouseEvent e){ boolean found = false; Point center = new Point(screenwidth/2, screenheight/2); int w0 = tilesize * sprites.size() + margin * (1+sprites.size()); int h0 = tilesize + 2*margin; Point start = new Point(center.x-w0/2, center.x-h0/2); Point mousePoint = this.getShiftedMousePos(e, renderPoint); for(int i = 0; i<sprites.size();i++){ int x = start.x+margin + i*(tilesize+margin); int y = start.y+margin; if(isBetween(mousePoint.x,mousePoint.y, x*scale,y*scale, (x+tilesize)*scale, (y+tilesize)*scale)){ hoveredPixelPos = new Point(x,y); changeindex = i; found = true; } } if(!found){ hoveredPixelPos = null; changeindex = -1; } } @Override public void mouseReleased(MouseEvent e){ if(hoveredPixelPos != null){ changeTo(); } } }; } public void changeTo(){ Sockenschach.instance.currentMatch.callMoveSP_BauerChange( Sockenschach.instance.gameBoard.getFieldByPos(from).getHolder().id, to, changeindex); Sockenschach.instance.renderHandler.removeFromQueue(this); } @Override public void render(Graphics2D g2){ super.render(g2); int bgcolor = 0xdd000000; fillRect(0,0,screenwidth, screenheight, bgcolor, g2); drawCenteredShadowedText("summon:", 30, 0xffcccccc, 3, g2); if(hoveredPixelPos != null){ fillRect(hoveredPixelPos.x, hoveredPixelPos.y, tilesize, tilesize, 0xffdaff16, g2); } drawFigures(g2); } public void drawFigures(Graphics2D g2){ Point center = new Point(screenwidth/2, screenheight/2); int w0 = tilesize * sprites.size() + margin * (1+sprites.size()); int h0 = tilesize + 2*margin; Point start = new Point(center.x-w0/2, center.x-h0/2); for(int i = 0; i<sprites.size();i++){ Tile t = new Tile(sprites.get(i), start.x+margin + i*(tilesize+margin), start.y+margin); drawImage(t,g2); } } }
java
18
0.576824
111
32.32
125
starcoderdata
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); C solver = new C(); solver.solve(1, in, out); out.close(); } static class C { public void solve(int testNumber, Scanner in, PrintWriter out) { if (solve(in.next())) { out.println("YES"); } else { out.println("NO"); } } public boolean solve(String input) { String word = input + "$"; int totalStates = 5; int[] statePos = new int[totalStates]; boolean[] activeStates = new boolean[totalStates]; activeStates[0] = true; boolean atLeastOnActiveState = true; while (atLeastOnActiveState) { atLeastOnActiveState = false; boolean[] newStates = new boolean[totalStates]; for (int stateId = 0; stateId < totalStates - 1; stateId++) { if (activeStates[stateId]) { atLeastOnActiveState = true; processState(stateId, statePos, newStates, word); } } if (newStates[4]) { return true; } activeStates = newStates; } return false; } private void processState(int stateId, int[] statePos, boolean[] newStates, String word) { int startIdx = statePos[stateId]; int nextStatePos = 0; switch (stateId) { case 0: if ((nextStatePos = matchString(word, "dream", startIdx)) > 0) { newStates[1] = true; statePos[1] = nextStatePos; newStates[0] = true; statePos[0] = nextStatePos; } else if ((nextStatePos = matchString(word, "er", startIdx)) > 0) { newStates[2] = true; statePos[2] = nextStatePos; } else if ((nextStatePos = matchString(word, "$", startIdx)) > 0) { newStates[4] = true; } break; case 1: if ((nextStatePos = matchString(word, "er", startIdx)) > 0) { newStates[0] = true; statePos[0] = nextStatePos; newStates[2] = true; statePos[2] = nextStatePos; } else if ((nextStatePos = matchString(word, "$", startIdx)) > 0) { newStates[4] = true; } break; case 2: if ((nextStatePos = matchString(word, "as", startIdx)) > 0) { newStates[3] = true; statePos[3] = nextStatePos; } break; case 3: if ((nextStatePos = matchString(word, "er", startIdx)) > 0) { newStates[0] = true; statePos[0] = nextStatePos; } else if ((nextStatePos = matchString(word, "e", startIdx)) > 0) { newStates[0] = true; statePos[0] = nextStatePos; } break; } } private int matchString(String word, String target, int startIdx) { if (startIdx + target.length() > word.length()) { return -1; } for (int i = 0; i < target.length(); i++) { if (word.charAt(startIdx + i) != target.charAt(i)) { return -1; } } return startIdx + target.length(); } } }
java
20
0.446993
98
34.02459
122
codenet
package com.igorcoura.documentmanager.service; import com.igorcoura.documentmanager.domain.entities.DocumentCategory; import com.igorcoura.documentmanager.domain.enums.EntitiesEnum; import com.igorcoura.documentmanager.domain.models.document.CreateDocumentCategoryModel; import com.igorcoura.documentmanager.domain.models.document.DocumentCategoryModel; import com.igorcoura.documentmanager.infra.repository.DocumentCategoryRepository; import com.igorcoura.documentmanager.infra.repository.custom.DocumentCategoryCustomRepository; import com.igorcoura.documentmanager.infra.shared.DocumentMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors; @Service public class DocumentCategoryService { @Autowired private DocumentCategoryRepository documentCategoryRepository; @Autowired private DocumentCategoryCustomRepository documentCategoryCustomRepository; public DocumentCategoryModel insert(CreateDocumentCategoryModel model){ var category = new DocumentCategory(); category.setCategory(model.getCategory()); category.setEntity(model.getEntity()); var entity = documentCategoryRepository.save(category); return DocumentCategoryModel.builder().category(entity.getCategory()).entity(entity.getEntity()).documentModel(DocumentMapper.toModel(entity.getDocument())).build(); } public List recoverAll(){ var entity = documentCategoryRepository.findAll(); return entity.stream().map(e -> DocumentCategoryModel.builder().category(e.getCategory()).entity(e.getEntity()).documentModel(DocumentMapper.toModel(e.getDocument())).build()).collect(Collectors.toList()); } public List recoverAll(String category, EntitiesEnum entity){ var resp = documentCategoryCustomRepository.findAll(category, entity); return resp.stream().map(e -> DocumentCategoryModel.builder().category(e.getCategory()).entity(e.getEntity()).documentModel(DocumentMapper.toModel(e.getDocument())).build()).collect(Collectors.toList()); } public void delete(String category){ } }
java
17
0.793644
213
45.541667
48
starcoderdata
public static Optional<PotionMixingRecipe> getMatching(RecipeManager manager, PotionMixture inputMixture, List<ItemStack> inputStacks) { if (inputMixture.isEmpty()) return Optional.empty(); for (var recipe : manager.listAllOfType(Type.INSTANCE)) { final var effectInputs = inputMixture.effects().stream().map(StatusEffectInstance::getEffectType).toList(); final var itemInputs = new ConcurrentLinkedQueue<>(inputStacks.stream().filter(stack -> !stack.isEmpty()).toList()); if (effectInputs.size() != recipe.effectInputs.size() || itemInputs.size() != recipe.itemInputs.size()) continue; int confirmedItemInputs = 0; for (var ingredient : recipe.itemInputs) { for (var stack : itemInputs) { if (!ingredient.test(stack)) continue; itemInputs.remove(stack); confirmedItemInputs++; break; } } //Test for awkward potion input if no effects have been declared boolean effectsConfirmed = recipe.effectInputs.isEmpty() ? inputMixture.basePotion() == Potions.AWKWARD : effectInputs.containsAll(recipe.effectInputs); if (!effectsConfirmed || confirmedItemInputs != recipe.itemInputs.size()) continue; return Optional.of(recipe); } return Optional.empty(); }
java
16
0.625526
164
42.242424
33
inline
package com.rideaustin.dispatch.womenonly; import static org.junit.Assert.assertTrue; import java.util.List; import javax.inject.Inject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.google.maps.model.LatLng; import com.rideaustin.config.AppConfig; import com.rideaustin.config.RAApplicationInitializer; import com.rideaustin.config.WebConfig; import com.rideaustin.model.ride.ActiveDriver; import com.rideaustin.model.ride.DriverType; import com.rideaustin.model.user.Rider; import com.rideaustin.rest.model.CompactActiveDriverDto; import com.rideaustin.test.AbstractNonTxTests; import com.rideaustin.test.actions.DriverAction; import com.rideaustin.test.actions.RiderAction; import com.rideaustin.test.config.FixtureConfig; import com.rideaustin.test.config.TestActionsConfig; import com.rideaustin.test.config.TestSetupConfig; import com.rideaustin.test.setup.RA142DCOnlyFPRiderSetup; import com.rideaustin.test.util.TestUtils; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {AppConfig.class, WebConfig.class, FixtureConfig.class, TestActionsConfig.class, TestSetupConfig.class}, initializers = RAApplicationInitializer.class) @WebAppConfiguration public class RA142DCOnlyFPRiderIT extends AbstractNonTxTests { @Inject private RiderAction riderAction; @Inject private DriverAction driverAction; @Override @Before public void setUp() throws Exception { super.setUp(); setup = createSetup(); } @Test public void test() throws Exception { final ActiveDriver driver = setup.getDriver(); final LatLng location = locationProvider.getCenter(); driverAction.goOnline(driver.getDriver().getEmail(), location); driverAction.locationUpdate(driver, location.lat, location.lng, new String[]{TestUtils.REGULAR}, new String[]{DriverType.DIRECT_CONNECT}); final Rider rider = setup.getRider(); final List result = riderAction.searchDrivers(rider.getEmail(), location, TestUtils.REGULAR, DriverType.FINGERPRINTED); assertTrue(result.isEmpty()); } }
java
11
0.812394
183
37
62
starcoderdata
import getpass import os f = open("countdown_2w.desktop", "x") s = open("countdown2.sh", "x") usr = str(getpass.getuser()) f.write("[Desktop Entry]\nVersion=1.0\nName=Countdown 2w\nComment=Simple countdown timer\nExec=/home/"+ usr +"/countdown_timer/countdown2.sh\nIcon=/home/"+ usr +"/countdown_timer/data/countdown.ico\nTerminal=false\nType=Application\nCategories=Application;") s.write("#!/bin/bash\ncd countdown_timer\npython3 countdown2windows.py") os.system("chmod +x countdown2.sh") os.system("mv countdown_2w.desktop ~/Desktop/") os.system("cd") os.system("chmod +x ~/Desktop/countdown_2w.desktop") os.system("gio set ~/Desktop/countdown_2w.desktop metadata::trusted true")
python
10
0.746356
258
44.733333
15
starcoderdata
let _partyService = null; class PartyController { constructor({PartyService}){ _partyService = PartyService; } async get(req,res){ const { partyId } = req.params; const party = await _partyService.get(partyId); return res.send(party); } async getAll(req,res){ const { pageSize, pageNum } = req.query; const party = await _partyService.getAll(pageSize, pageNum); return res.send(party); } async create(req, res){ const { body } = req; const createdParty = await _partyService.create(body); return res.status(201).send(createdParty); } async update(req,res){ const { body } = req; const { partyId } = req.params; const updatedParty = await _partyService.update(partyId, body); return res.send(updatedParty); } async delete(req,res){ const { partyId } = req.params; const deletedParty = await _partyService.delete(partyId); return res.send(deletedParty); } async getUserParties(req, res){ const { userId } = req.params; const parties = await _partyService.getUserParties(userId); return res.send(parties); } async upvoteParty(req, res){ const { partyId } = req.params; const party = await _partyService.upvoteParty(partyId); return res.send(party); } async downvoteParty(req, res){ const { partyId } = req.params; const party = await _partyService.downvoteParty(partyId); return res.send(party); } } module.exports = PartyController;
javascript
6
0.550773
75
29.728814
59
starcoderdata
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by // @class SCRElement, SCRUIElement; @protocol SCRElementHistoryVendor - (id - (void)flushElementHistory; - (SCRUIElement *)lastNavigatedValidUIElement; - (SCRUIElement *)removeLastUIElementFromHistory; - (void)addElementToHistory:(SCRElement *)arg1; @end
c
9
0.740991
77
25.117647
17
starcoderdata
using System; using importsNamespace; public class runme { static void Main() { B b = new B(); b.hello(); //call member function in A which is in a different SWIG generated library. b.bye(); if (b.member_virtual_test(A.MemberEnum.memberenum1) != A.MemberEnum.memberenum2) throw new Exception("Test 1 failed"); if (b.global_virtual_test(GlobalEnum.globalenum1) != GlobalEnum.globalenum2) throw new Exception("Test 2 failed"); imports_b.global_test(A.MemberEnum.memberenum1); } }
c#
12
0.64632
94
29.944444
18
starcoderdata
import time from metaflow import FlowSpec, step, profile D = {'one': 1, 'two': 2, 'three': 3} class ResumeFlow(FlowSpec): """ Use this flow to test resuming across versions: Run with a version X, resume with Y and vice versa. """ @step def start(self): self.d = D self.next(self.split) @step def split(self): self.splits = range(250) self.next(self.foreach, foreach='splits') @step def foreach(self): self.x = self.input self.next(self.join) @step def join(self, inputs): self.d = inputs[0].d self.agg = list(sorted(inp.x for inp in inputs)) self.next(self.end) @step def end(self): if self.agg != list(range(250)): raise Exception("incorrect results: %s" % self.agg) if self.d != D: raise Exception("incorrect results: %s" % self.d) if __name__ == '__main__': ResumeFlow()
python
13
0.562893
63
22.268293
41
starcoderdata
// SPDX-License-Identifier: MIT package com.daimler.sechub.developertools.admin.ui.action.adapter; import java.awt.BorderLayout; import java.awt.LayoutManager; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import com.daimler.sechub.developertools.admin.ui.action.adapter.TemplatesDialogData.Necessarity; import com.daimler.sechub.developertools.admin.ui.action.adapter.TemplatesDialogData.TemplateData; public class KeyValueUI implements TemplateDataUIPart { private KeyValuePanel panel; private JTextArea textArea; private TemplateData data; KeyValueUI(TemplateData data) { this.panel = new KeyValuePanel(new BorderLayout()); this.data = data; JPanel descriptionPanel = new JPanel(new BorderLayout()); String text = " text += " + (data.description == null ? "<no description available>" : data.description); text += " text += createNecessarityHTML(data); text += " " + data.type + ") text += " JEditorPane descriptionTextArea = new JEditorPane(); descriptionTextArea.setContentType("text/html"); descriptionTextArea.setText(text); descriptionTextArea.setEditable(false); descriptionPanel.add(new JScrollPane(descriptionTextArea), BorderLayout.CENTER); textArea = new JTextArea(); /* when recommended, we provide the recommended value initially - will be overridden when defined */ if (data.necessarity == Necessarity.RECOMMENDED) { if (data.recommendedValue != null && !data.recommendedValue.isEmpty()) { textArea.setText(data.recommendedValue); } } JSplitPane splitPane = new JSplitPane(0, descriptionPanel, textArea); this.panel.add(splitPane, BorderLayout.CENTER); } private String createNecessarityHTML(TemplateData data) { String html = ""; html += "Necessarity: if (data.necessarity.equals(Necessarity.MANDATORY)) { html += " style='color:red'"; } else if (data.necessarity.equals(Necessarity.UNKNOWN)) { html += " style='color:orange'"; } else if (data.necessarity.equals(Necessarity.RECOMMENDED)) { html += " style='color:blue'"; } html += ">"; html += data.necessarity; if (data.necessarity.equals(Necessarity.RECOMMENDED)) { html +="=>"+data.recommendedValue; } html += " return html; } public JComponent getComponent() { return panel; } @Override public void setText(String text) { textArea.setText(text); } @Override public String getText() { return textArea.getText(); } @Override public TemplateData getData() { return data; } public class KeyValuePanel extends JPanel implements TemplateDataUIPart { private static final long serialVersionUID = 1L; public KeyValuePanel(LayoutManager layoutManager) { super(layoutManager); } @Override public void setText(String text) { KeyValueUI.this.setText(text); } @Override public String getText() { return KeyValueUI.this.getText(); } @Override public TemplateData getData() { return KeyValueUI.this.getData(); } } }
java
13
0.635506
128
29.42623
122
starcoderdata
<?hh // strict namespace Zynga\Framework\Lockable\Cache\V1\Test\Mock; use Zynga\Framework\StorableObject\V1\Test\Mock\ValidNoRequired as ValidExampleObject ; // -- // This is a extension o the ValidExampleObject the mock infrastructure needs. // -- class SimpleStorable extends ValidExampleObject {}
c++
3
0.780328
83
24.416667
12
starcoderdata
#include <bits/stdc++.h> #define fort(i,n) for (int i = 1; i <= n; i++) #define ll long long #define pi pair<int,int> #define sz size() #define er erase #define fr first #define sc second using namespace std; ll n,m,ans; string s,t; int32_t main() { ios_base :: sync_with_stdio(0); cin.tie(); cout.tie(); cin >> n >> m >> s >> t; ll g=__gcd(n,m); fort(i,g) if (s[(i-1)*n/g]==t[(i-1)*m/g]) ++ans; if (ans==g) cout << n*m/g; else cout << -1; }
c++
12
0.544118
58
19.695652
23
codenet
import java.util.*; import java.io.*; /** * Driver class for the CAN Bus. * It loads instances of the classes specified in the file CAN_NODES, and then * constantly alternates between pushing and receiving bits among all the CAN * Controllers. Note that the bits are essentially simultaneously processed. * */ public class Main implements Runnable{ List processors; Map<Integer, ICANController> controllers; final String CAN_NODES = "CurrentNodes.txt"; static boolean isRunning; public void LoadNodes() throws Exception{ // Construct Host Procsesors by Reflection. processors = new ArrayList controllers = new HashMap<Integer, ICANController>(); Scanner in = new Scanner(new File(CAN_NODES)); while (in.hasNextLine()){ String line = in.nextLine(); if (line.startsWith("#") || line.trim().equals("")) continue; String[] args = line.split("\\s+"); Integer ID = Integer.parseInt(args[0]); IHostProcessor p = (IHostProcessor) Class.forName(args[1]).getConstructor(Integer.TYPE).newInstance(ID); ICANController c = p.getController(); processors.add(p); controllers.put(ID, c); } } class BitCompare implements Comparator public int compare(Bit a, Bit b){ Map<Bit, Integer> map = new HashMap map.put(Bit.ZERO, 0); map.put(Bit.ONE, 1); map.put(Bit.IDLE, 2); return map.get(a) - map.get(b); } } public void run(){ int bitCycle = 0; BitCompare cp = new BitCompare(); try { LoadNodes(); } catch(Exception e){ System.err.println("Loading nodes failed, exiting!"); e.printStackTrace(); System.exit(-1); } while (isRunning){ for (IHostProcessor proc : processors) proc.run(); Bit bit = Bit.IDLE; for (ICANController controller : controllers.values()){ Bit obit = controller.getBit(); if (cp.compare(obit, bit) < 0) bit = obit; } for (ICANController controller : controllers.values()) controller.putBit(bit); bitCycle++; } } /** * Start the polling thread, and terminate when the user presses [Enter]. */ public static void main(String[] args) throws Exception{ isRunning = true; (new Thread(new Main())).start(); System.in.read(); System.out.println("Exiting..."); isRunning = false; } }
java
15
0.575018
116
31.214286
84
starcoderdata
#include void fibn(int num){ int no = num - 2; while(no--){ static int a1 = 1; static int a2 = 1; int a3 = a1+a2; if(a1 == 1 && a2 ==1){ printf("%d %d ", a1,a2); } a1 = a2; a2 = a3; printf("%d ", a3); } } int main(){ int a = 3; fibn(19); return 0; }
c
11
0.315789
40
11.882353
34
starcoderdata
package nodemanager.model; import java.awt.image.BufferedImage; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; /** * A Graph is a collection of a map image, nodes, connections, and labels. * * @author */ public class Graph { private BufferedImage mapImage; private final HashMap<Integer, Node> nodes; private final HashMap<Integer, HashSet connections; private final HashMap<String, Integer> labels; private int nextNodeId; public Graph(){ mapImage = null; nodes = new HashMap<>(); connections = new HashMap<>(); labels = new HashMap<>(); nextNodeId = 0; } public final Node createNode(int x, int y){ Node n = new Node(nextNodeId, x, y); nextNodeId++; return n; } public final void addNode(Node n){ nodes.put(n.getId(), n); if(n.getId() >= nextNodeId){ nextNodeId = n.getId() + 1; } } public final boolean addConnection(int fromId, int toId){ boolean added = false; if(!connections.containsKey(fromId)){ connections.put(fromId, new HashSet<>()); added = true; } if(!connections.containsKey(toId)){ connections.put(toId, new HashSet<>()); added = true; } connections.get(fromId).add(toId); connections.get(toId).add(fromId); return added; } public final boolean addLabel(String label, int id){ boolean canAdd = !labels.containsKey(label.toUpperCase()); if(canAdd){ labels.put(label.toUpperCase(), id); } return canAdd; // no duplicate labels } public final void setMapImage(BufferedImage buff){ this.mapImage = buff; } public final void removeNode(int id){ this.nodes.remove(id); Arrays.stream(getConnectionsById(id)).forEach((adj)->{ this.removeConnection(id, adj); }); Arrays.stream(getLabelsById(id)).forEach((label)->{ this.removeLabel(label); }); } public final boolean removeConnection(int fromId, int toId){ boolean removed = false; if(connections.containsKey(fromId)){ removed = true; connections.get(fromId).remove(toId); } if(connections.containsKey(toId)){ removed = true; connections.get(toId).remove(fromId); } return removed; } public final boolean removeLabel(String label){ return this.labels.remove(label.toUpperCase()) != null; } public final List getAllNodes(){ return nodes.values().stream().collect(Collectors.toList()); } public final List getAllConnections(){ LinkedList pairs = new LinkedList<>(); connections.entrySet().forEach((entry)->{ entry.getValue().forEach((to) -> { pairs.add(new Integer[]{entry.getKey(), to}); }); }); return pairs; } public final List getAllLabel(){ return labels.keySet().stream().collect(Collectors.toList()); } public final BufferedImage getMapImage(){ return mapImage; } public final Node getNodeById(int id){ return nodes.get(id); } public final Node getNodeByLabel(String label){ return nodes.get(labels.get(label.toUpperCase())); } public final int[] getConnectionsById(int id){ return connections.getOrDefault(id, new HashSet return integer.intValue(); }).toArray(); } public final String[] getLabelsById(int id){ return labels.entrySet().stream().filter((entry)->{ return entry.getValue() == id; }).map((entry)->{ return entry.getKey(); }).toArray((size)->new String[size]); } public final String getDescriptionForNode(int nodeId){ StringBuilder sb = new StringBuilder(); Node node = getNodeById(nodeId); if(node == null){ sb.append(String.format("Couldn't find node with id %d", nodeId)); } else { sb.append(String.format("%s%n", node.toString())); sb.append("* Connections:\n"); for(int conns : getConnectionsById(node.getId())){ sb.append(String.format("\t%d%n", conns)); } sb.append("* Labels:\n"); for(String label : getLabelsById(node.getId())){ sb.append(String.format("\t%s%n", label)); } } return sb.toString(); } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("Graph data:\n"); sb.append("* Map Image:\n"); sb.append(String.format("\t%s%n", (mapImage == null) ? "NULL" : mapImage.toString())); sb.append("* Nodes:\n"); nodes.forEach((id, node)->{ sb.append(String.format("\t%d => %s%n", id, node.toString())); }); sb.append("* Connections:\n"); connections.forEach((from, conns)->{ conns.forEach((to)->{ sb.append(String.format("\t%d => %d%n", from.intValue(), to)); }); }); sb.append("* Labels:\n"); labels.forEach((label, id)->{ sb.append(String.format("\t%s => %d%n", label, id)); }); return sb.toString(); } public static final Graph createDefault(){ Graph ret = new Graph(); ret.addNode(new Node(-1, 0, 0)); ret.addNode(new Node(-2, 100, 100)); ret.mapImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); return ret; } }
java
22
0.55941
94
30.078125
192
starcoderdata
import template from './output_Answer.html'; import './output_Answer.scss'; let output_AnswerComponent = { bindings: { answers: '<' }, template, }; export default output_AnswerComponent;
javascript
8
0.688442
44
17.090909
11
starcoderdata
public override string ToString () { if (IsEmpty) return "Color [Empty]"; // Use the property here, not the field. if (IsNamedColor) return "Color [" + Name + "]"; return String.Format ("Color [A={0}, R={1}, G={2}, B={3}]", A, R, G, B); }
c#
9
0.55303
75
23.090909
11
inline
# /******************************************************************************* # * Author : # * Email : # *******************************************************************************/ import torch import torch.nn as nn from Model.Mixmatch_Wide_Resnet import NetworkBlock,BasicBlock,NetworkBlock_Same import torch.nn.functional as F class Wide_Resnet_AET_Model(nn.Module): def __init__(self, num_layer_in_block=4,num_classes=8,dropRate=0.3,widen_factor=2,run_type=0): super(Wide_Resnet_AET_Model, self).__init__() nChannels = [16, 16 * widen_factor, 32 * widen_factor, 64 * widen_factor,128*widen_factor] if run_type==0: self.block=NetworkBlock(num_layer_in_block, nChannels[2], nChannels[3], BasicBlock, 2, dropRate) elif run_type==1: self.block=NetworkBlock_Same(num_layer_in_block, nChannels[3], nChannels[3], BasicBlock, 1, dropRate) elif run_type==2: self.block=NetworkBlock(num_layer_in_block, nChannels[3], nChannels[4], BasicBlock, 2, dropRate) self.relu = nn.LeakyReLU(negative_slope=0.1, inplace=True) if run_type!=2: self.nChannels = nChannels[3] self.bn1 = nn.BatchNorm2d(nChannels[3], momentum=0.001) else: self.nChannels=nChannels[4] self.bn1 = nn.BatchNorm2d(nChannels[4], momentum=0.001) self.fc = nn.Linear(self.nChannels * 2, num_classes) self.run_type=run_type for m in self.modules(): if isinstance(m, nn.Linear): m.bias.data.zero_() def forward(self, x1, x2): #if self.run_type==0 or self.run_type==2:#need block or not x1=self.block(x1) x2=self.block(x2) x1=self.call_block(x1) x2=self.call_block(x2) x = torch.cat((x1, x2), dim=1) return self.fc(x) def call_block(self,feat): feat = self.relu(self.bn1(feat)) if self.run_type==2: feat = F.avg_pool2d(feat, 12) else: feat = F.avg_pool2d(feat, 8)#now the # feat = feat.view(feat.size(0), -1) feat = feat.view(-1, self.nChannels) return feat class Wide_Resnet_AET_LargeModel(nn.Module): def __init__(self, num_layer_in_block=4,num_classes=8,dropRate=0.3,widen_factor=2): super(Wide_Resnet_AET_LargeModel, self).__init__() nChannels = [16, 135, 135*widen_factor, 270*widen_factor] self.block=NetworkBlock(num_layer_in_block, nChannels[2], nChannels[3], BasicBlock, 2, dropRate) self.relu = nn.LeakyReLU(negative_slope=0.1, inplace=True) self.nChannels=nChannels[3] self.bn1 = nn.BatchNorm2d(nChannels[3], momentum=0.001) self.fc = nn.Linear(self.nChannels * 2, num_classes) for m in self.modules(): if isinstance(m, nn.Linear): m.bias.data.zero_() def forward(self, x1, x2): #if self.run_type==0 or self.run_type==2:#need block or not x1=self.block(x1) x2=self.block(x2) x1=self.call_block(x1) x2=self.call_block(x2) x = torch.cat((x1, x2), dim=1) return self.fc(x) def call_block(self,feat): feat = self.relu(self.bn1(feat)) feat = F.avg_pool2d(feat, 8) feat = feat.view(-1, self.nChannels) return feat #do not work if share parameters for aet part class Wide_Resnet_AET_Model_Share(nn.Module): def __init__(self, num_layer_in_block=4,dropRate=0.3,widen_factor=2,run_type=0): super(Wide_Resnet_AET_Model_Share, self).__init__() nChannels = [16, 16 * widen_factor, 32 * widen_factor, 64 * widen_factor,128*widen_factor] if run_type==0: self.block=NetworkBlock(num_layer_in_block, nChannels[2], nChannels[3], BasicBlock, 2, dropRate) elif run_type==1: self.block=NetworkBlock_Same(num_layer_in_block, nChannels[3], nChannels[3], BasicBlock, 1, dropRate) elif run_type==2: self.block=NetworkBlock(num_layer_in_block, nChannels[3], nChannels[4], BasicBlock, 2, dropRate) self.relu = nn.LeakyReLU(negative_slope=0.1, inplace=True) if run_type!=2: self.nChannels = nChannels[3] self.bn1 = nn.BatchNorm2d(nChannels[3], momentum=0.001) else: self.nChannels=nChannels[4] self.bn1 = nn.BatchNorm2d(nChannels[4], momentum=0.001) self.run_type=run_type def forward(self, x): #if self.run_type==0 or self.run_type==2:#need block or not x1=self.block(x) x1=self.call_block(x1) return x1 def call_block(self,feat): feat = self.relu(self.bn1(feat)) #if self.run_type!=2: feat = F.avg_pool2d(feat, 8) #else: # feat = F.avg_pool2d(feat, 4)#now the # feat = feat.view(feat.size(0), -1) feat = feat.view(-1, self.nChannels) return feat
python
14
0.582656
113
42.964286
112
starcoderdata
#ifndef XPROFILER_SRC_LOGBYPASS_HTTP_H #define XPROFILER_SRC_LOGBYPASS_HTTP_H #include "nan.h" #include "xpf_mutex-inl.h" namespace xprofiler { class EnvironmentData; constexpr uint16_t kMaxHttpStatusCode = 1000; struct HttpStatistics { Mutex mutex; // http server uint32_t live_http_request = 0; uint32_t http_response_close = 0; uint32_t http_response_sent = 0; uint32_t http_request_timeout = 0; uint32_t http_rt = 0; // ms // http status code: 0 ~ 999 uint32_t status_codes[kMaxHttpStatusCode] = {0}; }; void WriteHttpStatus(EnvironmentData* env_data, bool log_format_alinode, uint32_t http_patch_timeout); // javascript-accessible void AddLiveRequest(const Nan::FunctionCallbackInfo info); void AddCloseRequest(const Nan::FunctionCallbackInfo info); void AddSentRequest(const Nan::FunctionCallbackInfo info); void AddRequestTimeout(const Nan::FunctionCallbackInfo info); void AddHttpStatusCode(const Nan::FunctionCallbackInfo info); } // namespace xprofiler #endif /* XPROFILER_SRC_LOGBYPASS_HTTP_H */
c
9
0.741935
73
30
37
starcoderdata
package main; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.lwjgl.opengl.Display; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import org.newdawn.slick.geom.Rectangle; import components.Component; import components.UpdatingPanel; import visionCore.geom.Color; import static main.Main.displayScale; public class Menu extends Scene { public static Color[] flavors; static { flavors = new Color[9]; flavors[0] = Color.white.copy(); flavors[1] = Color.lightBlue.copy(); flavors[2] = Color.cyan.copy(); flavors[3] = Color.green.copy(); flavors[4] = Color.mint.copy(); flavors[5] = Color.orange.copy(); flavors[6] = Color.yellow.copy(); flavors[7] = Color.red.copy(); flavors[8] = Color.magenta.copy(); } private static Image bg, fadingOut; public List components; private Component focus; public Rectangle contentpanel; public String title; public float titleX, titleY; public boolean renderComponents; public Menu() { this.components = new ArrayList this.components.add(new UpdatingPanel()); this.contentpanel = new Rectangle((Display.getWidth() - 1024f * displayScale) * 0.5f, 150f * displayScale, 1024f * displayScale, 830f * displayScale); this.titleX = -1f; this.titleY = -1f; this.renderComponents = true; } @Override public void update(int delta) throws SlickException { super.update(delta); for (Iterator it = components.iterator(); it.hasNext();) { Component c = it.next(); c.update(delta); if (c.closed) { it.remove(); } } if (fadingOut != null) { fadingOut.setAlpha(fadingOut.getAlpha() * (float)Math.pow(0.875f, (float)delta / 16f)); if (fadingOut.getAlpha() <= 0.001f) { fadingOut = null; } } } @Override public void render(Graphics g) throws SlickException { super.render(g); if (bg != null) { float w = (float)Display.getWidth() / (float)bg.getWidth(); float h = (float)Display.getHeight() / (float)bg.getHeight(); float scale = Math.max(w, h); int x = (int)((Display.getWidth() - bg.getWidth() * scale) * 0.5f); int y = (int)((Display.getHeight() - bg.getHeight() * scale) * 0.5f); bg.draw(x, y, scale); } if (fadingOut != null) { float w = (float)Display.getWidth() / (float)fadingOut.getWidth(); float h = (float)Display.getHeight() / (float)fadingOut.getHeight(); float scale = Math.max(w, h); int x = (int)((Display.getWidth() - fadingOut.getWidth() * scale) * 0.5f); int y = (int)((Display.getHeight() - fadingOut.getHeight() * scale) * 0.5f); fadingOut.draw(x, y, scale); } float scale = (Display.getHeight() - 250f) / (float)GUIRes.contentPanel.getHeight(); g.setFont(Fonts.roboto.s48); int shadow = Math.max((int)(2f * displayScale + 0.5f), 1); int x = (int)((titleX > -1) ? titleX : contentpanel.x); int y = (int)((titleY > -1) ? titleY : contentpanel.y - g.getFont().getHeight("I") - 10f * displayScale); titleX = x; titleY = y; g.setColor(Color.white); g.drawStringShadow(title, x, y, shadow, 0.1f); Clock.renderClock(g, -20f, 10f, Color.white, Fonts.roboto.s48, true); if (renderComponents) { renderComponents(g); } } protected void renderComponents(Graphics g) throws SlickException { for (Component c : components) { c.render(g, 0f, 0f); } } @Override public void mouseWheelMoved(int change) { super.mouseWheelMoved(change); if (focus != null) { focus.mouseWheelMoved(change); } } @Override public void mouseInput(int button, boolean pressed) { } public void handleInput(int key, char c, boolean pressed) { super.handleInput(key, c, pressed); if (focus != null) { focus.handleInput(key, c, pressed); } } public static void setBG(Image img) { if (img == null) { return; } if (bg != null && bg.equals(img)) { return; } if (bg != null && !bg.isDestroyed()) { //fadingOut.setAlpha(1f); fadingOut = bg; } img.setAlpha(1f); bg = img; } public void setFocus(Component focus) { if (focus == null) { return; } if (this.focus != null) { this.focus.hasFocus = false; } focus.hasFocus = true; this.focus = focus; } protected Component getFocus() { return this.focus; } @Override public void clearScene() { super.clearScene(); for (Component c : components) { if (c != null) { c.clear(); } } } }
java
17
0.600246
152
19.208696
230
starcoderdata
import numpy as np from scipy.optimize import minimize import libSolver class Species: def __init__(self, charge, mass, density, vpara, vperp, fv, ns): """Constructs a species object with the required fields. """ assert(vpara.shape[0] == fv.shape[0]) assert(vperp.shape[0] == fv.shape[1]) assert(len(ns) != 0) self.charge = charge self.mass = mass self.density = density self.ns = list(ns) self.fv_h = 0.5*fv[1:, 1:] + 0.5*fv[:-1, :-1] self.vpara_h = 0.5*vpara[1:] + 0.5*vpara[:-1] self.vperp_h = 0.5*vperp[1:] + 0.5*vperp[:-1] self.dvpara_h = vpara[1:] - vpara[:-1] self.dvperp_h = vperp[1:] - vperp[:-1] normfv = 1.0/np.sum(2.0*np.pi*np.outer(np.ones(len(vpara)-1), self.vperp_h)*self.fv_h*np.outer(self.dvpara_h, self.dvperp_h)) self.fv_h *= normfv self.df_dvpara_h = normfv*(0.5*fv[1:, 1:] - 0.5*fv[:-1, 1:] + 0.5*fv[1:, :-1] - 0.5*fv[:-1, :-1])/np.outer(self.dvpara_h, np.ones(len(vperp)-1)) self.df_dvperp_h = normfv*(0.5*fv[1:, 1:] - 0.5*fv[1:, :-1] + 0.5*fv[:-1, 1:] - 0.5*fv[:-1, :-1])/np.outer(np.ones(len(vpara)-1), self.dvperp_h) class Solver: def __init__(self, B, species): """Constructs a dispersion solver from a static magnetic field and a collection of Species objects. """ self.lib = libSolver.Solver(list(species), B) self.kpara = None self.kperp = None def set_k(self, k): kpara = k[0] kperp = k[1] if not kpara == self.kpara: self.lib.push_kpara(kpara) self.kpara = kpara if not kperp == self.kperp: self.lib.push_kperp(kperp) self.kperp = kperp def marginalize(self, ww, k): """Computes an array of insolutions given a fixed value of k and array of complex frequencies ww. """ self.set_k(k) insolution = self.lib.marginalize(ww) return insolution def identify(self, ww, k, insolution): """Identifies local minima by marginalization of insolution for a complex array of frequencies and fixed value of k. """ insolution = np.abs(insolution) if len(np.shape(insolution)) == 1: minimas = np.where((insolution[1:-1] < insolution[2:]) & (insolution[1:-1] < insolution[:-2])) bounds = [] for minima in zip(*minimas): bounds.append(((ww[zip(minima - np.array([1]))].real, ww[zip(minima + np.array([1]))].real), (None, None))) return zip(ww[1:-1][minimas], insolution[1:-1][minimas], bounds) else: inspad = np.zeros([insolution.shape[0]+2, insolution.shape[1]+2]) inspad[1:-1, 1:-1] = insolution inspad[1:-1, 0] = insolution[:, 0]*1.001 inspad[1:-1, -1] = insolution[:, -1]*1.001 inspad[0, 1:-1] = insolution[0, :]*1.001 inspad[-1, 1:-1] = insolution[-1, :]*1.001 wwpad = np.zeros([ww.shape[0]+2, ww.shape[1]+2], dtype='complex') wwpad[1:-1, 1:-1] = ww wwpad[1:-1, 0] = 2*ww[:, 0] - ww[:, 1] wwpad[1:-1, -1] = 2*ww[:, -1] - ww[:, -2] wwpad[0, 1:-1] = 2*ww[0, :] - ww[1, :] wwpad[-1, 1:-1] = 2*ww[-1, :] - ww[-2, :] minimas = np.where((inspad[1:-1, 1:-1] < inspad[2:, 1:-1]) & (inspad[1:-1, 1:-1] < inspad[:-2, 1:-1]) & (inspad[1:-1, 1:-1] < inspad[1:-1, 2:]) & (inspad[1:-1, 1:-1] < inspad[1:-1, :-2]) & (inspad[1:-1, 1:-1] < inspad[2:, 2:]) & (inspad[1:-1, 1:-1] < inspad[2:, :-2]) & (inspad[1:-1, 1:-1] < inspad[:-2, 2:]) & (inspad[1:-1, 1:-1] < inspad[:-2, :-2])) bounds = [] for minima in zip(*minimas): bounds.append(((wwpad[0:-2, 1:-1][zip(minima)].real, wwpad[2:, 1:-1][zip(minima)].real), (wwpad[1:-1, 0:-2][zip(minima)].imag, wwpad[1:-1, 2:][zip(minima)].imag))) return zip(ww[minimas], insolution[minimas], bounds) def solve(self, wguess, k, bounds=((None, None), (None, None))): """Attempts to compute numerical convergence given a single frequency guess and fixed value of k. """ self.set_k(k) wr = wguess.real wi = wguess.imag wrbounds = bounds[0] wibounds = bounds[1] dwr = abs(wrbounds[1] - wrbounds[0])[0] if (wibounds[1] is None or wibounds[0] is None): wibounds = (np.array([wi*0.95, 0.0]), np.array([wi*1.05, 0.0])) dwi = abs(wibounds[1] - wibounds[0])[0] eps = min(dwr, dwi)*0.0001 def f(x): res = self.lib.evaluateDetM(20*(x[0] - 1.0)*dwr + wr, 20*(x[1] - 1.0)*dwi + wi) return np.abs(res) res = minimize(f, (1.0, 1.0), method='Nelder-Mead', options={'fatol': 1E-6, 'xatol': 1E-6, 'disp': False, 'maxiter':200}) return 20*(res['x'][0] - 1.0)*dwr + wr + 1.0j*(20*(res['x'][1] - 1.0)*dwi + wi), res['fun'] def roots(self, ww, k, insolution=None): """Finds roots for a given marginalization of complex frequencies and value of k. """ if insolution is None: insolution = self.marginalize(ww, k) candidates = self.identify(ww, k, insolution) roots = [] for candidate, insol, bounds in candidates: root, insol = self.solve(candidate, k, bounds) if insol>0.01: continue #if np.abs(root.imag)>np.abs(root.real)*0.1: # continue roots.append((root, insol)) return roots def growth(self, ww, k): roots = self.roots(ww, k) gamma = [0.0, 0.0, 1E200] for root, insol in roots: if root.imag<gamma[0]: continue gamma = (root.imag, root, insol) return gamma def polarization(self, w, k): wr = w.real wi = w.imag self.set_k(k) M = self.lib.evaluateM(wr, wi) eigenvalues, es = np.linalg.eig(M) es = es.T[np.argsort(np.abs(eigenvalues))] e1 = es[0] #solution direction e1 = e1/np.sum(np.abs(e1)**2)**0.5 ku = np.array((k[1], 0.0, k[0]))/(k[0]**2 + k[1]**2)**0.5 #propagation direction dop = np.arccos(np.abs(np.abs(e1).dot(ku))) #Degree of polarization theta = np.arctan2(k[1], k[0]) cos_theta = np.cos(theta) sin_theta = np.sin(theta) Ry = np.matrix(((cos_theta, 0.0, sin_theta), (0.0, 1.0, 0.0), (-sin_theta, 0.0, cos_theta))) e1r = Ry.dot(e1) #Now in basis where we can determine polarization px = e1r[0, 0] py = e1r[0, 1] phi = np.arctan2(np.abs(py), np.abs(px)) #orientation of polarization alpha_x = np.arctan2(px.imag, px.real) alpha_y = np.arctan2(py.imag, py.real) beta = alpha_y - alpha_x if beta > np.pi: beta = beta - 2*np.pi if beta < -np.pi: beta = beta + 2*np.pi if beta < -np.pi/2: beta -= 2*beta + np.pi if beta > np.pi/2: beta -= 2*beta - np.pi return dop, beta, phi def get_tensor_elements(self, w, k): wr = w.real wi = w.imag self.set_k(k) return self.lib.evaluateM(wr, wi) def get_dielectric_tensor_elements(self, w, k): wr = w.real wi = w.imag self.set_k(k) return self.lib.evaluateEps(wr, wi)
python
24
0.500454
152
42.078212
179
starcoderdata
import Taro, { Component } from '@tarojs/taro' import { View } from '@tarojs/components' import Banner from '../../components/main-banner' import Icons from '../../components/main-icon' import Commend from '../../components/main-comm' import Nomiss from '../../components/main-nomiss' import Festival from '../../components/main-festival' import Ticket from '../../components/main-ticket' import Commonwave from '../../components/common-wave' import './index.scss' export default class Index extends Component { constructor () { super(...arguments) this.state = { lists: null, } } componentDidMount() { this.requests().then((value) => { console.log('value:', value) const list = JSON.stringify(value); this.setState({ lists: list }) }) } async requests() { const reqs = await Taro.request({ url: 'http://t.weather.sojson.com/api/weather/city/101090201' }) console.log(reqs, '123456') return reqs } config = { navigationBarTitleText: '首页' } render () { return ( <View className='index'> <Banner /> <Icons /> <Ticket /> <Commend /> <Nomiss /> <Festival /> { this.state.lists } <Commonwave /> ) } }
javascript
16
0.586923
67
21.807018
57
starcoderdata
import React, {memo, useState, useEffect} from 'react'; import {Text, StyleSheet} from 'react-native'; import Background from '../components/Background'; import Button from '../components/Button'; import {logoutUser} from '../api/auth-api'; import BackButton from "../components/BackButton"; import firebase from "firebase/app"; import "firebase/auth"; import {getStatusBarHeight} from "react-native-status-bar-height"; import {Title} from "react-native-paper"; import {theme} from "../core/theme"; import RangeSlider from "rn-range-slider"; const Settings = ({navigation}) => { const user = firebase.auth().currentUser; const [priceRange, setPriceRange] = useState({low: 1, high: 3}); const userData = firebase.firestore().collection('users').doc(user.uid); useEffect(() => { if (user !== null) { userData.get().then( doc => doc.exists ? setPriceRange(doc.get('priceRange')) : setPriceRange({low: 1, high: 3})) .catch(err => { console.error(err); setPriceRange({low: 1, high: 3}) }) } }, [user]); return ( <BackButton goBack={() => navigation.navigate("Dashboard")}/> <Title style={styles.header}>Profile Settings Range <RangeSlider min={1} max={3} step={1} onValueChanged={(low, high) => setPriceRange({low: low, high: high})} /> <Button mode="outlined" onPress={() => logoutUser()}> Logout ); }; const styles = StyleSheet.create({ header: { fontSize: 26, color: theme.colors.primary, fontWeight: "bold", paddingVertical: 14, position: 'absolute', top: getStatusBarHeight() } }); export default memo(Settings);
javascript
24
0.566076
85
30.854839
62
starcoderdata
import unittest from identityshark.rule_matcher import compare_people, prepare_data class test_rule_matcher(unittest.TestCase): def test_compare_name(self): expected_matches = [(" " " (Jira)", " (" " " (Jira)", " ] expected_nonmatches = [(" " "robert", " (" " " (Jira)", "null"), (" " " (Jira)", None), ("Jane1", " "Jane2", " ("Tom (JIRA)", " "Tom"," ] frequent_emails = {" print("expected matches:") mistakes_matches = 0 for test_tuple in expected_matches: person_one = prepare_data("1", test_tuple[0],test_tuple[1], frequent_emails) person_two = prepare_data("2", test_tuple[2],test_tuple[3], frequent_emails) match = compare_people(person_one, person_two) if match>0: print("\tmatch (%i): (%s,%s)-(%s,%s)" % (match, test_tuple[0], test_tuple[1], test_tuple[2], test_tuple[3])) else: mistakes_matches = mistakes_matches+1 print("\tno match (%i): (%s,%s)-(%s,%s)" % (match,test_tuple[0],test_tuple[1],test_tuple[2],test_tuple[3])) print("expected non-matches:") mistakes_nonmatches = 0 for test_tuple in expected_nonmatches: person_1 = prepare_data("1", test_tuple[0], test_tuple[1], frequent_emails) person_2 = prepare_data("2", test_tuple[2], test_tuple[3], frequent_emails) match = compare_people(person_1, person_2) if match > 0: mistakes_nonmatches = mistakes_nonmatches+1 print("\tmatch (%i): (%s,%s)-(%s,%s)" % (match, test_tuple[0], test_tuple[1], test_tuple[2], test_tuple[3])) else: print("\tno match (%i): (%s,%s)-(%s,%s)" % (match,test_tuple[0], test_tuple[1], test_tuple[2], test_tuple[3])) self.assertEqual(0,mistakes_nonmatches+mistakes_matches, "%i incorrect non-matches (expected match); %i incorrect matches (expected non-match)" % (mistakes_matches,mistakes_nonmatches))
python
16
0.513147
153
53.111111
45
starcoderdata
def forward_seq(emis, tran, init, emitted_seq, num_states = 3, num_emits=None, nt2int = nt2intdict()): ## t, e, and i are np.matrix objects states = range(num_states) if num_emits == None: num_emits = len(emitted_seq) Forward = np.zeros([num_states,num_emits]) scalefactors = np.zeros([2,num_emits]) #initial Forward[:, 0] = np.multiply(init,emis[:,nt2int[emitted_seq[0]]]) ## scale to prevent underflow -- keep track of scaling scalefactors[0,0] = sum(Forward[:,0]) scalefactors[1,0] = np.log(scalefactors[0,0]) Forward[:,0] = Forward[:,0]/scalefactors[0,0] ## iterate for k in range(1, num_emits): emit = emis[:,nt2int[emitted_seq[k]]] Forward[:,k] = np.multiply(emit, np.dot(Forward[:,k-1],tran)) scalefactors[0,k] = sum(Forward[:,k]) scalefactors[1,k] = np.log(scalefactors[0,k]) + scalefactors[1,k-1] Forward[:,k] = Forward[:,k]/scalefactors[0,k] return Forward, scalefactors
python
13
0.619919
102
45.904762
21
inline
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<queue> #include<cmath> using namespace std; #define MAXN 200000 #define LL long long #define DB double #define FR first #define SE second int a[MAXN+5]; LL ans; LL L1[MAXN],L2[MAXN+5],R1[MAXN+5],R2[MAXN+5]; LL lsum[MAXN+5],rsum[MAXN+5]; int n; int get_num(int p) { if(p==0)return 0; if(p%2==1)return 1; return 2; } int main() { ans=1000000000; scanf("%d",&n); for(int i=1;i<=n;i++)scanf("%d",&a[i]); for(int i=1;i<=n;i++) lsum[i]=lsum[i-1]+a[i]; for(int i=n-1;i>=0;i--) rsum[i]=rsum[i+1]+a[i+1]; for(int i=1;i<=n;i++)a[i]=get_num(a[i]); for(int i=1;i<=n;i++) { if(a[i]==0)L1[i]=min(L1[i-1]+2,lsum[i]); else if(a[i]==1)L1[i]=min(L1[i-1]+1,lsum[i]); else L1[i]=min(L1[i-1],lsum[i]); if(a[i]==0)L2[i]=min(L1[i],min(L2[i-1]+1,lsum[i])); else if(a[i]==1)L2[i]=min(L1[i],min(L2[i-1],lsum[i])); else L2[i]=min(L1[i],min(L2[i-1]+1,lsum[i])); } for(int i=n-1;i>=0;i--) { if(a[i+1]==0)R1[i]=min(R1[i+1]+2,rsum[i]); else if(a[i+1]==1)R1[i]=min(R1[i+1]+1,rsum[i]); else R1[i]=min(R1[i+1],rsum[i]); if(a[i+1]==0)R2[i]=min(R1[i],min(R2[i+1]+1,rsum[i])); else if(a[i+1]==1)R2[i]=min(R1[i],min(R2[i+1],rsum[i])); else R2[i]=min(R1[i],min(R2[i+1]+1,rsum[i])); } for(int i=0;i<=n;i++) { //printf("%d %lld %lld\n",i,L1[i]+R2[i],L2[i]+R1[i]); ans=min(ans,min(L1[i]+R2[i],L2[i]+R1[i])); } printf("%lld\n",ans); }
c++
19
0.51254
64
25.827586
58
codenet
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Category; use Intervention\Image\Facades\Image; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Storage; class SettingsController extends Controller { public function index(){ $cats= Category::all(); ; $social= DB::table('social_links')->get(); $sections= DB::table('pages_content')->get(); return view('pages.features.settings',compact('cats','social','sections')); } public function changeBgVideo(Request $request){ $request->validate(['video'=>'file|mimes:mp4|required']); unlink(public_path('media/bg-video.mp4')); $request->file('video')->move(public_path('/media'),'bg-video.mp4'); return redirect()->back()->with('success','Video updated'); } public function changeLogo(Request $request){ $request->validate(['logo'=>'image|mimes:png|required|max:2048']); unlink(public_path('media/logo.png')); $request->file('logo')->move(public_path('/media'),'logo.png'); return redirect()->back()->with('success','Logo updated'); } public function updateSocialLink(Request $request,$id){ $request->validate([ 'name'=>'required|string|max:15', 'url'=>'required|url', ]); $active = $request->active ? 1:0; DB::table('social_links')->where('id',$id)->update([ 'name'=>$request->name, 'url'=>$request->url, 'active'=>$active, ]); return redirect()->back()->with('success','updated_succesfully'); } public function storeSocialLink(Request $request){ $request->validate([ 'name'=>'required|string|max:15', 'url'=>'required|string', 'icon'=>'required|image|mimes:png,jpg,svg|max:2048' ]); $filename = time() . "." . $request->file('icon')->getClientOriginalExtension(); $request->file('icon')->storeAs("public/logos", $filename); DB::table('social_links')->insert([ 'name'=>$request->name, 'url'=>$request->url, 'icon'=>$filename, ]); return redirect()->back()->with('success',trans('created_succesfully')); } public function destroySocialLink(Request $request,$id){ $filename=DB::table('social_links')->where('id',$id)->first()->icon; unlink(storage_path("app/public/logos/".$filename)); DB::table('social_links')->where('id',$id)->delete(); return redirect()->back()->with('success',trans('removed_succesfully')); } }
php
14
0.579775
88
29.340909
88
starcoderdata
const tap = require('tap'); const { tokenize, Operator } = require('../lib'); const tokens = tokenize('2sin(30) + (4 * 2)'); tap.equal(tokens.length, 5); // 2, *, sin(30), +, (4*2) tap.equal(tokens.join(' '), '2 * sin(30) + (4*2)'); tap.equal(tokenize('-(2) * -sqrt(4)').join(''), '-(2)*-sqrt(4)'); // because ! is an unknown operator // eslint-disable-next-line no-restricted-globals tap.throws(() => new Operator('!').perform(2, 1));
javascript
10
0.587699
65
35.583333
12
starcoderdata
// // Copyright © 2020 dahua. All rights reserved. // #import "LCUIKit.h" #import #import #import #import #import "UIDevice+LeChange.h" #import "LCLivePreviewDefine.h" #import "LCDeviceVideotapePlayManager.h" #import "LCLandscapeControlView.h" NS_ASSUME_NONNULL_BEGIN typedef enum : NSUInteger { LCVideotapePlayerControlPlay,///播放/暂停 LCVideotapePlayerControlClarity,///清晰度 LCVideotapePlayerControlTimes,///播放速度 LCVideotapePlayerControlVoice,///音频 LCVideotapePlayerControlFullScreen,///全屏 LCVideotapePlayerControlSnap,///截图 LCVideotapePlayerControlPVR,///录制 LCVideotapePlayerControlDownload///下载 } LCVideotapePlayerControlType; @interface LCVideotapePlayerPersenter : LCBasicPresenter /// 播放器 @property (copy, nonatomic) LCOpenSDK_PlayWindow * playWindow; /// 加载动画 @property (strong, nonatomic) UIImageView *loadImageview; /// 录像信息 @property (strong, nonatomic) LCDeviceVideotapePlayManager * videoManager; /// 横屏控制器 @property (weak, nonatomic) LCLandscapeControlView *landscapeControlView; @property (nonatomic) NSInteger sssdate; /// 重播按钮 @property (strong, nonatomic) LCButton *bigPlayBtn; ///// control @property (strong, nonatomic) LCButton * errorBtn; ///errorLab @property (strong, nonatomic) UILabel * errorMsgLab; /** 获取中间控制视图的子模块 @return 子模块列表 */ -(NSMutableArray *)getMiddleControlItems; /** 获取底部控制视图的子模块 @return 子模块列表 */ -(NSMutableArray *)getBottomControlItems; /** 根据Type获取按钮控件 @param type 按钮类型 */ - (LCButton *)getItemWithType:(LCVideotapePlayerControlType)type; //MARK: - Public Methods -(void)stopDownload; /** 进入前台处理 */ -(void)onActive:(id)sender; /** 进入后台处理 */ -(void)onResignActive:(id)sender; -(void)showVideoLoadImage; -(void)hideVideoLoadImage; /** 弹出输入音视频安全码弹窗 */ -(void)showPSKAlert:(BOOL)isPasswordError isPlay:(BOOL)isPlay; -(void)downLoad; -(void)showPlayBtn; -(void)hidePlayBtn; -(void)showErrorBtn; -(void)hideErrorBtn; -(void)configBigPlay; -(void)loadStatusView; @end NS_ASSUME_NONNULL_END
c
12
0.768067
166
19.34188
117
starcoderdata
# Copyright (c) 2016 Cisco Systems, Inc. # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from networking_vpp import etcdutils from networking_vpp import exceptions as vpp_exc from neutron.tests import base from testtools import ExpectedException from testtools import matchers OVERRIDE_PORT = 9999 class FakeConfig(object): def __init__(self, host, port, user, pw): self.etcd_host = host self.etcd_port = port self.etcd_user = user self.etcd_pass = pw self.etcd_insecure_explicit_disable_https = True self.etcd_cacert = None class TestAgentUtils(base.BaseTestCase): def parse_config_test_run(self, host, port, user=None, pw=None): fk = FakeConfig(host, port, user, pw) cf = etcdutils.EtcdClientFactory(fk) return cf.etcd_args['host'] def test_pass_user_password(self): # The defaults fk = FakeConfig('host', 1, None, None) cf = etcdutils.EtcdClientFactory(fk) self.assertThat(cf.etcd_args['username'], matchers.Equals(None)) self.assertThat(cf.etcd_args['password'], matchers.Equals(None)) # When set fk = FakeConfig('host', 1, 'uuu', 'ppp') cf = etcdutils.EtcdClientFactory(fk) self.assertThat(cf.etcd_args['username'], matchers.Equals('uuu')) self.assertThat(cf.etcd_args['password'], matchers.Equals(' def test_parse_empty_host_config(self): """Test parse_host_config with empty value """ with ExpectedException(vpp_exc.InvalidEtcHostConfig): self.parse_config_test_run('', OVERRIDE_PORT) def test_parse_fishy_host_config(self): """Test parse_host_config with non-string value """ with ExpectedException(vpp_exc.InvalidEtcHostsConfig): self.parse_config_test_run(1, OVERRIDE_PORT) with ExpectedException(vpp_exc.InvalidEtcHostsConfig): self.parse_config_test_run(None, OVERRIDE_PORT) with ExpectedException(vpp_exc.InvalidEtcHostConfig): self.parse_config_test_run(',', OVERRIDE_PORT) with ExpectedException(vpp_exc.InvalidEtcHostConfig): self.parse_config_test_run('host1,', OVERRIDE_PORT) with ExpectedException(vpp_exc.InvalidEtcHostConfig): self.parse_config_test_run(',host2', OVERRIDE_PORT) with ExpectedException(vpp_exc.InvalidEtcHostConfig): self.parse_config_test_run('host1,,host2', OVERRIDE_PORT) with ExpectedException(vpp_exc.InvalidEtcHostConfig): self.parse_config_test_run('host1:', OVERRIDE_PORT) with ExpectedException(vpp_exc.InvalidEtcHostConfig): self.parse_config_test_run('host1::123', OVERRIDE_PORT) with ExpectedException(vpp_exc.InvalidEtcHostConfig): self.parse_config_test_run('host1:123:123', OVERRIDE_PORT) with ExpectedException(vpp_exc.InvalidEtcHostConfig): self.parse_config_test_run('host1:123:', OVERRIDE_PORT) with ExpectedException(vpp_exc.InvalidEtcHostConfig): self.parse_config_test_run('host1:,host2', OVERRIDE_PORT) with ExpectedException(vpp_exc.InvalidEtcHostConfig): self.parse_config_test_run('host1::123,host2', OVERRIDE_PORT) with ExpectedException(vpp_exc.InvalidEtcHostConfig): self.parse_config_test_run('host1:123:123,host2', OVERRIDE_PORT) with ExpectedException(vpp_exc.InvalidEtcHostConfig): self.parse_config_test_run('host1:123:,host2', OVERRIDE_PORT) def test_parse_single_host_config(self): """Test parse_host_config with an IP or Host value """ ret = self.parse_config_test_run('192.168.1.10', OVERRIDE_PORT) self.assertThat(ret, matchers.Equals((('192.168.1.10', OVERRIDE_PORT),))) ret = self.parse_config_test_run('host1.lab1.mc', OVERRIDE_PORT) self.assertThat(ret, matchers.Equals((('host1.lab1.mc', OVERRIDE_PORT,),))) ret = self.parse_config_test_run('192.168.1.10:123', OVERRIDE_PORT) self.assertThat(ret, matchers.Equals((('192.168.1.10', 123,),))) ret = self.parse_config_test_run('host1.lab1.mc:123', OVERRIDE_PORT) self.assertThat(ret, matchers.Equals((('host1.lab1.mc', 123,),))) def test_parse_multi_host_config(self): """Test parse_host_config with multiple host-port values """ hosts = '192.168.1.10:1234,192.168.1.11:1235,192.168.1.12:1236' ret = self.parse_config_test_run(hosts, OVERRIDE_PORT) self.assertIsInstance(ret, tuple) self.assertThat(ret, matchers.Equals( (('192.168.1.10', 1234), ('192.168.1.11', 1235), ('192.168.1.12', 1236)) )) hosts = '192.168.1.10:1234,192.168.1.11,192.168.1.12:1236' ret = self.parse_config_test_run(hosts, OVERRIDE_PORT) self.assertIsInstance(ret, tuple) self.assertThat(ret, matchers.Equals( (('192.168.1.10', 1234), ('192.168.1.11', OVERRIDE_PORT), ('192.168.1.12', 1236)) )) def test_parse_single_host_invalid_config(self): """Test parse_host_config with invalid host-port value """ hosts = '192.168.1.10:fred,192.168.1.11,192.168.1.12:1236' with ExpectedException(vpp_exc.InvalidEtcHostConfig): self.parse_config_test_run(hosts, OVERRIDE_PORT) def test_parse_multi_host_invalid_config(self): """Test parse_host_config with invalid host-port value """ hosts = '192.168.1.10:fred,192.168.1.11,192.168.1.12:1236' with ExpectedException(vpp_exc.InvalidEtcHostConfig): self.parse_config_test_run(hosts, OVERRIDE_PORT) def test_parse_single_host_new_format(self): """Test parse_host_config with single host new format """ hosts = '192.168.1.10:1234' ret = self.parse_config_test_run(hosts, OVERRIDE_PORT) self.assertIsInstance(ret, tuple) self.assertThat(ret, matchers.Equals( (('192.168.1.10', 1234),) ))
python
13
0.6452
80
43.513333
150
starcoderdata
package com.gmail.stefvanschiedev.buildinggame.managers.arenas; import org.bukkit.configuration.file.YamlConfiguration; import com.gmail.stefvanschiedev.buildinggame.managers.files.SettingsManager; import com.gmail.stefvanschiedev.buildinggame.timers.VoteTimer; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; /** * This class handles all vote timers * * @since 2.3.0 */ public final class VoteTimerManager { /** * Loads/Reloads all vote timers for all arenas * * @since 2.3.0 */ @SuppressWarnings("MethodMayBeStatic") public void setup() { YamlConfiguration arenas = SettingsManager.getInstance().getArenas(); YamlConfiguration config = SettingsManager.getInstance().getConfig(); ArenaManager.getInstance().getArenas().forEach(arena -> { String name = arena.getName(); if (!arenas.contains(name + ".vote-timer")) arenas.set(name + ".vote-timer", config.getInt("timers.vote")); arena.setVoteTimer(new VoteTimer(arenas.getInt(name + ".vote-timer"), arena)); }); } /** * Constructs a new VoteTimerManager. This shouldn't be called to keep this class a singleton. */ private VoteTimerManager() {} /** * An instance of this class for the singleton principle */ private static final VoteTimerManager INSTANCE = new VoteTimerManager(); /** * Returns an instance of this singleton class * * @return an instance of this class * @since 2.3.0 */ @NotNull @Contract(pure = true) public static VoteTimerManager getInstance() { return INSTANCE; } }
java
19
0.698579
98
26.931034
58
starcoderdata
#include "pch.hpp" #include "pits.hpp" #include "ECS/Components/physicsComponents.hpp" #include "ECS/Components/objectsComponents.hpp" #include "ECS/Components/charactersComponents.hpp" #include "ECS/Components/graphicsComponents.hpp" #include "ECS/Components/simRegionComponents.hpp" namespace ph::system { using namespace component; void Pits::update(float dt) { PH_PROFILE_FUNCTION(); mRegistry.view<PitChunk, InsideSimRegion, BodyRect>().each([&] (const auto& pitChunk, auto, auto pitChunkBody) { // NOTE: KinematicCollisionBody is here to make player not fall into pits when we're using pf (player flying) terminal command mRegistry.view<BodyRect, BodyCircle, KinematicCollisionBody, InsideSimRegion> (entt::exclude<IsOnPlatform, CurrentlyDashing, FallingIntoPit>).each([&] (auto objectEntity, auto objectRect, auto objectCircle, auto, auto) { if(intersect(pitChunkBody, objectRect)) { for(const auto& pitBody : pitChunk.pits) { if(intersect(pitBody, objectRect, objectCircle)) { mRegistry.assign if(auto* rq = mRegistry.try_get rq->z = 188; return; } } } }); }); mRegistry.view<FallingIntoPit, BodyRect>().each([&] (auto entity, auto& falling, auto& body) { falling.timeToEnd -= dt; body.setSizeWithFixedCenter(Vec2(20.f) * falling.timeToEnd); if(falling.timeToEnd < 0.f) { DamageTag tag{1000, false}; mRegistry.assign_or_replace tag); mRegistry.remove } }); } }
c++
29
0.716276
128
27.709091
55
starcoderdata
const path = require('path'); const sh = require('shelljs'); const pkg = require('../package.json'); const dest = path.join(__dirname, '..', 'docs', 'api'); const distDest = path.join(dest, 'dist'); const exampleDest = path.join(dest, 'test-example'); const cleanupExample = function() { sh.rm('-rf', distDest); sh.rm('-rf', exampleDest); sh.rm('-rf', path.join(dest, 'node_modules')); }; const generateExample = function({skipBuild} = {}) { // run the build if (!skipBuild) { sh.exec('npm run build'); } // make sure that the example dest is available sh.mkdir('-p', exampleDest); // copy the `dist` dir sh.cp('-R', 'dist', path.join(dest, 'dist')); sh.rm(path.join(dest, 'dist', `video-js-${pkg.version}.zip`)); const filepaths = sh.find(path.join(__dirname, '..', 'sandbox', '**', '*.*')) .filter((filepath) => path.extname(filepath) === '.example'); // copy the sandbox example files filepaths.forEach(function(filepath) { const p = path.parse(filepath); sh.cp(filepath, path.join(exampleDest, p.name)); }); }; module.exports = { cleanupExample, generateExample };
javascript
9
0.631034
79
25.976744
43
starcoderdata
import tweepy import time import csv import codecs import json import xlsxwriter from tweepy import OAuthHandler access_token = " access_token_secret = " consumer_key = "nBxlK3FCdrf14fb8nNMslMUJU" consumer_secret = " # Creating the authentication object auth = tweepy.OAuthHandler(consumer_key, consumer_secret) # Setting your access token and secret auth.set_access_token(access_token, access_token_secret) # Creating the API object while passing in auth information api = tweepy.API(auth,wait_on_rate_limit=True) #f3 = codecs.open("C:/Users/mudasirw/Documents\DATA-mudasir/keyword-based-users-extracted.xlsx", 'w', encoding='utf-8'); for pages in tweepy.Cursor(api.search,q="(*)",lang="ar",tweet_mode='extended').pages(): #for pages in tweepy.Cursor(api.search,q="war",lang="en", tweet_mode='extended').pages(): #print (tweet.created_at, tweet.text.encode('utf-8')) #print tweet.in_reply_to_status_id for tweet in pages: if((tweet.in_reply_to_status_id is None) and not(tweet.full_text[:2]=="RT")): print(tweet.created_at) print(tweet.user.screen_name) print(tweet.full_text) print(tweet.retweeted) print("....................") # csvWriter.writerow((tweet.user.screen_name, tweet.created_at, tweet.full_text.encode('utf-8'))) # File_object.write(str(tweet.user.screen_name)+"\t"+str(tweet.created_at)+"\t"+str(tweet.full_text.encode('utf-8-sig'))+"\n") # f3.write(str(tweet.user.screen_name) + "\t" + str(tweet.created_at) + "\t" + str(tweet.full_text.encode('utf-8-sig')) + "\n") workbook = xlsxwriter.Workbook('C:/Users/mudasirw/Documents\DATA-mudasir/tweet_new.xlsx') worksheet = workbook.add_worksheet() row = 0 col = 0 worksheet.write(row, col, user) worksheet.write(row, col + 1, tweet) row += 1 workbook.close() print("**********************") ''' print(tweet.created_at) print("......................") print(tweet.full_text) print("###############") #print tweet.author._json['screen_name'] print tweet.user.screen_name print "......................" csvWriter.writerow([(tweet.user.screen_name,tweet.created_at)]) '''
python
13
0.618699
137
36.733333
60
starcoderdata
#include "DiscobusData485.h" DiscobusData485::DiscobusData485(volatile uint8_t de_pin_num, volatile uint8_t* de_ddr_register, volatile uint8_t* de_port_register): de_pin(de_pin_num), de_ddr(de_ddr_register), de_port(de_port_register) { *de_ddr |= (1 << de_pin_num); *de_port &= ~(1 << de_pin_num); } void DiscobusData485::enable_write() { *de_port |= (1 << de_pin); } void DiscobusData485::enable_read() { flush(); *de_port &= ~(1 << de_pin); } void DiscobusData485::write(uint8_t b) { DiscobusDataUart::write(b); }
c++
8
0.521569
71
27.333333
27
starcoderdata
import logging from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from django.contrib.auth.hashers import check_password logger = logging.getLogger('django.console') User = get_user_model() class SettingsBackend(ModelBackend): username = 'ivan' #username = 'client' email = ' password = ' def authenticate(self, request, username=None, password=None, **kwargs): login_valid = (self.username == username) if not login_valid: email = kwargs.get('email', username) email_valid = (self.email == email) else: email = self.email email_valid = True pwd_valid = check_password(password, self.password) if (login_valid or email_valid) and pwd_valid: try: user = User.objects.get(email=email) logger.debug('SettingsBackend login admin') except User.DoesNotExist: # Create a new user. There's no need to set a password # because only the password from settings.py is checked. user = User(name=self.username, email=self.email, password=self.password) user.is_active = True user.is_admin = True user.save() logger.debug('SettingsBackend admin create and login') return user return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None
python
16
0.599625
89
31.673469
49
starcoderdata
<?php /* * Copyright (c) 2005 Regents of The University of Michigan. * All Rights Reserved. See COPYRIGHT. */ require_once( 'config.php' ); if ( preg_match( "/[^a-f0-9]/", $_GET['sessionid'] ) !== 0 ) { exit(); } $rawUpload = @file_get_contents( $upload_session_tmp . $_GET['sessionid'] ); $upload = explode( ':', $rawUpload ); $totalBytes = ( isset( $upload[1] )) ? (int) $upload[1] : 0; $bytesUploaded = ( isset( $upload[2] )) ? (int) $upload[2] : 0; $formatUploaded = formatBytes( $bytesUploaded ); $formatTotal = formatBytes( $totalBytes ); if ( $bytesUploaded > 0 && $totalBytes > 0 ) { $percent = ( $bytesUploaded / $totalBytes ) * 100; } else { $percent = 0; } $formatPercent = round( $percent ); // Display file sizes in a user-friendly format function formatBytes( $bytes ) { if ( $bytes >= 1073741824 ) { return round( $bytes / 1073741824, 2 ) . ' GB'; } else if ( $bytes >= 1048576 ) { return round( $bytes / 1048576, 2 ) . ' MB'; } else if ( $bytes >= 1024 ) { return round( $bytes / 1024, 2 ) . ' KB'; } else if ( $bytes > 0 && $bytes < 1024 ) { return $bytes . ' Bytes'; } else { return "0 Bytes"; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="refresh" content="1; url="progress.php?sessionid=<?= $_GET['sessionid']; ?>" /> Document <style type="text/css"> <!-- body { font-family: Verdana, Arial, Helvetica, Geneva, sans-serif; font-size: 12px; background-color: #ffffcc; color: #666666; } --> <div style="width: 85%; height: 20px; border: 1px solid #cccccc; padding: 1px; margin: 15px auto 15px auto;"> <div style="width: <?= $percent; ?>%; height: 20px; background-color: #336699;"> <table width="100%"> <?= $formatUploaded . ' / ' . $formatTotal; ?> <td align="right"><?= $formatPercent; ?> %
php
16
0.575665
121
29.986486
74
starcoderdata
import Component from '@ember/component'; import layout from './template'; import { inject as service } from '@ember/service'; import { A } from '@ember/array'; import $ from 'jquery'; const NOTIFICATION_DELAY = 10 * 1000; // Default 10 seconds export default Component.extend({ layout, notificationHandler: service('notification-handler'), notifications: A([null,null,null,null,null]), slot: 0, clearNotif(slot) { const elem = $(`#notif_${slot}`); elem.transition('fly down'); const notifs = this.get('notifications').toArray(); notifs[slot] = null; this.set('notifications', notifs); }, addNotif(notif, slot) { const notifs = this.get('notifications').toArray(); notifs[slot] = notif; this.set('notifications', notifs); const elem = $(`#notif_${slot}`); elem.transition('fly up'); }, beginNotificationTimeout(slot) { window.setTimeout(this.clearNotif.bind(this, slot), NOTIFICATION_DELAY); }, actions: { toggleNotification() { let notification = this.get('notificationHandler').getNotification(); let notifs = this.get('notifications').toArray(); let nextSlot = this.get('slot'); if (notifs && notifs[nextSlot]) { this.clearNotif(nextSlot); } let newNotif = { header: notification.header, message: notification.message, }; this.addNotif(newNotif, nextSlot); this.beginNotificationTimeout(nextSlot); this.set('slot', (nextSlot+1)%5); } } });
javascript
16
0.606231
78
25.75
60
starcoderdata
def findCornerDistanceHandler(): global stopCountdown, forwardIntegral def log1(*msg): logArgs(*((formatArgL(" dt", round(deltaTime, 3), 5), formatArgR(" ld", distance1, 5), formatArgR(" fdd", deltaDistance1, 5), formatArgR(" rd", distance2, 5), formatArgR(" sdd", deltaDistance2, 5)) + msg)) dt = deltaTime forwardDistance = distance1 + distance2 forwardDelta = - math.sqrt(deltaDistance1 * deltaDistance1 + deltaDistance2 * deltaDistance2) if abs(forwardDelta) < 20: forwardIntegral += forwardDelta else: forwardIntegral = 0 if stopCountdown > 0: log1(formatArgR("s", round(0, 1), 4), formatArgR("a", round(0, 1), 3)) drive(0, 0) stopCountdown -= 1 if stopCountdown == 0: stop() elif distance1 * distance1 + distance2 * distance2 < CORNER_STOP_DISTANCE * CORNER_STOP_DISTANCE: # stop() stopCountdown = 3 else: forwardError = math.sqrt(distance1 * distance1 + distance2 * distance2) - CORNER_STOP_DISTANCE forwardSpeed = forwardGains[KGAIN_INDEX] * (forwardError * forwardGains[KpI] - forwardIntegral * forwardGains[KiI] + (forwardDelta / dt) * forwardGains[KdI]) forwardSpeed = normalise(forwardSpeed, MAX_FORWARD_SPEED) * MAX_FORWARD_SPEED if abs(distance1 - distance2) > 1: # and distance1 < 380 and distance2 < 380: angle = int(math.log10(abs(distance1 - distance2)) * KA) * sign(distance1 - distance2) else: angle = 0 drive(angle, forwardSpeed) log1(" CORN ", formatArgR("s", round(forwardSpeed, 1), 6), formatArgR("a", round(angle, 1), 5), formatArgR("e", round(forwardError), 5), formatArgR("i", round(forwardIntegral, 1), 6), formatArgR("fwd", round(forwardDelta), 6))
python
19
0.628135
234
43.756098
41
inline
package cass.rollup.processors.v2.graph.collapser; public class PacketRelation { private RelationType.RELATION_TYPE type; private NodePacket source; private NodePacket target; public PacketRelation(NodePacket source, NodePacket target, RelationType.RELATION_TYPE type) { this.source = source; this.target = target; this.type = type; } public NodePacket getSource() {return source;} public void setSource(NodePacket source) {this.source = source;} public NodePacket getTarget() {return target;} public void setTarget(NodePacket target) {this.target = target;} public RelationType.RELATION_TYPE getType() {return type;} public void setType(RelationType.RELATION_TYPE type) {this.type = type;} public String toString() { return getSource().toString() + " >>" + getType() + "<< " + getTarget().toString(); } }
java
13
0.670996
98
32.222222
27
starcoderdata
//Rest the value when reply-dialog-box dismiss function undo_reply() { $('#follow_id').val(-1); $('#follow').val(""); } $("#content").on('input', function () { var contentStr = $("#content").val().replace(/\s+/g, ""); if (contentStr == "") { undo_reply() } }) function go_to_reply(id, author_name) { var nav = $('#submit-comment'); if (nav.length) { $('html, body').animate({scrollTop: nav.offset().top}, 800); $('#follow_id').val(id); $('#follow').val(author_name); $('#content').text("@" + author_name + " ") } } //Reset the follow value when refresh page window.onload = function () { $('#follow_id').val(-1); $('#follow').val(""); }
javascript
19
0.531292
68
22.46875
32
starcoderdata
private static void processDeclareRoles(WebApp webApp, AbstractFinder classFinder) throws DeploymentException { log.debug("processDeclareRoles(): Entry: webApp: " + webApp.toString()); List<Class<?>> classesWithDeclareRoles = classFinder.findAnnotatedClasses(DeclareRoles.class); // Class-level annotation for (Class cls : classesWithDeclareRoles) { DeclareRoles declareRoles = (DeclareRoles) cls.getAnnotation(DeclareRoles.class); if (declareRoles != null && Servlet.class.isAssignableFrom(cls)) { addDeclareRoles(webApp, declareRoles, cls); } } // Validate deployment descriptor to ensure it's still okay // validateDD(new AnnotatedWebApp(webApp)); log.debug("processDeclareRoles(): Exit: webApp: " + webApp.toString()); }
java
11
0.674144
111
46.111111
18
inline
import React, {Fragment} from "react"; import Header from '../components/Header'; import LeftNav from '../components/LeftNav'; import RightChat from '../components/RightChat'; import AppFooter from '../components/AppFooter'; import PopupChat from '../components/PopupChat'; import ProfileDetail from '../components/ProfileDetail'; import ProfilePhoto from '../components/ProfilePhoto'; import ProfileCardThree from '../components/ProfileCardThree'; import CreatePost from '../components/CreatePost'; import Events from '../components/Events'; import PostView from '../components/PostView'; import Load from '../components/Load'; const UserPage = () => ( <div className="main-content right-chat-active"> <div className="middle-sidebar-bottom"> <div className="middle-sidebar-left pe-0"> <div className="row"> <div className="col-xl-12 mb-3"> <div className="col-xl-4 col-xxl-3 col-lg-4 pe-0"> <div className="col-xl-8 col-xxl-9 col-lg-8"> <PostView id="32" postvideo="" postimage="post.png" avater="user.png" user=" time="22 min ago" des="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi nulla dolor, ornare at commodo non, feugiat non nisi. Phasellus faucibus mollis pharetra. Proin blandit ac massa sed rhoncus."/> <PostView id="31" postvideo="" postimage="post.png" avater="user.png" user=" time="22 min ago" des="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi nulla dolor, ornare at commodo non, feugiat non nisi. Phasellus faucibus mollis pharetra. Proin blandit ac massa sed rhoncus."/> <PostView id="33" postvideo="" postimage="post.png" avater="user.png" user=" time="2 hour ago" des="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi nulla dolor, ornare at commodo non, feugiat non nisi. Phasellus faucibus mollis pharetra. Proin blandit ac massa sed rhoncus."/> ); export default UserPage;
javascript
11
0.63317
220
41.964912
57
starcoderdata
[HttpPost] [Authorize] [ValidateAntiForgeryToken] public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var ignore = new ApplicationUser { UserName = model.Email, Email = model.Email }; //lets add him to database this.PlayerStore.CreatePlayer(this.User); } return Redirect("http://localhost:4200"); }
c#
14
0.55971
133
38.52381
21
inline
def printDebug(text): """ standardized debug message """ if not debug: return if writeOut is True: try: f = open(outFile, "a") f.write(" !!! DEBUG: "+text+"\n") f.close() except: print "write error" sys.stderr.write(colorString("!!! DEBUG: "+text,"yellow")+"\n")
python
13
0.604895
64
19.5
14
inline
// // ZYWeakTimer.h // // Created by Zy on 18/3/5. // Copyright © 2016年 Zy. All rights reserved. // #import typedef void(^TimerHandler)(id _Nullable userInfo); @interface ZYWeakTimer : NSObject + (NSTimer *_Nonnull)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id _Nullable )aTarget selector:(SEL _Nullable )aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo; + (NSTimer *_Nullable)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id _Nullable )aTarget block:(TimerHandler _Nonnull )block userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo; @end
c
5
0.766613
191
31.473684
19
starcoderdata
def convexhull(x, y, rep=1, nprev=0): """RETURNS THE CONVEX HULL OF x, y THAT IS, THE EXTERIOR POINTS""" x = x.astype(float) y = y.astype(float) x, y = CCWsort(x, y) xo = mean(x) yo = mean(y) x = x.tolist() y = y.tolist() dmax = max([p2p(x), p2p(y)]) ngood = 0 while ngood < len(x)+1: dx = x[1] - xo dy = y[1] - yo dr = hypot(dx, dy) dx = dx * dmax / dr dy = dy * dmax / dr x1 = xo - dx y1 = yo - dy if not outside(x[:3], y[:3], x1, y1): del x[1] del y[1] else: # ROTATE THE COORD LISTS x.append(x.pop(0)) y.append(y.pop(0)) ngood += 1 x = array(x) y = array(y) # REPEAT UNTIL CONVERGENCE if (nprev == 0) or (len(x) < nprev): x, y = convexhull(x, y, nprev=len(x)) if rep: x = concatenate((x, [x[0]])) y = concatenate((y, [y[0]])) return x, y
python
13
0.446043
45
23.35
40
inline
/* * Copyright 2021 Allette Systems (Australia) * http://www.allette.com.au * * 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.pageseeder.ox.psml.validation; import org.pageseeder.ox.api.Downloadable; import org.pageseeder.ox.core.Model; import org.pageseeder.ox.core.PackageData; import org.pageseeder.ox.core.ResultStatus; import org.pageseeder.ox.psml.util.ReportsBuilder; import org.pageseeder.ox.tool.ResultBase; import org.pageseeder.xmlwriter.XMLWriter; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class ValidationStepResult extends ResultBase implements Downloadable { private Map<String, ValidationResult> _results = new HashMap<>(); private final String _output; private String error = null; public ValidationStepResult(Model m, PackageData p, String output) { super(m, p); this._output = output; } public void addResults(String name, ValidationResult results) { this._results.put(name, results); if (results.hasErrors()) setStatus(ResultStatus.ERROR); } public void finished() { if (this._output != null && this._output.endsWith(".psml")) this.error = ReportsBuilder.createPSMLReport(downloadPath(), this._results, this.status()); if (this._output != null && this._output.endsWith(".csv")) this.error = ReportsBuilder.createCSVReport(downloadPath(), this._results); done(); } @Override public boolean isDownloadable() { return this._output != null && error == null; } @Override public void toXML(XMLWriter xml) throws IOException { xml.openElement("result"); xml.attribute("id", data().id()); xml.attribute("model", model().name()); xml.attribute("status", status().toString().toLowerCase()); xml.attribute("time", Long.toString(time())); xml.attribute("downloadable", isDownloadable() ? "true" : "false"); if (this._output != null) xml.attribute("path", data().getPath(downloadPath())); if (this._results.size() == 1) xml.attribute("input", this._results.keySet().iterator().next()); if (this.error != null) xml.attribute("error", this.error); if (this._results != null) { // add infos for the UI xml.openElement("infos"); xml.attribute("name", "validation"); if (this._results.size() == 1) { ValidationResult r = this._results.values().iterator().next(); xml.openElement("info"); xml.attribute("name", "validated"); xml.attribute("value", r.isValidated() ? "true" : "false"); xml.attribute("type", "string"); xml.closeElement(); xml.openElement("info"); xml.attribute("name", "valid"); xml.attribute("value", r.hasErrors() ? "false" : "true"); xml.attribute("type", "string"); xml.closeElement(); if (r.hasErrors()) { xml.openElement("info"); xml.attribute("name", "number errors"); xml.attribute("value", r.errors().size()); xml.attribute("type", "string"); xml.closeElement(); } } else { int valid = 0; int invalid = 0; for (ValidationResult r : this._results.values()) { if (r.hasErrors()) invalid++; else valid++; } xml.openElement("info"); xml.attribute("name", "total documents"); xml.attribute("value", this._results.size()); xml.attribute("type", "string"); xml.closeElement(); xml.openElement("info"); xml.attribute("name", "valid documents"); xml.attribute("value", String.valueOf(valid)); xml.attribute("type", "string"); xml.closeElement(); xml.openElement("info"); xml.attribute("name", "invalid documents"); xml.attribute("value", String.valueOf(invalid)); xml.attribute("type", "string"); xml.closeElement(); } xml.closeElement(); // infos } xml.closeElement(); // result } @Override public File downloadPath() { return data().getFile(this._output); } }
java
17
0.64116
100
35.11811
127
starcoderdata
/** * Copyright (C) 2012 Ness Computing, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nesscomputing.httpclient.testing; import static com.nesscomputing.httpclient.internal.HttpClientMethod.GET; import static com.nesscomputing.httpclient.internal.HttpClientMethod.PUT; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.net.URI; import java.util.Collections; import java.util.List; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.junit.Test; import com.nesscomputing.httpclient.HttpClient; import com.nesscomputing.httpclient.HttpClientRequest; import com.nesscomputing.httpclient.HttpClientResponse; import com.nesscomputing.httpclient.internal.HttpClientBodySource; import com.nesscomputing.httpclient.internal.HttpClientMethod; /** * This pretty well doubles as an example use case of the {@link TestingHttpClientBuilder}. */ public class TestingHttpClientBuilderTest { private final CapturingHttpResponseHandler handler = new CapturingHttpResponseHandler(); @Test(expected=IllegalStateException.class) public void testEmptyClient() throws Exception { TestingHttpClientBuilder builder = new TestingHttpClientBuilder(); HttpClient httpClient = builder.build(); httpClient.get("/", handler).perform(); } @Test public void testSimpleResponse() throws Exception { TestingHttpClientBuilder builder = new TestingHttpClientBuilder(); builder.on(GET).of("/whozamit").respondWith(Response.noContent()); builder.on(GET).of("/foo").respondWith(Response.ok("bar")); builder.on(GET).of("/").respondWith(Response.status(Status.NOT_FOUND)); HttpClient httpClient = builder.build(); HttpClientResponse response = httpClient.get("/whozamit", handler).perform(); assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatusCode()); response = httpClient.get("/foo", handler).perform(); assertEquals(Status.OK.getStatusCode(), response.getStatusCode()); assertEquals("OK", response.getStatusText()); assertEquals(Long.valueOf(3), response.getContentLength()); assertEquals(MediaType.TEXT_PLAIN, response.getContentType()); assertEquals("bar", IOUtils.toString(response.getResponseBodyAsStream(), "UTF-8")); response = httpClient.get("/", handler).perform(); assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatusCode()); } @Test public void testJsonResponse() throws Exception { ObjectMapper mapper = new ObjectMapper(); TestingHttpClientBuilder builder = new TestingHttpClientBuilder().withObjectMapper(mapper); Map<String, String> superImportantMap = Collections.singletonMap("foo", "bar"); builder.on(GET).of("/json").respondWith(Response.ok(superImportantMap)); HttpClient httpClient = builder.build(); HttpClientResponse response = httpClient.get("/json", handler).perform(); assertEquals(Status.OK.getStatusCode(), response.getStatusCode()); assertEquals(MediaType.APPLICATION_JSON, response.getContentType()); Map<String, String> result = mapper.readValue(response.getResponseBodyAsStream(), new TypeReference<Map<String, String>>() {}); assertEquals(superImportantMap, result); } @Test public void testBinaryData() throws Exception { byte[] data = DigestUtils.sha("There's no dark side of the moon, really. Matter of fact it's all dark."); TestingHttpClientBuilder builder = new TestingHttpClientBuilder(); builder.on(GET).of("/").respondWith(Response.ok(data)); HttpClient httpClient = builder.build(); HttpClientResponse response = httpClient.get("/", handler).perform(); assertEquals(MediaType.APPLICATION_OCTET_STREAM, response.getContentType()); assertArrayEquals(data, IOUtils.toByteArray(response.getResponseBodyAsStream())); } @Test public void testIOExcetionResponse() throws Exception { TestingHttpClientBuilder builder = new TestingHttpClientBuilder(); builder.on(GET).of("/exception").respondWith(new IOException("danger")); HttpClient httpClient = builder.build(); boolean thrown = false; try { httpClient.get("/exception", handler).perform(); fail("should throw"); } catch (IOException e) { assertEquals("danger", e.getMessage()); thrown = true; } assertTrue("should throw", thrown); } @Test public void testCustomMatcherAndGenerator() throws Exception { TestingHttpClientBuilder builder = new TestingHttpClientBuilder(); RequestMatcher matcher = new RequestMatcher() { @Override public boolean apply(HttpClientRequest input) { try { Integer.parseInt(input.getUri().getPath().substring(1)); } catch (NumberFormatException e) { return false; } return true; } }; ResponseGenerator generator = new ResponseGenerator { @Override public HttpClientResponse respondTo(HttpClientRequest request) { HttpClientResponse response = createMock(HttpClientResponse.class); expect(response.getStatusCode()).andReturn( Integer.parseInt(request.getUri().getPath().substring(1))).anyTimes(); replay(response); return response; } }; builder.whenMatches(matcher).respondWith(generator); HttpClient httpClient = builder.build(); HttpClientResponse response = httpClient.get("/563", handler).perform(); assertEquals(563, response.getStatusCode()); try { httpClient.get("/asdf", handler).perform(); fail(); } catch (IllegalStateException e) { // Expected } } @Test public void testPut() throws Exception { TestingHttpClientBuilder builder = new TestingHttpClientBuilder(); builder.on(PUT).of("/sandwich").respondWith(new ResponseGenerator { @Override public HttpClientResponse respondTo(HttpClientRequest request) throws IOException { final Response response; HttpClientBodySource body = request.getHttpBodySource(); if (body != null && "sudo".equals(IOUtils.toString(body.getContent(), "UTF-8"))) { response = Response.created(URI.create("ok://sandwich")).build(); } else { response = Response.status(Status.FORBIDDEN).build(); } return new JaxRsResponseHttpResponseGenerator(null, response).respondTo(request); } }); HttpClient httpClient = builder.build(); HttpClientResponse response = httpClient.put("/sandwich", handler).perform(); assertEquals(Status.FORBIDDEN.getStatusCode(), response.getStatusCode()); response = httpClient.put("/sandwich", handler).setContent("sudo").perform(); assertEquals(Status.CREATED.getStatusCode(), response.getStatusCode()); assertEquals("ok://sandwich", response.getHeader("Location")); } @Test public void testGetHeaderAndGetHeaders() throws Exception { TestingHttpClientBuilder builder = new TestingHttpClientBuilder(); builder.on(HttpClientMethod.GET).of("out").respondWith( Response.status(500) .header("Connection", "closed") .header("Content-Type", "application/json; charset=bogus") .header("Content-Language", "klingon") .header("MAGIC", "a") .header("MAGIC", "b") .header("MAGIC", "c") .entity("{\"a\":\"okay\"}")); HttpClient http = builder.build(); HttpClientResponse res = http.get("out", handler).perform(); String header = res.getHeader("bogus"); assertEquals(null, header); List headers = res.getHeaders("bogus"); assertEquals(null, headers); header = res.getHeader("Content-Language"); assertEquals("klingon", header); headers = res.getHeaders("Content-Language"); assertEquals(Lists.newArrayList("klingon"), headers); header = res.getHeader("magic"); assertEquals("a", header); headers = res.getHeaders("magic"); assertEquals(Lists.newArrayList("a","b","c"), headers); } }
java
22
0.669501
135
42.382222
225
starcoderdata
'use strict'; nyplViewer.factory('FirebaseStorageModel', function (firebase, Auth, $q) { var factory = this; return { deleteSelectedTheme: function (theme) { console.log(theme); var firebaseUser = Auth.authObj.$getAuth(); firebase.database().ref('users').child(firebaseUser.uid).child("themes").child(theme.id).remove(); }, saveSelectedTheme: function (theme) { var firebaseUser = Auth.authObj.$getAuth(); firebase.database().ref('users').child(firebaseUser.uid).child("selectedTheme").set(theme); //some more user data }, getUserInfo: function () { var firebaseUser = Auth.authObj.$getAuth(); return firebase.database().ref('users').child(firebaseUser.uid).once('value').then(function (snapshot) { var user = snapshot.val(); return user; }) }, getThemes: function () { var firebaseUser = Auth.authObj.$getAuth(); return firebase.database().ref('users').child(firebaseUser.uid).child("themes").once('value').then(function (snapshot) { //firebase.database().ref('themes').once('value').then(function (snapshot) { var themes = snapshot.val(); return themes; }) }, getSubmittedThemes: function () { var firebaseUser = Auth.authObj.$getAuth(); return firebase.database().ref("submittedThemes").once('value').then(function (snapshot) { //firebase.database().ref('themes').once('value').then(function (snapshot) { var getSubmittedThemes = snapshot.val(); return getSubmittedThemes; }) }, getDefaultThemes: function () { var firebaseUser = Auth.authObj.$getAuth(); return firebase.database().ref("defaultThemes").once('value').then(function (snapshot) { //firebase.database().ref('themes').once('value').then(function (snapshot) { var themes = snapshot.val(); return themes; }) }, createTheme: function (theme) { var firebaseUser = Auth.authObj.$getAuth(); var themesRef = firebase.database().ref('users').child(firebaseUser.uid).child("themes").push(); themesRef.set(theme); var submittedThemesRef = firebase.database().ref("submittedThemes").push(); submittedThemesRef.set(theme); //some more user data }, createDefaultTheme: function (theme) { var firebaseUser = Auth.authObj.$getAuth(); var themesRef = firebase.database().ref("defaultThemes").push(); themesRef.set(theme); //some more user data }, deleteSubmittedTheme: function (theme) { var firebaseUser = Auth.authObj.$getAuth(); firebase.database().ref("submittedThemes").child(theme.id).remove(); }, editDefaultTheme: function (theme) { var firebaseUser = Auth.authObj.$getAuth(); var id = theme.id; delete theme.id; firebase.database().ref("defaultThemes").child(id).set(theme); }, editTheme: function (theme) { var firebaseUser = Auth.authObj.$getAuth(); var id = theme.id; delete theme.id; firebase.database().ref('users').child(firebaseUser.uid).child("themes").child(id).set(theme); }, } });
javascript
24
0.561281
132
43.8875
80
starcoderdata
const { getName, setName } = require('./2-1-module'); console.log(getName()); console.log(setName('Alessandra')); console.log(getName()); /* default undefined Alessandra */
javascript
4
0.697297
53
15.909091
11
starcoderdata
func (b *Body) use(s has.Slotable, usage usageBits) bool { if b == nil { return false } what := s.Parent() refs := s.Slots() nextRef: for _, ref := range refs { for x, s := range b.slots { if s.ref == ref && s.used == nil && s.usage&missing == 0 { b.slots[x].used = what b.slots[x].usage |= usage continue nextRef } } // Failed to assign all slots, so undo the slots we did assign. b.Remove(what) return false } return true }
go
15
0.591398
65
18.416667
24
inline
void vtkHyperTreeGridToDualGrid::GenerateDualCornerFromLeaf1D( vtkHyperTreeGridNonOrientedMooreSuperCursor* cursor, vtkHyperTreeGrid *input) { // With d=1: // (d-0)-faces are corners, neighbor cursors are 0 and 2 // (d-1)-faces do not exist // (d-2)-faces do not exist // Retrieve neighbor (left/right) cursors vtkSmartPointer<vtkHyperTreeGridOrientedGeometryCursor> cursorL = cursor->GetOrientedGeometryCursor( 0 ); vtkSmartPointer<vtkHyperTreeGridOrientedGeometryCursor> cursorR = cursor->GetOrientedGeometryCursor( 2 ); // Retrieve cursor center coordinates double pt[3]; cursor->GetPoint( pt ); // Check across d-face neighbors whether point must be adjusted if ( ! cursorL->HasTree() ) { // Move to left corner pt[input->GetOrientation()] -= .5 * cursor->GetSize()[input->GetOrientation()];; } if ( ! cursorR->HasTree() ) { // Move to right corner pt[input->GetOrientation()] += .5 * cursor->GetSize()[input->GetOrientation()];; } // Retrieve global index of center cursor vtkIdType id = cursor->GetGlobalNodeIndex(); // Insert dual point at center of leaf cell this->Points->SetPoint( id, pt ); // Storage for edge vertex IDs: dual cell ownership to cursor with higher index vtkIdType ids[2]; ids[0] = id; // Check whether a dual edge to left neighbor exists if ( cursorL->HasTree() && cursorL->IsLeaf() ) { // If left neighbor is a leaf, always create an edge ids[1] = cursorL->GetGlobalNodeIndex(); this->Connectivity->InsertNextTypedTuple( ids ); } // Check whether a dual edge to right neighbor exists if ( ( cursorR->HasTree() && cursorR->IsLeaf() ) && cursorR->GetLevel() != cursor->GetLevel() ) { // If right neighbor is a leaf, create an edge only if right cell at higher level ids[1] = cursorR->GetGlobalNodeIndex(); this->Connectivity->InsertNextTypedTuple( ids ); } }
c++
12
0.689366
140
34.37037
54
inline
fn identify_addr(&mut self, addr: Multiaddr) { match self.inner.match_pid(&addr) { // Only add identified addr to connected peer, offline peer address // maybe outdated Some(ref pid) if self.inner.peer_connected(pid) => self.inner.add_peer_addr(&pid, addr), // Match an offline peer, noop, peer maybe next connection condidate Some(_) => (), _ => { info!( "network: {:?}: discover unknown addr {}", self.peer_id, addr ); self.unknown_addrs.insert(UnknownAddr::new(addr)); } } }
rust
13
0.497015
100
38.470588
17
inline
var getTargetArch = require('./index.js').default describe(getTargetArch, function() { it.each([ ['I386', 0x14c], ['AMD64', 0x8664], ])('detects %s', function(expectedArchName, expectedArchCode, done) { getTargetArch('./test.' + expectedArchName + '.dll', function(err, actualArchName, actualArchCode) { expect(err).toBeNull() expect(actualArchCode).toBe(expectedArchCode) expect(actualArchName).toBe(expectedArchName) done() }) }) it('handles big-endian', function(done) { getTargetArch('./test.big-endian.dll', function(err, architectureName, architectureCode) { expect(err).toBeNull() expect(architectureName).toBe('MIPS16') expect(architectureCode).toBe(0x266) done() }) }) it('errors when file does not exist', function(done) { getTargetArch('./nothere', function(err) { expect(err).not.toBeNull() done() }) }) it('errors when MZ magic cannot be read', function(done) { getTargetArch('./test.no-mz.dll', function(err) { expect(String(err)).toBe('Error: failed to read MZ magic') done() }) }) it('errors when MZ magic is incorrect', function(done) { getTargetArch('./test.bad-mz.dll', function(err) { expect(String(err)).toBe('Error: not a DOS-MZ file') done() }) }) })
javascript
21
0.645046
104
29.5
46
starcoderdata
package com.hgtreetable; import javax.swing.*; import javax.swing.tree.*; import javax.swing.table.*; import javax.swing.event.*; import java.util.EventObject; import java.awt.Dimension; import java.awt.Component; import java.awt.Graphics; /** * A JTable that can show trees in its cells. Expanding/collapsing tree nodes * adds/removes rows from the table. * * This class is not quite complete. */ public final class HGTreeTable extends JTable { /** Field : long */ private static final long serialVersionUID = 3258131340820885553L; /** * * @uml.property name="tree" * @uml.associationEnd multiplicity="(1 1)" inverse="this$0:com.hgtreetable.HGTreeTable$TreeTableCellRenderer" */ protected TreeTableCellRenderer tree; /** * * @uml.property name="model" * @uml.associationEnd multiplicity="(1 1)" */ protected TreeTableModel model; /** * * @uml.property name="defaultRenderer" * @uml.associationEnd multiplicity="(1 1)" */ DefaultTreeCellRenderer defaultRenderer; /** * Method HGTreeTable. Main Constructor * @param treeTableModel */ public HGTreeTable(TreeTableModel treeTableModel) { super(); model = treeTableModel; // Create the tree. It will be used as a renderer and editor. tree = new TreeTableCellRenderer(treeTableModel); // Install a tableModel representing the visible rows in the tree. super.setModel(new TreeTableModelAdapter(treeTableModel, tree)); // Force the JTable and JTree to share their row selection models. tree.setSelectionModel(new DefaultTreeSelectionModel() { /** Field : long */ private static final long serialVersionUID = 3689917275188836405L; // Extend the implementation of the constructor, as if: /* public this() */ { setSelectionModel(listSelectionModel); } }); // Make the tree and table row heights the same. tree.setRowHeight(getRowHeight()); this.setIntercellSpacing(new Dimension(0, 0)); // Install the tree editor renderer and editor. setDefaultRenderer(TreeTableModel.class, tree); defaultRenderer = new DefaultTreeCellRenderer(); tree.setCellRenderer(defaultRenderer); setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor()); //These could be factored out. tree.setRootVisible(false); tree.setShowsRootHandles(true); this.setShowGrid(false); this.setColumnSelectionAllowed(false); } /** Sets the icon to use for leaf nodes. If icon==null, no icon * is used. */ public void setLeafIcon(Icon icon) { defaultRenderer.setLeafIcon(icon); } /** Sets the icon to use for open non-leaf nodes. If icon==null, no icon * is used. */ public void setOpenIcon(Icon icon) { defaultRenderer.setOpenIcon(icon); } /** Sets the icon to use for closed non-leaf nodes. If icon==null, no icon * is used. */ public void setClosedIcon(Icon icon) { defaultRenderer.setClosedIcon(icon); } /** Sets this to use an "angled" line style to connect sibling nodes. */ public void setAngledLines() { tree.putClientProperty("JTree.lineStyle", "Angled"); } /** Returns the user object associated with row i of this, or * null if now object found. */ public Object nodeForRow(int row) { TreePath treePath = tree.getPathForRow(row); if (treePath == null) return null; return treePath.getLastPathComponent(); } /** Returns true iff the given display row is expanded. */ public boolean isExpanded(int row) { return tree.isExpanded(row); } /** Returns true iff the given display row is collapsed. */ public boolean isCollapsed(int row) { return tree.isCollapsed(row); } public void expandPath(Object[] path) { tree.expandPath(new TreePath(path)); } /** Adds a TreeExpansionListener to the uderlying tree. */ public void addTreeExpansionListener(TreeExpansionListener l) { tree.addTreeExpansionListener(l); } /* Workaround for BasicTableUI anomaly. Make sure the UI never tries to * paint the editor. The UI currently uses different techniques to * paint the renderers and editors and overriding setBounds() below * is not the right thing to do for an editor. Returning -1 for the * editing row in this case, ensures the editor is never painted. */ public int getEditingRow() { return (getColumnClass(editingColumn) == TreeTableModel.class) ? -1 : editingRow; } /** * Returns the TreeTableModel passed to this. Using this, you can tell if * node is a leaf, etc. * * @uml.property name="model" */ public TreeTableModel getTreeTableModel() { return model; } // // The renderer used to display the tree nodes, a JTree. // public class TreeTableCellRenderer extends JTree implements TableCellRenderer { /** Field : long */ private static final long serialVersionUID = 3256728359806578738L; protected int visibleRow; public TreeTableCellRenderer(TreeModel model) { super(model); } public void setBounds(int x, int y, int w, int h) { super.setBounds(x, 0, w, HGTreeTable.this.getHeight()); } public void paint(Graphics g) { g.translate(0, -visibleRow * getRowHeight()); super.paint(g); } public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (isSelected) setBackground(table.getSelectionBackground()); else setBackground(table.getBackground()); visibleRow = row; return this; } } // // The editor used to interact with tree nodes, a JTree. // public class TreeTableCellEditor extends AbstractCellEditor implements TableCellEditor { /** Field : long */ private static final long serialVersionUID = 3256438110144706357L; public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int r, int c) { return tree; } // We are going to Stop all editing for now. protected EventListenerList listenerList = null; public Object getCellEditorValue() { return null; } public boolean isCellEditable(EventObject e) { return true; } public boolean shouldSelectCell(EventObject anEvent) { return false; } public boolean stopCellEditing() { return true; } public void cancelCellEditing() {} public void addCellEditorListener(CellEditorListener l) {} public void removeCellEditorListener(CellEditorListener l) {} /** * Butchered by Hans */ protected void fireEditingStopped() {} /** * Butchered by Hans */ protected void fireEditingCanceled() {} } }
java
14
0.652132
112
24.614545
275
starcoderdata
#ifndef __MUSICBOX_H__ #define __MUSICBOX_H__ #include "../menu.h" #include "pitches.h" extern MENU_TYP musicbox; typedef struct { char *name; int *notes; int *noteDurations; unsigned int noteLength; unsigned int musicTime; } music_t; typedef struct { music_t **music_list; unsigned int music_list_len; int cur_music_index; unsigned int cur_music_note; unsigned int cur_music_time; unsigned int isPlaying; } player_t; int musicbox_init(void); int musicbox_uninit(void); void musicbox_task(void); void musicbox_key_handel(key_code_t key_code); void musicbox_cover_draw(int *draw_index); static uint8_t icon_data_next_song_24_24[] = { 0x00, 0x00, 0x00, 0xFE, 0xFC, 0xF8, 0xF0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x7F, 0x7F, 0x00, 0x00, 0x00}; static icon_t icon_next_song_24_24 = {icon_data_next_song_24_24, 24, 24}; static uint8_t icon_data_previous_song_24_24[] = { 0x00, 0x00, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0x00, 0x00, 0x00}; static icon_t icon_previous_song_24_24 = {icon_data_previous_song_24_24, 24, 24}; static uint8_t icon_data_resemu_24_24[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFC, 0xF8, 0xF0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x3F, 0x1F, 0x0F, 0x07, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_resume_24_24 = {icon_data_resemu_24_24, 24, 24}; static uint8_t icon_data_pause_24_24[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x7F, 0x7F, 0x7F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static icon_t icon_pause_24_24 = {icon_data_pause_24_24, 24, 24}; static uint8_t icon_data_note_32_32[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xF8, 0xF8, 0xF8, 0x7C, 0x7C, 0x7C, 0x3C, 0x3E, 0x3E, 0x3E, 0x9E, 0x9E, 0x9F, 0x9F, 0xCF, 0xCF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x1C, 0x1C, 0x0E, 0x0E, 0x0F, 0x07, 0x07, 0x07, 0x07, 0x07, 0x03, 0x03, 0x01, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x80, 0x80, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x80, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xF8, 0xFC, 0xFE, 0x9E, 0x0F, 0x0F, 0x0F, 0x0F, 0x9E, 0xFF, 0xFF, 0xFF, 0xFF, 0x1F, 0x7F, 0x7F, 0xFF, 0xF3, 0xE1, 0xE1, 0xE1, 0xE1, 0xF3, 0xFF, 0x7F, 0x3F, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x07, 0x0F, 0x0F, 0x1F, 0x1F, 0x1F, 0x1F, 0x0F, 0x0F, 0x07, 0x01, 0x00}; static icon_t icon_note_32_32 = {icon_data_note_32_32, 32, 32}; static int liang_zhi_lao_hu_Notes[] = { NOTE_C4, NOTE_D4, NOTE_E4, NOTE_C4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_C4, NOTE_E4, NOTE_F4, NOTE_G4, NOTE_E4, NOTE_F4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_F4, NOTE_E4, NOTE_C4, NOTE_G4, NOTE_A4, NOTE_G4, NOTE_F4, NOTE_E4, NOTE_C4, NOTE_D4, NOTE_G3, NOTE_C4, 0, NOTE_D4, NOTE_G3, NOTE_C4, 0}; static int liang_zhi_lao_hu_NoteDurations[] = { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 8, 8, 4, 8, 8, 8, 8, 4, 4, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4}; static music_t liang_zhi_lao_hu = {"liang_zhi_lao_hu", liang_zhi_lao_hu_Notes, liang_zhi_lao_hu_NoteDurations, 34}; static int Imperial_March_Notes[] = { // Dart Vader theme (Imperial March) - Star wars // Score available at https://musescore.com/user/202909/scores/1141521 // The tenor saxophone part was used // notes from // https://github.com/robsoncouto/arduino-songs/blob/master/imperialmarch/imperialmarch.ino NOTE_A4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_F4, REST, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_F4, REST, NOTE_A4, NOTE_A4, NOTE_A4, NOTE_F4, NOTE_C5, NOTE_A4, NOTE_F4, NOTE_C5, NOTE_A4, NOTE_E5, NOTE_E5, NOTE_E5, NOTE_F5, NOTE_C5, NOTE_A4, NOTE_F4, NOTE_C5, NOTE_A4, NOTE_A5, NOTE_A4, NOTE_A4, NOTE_A5, NOTE_GS5, NOTE_G5, NOTE_DS5, NOTE_D5, NOTE_DS5, REST, NOTE_A4, NOTE_DS5, NOTE_D5, NOTE_CS5, NOTE_C5, NOTE_B4, NOTE_C5, REST, NOTE_F4, NOTE_GS4, NOTE_F4, NOTE_A4, NOTE_C5, NOTE_A4, NOTE_C5, NOTE_E5, NOTE_A5, NOTE_A4, NOTE_A4, NOTE_A5, NOTE_GS5, NOTE_G5, NOTE_DS5, NOTE_D5, NOTE_DS5, REST, NOTE_A4, NOTE_DS5, NOTE_D5, NOTE_CS5, NOTE_C5, NOTE_B4, NOTE_C5, REST, NOTE_F4, NOTE_GS4, NOTE_F4, NOTE_A4, NOTE_A4, NOTE_F4, NOTE_C5, NOTE_A4}; static int Imperial_March_NoteDurations[] = { -4, -4, 16, 16, 16, 16, 8, 8, -4, -4, 16, 16, 16, 16, 8, 8, 4, 4, 4, -8, 16, 4, -8, 16, 2, 4, 4, 4, -8, 16, 4, -8, 16, 2, 4, -8, 16, 4, -8, 16, 16, 16, 8, 8, 8, 4, -8, 16, 16, 16, 16, 8, 8, 4, -8, 16, 4, -8, 16, 2, 4, -8, 16, 4, -8, 16, 16, 16, 8, 8, 8, 4, -8, 16, 16, 16, 16, 8, 8, 4, -8, 16, 4, -8, 16, 2}; static music_t Imperial_March = {"Imperial_March", Imperial_March_Notes, Imperial_March_NoteDurations, 86}; #endif
c
8
0.609779
95
45.277372
137
research_code
from flask import Blueprint, redirect, render_template, request from TagModel import * from PostModel import * from UserModel import * from CommentModel import * from htmlmin.minify import html_minify from appconfig import * fe = Blueprint('fe', __name__) @fe.route('/tag/ methods=['GET']) def hometags(tagname=None): tag = TagModel() post = PostModel() tagId = tag.getTagByName(tagname) t = render_template("home/index.html", tags=tag.tags(), posts=post.posts(None, tagId)) return html_minify(unicode(t).encode('utf-8')) @fe.route('/', methods=['GET']) def home(): tag = TagModel() post = PostModel() t = render_template("home/index.html", tags=tag.tags(), posts=post.posts(True, None)) return html_minify(unicode(t).encode('utf-8')) @fe.route('/read/ methods=['GET','POST']) def read(slug=None): from models import db tag = TagModel() post = PostModel() comment = CommentModel() id = post.post(slug) id.NoOfViews += 1 db.session.commit() postFiles = post.getPostFiles(id.Id) if request.method == "POST": if 'comment' in request.form and 'cid' not in request.form: comment.addcomment(request.form['comment'], request.form['email'], request.form['nick'], id.Id) if 'comment' in request.form and 'cid' in request.form: comment.addcomment(request.form['comment'], request.form['email'], request.form['nick'], id.Id, request.form['cid']) ##send reply to if any email address defined c = comment.getCommentEmail(request.form['cid']) if c.Email: from UserModel import UserModel u = UserModel() u.send_email(request.form['nick'] + " just commented on post "+id.Title, c.Email, request.form['comment']+ " c.Nick) if 'password' in request.form: from werkzeug import check_password_hash if check_password_hash(id.Password, request.form['password']): t = render_template("home/read.html", tags=tag.tags(), post=post.post(slug), comments = comment.comments(id), postFiles=postFiles) return html_minify(unicode(t).encode('utf-8')) if id.Password != ' t = render_template("home/read-with-password.html", tags=tag.tags(), post=post.post(slug), comments = comment.comments(id), postFiles=postFiles) else: t = render_template("home/read.html", tags=tag.tags(), post=post.post(slug), comments = comment.comments(id), postFiles=postFiles) return html_minify(unicode(t).encode('utf-8')) @fe.route("/sitemap.xml", methods=["GET"]) def sitemap(): p = PostModel() return p.generateSiteMap() #helper methods @fe.context_processor def utility_processor(): def format_font(id): tag = TagModel() return tag.getRepeats(id) return dict(format_font=format_font) @fe.context_processor def utility_processor(): def snap(c): return c[0:500]+"..." return dict(snap=snap) @fe.context_processor def utility_processor(): def getnick(id): u = UserModel() user = u.getUser(id) return user.Nick return dict(getnick=getnick) @fe.context_processor def utility_processor(): def getimages(id): p = PostModel() return p.getPostImages(id) return dict(getimages=getimages) @fe.context_processor def utility_processor(): def getChildren(id): p = CommentModel() return p.getChildren(id) return dict(getChildren=getChildren)
python
20
0.641515
167
29.158333
120
starcoderdata
<?php namespace Database\Seeders; use Illuminate\Database\Console\Seeds\WithoutModelEvents; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use App\Models\faculty; class Facultyseeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { faculty::create(['faculty' => 'Computing']); faculty::create(['faculty' => 'Management']); faculty::create(['faculty' => 'Hospitality']); } }
php
12
0.659926
57
21.666667
24
starcoderdata
func validateStruct(path string, s interface{}) (bool, []*ValidError) { if s == nil { return true, nil } result := true newPath := path + "." validErrors := make([]*ValidError, 0) val := reflect.ValueOf(s) if val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { val = val.Elem() } // we only accept structs if val.Kind() != reflect.Struct { validErrors = append(validErrors, &ValidError{ Msg: fmt.Sprintf("input must be structs, but get %s", val.Kind()), }) return false, validErrors } for i := 0; i < val.NumField(); i++ { valueField := val.Field(i) typeField := val.Type().Field(i) if typeField.PkgPath != "" { continue // Private field } if valueField.Kind() == reflect.Interface { valueField = valueField.Elem() } if (valueField.Kind() == reflect.Struct || (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) && typeField.Tag.Get(validTag) != "-" { isTypeValid, validErrs := validateStruct(newPath+getTagName(typeField), valueField.Interface()) if len(validErrs) > 0 { validErrors = append(validErrors, validErrs...) } result = result && isTypeValid continue } if valueField.Kind() == reflect.Ptr { valueField = valueField.Elem() } isTypeValid, validErrs := typeCheck(newPath, valueField, typeField) if len(validErrs) > 0 { validErrors = append(validErrors, validErrs...) } result = result && isTypeValid } return result, validErrors }
go
18
0.651052
129
27.346154
52
inline
module.exports = { logo:( <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="20px" height="20px" viewBox="0 0 20 20" enableBackground="new 0 0 20 20" xmlSpace="preserve"> <path className="Blue_1_" fill="#2D3283" d="M18.91,20.014c0.61,0,1.104-0.493,1.104-1.104V1.104C20.015,0.495,19.521,0,18.91,0H1.105 C0.495,0,0,0.495,0,1.104V18.91c0,0.61,0.494,1.104,1.104,1.104H18.91z"/> <path id="f" fill="#FFFFFF" d="M13.81,20.014v-7.75h2.603l0.39-3.021H13.81V7.315c0-0.875,0.243-1.471,1.497-1.471l1.6,0V3.142 c-0.276-0.037-1.226-0.119-2.33-0.119c-2.307,0-3.886,1.408-3.886,3.993v2.228H8.083v3.021h2.608v7.75H13.81z"/> ), };
javascript
9
0.619481
130
37.55
20
starcoderdata
package wrr import ( "fmt" ) // 参考- http://blog.csdn.net/gqtcgq/article/details/52076997 // Server weight-round-robin. type Server struct { Name string Weight int CurWeight int } func getsum(set []int, size int) (sum int) { for i := 0; i < size; i++ { sum += set[i] } return } // greatest common divisor func gcd(a, b int) int { var c int for b > 0 { c = a % b a = b b = c } return a } func getgcd(set []int, size int) (res int) { res = set[0] for i := 0; i < size; i++ { res = gcd(res, set[i]) } return } func getmax(set []int, size int) (max int) { max = set[0] for i := 0; i < size; i++ { if max < set[i] { max = set[i] } } return } // get weight-round-robin func getwrr(s []*Server, size, gcd, max int, i, cw *int) int { for { *i = (*i + 1) % size if *i == 0 { *cw = *cw - gcd if *cw <= 0 { *cw = max if *cw == 0 { return -1 } } } if s[*i].Weight >= *cw { return *i } } } func wrr(s []*Server, weights []int, size int) { var ( index, curweight int ) index = -1 curweight = 0 gcd := getgcd(weights, size) max := getmax(weights, size) sum := getsum(weights, size) for i := 0; i < sum; i++ { getwrr(s, size, gcd, max, &index, &curweight) fmt.Printf("%s(%d)\n", s[index].Name, s[index].Weight) } println("----------") } func initServers(names []string, ws []int, size int) (ss []*Server) { ss = make([]*Server, 0, size) for i := 0; i < size; i++ { s := &Server{} s.Name = names[i] s.Weight = ws[i] ss = append(ss, s) } return } // PrintWrr test wrr. func PrintWrr() { weights := []int{1, 2, 4} names := []string{"a", "b", "c"} size := len(weights) s := initServers(names, weights, size) for i := 0; i < size; i++ { fmt.Printf("%s(%d)\n", s[i].Name, s[i].Weight) } println("----------") println("wrr sequence is") wrr(s, weights, size) }
go
14
0.537393
69
16.018182
110
starcoderdata
package io.choerodon.message.api.controller.v1; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import io.choerodon.core.iam.ResourceLevel; import io.choerodon.message.api.vo.CustomEmailSendInfoVO; import io.choerodon.message.app.service.MessageC7nService; import io.choerodon.message.infra.config.C7nSwaggerApiConfig; import io.choerodon.swagger.annotation.Permission; /** * 〈功能简述〉 * 〈〉 * * @author wanghao * @since 2020/12/15 16:17 */ @RestController @Api(tags = C7nSwaggerApiConfig.CHOEROODN_USER_MESSAGES) @RequestMapping("/choerodon/v1/projects/{project_id}/message/emails") public class C7nProjectMailSendController { @Autowired private MessageC7nService messageC7nService; @Permission(level = ResourceLevel.ORGANIZATION) @ApiOperation("发送自定义邮件") @PostMapping("/custom") public ResponseEntity sendCustomEmail(@RequestBody @Validated CustomEmailSendInfoVO customEmailSendInfoVO) { messageC7nService.sendCustomEmail(customEmailSendInfoVO); return ResponseEntity.noContent().build(); } }
java
6
0.799427
118
33.04878
41
starcoderdata
#include"ArchiveLibDef.h" unsigned int ArcLib::ConvertModeToUnsignedInt(Mode m){ switch (m){ case Mode::SimpleBind: return 0; break; case Mode::Compress: return 1; break; case Mode::EXOREncrypt: return 2; break; default: return 0; break; } } std::string ArcLib::ConvertModeToString(Mode m){ switch (m){ case Mode::SimpleBind: return "SimpleBind"; break; case Mode::Compress: return "Compress"; break; case Mode::EXOREncrypt: return "EXOREncrypt"; break; default: return "ERROR"; break; } } ArcLib::Mode ArcLib::ConvertUnsignedIntToMode(unsigned int in){ switch (in){ case 0: return Mode::SimpleBind; break; case 1: return Mode::Compress; break; case 2: return Mode::EXOREncrypt; break; default: return Mode::SimpleBind; break; } }
c++
8
0.687578
63
14.96
50
starcoderdata