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 il.ac.bgu.cs.bp.bpjs.model; import il.ac.bgu.cs.bp.bpjs.model.eventsets.EventSet; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import org.mozilla.javascript.ConsString; import org.mozilla.javascript.ScriptableObject; /** * A base class for events. Each event has a name and optional data, which is a * Javascript object. * * For two events to be equal, their names and data have to match. * * Each event implicitly defines a singleton {@link EventSet}, which contains * only itself. */ @SuppressWarnings("serial") public class BEvent implements Comparable EventSet, java.io.Serializable { private static final AtomicInteger INSTANCE_ID_GEN = new AtomicInteger(0); /** * Name of the event. Public access, so that the Javascript code feels * natural. */ public final String name; /** * Extra data for the event. Public access, so that the Javascript code * feels natural. */ public final Object maybeData; public static BEvent named(String aName) { return new BEvent(aName); } public BEvent(String aName) { this(aName, null); } public BEvent(String aName, Object someData) { name = aName; maybeData = someData; } public BEvent() { this("BEvent-" + INSTANCE_ID_GEN.incrementAndGet()); } @Override public String toString() { return "[BEvent name:" + name + (getDataField().map(v -> " data:" + v).orElse("")) + "]"; } public String getName() { return name; } /** * @return The data field of the event. */ public Optional getDataField() { return Optional.ofNullable(maybeData); } /** * A Javascript accessor for the event's data. If you are using this method * from Java code, you may want to consider using {@link #getDataField()}. * * @return the event's data, or {@code null}. * @see #getDataField() */ public Object getData() { return maybeData; } @Override public boolean equals(Object obj) { // Circuit breakers if (obj == this) { return true; } if (obj == null) { return false; } if (!(obj instanceof BEvent)) { return false; } BEvent other = (BEvent) obj; // simple cases if (!name.equals(other.name)) { return false; } if ( (maybeData!=null) ^ (other.getDataField().isPresent()) ) { // one has data, the other does not. return false; } if ( (maybeData!=null) ) { // and, by above test, other also has data // OK, delve into Javascript semantics. Object theirData = other.getDataField().get(); if (!(maybeData.getClass().isAssignableFrom(theirData.getClass()) || theirData.getClass().isAssignableFrom(maybeData.getClass()))) { return false; // not same type of data. } // Evaluate datas. return jsObjectsEqual(maybeData, theirData); } else { // whew - both don't have data return true; } } @Override public int hashCode() { int hash = 3; hash = 67 * hash + Objects.hashCode(this.name); return hash; } @Override public int compareTo(BEvent e) { return name.compareTo(e.getName()); } @Override public boolean contains(BEvent event) { return equals(event); } /** * Deep-compare of {@code o1} and {@code o2}. Recurses down these objects, * when needed. * * NOT DEAL WITH CIRCULAR REFERENCES! * * @param o1 * @param o2 * @return {@code true} iff both objects are recursively equal */ private boolean jsObjectsEqual(Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null ^ o2 == null) { return false; } // Concatenated strings in Rhino have a different type. We need to manually // resolve to String semantics, which is what the following lines do. if (o1 instanceof ConsString) { o1 = o1.toString(); } if (o2 instanceof ConsString) { o2 = o2.toString(); } if (!o1.getClass().equals(o2.getClass())) { return false; } // established: o1 and o2 are non-null and of the same class. return (o1 instanceof ScriptableObject) && (o2 instanceof ScriptableObject) ? jsScriptableObjectEqual((ScriptableObject) o1, (ScriptableObject) o2) : o1.equals(o2); } private boolean jsScriptableObjectEqual(ScriptableObject o1, ScriptableObject o2) { Object[] o1Ids = o1.getIds(); Object[] o2Ids = o2.getIds(); if (o1Ids.length != o2Ids.length) { return false; } return Stream.of(o1Ids).allMatch(id -> jsObjectsEqual(o1.get(id), o2.get(id))) && Stream.of(o2Ids).allMatch(id -> jsObjectsEqual(o1.get(id), o2.get(id))); } }
java
16
0.576858
97
27.435484
186
starcoderdata
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; namespace DankMemes.GPSOAuthSharp { // gpsoauth:__init__.py // URL: https://github.com/simon-weber/gpsoauth/blob/master/gpsoauth/__init__.py public class GPSOAuthClient { static string b64Key = " + " + " + " static RSAParameters androidKey = GoogleKeyUtils.KeyFromB64(b64Key); static string version = "0.0.5"; static string authUrl = "https://android.clients.google.com/auth"; static string userAgent = "GPSOAuthSharp/" + version; private string email; private string password; public GPSOAuthClient(string email, string password) { this.email = email; this.password = password; } // _perform_auth_request private Dictionary<string, string> PerformAuthRequest(Dictionary<string, string> data) { NameValueCollection nvc = new NameValueCollection(); foreach (var kvp in data) { nvc.Add(kvp.Key.ToString(), kvp.Value.ToString()); } using (WebClient client = new WebClient()) { client.Headers.Add(HttpRequestHeader.UserAgent, userAgent); string result; try { byte[] response = client.UploadValues(authUrl, nvc); result = Encoding.UTF8.GetString(response); } catch (WebException e) { result = new StreamReader(e.Response.GetResponseStream()).ReadToEnd(); } return GoogleKeyUtils.ParseAuthResponse(result); } } // perform_master_login public Dictionary<string, string> PerformMasterLogin(string service = "ac2dm", string deviceCountry = "us", string operatorCountry = "us", string lang = "en", int sdkVersion = 21) { string signature = GoogleKeyUtils.CreateSignature(email, password, androidKey); var dict = new Dictionary<string, string> { { "accountType", "HOSTED_OR_GOOGLE" }, { "Email", email }, { "has_permission", 1.ToString() }, { "add_account", 1.ToString() }, { "EncryptedPasswd", signature}, { "service", service }, { "source", "android" }, { "device_country", deviceCountry }, { "operatorCountry", operatorCountry }, { "lang", lang }, { "sdk_version", sdkVersion.ToString() } }; return PerformAuthRequest(dict); } // perform_oauth public Dictionary<string, string> PerformOAuth(string masterToken, string service, string app, string clientSig, string deviceCountry = "us", string operatorCountry = "us", string lang = "en", int sdkVersion = 21) { var dict = new Dictionary<string, string> { { "accountType", "HOSTED_OR_GOOGLE" }, { "Email", email }, { "has_permission", 1.ToString() }, { "EncryptedPasswd", masterToken}, { "service", service }, { "source", "android" }, { "app", app }, { "client_sig", clientSig }, { "device_country", deviceCountry }, { "operatorCountry", operatorCountry }, { "lang", lang }, { "sdk_version", sdkVersion.ToString() } }; return PerformAuthRequest(dict); } } // gpsoauth:google.py // URL: https://github.com/simon-weber/gpsoauth/blob/master/gpsoauth/google.py class GoogleKeyUtils { // key_from_b64 // BitConverter has different endianness, hence the Reverse() public static RSAParameters KeyFromB64(string b64Key) { byte[] decoded = Convert.FromBase64String(b64Key); int modLength = BitConverter.ToInt32(decoded.Take(4).Reverse().ToArray(), 0); byte[] mod = decoded.Skip(4).Take(modLength).ToArray(); int expLength = BitConverter.ToInt32(decoded.Skip(modLength + 4).Take(4).Reverse().ToArray(), 0); byte[] exponent = decoded.Skip(modLength + 8).Take(expLength).ToArray(); RSAParameters rsaKeyInfo = new RSAParameters(); rsaKeyInfo.Modulus = mod; rsaKeyInfo.Exponent = exponent; return rsaKeyInfo; } // key_to_struct // Python version returns a string, but we use byte[] to get the same results public static byte[] KeyToStruct(RSAParameters key) { byte[] modLength = { 0x00, 0x00, 0x00, 0x80 }; byte[] mod = key.Modulus; byte[] expLength = { 0x00, 0x00, 0x00, 0x03 }; byte[] exponent = key.Exponent; return DataTypeUtils.CombineBytes(modLength, mod, expLength, exponent); } // parse_auth_response public static Dictionary<string, string> ParseAuthResponse(string text) { Dictionary<string, string> responseData = new Dictionary<string, string>(); foreach (string line in text.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries)) { string[] parts = line.Split('='); responseData.Add(parts[0], parts[1]); } return responseData; } // signature public static string CreateSignature(string email, string password, RSAParameters key) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(key); SHA1 sha1 = SHA1.Create(); byte[] prefix = { 0x00 }; byte[] hash = sha1.ComputeHash(GoogleKeyUtils.KeyToStruct(key)).Take(4).ToArray(); byte[] encrypted = rsa.Encrypt(Encoding.UTF8.GetBytes(email + "\x00" + password), true); return DataTypeUtils.UrlSafeBase64(DataTypeUtils.CombineBytes(prefix, hash, encrypted)); } } class DataTypeUtils { public static string UrlSafeBase64(byte[] byteArray) { return Convert.ToBase64String(byteArray).Replace('+', '-').Replace('/', '_'); } public static byte[] CombineBytes(params byte[][] arrays) { byte[] rv = new byte[arrays.Sum(a => a.Length)]; int offset = 0; foreach (byte[] array in arrays) { Buffer.BlockCopy(array, 0, rv, offset, array.Length); offset += array.Length; } return rv; } } }
c#
24
0.551744
120
38.361582
177
starcoderdata
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Microsoft.Practices.Unity; namespace Remontinka.Client.Core.Interception { /// /// Represents type interseption and dpendency injection engine. /// public class ModelResolver { #region Fabric /// /// The created instances. /// private static readonly ICollection _instances = new Collection /// /// Creates a new instance. /// private ModelResolver() { _container = new UnityContainer(); } /// /// Creates and setups a new instance for model obejct wiring. /// /// <param name="modelInterception">The database model interception settings. public static ModelResolver SetUp(IModelConfiguration modelInterception) { var wiring = new ModelResolver(); modelInterception.Initialize(wiring._container); _instances.Add(wiring); return wiring; } /// /// Gets the Container Wiring instance by owned IUnityContater instance. /// /// <param name="container">The owned unity container. /// finded instance or null. internal static ModelResolver GetInstanceByContainer(IUnityContainer container) { return _instances.FirstOrDefault(instance => ReferenceEquals(instance.Container, container)); } #endregion Fabric #region interception private IUnityContainer _container; #endregion #region Public Methods/Properties public IUnityContainer Container { get { return _container; } } public void TearDown() { if (_container != null) { _container.Dispose(); } _instances.Remove(this); _container = null; } #endregion #region Value change event /// /// Suspending counter of value changing event. /// private int _valueChangedSuspendCounter; /// /// Starts suspendings of rising valuse change events. /// public void BeginSuspendValueChangeEvent() { _valueChangedSuspendCounter++; } /// /// End suspendings of rising valuse change events. /// public void EndSuspendValueChangeEvent() { if (_valueChangedSuspendCounter > 0) { _valueChangedSuspendCounter--; } } /// /// Occurs when a value of interseption objects has been changed. /// public event EventHandler ValueChanged; /// /// Rises a value changed event. /// /// <param name="e"> public void RiseValueChanged(ValueChangedEventArgs e) { if (_valueChangedSuspendCounter == 0) { EventHandler handler = ValueChanged; if (handler != null) { handler(this, e); } } } #endregion Value change event #region Creating instance /// /// Creates an instance for intercepting. /// /// <typeparam name="T">The instance type. /// created instance public T CreateInstance { BeginSuspendValueChangeEvent(); var instance = _container.Resolve var bindableModel = instance as BindableModelObject; EndSuspendValueChangeEvent(); return instance; } #endregion Creating instance } }
c#
16
0.566909
105
27.446667
150
starcoderdata
#include #include "gui/mainwindow.h" #include "memory/debugmemory.h" #include "cpu/debugcpu.h" #include "interrupt/interrupt.h" #include "bios/bios.h" #include "io/ioportlist.h" #include "io/keyboard.h" #include "io/diskette.h" #include "io/timeofday.h" #include "gui/video.h" #include "io/printer.h" #include "io/serial.h" #include "io/cmosram.h" #include "io/systemservice.h" #include "io/pic.h" #include #include std::ofstream fdebug("debug.txt"); void myMessageOutput(QtMsgType type, const char *msg) { switch (type) { case QtDebugMsg: fprintf(stderr, "Debug: %s\n", msg); fdebug<<msg<<std::endl; fdebug.flush(); break; case QtWarningMsg: fprintf(stderr, "Warning: %s\n", msg); break; case QtCriticalMsg: fprintf(stderr, "Critical: %s\n", msg); break; case QtFatalMsg: fprintf(stderr, "Fatal: %s\n", msg); abort(); } } int main(int argc, char *argv[]) { qInstallMsgHandler(myMessageOutput); QApplication a(argc, argv); //------------------------------------------------------------------------ //CPU&DebugCPU DebugCPU cpu; //------------------------------------- //Memory&IOPortList&Interrupt DebugMemory memory; IOPortList ioPortList(memory,cpu.getRegisterFile()); Interrupt interrupt; cpu.initHardwareConnection(memory,ioPortList,interrupt); //------------------------------------- //BIOS&IO BIOS bios(memory,"bios.bin","biosdata.bin"); //! @todo put your written io class here. //---------------------- //MainWindow is nolonger necessary. //(init mainwindow first as the ConsoleWidget is in the mainwindow). //MainWindow w(memory); //w.show(); //ConsoleWidget ConsoleWidget w(NULL,memory.getVideoTextMemoryAddress()); w.show(); //Keyboard Keyboard keyboard; ioPortList.add2PortList(0x16+0x80,&keyboard.keyio); QObject::connect(&w,SIGNAL(keyStatusChange(u16,bool)),&keyboard,SLOT(keyStatusGet(u16,bool))); QObject::connect(&w,SIGNAL(toggleKeyChange(bool,bool,bool,bool,bool,bool)),&keyboard,SLOT(toggleKeyGet(bool,bool,bool,bool,bool,bool))); //Video Video video(memory,cpu.getRegisterFile(),w); ioPortList.add2PortList(0x10+0x80,&video); //Diskette Diskette diskette("images/DOS.IMG","images/NP.IMA"); ioPortList.add2PortList(0x13+0x80,&diskette.getIOPort()); //TimeOfDay TimeOfDay timeOfDay; ioPortList.add2PortList(0x1a+0x80,&timeOfDay.getIOPort()); //CMOSRAM CMOSRAM cmosRAM; ioPortList.add2PortList(0x70,&cmosRAM.getIndexIOPort()); ioPortList.add2PortList(0x71,&cmosRAM.getDataIOPort()); //Printer Printer printer; ioPortList.add2PortList(0x17+0x80,&printer.getIOPort()); //Serial Serial serial; ioPortList.add2PortList(0x14+0x80,&serial.getIOPort()); //SystemService SystemService systemService; ioPortList.add2PortList(0x15+0x80,&systemService.getIOPort()); //PIC PIC pic; ioPortList.add2PortList(0x20,&pic.getIOPort()); //------------------------------------- //start cpu execution in another thread. cpu.start(); //------------------------------------------------------------------------ return a.exec(); }
c++
11
0.61267
140
26.396694
121
starcoderdata
package fr.redstonneur1256.maps.spigot.map; import fr.redstonneur1256.maps.display.DefaultDisplay; import fr.redstonneur1256.maps.render.MapPalette; import fr.redstonneur1256.maps.spigot.adapter.Call; import fr.redstonneur1256.maps.utils.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.map.MapRenderer; import org.bukkit.map.MapView; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @SuppressWarnings("deprecation") public class BukkitMap { private short id; private int[] rawColors; private byte[] data; private int[] tempColors; private boolean modified; public BukkitMap(short id) { int count = DefaultDisplay.MAP_SIZE * DefaultDisplay.MAP_SIZE; this.id = id; this.rawColors = new int[count]; this.tempColors = new int[count]; this.data = new byte[count]; Arrays.fill(rawColors, 0); Arrays.fill(tempColors, 0); Arrays.fill(data, (byte) 0); MapView map = Bukkit.getMap(id); if(map == null) { Logger.log(ChatColor.RED + "Failed to remove default renderers for map " + id + ", map may blink in game."); return; } for(MapRenderer mapRenderer : new ArrayList<>(map.getRenderers())) { map.removeRenderer(mapRenderer); } map.setScale(MapView.Scale.FARTHEST); } public short getID() { return id; } public void draw(BufferedImage image) { draw(image, 0, 0, Math.min(image.getWidth(), 128), Math.min(image.getHeight(), 128)); } public void draw(BufferedImage image, int x, int y, int width, int height) { int[] rgb = this.tempColors; int[] rawColors = this.rawColors; byte[] data = this.data; boolean modified = this.modified; byte[] palette = MapPalette.getPalette(); // Use a scan width of DefaultDisplay.MAP_SIZE because the array is made for this size image.getRGB(x, y, width, height, rgb, 0, DefaultDisplay.MAP_SIZE); for(int i = 0; i < rgb.length; i++) { int color = rgb[i]; if(rawColors[i] != color) { rawColors[i] = color; byte newColor = palette[rgb[i] & 0xFFFFFF]; if(newColor != data[i]) { data[i] = newColor; modified = true; } } } this.modified = modified; } public void send(Player player) { MapView.Scale scale = MapView.Scale.FARTHEST; List icons = Collections.emptyList(); Call.sendMap(player, id, scale.getValue(), icons, data, 0, 0, 128, 128); } public void markModified(boolean modified) { this.modified = modified; } public boolean isModified() { return modified; } }
java
14
0.613751
120
28.376238
101
starcoderdata
using System.Web.Mvc; using LETS.Models; using LETS.Services; using LETS.ViewModels; using Orchard; using Orchard.ContentManagement; using Orchard.Themes; namespace LETS.Controllers { public class LocalityController : Controller { private readonly IOrchardServices _orchardServices; private readonly INoticeService _noticeService; private readonly IContentManager _contentManager; private readonly IMemberService _memberService; public LocalityController(IOrchardServices orchardServices, INoticeService noticeService, IContentManager contentManager, IMemberService memberService) { _orchardServices = orchardServices; _noticeService = noticeService; _contentManager = contentManager; _memberService = memberService; } [Themed] public ActionResult Index(int id) { return View(); } [Themed] public ActionResult Notices(int id) { if (!_orchardServices.Authorizer.Authorize(Permissions.AccessMemberContent)) return new HttpUnauthorizedResult(); var notices = _noticeService.GetNoticesByLocality(id); var locality = _contentManager.Get var members = _memberService.GetMembersByLocality(id); var localityNoticesMembersViewModel = new LocalityNoticesMembersViewModel { Notices = notices, Locality = locality, Members = members }; return View(localityNoticesMembersViewModel); } } }
c#
15
0.697118
161
35.266667
45
starcoderdata
# coding=utf-8 from __future__ import print_function import sys from asdl.hypothesis import Hypothesis, ApplyRuleAction from asdl.lang.prolog.prolog_transition_system import * from asdl.asdl import ASDLGrammar from components.action_info import get_action_infos from components.dataset import Example from components.vocab import VocabEntry, Vocab try: import cPickle as pickle except: import pickle import numpy as np def load_dataset(transition_system, dataset_file): examples = [] for idx, line in enumerate(open(dataset_file)): src_query, tgt_code = line.strip().split('\t') src_query_tokens = src_query.split(' ') tgt_ast = prolog_expr_to_ast(transition_system.grammar, tgt_code) reconstructed_prolog_expr = ast_to_prolog_expr(tgt_ast) assert tgt_code == reconstructed_prolog_expr tgt_actions = transition_system.get_actions(tgt_ast) # sanity check hyp = Hypothesis() for action in tgt_actions: assert action.__class__ in transition_system.get_valid_continuation_types(hyp) if isinstance(action, ApplyRuleAction): assert action.production in transition_system.get_valid_continuating_productions(hyp) hyp = hyp.clone_and_apply_action(action) assert hyp.frontier_node is None and hyp.frontier_field is None assert is_equal_ast(hyp.tree, tgt_ast) expr_from_hyp = transition_system.ast_to_surface_code(hyp.tree) assert expr_from_hyp == tgt_code tgt_action_infos = get_action_infos(src_query_tokens, tgt_actions) print(idx) example = Example(idx=idx, src_sent=src_query_tokens, tgt_actions=tgt_action_infos, tgt_code=tgt_code, tgt_ast=tgt_ast, meta=None) examples.append(example) return examples def prepare_dataset(): # vocab_freq_cutoff = 1 for atis vocab_freq_cutoff = 2 # for geo query grammar = ASDLGrammar.from_text(open('asdl/lang/prolog/prolog_asdl.txt').read()) transition_system = PrologTransitionSystem(grammar) train_set = load_dataset(transition_system, 'data/jobs/train.txt') test_set = load_dataset(transition_system, 'data/jobs/test.txt') # generate vocabulary src_vocab = VocabEntry.from_corpus([e.src_sent for e in train_set], size=5000, freq_cutoff=vocab_freq_cutoff) primitive_tokens = [map(lambda a: a.action.token, filter(lambda a: isinstance(a.action, GenTokenAction), e.tgt_actions)) for e in train_set] primitive_vocab = VocabEntry.from_corpus(primitive_tokens, size=5000, freq_cutoff=0) # generate vocabulary for the code tokens! code_tokens = [transition_system.tokenize_code(e.tgt_code, mode='decoder') for e in train_set] code_vocab = VocabEntry.from_corpus(code_tokens, size=5000, freq_cutoff=0) vocab = Vocab(source=src_vocab, primitive=primitive_vocab, code=code_vocab) print('generated vocabulary %s' % repr(vocab), file=sys.stderr) action_len = [len(e.tgt_actions) for e in chain(train_set, test_set)] print('Max action len: %d' % max(action_len), file=sys.stderr) print('Avg action len: %d' % np.average(action_len), file=sys.stderr) print('Actions larger than 100: %d' % len(list(filter(lambda x: x > 100, action_len))), file=sys.stderr) pickle.dump(train_set, open('data/jobs/train.bin', 'wb')) pickle.dump(test_set, open('data/jobs/test.bin', 'wb')) pickle.dump(vocab, open('data/jobs/vocab.freq2.bin', 'wb')) if __name__ == '__main__': prepare_dataset()
python
15
0.658009
113
37.103093
97
research_code
using System.Linq.Expressions; namespace XpressTest; public interface IVoidMockCountVerifierCreator<TMock, TAsserter> { IMockCountVerifier Create( Expression expression ); }
c#
11
0.755656
64
21.2
10
starcoderdata
private void updateNub(NubUsage nub, SrcUsage u, Origin origin, NubUsage parent) { LOG.debug("Updating {} from source {}", nub.parsedName.getScientificName(), u.parsedName.getScientificName()); NubUsage currNubParent = db.parent(nub); // update nomenclature and status only from source usages if (u.key != null) { nub.sourceIds.add(u.key); // update author, publication and nom status updateNomenclature(nub, u); // prefer accepted version over doubtful if its coming from the same dataset! if (nub.status == TaxonomicStatus.DOUBTFUL && u.status == TaxonomicStatus.ACCEPTED && fromCurrentSource(nub)) { nub.status = u.status; if (isNewParentApplicable(nub, currNubParent, parent) && !db.existsInClassification(currNubParent.node, parent.node, false)) { // current classification doesnt have that parent yet, lets apply it LOG.debug("Update doubtful {} classification with new parent {} {}", nub.parsedName.getScientificName(), parent.rank, parent.parsedName.getScientificName()); db.createParentRelation(nub, parent); } } if (origin == Origin.SOURCE) { // only override original origin value if we update from a true source nub.origin = Origin.SOURCE; } } if (nub.status.isSynonym()) { // maybe we have a proparte synonym from the same dataset? if (fromCurrentSource(nub) && !parent.node.equals(currNubParent.node)) { nub.status = TaxonomicStatus.PROPARTE_SYNONYM; // persistent new pro parte relation LOG.debug("New accepted name {} found for pro parte synonym {}", parent.parsedName.getScientificName(), nub.parsedName.getScientificName()); db.setSingleFromRelationship(nub.node, parent.node, RelType.PROPARTE_SYNONYM_OF); } else { // this might be a more exact kind of synonym status if (nub.status == TaxonomicStatus.SYNONYM) { nub.status = u.status; } } } else { // ACCEPTED if (isNewParentApplicable(nub, currNubParent, parent) && (currNubParent.kingdom == Kingdom.INCERTAE_SEDIS || db.existsInClassification(parent.node, currNubParent.node, false) && currNubParent.rank != parent.rank ) ) { LOG.debug("Update {} classification with new parent {} {}", nub.parsedName.getScientificName(), parent.rank, parent.parsedName.getScientificName()); db.createParentRelation(nub, parent); } } db.store(nub); }
java
14
0.661666
167
47.730769
52
inline
def resultsgraph(g, nomg, gtype='normal'): """ Makes a graph of nominal/non-nominal states by comparing the nominal graph states with the non-nominal graph states Parameters ---------- g : networkx Graph graph for the fault scenario where the functions are nodes and flows are edges and with 'faults' and 'states' attributes nomg : networkx Graph graph for the nominal scenario where the functions are nodes and flows are edges and with 'faults' and 'states' attributes gtype : 'normal' or 'bipartite' whether the graph is a normal multgraph, or a bipartite graph Returns ------- rg : networkx graph copy of g with 'status' attributes added for faulty/degraded functions/flows """ rg=g.copy() if gtype=='normal': for edge in g.edges: for flow in list(g.edges[edge].keys()): if g.edges[edge][flow]!=nomg.edges[edge][flow]: status='Degraded' else: status='Nominal' rg.edges[edge][flow]={'values':g.edges[edge][flow],'status':status} for node in g.nodes: if g.nodes[node]['modes'].difference(['nom']): status='Faulty' elif g.nodes[node]['states']!=nomg.nodes[node]['states']: status='Degraded' else: status='Nominal' rg.nodes[node]['status']=status elif gtype=='bipartite' or 'component': for node in g.nodes: if g.nodes[node]['bipartite']==0 or g.nodes[node].get('iscomponent', False): #condition only checked for functions if g.nodes[node].get('modes', {'nom'}).difference(['nom']): status='Faulty' else: status='Nominal' elif g.nodes[node]['states']!=nomg.nodes[node]['states']: status='Degraded' else: status='Nominal' rg.nodes[node]['status']=status return rg
python
17
0.591074
130
48.435897
39
inline
const teacherRouter = { path: '/', component: () => import(/* webpackChunkName: "home" */ '../../components/common/Home.vue'), meta: { title: '自述文件' }, children: [ { path: '/myTeachCourse', component: () => import(/* webpackChunkName: "dashboard" */ '../../components/teacher/ShowMyCourse'), meta: { title: '授课页面' }, roles: [1,'normal'] }, { path: '/getAllTeacherCourse', component: () => import(/* webpackChunkName: "dashboard" */ '../../components/teacher/GetAllCourse'), meta: { title: '全部课程' }, roles: [1,'normal'] }, { path: '/teachCourse', component: () => import(/* webpackChunkName: "dashboard" */ '../../components/teacher/SelectCourse'), meta: { title: '授课绑定' }, roles: [1,'normal'] }, { path: '/dropTeachCourse', component: () => import(/* webpackChunkName: "dashboard" */ '../../components/teacher/DropCourse'), meta: { title: '解除授课' }, roles: [1,'normal'] }, { path: '/changeTeacherInfo', component: () => import(/* webpackChunkName: "dashboard" */ '../../components/teacher/ChangeInfo'), meta: { title: '信息修改' }, roles: [1,'normal'] } ] }; export default teacherRouter;
javascript
10
0.493902
113
35.02439
41
starcoderdata
void CreateSurroundingPoints() { float radius = CircleScale / 2f; float diagonal = (radius + IdealOffset) / Mathf.Sqrt(2); if (_ideals == null) { _ideals = new List<GameObject>(); //Create 8 surrounding squares GameObject square = GameObject.CreatePrimitive(PrimitiveType.Cube); square.transform.position = new Vector3(-radius - IdealOffset, 0, 0); square.AddComponent<EmotionIdeal>(); _ideals.Add(square); square = GameObject.CreatePrimitive(PrimitiveType.Cube); square.transform.position = new Vector3(radius + IdealOffset, 0, 0); square.AddComponent<EmotionIdeal>(); _ideals.Add(square); square = GameObject.CreatePrimitive(PrimitiveType.Cube); square.transform.position = new Vector3(0, radius + IdealOffset, 0); square.AddComponent<EmotionIdeal>(); _ideals.Add(square); square = GameObject.CreatePrimitive(PrimitiveType.Cube); square.transform.position = new Vector3(0, -radius - IdealOffset, 0); square.AddComponent<EmotionIdeal>(); _ideals.Add(square); square = GameObject.CreatePrimitive(PrimitiveType.Cube); square.transform.position = new Vector3(diagonal, diagonal, 0); square.AddComponent<EmotionIdeal>(); _ideals.Add(square); square = GameObject.CreatePrimitive(PrimitiveType.Cube); square.transform.position = new Vector3(-diagonal, -diagonal, 0); square.AddComponent<EmotionIdeal>(); _ideals.Add(square); square = GameObject.CreatePrimitive(PrimitiveType.Cube); square.transform.position = new Vector3(diagonal, -diagonal, 0); square.AddComponent<EmotionIdeal>(); _ideals.Add(square); square = GameObject.CreatePrimitive(PrimitiveType.Cube); square.transform.position = new Vector3(-diagonal, diagonal, 0); square.AddComponent<EmotionIdeal>(); _ideals.Add(square); } }
c#
14
0.611266
81
41.137255
51
inline
#include<bits/stdc++.h> using namespace std; #define N 120000 #define LL long long LL n,m,ans,a[N],b[N],pre[N],suf[N],q[N]; int main(){ scanf("%lld%lld",&n,&m); for (LL i=1;i<=n;++i) scanf("%lld%lld",&a[i],&b[i]); for (LL i=1;i<=n;++i) pre[i]=pre[i-1]+b[i]; for (LL i=n;i;--i) suf[i]=suf[i+1]+b[i]; LL tt=1,ww=0; for (LL i=1;i<=n;++i){ ans=max(ans,suf[i]-(m-a[i])); for (;tt<=ww&&suf[q[ww]]-(m-a[q[ww]])*2<=suf[i]-(m-a[i])*2;--ww); q[++ww]=i; } for (LL i=1;i<=n;++i){ for (;tt<=ww&&q[tt]<=i;++tt); if (tt<=ww) ans=max(ans,suf[q[tt]]-(m-a[q[tt]])*2+pre[i]-a[i]); } tt=1,ww=0; for (LL i=n;i;--i){ ans=max(ans,pre[i]-a[i]); for (;tt<=ww&&pre[q[ww]]-a[q[ww]]*2<=pre[i]-a[i]*2;--ww); q[++ww]=i; } for (LL i=n;i;--i){ for (;tt<=ww&&q[tt]>=i;++tt); if (tt<=ww) ans=max(ans,pre[q[tt]]-a[q[tt]]*2+suf[i]-(m-a[i])); } printf("%lld\n",ans); return 0; }
c++
20
0.482525
67
21.769231
39
codenet
using TicTacToe.Game.Board; using TicTacToe.Game.Player; namespace TicTacToe.Game { public interface IGameRenderer { void RenderResult(IGameResult gameResult); void RenderBoard(ITicTacToeBoard ticTacToeBoard); void RenderStart(ITicTacToePlayer player1, ITicTacToePlayer player2, ITicTacToeBoard ticTacToeBoard); } }
c#
8
0.763158
109
28.307692
13
starcoderdata
@Override public Void call() throws Exception { log.info("{}: Destroying all workers.", nodeName); // StopWorker may remove elements from the set of worker IDs. That might generate // a ConcurrentModificationException if we were iterating over the worker ID // set directly. Therefore, we make a copy of the worker IDs here and iterate // over that instead. // // Note that there is no possible way that more worker IDs can be added while this // callable is running, because the state change executor is single-threaded. ArrayList<Long> workerIds = new ArrayList<>(workers.keySet()); for (long workerId : workerIds) { try { new StopWorker(workerId, true).call(); } catch (Exception e) { log.error("Failed to stop worker {}", workerId, e); } } return null; }
java
12
0.558416
94
44.954545
22
inline
using System; using Umbraco.Core.Migrations; using Umbraco.Core.Logging; using NPoco; using Umbraco.Core.Persistence.DatabaseAnnotations; namespace Our.Umbraco.FullTextSearch.Migrations.ZeroThreeZero { public class RemoveCacheTaskTable : MigrationBase { public RemoveCacheTaskTable(IMigrationContext context) : base(context) { } public override void Migrate() { Logger.Debug migration {MigrationStep}", "RemoveCacheTable"); // Lots of methods available in the MigrationBase class - discover with this. if (TableExists("FullTextCacheTasks")) { Delete.Table("FullTextCacheTasks").Do(); } else { Logger.Debug database table {DbTable} doesn't exist, skipping", "FullTextCacheTasks"); } } } }
c#
16
0.64664
129
30.677419
31
starcoderdata
import { FileLoader } from './FileLoader'; import Parameter from '../Parameter'; const proxyURL = 'https://www.geowe.org/proxy/proxy.php?url='; export class UrlFileLoader extends FileLoader { constructor(mapSetting) { super(mapSetting); this._files = []; this._layerSetting = mapSetting.getLayerSetting(); if (Object.prototype.hasOwnProperty.call(this._layerSetting, Parameter.GEOJSON_FILE_URL)) { this._files = this._layerSetting.geojson.files; this._totalFiles = this._files.length; const colorPaletteSetting = this._mapSetting.colorPalette; colorPaletteSetting.colorTotal = this._totalFiles; this.configureColorPalette(colorPaletteSetting); } } load() { super.load(); this._files.forEach((file) => { this.loadUrlFile(file); }); } loadUrlFile(url, proxy = false) { this._loadMonitorPanel.show('Cargando url...'); const request = proxy ? proxyURL + url : url; fetch(request) .then((response) => { this._loadMonitorPanel.show('Cargando datos...'); return response.json(); }) .then((json) => { this._loadMonitorPanel.show('Obteniendo elementos...'); setTimeout(() => { var layerName = url.split('/').pop().split('?')[0]; var fc = this.getFeatureCollection(json); this._loadMonitorPanel.show(`Cargando ${fc.length} elementos...`); this.addToMap(fc, layerName); if (json.title) { this.setMapTitle(json.title); } }, 900); }) .catch((error) => { // this._totalFileLoaded++; this.loadUrlFile(url, true); // alert('Problema al cargar: ' + error.message); }); } }
javascript
26
0.515269
99
35.563636
55
starcoderdata
define(["jquery", "util", "session", "elementFinder"], function($, util, session, elementFinder){ var listeners = []; var TIME_UPDATE = 'timeupdate'; var MIRRORED_EVENTS = ['play', 'pause']; var TOO_FAR_APART = 3000; session.on("reinitialize", function () { unsetListeners(); setupListeners(); }); session.on("ui-ready", setupListeners); function setupListeners() { var videos = $('video'); setupMirroredEvents(videos); setupTimeSync(videos); }; function setupMirroredEvents(videos) { var currentListener; MIRRORED_EVENTS.forEach(function (eventName) { currentListener = makeEventSender(eventName); videos.on(eventName, currentListener); listeners.push({ name: eventName, listener: currentListener }); }); }; function makeEventSender(eventName) { return function (event, options) { var element = event.target; options || (options = {}); if (!options.silent) { session.send({ type: ('video-'+eventName), location: elementFinder.elementLocation(element), position: element.currentTime }); } } }; function setupTimeSync(videos) { videos.each(function(i, video) { var onTimeUpdate = makeTimeUpdater(); $(video).on(TIME_UPDATE, onTimeUpdate); listeners.push({ name: TIME_UPDATE, listener: onTimeUpdate }); }); }; function makeTimeUpdater() { var last = 0; return function (event) { var currentTime = event.target.currentTime; if(areTooFarApart(currentTime, last)){ makeEventSender(TIME_UPDATE)(event); } last = currentTime; }; }; function areTooFarApart(currentTime, lastTime) { var secDiff = Math.abs(currentTime - lastTime); var milliDiff = secDiff * 1000; return milliDiff > TOO_FAR_APART; } session.on("close", unsetListeners); function unsetListeners() { var videos = $('video'); listeners.forEach(function (event) { videos.off(event.name, event.listener); }); listeners = []; }; session.hub.on('video-timeupdate', function (msg) { var element = $findElement(msg.location); var oldTime = element.prop('currentTime'); var newTime = msg.position; //to help throttle uneccesary position changes if(areTooFarApart(oldTime, newTime)){ setTime(element, msg.position); }; }) MIRRORED_EVENTS.forEach( function (eventName) { session.hub.on("video-"+eventName, function (msg) { var element = $findElement(msg.location); setTime(element, msg.position); element.trigger(eventName, {silent: true}); }); }) //Currently does not discriminate between visible and invisible videos function $findElement(location) { return $(elementFinder.findElement(location)); } function setTime(video, time) { video.prop('currentTime', time); } });
javascript
20
0.637054
82
24.024793
121
starcoderdata
import request from '@/utils/request' //模板提供的组件,axios封装 const apiurl = "/checkcentersys/userinfo/" export default { /* getTeacherPageListTest(page, limit, searchObj) { return request({ //后端controller里面的路径 url: `${apiurl}/moreCondtionPageList/${page}/${limit}`, //提交方式 method: 'post', //传递条件对象,如果传递json数据,使用data。如果不是json,使用params data: searchObj }) }, */ /* getTeacherPageList(page, limit) { return request({ //后端controller里面的路径 url: '/userinfo/findAllUser/' + page + '/' + limit, //提交方式 method: 'post', //传递条件对象,如果传递json数据,使用data。如果不是json,使用params }) }, */ //分页条件查询的方法 //三个参数:当前页,每页记录数,条件封装对象 /* getTeacherPageList(page, limit, searchObj) { return request({ //后端controller里面的路径 url: '/eduservice/teacher/moreCondtionPageList/' + page + '/' + limit, //提交方式 method: 'post', //传递条件对象,如果传递json数据,使用data。如果不是json,使用params data: searchObj }) }, */ //分页条件查询的方法 //三个参数:当前页,每页记录数,条件封装对象 getUserPageList(page, pageSize, searchObj) { return request({ //后端controller里面的路径 url: 'http://127.0.0.1:8082/checkcentersys/userinfo/moreCondtionPageList/' + page + '/' + pageSize, //提交方式 method: 'post', //传递条件对象,如果传递json数据,使用data。如果不是json,使用params data: searchObj }) }, getUser() { return request({ //后端controller里面的路径 url: 'http://127.0.0.1:8082/checkcentersys/userinfo/list' , //提交方式 method: 'get' }) }, //删除 deleteUserId(id) { return request({ //后端controller里面的路径 url: 'http://127.0.0.1:8082/checkcentersys/userinfo/' + id, //提交方式 method: 'delete' }) }, //添加 saveUserInfo(userinfo) { return request({ //后端controller里面的路径 url: 'http://127.0.0.1:8082/checkcentersys/userinfo/addUser', //提交方式 method: 'post', data: userinfo }) }, //根据id查询 getUserId(id) { return request({ //后端controller里面的路径 url: 'http://127.0.0.1:8082/checkcentersys/userinfo/getUserInfo/' + id, //url: `${apiurl}/getUserInfo/${id}`, //提交方式 method: 'get' }) }, //修改用户 updateUserInfoId(id, userinfo) { return request({ //后端controller里面的路径 url: 'http://127.0.0.1:8082/checkcentersys/userinfo/updateUserInfo/' + id, //提交方式 method: 'post', data: userinfo }) } }
javascript
14
0.508697
111
26.627451
102
starcoderdata
#pragma once #include "SurfaceMeshHelper.h" #include "MatlabSurfaceMeshHelper.h" #include "MeanValueLaplacianHelper.h" /// Augments the setContraints with poles information class MatlabContractionHelper : public SurfaceMeshHelper{ private: IndexVertexProperty vindex; MatlabSurfaceMeshHelper matlab; public: MatlabContractionHelper(SurfaceMeshModel* mesh) : SurfaceMeshHelper(mesh),matlab(mesh){} void evolve(ScalarVertexProperty omega_H, ScalarVertexProperty omega_L, ScalarVertexProperty omega_P, Vector3VertexProperty poles, Scalar zero_TH){ ScalarHalfedgeProperty hweight = MeanValueLaplacianHelper(mesh).computeMeanValueHalfEdgeWeights(zero_TH,"h:weight"); /// Update laplacian vindex = matlab.createVertexIndexes(); createLaplacianMatrix(hweight); /// Set constraints and solve setConstraints(omega_H,omega_L,omega_P,poles); solve(); extractSolution(VPOINT); } private: void createLaplacianMatrix(ScalarHalfedgeProperty hweight){ /// Fill memory Size nv = mesh->n_vertices(); Counter nzmax = mesh->n_halfedges()+mesh->n_vertices(); mxArray* _L = mxCreateSparse(nv, nv, nzmax, mxREAL); double* sr = mxGetPr(_L); mwIndex* irs = mxGetIr(_L); mwIndex* jcs = mxGetJc(_L); /// Fill sparse matrix in order int k=0; /// Tot number elements int j=0; /// Column index typedef std::pair Key; foreach(Vertex v, mesh->vertices()){ jcs[j] = k; /// Sort off elements (including diagonal) QVector indices; /// If cotangent then it's symmetric and we can fill /// in the diagonal elements directly... Scalar diagel=0; foreach(Halfedge h, mesh->onering_hedges(v)) diagel+=hweight[h]; indices.push_back(Key(vindex[v],-diagel)); /// Only off-diagonal elements are inserted!! foreach(Halfedge h, mesh->onering_hedges(v)){ Index vi = vindex[mesh->to_vertex(h)]; indices.push_back(Key(vi,hweight[h])); } /// Sort them in order std::sort(indices.begin(), indices.end()); /// Insert them in the sparse matrix foreach(Key key,indices){ // qDebug() << key.first << key.second; sr[k] = key.second; irs[k] = key.first; k++; } j++; } jcs[mesh->n_vertices()] = k; matlab.put("L", _L); } void setConstraints(ScalarVertexProperty omega_H, ScalarVertexProperty omega_L){ if(!omega_H || !omega_L) throw MissingPropertyException("Invalid"); if(!vindex) throw MissingPropertyException("v:index"); /// Initialize "omega_L" { mxArray* _w = mxCreateDoubleMatrix(mesh->n_vertices(),1,mxREAL); double* w = mxGetPr(_w); foreach(Vertex v, mesh->vertices()) w[ vindex[v] ] = omega_L[v]; matlab.put("omega_L", _w); } /// Initialize "omega_H" { mxArray* _w = mxCreateDoubleMatrix(mesh->n_vertices(),1,mxREAL); double* w = mxGetPr(_w); foreach(Vertex v, mesh->vertices()) w[ vindex[v] ] = omega_H[v]; matlab.put("omega_H", _w); } /// Initialize x0 { const char* x0_property = "v:point"; Vector3VertexProperty points = mesh->get_vertex_property if(!points) throw MissingPropertyException(x0_property); mxArray* _x0 = mxCreateDoubleMatrix(mesh->n_vertices(),3,mxREAL); double* x0 = mxGetPr(_x0); Index nrows = mesh->n_vertices(); foreach(Vertex v, mesh->vertices()){ // qDebug() << points[v]; x0[ vindex[v] + 0*nrows ] = points[v].x(); x0[ vindex[v] + 1*nrows ] = points[v].y(); x0[ vindex[v] + 2*nrows ] = points[v].z(); } matlab.put("x0", _x0); } } void setConstraints(ScalarVertexProperty omega_H, ScalarVertexProperty omega_L, ScalarVertexProperty omega_P, Vector3VertexProperty poles){ /// Do what was already there setConstraints(omega_H,omega_L); if(!omega_P) throw MissingPropertyException("Invalid"); BoolVertexProperty vissplit = mesh->get_vertex_property /// Initialize omega_P (poles constraints) { mxArray* _w = mxCreateDoubleMatrix(mesh->n_vertices(),1,mxREAL); double* w = mxGetPr(_w); foreach(Vertex v, mesh->vertices()) w[ vindex[v] ] = omega_P[v]; matlab.put("omega_P", _w); } /// Initialize p0 (poles positions) { mxArray* _p0 = mxCreateDoubleMatrix(mesh->n_vertices(),3,mxREAL); double* p0 = mxGetPr(_p0); Index nrows = mesh->n_vertices(); foreach(Vertex v, mesh->vertices()){ if(vissplit[v]) continue; p0[ vindex[v] + 0*nrows ] = poles[v].x(); p0[ vindex[v] + 1*nrows ] = poles[v].y(); p0[ vindex[v] + 2*nrows ] = poles[v].z(); } matlab.put("p0", _p0); } } void solve(){ // matlab.eval("save('/Users/ata2/Developer/skelcollapse/poles.mat')"); matlab.eval("lastwarn('');"); matlab.eval("nv = size(L,1);"); matlab.eval("OMEGA_L = spdiags(omega_L,0,nv,nv);"); matlab.eval("L = OMEGA_L * L';"); matlab.eval("H = spdiags(omega_H, 0, nv, nv);"); matlab.eval("P = spdiags(omega_P, 0, nv, nv);"); matlab.eval("LHS = [L; H; P];"); matlab.eval("RHS = [ zeros(nv,3) ; H*x0 ; P*p0];"); matlab.eval("x = LHS \\ RHS;"); matlab.check_for_warnings(); } void extractSolution(const string property){ Vector3VertexProperty solution = mesh->get_vertex_property mxArray* _x = matlab.get("x"); if(_x == NULL) throw StarlabException("matlab solver failure"); double* x = mxGetPr(_x); Index nrows = mesh->n_vertices(); foreach(Vertex v, mesh->vertices()){ solution[v].x() = x[vindex[v] + nrows*0]; solution[v].y() = x[vindex[v] + nrows*1]; solution[v].z() = x[vindex[v] + nrows*2]; } } };
c
11
0.535989
151
38.255814
172
starcoderdata
def main(): require_mass_calculations = None if len(sys.argv) > 1: # Parse arguments and run non-interactively. parser = argparse.ArgumentParser(description='This is a script for processing data from a NEWARE battery cycler.') parser.add_argument('-m', '--mass', help='Mass in milligrams',required=False) parser.add_argument('-i', '--input', help='Input file',required=True) parser.add_argument('-v', '--verbose', action='store_const', dest='loglevel', const=logging.INFO, default=logging.WARNING) parser.add_argument args = parser.parse_args() logging.basicConfig(level=args.loglevel) input_file_path = args.input cycle_dict = parse_general_report(input_file_path) mass_g = infer_mass(cycle_dict) if args.mass: if mass_g: logging.warning("Mass inferred from file is {}mg but this is overriden by required value of {}mg".format(1000.0*mass_g, args.mass)) require_mass_calculations = True mass_g = float(args.mass)/1000.0 else: mass_g = infer_mass(cycle_dict) require_mass_calculations = False else: # Take interactive user input. while True: input_file_path = raw_input("Enter filename:") #TODO: make this more robust againt mistyped filenames. try: cycle_dict = parse_general_report(input_file_path) break except IOError: sys.stderr.write("No such file or directory:", input_file_path) mass_g = infer_mass(cycle_dict) if mass_g == None: mass_g, require_mass_calculations = mass_from_user() else: print("Mass is inferred to be {}mg".format(mass_g*1000)) while True: yes_or_no = raw_input("Use this value for mass? ") try: if distutils.util.strtobool(yes_or_no): require_mass_calculations = False break else: mass_g, require_mass_calculations = mass_from_user() break except ValueError: print("Please enter yes or no.") if require_mass_calculations: calculate_specific_capacities(cycle_dict, mass_g) capacity_type = 'mAh/g' else: capacity_type = 'mAh' input_file_path_no_extension = os.path.splitext(input_file_path)[0] basename_no_extension = os.path.splitext(os.path.basename(input_file_path))[0] out_dir = input_file_path_no_extension + "_data_extracted" logging.debug("Saving to folder {}".format(out_dir)) if not os.path.isdir(out_dir): os.mkdir(out_dir) write_ini_file(input_file_path, cycle_dict, mass_g, out_dir, basename_no_extension) write_cycle_summary_file(cycle_dict, mass_g, out_dir, basename_no_extension) write_individual_cycle_files(cycle_dict, capacity_type, out_dir, basename_no_extension) write_grace_input_file(cycle_dict, capacity_type, out_dir, basename_no_extension) write_grace_cycle_summary(cycle_dict, capacity_type, out_dir, basename_no_extension) write_origin_input_file(cycle_dict, capacity_type, out_dir, basename_no_extension) write_gnuplot_input_file(cycle_dict, capacity_type, out_dir, basename_no_extension)
python
20
0.610997
147
47.6
70
inline
package furgl.mobEvents.common.entity.layer; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.entity.RenderLivingBase; import net.minecraft.client.renderer.entity.layers.LayerVillagerArmor; import net.minecraft.entity.EntityLivingBase; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; public class LayerZombieBossArmor extends LayerVillagerArmor { private final RenderLivingBase renderer; private float alpha = 1.0F; private float colorR = 1.0F; private float colorG = 1.0F; private float colorB = 1.0F; public LayerZombieBossArmor(RenderLivingBase rendererIn) { super(rendererIn); this.renderer = rendererIn; } @Override public void doRenderLayer(EntityLivingBase entitylivingbaseIn, float p_177141_2_, float p_177141_3_, float partialTicks, float p_177141_5_, float p_177141_6_, float p_177141_7_, float scale) { this.renderLayer(entitylivingbaseIn, p_177141_2_, p_177141_3_, partialTicks, p_177141_5_, p_177141_6_, p_177141_7_, scale, EntityEquipmentSlot.HEAD); this.renderLayer(entitylivingbaseIn, p_177141_2_, p_177141_3_, partialTicks, p_177141_5_, p_177141_6_, p_177141_7_, scale, EntityEquipmentSlot.LEGS); this.renderLayer(entitylivingbaseIn, p_177141_2_, p_177141_3_, partialTicks, p_177141_5_, p_177141_6_, p_177141_7_, scale, EntityEquipmentSlot.FEET); float scale2 = 1.5F; GlStateManager.scale(scale2, scale2, scale2); this.renderLayer(entitylivingbaseIn, p_177141_2_, p_177141_3_, partialTicks, p_177141_5_, p_177141_6_, p_177141_7_, scale-0.02f, EntityEquipmentSlot.CHEST); } private void renderLayer(EntityLivingBase entitylivingbaseIn, float p_177182_2_, float p_177182_3_, float p_177182_4_, float p_177182_5_, float p_177182_6_, float p_177182_7_, float p_177182_8_, EntityEquipmentSlot armorSlot) { ItemStack itemstack = this.getItemStackFromSlot(entitylivingbaseIn, armorSlot); if (itemstack != null && itemstack.getItem() instanceof ItemArmor) { ItemArmor itemarmor = (ItemArmor)itemstack.getItem(); ModelBiped t = this.getModelFromSlot(armorSlot); t.setModelAttributes(this.renderer.getMainModel()); t.setLivingAnimations(entitylivingbaseIn, p_177182_2_, p_177182_3_, p_177182_4_); t = getArmorModelHook(entitylivingbaseIn, itemstack, armorSlot, t); this.setModelSlotVisible(t, armorSlot); this.renderer.bindTexture(this.getArmorResource(entitylivingbaseIn, itemstack, armorSlot, null)); int i = itemarmor.getColor(itemstack); { if (i != -1) // Allow this for anything, not only cloth. { float f = (float)(i >> 16 & 255) / 255.0F; float f1 = (float)(i >> 8 & 255) / 255.0F; float f2 = (float)(i & 255) / 255.0F; GlStateManager.color(this.colorR * f, this.colorG * f1, this.colorB * f2, this.alpha); t.render(entitylivingbaseIn, p_177182_2_, p_177182_3_, p_177182_5_, p_177182_6_, p_177182_7_, p_177182_8_); this.renderer.bindTexture(this.getArmorResource(entitylivingbaseIn, itemstack, armorSlot, "overlay")); } { // Non-colored GlStateManager.color(this.colorR, this.colorG, this.colorB, this.alpha); t.render(entitylivingbaseIn, p_177182_2_, p_177182_3_, p_177182_5_, p_177182_6_, p_177182_7_, p_177182_8_); } // Default if (/*!this.field_177193_i && */itemstack.hasEffect()) { this.func_177183_a(entitylivingbaseIn, t, p_177182_2_, p_177182_3_, p_177182_4_, p_177182_5_, p_177182_6_, p_177182_7_, p_177182_8_); } } } } private void func_177183_a(EntityLivingBase entitylivingbaseIn, ModelBiped modelbaseIn, float p_177183_3_, float p_177183_4_, float p_177183_5_, float p_177183_6_, float p_177183_7_, float p_177183_8_, float p_177183_9_) { float f = (float)entitylivingbaseIn.ticksExisted + p_177183_5_; this.renderer.bindTexture(ENCHANTED_ITEM_GLINT_RES); GlStateManager.enableBlend(); GlStateManager.depthFunc(514); GlStateManager.depthMask(false); float f1 = 0.5F; GlStateManager.color(f1, f1, f1, 1.0F); for (int i = 0; i < 2; ++i) { GlStateManager.disableLighting(); GlStateManager.blendFunc(768, 1); float f2 = 0.76F; GlStateManager.color(0.5F * f2, 0.25F * f2, 0.8F * f2, 1.0F); GlStateManager.matrixMode(5890); GlStateManager.loadIdentity(); float f3 = 0.33333334F; GlStateManager.scale(f3, f3, f3); GlStateManager.rotate(30.0F - (float)i * 60.0F, 0.0F, 0.0F, 1.0F); GlStateManager.translate(0.0F, f * (0.001F + (float)i * 0.003F) * 20.0F, 0.0F); GlStateManager.matrixMode(5888); modelbaseIn.render(entitylivingbaseIn, p_177183_3_, p_177183_4_, p_177183_6_, p_177183_7_, p_177183_8_, p_177183_9_); } GlStateManager.matrixMode(5890); GlStateManager.loadIdentity(); GlStateManager.matrixMode(5888); GlStateManager.enableLighting(); GlStateManager.depthMask(true); GlStateManager.depthFunc(515); GlStateManager.disableBlend(); } }
java
17
0.720411
226
44.577982
109
starcoderdata
REPARSELIB_API BOOL GetPrintName(IN LPCWSTR sFileName, OUT LPWSTR sPrintName, IN USHORT uPrintNameLength) { PREPARSE_DATA_BUFFER pReparse; DWORD dwTag; if ((NULL == sPrintName) || (0 == uPrintNameLength)) { return FALSE; } if (!ReparsePointExists(sFileName)) { return FALSE; } if (!GetReparseTag(sFileName, &dwTag)) { return FALSE; } // If not mount point, reparse point or symbolic link if ( ! ( (dwTag == IO_REPARSE_TAG_MOUNT_POINT) || (dwTag == IO_REPARSE_TAG_SYMLINK) ) ) { return FALSE; } pReparse = (PREPARSE_DATA_BUFFER) GlobalAlloc(GPTR, MAXIMUM_REPARSE_DATA_BUFFER_SIZE); if (!GetReparseBuffer(sFileName, (PREPARSE_GUID_DATA_BUFFER)pReparse)) { GlobalFree(pReparse); return FALSE; } switch (dwTag) { case IO_REPARSE_TAG_MOUNT_POINT: if (uPrintNameLength >= pReparse->MountPointReparseBuffer.PrintNameLength) { memset(sPrintName, 0, uPrintNameLength); memcpy ( sPrintName, &pReparse->MountPointReparseBuffer.PathBuffer [ pReparse->MountPointReparseBuffer.PrintNameOffset / sizeof(wchar_t) ], pReparse->MountPointReparseBuffer.PrintNameLength ); } else { GlobalFree(pReparse); return FALSE; } break; case IO_REPARSE_TAG_SYMLINK: if (uPrintNameLength >= pReparse->SymbolicLinkReparseBuffer.PrintNameLength) { memset(sPrintName, 0, uPrintNameLength); memcpy ( sPrintName, &pReparse->SymbolicLinkReparseBuffer.PathBuffer [ pReparse->SymbolicLinkReparseBuffer.PrintNameOffset / sizeof(wchar_t) ], pReparse->SymbolicLinkReparseBuffer.PrintNameLength ); } else { GlobalFree(pReparse); return FALSE; } break; } GlobalFree(pReparse); return TRUE; }
c++
17
0.619442
105
22.888889
81
inline
def _post(self, uri, data): """ Simple POST request for a given path. """ headers = self._get_headers() logging.debug("URI=" + str(uri)) logging.debug("BODY=" + json.dumps(data)) response = self.session.post(uri, headers=headers, data=json.dumps(data)) if response.status_code in [200, 204]: try: return response.json() except ValueError: return "{}" else: logging.error(response.content) response.raise_for_status()
python
10
0.511945
58
29.894737
19
inline
var uuid = require('node-uuid'); // Менеджер комнат var roomManager = require('./rooms'); /** * Глобальные объекты */ // Главный объект Socket.IO var io; // Файл конфигурации (config.json) var config; /** * Выполняет callback только в том случае, если игрок уже подтвердил вход в * комнату. В противном случае callback игнорируется. */ function assertAck(socket, callback) { return function (data) { if (typeof socket.userData == 'undefined') { return; } callback(socket.userData.room, socket.userData.player, data); socket.userData.room.updateRoomTimeout( config.newRoomTimeout, config.inactiveRoomTimeout); }; } /** * Главная функция обработки событий сокета. * Все сообщения, посылаемые серверу, обрабатываются здесь. */ function onClientConnection(socket) { if (config.debug) { var clientIP; var forwarded = socket.request.headers['x-forwarded-for']; if (forwarded) { // Соединение через Heroku (или другую систему рутинга) var forwardedIPs = forwarded.split(','); clientIP = forwardedIPs[0]; } if (!clientIP) { // Обычное соединение clientIP = socket.request.connection.remoteAddress; } console.log("[IO] Соединение с клиентом %s", clientIP); } /** * Получение UUID (только через API) */ socket.on('getNewPlayerID', function onGetNewPlayerID() { socket.emit('playerIDReturned', uuid.v4()); }); /** * Кнопки главного меню */ socket.on('findRoom', function onFindRoom() { var roomID = roomManager.findRoomID( config.defaultOptions, config.newRoomTimeout); socket.emit('roomIDReturned', roomID); }); socket.on('newRoom', function onNewRoom() { var roomID = roomManager.newRoomID( config.defaultOptions, config.newRoomTimeout); socket.emit('roomIDReturned', roomID); }); /** * Подтверждение комнаты */ socket.on('ackRoom', function onAckRoom(data) { if (typeof data == 'undefined') { return; } var room = roomManager.rooms[data.roomID]; var playerID = data.playerID; var playerName = data.playerName || config.defaultName; // Проверка на существование комнаты if (typeof room == 'undefined') { socket.emit('roomDoesNotExist'); return; } room.connect(playerID, playerName, socket, { // Вызывается при первом подключении к комнате first: function (playerData) { socket.broadcast.to(room.id).emit('playerJoined', playerData); }, // Вызывается при успешном подключении к комнате success: function (userData, roomData) { socket.userData = userData; socket.join(room.id); if (roomData.role == 'mafia') { socket.join(room.id + '_m'); } if (roomData.eliminated) { socket.join(room.id + '_e'); } socket.emit('roomData', roomData); }, // Вызывается, если комната запечатана sealed: function () { socket.emit('roomIsSealed'); } }); room.updateRoomTimeout(config.newRoomTimeout, config.inactiveRoomTimeout); }); /** * Начало игры */ socket.on('startGame', assertAck(socket, function onStartGame(room, player) { if (player === room.owner) { room.startGame({ join: function (player, roomID) { player.socket.join(roomID); }, leave: function (player, roomID) { player.socket.leave(roomID); }, broadcast: function (eventName, data) { io.to(room.id).emit(eventName, data); }, emit: function (player, eventName, data) { player.socket.emit(eventName, data); } }); } } )); /** * Выход из игры */ socket.on('leaveGame', assertAck(socket, function onLeaveGame(room, player) { room.disconnect(player, function (playerInfo) { socket.broadcast.to(room.id).emit('playerLeft', playerInfo); socket.leave(room.id); if (playerInfo.role == 'mafia') { socket.leave(room.id + '_m'); } if (playerInfo.eliminated) { socket.leave(room.id + '_e'); } }); } )); /** * Голосование */ socket.on('playerVote', assertAck(socket, function onPlayerVote(room, player, data) { room.handleVote(player, data, { confirmed: function (data) { socket.broadcast.to(data.roomID).emit('playerVote', data.voteData); // socket.emit('voteConfirmed', data.voteID); }, rejected: function (data) { // socket.emit('voteRejected', data.voteID); } }); } )); /** * Выбор игрока */ socket.on('playerChoice', assertAck(socket, function onPlayerChoice(room, player, data) { room.handleChoice(player, data, { confirmed: function (data) { // socket.emit('choiceConfirmed', data.choiceID); }, rejected: function (data) { // socket.emit('choiceRejected', data.choiceID); } }); } )); /** * Сообщение чата */ socket.on('chatMessage', assertAck(socket, function onChatMessage(room, player, data) { room.handleChatMessage(player, data, { confirmed: function (data) { socket.broadcast.to(data.roomID).emit('chatMessage', data.messageData); // socket.emit('messageConfirmed', data.messageID); }, rejected: function (data) { // socket.emit('messageRejected', data.messageID); } }); } )); }; /** * Проверка существования комнаты */ exports.checkRoomExistence = function (roomID, callback) { callback(roomID in roomManager.rooms); }; /** * Инициализация модуля игры */ exports.initialize = function (_io, _config) { io = _io; config = _config; io.on('connection', onClientConnection); };
javascript
25
0.604053
81
24.758772
228
starcoderdata
package org.platformlayer.service.network.ops; import org.platformlayer.core.model.Secret; import org.platformlayer.ops.Handler; import org.platformlayer.ops.networks.HasIpsecPolicy; import org.platformlayer.service.network.model.IpsecPolicy; public class IpsecPolicyController implements HasIpsecPolicy { @Handler public void handler() { } @Override public Secret getIpsecPreSharedKey(Object model) { // TODO: Have controller per model; inject item? Or use OpsContext? return ((IpsecPolicy) model).ipsecSecret; } }
java
9
0.799622
69
28.388889
18
starcoderdata
import unittest from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException import unittest, time, re, os, platform from crcapp.tests import BaseTest class VehiclesInsert(BaseTest): # Test for editing of vehicle in staff page def test_VehiclesInsert(self): driver = self.driver driver.get("http://127.0.0.1:8000/") driver.find_element_by_link_text("Login").click() driver.find_element_by_id("username").click() driver.find_element_by_id("username").clear() driver.find_element_by_id("username").send_keys("dev") driver.find_element_by_id("password").clear() driver.find_element_by_id("password").send_keys(" driver.find_element_by_xpath("(.//*[normalize-space(text()) and normalize-space(.)='Password'])[1]/following::button[1]").click() driver.find_element_by_link_text("Insert Vehicle").click() driver.find_element_by_id("makeName").click() driver.find_element_by_id("makeName").clear() driver.find_element_by_id("makeName").send_keys("111") driver.find_element_by_id("model").click() driver.find_element_by_id("model").clear() driver.find_element_by_id("model").send_keys("111") driver.find_element_by_id("series").click() driver.find_element_by_id("series").clear() driver.find_element_by_id("series").send_keys("111") driver.find_element_by_id("year").click() driver.find_element_by_id("year").clear() driver.find_element_by_id("year").send_keys("2018") driver.find_element_by_id("enginesize").click() driver.find_element_by_id("enginesize").clear() driver.find_element_by_id("enginesize").send_keys("111") driver.find_element_by_id("seatingCapacity").click() driver.find_element_by_id("seatingCapacity").clear() driver.find_element_by_id("seatingCapacity").send_keys("111") driver.find_element_by_id("fuelSystem").click() driver.find_element_by_id("fuelSystem").clear() driver.find_element_by_id("fuelSystem").send_keys("111") driver.find_element_by_id("tankcapacity").click() driver.find_element_by_id("tankcapacity").clear() driver.find_element_by_id("tankcapacity").send_keys("111") driver.find_element_by_id("power").click() driver.find_element_by_id("power").clear() driver.find_element_by_id("power").send_keys("111") driver.find_element_by_id("standardTransmission").click() driver.find_element_by_id("standardTransmission").clear() driver.find_element_by_id("standardTransmission").send_keys("111") driver.find_element_by_id("wheelBase").click() driver.find_element_by_id("wheelBase").clear() driver.find_element_by_id("wheelBase").send_keys("111") driver.find_element_by_id("bodyType").click() driver.find_element_by_id("bodyType").clear() driver.find_element_by_id("bodyType").send_keys("111") driver.find_element_by_id("driveType").click() Select(driver.find_element_by_id("driveType")).select_by_visible_text("AWD") driver.find_element_by_id("newPrice").click() driver.find_element_by_id("newPrice").clear() driver.find_element_by_id("newPrice").send_keys("111") driver.find_element_by_id("select2-storeID-container").click() # DropDown not working # driver.find_element_by_id("select2-storeID-result-ud7i-S0001").click() # driver.find_element_by_id("submit").click() # WebDriverWait(driver, 10).until(EC.text_to_be_present_in_element((By.XPATH, "//*[@id='content']/div/div/div/div/p"), "Vehicle inserted.")) # driver.find_element_by_xpath("//*[@id='mainContent']/div[1]/div/nav/ol/li[1]/a").click() # driver.find_element_by_link_text("View Vehicles").click() # driver.find_element_by_xpath("(.//*[normalize-space(text()) and normalize-space(.)='Search:'])[1]/input[1]").click() # driver.find_element_by_xpath("(.//*[normalize-space(text()) and normalize-space(.)='Search:'])[1]/input[1]").clear() # driver.find_element_by_xpath("(.//*[normalize-space(text()) and normalize-space(.)='Search:'])[1]/input[1]").send_keys("111") # self.assertEqual("111", driver.find_element_by_xpath("(.//*[normalize-space(text()) and normalize-space(.)='V15402'])[1]/following::td[1]").text)
python
13
0.661928
155
59.556962
79
starcoderdata
# interesting_lines.py def interesting_lines(f): for line in f: if line.startswith("#"): continue line = line.strip() if not line: # Empty line continue yield line with open('myconfig.ini') as f: for line in interesting_lines(f): print(line)
python
9
0.549689
37
16.888889
18
starcoderdata
def setRandomSeed(seed): """ Sets the random seed used by the configuration sampler. Args: seed (int) """ return _motionplanning.setRandomSeed(seed)
python
6
0.636872
61
21.5
8
inline
uint8_t OpenBCI_Wifi_Class::passthroughCommands(String commands) { uint8_t numCmds = uint8_t(commands.length()); if (numCmds > BYTES_PER_SPI_PACKET - 1) { return PASSTHROUGH_FAIL_TOO_MANY_CHARS; } else if (numCmds == 0) { return PASSTHROUGH_FAIL_NO_CHARS; } // Serial.printf("got %d commands | passthroughPosition: %d\n", numCmds, passthroughPosition); if (passthroughPosition > 0) { if (numCmds > BYTES_PER_SPI_PACKET - passthroughPosition-1) { // -1 because of numCmds as first byte return PASSTHROUGH_FAIL_QUEUE_FILLED; } passthroughBuffer[0] += numCmds; } else { passthroughBuffer[passthroughPosition++] = numCmds; } for (int i = 0; i < numCmds; i++) { // Serial.printf("cmd %c | passthroughPosition: %d\n", commands.charAt(i), passthroughPosition); passthroughBuffer[passthroughPosition++] = commands.charAt(i); } passthroughBufferLoaded = true; clientWaitingForResponse = true; timePassthroughBufferLoaded = millis(); SPISlave.setData(passthroughBuffer, BYTES_PER_SPI_PACKET); return PASSTHROUGH_PASS; }
c++
11
0.703807
104
40.461538
26
inline
def test_common_attrs(self): """Test to ensure that types with similar attributes all match""" class CustomClass(): def pop(self): return 'pop!' @self.check_arg_attrs(a='pop') def return_values(a, b): return (a, b) cstm = CustomClass() self.assertEqual(return_values(a=[1, 2, 3], b=0), ([1, 2, 3], 0)) self.assertEqual(return_values(a={1, 2, 3}, b=0), ({1, 2, 3}, 0)) self.assertEqual(return_values(a={'a': 1, 'b': 2, 'c': 3}, b=0), ({'a': 1, 'b': 2, 'c': 3}, 0)) self.assertEqual(return_values(a=cstm, b=0), (cstm, 0))
python
12
0.507837
103
30.95
20
inline
public void generateTrees(EBPFProfilingAnalyzation analyzation, Stream<EBPFProfilingStack> stackStream) { Collection<EBPFProfilingTree> stackTrees = stackStream // stack list cannot be empty .filter(s -> CollectionUtils.isNotEmpty(s.getSymbols())) // analyze the symbol and combine as trees .collect(Collectors.groupingBy(s -> s.getSymbols() .get(0), ANALYZE_COLLECTOR)).values(); analyzation.getTrees().addAll(stackTrees); }
java
14
0.634831
105
52.5
10
inline
<div class="container-fluid"> <!-- acerca de mi --> <div class="row"> <div id="acercade" class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs 12"> <img class="docente" src="<?php echo base_url("assets/imagenes/figura0.jpg")?>"> <div class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs 12"> <img class="img-me" src="<?php echo base_url("assets/imagenes/sobreMi.png")?>"> <h2 class="myH2">About me <div id="bloque_inf" class="col-md-12 row"> <div class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs-12"> <label class="nick">Nombre: <div class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs-12"> <label class="inf"> <div class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs-12"> <label class="nick">Grado: <div class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs-12"> <label class="inf">Doctor en Ciencias Matemáticas <div class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs-12"> <label class="nick">Puesto: <div class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs-12"> <label class="inf">Catedrático Investigador Titular <!-- investigacion --> <div class="row"> <div class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs 12"> <img class="img-encabezado" src="<?php echo base_url("assets/imagenes/investigaciones.png")?>"> <h2 class="myH2">SECCIÓN DE INVESTIGACIÓN Y AREAS DE INTERÉS <div class="description container"> <p class="contexto"> <b id="semblanza">Semblanza: Nací en la Cuidad de México y realicé mis estudios de licenciatura y doctorado en la Universidad Autónoma Metropolitana Unidad Iztapalapa del 2003 al 2013 donde me gradué con honores. Posteriormente realicé estancias posdoctorales en Yeshiva University y el Instituto Tecnológico Autónomo de México en las Ciudades de Nueva York y México respectivamente. He impartido varias conferencias tanto en México como en Estados Unidos y Europa. Mis áreas de interés son los Sistemas Dinámicos y sus aplicaciones en Mecánica Celeste, Astrofísica y Dinámica Orbital, así como Pruebas Asistidas por Computadora para Sistemas No Lineales y Simulación. <div id="contenedor" class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs 12"> <div class="col-md-12 contenedor_img"> <div class="row"> <div class="col-md-6"> <img src="<?php echo base_url("assets/imagenes/1.png");?>" class="img_contenida"> <div class="col-md-6"> <img src="<?php echo base_url("assets/imagenes/2.png");?>" class="img_contenida"> <div class="row"> <div class="col-md-6"> <img src="<?php echo base_url("assets/imagenes/3.png");?>" class="img_contenida"> <div class="col-md-6"> <img src="<?php echo base_url("assets/imagenes/4.png");?>" class="img_contenida"> <!-- publicaciones --> <div class=""> <div class="row publicaciones"> <div class="col-md-12 col-lg-12 col-xl-12 col-sm-12 col-xs-12"> <h2 class="myH2 head_title"><img id="img-libro" src="<?php echo base_url("assets/imagenes/publicaciones.png")?>">Publicaciones Recientes: <!-- <h2 class="myH2 head_title">Publicaciones Recientes: --> <div class="row publicaciones"> <div class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs 12"> <div class="lis-left"> <ul class="ok"> <li type="disc"> <p class="list"> et al. Hill Four-Body Problem with Oblate Bodies: An Application to the Sun–Jupiter–Hektor–Skamandrios System. J Nonlinear Sci (2020). https://doi.org/10.1007/s00332-020-09640-x. <li type="disc"> <p class="list"> Un vistazo al método de Taylor con diferenciación automática para problemas de valor inicial. Abstraction & Application (2019). <li type="disc"> <p class="list"> Spatial periodic orbits in the equilateral circular restricted four body problem. Computer-assisted proofs of existence. Celestial Mechanics and Dynamical Astronomy (2018). <li type="disc"> <p class="list"> Horseshoe orbits in the restricted four-body problem. Astrophysics and Space Science (2017). <div class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs 12"> <div class="lis-right"> <li type="disc"> <p class="list"> Burgos-García,J. Families of periodic orbits in the planar Hill four body problem. Astrophysics and Space Science (2016). <li type="disc"> <p class="list"> approximation in a restricted four-body problem. Celestial Mechanics and Dynamical Astronomy (2018). <li type="disc"> <p class="list"> On the blue sky catastrophe termination in the restricted four body problem. Celestial Mechanics and Dynamical Astronomy (2013). <li type="disc"> <p class="list"> Periodic orbits in the restricted four-body problem with two equal masses. Astrophysics and Space Science (2013). <li type="disc"> <p class="list"> Burgos-García,J. REGULARIZATION IN THE RESTRICTED FOUR BODY PROBLEM. Aportaciones Matemáticas (2012). <!-- proyectos --> <div class="proyectos"> <div class="row proyects"> <div class="col-md-12 col-lg-12 col-xl-12 col-sm-12 col-xs-12"> <h2 class="myH2">Proyectos de investigación: <div class="col-md-12 container"> <div class="row"> <div class="col-md-4 col-lg-4 col-xl-4 col-sm-12 col-xs-12"> <div class="card card-investigacion"> <img src="<?php echo base_url("assets/imagenes/proyectos_1.png")?>" class="cards_img1" alt="..."> <div class="card-body"> <p class="card-text"> 1. INSTABILITY OF DYNAMICAL SYSTEMS. Proyecto patrocinado por la National Science Fundation el Consejo Nacional de Ciencia y Tecnología. (2014) <div class="col-md-4 col-lg-4 col-xl-4 col-sm-12 col-xs-12"> <div class="card card-investigacion"> <img src="<?php echo base_url("assets/imagenes/proyectos_2.png")?>" class="cards_img2" alt="..."> <div class="card-body"> <p class="card-text"> 2. Inestabilidad en sistemas Hamiltonianos y sus aplicaciones en Mecánica Celeste y Dinámica Orbital. Proyecto patrocinado por el Programa para el Desarrollo Profesional Docente. (2016) <div class="col-md-4 col-lg-4 col-xl-4 col-sm-12 col-xs-12"> <div class="card card-investigacion"> <img src="<?php echo base_url("assets/imagenes/proyectos_3.png")?>" class="cards_img3" alt="..."> <div class="card-body"> <p class="card-text"> 3. La enseñanza de las Matemáticas para la industria 4.0. Proyecto patrocinado por Consejo Estatal de Ciencia y Tecnología del Estado de Coahuila. (2019) <!-- docencia --> <div class="row"> <div id="docencia" class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs 12"> <img class="docencia" src="<?php echo base_url("assets/imagenes/clases.png")?>"> <div class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs 12"> <img class="img-encabezado" src="<?php echo base_url("assets/imagenes/docencia.png")?>"> <h2 class="myH2">SECCIÓN DE DOCENCIA <div class="description container"> <p class="contexto"> Materias impartidas: Mecánica Clásica, Física Computacional, Análisis Numérico I y II, Ecuaciones Diferenciales Parciales, Álgebra Superior, Sistemas Dinámicos, Ecuaciones Diferenciales Ordinarias entre varias otras. <!-- distinciones --> <div class="row"> <div class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs 12"> <img class="img-encabezado" src="<?php echo base_url("assets/imagenes/distinciones.png")?>"> <h2 class="myH2">SECCION DE DISTINCIONES <div class="description container"> <p class="contexto"> 2020- Reconocimiento al perfil deseable por parte del Programa para el Desarrollo Profesional Docente 2016-Fecha actual. Investigador Nacional Nivel I. Sistema Nacional de Investigadores 2007 Medalla al mérito universitario (Distinción a la excelencia académica). Universidad Autónoma Metropolitana. <div id="distinciones" class="col-md-6 col-lg-6 col-xl-6 col-sm-12 col-xs 12"> <!-- <img class="docente" src="<?php echo base_url("assets/imagenes/figura0.jpg")?>"> -->
php
6
0.442686
197
48.37037
270
starcoderdata
void CollidersPage::OnCollidersCollectionChanged( Windows::Foundation::Collections::IObservableVector<NetcodeAssetEditor::DC_Collider> const & sender, Windows::Foundation::Collections::IVectorChangedEventArgs const & evt) { auto changeEvent = evt.CollectionChange(); if(changeEvent == Windows::Foundation::Collections::CollectionChange::ItemInserted) { uint32_t idx = evt.Index(); tokens.InsertAt(idx, AddCallbackFor(idx)); } // on removal the indices must be updated to reflect the proper reference if(changeEvent == Windows::Foundation::Collections::CollectionChange::ItemRemoved) { uint32_t idx = evt.Index(); tokens.RemoveAt(idx); auto tokensView = tokens.GetView(); auto collidersView = colliders.GetView(); for(uint32_t i = 0; i < tokensView.Size(); ++i) { collidersView.GetAt(i).PropertyChanged(tokens.GetAt(i)); } tokens.Clear(); for(uint32_t i = 0; i < collidersView.Size(); ++i) { tokens.Append(AddCallbackFor(i)); } } }
c++
12
0.605646
108
38
30
inline
@SuppressWarnings("squid:S3776") // Suppress high Cognitive Complexity warning @Override public VectorTVList clone() { VectorTVList cloneList = new VectorTVList(dataTypes); cloneAs(cloneList); for (int[] indicesArray : indices) { cloneList.indices.add(cloneIndex(indicesArray)); } for (int i = 0; i < values.size(); i++) { List<Object> columnValues = values.get(i); for (Object valueArray : columnValues) { cloneList.values.get(i).add(cloneValue(dataTypes.get(i), valueArray)); } if (bitMaps != null && bitMaps.get(i) != null) { List<BitMap> columnBitMaps = bitMaps.get(i); if (cloneList.bitMaps == null) { cloneList.bitMaps = new ArrayList<>(dataTypes.size()); for (int j = 0; j < dataTypes.size(); j++) { cloneList.bitMaps.add(null); } } if (cloneList.bitMaps.get(i) == null) { List<BitMap> cloneColumnBitMaps = new ArrayList<>(); cloneList.bitMaps.set(i, cloneColumnBitMaps); } for (BitMap bitMap : columnBitMaps) { cloneList.bitMaps.get(i).add(cloneBitMap(bitMap)); } } } return cloneList; }
java
15
0.597835
78
36.5625
32
inline
/** * Created by yotam on 23/06/2017. */ /** * Created by yotam on 02/08/2016. */ (function () { 'use strict'; angular .module('myApp.services') .service('Consts', function () { this.SEARCH_HOURS_RANGE = 2; }); })();
javascript
14
0.5
40
16.733333
15
starcoderdata
package leetcode281_290; /**Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): Any live cell with fewer than two live neighbors dies, as if caused by under-population. Any live cell with two or three live neighbors lives on to the next generation. Any live cell with more than three live neighbors dies, as if by over-population.. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. Write a function to compute the next state (after one update) of the board given its current state. Follow up: Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems? * Created by eugene on 16/5/25. */ public class GameOfLife { /**注意如何引入预定义directions简化代码 * 注意如何设定状态机值 状态0: 死细胞转为死细胞 状态1: 活细胞转为活细胞 状态2: 活细胞转为死细胞 状态3: 死细胞转为活细胞 最后我们对所有状态对2取余,那么状态0和2就变成死细胞,状态1和3就是活细胞. */ int[][] directions ={{1,-1},{1,0},{1,1},{0,-1},{0,1},{-1,-1},{-1,0},{-1,1}}; public void gameOfLife(int[][] board) { int m = board.length, n = board[0].length; for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ int live=0; for(int[] d: directions){ if(d[0]+i<0 || d[0]+i>=m || d[1]+j<0 || d[1]+j>=n) continue; if(board[d[0]+i][d[1]+j]==1 || board[d[0]+i][d[1]+j]==2) live++; } if(board[i][j]==0 && live==3) board[i][j]=3; if(board[i][j]==1 && (live<2 || live>3)) board[i][j]=2; } } for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ board[i][j] %= 2; } } } }
java
19
0.609446
100
40.54717
53
starcoderdata
using System.Windows.Media; namespace FontViewer.Model { public static class ColorExtensions { public static float GetHue(this Color c) => System.Drawing.Color.FromArgb(c.A, c.R, c.G, c.B).GetHue(); public static float GetBrightness(this System.Windows.Media.Color c) => System.Drawing.Color.FromArgb(c.A, c.R, c.G, c.B).GetBrightness(); public static float GetSaturation(this System.Windows.Media.Color c) => System.Drawing.Color.FromArgb(c.A, c.R, c.G, c.B).GetSaturation(); } }
c#
13
0.719682
73
30.4375
16
starcoderdata
<?php use App\Http\Controllers\Auth\RegisterController; // Registration Routes... Route::get('register', [RegisterController::class, 'showRegistrationForm'])->name('register'); Route::post('register', [RegisterController::class,'register']);
php
9
0.737903
94
21.545455
11
starcoderdata
import express from 'express'; import pins from './routes/pins'; const app = express(); app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); export default () => { return new Promise(resolve => { app.use('/pins', pins); resolve(app.listen(3030)); }); }
javascript
14
0.647922
95
24.5625
16
starcoderdata
<?php if(qode_options()->getOptionValue('enable_search') == 'yes') { $search_type_class = 'search_slides_from_window_top'; if(qode_options()->getOptionValue('search_type') !== '') { $search_type_class = qode_options()->getOptionValue('search_type'); } if(qode_options()->getOptionValue('search_type') == 'search_covers_header' && qode_options()->getOptionValue('search_cover_only_bottom_yesno')=='yes') { $search_type_class .= ' search_covers_only_bottom'; } ?> <a class="search_button <?php echo esc_attr($search_type_class); ?> <?php echo esc_attr($header_button_size); ?>" href="javascript:void(0)"> <?php qode_icon_collections()->getSearchIcon(qode_options()->getOptionValue('search_icon_pack')); ?> <?php if($search_type_class == 'fullscreen_search' && $fullscreen_search_animation=='from_circle'){ ?> <div class="fullscreen_search_overlay"> <?php } ?> <?php } ?>
php
11
0.684157
153
51.210526
19
starcoderdata
<?php namespace App\Http\Controllers; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class RespondsWithHttpStatusController extends Controller { /** * Return statusCode 200. * @param null|array|Model $data * @param $status * @return \Illuminate\Http\JsonResponse */ public function respond(Array $data, $status = 'success'){ return response()->json([ 'status' => $status, 'status_code' => Response::HTTP_OK, 'data' => $data ], Response::HTTP_OK); } /** * Return statusCode 200. * @param string $message * @return \Illuminate\Http\JsonResponse */ public function responseOk($message) { return response()->json([ 'status' => 'success', 'status_code' => Response::HTTP_OK, 'data' => $message ], Response::HTTP_OK); } /** * Return statusCode 201 * @param null|array|Model $data * @param string $message * @return \Illuminate\Http\JsonResponse */ public function responseCreated(Array $data, $message = ''){ return response()->json([ 'status' => 'success', 'status_code' => Response::HTTP_CREATED, 'data' => $data, 'message' => $message ], Response::HTTP_CREATED); } /** * Return statusCode 422 * @param string $message * @return \Illuminate\Http\JsonResponse */ public function responseUnProcess($message){ return response()->json([ 'status' => 'fail', 'status_code' => Response::HTTP_UNPROCESSABLE_ENTITY, 'message' => $message ], Response::HTTP_UNPROCESSABLE_ENTITY); } /** * Return statusCode 204 * @return \Illuminate\Http\JsonResponse */ public function responseNoContent(){ return response()->json([], Response::HTTP_NO_CONTENT); } }
php
12
0.57008
65
26.189189
74
starcoderdata
func appendTransliterate(base, norm string, uppercase bool) { normRunes := []rune(norm) baseRunes := []rune(base) lenNorm := len(normRunes) lenBase := len(baseRunes) if lenNorm != lenBase { panic("Base and normalized strings have differend length: base=" + strconv.Itoa(lenBase) + ", norm=" + strconv.Itoa(lenNorm)) // programmer error in constant length } for i, baseRune := range baseRunes { normMap[baseRune] = normRunes[i] } if uppercase { upperBase := strings.ToUpper(base) upperNorm := strings.ToUpper(norm) normRune := []rune(upperNorm) for i, baseRune := range []rune(upperBase) { normMap[baseRune] = normRune[i] } } }
go
13
0.689024
166
27.565217
23
inline
otError qorvoRadioTransmit(otRadioFrame* aPacket) { otError error = OT_ERROR_INVALID_STATE; UInt8 offset = 0; gpPd_Loh_t pdLoh; gpMacCore_Security_t secOptions; gpMacCore_MultiChannelOptions_t multiChannelOptions; gpMacCore_AddressMode_t srcAddrMode = 0x02; gpMacCore_AddressInfo_t dstAddrInfo; UInt8 txOptions = 0; pdLoh.handle = gpPd_GetPd(); if(pdLoh.handle == GP_PD_INVALID_HANDLE) { GP_LOG_SYSTEM_PRINTF("no more pd handles:%x !", 0, pdLoh.handle); return OT_ERROR_NO_BUFS; } GP_LOG_PRINTF("Tx on channel %d seq = %d", 0, aPacket->mChannel, aPacket->mPsdu[2]); //GP_LOG_SYSTEM_PRINTF("tx mac len:%d pd=%d",0, aPacket->mLength, pdLoh.handle); //gpLog_PrintBuffer(aPacket->mLength, aPacket->mPsdu); pdLoh.length = aPacket->mLength - offset; pdLoh.length -= 2; // drop the 2 crc bytes pdLoh.offset = 0; gpPd_WriteByteStream(pdLoh.handle, pdLoh.offset, pdLoh.length, aPacket->mPsdu + offset); //multiChannelOptions.channel[0] = local->phy->current_channel; GP_ASSERT_DEV_INT(aPacket->mChannel >= 11); GP_ASSERT_DEV_INT(aPacket->mChannel <= 26); multiChannelOptions.channel[0] = aPacket->mChannel; multiChannelOptions.channel[1] = GP_MACCORE_INVALID_CHANNEL; multiChannelOptions.channel[2] = GP_MACCORE_INVALID_CHANNEL; memset(&secOptions, 0, sizeof(gpMacCore_Security_t)); secOptions.securityLevel = gpEncryption_SecLevelNothing; dstAddrInfo.addressMode = 0x03; txOptions = GP_MACCORE_TX_OPT_RAW; gpMacDispatcher_DataRequest(srcAddrMode, &dstAddrInfo, txOptions, &secOptions, multiChannelOptions, pdLoh, qorvoGetStackId()); error = OT_ERROR_NONE; return error; }
c
9
0.69697
130
36.326087
46
inline
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "UnrealHeaderTool.h" #include "UHTMakefile/UHTMakefile.h" #include "UHTMakefile/CompilerMetadataManagerArchiveProxy.h" FCompilerMetadataManagerArchiveProxy::FCompilerMetadataManagerArchiveProxy(const FUHTMakefile& UHTMakefile, TArray<TPair<UStruct*, FClassMetaData*>>& CompilerMetadataManager) { for (auto& Kvp : CompilerMetadataManager) { Array.Add(TPairInitializer<FSerializeIndex, FClassMetaDataArchiveProxy>(UHTMakefile.GetStructIndex(Kvp.Key), FClassMetaDataArchiveProxy(UHTMakefile, Kvp.Value))); } } void FCompilerMetadataManagerArchiveProxy::AddReferencedNames(const FCompilerMetadataManager* CompilerMetadataManager, FUHTMakefile& UHTMakefile) { for (auto& Kvp : *CompilerMetadataManager) { FClassMetaDataArchiveProxy::AddReferencedNames(Kvp.Value, UHTMakefile); } } void FCompilerMetadataManagerArchiveProxy::Resolve(int32 Index, FCompilerMetadataManager& CompilerMetadataManager, FUHTMakefile& UHTMakefile) { auto& Kvp = Array[Index]; UStruct* Struct = UHTMakefile.GetStructByIndex(Kvp.Key); FClassMetaData* ClassMetaData = GScriptHelper.AddClassData(Struct, UHTMakefile, nullptr); Kvp.Value.PostConstruct(ClassMetaData); Kvp.Value.Resolve(ClassMetaData, UHTMakefile); UHTMakefile.CreateGScriptHelperEntry(Struct, ClassMetaData); } FArchive& operator<<(FArchive& Ar, FCompilerMetadataManagerArchiveProxy& CompilerMetadataManagerArchiveProxy) { Ar << CompilerMetadataManagerArchiveProxy.Array; return Ar; }
c++
13
0.834851
174
43.513514
37
starcoderdata
#ifndef _MATRIX_TEST_GROUP_H_ #define _MATRIX_TEST_GROUP_H_ /*--------------------------------------------------------------------------------*/ /* Declare Test Groups */ /*--------------------------------------------------------------------------------*/ JTEST_DECLARE_GROUP(matrix_tests); #endif /* _MATRIX_TEST_GROUP_H_ */
c
5
0.335366
84
35.444444
9
starcoderdata
package es.victorgf87.santanderopenapiwrapper.serializedclasses; import com.google.gson.annotations.SerializedName; import com.google.gson.internal.LinkedTreeMap; import java.util.List; /** * Class containing a list of collections. * * Created by Víctor on 15/07/2015. */ public class CollectionsList { @SerializedName("summary")private Summary summary; //A request contains a summary @SerializedName("listCollections")private LinkedTreeMap collections;//List of collections @SerializedName("resources")Object resources; public List { List ret=collections.get("collection"); return ret; } public Summary getSummary() { return summary; } }
java
10
0.711924
118
25.354839
31
starcoderdata
package prunedp; import java.util.BitSet; public class Router implements Comparable public int u; public int v; public BitSet X; public double weight; Router(int u, int v, int xs){ this.u = u; this.v = v; X = new BitSet(xs); weight = 0; } public Router(int u, int v, int xs, int loc){ this.u = u; this.v = v; X = new BitSet(xs); X.set(loc); weight = 0; } public int compareTo(Router r2) { int result = this.weight > r2.weight ? 1 : (this.weight < r2.weight ? -1 : 0); if (result == 0) result = (this.u < r2.u) ? 1 : (this.u == r2.u ? 0 : -1); if (result == 0) result = (this.v < r2.v) ? 1 : (this.v == r2.v ? 0 : -1); return result; } }
java
13
0.562897
80
19.888889
36
starcoderdata
func (me *serviceGraphProcessor) createOrUpdateServiceAndIngress(node *fogappsCRDs.ServiceGraphNode) error { existingServiceAndIngress := &svcGraphUtil.ServiceAndIngressPair{} var serviceAndIngress *svcGraphUtil.ServiceAndIngressPair var err error // Check if we have an existing Service and Ingress. if existingService, ok := me.existingChildObjects.Services[node.Name]; ok { existingServiceAndIngress.Service = existingService.DeepCopy() } if existingIngress, ok := me.existingChildObjects.Ingresses[node.Name]; ok { existingServiceAndIngress.Ingress = existingIngress.DeepCopy() } if existingServiceAndIngress.Service != nil || existingServiceAndIngress.Ingress != nil { serviceAndIngress, err = svcGraphUtil.UpdateServiceAndIngress(existingServiceAndIngress, node, me.svcGraph) } else { if serviceAndIngress, err = svcGraphUtil.CreateServiceAndIngress(node, me.svcGraph); err == nil { if serviceAndIngress.Service != nil { if err = me.setOwner(serviceAndIngress.Service); err != nil { return err } } if serviceAndIngress.Ingress != nil { if err := me.setOwner(serviceAndIngress.Ingress); err != nil { return err } } } } if err != nil { return err } if serviceAndIngress.Service != nil { kubeutil.SetSpecHash(serviceAndIngress.Service, serviceAndIngress.Service.Spec) me.newChildObjects.Services[serviceAndIngress.Service.Name] = serviceAndIngress.Service } if serviceAndIngress.Ingress != nil { kubeutil.SetSpecHash(serviceAndIngress.Ingress, serviceAndIngress.Ingress.Spec) me.newChildObjects.Ingresses[serviceAndIngress.Ingress.Name] = serviceAndIngress.Ingress } return nil }
go
15
0.769092
109
35.977778
45
inline
def get_group(self, group_id): """ Gets the group with the provided group_id """ group_id = self.get_group_ids(group_id)[0] response = self.get_request('groups/{}'.format(group_id)).json() return response
python
12
0.573123
72
30.75
8
inline
<?php namespace abcms\multilanguage\module; use Yii; use abcms\multilanguage\MultilanguageBase; /** * multilanguage module definition class */ class Module extends \yii\base\Module { /** * {@inheritdoc} */ public $controllerNamespace = 'abcms\multilanguage\module\controllers'; /** * {@inheritdoc} */ public $defaultRoute = 'message'; /** * @var string the Multilanguage application component ID. */ public $multilanguageId = 'multilanguage'; /** * {@inheritdoc} */ public function init() { parent::init(); // custom initialization code goes here } /** * Return the multilanguage component * @return MultilanguageBase */ public function getMultilanguage() { return Yii::$app->get($this->multilanguageId); } }
php
11
0.599307
75
17.826087
46
starcoderdata
using FluentAssertions; using FluentAssertions.Execution; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Cofoundry.Domain.Tests.Integration.Entities.Queries { [Collection(nameof(DbDependentFixtureCollection))] public class GetEntityDependencySummaryByRelatedEntityIdQueryHandlerTests { const string UNIQUE_PREFIX = "GEntDepSumByRelIdQHT "; private readonly DbDependentTestApplicationFactory _appFactory; public GetEntityDependencySummaryByRelatedEntityIdQueryHandlerTests( DbDependentTestApplicationFactory appFactory ) { _appFactory = appFactory; } [Fact] public async Task MapsBasicData() { var uniqueData = UNIQUE_PREFIX + nameof(MapsBasicData); using var app = _appFactory.Create(); var contentRepository = app.Services.GetContentRepositoryWithElevatedPermissions(); var directoryId = await app.TestData.PageDirectories().AddAsync(uniqueData); await app.TestData.UnstructuredData().AddAsync RelatedEntityCascadeAction.None); var dependencies = await contentRepository.ExecuteQueryAsync(new GetEntityDependencySummaryByRelatedEntityIdQuery(PageDirectoryEntityDefinition.DefinitionCode, directoryId)); using (new AssertionScope()) { // Generally entity mapping is down to the query referenced in IDependableEntityDefinition.CreateGetEntityMicroSummariesByIdRangeQuery // but we'll check the basic mapping for one test here dependencies.Should().NotBeNull(); dependencies.Should().HaveCount(1); var dependency = dependencies.First(); dependency.CanDelete.Should().BeFalse(); dependency.Entity.Should().NotBeNull(); dependency.Entity.RootEntityId.Should().Be(app.SeededEntities.CustomEntityForUnstructuredDataTests.CustomEntityId); dependency.Entity.RootEntityTitle.Should().Be(app.SeededEntities.CustomEntityForUnstructuredDataTests.Title); dependency.Entity.EntityDefinitionCode.Should().Be(app.SeededEntities.CustomEntityForUnstructuredDataTests.CustomEntityDefinitionCode); dependency.Entity.EntityDefinitionName.Should().Be(new TestCustomEntityDefinition().Name); dependency.Entity.IsPreviousVersion.Should().BeFalse(); } } [Fact] public async Task MapsCanDelete() { var uniqueData = UNIQUE_PREFIX + nameof(MapsCanDelete); using var app = _appFactory.Create(); var contentRepository = app.Services.GetContentRepositoryWithElevatedPermissions(); var directoryId = await app.TestData.PageDirectories().AddAsync(uniqueData); await app.TestData.UnstructuredData().AddAsync RelatedEntityCascadeAction.Cascade); var dependencies = await contentRepository.ExecuteQueryAsync(new GetEntityDependencySummaryByRelatedEntityIdQuery(PageDirectoryEntityDefinition.DefinitionCode, directoryId)); using (new AssertionScope()) { dependencies.Should().HaveCount(1); var dependency = dependencies.First(); dependency.CanDelete.Should().BeTrue(); } } [Fact] public async Task DoesNotFetchDuplicates() { var uniqueData = UNIQUE_PREFIX + nameof(DoesNotFetchDuplicates); using var app = _appFactory.Create(); var contentRepository = app.Services.GetContentRepositoryWithElevatedPermissions(); var directoryId = await app.TestData.PageDirectories().AddAsync(uniqueData); var pageId = await app.TestData.Pages().AddAsync(uniqueData, directoryId, c => c.Publish = true); var pageDraftId = await app.TestData.Pages().AddDraftAsync(pageId); var blockId = await app.TestData.Pages().AddPlainTextBlockToTestTemplateAsync(pageDraftId); var customEntity1Id = await app.TestData.CustomEntities().AddAsync(uniqueData + "1"); var customEntity2Id = await app.TestData.CustomEntities().AddAsync(uniqueData + "2"); var relatedEntityId = await app.TestData.CustomEntities().AddAsync(uniqueData + "related"); await app.TestData.UnstructuredData().AddAsync( PageEntityDefinition.DefinitionCode, pageId, TestCustomEntityDefinition.Code, relatedEntityId, RelatedEntityCascadeAction.Cascade ); await app.TestData.UnstructuredData().AddAsync( PageVersionBlockEntityDefinition.DefinitionCode, blockId, TestCustomEntityDefinition.Code, relatedEntityId, RelatedEntityCascadeAction.None ); await app.TestData.UnstructuredData().AddAsync( TestCustomEntityDefinition.Code, customEntity1Id, TestCustomEntityDefinition.Code, relatedEntityId, RelatedEntityCascadeAction.None ); await app.TestData.UnstructuredData().AddAsync( TestCustomEntityDefinition.Code, customEntity2Id, TestCustomEntityDefinition.Code, relatedEntityId, RelatedEntityCascadeAction.Cascade ); var dependencies = await contentRepository.ExecuteQueryAsync(new GetEntityDependencySummaryByRelatedEntityIdQuery(TestCustomEntityDefinition.Code, relatedEntityId)); using (new AssertionScope()) { dependencies.Should().HaveCount(3); var pageDependency = dependencies.SingleOrDefault(e => e.Entity.RootEntityId == pageId && e.Entity.EntityDefinitionCode == PageEntityDefinition.DefinitionCode); pageDependency.Should().NotBeNull(); pageDependency.CanDelete.Should().BeFalse(); dependencies.Should().ContainSingle(e => e.Entity.RootEntityId == customEntity1Id && e.Entity.EntityDefinitionCode == TestCustomEntityDefinition.Code); dependencies.Should().ContainSingle(e => e.Entity.RootEntityId == customEntity2Id && e.Entity.EntityDefinitionCode == TestCustomEntityDefinition.Code); } } } }
c#
21
0.677624
186
50.592
125
starcoderdata
from color_list import ColorList from list_console_view import ListConsoleView def main(): colors = ColorList() command = input("Please enter a command > ") while command: if command == "append": color_name = input("Color Name > ") color_hexcode = input("Color Hexcode > ") colors.append(color_name, color_hexcode) elif command == "remove": color_id = int(input("Enter a Color Id to Remove > ")) colors.remove(color_id) elif command == "clear": colors.clear() elif command == "count": list_console_view = ListConsoleView(colors) list_console_view.display_count() elif command == "list": list_console_view = ListConsoleView(colors) list_console_view.display_table() elif command == "save": csv_file_name = input("CSV File Name > ") colors.save(csv_file_name) elif command == "load": csv_file_name = input("CSV File Name > ") colors.load(csv_file_name) elif command == "save zip": zip_file_name = input("Zip File Name > ") colors.save_zip(zip_file_name) elif command == "load zip": zip_file_name = input("Zip File Name > ") colors.load_zip(zip_file_name) command = input("Please enter a command > ") if __name__ == '__main__': main()
python
15
0.550546
66
31.533333
45
starcoderdata
/** * */ /** * @author zi-m.cn * */ package com.zim.terminal.saika.ack;
java
6
0.519481
35
8.75
8
starcoderdata
namespace Ryujinx.HLE.HOS.Services.SurfaceFlinger { struct ParcelHeader { public uint PayloadSize; public uint PayloadOffset; public uint ObjectsSize; public uint ObjectOffset; } }
c#
8
0.659292
50
21.6
10
starcoderdata
/* audio.[ch] * * part of the Systems Programming 2005 assignment * (c) Vrije Universiteit Amsterdam, BSD License applies * contact info : wdb -_at-_ few.vu.nl * */ /* To make audio playback work on modern Linux systems: - Start your audio client with "padsp audioclient" instead of just "audioclient" - Or set $LD_PRELOAD to libpulsedsp.so */ #include #include #include #include #include #include #include #include #include #define AUDIODEV "/dev/dsp" #define swap_short(x) (x) #define swap_long(x) (x) #include #include #include "audio.h" /* Definitions for the WAVE format */ #define RIFF "RIFF" #define WAVEFMT "WAVEfmt" #define DATA 0x61746164 #define PCM_CODE 1 typedef struct _waveheader { char main_chunk[4]; /* 'RIFF' */ uint32_t length; /* filelen */ char chunk_type[7]; /* 'WAVEfmt' */ uint32_t sc_len; /* length of sub_chunk, =16 */ uint16_t format; /* should be 1 for PCM-code */ uint16_t chans; /* 1 Mono, 2 Stereo */ uint32_t sample_fq; /* frequence of sample */ uint32_t byte_p_sec; uint16_t byte_p_spl; /* samplesize; 1 or 2 bytes */ uint16_t bit_p_spl; /* 8, 12 or 16 bit */ uint32_t data_chunk; /* 'data' */ uint32_t data_length; /* samplecount */ } WaveHeader; int aud_readinit (char *filename, int *sample_rate, int *sample_size, int *channels ) { /* Sets up a descriptor to read from a wave (RIFF). * Returns file descriptor if successful*/ int fd; WaveHeader wh; if (0 > (fd = open (filename, O_RDONLY))){ fprintf(stderr,"unable to open the audiofile\n"); return -1; } read (fd, &wh, sizeof(wh)); if (0 != bcmp(wh.main_chunk, RIFF, sizeof(wh.main_chunk)) || 0 != bcmp(wh.chunk_type, WAVEFMT, sizeof(wh.chunk_type)) ) { fprintf (stderr, "not a WAVE-file\n"); errno = 3;// EFTYPE; return -1; } if (swap_short(wh.format) != PCM_CODE) { fprintf (stderr, "can't play non PCM WAVE-files\n"); errno = 5;//EFTYPE; return -1; } if (swap_short(wh.chans) > 2) { fprintf (stderr, "can't play WAVE-files with %d tracks\n", wh.chans); return -1; } *sample_rate = (unsigned int) swap_long(wh.sample_fq); *sample_size = (unsigned int) swap_short(wh.bit_p_spl); *channels = (unsigned int) swap_short(wh.chans); fprintf (stderr, "%s chan=%u, freq=%u bitrate=%u format=%hu\n", filename, *channels, *sample_rate, *sample_size, wh.format); return fd; } int aud_writeinit (int sample_rate, int sample_size, int channels) { /* Sets up the audio device params. * Returns device file descriptor if successful*/ int audio_fd, error; char *devicename; printf("requested chans=%d, sample rate=%d sample size=%d\n", channels, sample_rate, sample_size); if (NULL == (devicename = getenv("AUDIODEV"))) devicename = AUDIODEV; if ((audio_fd = open (devicename, O_WRONLY, 0)) < 0) { perror ("setparams : open ") ; return -1; } if (ioctl (audio_fd, SNDCTL_DSP_RESET, 0) != 0) { perror ("setparams : reset ") ; close(audio_fd); return -1; } if ((error = ioctl (audio_fd, SNDCTL_DSP_SAMPLESIZE, &sample_size)) != 0) { perror ("setparams : bitwidth ") ; close(audio_fd); return -1; } if (ioctl (audio_fd, SNDCTL_DSP_CHANNELS, &channels) != 0) { perror ("setparams : channels ") ; close(audio_fd); return -1; } if ((error = ioctl (audio_fd, SNDCTL_DSP_SPEED, &sample_rate)) != 0) { perror ("setparams : sample rate ") ; close(audio_fd); return -1; } if ((error = ioctl (audio_fd, SNDCTL_DSP_SYNC, 0)) != 0) { perror ("setparams : sync ") ; close(audio_fd); return -1; } printf("set chans=%d, sample rate=%d sample size=%d\n", channels,sample_rate, sample_size); return audio_fd; }
c
12
0.623667
83
25.789116
147
starcoderdata
<?php namespace App\Http\Requests\Auth; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Validator; class RegisterRequest extends FormRequest { public function rules(): array { Validator::extend('without_spaces', function($attr, $value){ return preg_match('/^\S*$/u', $value); }); return [ 'name' => 'required|min:3|max:25|unique:users|without_spaces|regex:/(^([a-zA-Z]+)(\d+)?$)/u', 'email' => 'required|email|min:3|max:25|unique:users', 'password' => ' ]; } }
php
16
0.588235
105
27.333333
21
starcoderdata
using ChromaBoy.Hardware; namespace ChromaBoy.Software.Opcodes { public class SET : Opcode // SET r { private Register target; private byte bit; private byte modValue; private ushort modAddress; public SET(Gameboy parent, byte opcode) : base(parent) { target = OpcodeUtils.BitsToRegister(opcode & 0b111); bit = (byte)((opcode & 0b111000) >> 3); Cycles = target == Register.M ? 16 : 8; Length = 2; TickAccurate = true; Disassembly = "set $" + bit.ToString("X2") + ", " + (target == Register.M ? "[hl]" : OpcodeUtils.RegisterToString(target)); } public override void ExecuteTick() { base.ExecuteTick(); if (target == Register.M && Tick == 3) { modAddress = (ushort)((parent.Registers[Register.H] << 8) | (parent.Registers[Register.L])); } else if ((target == Register.M && Tick == 7) || (target != Register.M && Tick == 3)) { modValue = target == Register.M ? parent.Memory[modAddress] : parent.Registers[target]; } else if ((target == Register.M && Tick == 11) || (target != Register.M && Tick == 7)) { if (target == Register.M) parent.Memory[modAddress] = (byte)(modValue | (byte)(1 << bit)); else parent.Registers[target] = (byte)(modValue | (byte)(1 << bit)); } } } }
c#
20
0.500963
135
34.386364
44
starcoderdata
import AvailableSeat from './shapes/availableSeat'; import UnavailableSeat from './shapes/unavailableSeat'; import BookedSeat from './shapes/bookedSeat'; class EventSeat { constructor(opts) { this.id = opts.id; this.x = opts.x; this.y = opts.y; this.booked = opts.booked || false; this.unavailable = opts.unavailable || false; this.isSelected = false; this.opts = opts; const shape = this._shapeClass(); this.seatShape = new shape( Object.assign( { id: this.id, x: this.x, y: this.y, name: this.name(), preventDefault: false, }, this.opts ) ); this._bindEvents(); } _shapeClass() { // if (this.isSelected) return this.opts.selectedColor; if (this.booked) return BookedSeat; if (this.unavailable) return UnavailableSeat; return AvailableSeat; } _bindEvents() { this.seatShape .on('mouseenter', (e) => { const container = e.target.getStage().container(); if (this.booked || this.unavailable) container.style.cursor = 'not-allowed'; else container.style.cursor = 'pointer'; }) .on('mouseleave', (e) => { const container = e.target.getStage().container(); container.style.cursor = ''; }) .setAttr('seat', this); } /** * The color to fill this seat with. */ color() { if (this.isSelected) return this.opts.selectedColor; if (this.booked) return this.opts.bookedColor; return this.opts.seatColor; } /** * The name for this seat, used for finding selected seats from * the Konva Stage object. */ name() { if (this.isSelected) return 'selected'; return 'unselected'; } /** * Select this seat. */ select() { if (this.booked || this.unavailable) return; this.isSelected = true; this.change(); } /** * Deselect this seat. */ deselect() { this.isSelected = false; this.change(); } change() { this.seatShape.find('Circle').fill(this.color()); this.seatShape.name(this.name()); } /** * Get the Konva shape object representing this seat. */ get shape() { return this.seatShape; } } export default EventSeat;
javascript
21
0.591674
84
20.721154
104
starcoderdata
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.jini.lookup.ui.factory; import java.awt.Panel; /** * UI factory for an AWT * * the UI generated by the method declared in this interface implements * and supports the Java Accessibility * API, an attribute * should be placed in the set. * * may be placed in the attributes set to indicate * a preferred title of a pop-up window containing this component. * * @author */ public interface PanelFactory extends java.io.Serializable { /** * Convenience constant to use in the * field of that contain a * * The value of this constant is */ String TOOLKIT = "java.awt"; /** * Convenience constant to use in the * set in the set of * that contain a * The value of this constant is */ String TYPE_NAME = "net.jini.lookup.ui.factory.PanelFactory"; /** * Returns a */ Panel getPanel(Object roleObject); }
java
6
0.708333
92
37.315789
57
starcoderdata
public void handle( org.apache.lucene.document.Document luceneDocument, Document document ) { for ( String date : document.getAll( "date" ) ) { // Store, but do not index, the full date. luceneDocument.add( new Field( "date", date, Field.Store.YES, Field.Index.NO ) ); // Index, but do not store, the year and the year+month. These are what can be searched. if ( date.length() >= 6 ) { luceneDocument.add( new Field( "date", date.substring( 0, 6 ), Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS ) ); } if ( date.length() >= 4 ) { luceneDocument.add( new Field( "date", date.substring( 0, 4 ), Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS ) ); } } }
java
14
0.577608
130
42.722222
18
inline
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class Image extends Model { public function setImage(string $image) { $this->setAttribute('file', $image); } public function setAdvertisementId(int $advertisementId) { $this->setAttribute('advertisement_id', $advertisementId); } public function getImage(string $image) { $this->getAttribute('file', $image); } public function getAdvertisementId(int $advertisementId) { $this->getAttribute('advertisement_id', $advertisementId); } public function advertisement() : BelongsTo { return $this->belongsTo(Advertisement::class, 'advertisement_id'); } }
php
10
0.657289
74
20.75
36
starcoderdata
from scrappybara.utils.text import CONSONANTS, VOWELS class Inflector(object): def __init__(self, language_model, lemma_pp): self.__lm = language_model self.__lemma_pp = lemma_pp def past_participle(self, lemma): try: # Irregular return self.__lemma_pp[lemma] except KeyError: # Special endings if len(lemma) > 2: if lemma[-3] in CONSONANTS and lemma.endswith('ie'): return lemma + 'd' if len(lemma) > 1: if lemma[-2] in CONSONANTS and lemma[-1] == 'y': return lemma[:-1] + 'ied' if lemma[-2] in CONSONANTS and lemma.endswith('e'): return lemma + 'd' if lemma[-2] in VOWELS and lemma[-1] in CONSONANTS: best = self.__lm.best_token(lemma + 'ed', lemma + lemma[-1] + 'ed') if best: return best # Standard case return lemma + 'ed'
python
20
0.483716
87
35
29
starcoderdata
using Confluent.Kafka; using Confluent.SchemaRegistry; namespace KafkaFacade { public interface IProducerClient { } }
c#
5
0.734848
36
11.090909
11
starcoderdata
@Override public void loadFromXML(XML xml) { // There must be exactly one top-level child named "conditions" // or "condition". List<XML> bag = xml.getXMLList(Tag.CONDITIONS + "|" + Tag.CONDITION); if (bag.size() != 1) { throw new XMLFlowException("There must be exactly one of " + "<conditions> or <condition> as a direct child element " + "of <if> or <ifNot>. Got instead: \"" + StringUtils.abbreviate(xml.toString(0) .replaceAll("[\n\r]", ""), 40) + "\""); } XMLCondition<T> cond = new XMLCondition<>(flow); cond.loadFromXML(bag.get(0)); this.condition = cond; // There must be exactly one top-level child named "then" // and one optional "else". // TODO enforce in schema that there must be one "then". this.thenConsumer = flow.parse(xml.getXML(Tag.THEN.toString())); this.elseConsumer = flow.parse(xml.getXML(Tag.ELSE.toString())); }
java
15
0.556613
78
46.818182
22
inline
<?php return [ 'create_main_category' => 'إنشاء قسم رئيس جديد', 'main_categories' => 'الأقسام الرئيسية', 'sub_categories' => 'الأقسام الفرعية', 'add_successfully' => 'تم الحفظ بنجاح', 'something_wrong' => 'هناك خطأ ما!', 'user' => 'الصفحة الرئيسية', 'vendors' => 'التجار', 'new_record' => 'صف جديد', 'create_vendor' => 'إضافة تاجر', 'brands' => 'العلامات التجارية', 'languages' => 'اللغات', 'banners' => 'الرايات', 'all' => 'الكل', 'create new' => 'إنشاء جديد', 'coupons' => 'الكوبونات', 'sales' => 'المبيعات', 'orders' => "الطلبات", 'settings' => 'الإعدادات', 'users' => 'المستخدمين', '' => '', ];
php
5
0.407157
62
40.36
25
starcoderdata
package main import ( "fmt" "strings" "github.com/fatih/color" ) const ( lineBreak = "\n" fileStartPrefix = "-- # start # " fileEndPrefix = "-- # end # " ) var ( colorOK = color.New(color.BgGreen, color.FgWhite, color.Bold) colorFail = color.New(color.BgRed, color.FgWhite, color.Bold) colorTestPath = color.New() colorMessage = color.New(color.Bold) colorFailPath = color.New(color.Underline) colorFailChar = color.New(color.FgRed, color.Underline) colorText = color.New() ) type logger interface { ok() failSQL(message, text string, pos int) fail(string) } type stdLog struct { path string } func newStdLog(path string) *stdLog { return &stdLog{path} } func (l *stdLog) ok() { fmt.Println(colorOK.Sprintf(" OK ") + " " + colorTestPath.Sprintf(l.path)) } func (l *stdLog) fail(msg string) { fmt.Printf( "%s %s %s\n", colorFail.Sprint(" FAIL "), colorTestPath.Sprint(l.path), colorMessage.Sprint(msg), ) } func (l *stdLog) failSQL(msg, s string, i int) { l.fail(msg) fmt.Printf( "\n @ %s\n | %s\n\n", colorFailPath.Sprint(pathByIndex(s, i)), colorText.Sprint(textByIndex(s, i)), ) } func pathByIndex(s string, i int) string { endCount := 0 for j := strings.LastIndex(s[:i], lineBreak); j >= 0; j-- { prefixEnd := j + len(fileStartPrefix) if s[j:prefixEnd] == fileStartPrefix { if endCount > 0 { endCount-- continue } return s[prefixEnd : prefixEnd+strings.Index(s[prefixEnd:], lineBreak)] } if s[j:j+len(fileEndPrefix)] == fileEndPrefix { endCount++ } } panic("invalid file") } func textByIndex(s string, i int) string { return s[strings.LastIndex(s[:i], lineBreak)+1:i] + colorFailChar.Sprint(s[i:i+1]) + s[i+1:i+strings.Index(s[i:], lineBreak)] }
go
14
0.648358
77
19.776471
85
starcoderdata
//========= Copyright Valve Corporation, All rights reserved. ============// // // //============================================================================= #ifndef TF_WEAPON_PISTOL_H #define TF_WEAPON_PISTOL_H #ifdef _WIN32 #pragma once #endif #include "tf_weaponbase_gun.h" #include "tf_weapon_shotgun.h" // Client specific. #ifdef CLIENT_DLL #define CTFPistol C_TFPistol #define CTFPistol_Scout C_TFPistol_Scout #define CTFPistol_ScoutPrimary C_TFPistol_ScoutPrimary #define CTFPistol_ScoutSecondary C_TFPistol_ScoutSecondary #endif // We allow the pistol to fire as fast as the player can click. // This is the minimum time between shots. #define PISTOL_FASTEST_REFIRE_TIME 0.1f // The faster the player fires, the more inaccurate he becomes #define PISTOL_ACCURACY_SHOT_PENALTY_TIME 0.2f // Applied amount of time each shot adds to the time we must recover from #define PISTOL_ACCURACY_MAXIMUM_PENALTY_TIME 1.5f // Maximum time penalty we'll allow //============================================================================= // // TF Weapon Pistol. // class CTFPistol : public CTFWeaponBaseGun { public: DECLARE_CLASS( CTFPistol, CTFWeaponBaseGun ); DECLARE_NETWORKCLASS(); DECLARE_PREDICTABLE(); // Server specific. #ifdef GAME_DLL DECLARE_DATADESC(); #endif CTFPistol() {} ~CTFPistol() {} virtual int GetWeaponID( void ) const { return TF_WEAPON_PISTOL; } private: CTFPistol( const CTFPistol & ) {} }; // Scout specific version class CTFPistol_Scout : public CTFPistol { public: DECLARE_CLASS( CTFPistol_Scout, CTFPistol ); DECLARE_NETWORKCLASS(); DECLARE_PREDICTABLE(); virtual int GetWeaponID( void ) const { return TF_WEAPON_PISTOL_SCOUT; } }; class CTFPistol_ScoutPrimary : public CTFPistol_Scout { public: DECLARE_CLASS( CTFPistol_ScoutPrimary, CTFPistol_Scout ); DECLARE_NETWORKCLASS(); DECLARE_PREDICTABLE(); CTFPistol_ScoutPrimary(); virtual int GetViewModelWeaponRole() { return TF_WPN_TYPE_SECONDARY; } virtual int GetWeaponID( void ) const { return TF_WEAPON_HANDGUN_SCOUT_PRIMARY; } virtual void PlayWeaponShootSound( void ); virtual void SecondaryAttack( void ); virtual void ItemPostFrame(); virtual bool Holster( CBaseCombatWeapon *pSwitchingTo ); virtual void Precache( void ); void Push( void ); private: float m_flPushTime; }; class CTFPistol_ScoutSecondary : public CTFPistol_Scout { public: DECLARE_CLASS( CTFPistol_ScoutSecondary, CTFPistol_Scout ); DECLARE_NETWORKCLASS(); DECLARE_PREDICTABLE(); virtual int GetViewModelWeaponRole() { return TF_WPN_TYPE_SECONDARY; } virtual int GetWeaponID( void ) const { return TF_WEAPON_HANDGUN_SCOUT_SECONDARY; } virtual int GetDamageType( void ) const; }; #endif // TF_WEAPON_PISTOL_H
c
11
0.703453
121
25.761905
105
starcoderdata
private void testStress(final QualityOfServiceMode qosMode, final boolean persistent, final int batchSize) throws Exception { Connection connSource = null; JMSBridgeImpl bridge = null; Thread t = null; ConnectionFactoryFactory factInUse0 = cff0; ConnectionFactoryFactory factInUse1 = cff1; if (qosMode.equals(QualityOfServiceMode.ONCE_AND_ONLY_ONCE)) { factInUse0 = cff0xa; factInUse1 = cff1xa; ServiceUtils.setTransactionManager(newTransactionManager()); } try { bridge = new JMSBridgeImpl(factInUse0, factInUse1, sourceQueueFactory, targetQueueFactory, null, null, null, null, null, 5000, 10, qosMode, batchSize, -1, null, null, false).setBridgeName("test-bridge"); bridge.start(); connSource = cf0.createConnection(); Session sessSend = connSource.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sessSend.createProducer(sourceQueue); final int NUM_MESSAGES = 250; StressSender sender = new StressSender(); sender.sess = sessSend; sender.prod = prod; sender.numMessages = NUM_MESSAGES; prod.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT); t = new Thread(sender); t.start(); checkAllMessageReceivedInOrder(cf1, targetQueue, 0, NUM_MESSAGES, false); t.join(); if (sender.ex != null) { // An error occurred during the send throw sender.ex; } } finally { if (t != null) { t.join(10000); } if (connSource != null) { try { connSource.close(); } catch (Exception e) { JMSBridgeTest.log.error("Failed to close connection", e); } } if (bridge != null) { bridge.stop(); } } }
java
15
0.581095
212
29.014925
67
inline
int ClockAnalog::adjust_time(time_t iv_time) { time_t sys_time = iv_time; time_t clock_time = _mv_clock_time; time_t diff_time; int lv_diff_sec; // pulses are allowed _mv_no_pulse = false; _mv_diff_sec = 0; if (clock_time == sys_time) { return _mv_diff_sec; } if (clock_time < sys_time) { // Clock behind system time // calculate difference diff_time = sys_time - clock_time; //DebugPrint("Diff : " + String(year(diff_time)) + "." + String(month(diff_time)) + "." + String(day(diff_time)) ); //DebugPrintln(", " + String(hour(diff_time)) + ":" + String(minute(diff_time)) + ":" + String(second(diff_time)) ); // if difference > 12h -> calculate remainder and add the rest to actual time // it makes no sense to catch up with greater differences if ( diff_time >= gc_12h_sec ){ int diff_rem = diff_time % gc_12h_sec; // add Difference minus remainder to actual time _mv_clock_time = _mv_clock_time + diff_time - diff_rem; // Continue with remainder diff_time = diff_rem; } // convert Difference to int lv_diff_sec = diff_time; // Don't adjust a difference of 1 sec, this would just lead to jitter ... if ( lv_diff_sec > 1) { _mv_diff_sec = lv_diff_sec; } } else { // Clock in front system time // so we have to wait and don't do any pulses _mv_no_pulse = true; } return _mv_diff_sec; }
c++
11
0.580081
120
29
48
inline
import numpy as np import math from scipy import signal def get_slice(strain, merger_time, window_size = None, step = 1, axis = -1): """ :param strain: :param merger_time: :param window_size: :param step: :param axis: :return: """ if not window_size: fs = 4096 window_size = 2 * fs bound_low = np.floor(merger_time - np.floor(window_size/2)).astype(int) bound_up = np.floor(merger_time + np.floor(window_size/2)).astype(int) return strain.take(indices=range(bound_low, bound_up, step), axis=axis) def get_slice_noise(strain, merger_time, cut_window = None, step = 1, axis = -1): """ :param strain: :param merger_time: :param cut_window: :param step: :param axis: :return: """ if not cut_window: fs = 4096 cut_window = [9*fs, 1*fs] # for ifo, val in enumerate(strain): bound_low = np.floor(merger_time - cut_window[0]).astype(int) bound_up = np.floor(merger_time - cut_window[-1]).astype(int) return strain.take(indices=range(bound_low, bound_up, step), axis=axis) def nexpow2(x): """ :param x: :return: """ return 1 if x == 0 else 2**math.ceil(math.log2(x)) def rolling_window(data, window_len, noverlap=1, padded=False, axis=-1, copy=True): """ Calculate a rolling window over a data :param data: numpy array. The array to be slided over. :param window_len: int. The rolling window size :param noverlap: int. The rolling window stepsize. Defaults to 1. :param padded: :param axis: int. The axis to roll over. Defaults to the last axis. :param copy: bool. Return strided array as copy to avoid sideffects when manipulating the output array. :return: numpy array A matrix where row in last dimension consists of one instance of the rolling window. See Also -------- pieces : Calculate number of pieces available by rolling """ data = data if isinstance(data, np.ndarray) else np.array(data) assert axis < data.ndim, "Array dimension is less than axis" assert noverlap >= 1, "Minimum overlap cannot be less than 1" assert window_len <= data.shape[axis], "Window size cannot exceed the axis length" arr_shape = list(data.shape) arr_shape[axis] = np.floor(data.shape[axis] / noverlap - window_len / noverlap + 1).astype(int) arr_shape.append(window_len) strides = list(data.strides) strides[axis] *= noverlap strides.append(data.strides[axis]) strided = np.lib.stride_tricks.as_strided( data, shape=arr_shape, strides=strides ) if copy: return strided.copy() else: return strided def p_corr(x, y, tau): """ :param x: :param y: :param tau: :return: """ if len(x) != len(y): print("The arrays must be of the same length!") return if tau > 0: x = x[:-tau] y = y[tau:] elif tau != 0: x = x[np.abs(tau):] y = y[:-np.abs(tau)] n = len(x) x = x - np.mean(x) y = y - np.mean(y) std_x = np.std(x) std_y = np.std(y) cov = np.sum(x * y) / (n - 1) cr = cov / (std_x * std_y) cr_err = np.std(x * y) / (np.sqrt(n) * std_x * std_y) \ + cr * (np.std(x ** 2) / (2 * std_x ** 2) + np.std(y ** 2) / (2 * std_y ** 2)) / np.sqrt(n) return cr, cr_err # ============================================================================= # Filters taken from pycbc # Reference: https://github.com/gwastro/pycbc # ============================================================================= def fir_zero_filter(coeff, timeseries): """Filter the timeseries with a set of FIR coefficients Parameters ---------- coeff: numpy.ndarray FIR coefficients. Should be and odd length and symmetric. timeseries: pycbc.types.TimeSeries Time series to be filtered. Returns ------- filtered_series: pycbc.types.TimeSeries Return the filtered timeseries, which has been properly shifted to account for the FIR filter delay and the corrupted regions zeroed out. """ # apply the filter series = signal.lfilter(coeff, 1.0, timeseries) # reverse the time shift caused by the filter, # corruption regions contain zeros # If the number of filter coefficients is odd, the central point *should* # be included in the output so we only zero out a region of len(coeff) - 1 series[:(len(coeff) // 2) * 2] = 0 series.roll(-len(coeff)//2) return series def notch_fir(timeseries, f1, f2, order, beta=5.0): """ notch filter the time series using an FIR filtered generated from the ideal response passed through a time-domain kaiser window (beta = 5.0) The suppression of the notch filter is related to the bandwidth and the number of samples in the filter length. For a few Hz bandwidth, a length corresponding to a few seconds is typically required to create significant suppression in the notched band. To achieve frequency resolution df at sampling frequency fs, order should be at least fs/df. Parameters ---------- Time Series: TimeSeries The time series to be notched. f1: float The start of the frequency suppression. f2: float The end of the frequency suppression. order: int Number of corrupted samples on each side of the time series (Extent of the filter on either side of zero) beta: float Beta parameter of the kaiser window that sets the side lobe attenuation. """ k1 = f1 / float((int(1.0 / timeseries.delta_t) / 2)) k2 = f2 / float((int(1.0 / timeseries.delta_t) / 2)) coeff = signal.firwin(order * 2 + 1, [k1, k2], window=('kaiser', beta)) return fir_zero_filter(coeff, timeseries) def lowpass_fir(timeseries, frequency, order, beta=5.0): """ Lowpass filter the time series using an FIR filtered generated from the ideal response passed through a kaiser window (beta = 5.0) Parameters ---------- Time Series: TimeSeries The time series to be low-passed. frequency: float The frequency below which is suppressed. order: int Number of corrupted samples on each side of the time series beta: float Beta parameter of the kaiser window that sets the side lobe attenuation. """ k = frequency / float((int(1.0 / timeseries.delta_t) / 2)) coeff = signal.firwin(order * 2 + 1, k, window=('kaiser', beta)) return fir_zero_filter(coeff, timeseries) def highpass_fir(timeseries, frequency, order, beta=5.0): """ Highpass filter the time series using an FIR filtered generated from the ideal response passed through a kaiser window (beta = 5.0) Parameters ---------- Time Series: TimeSeries The time series to be high-passed. frequency: float The frequency below which is suppressed. order: int Number of corrupted samples on each side of the time series beta: float Beta parameter of the kaiser window that sets the side lobe attenuation. """ k = frequency / float((int(1.0 / timeseries.delta_t) / 2)) coeff = signal.firwin(order * 2 + 1, k, window=('kaiser', beta), pass_zero=False) return fir_zero_filter(coeff, timeseries) # ============================================================================= # # ============================================================================= def time_slice(timeseries, start, end, mode='floor'): """Return the slice of the time series that contains the time range in GPS seconds. """ # if start < timeseries.start_time: # raise ValueError('Time series does not contain a time as early as %s' % start) # if end > timeseries.end_time: # raise ValueError('Time series does not contain a time as late as %s' % end) start_idx = float(start) * timeseries.sample_rate end_idx = fload(end) * timeseries.sample_rate # start_idx = float(start - self.start_time) * self.sample_rate # end_idx = float(end - self.start_time) * self.sample_rate if _numpy.isclose(start_idx, round(start_idx)): start_idx = round(start_idx) if _numpy.isclose(end_idx, round(end_idx)): end_idx = round(end_idx) if mode == 'floor': start_idx = int(start_idx) end_idx = int(end_idx) elif mode == 'nearest': start_idx = int(round(start_idx)) end_idx = int(round(end_idx)) else: raise ValueError("Invalid mode: {}".format(mode)) return timeseries[start_idx:end_idx]
python
14
0.606887
99
32.542636
258
starcoderdata
/* ----------------------------------------------------------------------------- * Copyright (c) 2011 Ozmo Inc * Released under the GNU General Public License Version 2 (GPLv2). * ----------------------------------------------------------------------------- */ #ifndef _OZUSBIF_H #define _OZUSBIF_H #include <linux/usb.h> /* Reference counting functions. */ void oz_usb_get(void *hpd); void oz_usb_put(void *hpd); /* Stream functions. */ int oz_usb_stream_create(void *hpd, u8 ep_num); int oz_usb_stream_delete(void *hpd, u8 ep_num); /* Request functions. */ int oz_usb_control_req(void *hpd, u8 req_id, struct usb_ctrlrequest *setup, const u8 *data, int data_len); int oz_usb_get_desc_req(void *hpd, u8 req_id, u8 req_type, u8 desc_type, u8 index, __le16 windex, int offset, int len); int oz_usb_send_isoc(void *hpd, u8 ep_num, struct urb *urb); void oz_usb_request_heartbeat(void *hpd); /* Confirmation functions. */ void oz_hcd_get_desc_cnf(void *hport, u8 req_id, int status, const u8 *desc, int length, int offset, int total_size); void oz_hcd_control_cnf(void *hport, u8 req_id, u8 rcode, const u8 *data, int data_len); /* Indication functions. */ void oz_hcd_data_ind(void *hport, u8 endpoint, const u8 *data, int data_len); int oz_hcd_heartbeat(void *hport); #endif /* _OZUSBIF_H */
c
7
0.607768
80
29.534884
43
research_code
from alpyro_msgs import RosMessage, float32 class ShapeResult(RosMessage): __msg_typ__ = "turtle_actionlib/ShapeResult" __msg_def__ = "ZmxvYXQzMiBpbnRlcmlvcl9hbmdsZQpmbG9hdDMyIGFwb3RoZW0KCg==" __md5_sum__ = "b06c6e2225f820dbc644270387cd1a7c" interior_angle: float32 apothem: float32
python
6
0.770898
74
28.363636
11
starcoderdata
<?php namespace Frontend\Modules\FormBuilder\EventListener; use Frontend\Modules\FormBuilder\Event\FormBuilderSubmittedEvent; use Frontend\Modules\FormBuilder\Engine\Model as FrontendFormBuilderModel; /** * A Formbuilder submitted event subscriber that will send a notification * * @author */ final class FormBuilderSubmittedNotificationSubscriber { /** * @param FormBuilderSubmittedEvent $event */ public function onFormSubmitted(FormBuilderSubmittedEvent $event) { $form = $event->getForm(); FrontendFormBuilderModel::notifyAdmin( array( 'form_id' => $form['id'], 'entry_id' => $event->getDataId(), ) ); } }
php
13
0.658108
74
25.428571
28
starcoderdata
import os from arxiv.docs.factory import create_web_app as base_create os.environ['SITE_NAME'] = 'api' os.environ['STATIC_ROOT'] = os.path.abspath('./api/static/') + '/' os.environ['TEMPLATE_ROOT'] = os.path.abspath('./api/templates/') + '/' def create_web_app(): return base_create() app = create_web_app()
python
7
0.667674
71
26.583333
12
starcoderdata
<?php declare(strict_types=1); namespace Smsapi\Client\Feature\Mfa\Data; use stdClass; /** * @internal */ class MfaFactory { public function createFromObject(stdClass $object): Mfa { $mfa = new Mfa(); $mfa->id = $object->id; $mfa->code = $object->code; $mfa->phoneNumber = $object->phone_number; $mfa->from = $object->from; return $mfa; } }
php
9
0.578824
59
16
25
starcoderdata
def move(self, move: 'StandardMove') -> Optional['Piece']: """ try to execute given move, return captured piece if not fails """ self.assert_move(move) source, destination = move.source, move.destination moved_piece = self.board.get_piece(position=source) if moved_piece.side != self.on_move: raise WrongMoveOrder("You are trying to move %s when %s are on move" % (moved_piece.side, self.on_move)) # move are accepted by the game logic, all below concerns game state (counters, history, proper move execution) self.save_history() moved_piece = self.board.remove_piece(position=source) taken_piece = self.board.put_piece(piece=moved_piece, position=destination) if isinstance(moved_piece, Pawn): if destination == self.en_passant: # check if en passant move was involved taken_piece = self.board.remove_piece(StandardPosition((destination.file, source.rank))) # check if pawn was pushed by two fields, set needed en passant position if so if abs(source.rank - destination.rank) == 2: self.__en_passant = StandardPosition( (source.file, int((source.rank + destination.rank) / 2)) ) else: # clear en passant position on any other pawn-move self.__en_passant = None self.__half_moves_since_pawn_moved = 0 if destination.rank in (7, 0): # handle promotion self.board.put_piece(move.promotion(self.on_move), destination) else: # clear en passant position on any other piece-move if self.__en_passant: self.__en_passant = None self.__half_moves_since_pawn_moved += 1 # simple and ugly check for castling execution if isinstance(moved_piece, King) and abs(source.file - destination.file) == 2: rank = source.rank if move.destination.file == 6: # king-castle moved_rook = self.board.remove_piece(position=StandardPosition((7, rank))) self.board.put_piece(moved_rook, StandardPosition((5, rank))) elif destination.file == 2: # queen-castle moved_rook = self.board.remove_piece(position=StandardPosition((0, rank))) self.board.put_piece(moved_rook, StandardPosition((3, rank))) if not taken_piece: self.__half_moves_since_capture += 1 else: self.__half_moves_since_capture = 0 self.__pocket[self.on_move].append(taken_piece) # put taken piece to the side pocket! self.__update_castling_info(source, destination) self.__position_occurence[hash(self.board)] += 1 self.moves_history.append(move) self.__half_moves += 1 return taken_piece
python
18
0.602626
119
49.789474
57
inline
import numpy as np import numba from numba import prange #Function to update B and R for a single node by maximising benefit sum from left and right subtrees of the node def node_update_b(k, indexes, child0, child1, T_node, T_child0, T_child1, B_child0, B_child1): alpha = min(k, T_node) R_min, R_max = np.maximum(1, indexes-T_child0), np.minimum(T_child1, indexes-1) B_ret, R_ret = np.zeros((alpha-1,)), np.zeros((alpha-1,), dtype=np.int32) for i in range(2, alpha+1): B_node = B_child1[R_min[i-2]-1:R_max[i-2]] + (B_child0[i-R_max[i-2]-1:i-R_min[i-2]])[::-1] # print(B_node) B_ret[i-2], R_ret[i-2] = np.max(B_node), R_min[i-2]+np.argmax(B_node) return B_ret, R_ret #Function to update B and R for a single node by maximising benefit sum from left and right subtrees of the node #Stores fg and bg rather storing Benefit, reduces floating point error # TODO - Speedup def node_update_b_vectorized(k, w, indexes, child0, child1, T_node, T_child0, T_child1, Bf_child0, Bf_child1, Bb_child0, Bb_child1): alpha = min(k, T_node) R_min, R_max = np.maximum(1, indexes-T_child0), np.minimum(T_child1, indexes-1) R_ret = np.zeros((alpha-1,), dtype=np.int32) Bf_ret, Bb_ret = np.zeros((alpha-1,), dtype=np.int32), np.zeros((alpha-1,), dtype=np.int32) for i in range(2, alpha+1): B_f = (Bf_child1[R_min[i-2]-1:R_max[i-2]]) + (Bf_child0[i-R_max[i-2]-1:i-R_min[i-2]])[::-1] B_b = Bb_child1[R_min[i-2]-1:R_max[i-2]] + (Bb_child0[i-R_max[i-2]-1:i-R_min[i-2]])[::-1] B_node = B_f - (w*B_b) R_ret[i-2] = R_min[i-2]+np.argmax(B_node) Bf_ret[i-2], Bb_ret[i-2] = B_f[R_ret[i-2]-R_min[i-2]], B_b[R_ret[i-2]-R_min[i-2]] return Bf_ret, Bb_ret, R_ret #Function to update B and R for a single node by maximising benefit sum from left and right subtrees of the node def node_update_c(k, indexes, child0, child1, T_node, T_child0, T_child1, B_child0, B_child1): alpha = min(k, T_node) R_min, R_max = np.maximum(0, indexes-T_child0), np.minimum(T_child1, indexes) B_ret, R_ret = np.zeros((alpha,)), np.zeros((alpha,), dtype=np.int32) for i in range(1, alpha+1): B_node = B_child1[R_min[i-1]:R_max[i-1]+1] + (B_child0[i-R_max[i-1]:i-R_min[i-1]+1])[::-1] B_ret[i-1], R_ret[i-1] = np.max(B_node), R_min[i-1]+np.argmax(B_node) return B_ret, R_ret #Function to update B and R for a single node by maximising benefit sum from left and right subtrees of the node def node_update_d(k, indexes, child0, child1, T_node, T_child0, T_child1, Bplus_child0, Bneg_child0, Bplus_child1, Bneg_child1): alpha = min(k, T_node) R_min, R_max = np.maximum(0, indexes-T_child0), np.minimum(T_child1, indexes) Bplus_ret, Rplus_ret = np.zeros((alpha,)), np.zeros((alpha,), dtype=np.int32) Bneg_ret, Rneg_ret = np.zeros((alpha,)), np.zeros((alpha,), dtype=np.int32) for i in range(1, alpha+1): Bplus_node = Bplus_child1[R_min[i-1]:R_max[i-1]+1] + (Bplus_child0[i-R_max[i-1]:i-R_min[i-1]+1])[::-1] Bneg_node = Bneg_child1[R_min[i-1]:R_max[i-1]+1] + (Bneg_child0[i-R_max[i-1]:i-R_min[i-1]+1])[::-1] Bplus_ret[i-1], Rplus_ret[i-1] = np.max(Bplus_node), R_min[i-1]+np.argmax(Bplus_node) Bneg_ret[i-1], Rneg_ret[i-1] = np.min(Bneg_node), R_min[i-1]+np.argmin(Bneg_node) return Bplus_ret, Bneg_ret, Rplus_ret, Rneg_ret #Update Benefit and Belong (+ve and -ve) for a node def b_belong_update_d(T_node, Attr, Bplus_node, Bneg_node, belongplus_node, belongneg_node, Rplus_node, Rneg_node): for i in range(T_node,0,-1): if(Attr-Bplus_node[i-1] >= Bneg_node[i]): belongneg_node[i-1] = False else: Bneg_node[i], Rneg_node[i], belongneg_node[i-1] = Attr-Bplus_node[i-1], Rplus_node[i-1], True if(Attr-Bneg_node[i-1] <= Bplus_node[i]): belongplus_node[i-1] = False else: Bplus_node[i], Rplus_node[i], belongplus_node[i-1] = Attr-Bneg_node[i-1], Rneg_node[i-1], True return Bplus_node, Bneg_node, belongplus_node, belongneg_node, Rplus_node, Rneg_node
python
16
0.617373
132
52.576923
78
starcoderdata
package com.example.demo.util; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Random; public class Img2String implements Runnable{ private String url; public Img2String(String url){ this.url = url; } /** * 将图片转换为字符串 * @throws Exception */ public String image2txt() { String str = ".:!$"; int[] rgb = new int[3]; File file = new File(url); BufferedImage bi = null; try { bi = ImageIO.read(file); } catch (Exception e) { return null; } int width = bi.getWidth(); int height = bi.getHeight(); int minx = bi.getMinX(); int miny = bi.getMinY(); StringBuilder sb=new StringBuilder(); for (int i = miny; i < height; i+=5) { for (int j = minx; j < width; j+=5) { int pixel = bi.getRGB(j, i); // 下面三行代码将一个数字转换为RGB数字 rgb[0] = (pixel & 0xff0000) >> 16; rgb[1] = (pixel & 0xff00) >> 8; rgb[2] = (pixel & 0xff); //判断接近白色还是黑色,接近白色写入空格,接近黑色写入字符串 if (rgb[0] > 200&&rgb[1]>200&&rgb[2]>200) { sb.append(str.charAt(0)); } else if (rgb[0] > 150&&rgb[1]>150&&rgb[2]>150){ sb.append(str.charAt(1)); }else if (rgb[0] > 100&&rgb[1]>100&&rgb[2]>100){ sb.append(str.charAt(2)); }else { sb.append(str.charAt(3)); } } sb.append("\n"); } return sb.toString(); } /** * 将字符串写入文件 * @param filePath * @param content */ public void writeToTxt(String filePath, String content) { BufferedWriter out = null; try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true),"UTF-8")); out.write(content); } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 将bufferImage写入图片 * @param path * @param image */ public void writeToImg(String path,BufferedImage image){ try { ImageIO.write(image, "jpg", new File(path)); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { image2txt(); // writeToImg(image, "d:mine.jpg"); } }
java
18
0.483356
107
27.742268
97
starcoderdata
package main; import fenster.Eingabe; import fenster.Hauptfenster; public class Main { public static void main(String[] args) { //new Hauptfenster(5, "MS 1", "MS 2"); new Eingabe(); } }
java
6
0.674797
41
15.642857
14
starcoderdata
#include <stdio.h> #include <ctype.h> #include <assert.h> #include <iostream> #include <string> #include <vector> #include <map> using namespace std; #define rep(i, n) for(int i=0; i<(int)(n); i++) string token, _s; unsigned _ix; void next() { if(_ix>=_s.size()) token = ""; else { unsigned k = _ix; if(!isdigit(_s[_ix])) _ix++; else while(_ix<_s.size() && isdigit(_s[_ix])) _ix++; token = _s.substr(k, _ix-k); } } unsigned myatoi(const string& s) { unsigned a = 0; rep(i, s.size()) a = a*10+s[i]-'0'; return a; } typedef vector<vector<unsigned> > mat; inline int rsize(const mat& a) { return a.size(); } inline int csize(const mat& a) { assert(rsize(a)>0); return a[0].size(); } mat mul(const mat& a, const mat& b) { if(csize(a)==1 && rsize(a)==1) { mat r(rsize(b), vector<unsigned>(csize(b))); rep(i, rsize(r)) rep(j, csize(r)) r[i][j] = a[0][0]*b[i][j]; return r; } else if(csize(b)==1 && rsize(b)==1) return mul(b, a); else { assert(csize(a)==rsize(b)); mat r(rsize(a), vector<unsigned>(csize(b))); rep(i, rsize(a)) rep(j, csize(b)) rep(k, csize(a)) { r[i][j]+=a[i][k]*b[k][j]; } return r; } } void print(const mat& a) { rep(i, rsize(a)) rep(j, csize(a)) { printf("%d%c", a[i][j]%(1<<15), j<csize(a)-1 ? ' ' : '\n'); } } map<char, mat> vars; mat expr(), term(), factor(), primary(), row(); mat parse(const string& src) { _s = src; _ix = 0; next(); return expr(); } mat expr() { mat r(term()); while(token=="+" || token=="-") { char op = token[0]; next(); mat t(term()); assert(rsize(r)==rsize(t)); assert(csize(r)==csize(t)); if(op=='+') rep(i, rsize(r)) rep(j, csize(r)) r[i][j] += t[i][j]; if(op=='-') rep(i, rsize(r)) rep(j, csize(r)) r[i][j] -= t[i][j]; } return r; } mat term() { mat r(factor()); while(token=="*") { next(); r = mul(r, factor()); } return r; } mat factor() { if(token!="-") return primary(); else { next(); mat r(factor()); rep(i, rsize(r)) rep(j, csize(r)) r[i][j] = -r[i][j]; return r; } } mat primary() { mat r; if(isdigit(token[0])) r = mat(1, vector<unsigned>(1, myatoi(token))); else if(isupper(token[0])) r = vars[token[0]]; else if(token[0]=='(') { next(); r = expr(); assert(token==")"); } else { assert(token=="["); next(); r = row(); while(token==";") { next(); mat t(row()); assert(csize(r)==csize(t)); rep(i, rsize(t)) r.push_back(t[i]); } assert(token=="]"); } next(); while(token=="'" || token=="(") { if(token=="'") { next(); mat t(csize(r), vector<unsigned>(rsize(r))); rep(i, rsize(r)) rep(j, csize(r)) t[j][i] = r[i][j]; r = t; } else if(token=="(") { next(); mat ix(expr()); assert(token==","); next(); mat jx(expr()); assert(token==")"); next(); mat t(csize(ix), vector<unsigned>(csize(jx))); rep(i, csize(ix)) rep(j, csize(jx)) { t[i][j] = r[ix[0][i]-1][jx[0][j]-1]; } r = t; } } return r; } mat row() { mat r(expr()); while(token==" ") { next(); mat t(expr()); assert(rsize(r)==rsize(t)); rep(i, rsize(r)) rep(j, csize(t)) r[i].push_back(t[i][j]); } return r; } int main() { for(;;) { string s; getline(cin, s); const int n = myatoi(s); if(n==0) return 0; vars.clear(); rep(i, n) { getline(cin, s); const char var = s[0]; mat r(parse(s.substr(2))); print(r); vars[var] = r; } puts("-----"); } return 0; }
c++
20
0.431406
73
22.331429
175
codenet
def _test_optimise_method(self, minimise_method, maximise_method, test_success=True): """ Tests an optimiser method. """ num_min_successes = 0 num_max_successes = 0 for prob in self.problems: # First the minimimum if prob.min_val is not None: min_val_soln, min_pt_soln, _ = minimise_method(prob.obj, prob.bounds, self.max_evals) val_diff = abs(prob.min_val - min_val_soln) point_diff = np.linalg.norm(prob.min_pt - min_pt_soln) self.report(prob.descr + '(min):: true-val: %0.4f, soln: %0.4f, diff: %0.4f.'%(prob.min_val, min_val_soln, val_diff), 'test_result') self.report(prob.descr + '(min):: true-pt: %s, soln: %s, diff: %0.4f.'%(prob.min_pt, min_pt_soln, point_diff), 'test_result') min_is_successful = val_diff < 1e-3 and point_diff < 1e-3 * prob.dim num_min_successes += min_is_successful else: num_min_successes += 1 # Now the maximum if prob.max_val is not None: max_val_soln, max_pt_soln, _ = maximise_method(prob.obj, prob.bounds, self.max_evals) val_diff = abs(prob.max_val - max_val_soln) point_diff = np.linalg.norm(prob.max_pt - max_pt_soln) self.report(prob.descr + '(max):: true-val: %0.4f, soln: %0.4f, diff: %0.4f.'%(prob.max_val, max_val_soln, val_diff), 'test_result') self.report(prob.descr + '(max):: true-pt: %s, soln: %s, diff: %0.4f.'%(prob.max_pt, max_pt_soln, point_diff), 'test_result') max_is_successful = val_diff < 1e-3 and point_diff < 1e-3 * prob.dim num_max_successes += max_is_successful else: num_max_successes += max_is_successful # Check if successful if test_success: assert num_min_successes == len(self.problems) assert num_max_successes == len(self.problems)
python
14
0.553946
85
47.853659
41
inline
from setuptools import setup from distutils.extension import Extension import sys try: from Cython.Distutils import build_ext CYTHON = True except: CYTHON = False DEPENDENCIES = ['setuptools'] # get the version without an import VERSION = "Undefined" DOC = "" inside_doc = False for line in open('vcf/__init__.py'): if "'''" in line: inside_doc = not inside_doc if inside_doc: DOC += line.replace("'''", "") if (line.startswith('VERSION')): exec(line.strip()) extras = {} if CYTHON: extras['cmdclass'] = {'build_ext': build_ext} extras['ext_modules'] = [Extension("vcf.cparse", ["vcf/cparse.pyx"])] setup( name='PyVCF', packages=['vcf', 'vcf.test'], scripts=['scripts/vcf_melt', 'scripts/vcf_filter.py', 'scripts/vcf_sample_filter.py'], author=' and @jdoughertyii', author_email=' description='Variant Call Format (VCF) parser for Python', long_description=DOC, test_suite='vcf.test.test_vcf.suite', install_requires=DEPENDENCIES, entry_points = { 'vcf.filters': [ 'site_quality = vcf.filters:SiteQuality', 'vgq = vcf.filters:VariantGenotypeQuality', 'eb = vcf.filters:ErrorBiasFilter', 'dps = vcf.filters:DepthPerSample', 'avg-dps = vcf.filters:AvgDepthPerSample', 'snp-only = vcf.filters:SnpOnly', ] }, url='https://github.com/jamescasbon/PyVCF', version=VERSION, classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Cython', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Scientific/Engineering :: Bio-Informatics', ], keywords='bioinformatics', include_package_data=True, package_data = { '': ['*.vcf', '*.gz', '*.tbi'], }, **extras )
python
10
0.593911
73
31.012658
79
starcoderdata
/********************************************************************** This source file is a part of Demi3D __ ___ __ __ __ | \|_ |\/|| _)| \ |__/|__| || __)|__/ Copyright (c) 2013-2014 Demi team https://github.com/wangyanxing/Demi3D Released under the MIT License https://github.com/wangyanxing/Demi3D/blob/master/License.txt ***********************************************************************/ #include "FxerPch.h" #include "EmitterBaseObj.h" #include "HonFxerApp.h" #include "EditorManager.h" #include "EffectManager.h" #include "ParticleElementObj.h" #include "ParticleElement.h" #include "ParticleEmitter.h" #include "PropertyItem.h" #include "K2Clip.h" #include "K2Model.h" #include "EnumProperties.h" namespace Demi { DiEmitterBaseObj::DiEmitterBaseObj() { } DiEmitterBaseObj::~DiEmitterBaseObj() { } void DiEmitterBaseObj::OnMenuPopup(MyGUI::PopupMenu* menu, bool multiSelection) { DiEditorManager::Get()->SetCurrentSelection(this); menu->removeAllItems(); menu->addItem("Delete", MyGUI::MenuItemType::Normal, "removeObj"); } void DiEmitterBaseObj::OnDestroy() { mEmitter->SetParentElement(nullptr); auto parent = dynamic_cast parent->GetParticleElement()->DestroyEmitter(mEmitter); } void DiEmitterBaseObj::OnSelect() { DiBaseEditorObj::OnSelect(); } DiString DiEmitterBaseObj::GetUICaption() { return mEmitter->GetName(); } DiK2Skeleton* DiEmitterBaseObj::GetAttachedSkeleton() { return mEmitter ? mEmitter->GetAttachedSkeleton() : nullptr; } void DiEmitterBaseObj::OnCreate() { DiBaseEditorObj::OnCreate(); auto parent = dynamic_cast mEmitter = parent->GetParticleElement()->CreateEmitter(GetEmitterType()); mEmitter->SetName(DiEditorManager::Get()->GenerateEmitterName(GetEmitterType())); } void DiEmitterBaseObj::OnCreate(const DiAny& param) { DiBaseEditorObj::OnCreate(); mEmitter = any_cast DI_ASSERT(mEmitter); if(mEmitter->GetName().empty()) { mEmitter->SetName(DiEditorManager::Get()->GenerateEmitterName(GetEmitterType())); } } void DiEmitterBaseObj::ChangeAttachBone() { mEmitter->SetBone(mBoneName); } void DiEmitterBaseObj::InitPropertyTable() { DiPropertyGroup* g = DI_NEW DiPropertyGroup("Emitter"); g->AddProperty("Name" , DI_NEW DiStringProperty([&]{ return mEmitter->GetName(); }, [&](DiString& val){ mEmitter->SetName(val); })); g->AddProperty("Emission Rate" , DI_NEW DiDynProperty([&]{ return mEmitter->GetDynEmissionRate(); }, [&](DiDynamicAttribute*& val){ mEmitter->SetDynEmissionRate(val); })); g->AddProperty("Angle" , DI_NEW DiDynProperty([&]{ return mEmitter->GetDynAngle(); }, [&](DiDynamicAttribute*& val){ mEmitter->SetDynAngle(val); })); g->AddProperty("Life" , DI_NEW DiDynProperty([&]{ return mEmitter->GetDynTotalTimeToLive(); }, [&](DiDynamicAttribute*& val){ mEmitter->SetDynTotalTimeToLive(val); })); g->AddProperty("Mass" , DI_NEW DiDynProperty([&]{ return mEmitter->GetDynParticleMass(); }, [&](DiDynamicAttribute*& val){ mEmitter->SetDynParticleMass(val); })); g->AddProperty("Velocity" , DI_NEW DiDynProperty([&]{ return mEmitter->GetDynVelocity(); }, [&](DiDynamicAttribute*& val){ mEmitter->SetDynVelocity(val); })); g->AddProperty("Duration" , DI_NEW DiDynProperty([&]{ return mEmitter->GetDynDuration(); }, [&](DiDynamicAttribute*& val){ mEmitter->SetDynDuration(val); })); g->AddProperty("Repeat Delay" , DI_NEW DiDynProperty([&]{ return mEmitter->GetDynRepeatDelay(); }, [&](DiDynamicAttribute*& val){ mEmitter->SetDynRepeatDelay(val); })); g->AddProperty("Dimensions" , DI_NEW DiDynProperty([&]{ return mEmitter->GetDynParticleAllDimensions(); }, [&](DiDynamicAttribute*& val){ mEmitter->SetDynParticleAllDimensions(val); })); g->AddProperty("Width" , DI_NEW DiDynProperty([&]{ return mEmitter->GetDynParticleWidth(); }, [&](DiDynamicAttribute*& val){ mEmitter->SetDynParticleWidth(val); })); g->AddProperty("Height" , DI_NEW DiDynProperty([&]{ return mEmitter->GetDynParticleHeight(); }, [&](DiDynamicAttribute*& val){ mEmitter->SetDynParticleHeight(val); })); g->AddProperty("Depth" , DI_NEW DiDynProperty([&]{ return mEmitter->GetDynParticleDepth(); }, [&](DiDynamicAttribute*& val){ mEmitter->SetDynParticleDepth(val); })); g->AddProperty("Original Enabled", DI_NEW DiBoolProperty([&]{ return mEmitter->GetOriginalEnabled(); }, [&](bool& val){ mEmitter->SetOriginalEnabled(val); })); auto prop = g->AddProperty("Position", DI_NEW DiVec3Property([&] { return mEmitter->position; }, [&](DiVec3& val){ mEmitter->position = val; NotifyTransfromUpdate(); })); mPositionProp = static_cast g->AddProperty("Keep Local" , DI_NEW DiBoolProperty([&]{ return mEmitter->IsKeepLocal(); }, [&](bool& val){ mEmitter->SetKeepLocal(val); })); g->AddProperty("Orientation" , DI_NEW DiQuatProperty([&]{ return mEmitter->GetParticleOrientation(); }, [&](DiQuat& val){ mEmitter->SetParticleOrientation(val); })); g->AddProperty("Color" , DI_NEW DiColorProperty([&]{ return mEmitter->GetParticleColour(); }, [&](DiColor& val){ mEmitter->SetParticleColour(val); })); g->AddProperty("Auto Direction" , DI_NEW DiBoolProperty([&]{ return mEmitter->IsAutoDirection(); }, [&](bool& val){ mEmitter->SetAutoDirection(val); })); g->AddProperty("Force Emission" , DI_NEW DiBoolProperty([&]{ return mEmitter->IsForceEmission(); }, [&](bool& val){ mEmitter->SetForceEmission(val); })); g->AddProperty("Bones" , DI_NEW DiDynEnumProperty([&] { DiDynEnumPropPtr ret; if(!mBoneName.empty()) ret = make_shared mBoneName); else ret = make_shared if(ret) ret->eventType = "AttachRefModel"; return ret; }, [&](DiDynEnumPropPtr& v){ mBoneName = v->value; ChangeAttachBone(); })); g->CreateUI(); mPropGroups.push_back(g); } }
c++
20
0.510999
143
43.469945
183
starcoderdata
#include "src/pch.h" #include "Platform/OpenGL/OpenGLContext.h" namespace Aulys { }; // namespace Aulys
c++
4
0.741007
42
14.444444
9
starcoderdata
<?php declare(strict_types=1); namespace Netgen\Layouts\Tests\Parameters\Stubs; use Netgen\Layouts\Parameters\Form\Mapper as BaseMapper; use Netgen\Layouts\Parameters\ParameterDefinition; use Symfony\Component\Form\Extension\Core\Type\FormType; final class FormMapper extends BaseMapper { private bool $compound; public function __construct(bool $compound = false) { $this->compound = $compound; } public function getFormType(): string { return FormType::class; } public function mapOptions(ParameterDefinition $parameterDefinition): array { return [ 'compound' => $this->compound, ]; } }
php
10
0.682927
79
20.78125
32
starcoderdata
static DWORD MCIQTZ_mciWhere(UINT wDevID, DWORD dwFlags, LPMCI_DGV_RECT_PARMS lpParms) { WINE_MCIQTZ* wma; IVideoWindow* pVideoWindow; HRESULT hr; HWND hWnd; RECT rc; TRACE("(%04x, %08X, %p)\n", wDevID, dwFlags, lpParms); if (!lpParms) return MCIERR_NULL_PARAMETER_BLOCK; wma = MCIQTZ_mciGetOpenDev(wDevID); if (!wma) return MCIERR_INVALID_DEVICE_ID; /* Find if there is a video stream and get the display window */ hr = IGraphBuilder_QueryInterface(wma->pgraph, &IID_IVideoWindow, (LPVOID*)&pVideoWindow); if (FAILED(hr)) { ERR("Cannot get IVideoWindow interface (hr = %x)\n", hr); return MCIERR_INTERNAL; } hr = IVideoWindow_get_Owner(pVideoWindow, (OAHWND*)&hWnd); IVideoWindow_Release(pVideoWindow); if (FAILED(hr)) { TRACE("No video stream, returning no window error\n"); return MCIERR_NO_WINDOW; } if (dwFlags & MCI_DGV_WHERE_SOURCE) { if (dwFlags & MCI_DGV_WHERE_MAX) FIXME("MCI_DGV_WHERE_SOURCE_MAX not supported yet\n"); else FIXME("MCI_DGV_WHERE_SOURCE not supported yet\n"); return MCIERR_UNRECOGNIZED_COMMAND; } if (dwFlags & MCI_DGV_WHERE_DESTINATION) { if (dwFlags & MCI_DGV_WHERE_MAX) { GetClientRect(hWnd, &rc); TRACE("MCI_DGV_WHERE_DESTINATION_MAX %s\n", wine_dbgstr_rect(&rc)); } else { FIXME("MCI_DGV_WHERE_DESTINATION not supported yet\n"); return MCIERR_UNRECOGNIZED_COMMAND; } } if (dwFlags & MCI_DGV_WHERE_FRAME) { if (dwFlags & MCI_DGV_WHERE_MAX) FIXME("MCI_DGV_WHERE_FRAME_MAX not supported yet\n"); else FIXME("MCI_DGV_WHERE_FRAME not supported yet\n"); return MCIERR_UNRECOGNIZED_COMMAND; } if (dwFlags & MCI_DGV_WHERE_VIDEO) { if (dwFlags & MCI_DGV_WHERE_MAX) FIXME("MCI_DGV_WHERE_VIDEO_MAX not supported yet\n"); else FIXME("MCI_DGV_WHERE_VIDEO not supported yet\n"); return MCIERR_UNRECOGNIZED_COMMAND; } if (dwFlags & MCI_DGV_WHERE_WINDOW) { if (dwFlags & MCI_DGV_WHERE_MAX) { GetWindowRect(GetDesktopWindow(), &rc); TRACE("MCI_DGV_WHERE_WINDOW_MAX %s\n", wine_dbgstr_rect(&rc)); } else { GetWindowRect(hWnd, &rc); TRACE("MCI_DGV_WHERE_WINDOW %s\n", wine_dbgstr_rect(&rc)); } } /* In MCI, RECT structure is used differently: rc.right = width & rc.bottom = height * So convert the normal RECT into a MCI RECT before returning */ lpParms->rc.left = rc.left; lpParms->rc.top = rc.right; lpParms->rc.right = rc.right - rc.left; lpParms->rc.bottom = rc.bottom - rc.top; return 0; }
c
14
0.60043
94
33.8625
80
inline
#pragma once #include "CoreMinimal.h" /** * Struct that contains all the information relative to a peer */ struct PeerInfo{ public: PeerInfo(); //All the possible addresses of the peer TArray addresses; //Address test and working to perform comunnications FString chosenAddress = "\0"; //Array containing all the ports for the addresses (index of array of addresses matchs the index of the ports) TArray ports; //Port number corresponding to the choosen address int choosenPort; //Id of the peer int id; //States if this peer has confirmed that he is ready to play bool ready = false; };
c
6
0.751506
111
25.56
25
starcoderdata
/* MIT License Copyright (c) 2018 Virtalis Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /// @file #ifndef VRAPI_H #error api.h must be included before this file #endif /// @defgroup api_ffi Foreign Function Interface /// Functions for interacting with the scripting engine inside VRTree /// @{ /// Deletes the memory allocated for this FFI variable and closes the handle VR_API (void, VRFFIFree, (HFFIVar var)); /// Identifies the type of variable. /// @param var FFI variant handle /// @return the type of the variable (direct enum conversion) /// @note due to the return value being based on an enum, the representation may change between API versions. /// Thus, it is recommended to only use this compare types against other variants. VR_API (int, VRFFIGetType, (HFFIVar var)); /// Calls a named function in the scripting environment. /// @param func The name of the method to call /// @param args Array of HFFIVar handles representing the function parameters (pushed in array order). /// The array may contain null entries, in which case a nil variant will be substituted for the call. /// @param nArgs number of arguments in the args array /// @return a new variant handle containing the return value from the function. This will need to be ::VRFFIFree'd after use. /// @note this function, being C, is limited to returning only one value, so calling a FFI function that returns multiple values /// will only return the first value returned by the FFI function. The rest of the return values are currently discarded. VR_API (HFFIVar, VRFFIInvoke, (const char* func, HFFIVar* args, int nArgs)); /// Registers a function as a global Lua function in the main script environment. /// This function becomes a first-class Lua function callable by any Lua code in events or other plugins. /// @param funcName The name of the function as it should appear in the Lua state /// @param func The function to call when invoked from the Lua state /// @param minArgc minimuim number of arguments expected /// @param userData Userdata which is passed back to func when it is invoked. /// @return 0 if successful, non-zero if a function with this name already exists. /// @note currently you can only register functions in the global scope, and only if they don't already exist. VR_API (int, VRFFIRegister, (const char* funcName, FFIFunc func, int minArgc, void* userData)); /// Unregisters a previously registered FFIFunc /// @return 0 if successful VR_API (int, VRFFIUnregister, (const char* funcName, FFIFunc func)); /// Creates a boolean FFI variable and returns it. /// @param value the value to wrap in the variant. any value other than zero results in a true boolean value. /// @return a new FFI variant handle representing the value /// @see VRFFIFree(HFFIVar) VR_API (HFFIVar, VRFFIMakeBool, (char value)); /// Reads the boolean value contained in the FFI variable and returns it /// @param var FFI variant handle, must be of type Bool /// @return 0 if false, 1 if true VR_API (char, VRFFIGetBool, (HFFIVar var)); /// Creates a number FFI variable and returns it. /// @param value the value to wrap in the variant. /// @return a new FFI variant handle representing the value /// @see VRFFIFree(HFFIVar) VR_API (HFFIVar, VRFFIMakeInt, (int value)); /// Reads the integer value contained in the FFI variable and returns it /// @param var FFI variant handle, must be of type Int /// @return integer value VR_API (int, VRFFIGetInt, (HFFIVar var)); /// Creates a number FFI variable and returns it. /// @param value the value to wrap in the variant. /// @return a new FFI variant handle representing the value /// @see VRFFIFree(HFFIVar) VR_API (HFFIVar, VRFFIMakeDouble, (double value)); /// Reads the double value contained in the FFI variable and returns it /// @param var FFI variant handle, must be of type Double /// @return double value VR_API (double, VRFFIGetDouble, (HFFIVar var)); /// Creates a string FFI variable and returns it. /// @param value the value to wrap in the variant. /// @return a new FFI variant handle representing the value /// @see VRFFIFree(HFFIVar) VR_API (HFFIVar, VRFFIMakeString, (const char* value)); /// Reads the string value contained in the FFI variable and returns it /// @param var FFI variant handle, must be of type String /// @return null terminated string, may be UTF-8 encoded. /// @warning the return value is only valid for the lifetime of the FFI variant. /// Using this string pointer after calling ::VRFFIFree on this var, without first copying it, will result in undefined behaviour. VR_API (const char*, VRFFIGetString, (HFFIVar var)); /// Creates a vec2 (2 doubles in an array) /// @param values to wrap in the variant. expects an array of 2 doubles. /// @return a new FFI variant handle representing the value /// @see VRFFIFree(HFFIVar) VR_API (HFFIVar, VRFFIMakeVec2, (const double* values)); /// Reads the vec2 contained in the FFI variable and returns it /// @param var FFI variant handle, must be of type Vec2 /// @return pointer to array of 2 doubles containing the values. /// @warning the return value is only valid until the next call to ::VRFFIGetVec2 with ANY HFFIVar. VR_API (const double*, VRFFIGetVec2, (HFFIVar var)); /// Creates a vec3 (3 doubles in an array) /// @param values to wrap in the variant. expects an array of 3 doubles. /// @return a new FFI variant handle representing the value /// @see VRFFIFree(HFFIVar) VR_API (HFFIVar, VRFFIMakeVec3, (const double* values)); /// Reads the vec3 contained in the FFI variable and returns it /// @param var FFI variant handle, must be of type Vec3 /// @return pointer to array of 3 doubles containing the values. /// @warning the return value is only valid until the next call to ::VRFFIGetVec3 with ANY HFFIVar. VR_API (const double*, VRFFIGetVec3, (HFFIVar var)); /// Creates a vec4 (4 doubles in an array) /// @param values to wrap in the variant. expects an array of 4 doubles. /// @return a new FFI variant handle representing the value /// @see VRFFIFree(HFFIVar) VR_API (HFFIVar, VRFFIMakeVec4, (const double* values)); /// Reads the vec4 contained in the FFI variable and returns it /// @param var FFI variant handle, must be of type Vec4 /// @return pointer to array of 4 doubles containing the values. /// @warning the return value is only valid until the next call to ::VRFFIGetVec4 with ANY HFFIVar. VR_API (const double*, VRFFIGetVec4, (HFFIVar var)); /// Creates a mat3 (9 doubles in an array) /// @param values to wrap in the variant. expects an array of 9 doubles. /// @return a new FFI variant handle representing the value /// @see VRFFIFree(HFFIVar) VR_API (HFFIVar, VRFFIMakeMat3, (const double* values)); /// Reads the mat3 contained in the FFI variable and returns it /// @param var FFI variant handle, must be of type Mat3 /// @return pointer to array of 9 doubles containing the values. /// @warning the return value is only valid until the next call to ::VRFFIGetMat3 with ANY HFFIVar. VR_API (const double*, VRFFIGetMat3, (HFFIVar var)); /// Creates a mat4 (16 doubles in an array) /// @param values to wrap in the variant. expects an array of 16 doubles. /// @return a new FFI variant handle representing the value /// @see VRFFIFree(HFFIVar) VR_API (HFFIVar, VRFFIMakeMat4, (const double* values)); /// Reads the mat4 contained in the FFI variable and returns it /// @param var FFI variant handle, must be of type Mat4 /// @return pointer to array of 16 doubles containing the values. /// @warning the return value is only valid until the next call to ::VRFFIGetMat4 with ANY HFFIVar. VR_API (const double*, VRFFIGetMat4, (HFFIVar var)); /// Creates a sphere (4 doubles in an array) /// @param values to wrap in the variant. expects an array of 4 doubles (centre xyz, radius) /// @return a new FFI variant handle representing the value /// @see VRFFIFree(HFFIVar) VR_API (HFFIVar, VRFFIMakeSphere, (const double* values)); /// Reads the sphere contained in the FFI variable and returns it /// @param var FFI variant handle, must be of type Sphere /// @return pointer to array of 4 doubles containing the values (centre xyz, radius) /// @warning the return value is only valid until the next call to ::VRFFIGetSphere with ANY HFFIVar. VR_API (const double*, VRFFIGetSphere, (HFFIVar var)); /// Creates a quaternion (4 doubles in an array) /// @param values to wrap in the variant. expects an array of 4 doubles (vector xyz, angle) /// @return a new FFI variant handle representing the value /// @see VRFFIFree(HFFIVar) VR_API (HFFIVar, VRFFIMakeQuat, (const double* values)); /// Reads the quaternion contained in the FFI variable and returns it /// @param var FFI variant handle, must be of type Quat /// @return pointer to array of 4 doubles containing the values (vector xyz, angle) /// @warning the return value is only valid until the next call to ::VRFFIGetQuat with ANY HFFIVar. VR_API (const double*, VRFFIGetQuat, (HFFIVar var)); /// Creates a plane (4 doubles in an array) /// @param values to wrap in the variant. expects an array of 4 doubles (normal xyz, distance) /// @return a new FFI variant handle representing the value /// @see VRFFIFree(HFFIVar) VR_API (HFFIVar, VRFFIMakePlane, (const double* values)); /// Reads the plane contained in the FFI variable and returns it /// @param var FFI variant handle, must be of type Plane /// @return pointer to array of 4 doubles containing the values (normal xyz, distance) /// @warning the return value is only valid until the next call to ::VRFFIGetPlane with ANY HFFIVar. VR_API (const double*, VRFFIGetPlane, (HFFIVar var)); /// Creates a ray (6 doubles in an array) /// @param values to wrap in the variant. expects an array of 6 doubles (origin xyz, direction xyz) /// @return a new FFI variant handle representing the value /// @see VRFFIFree(HFFIVar) VR_API (HFFIVar, VRFFIMakeRay, (const double* values)); /// Reads the ray contained in the FFI variable and returns it /// @param var FFI variant handle, must be of type Ray /// @return pointer to array of 6 doubles containing the values (origin xyz, direction xyz) /// @warning the return value is only valid until the next call to ::VRFFIGetRay with ANY HFFIVar. VR_API (const double*, VRFFIGetRay, (HFFIVar var)); /// Creates an AABB (6 doubles in an array) /// @param values to wrap in the variant. expects an array of 6 doubles (min xyz, max xyz) /// @return a new FFI variant handle representing the value /// @see VRFFIFree(HFFIVar) VR_API (HFFIVar, VRFFIMakeAABB, (const double* values)); /// Reads the AABB contained in the FFI variable and returns it /// @param var FFI variant handle, must be of type AABB /// @return pointer to array of 6 doubles containing the values (min xyz, max xyz) /// @warning the return value is only valid until the next call to ::VRFFIGetAABB with ANY HFFIVar. VR_API (const double*, VRFFIGetAABB, (HFFIVar var)); /// Wraps a node handle in an FFI variable /// @param handle valid node handle /// @return a new FFI variant handle representing the node /// @see VRFFIFree(HFFIVar) /// @note The node handle need not remain open in order for the returned var to remain valid. VR_API (HFFIVar, VRFFIMakeNode, (HNode handle)); /// Reads the node contained in the FFI variable and returns a new handle to it /// @param var FFI variant handle, must be of type Node /// @return new node handle to the node contained in the var /// @see VRCloseNodeHandle /// @note the FFI var need not remain valid in order for the returned node handle to remain open. VR_API (HNode, VRFFIGetNode, (HFFIVar var)); /// Registers a C function with a name which can then be used to call the function in direct response /// to an Event (e.g. Create, Activate, Timestep, etc) /// @param name The name with which to register the function. /// @param func The function to register /// @param userData arbitrary data to pass to the callback /// @see VRUnregisterEventFunction(const char*) VR_API (void, VRRegisterEventFunction, (const char* name, ScriptEventFunc func, void* userData)); /// Unregisters a previously registered event function /// @param name the name of the function to unregister (as it was registered). VR_API (void, VRUnregisterEventFunction, (const char* name)); /// Reads the value from an event register during a call to a registered event function. /// These are the equivalent to the values provided to an event script such as __Self and __Other. /// @param registerName the register to get the value from /// @return a new FFI variant handle representing the value VR_API (HFFIVar, VRFFIGetEventRegister, (const char* registerName)); /// @}
c
9
0.745529
130
49.910448
268
starcoderdata
private void enterClass(@Nullable ClassDescriptor classDescriptor, @NotNull String className, boolean nullable) { this.classDescriptor = classDescriptor; if (this.classDescriptor == null) { // TODO: report in to trace this.errorType = ErrorUtils.createErrorType("class not found by name: " + className); } this.nullable = nullable; this.typeArguments = new ArrayList<TypeProjection>(); }
java
11
0.664474
113
44.7
10
inline
public static void main(String[] args) { // Create a new Sixpack client // NOTE: While we've passed in the default url and a random client id, // they are optional, if they aren't specified the defaults will be used Sixpack sixpack = new SixpackBuilder() .setSixpackUrl(Sixpack.DEFAULT_URL) .setClientId(Sixpack.generateRandomClientId()) .build(); sixpack.setLogLevel(LogLevel.NONE); // build a new Experiment Experiment pillColor = sixpack.experiment() .withName("pill-color") .withAlternatives( new Alternative("red"), new Alternative("blue") ).build(); // participate in the new experiment ParticipatingExperiment participatingExperiment = pillColor.participate(); // We successfully participated, now we can use the alternative specified by Sixpack System.out.println("Will you take a " + participatingExperiment.selectedAlternative.name + " pill? [y/n]"); String answer = new Scanner(System.in).nextLine(); if ("y".equalsIgnoreCase(answer)) { // the user selected the "converting" answer! convert them using the ParticipatingExperiment try { participatingExperiment.convert(); // And that's it! you should now be able to view your results from sixpack-web System.out.println("Success!"); System.exit(0); } catch (ConversionError error) { // Failing to covert is likely due to network issues... at this point you can try again // or backoff and retry, whatever you think makes the most sense for your application System.out.println("Failed to convert in " + participatingExperiment.baseExperiment + ". Error: " + error.getMessage()); System.exit(2); } } }
java
15
0.596404
136
45.581395
43
inline
#ifndef HELPER_H #define HELPER_H //#include #include #include class helper { public: helper(); void debugMsg(std::string s) { std::cout<<s<< std::endl; } protected: private: }; #endif // HELPER_H
c
10
0.539792
37
12.136364
22
starcoderdata
package com.reportcenter.framework.web.page; import java.util.Map; /** * 表格请求参数封装 * * @author Sendy */ public class PageUtilEntity { /** 当前记录起始索引 */ private int page; /** 每页显示记录数 */ private int size; /** 排序列 */ private String orderByColumn; /** 排序的方向 "desc" 或者 "asc". */ private String isAsc; /** true:需要分页的地方,传入的参数就是Page实体;false:需要分页的地方,传入的参数所代表的实体拥有Page属性 */ private boolean entityOrField; /** 总记录数 */ private int totalResult; /** 搜索值 */ private String searchValue; /** 请求参数 */ protected Map<String, Object> reqMap; public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public String getOrderByColumn() { return orderByColumn; } public void setOrderByColumn(String orderByColumn) { this.orderByColumn = orderByColumn; } public String getIsAsc() { return isAsc; } public void setIsAsc(String isAsc) { this.isAsc = isAsc; } public boolean isEntityOrField() { return entityOrField; } public void setEntityOrField(boolean entityOrField) { this.entityOrField = entityOrField; } public int getTotalResult() { return totalResult; } public void setTotalResult(int totalResult) { this.totalResult = totalResult; } public String getSearchValue() { return searchValue; } public void setSearchValue(String searchValue) { this.searchValue = searchValue; } public Map<String, Object> getReqMap() { return reqMap; } public void setReqMap(Map<String, Object> reqMap) { this.reqMap = reqMap; } }
java
8
0.599202
90
17.236364
110
starcoderdata
pub fn enabled(&self, metadata: &Metadata<'_>) -> bool { self.collector .map(|collector| collector.enabled(metadata)) // If this context is `None`, we are registering a callsite, so // return `true` so that the subscriber does not incorrectly assume that // the inner collector has disabled this metadata. // TODO(eliza): would it be more correct for this to return an `Option`? .unwrap_or(true) }
rust
10
0.607069
84
52.555556
9
inline
package msifeed.makriva; import msifeed.makriva.compat.MakrivaCompat; import msifeed.makriva.model.PlayerPose; import msifeed.makriva.model.SharedShape; import net.minecraft.entity.player.EntityPlayer; public class MakrivaCommons { public static PlayerPose findPose(EntityPlayer player) { if (player.isElytraFlying()) return PlayerPose.elytraFly; else if (player.isPlayerSleeping()) return PlayerPose.sleep; else if (player.isRiding()) return PlayerPose.sit; final PlayerPose compat = MakrivaCompat.getPose(player); if (compat != null) return compat; if (player.isSneaking()) return PlayerPose.sneak; return PlayerPose.stand; } public static float calculateEyeHeight(EntityPlayer player, SharedShape shape, PlayerPose pose) { float height = shape.getEyeHeight(pose); if (shape.eyeHeight.isEmpty()) { height += MakrivaCompat.getEyeHeightOffset(player, pose); } return height; } }
java
11
0.667608
101
29.342857
35
starcoderdata
SLONG OS_has_rdtsc(void) { SLONG res; _asm { mov eax, 0 cpuid mov res, eax } if (res == 0) { // // This is an old 486! // return FALSE; } // // Check the processor feature info. // _asm { mov eax, 1 cpuid mov res, edx } if (res & (1 << 4)) { return TRUE; } else { return FALSE; } }
c++
8
0.497006
37
7.375
40
inline
from identity.ecrfs.model import RedcapInstance, RedcapProject from identity.setup.participant_identifier_types import ParticipantIdentifierTypeName from identity.setup.redcap_instances import REDCapInstanceDetail from identity.setup.studies import StudyName from identity.ecrfs.setup.standard import SEX_MAP_0F1M_GENDER, STANDARD_WITHDRAWAL from identity.ecrfs.setup import crfs, RedCapEcrfDefinition crfs.extend([ RedCapEcrfDefinition({ 'crfs': [ { 'instance': REDCapInstanceDetail.UHL_LIVE, 'study': StudyName.SCAD, 'projects': [28], }, ], 'recruitment_date_column_name': 'int_date', 'birth_date_column_name': 'dob', 'withdrawal_date_column_name': 'withdrawal_date', 'withdrawn_from_study_column_name': 'withdrawal_date', 'withdrawn_from_study_values': [' **SEX_MAP_0F1M_GENDER, 'complete_or_expected_column_name': 'study_status', 'complete_or_expected_values': [' '1'], 'identity_map': { ParticipantIdentifierTypeName.SCAD_REG_ID: 'scadreg_id', ParticipantIdentifierTypeName.SCAD_ID: 'scad_id', ParticipantIdentifierTypeName.SCAD_LOCAL_ID: 'scad_local_id', } }), RedCapEcrfDefinition({ 'crfs': [ { 'instance': REDCapInstanceDetail.UHL_LIVE, 'study': StudyName.SCAD, 'projects': [77], }, { 'instance': REDCapInstanceDetail.UHL_HSCN, 'study': StudyName.SCAD, 'projects': [68], }, ], 'recruitment_date_column_name': 'consent_date', 'birth_date_column_name': 'dob', **SEX_MAP_0F1M_GENDER, **STANDARD_WITHDRAWAL, 'complete_or_expected_column_name': 'study_status', 'complete_or_expected_values': ['1'], 'identity_map': { ParticipantIdentifierTypeName.SCAD_ID: 'record', ParticipantIdentifierTypeName.SCAD_REG_ID: 'scadreg_id', } }), RedCapEcrfDefinition({ 'crfs': [ { 'instance': REDCapInstanceDetail.UHL_LIVE, 'study': StudyName.SCAD, 'projects': [31], }, ], 'recruitment_date_column_name': 'scad_reg_date', 'first_name_column_name': 'frst_nm', 'last_name_column_name': 'lst_nm', 'postcode_column_name': 'addrss_pstcd', 'birth_date_column_name': 'dob', **SEX_MAP_0F1M_GENDER, 'identity_map': { ParticipantIdentifierTypeName.SCAD_REG_ID: 'record_id', } }), RedCapEcrfDefinition({ 'crfs': [ { 'instance': REDCapInstanceDetail.UOL_INTERNET, 'study': StudyName.SCAD, 'projects': [12], }, ], 'first_name_column_name': 'first_name', 'last_name_column_name': 'last_name', 'postcode_column_name': 'address_postcode', 'birth_date_column_name': 'mayo_dob', **SEX_MAP_0F1M_GENDER, 'identity_map': { ParticipantIdentifierTypeName.SCAD_SURVEY_ID: 'record', } }), RedCapEcrfDefinition({ 'crfs': [ { 'instance': REDCapInstanceDetail.UOL_INTERNET, 'study': StudyName.SCAD, 'projects': [13], }, ], 'first_name_column_name': 'first_name', 'last_name_column_name': 'last_name', 'postcode_column_name': 'address_postcode', 'birth_date_column_name': 'dob', **SEX_MAP_0F1M_GENDER, 'identity_map': { ParticipantIdentifierTypeName.SCAD_REG_ID: 'scad_reg_id', } })])
python
13
0.601143
85
26.559055
127
starcoderdata
frequency.py import pandas as pd import os # user inputted variables folder_path = r"excel_files" frequency_data_column_number = 3 # program variable file_list = os.listdir(folder_path) # cd into directory os.chdir(folder_path) # create empty dataframe master_df = pd.DataFrame() # go through files and append data into master dataframe for file in file_list: master_df = master_df.append(pd.read_excel(file, header=None, skiprows=25), ignore_index=True) # define new dataframe for frequency data frequency_data = master_df.iloc[:, frequency_data_column_number].dropna().to_frame() # set header for frequency data frequency_data.columns = ["data"] # get frequency data from master dataframe frequency = frequency_data.data.str.split(expand=True).stack().value_counts().to_frame() # save to excel frequency.to_excel("Word Frequency.xlsx")
python
13
0.755986
98
26.40625
32
starcoderdata
var async = require('async') , byline = require('byline') process.stdin.setEncoding('utf8') var stream = byline(process.stdin) var tableInfo = {} var currentTable = false stream.on('data',function(line){ if(/^CREATE TABLE /.test(line)){ currentTable = line.replace(/^CREATE TABLE `/,'').replace(/` \($/,'') tableInfo[currentTable] = {fields:[],loaded:false} } if(currentTable){ if(/^ `.*` .*$/.test(line)){ var l = line.replace(/^ `/,'').replace(/` .*$/,'') tableInfo[currentTable].fields.push(l) } } if(currentTable && /^\) ENGINE=/.test(line)){ tableInfo[currentTable].loaded = true console.log('db.createCollection(\'' + currentTable + '\')') currentTable = false } if(/^INSERT INTO /.test(line)){ var table = line.replace(/^INSERT INTO `/,'').replace(/` VALUES.*$/,'') var values = line.replace(/^INSERT INTO .* VALUES \(/,'').replace(/\);$/,'') var m = values.split(',') var cmd = 'db.' + table + '.insert({' async.timesSeries(tableInfo[table].fields.length,function(x,next){ if(0 !== x) cmd = cmd + ',' cmd = cmd + tableInfo[table].fields[x] + ':' + m[x] next() },function(){ cmd = cmd + '})' console.log(cmd) }) } }) stream.on('end',function(line){ //console.log(tableInfo) })
javascript
18
0.570248
80
27.934783
46
starcoderdata
#include <bits/stdc++.h> #define int long long #define For(i,a,b) for (int i = a; i <= (b); ++i) #define For2(i,a,b) for (int i = a; i >= (b); --i) #define test int _t; cin >> _t; while (_t--) #define pii pair<int, int> #define mpii map<int, int> #define all(a) a.begin(), a.end() #define pb push_back #define fi first #define se second #define mp make_pair #define sz(a) (int)a.size() #define PI 3.1415926535897932384626433832795 #define MOD 1000000007 #define INF 2147483647 #define EPS 1e-9 //#define FILEOPEN using namespace std; const int MAXN = (1 << 18) + 5; int a[MAXN], ans[MAXN]; multiset<int, greater<int> > s[MAXN]; multiset<int, greater<int> > two_last(multiset<int, greater<int> > f) { int p = 0; if (sz(f) <= 2) return f; multiset<int, greater<int> > res; for (int i: f) { if (++p == 3) break; res.insert(i); } return res; } signed main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifdef FILEOPEN freopen("input.in", "r", stdin); freopen("input.out", "w", stdout); #endif int n; cin >> n; For(i,0,(1 << n) - 1) cin >> a[i]; // cerr << 1; For(i,0,(1 << n) - 1) { // cerr << a[i] << endl; s[i].insert(a[i]); } For(bit,0,n - 1) { For(x,0,(1 << n) - 1) { if (!(x & (1 << (bit)))) { int f = (x | (1 << bit)); for (auto i: s[x]) s[f].insert(i); s[f] = two_last(s[f]); } } } ans[0] = -INF; For(k,1,(1 << n) - 1) { int sum = 0; for (int i: s[k]) sum += i; ans[k] = max(ans[k - 1], sum); cout << ans[k] << endl; } }
c++
13
0.551974
71
19.554054
74
codenet