repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
forkunited/ARKWater
src/main/java/ark/cluster/ClustererString.java
package ark.cluster; import java.util.List; import ark.data.DataTools; public abstract class ClustererString extends Clusterer<String> { protected DataTools.StringTransform cleanFn; public ClustererString(DataTools.StringTransform cleanFn) { this.cleanFn = cleanFn; } @Override public List<String> getClusters(String obj) { if (this.cleanFn != null) obj = this.cleanFn.transform(obj); return getClustersHelper(obj); } protected abstract List<String> getClustersHelper(String obj); }
pkavumba/arxiv-vanity-restful-api
arxiv_vanity/papers/models.py
<reponame>pkavumba/arxiv-vanity-restful-api import datetime import docker.errors from django.conf import settings from django.db import models from django.contrib.postgres.fields import ArrayField, JSONField from django.core.files.storage import default_storage from django.urls import reverse from django.utils import timezone import os from ..scraper.query import query_single_paper from ..storage import storage_delete_path from ..utils import log_exception from .downloader import download_source_file from .processor import process_render from .renderer import render_paper, create_client, TooManyRendersRunningError class RenderError(Exception): pass class PaperIsNotRenderableError(RenderError): """Paper cannot be rendered.""" class RenderAlreadyStartedError(RenderError): """Render started when render has already been started.""" class RenderWrongStateError(RenderError): """The state of a render is being updated when it has not been started.""" class PaperQuerySet(models.QuerySet): def _with_has_successful_render_annotation(self): renders = Render.objects.filter( paper=models.OuterRef("pk"), state=Render.STATE_SUCCESS ) return self.annotate(has_successful_render=models.Exists(renders)) def has_successful_render(self): qs = self._with_has_successful_render_annotation() return qs.filter(has_successful_render=True) def has_no_successful_render(self): qs = self._with_has_successful_render_annotation() return qs.filter(has_successful_render=False) def _with_has_not_deleted_render_annotation(self): renders = Render.objects.filter(paper=models.OuterRef("pk"), is_deleted=False) return self.annotate(has_not_deleted_render=models.Exists(renders)) def has_not_deleted_render(self): qs = self._with_has_not_deleted_render_annotation() return qs.filter(has_not_deleted_render=True) def downloaded(self): return self.filter(source_file__isnull=False) def not_downloaded(self): return self.filter(source_file__isnull=True) def update_or_create_from_api(self, result): return self.update_or_create(arxiv_id=result["arxiv_id"], defaults=result) def update_or_create_from_arxiv_id(self, arxiv_id): """ Query the arXiv API and create a Paper from it. Raises: `arxiv_vanity.scraper.query.PaperNotFoundError`: If paper does not exist on arxiv. """ return self.update_or_create_from_api(query_single_paper(arxiv_id)) def machine_learning(self): """ Return only machine learning papers. """ return self.filter( categories__overlap=settings.PAPERS_MACHINE_LEARNING_CATEGORIES ) class PaperManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_deleted=False) def deleted(self): return super().get_queryset().filter(is_deleted=True) class Paper(models.Model): # ArXiV fields arxiv_id = models.CharField(max_length=50, unique=True) arxiv_version = models.IntegerField() title = models.TextField() published = models.DateTimeField() updated = models.DateTimeField(db_index=True) summary = models.TextField() authors = JSONField() arxiv_url = models.URLField() pdf_url = models.URLField() primary_category = models.CharField(max_length=100) categories = ArrayField(models.CharField(max_length=100)) comment = models.TextField(null=True, blank=True) doi = models.CharField(null=True, blank=True, max_length=255) journal_ref = models.TextField(null=True, blank=True, max_length=255) # arXiv Vanity fields source_file = models.ForeignKey( "SourceFile", on_delete=models.SET_NULL, null=True, blank=True ) is_deleted = models.BooleanField(default=False) objects = PaperManager.from_queryset(PaperQuerySet)() class Meta: get_latest_by = "updated" def __str__(self): return self.title def get_absolute_url(self): return reverse("paper_detail", args=(self.arxiv_id,)) def get_https_arxiv_url(self): url = self.arxiv_url if url.startswith("http://arxiv.org"): url = "https" + url.lstrip("http") return url def get_https_pdf_url(self): url = self.pdf_url if url.startswith("http://arxiv.org"): url = "https" + url.lstrip("http") return url def is_renderable(self): """ Returns whether it is possible to render this paper. """ return self.source_file and self.source_file.is_renderable() def get_or_download_source_file(self): """ Attempts to get the source file from a bulk data download, otherwise downloads it and creates it. """ self.source_file = SourceFile.objects.get_or_download(self.arxiv_id) self.save() return self.source_file def get_render_to_display_and_render_if_needed(self, force_render=False): """ Returns the render that should display for this paper, and kicks off a new render if need be. """ try: render = self.renders.not_deleted().latest() except Render.DoesNotExist: render = None if not render: return self.render() # Stuck for some reason, give it a boot # This normally happens if there is an exception raised in render() if render.state == Render.STATE_UNSTARTED: # This will put it into running state render = self.render() # There is already a render running, so try and get the most recent one that isn't running if render.state == Render.STATE_RUNNING: try: return self.renders.not_deleted().succeeded().latest() except Render.DoesNotExist: # If this is the only render or the other renders errored, display loading render return render elif render.state == Render.STATE_FAILURE: # Kick off render if this one has expired if render.is_expired() or force_render: try: render = self.render() except TooManyRendersRunningError: pass except: #  Don't block displaying render if kicking off failed log_exception() # Try and display a successful render try: return self.renders.not_deleted().succeeded().latest() # Otherwise, display the failed or running render except Render.DoesNotExist: return render elif render.state == Render.STATE_SUCCESS: # Kick off render in background if it has expired if render.is_expired() or force_render: try: self.render() except TooManyRendersRunningError: pass except: #  Don't block displaying render if kicking off failed log_exception() return render else: raise Exception(f"Unknown render state: {render.state}") def render(self): """ Make a new render of this paper. Will download the source file and save itself if it hasn't already. """ if not self.source_file: self.get_or_download_source_file() if not self.source_file.is_renderable(): raise PaperIsNotRenderableError("This paper is not renderable.") render = Render.objects.create(paper=self) render.run() return render def _get_expired_date(): expired_delta = datetime.timedelta(days=settings.PAPERS_EXPIRED_DAYS) return timezone.now() - expired_delta class RenderQuerySet(models.QuerySet): def running(self): return self.filter(state=Render.STATE_RUNNING) def succeeded(self): return self.filter(state=Render.STATE_SUCCESS) def failed(self): return self.filter(state=Render.STATE_FAILURE) def not_deleted(self): return self.filter(is_deleted=False) def deleted(self): return self.filter(is_deleted=True) def update_state(self): """ Update the state of renders that have a container. """ qs = self.exclude(state=Render.STATE_UNSTARTED).filter( container_is_removed=False ) for render in qs.iterator(chunk_size=100): try: render.update_state() render.delete_older_renders_if_successful() except: log_exception() return self def expired(self): """ Returns renders that ran more than PAPERS_EXPIRED_DAYS ago. """ return self.filter(created_at__lte=_get_expired_date()) def not_expired(self): """ Returns renders than ran less than PAPERS_EXPIRED_DAYS ago. """ return self.filter(created_at__gt=_get_expired_date()) def mark_as_deleted(self): """ Mark renders as deleted. Useful for forcing re-rendering. """ for render in self.iterator(): render.mark_as_deleted() return self class Render(models.Model): STATE_UNSTARTED = "unstarted" STATE_RUNNING = "running" STATE_SUCCESS = "success" STATE_FAILURE = "failure" paper = models.ForeignKey(Paper, on_delete=models.CASCADE, related_name="renders") created_at = models.DateTimeField(auto_now_add=True) state = models.CharField( max_length=20, default=STATE_UNSTARTED, choices=( (STATE_UNSTARTED, "Unstarted"), (STATE_RUNNING, "Running"), (STATE_SUCCESS, "Success"), (STATE_FAILURE, "Failure"), ), ) is_deleted = models.BooleanField(default=False) container_id = models.CharField(max_length=64, null=True, blank=True) container_inspect = JSONField(null=True, blank=True) container_logs = models.TextField(null=True, blank=True) container_is_removed = models.BooleanField(default=False) objects = RenderQuerySet.as_manager() class Meta: get_latest_by = "created_at" def __str__(self): return self.paper.title def save(self, *args, **kwargs): super(Render, self).save(*args, **kwargs) def get_output_path(self): """ Path to the directory that this render is in. """ return os.path.join("render-output", str(self.id)) def get_html_path(self): """ Path to the HTML file of this render. """ return os.path.join(self.get_output_path(), "index.html") def get_output_url(self): """ Returns the URL to the output path. """ return settings.MEDIA_URL + self.get_output_path() def short_container_id(self): if self.container_id: return self.container_id[:12] def get_webhook_url(self): """ Get the webhook to call when the Engrafo job ends to update render state. """ path = reverse("render_update_state", args=(self.id,)) return settings.ENGRAFO_WEBHOOK_URL_PREFIX + path def run(self): """ Start running this render. """ if self.state != Render.STATE_UNSTARTED: raise RenderAlreadyStartedError( f"Render {self.id} has already been started" ) self.container_id = render_paper( self.paper.source_file.file.name, self.get_output_path(), webhook_url=self.get_webhook_url(), ).id self.state = Render.STATE_RUNNING self.save() def update_state(self, exit_code=None): """ Update state of this render from the container. This is used for two purposes: 1. Called by the webhook to update the state. In this case, exit_code is passed through instead of using the containers exit code because the container is still running (it's sending the webhook!). 2. Called by the update_render_state cron job. In this case, it'll sync all of the details about the containers that exist, and remove any containers that have stopped. This sweeps up containers that have reported their state in (1). """ if self.state == Render.STATE_UNSTARTED: # The create container timeed out, but container ran anyway # Clean up after it... self.mark_as_deleted() return client = create_client() try: container = client.containers.get(self.container_id) self.container_inspect = container.attrs self.container_logs = str(container.logs(), "utf-8").replace("\x00", "") except docker.errors.NotFound: # Container has been removed for some reason, so mark it as # removed so we don't try to update its state again self.container_is_removed = True # Give it a failed state if the render was still running if self.state == Render.STATE_RUNNING: self.state = Render.STATE_FAILURE self.save() return if exit_code is None and container.status == "exited": exit_code = container.attrs["State"]["ExitCode"] if exit_code is not None: # Safer to convert int to str than other way round if str(exit_code) == "0": self.state = Render.STATE_SUCCESS else: self.state = Render.STATE_FAILURE # Deleting containers on Hyper.sh often fails, so save here so we at # least save the state. If remove fails, this will get retried by # the update_render_state cron job. self.save() if container.status == "exited": try: # Force, or Hyper.sh often throws a 500 container.remove(force=True) except docker.errors.NotFound: # Somebody got in there before us. Oh well. pass self.container_is_removed = True self.save() def get_processed_render(self): """ Do final processing on this render and returns it as a dictionary of {"body", "script", "styles"}. """ context = {"render": self, "paper": self.paper} with default_storage.open(self.get_html_path()) as fh: return process_render(fh, self.get_output_url(), context=context) def is_expired(self): """ Returns True if this render was run more than PAPERS_EXPIRED_DAYS ago. """ return self.created_at <= _get_expired_date() def mark_as_deleted(self): """ Delete render's output and mark is as deleted. """ try: self.delete_output() except FileNotFoundError: log_exception() self.is_deleted = True self.save() def delete_output(self): """ Delete output path. """ storage_delete_path(default_storage, self.get_output_path()) def delete_older_renders_if_successful(self): """ Delete any older undeleted renders if this render was successful. """ if not self.state == Render.STATE_SUCCESS: return for render in self.paper.renders.not_deleted().filter(pk__lt=self.pk): render.mark_as_deleted() class SourceFileBulkTarball(models.Model): """ A tarball of sources that is listed in arXiv's bulk sources manifest. We keep track of these so we know which tarballs we have already downloaded. They're quite big so we don't want to get them every time. """ filename = models.CharField(max_length=255, unique=True) content_md5sum = models.TextField() first_item = models.TextField() last_item = models.TextField() md5sum = models.TextField() num_items = models.IntegerField() seq_num = models.IntegerField() size = models.IntegerField() timestamp = models.TextField() yymm = models.TextField() def __str__(self): return self.filename def has_correct_number_of_files(self): """ Number of items specified in the manifest matches how many we have in the database. If this is false, it suggests there was some error in downloading source files. """ return self.num_items == self.sourcefile_set.count() class SourceFileQuerySet(models.QuerySet): def get_or_download(self, arxiv_id): """ Returns a source file for an arxiv ID if it exists (probably created from a bulk source download), otherwise downloads and creates it. """ try: return self.get(arxiv_id=arxiv_id) except SourceFile.DoesNotExist: return self.download_and_create(arxiv_id) def download_and_create(self, arxiv_id): """ Download the LaTeX source of this paper, save to storage, and create SourceFile. """ file = download_source_file(arxiv_id) return self.create(arxiv_id=arxiv_id, file=file) def filename_exists(self, fn): return self.filter(file=f"source-files/{fn}").exists() class SourceFile(models.Model): """ Represents a paper source file from arXiv. NOTE: This is a new system, not yet used by the `Paper` model. Initially, we are downloading arXiv's bulk papers into this model, then we can switch `Paper` to use this model. """ arxiv_id = models.CharField(max_length=50, unique=True) file = models.FileField(upload_to="source-files/", unique=True) bulk_tarball = models.ForeignKey( SourceFileBulkTarball, on_delete=models.SET_NULL, null=True, blank=True, help_text="If this source file is from arXiv's bulk download service, this is the tarball it was in. If null, this source file was downloaded individually.", ) objects = SourceFileQuerySet.as_manager() def __str__(self): return str(self.file) def is_pdf(self): return self.file.name.endswith(".pdf") def is_renderable(self): """ Returns whether it is possible to render this file. """ name = self.file.name return ( name is not None and name.endswith(".gz") and not name.endswith(".ps.gz") and not name.endswith(".dvi.gz") )
potherca-contrib/origin-community-cartridges
openshift-origin-cartridge-jbossrhq-4/template/deployments/rhq.ear/rhq-core-domain-ejb3.jar/org/rhq/core/domain/sync/entity/SystemSettings.java
/* * RHQ Management Platform * Copyright (C) 2005-2011 Red Hat, Inc. * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.rhq.core.domain.sync.entity; import java.io.Serializable; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlValue; /** * A domain class representing the system settings of an RHQ installation. * * @author <NAME> */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class SystemSettings extends AbstractExportedEntity { private static final long serialVersionUID = 2L; @XmlAccessorType(XmlAccessType.FIELD) public static class Entry implements Serializable { private static final long serialVersionUID = 1L; @XmlAttribute private String key; @XmlValue private String value; public Entry() { } public Entry(String key, String value) { this.key = key; this.value = value; } /** * @return the key */ public String getKey() { return key; } /** * @param key the key to set */ public void setKey(String key) { this.key = key; } /** * @return the value */ public String getValue() { return value; } /** * @param value the value to set */ public void setValue(String value) { this.value = value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((key == null) ? 0 : key.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Entry other = (Entry) obj; return key.equals(other.getKey()); } @Override public String toString() { return key + " = '" + value + "'"; } } @XmlElement(name = "entry") private Set<Entry> entries; public SystemSettings() { setReferencedEntityId(0); entries = new HashSet<Entry>(); } public SystemSettings(Map<String, String> settings) { this(); initFrom(settings); } public SystemSettings(Properties settings) { this(); HashMap<String, String> map = new HashMap<String, String>(); for (Map.Entry<Object, Object> entry : settings.entrySet()) { String key = entry.getKey().toString(); String value = entry.getValue().toString(); map.put(key, value); } initFrom(map); } public Map<String, String> toMap() { HashMap<String, String> settings = new HashMap<String, String>(); for(Entry e : entries) { settings.put(e.getKey(), e.getValue()); } return settings; } public Properties toProperties() { Properties ret = new Properties(); ret.putAll(toMap()); return ret; } public void initFrom(Map<String, String> settings) { entries.clear(); for(Map.Entry<String, String> e : settings.entrySet()) { entries.add(new Entry(e.getKey(), e.getValue())); } } @Override public String toString() { return "SystemSettings" + entries; } }
comprakt/comprakt-fuzz-tests
output/b88694246bd04e2fb37a7a48494bdc2d.java
<gh_stars>0 class Ufl_Z { public boolean[][][] hWkdGpZX3; public void[] EzM9cQ55J () throws w { return -null.gBPE(); return -false[ true.hFm]; int[][] uXk8U1 = new K().ic(); void RZJ0yF9TTBGm = false.HtdMvlliMaMV() = 970942[ new int[ -wvGU[ !!Jaujfzdq6LvQm().RUTkE()]].fo8WuvX()]; { if ( -!-this[ new YnMaFucqR1oEP().P1WtQUx8F_Sc()]) { void Ietf_FJm7GqnZ; } ; int[][] U; { { --true[ !!!0[ !true[ -this[ --!!!!--nx().l]]]]; } } ; int[] ZKJBIuY7q; gHT X7xgTFrRZd3r; if ( new boolean[ false._Kpi].bfsiO1jZ()) { BigEwtz2 iMd7Ec; } boolean[][] slIzP; } KAcPQz N9eiTyRBUPw = -!true.Cxanx(); return true.bQ(); } public static void IjvbPmbStDbFV (String[] KlT) { void[] Xr2D; int yumv8REf1 = -new boolean[ true.Ox][ !!-!-!!true.X_z9Be()]; } public boolean srx5dpzqlPjpCa (void s7XxjWtfwsoPiu, c3xHv HowuP5RC, int NUn_x, SYHlM8t5BF[] pj_at5E4CxEt4V, kZyxMeD[][][] GlyUYVjrcS0, int[][][][] R4q1MbBNv4lgp4, void[][] Sro) throws nnGcbTvZlbExO { { void ett7NorCDlG8Sn; int[][] B3CC; SycDyj Ss2; void ltdg_XkRLlh; 97.JgFQfJ2dGu; ; boolean[][] _; t8[][] Jj; ReRy4e1pzQ[] lI427NTCp; j4AveoEA.BF4q1hVF(); boolean[] jWTXx; ; mUdAK2Am2XX maV1F; ; { { void[] OZsTzeR; } } { int dfM_F; } } nt4T16 B = 305847306[ this.ZQIDVgvcAySdZ] = this[ true.T7SOh_QG6G9e()]; void kImIOj05V7; int l5tO3oIuKr; true.iuPhTeqtCftq_f; boolean[] PYbrlyPUART = S7_FESR.SKwiTTnffeOct = true.WASPBn8s9IY; int GUQVgb = Z7fXdtWUXfHu2[ -( !-F().Nu6ZZ())[ true.Y41wG4oM7w0mmc]] = false.CxNF1FBfSMeJef; void uSAFrV6 = this.bXEC(); ( ( !58.FL).gk0uJmafpy()).mDDu5tLXt; int[][][][] bhQ4wbiudwinDH = !true[ !214453.MsszKtz0wODu]; b4BAYYPy x8vFY6rSMIZ = this.bTdywycHYX() = iJCvG3Jej()[ new t2().G5DhN]; boolean nNO0esUGS = ( !F_.Gzb)[ jTZUgc0().rjq_PPFT]; boolean R4gOhC; { ; uTOD6SGIpsx[] z15YI; ESgx10aXvI42_ c_YjFheGxs; } int Q; void LVhggz; int[][] jI = 549092.WH0kjN0WN(); } public static void H8S (String[] j_VWL4) { return; if ( ----false.Z5()) !!!!false.G4(); ; int aGODJbxV; { boolean BumDU57UJZKovF; ; ; eXBHp oUdGP; } int ZP23bXGjdv; } public boolean Dt0GhX_f; } class cWzbP6IjHICf8 { public int KM0ZldHqz9HgH () { S[][][][][] BivTbsHyBp = false.bUB18wibzLm3gk(); if ( this.ewrPD__eYBp) if ( true[ PFK_5[ !( zm().lfVestTNQ).ngis2FAB2()]]) hfSX0rv().J0uPSetuA; h[][][][] OZ9tKiyCfoW; !!this[ true[ ---!new rRl5js[ RR3.hD][ --new tqmrlyKRjj().rpU70yfxdY()]]]; void[][][] uAC0L = true[ !false._pE97]; boolean[] D8qpgPrUE; return; if ( new UgpSnQy().dNgjyEtj()) while ( -!true.yteXDwzq2) if ( -PGu8kT5A.f7S) ;else { { !this[ null[ null[ new ZRWrgcOVxAz2[ S_.TAYXkJc9hErP6].wsTX()]]]; } } return !-!-new boolean[ !null[ this[ --!--this.cBYAN5OEq_bVE()]]].N_v5UZa(); int pIvs6Ed6J9rCMs = true.xpRBXkkCgXm8e() = -new boolean[ ( new TDPydarwj7CMq()[ -!new nh7biyn_1kUmI7().czr5VXEoOXj()])[ !0567.OrN0Ik()]].Bh(); { ; ; ; Rm0NVXiw1[] i6PUYOroCmR; void mu; while ( -new edkI()._gz4ySBPVk5()) return; ; boolean iIw6j4ND2jlYAV; { int[][][] zLz_I; } Jex2HWE bD3N5; this.yzmxmV1HSNsEy(); while ( -false.bC) { HgQIl4dtHYju Uw51Y27ZX2AV; } ; return; } ; int[] f; if ( -!true[ this.B]) ; boolean xMPH = !681995533.E0xo(); ; } public void[][][][][][] VX3Xv () throws x1yEtQGpqXUg { void XjqIuxTAC404h = h()[ LJpOEsEFo3e9().zfe9IYHF()] = !false.LuHt9; boolean WZ4GTSj0mqqa; return !6.b(); while ( ( !new uBhDVbQQa0bGn().YuxP).C3zVM()) ; while ( ( null[ -null[ true.F0svRN]]).bt) !!MmigC1Ind9b[ null[ ---o1AqlFoA[ -( ( !ThqmEZbwkdf0.Uhi1FZw8trlZz).v8ej7bf8).LYqLsh6Qg()]]]; ; ZRrmyxw7spH[][] EwYE = new boolean[ new boolean[ 3025431.Ty7nXvJ].B_8frEEae].gI8f5SZraeTtk = this.SkHYALcC7; if ( null[ -KQEpxV0WLA4Q().uaweVid_omq()]) while ( new aaGxs1EkPSJjdL[ -false[ --( -!51.rbFVoP()).pKAM6r()]][ false.u2r1BTJSYMK()]) ; return !--true.mr(); while ( true[ !null.YZQ37zDmgqRTu]) if ( -!!67.M46yFOQEQ4) ----!null[ -this.eZVryo8U2duFO]; kinplrXd[] Fo8Gf8ebk4I; int ipDvJsH4 = !--!this.YwXF = -LbbEIG.v5; } public int lSmiipf6idFQi () throws ndO8U58dFG { return; ; void ZKvxt1pDcp_Xe = z.zom4g(); UQpqcqlKdd[][] JSHX9ErEcqeR = true[ ( this.VssuouPy).eGEU6lqVcGbV()]; ; int d9cqElkb2uL; ; void[] seuPJhBCC5 = !new m7mlHaR().v7NYbQgal6nS; int[] q = -!!ogIPT6iF.dmaI1hdQLa() = wAB3RNYwYOs().Fpa(); void aszkWzFXzKO; n2aM3KlOo06OpJ[][] eeLi = --true.UBQEjNuhQ(); void tqK5bkKjQ9HZJs = !new nkDGDH[ -null[ -this[ -!this.yfp()]]][ --this.i2jj58P9m]; return null.hJX(); if ( iQLw4EfC[ -( ---!null.LUbnk())[ -!!36.YBSEKfVCVNnOo()]]) while ( true.WEm9B6DMQG_) ; return; int pmtdz = lBgRc2c()[ -gI3rrbWALS()[ 2306987.duaSJ2P2KHa]] = -false.yIeqo(); } public int[] Qsy0 () throws V { boolean my = !vj29rqnT_R2().lMBLIY = new ycc5YMMg().Fgvv(); while ( true[ -SO2bjsTkCuOq.w5P()]) { while ( R()[ new void[ -null.TzAO].qdboVL_bLN()]) -this.xRcOnHUS6X3(); } ; if ( -!-!( -!-!---false[ null.Z()]).lxevwBU58NQC9e()) ;else { if ( -this.jRZRYj9nu()) -x().LHEQe0cHBkV; } void[] nd = this.Co() = false.ge7tgN(); } public static void CrMrd3aqSZG (String[] k4BFA1MdntXm) { ; return null[ !!!new m().IE]; { int[] YgmfXJ_V; int[] g61Y9Y; while ( 6575[ new int[ true[ !-!new gZF().e_VLVOd0mynmbF]][ !this[ false.RpA()]]]) while ( true.S_g()) return; while ( !-( -!!!-( true.JGXY4z2KGhZJ())[ -!-!-amL[ H9M83cSzhc.VxM]])[ -new d8yupvpp4W5X().kvOjK80PG()]) ; return; return; ; TkjYUaO3 J; !( false.w).yugMA_hRv5o; if ( -Wl7jfZAHbRMUt().ZG_6Y) { a9Zah7r0FA[][] r5XSC; } OQNM9HjR4H[] vVhiAF; void[][][][][][][][][] Izd3iZxbDscPVt; return; ; if ( !new thyA2xlhGNvemS().KMBzreRpP) return; while ( new boolean[ -this[ !-new T()[ new boolean[ true.rJn1VjhDv_9q].mTCEL1sn51r]]].voKmDO()) while ( false.B2Uj44K4S()) { boolean[] Qi90H; } } while ( ( this.lLbDk7vOP()).N()) { int MRXdwr; } !this[ new XYUVwBab()[ this[ -!this.Xu()]]]; boolean[] D7ZYS = !!false[ ( oVJaMIbA[ this.K4x4g])[ !this.GM_ESRo3nE4()]]; while ( -!-this[ !new IxDXgcA_AM[ -!this.M8929BvnNzQy9][ -null[ --sBHyOkwh4E7twW.cBakYesORMyP]]]) if ( ---null.MzxpzEMzb8) while ( !true.LqKEvZPC()) while ( jZyU0MNKAHcHL.JtdOZAuqiNgvW0()) ; { boolean[][] Iap; { while ( null.k911CuJThi()) { int sc_yy7; } } -new void[ this.UcfG6qz2L()].fHJ1MMDccO5(); return; if ( false[ muD10[ !-!-3731.fY4n1G9it5()]]) while ( ( --( null[ POM.r()])[ -true[ -( this.g7bV5szLU387j()).RBYD()]])[ new void[ -YbfvpsPYVTgWw2().W].BPza0lb7De1()]) return; boolean Wgb4esS9KwIHL; void[] zV_bPLXQ0N2J; if ( 1537[ 3[ !false[ -8145497.cpEQ()]]]) !new boolean[ 7.vY3ha1NOLsIIK2][ true.F8]; void[][][][][][] jVVHRRwHcag7n; DGS P1HMAJ; } return false[ -lEbO6x.cod_iMXtpGVQ]; if ( --( null[ !-!-null[ -this.NzJzS]])[ -!!( ( 35385254[ this.JGi91Fo()]).um).q]) { while ( !!47357585.Ccs()) if ( -true[ !!gW.wdyXpmW]) ; }else !!---true[ -this.jh]; boolean[][] uA = --null[ -new void[ ( SrGg.Jq2t8T9424).DFBaczbcfa][ false[ -937189.biEt8u8LRldB()]]] = new idtbTSuoGUM[ !--new int[ null.gfUrNd1Khe()][ -!30058[ true.wdk5RrlQ()]]].iEQRh9sMZnEWj; void[] r = -!new jbjtOy[ !this.CqZ4zgBvEgQRI].zbe8173FgL(); while ( NqcmIQzU()[ -new c[ ( -!new V1UwlLhhTXW4().h8Rkvrg9).gMNM()].knT()]) ; Xt5JVLVBCw[] G = new C5e6()[ false[ !FM9rys8()[ null.nN]]] = !-a.tCPJd2ExertZ5(); { return; { while ( -TvvatIU3Wd.PMn0QW) ; } int[][][] aVpV4fU; -null[ new int[ this.QrB6jzLiICTI()].vIl()]; void F_XICK1eRop5R8; ; boolean y3; if ( -this._) { void p3clE; } } } public int vx () throws sVSCeUZIn { while ( false.WYo5Zvw()) return; return; if ( this.uURz6y()) return; TkqTC4ak yPdr = !e5Zf5Rfq8okQ2Q.C3Xz() = !Vmp59h0GXwz5.S6q_LNq6qxp08o; return; Tomhzk9 bKUnvOF0i; ; return; if ( jO()[ !-!--TYLDdQ.VTOkFBj()]) return;else { MF6[] J; } void a9sbEzqnHn = !( --new irqsIpRBDWSuu().LUUkcGrENBc()).CDxmV; ; } public boolean[] tTPF8l5 () throws Ng73ZEiPP3 { if ( !67055.agRkXN) ;else ; while ( new BjYG_DC5gywNd().fFBVn676deBD) { dQu2zPe8N[][] cw9yddWDrXEn; } int[] EO6xO6LIlmd1 = A().iqaF(); boolean r8; ; while ( !!!new void[ !-( LIbH()[ -new LnYoDQL3G9().b1opwMWHn()]).VGiZk()][ --!!-!!-!true.gYsAAhgO7lNvBz()]) while ( !!!KBH48.ilGZsQK) NwvHnJk_tzAS87().KHLq8Yn(); void[] Up03 = !new Ulf7[ !( ABvN5trPle()[ -tAPtiCJdI4j()[ -new t8RQokLHUS9().zBKgnhrJZ]])[ K.K]]._4f1tqOVXCZw8b(); while ( new boolean[ ---!SZK.BoaIgOIK1U()].crPTYSH()) { loJl1FVcPj Y3TBWtUU; } OggA3jdPICCaMX G54lNv = -new int[ null[ !( true.eAjLvssehL1Rai)[ -----9.AJXFt_SP()]]].BMvc0a; ; while ( -true.lRwdT) while ( -false.m()) !true._lt(); ; int CECp0DWYeW40 = !( ( --this.C()).e())[ RHBlDy4eu.TvhzhAC0Dzogi()] = !--false.N1e; ; while ( false[ !true.StdRWyNa]) !-081881550._DFjqVX0BzBt(); { if ( this.QbB7Pz3CT0_q()) ; ; return; void[] XJuUizBdR17; if ( !-false.Qhrn_Na) return; { if ( 813026.PpPoHq2d) -!-294.Bv8atOy1mMiv(); } -new Pp8s().g7_; return; int[] wePascmMk1_H4P; } !!a8j4R1vtjv93.BgQN4qXaEx(); hoOKoMB k2vZWzEv9L = --!!true.tzevBk; ; } } class XF { } class q { } class sCxXImDNLZeTA { public boolean z_MyMe44GWm; public static void ILwzeC (String[] K8yFq_pd) { int _sf = !-( new int[ !false[ true.qCSX()]][ -rz.sHgPFHz()]).lGhItVLFOGB5y(); return; boolean[][] QqYoV3cd0C = true[ new X[ new MBBztqnY5().dVEbmeL()][ w5uOAkJNrvXE.koWfydd]] = new int[ false.J_xhzIh0F7hj].d; TinojCPax_[][] hRB4s; void[] FE1_ = -!-( true[ !( new Fg4cqPRe1Qlrm2().UZ).mpMIcno()])[ _n9p9Z()[ new int[ null.cCFfe0_].JZODoWf]]; } }
vgmtool/vgm2pre
phoenix/.test/test-layout.cpp
<filename>phoenix/.test/test-layout.cpp<gh_stars>10-100 #include "phoenix.hpp" using namespace nall; using namespace phoenix; struct Application : Window { VerticalLayout layout; Button button1; Button button2; Button button3; Application() { setStatusText("???"); setStatusVisible(); setFrameGeometry({ 64, 64, 640, 400 }); button1.setText("Button 1"); button2.setText("Button 2"); button3.setText("Button 3"); append(layout); layout.setMargin(5); layout.append(button1, ~0, 0, 5); layout.append(button2, ~0, 0, 5); layout.append(button3, ~0, 0, 5); onClose = &OS::quit; button1.onTick = [&] { layout.append(button3, ~0, 0, 5); }; button2.onTick = [&] { layout.remove(button3); }; button3.onTick = [&] { setFullScreen(!fullScreen()); }; setVisible(); } }; /* struct Application : Window { VerticalLayout layout; HorizontalLayout aLayout; HorizontalLayout bLayout; Button button1; Button button2; Button button3; Button button4; Button button5; ListView list; Application() { setGeometry({ 256, 256, 640, 400 }); button1.setText("Button 1"); button2.setText("Button 2"); button3.setText("Button 3"); button4.setText("Button 4"); button5.setText("Button 5"); list.append("Item 1"); list.append("Item 2"); list.append("Item 3"); list.append("Item 4"); list.append("Item 5"); layout.setMargin(5); layout.append(aLayout, ~0, 0, 5); layout.append(bLayout, ~0, 0, 5); aLayout.append(button1, ~0, 25, 5); aLayout.append(button2, ~0, 25, 5); aLayout.append(button3, ~0, 25, 5); bLayout.append(button4, ~0, 25, 5); bLayout.append(button5, ~0, 25, 5); layout.append(list, ~0, ~0); append(layout); onClose = &OS::quit; button1.onTick = [&] { aLayout.append(button3, ~0, 25, 5); }; button2.onTick = [&] { aLayout.remove(button3); }; button3.onTick = [&] {}; button4.onTick = [&] { layout.append(aLayout, ~0, 0, 5); }; button5.onTick = [&] { layout.remove(aLayout); }; setVisible(); } }; */ int main() { auto application = new Application; OS::main(); delete application; return 0; }
uk-gov-mirror/DFE-Digital.get-help-with-tech
spec/models/allocation_data_file_spec.rb
require 'rails_helper' RSpec.describe AllocationDataFile, type: :model do describe '#allocations' do let(:filename) { Rails.root.join('tmp/allocation_test_data.csv') } context 'when a school has an allocation entry' do let(:attrs) do { urn: '103001', school_name: 'Little School', y3_10: '23', y10: '0', } end before do create_allocations_csv_file(filename, [attrs]) end after do remove_file(filename) end it 'retrieves the allocation data' do allocations = described_class.new(filename).allocations expect(allocations.first).to include( urn: '103001', name: 'Little School', y3_10: 23, y10: 0, ) end end end end
gavab/Prog2
gyak/Override.java
<filename>gyak/Override.java class A{ int i,j; A(int i, int j){ this.i=i; this.j=j; } void show(){ System.out.println("i=="+i+" j=="+j); } } class B extends A{ int k; B(int i, int j, int k){ super(i,j); this.k=k; } void show(){ super.show(); System.out.println("k=="+k); } } class Override{ public static void main(String[] args) { B subOb=new B(1,2,3); subOb.show(); } }
santomon/taskonomy
code/tools/train_imagenet.py
<gh_stars>100-1000 ''' Name: extract.py Desc: Extract losses. Usage: python encode_inputs.py /path/to/cfgdir/ --gpu gpu_id ''' from __future__ import absolute_import, division, print_function import argparse import os import numpy as np import pdb import pickle from runstats import Statistics import tensorflow as tf import tensorflow.contrib.slim as slim import threading import time import init_paths from data.load_ops import resize_rescale_image from data.load_ops import class_1000_imagenet from data.load_ops import class_selected_imagenet from data.task_data_loading import load_and_specify_preprocessors_for_representation_extraction import general_utils from general_utils import RuntimeDeterminedEnviromentVars import models.architectures as architectures from models.sample_models import * import utils parser = argparse.ArgumentParser(description='Extract accuracy for a transfer to class 1000 on ImageNet') parser.add_argument( '--cfg_dir', dest='cfg_dir', help='directory containing config.py file, should include a checkpoint directory' ) parser.set_defaults(cfg_dir="/home/ubuntu/task-taxonomy-331b/experiments") parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', type=int) parser.add_argument('--nopause', dest='nopause', action='store_true') parser.set_defaults(nopause=True) parser.add_argument('--selected', dest='is_selected', action='store_true') parser.set_defaults(is_selected=False) parser.add_argument('--transfer', dest='pretrain_transfer', action='store_true') parser.set_defaults(pretrain_transfer=False) parser.add_argument('--transfer-type', dest='pretrain_transfer_type') parser.set_defaults(pretrain_transfer_type='full_taskonomy_beta1/DO_NOT_REPLACE_TARGET_DECODER/16k') parser.add_argument('--task', dest='task') parser.add_argument('--data-split', dest='data_split') parser.set_defaults(data_split="val" ) parser.add_argument('--out-dir', dest='out_dir') parser.set_defaults(out_dir="") parser.add_argument('--out-name', dest='out_name') parser.set_defaults(out_name="") parser.add_argument('--representation-task', dest='representation_task') parser.set_defaults(representation_task="") parser.add_argument('--print-every', dest='print_every') parser.set_defaults(print_every="10") parser.add_argument('--data-use', dest='data_used', type=int) parser.set_defaults(data_used=16000) parser.add_argument('--from-scratch', dest='from_scratch', action='store_true') parser.set_defaults(from_scratch=False) parser.add_argument('--train-mode', dest='train_mode', action='store_true') # parser.set_defaults(print_every="100") # TRAIN_MODE =True def main( _ ): args = parser.parse_args() global TRAIN_MODE TRAIN_MODE = args.train_mode #task_list = ["autoencoder", "colorization","curvature", "denoise", "edge2d", "edge3d", "ego_motion", "fix_pose", "impainting", "jigsaw", "keypoint2d", "keypoint3d", "non_fixated_pose", "point_match", "reshade", "rgb2depth", "rgb2mist", "rgb2sfnorm", "room_layout", "segment25d", "segment2d", "vanishing_point"] #single channel for colorization !!!!!!!!!!!!!!!!!!!!!!!!! COME BACK TO THIS !!!!!!!!!!!!!!!!!!!!!!!!!!! task_list = [ args.task ] # Get available GPUs local_device_protos = utils.get_available_devices() print( 'Found devices:', [ x.name for x in local_device_protos ] ) # set GPU id if args.gpu_id: print( 'using gpu %d' % args.gpu_id ) os.environ[ 'CUDA_VISIBLE_DEVICES' ] = str( args.gpu_id ) else: print( 'no gpu specified' ) for task in task_list: if args.is_selected: to_task = 'class_selected' target_loading_fn = class_selected_imagenet else: to_task = 'class_1000' target_loading_fn = class_1000_imagenet if args.pretrain_transfer: task_dir = os.path.join(args.cfg_dir, args.pretrain_transfer_type, "{}__{}__8__unlocked".format(task, to_task)) else: task_dir = os.path.join(args.cfg_dir, 'final', task) cfg = utils.load_config( task_dir, nopause=args.nopause ) root_dir = cfg['root_dir'] if args.is_selected: split_file = os.path.abspath( os.path.join( root_dir, 'assets/aws_data/train_selected_imagenet_info.pkl') ) else: split_file = os.path.abspath( os.path.join( root_dir, 'assets/aws_data/train_split_imagenet_info.pkl') ) cfg['dataset_dir'] = '/home/ubuntu/imagenet' cfg['train_filenames'] = split_file cfg['val_filenames'] = split_file cfg['test_filenames'] = split_file if 'train_list_of_fileinfos' in cfg: split_file_ = os.path.join( cfg['input_cfg']['log_root'], task, '{task}_val_imagenet_representations.pkl'.format( task=task )) cfg['train_representations_file'] = split_file_ cfg['val_representations_file'] = split_file_ cfg['test_representations_file'] = split_file_ split_file_ = os.path.join(root_dir, 'assets/aws_data/val_imagenet.npy') cfg['train_list_of_fileinfos'] = split_file_ cfg['val_list_of_fileinfos'] = split_file_ cfg['test_list_of_fileinfos'] = split_file_ # cfg['resize_interpolation_order'] = 0 # if cfg['model_path'] is None: # cfg['model_path'] = os.path.join(cfg['dataset_dir'], "model_log", task, "model.permanent-ckpt") cfg['target_from_filenames'] = target_loading_fn # Try latest checkpoint by epoch cfg['model_path'] = tf.train.latest_checkpoint( os.path.join( cfg['log_root'], 'logs', 'slim-train' )) # Try latest checkpoint by time if cfg['model_path'] is None: cfg['model_path'] = tf.train.latest_checkpoint( os.path.join( cfg['log_root'], 'logs', 'slim-train', 'time' )) # Try to get one saved manually if cfg['model_path'] is None: cfg['model_path'] = os.path.join(cfg['log_root'], task, "model.permanent-ckpt") # cfg['model_path'] = os.path.join(cfg['log_root'], 'logs', 'slim-train', 'time', "model.ckpt-1350") cfg['randomize'] = False cfg['num_epochs'] = 20 cfg['batch_size'] = 32 #if TRAIN_MODE else 1 cfg['num_read_threads'] = 30 if 'batch_size' in cfg['encoder_kwargs']: cfg['encoder_kwargs']['batch_size'] = cfg['batch_size'] try: cfg['target_cfg']['batch_size'] = cfg['batch_size'] except: pass try: cfg['target_cfg']['encoder_kwargs']['batch_size'] = cfg['batch_size'] except: pass loss_dir = args.cfg_dir cfg['src_encoder_ckpt'] = tf.train.latest_checkpoint( os.path.join( cfg['input_cfg']['log_root'], task, 'logs', 'slim-train', 'time' )) if cfg['src_encoder_ckpt'] is None: cfg['src_encoder_ckpt'] = os.path.join(cfg['input_cfg']['log_root'], task, "model.permanent-ckpt") cfg['finetune_encoder_imagenet'] = True cfg['data_used'] = args.data_used cfg['input_cfg']['num_input'] = 1 run_extract_losses( args, cfg, loss_dir, task ) def run_extract_losses( args, cfg, save_dir, given_task ): transfer = (cfg['model_type'] == architectures.TransferNet) if transfer: get_data_prefetch_threads_init_fn = utils.get_data_prefetch_threads_init_fn_transfer_imagenet setup_input_fn = utils.setup_input_transfer_imagenet else: setup_input_fn = utils.setup_input get_data_prefetch_threads_init_fn = utils.get_data_prefetch_threads_init_fn # set up logging tf.logging.set_verbosity( tf.logging.ERROR ) stats = Statistics() print_every = int(args.print_every) with tf.Graph().as_default() as g: # create ops and placeholders inputs = setup_input_fn( cfg, is_training=True, use_filename_queue=False ) #RuntimeDeterminedEnviromentVars.load_dynamic_variables( inputs, cfg ) #RuntimeDeterminedEnviromentVars.populate_registered_variables() max_steps = get_max_steps(inputs[ 'max_steps' ], args.data_split) # build model (and losses and train_op) model = utils.setup_model( inputs, cfg, is_training=True ) # set up metrics to evaluate names_to_values, names_to_updates = setup_metrics( inputs, model, cfg ) train_step_fn = model['train_step_fn'] # execute training start_time = time.time() utils.print_start_info( cfg, max_steps, is_training=True ) # start session and restore model training_runners = { 'sess': tf.Session(), 'coord': tf.train.Coordinator() } try: if cfg['model_path'] is None: print('Please specify a checkpoint directory') return print('Attention, model_path is ', cfg['model_path']) restore_ckpt = not args.from_scratch if restore_ckpt: non_encoder_var = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES) adams = [] for v in tuple(non_encoder_var): if 'Adam' in v.name: non_encoder_var.remove(v) adams.append(v) continue for x in model['model'].encoder_vars: if v.name == x.name: non_encoder_var.remove(v) saver_for_transfer = tf.train.Saver(non_encoder_var) saver_for_transfer.restore( training_runners[ 'sess' ], cfg[ 'model_path' ] ) training_runners[ 'sess' ].run(tf.variables_initializer(adams)) print('Loading Source Encoder:...') model['init_fn'](training_runners[ 'sess' ]) print('Starting Training:..') else: init_op = tf.global_variables_initializer() training_runners['sess'].run(init_op) assign_op = model['global_step'].assign(0) training_runners['sess'].run(assign_op) # var = [v for v in tf.global_variables() if 'decoder' in v.name][0] # print(training_runners[ 'sess' ].run(var)) utils.print_start_info( cfg, max_steps, is_training=True ) data_prefetch_init_fn = get_data_prefetch_threads_init_fn( inputs, cfg, is_training=True, use_filename_queue=False ) prefetch_threads = threading.Thread( target=data_prefetch_init_fn, args=( training_runners[ 'sess' ], training_runners[ 'coord' ] )) prefetch_threads.start() # run one example so that we can calculate some statistics about the representations start = time.perf_counter() saver = tf.train.Saver() save_ckpt_name = 'imagenet' if args.from_scratch: save_ckpt_name = 'imagenet_scratch' for step in range( max_steps // 2 - 1 ): total_loss, should_stop = train_step_fn( training_runners['sess'], model['train_op'], model['global_step'], train_step_kwargs=model[ 'train_step_kwargs' ]) # print(data_idx) # print(p.mean(), t) stats.push(total_loss) if step % print_every == 0 and step > 0: print( 'Step {0} of {1}: ({5}: {2:.3f} || stddev: {3:.3f} :: ({4:.2f} secs/step)'.format( step, max_steps - 1, stats.mean(), np.sqrt(stats.variance()), # stats.variance(), (time.perf_counter() - start) / print_every, 'Total_loss' )) start = time.perf_counter() if step % 3000 == 2999: saver.save(training_runners['sess'], os.path.join(cfg['log_root'], given_task, '{}_{}'.format(save_ckpt_name, step))) if training_runners['coord'].should_stop(): break print('Heressss') saver.save(training_runners['sess'], os.path.join(cfg['log_root'], given_task, save_ckpt_name)) print('time to extract %d epochs: %.3f hrs' % (cfg['num_epochs'], end_train_time/(60*60))) finally: utils.request_data_loading_end( training_runners ) utils.end_data_loading_and_sess( training_runners ) def setup_metrics( inputs, model, cfg ): # predictions = model[ 'model' ]. # Choose the metrics to compute: # names_to_values, names_to_updates = slim.metrics.aggregate_metric_map( {} ) return {}, {} def get_max_steps(original_max_steps, data_split): n_images = None if data_split == 'train': n_images = 129380 elif data_split == 'val': n_images = 50000 elif data_split == 'test': n_images = 17853 else: raise NotImplementedError('Unknown data split {}'.format(data_split)) if original_max_steps != n_images: print("Adjusting number of steps from {} -> {}".format( max(original_max_steps, n_images), min(original_max_steps, n_images) )) return min(original_max_steps, n_images) if __name__=='__main__': main( '' )
Alexhuszagh/funxx
pycpp/re/new.h
<gh_stars>1-10 // :copyright: (c) 2017 <NAME>. // :license: MIT, see licenses/mit.md for more details. /** * \addtogroup PyCPP * \brief Specialized memory allocation for RE objects. */ #pragma once #include <pycpp/stl/memory.h> #include <pycpp/stl/utility.h> #include <string.h> PYCPP_BEGIN_NAMESPACE // FUNCTIONS // --------- /** * \brief Global allocator for RE data. * * To change the allocation behavior of this allocator, * change the underlying `resource` so it is copy * constructed into all RE data. * * This can only change the memory allocated internally by the RE2 * wrappers, as RE2 uses the global memory allocator. */ inline byte_allocator& re_allocator() noexcept { static byte_allocator singleton; return singleton; } template <typename T, typename ... Ts> T* re_new(Ts&&... ts) { static byte_allocator& alloc = re_allocator(); using traits_type = allocator_traits<byte_allocator>; byte* p = traits_type::allocate(alloc, sizeof(T)); new(p) T(forward<Ts>(ts)...); return reinterpret_cast<T*>(p); } template <typename T> void re_delete(T* t) noexcept { static byte_allocator& alloc = re_allocator(); using traits_type = allocator_traits<byte_allocator>; if (t != nullptr) { t->~T(); traits_type::deallocate(alloc, reinterpret_cast<byte*>(t), 1); } } PYCPP_END_NAMESPACE
ipetkowww/java-fundamentals
10. Text Processing/src/lab_tasks/Lab05_DigitsLettersAndOther.java
<gh_stars>0 package lab_tasks; import java.util.Scanner; public class Lab05_DigitsLettersAndOther { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); StringBuilder digits = new StringBuilder(); StringBuilder letters = new StringBuilder(); StringBuilder otherCharacters = new StringBuilder(); for (int i = 0; i < input.length(); i++) { char currentChar = input.charAt(i); if (Character.isDigit(currentChar)) { digits.append(currentChar); } else if (Character.isLetter(currentChar)) { letters.append(currentChar); } else { otherCharacters.append(currentChar); } } System.out.println(digits); System.out.println(letters); System.out.println(otherCharacters); } }
outr/lucene4s
implementation/src/main/scala/com/outr/lucene4s/field/value/support/StringValueSupport.scala
package com.outr.lucene4s.field.value.support object StringValueSupport extends StringBackedValueSupport[String] { override def toString(value: String): String = value override def fromString(s: String): String = s }
Mjtlittle/portfolio
src/components/EmailForm/index.js
import React from 'react' import mailtoLink from 'mailto-link' import styles from './EmailForm.module.sass' import { useInputState } from '../../hooks/useInputState' import { useSiteMetadata } from '../../hooks/useSiteMetadata' const EmailForm = () => { const { email } = useSiteMetadata() const [subject, subjectHandleChange, subjectReset] = useInputState('') const [body, bodyHandleChange, bodyReset] = useInputState('') const submitEmail = () => { // open the mailto link const link = mailtoLink({ to: email, subject: subject, body: body, }) window.open(link) // reset the form subjectReset() bodyReset() } return ( <form className={styles.container} onSubmit={submitEmail}> <label>Subject</label> <input type='text' value={subject} onChange={subjectHandleChange} /> <label>Body</label> <textarea value={body} onChange={bodyHandleChange} /> <input type='submit' value='Send' /> </form> ) } export default EmailForm
xxm1995/bootx-platform
bootx-services/service-order/src/main/java/cn/bootx/order/core/billing/entity/OrderBilling.java
<gh_stars>1-10 package cn.bootx.order.core.billing.entity; import cn.bootx.common.core.function.EntityBaseFunction; import cn.bootx.common.mybatisplus.base.MpBaseEntity; import cn.bootx.order.core.billing.convert.BillingConvert; import cn.bootx.order.dto.billing.OrderBillingDto; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.math.BigDecimal; /** * 订单账单 * @author xxm * @date 2020/12/11 */ @EqualsAndHashCode(callSuper = true) @Data @Accessors(chain = true) @TableName("pc_order_billing") public class OrderBilling extends MpBaseEntity implements EntityBaseFunction<OrderBillingDto> { /** 用户id */ private Long userId; /** 渠道id */ private Long channelId; /** 订单id */ private Long orderId; /** 支付类型 */ private Integer payType; /** 金额 */ private BigDecimal amount; /** * 交易数量(积分,代金券,兑换券的场合具体数量 */ private Integer count; /** 业务id */ private String businessId; @Override public OrderBillingDto toDto() { return BillingConvert.CONVERT.convert(this); } }
DataCanvasIO/StreamTau2
streamtau_streaming/src/main/java/com/zetyun/streamtau/streaming/StreamBuilder.java
/* * Copyright 2020 Zetyun * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zetyun.streamtau.streaming; import com.zetyun.streamtau.streaming.model.Dag; import com.zetyun.streamtau.streaming.transformer.TransformContext; import org.apache.flink.client.FlinkPipelineTranslationUtil; import org.apache.flink.client.program.StreamPlanEnvironment; import org.apache.flink.configuration.Configuration; import org.apache.flink.runtime.jobgraph.JobGraph; public final class StreamBuilder { private StreamBuilder() { } public static JobGraph buildJobGraph(Dag dag) { StreamPlanEnvironment env = new StreamPlanEnvironment(new Configuration(), null, 1); TransformContext.transform(env, dag); return FlinkPipelineTranslationUtil.getJobGraph(env.getPipeline(), new Configuration(), 1); } }
perfectrecall/aws-sdk-cpp
aws-cpp-sdk-sagemaker/include/aws/sagemaker/model/SendPipelineExecutionStepSuccessRequest.h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/sagemaker/SageMaker_EXPORTS.h> #include <aws/sagemaker/SageMakerRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/sagemaker/model/OutputParameter.h> #include <utility> #include <aws/core/utils/UUID.h> namespace Aws { namespace SageMaker { namespace Model { /** */ class AWS_SAGEMAKER_API SendPipelineExecutionStepSuccessRequest : public SageMakerRequest { public: SendPipelineExecutionStepSuccessRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "SendPipelineExecutionStepSuccess"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The pipeline generated token from the Amazon SQS queue.</p> */ inline const Aws::String& GetCallbackToken() const{ return m_callbackToken; } /** * <p>The pipeline generated token from the Amazon SQS queue.</p> */ inline bool CallbackTokenHasBeenSet() const { return m_callbackTokenHasBeenSet; } /** * <p>The pipeline generated token from the Amazon SQS queue.</p> */ inline void SetCallbackToken(const Aws::String& value) { m_callbackTokenHasBeenSet = true; m_callbackToken = value; } /** * <p>The pipeline generated token from the Amazon SQS queue.</p> */ inline void SetCallbackToken(Aws::String&& value) { m_callbackTokenHasBeenSet = true; m_callbackToken = std::move(value); } /** * <p>The pipeline generated token from the Amazon SQS queue.</p> */ inline void SetCallbackToken(const char* value) { m_callbackTokenHasBeenSet = true; m_callbackToken.assign(value); } /** * <p>The pipeline generated token from the Amazon SQS queue.</p> */ inline SendPipelineExecutionStepSuccessRequest& WithCallbackToken(const Aws::String& value) { SetCallbackToken(value); return *this;} /** * <p>The pipeline generated token from the Amazon SQS queue.</p> */ inline SendPipelineExecutionStepSuccessRequest& WithCallbackToken(Aws::String&& value) { SetCallbackToken(std::move(value)); return *this;} /** * <p>The pipeline generated token from the Amazon SQS queue.</p> */ inline SendPipelineExecutionStepSuccessRequest& WithCallbackToken(const char* value) { SetCallbackToken(value); return *this;} /** * <p>A list of the output parameters of the callback step.</p> */ inline const Aws::Vector<OutputParameter>& GetOutputParameters() const{ return m_outputParameters; } /** * <p>A list of the output parameters of the callback step.</p> */ inline bool OutputParametersHasBeenSet() const { return m_outputParametersHasBeenSet; } /** * <p>A list of the output parameters of the callback step.</p> */ inline void SetOutputParameters(const Aws::Vector<OutputParameter>& value) { m_outputParametersHasBeenSet = true; m_outputParameters = value; } /** * <p>A list of the output parameters of the callback step.</p> */ inline void SetOutputParameters(Aws::Vector<OutputParameter>&& value) { m_outputParametersHasBeenSet = true; m_outputParameters = std::move(value); } /** * <p>A list of the output parameters of the callback step.</p> */ inline SendPipelineExecutionStepSuccessRequest& WithOutputParameters(const Aws::Vector<OutputParameter>& value) { SetOutputParameters(value); return *this;} /** * <p>A list of the output parameters of the callback step.</p> */ inline SendPipelineExecutionStepSuccessRequest& WithOutputParameters(Aws::Vector<OutputParameter>&& value) { SetOutputParameters(std::move(value)); return *this;} /** * <p>A list of the output parameters of the callback step.</p> */ inline SendPipelineExecutionStepSuccessRequest& AddOutputParameters(const OutputParameter& value) { m_outputParametersHasBeenSet = true; m_outputParameters.push_back(value); return *this; } /** * <p>A list of the output parameters of the callback step.</p> */ inline SendPipelineExecutionStepSuccessRequest& AddOutputParameters(OutputParameter&& value) { m_outputParametersHasBeenSet = true; m_outputParameters.push_back(std::move(value)); return *this; } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the operation. An idempotent operation completes no more than one * time.</p> */ inline const Aws::String& GetClientRequestToken() const{ return m_clientRequestToken; } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the operation. An idempotent operation completes no more than one * time.</p> */ inline bool ClientRequestTokenHasBeenSet() const { return m_clientRequestTokenHasBeenSet; } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the operation. An idempotent operation completes no more than one * time.</p> */ inline void SetClientRequestToken(const Aws::String& value) { m_clientRequestTokenHasBeenSet = true; m_clientRequestToken = value; } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the operation. An idempotent operation completes no more than one * time.</p> */ inline void SetClientRequestToken(Aws::String&& value) { m_clientRequestTokenHasBeenSet = true; m_clientRequestToken = std::move(value); } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the operation. An idempotent operation completes no more than one * time.</p> */ inline void SetClientRequestToken(const char* value) { m_clientRequestTokenHasBeenSet = true; m_clientRequestToken.assign(value); } /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the operation. An idempotent operation completes no more than one * time.</p> */ inline SendPipelineExecutionStepSuccessRequest& WithClientRequestToken(const Aws::String& value) { SetClientRequestToken(value); return *this;} /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the operation. An idempotent operation completes no more than one * time.</p> */ inline SendPipelineExecutionStepSuccessRequest& WithClientRequestToken(Aws::String&& value) { SetClientRequestToken(std::move(value)); return *this;} /** * <p>A unique, case-sensitive identifier that you provide to ensure the * idempotency of the operation. An idempotent operation completes no more than one * time.</p> */ inline SendPipelineExecutionStepSuccessRequest& WithClientRequestToken(const char* value) { SetClientRequestToken(value); return *this;} private: Aws::String m_callbackToken; bool m_callbackTokenHasBeenSet; Aws::Vector<OutputParameter> m_outputParameters; bool m_outputParametersHasBeenSet; Aws::String m_clientRequestToken; bool m_clientRequestTokenHasBeenSet; }; } // namespace Model } // namespace SageMaker } // namespace Aws
cailean-d/chat-app-server
server/models/friend.js
<filename>server/models/friend.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const database = mongoose.connection; const friendSchema = new Schema({ friend_1: { type: String, required: true }, friend_2: { type: String, required: true }, status: { type: String, required: true, default: 0 }, date: { type: Date, required: true, default: Date.now } }); module.exports = database.model('friends', friendSchema);
vvoww/BKCommonLib
src/main/java/com/bergerkiller/bukkit/common/collections/octree/DoubleOctree.java
<reponame>vvoww/BKCommonLib<filename>src/main/java/com/bergerkiller/bukkit/common/collections/octree/DoubleOctree.java package com.bergerkiller.bukkit.common.collections.octree; import java.util.AbstractCollection; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.NoSuchElementException; import org.bukkit.util.Vector; import com.bergerkiller.bukkit.common.bases.IntVector3; import com.bergerkiller.bukkit.common.utils.LogicUtil; import com.bergerkiller.bukkit.common.utils.MathUtil; /** * Wraps the {@link Octree} to store data at double x/y/z coordinates, instead of int. * This is done by giving each 1x1x1 area a linked list of entries stored there. * If a lot of values are stored inside single 1x1x1 areas, this container is not recommended.<br> * <br> * Within 1x1x1 blocks, when iterating the elements, the sorting of the elements will be ascending. * First sorted by x-coordinate, then by y-coordinate, then by z-coordinate.<br> * <br> * The block coordinate of a coordinate is the Double floor value. * * @param <T> The value type of the DoubleOctree */ public class DoubleOctree<T> implements DoubleOctreeIterable<T> { private final Octree<Entry<T>> tree; private final DoubleOctreeIterator<T> remove_iter; public DoubleOctree() { this.tree = new Octree<Entry<T>>(); this.remove_iter = new DoubleOctreeIterator<T>(this.tree.remove_iter); } /** * Clears all the contents of this Double Octree, freeing all memory associated with it. */ public void clear() { this.tree.clear(); } @Override public DoubleOctreeIterator<T> iterator() { return new DoubleOctreeIterator<T>(this.tree.iterator()); } /** * Gets an unmodifiable view of all the values inside this tree * * @return values */ public Collection<T> values() { return new DoubleOctreeValues<T>(this.tree.values()); } private static final class DoubleOctreeValues<T> extends AbstractCollection<T> { private final Collection<Entry<T>> rootEntries; public DoubleOctreeValues(Collection<Entry<T>> rootEntries) { this.rootEntries = rootEntries; } @Override public Iterator<T> iterator() { return new Iterator<T>() { private Iterator<Entry<T>> rootEntryIter = rootEntries.iterator(); private Entry<T> nextEntry = null; @Override public boolean hasNext() { if (this.nextEntry == null) { if (this.rootEntryIter.hasNext()) { this.nextEntry = this.rootEntryIter.next(); } else { return false; } } return true; } @Override public T next() { if (!this.hasNext()) { throw new NoSuchElementException("No more elements inside the tree"); } T value = this.nextEntry.getValue(); this.nextEntry = this.nextEntry.next; return value; } }; } @Override public int size() { int size = 0; Iterator<T> iter = this.iterator(); while (iter.hasNext()) { size++; iter.next(); } return size; } } /** * Gets a view of the contents of this tree that lay inside a cuboid area. * The maximum coordinate includes all values inside that block of values. * If this is {1,2,3} then this will includes coordinates such as {1.2, 2.99, 3.0}. * * @param min coordinates of the cuboid (inclusive) * @param max coordinates of the cuboid (inclusive) * @return iterable */ public DoubleOctreeIterable<T> cuboid(final IntVector3 min, final IntVector3 max) { return () -> new DoubleOctreeIterator<T>(new OctreeCuboidIterator<Entry<T>>(DoubleOctree.this.tree, min, max)); } /** * Gets a view of the contents of this tree that lay inside a single 1x1x1 block area. * The maximum coordinate includes all values inside that block of values. * If this is {1,2,3} then this will includes coordinates such as {1.2, 2.99, 3.0}. * * @param block coordinate * @return iterable */ public DoubleOctreeIterable<T> block(final IntVector3 block) { return () -> new DoubleOctreeIterator<T>(new OctreePointIterator<Entry<T>>(DoubleOctree.this.tree, block)); } /** * Checks whether a value is stored at the coordinates specified. * * @param x The X-coordinate * @param y The Y-coordinate * @param z The Z-coordinate * @param value The value expected to be stored here * @return True if a value is stored at the coordinates, False if not */ public boolean contains(double x, double y, double z, Object value) { Entry<T> entry = this.tree.get(MathUtil.floor(x), MathUtil.floor(y), MathUtil.floor(z)); if (entry != null) { do { int compare = entry.compareTo(x, y, z); if (compare > 0) { return false; } else if (compare == 0 && LogicUtil.bothNullOrEqual(entry.getValue(), value)) { return true; } } while ((entry = entry.next) != null); } return false; } /** * Gets the values stored at the specified coordinates. * * @param x The X-coordinate * @param y The Y-coordinate * @param z The Z-coordinate * @return Values stored at these coordinates */ public Collection<T> get(double x, double y, double z) { Entry<T> firstEntry = this.getFirstEntry(x, y, z); return (firstEntry == null) ? Collections.emptyList() : new PositionCollection<T>(firstEntry); } /** * Adds a new entry at the specified coordinates * * @param x The X-coordinate * @param y The Y-coordinate * @param z The Z-coordinate * @param value The value to store */ public void add(double x, double y, double z, T value) { addEntry(new Entry<T>(x, y, z, value)); } /** * Removes an entry stored at the coordinates specified, returning the entry that was * removed. * * @param x The X-coordinate * @param y The Y-coordinate * @param z The Z-coordinate * @param value The value of the entry to remove * @return True if an entry was found and removed, False otherwise */ public boolean remove(double x, double y, double z, Object value) { this.remove_iter.reset(); this.tree.remove_iter.reset(MathUtil.floor(x), MathUtil.floor(y), MathUtil.floor(z)); while (this.remove_iter.hasNext()) { Entry<T> entry = this.remove_iter.nextEntry(); int compare = entry.compareTo(x, y, z); if (compare > 0) { break; } else if (compare == 0 && LogicUtil.bothNullOrEqual(entry.getValue(), value)) { this.remove_iter.remove(); return true; } else if (compare > 0) { break; } } return false; } /** * Moves an entry from the old position to a new position as efficiently as possible. * The lookup is optimized in several ways to speed this up: * <ul> * <li>If the position is unchanged, only the value is updated * <li>If the old and new position are in the same 1x1x1 block, chain lookup is only done once * <li>Traversing the underlying tree is done while excluding regions that contain neither old nor new entry * </ul> * * @param oldX The X-coordinate of the old position * @param oldY The Y-coordinate of the old position * @param oldZ The Z-coordinate of the old position * @param oldValue The value stored at the old position * @param newX The X-coordinate of the desired new position * @param newY The Y-coordinate of the desired new position * @param newZ The Z-coordinate of the desired new position * @param newValue The value to store at the new position * @return True if the old value was found and moved, False otherwise * @see {@link #moveEntry(Entry, Entry)} */ public boolean move(double oldX, double oldY, double oldZ, T oldValue, double newX, double newY, double newZ, T newValue) { return moveEntry(new Entry<T>(oldX, oldY, oldZ, oldValue), new Entry<T>(newX, newY, newZ, newValue)); } /** * Moves an entry from the old position to a new position as efficiently as possible. * The lookup is optimized in several ways to speed this up: * <ul> * <li>If the position is unchanged, only the value is updated * <li>If the old and new position are in the same 1x1x1 block, chain lookup is only done once * <li>Traversing the underlying tree is done while excluding regions that contain neither old nor new entry * </ul> * * @param oldX The X-coordinate of the old position * @param oldY The Y-coordinate of the old position * @param oldZ The Z-coordinate of the old position * @param value The value stored at the old position that will be moved to a new position * @param newX The X-coordinate of the desired new position * @param newY The Y-coordinate of the desired new position * @param newZ The Z-coordinate of the desired new position * @return True if the old value was found and moved, False otherwise * @see {@link #moveEntry(Entry, Entry)} */ public boolean move(double oldX, double oldY, double oldZ, T value, double newX, double newY, double newZ) { return moveEntry(new Entry<T>(oldX, oldY, oldZ, value), new Entry<T>(newX, newY, newZ, value)); } /** * Checks whether the value stored at the coordinates of an entry, * match the value of the entry. The {@link Object#equals(Object)} method * is used to perform the final check. If the value of the entry * and of what is stored are both null, the two are assumed equal. * * @param entry The entry to find * @return True if the entry specified is contained, False if not */ public boolean containsEntry(Entry<?> entry) { Entry<T> existing = this.getFirstEntry(entry.getX(), entry.getY(), entry.getZ()); if (existing == null) { return false; } else if (existing.valueEquals(entry)) { return true; } existing = existing.next; while (existing != null && existing.equalsCoord(entry.getX(), entry.getY(), entry.getZ())) { if (existing.valueEquals(entry)) { return true; } else { existing = existing.next; } } return false; } /** * Gets the first entry stored that represents the coordinates specified * * @param x The X-coordinate * @param y The Y-coordinate * @param z The Z-coordinate * @return First entry stored at these coordinates. Null if nothing is stored. */ private Entry<T> getFirstEntry(double x, double y, double z) { int compare; Entry<T> entry = this.tree.get(MathUtil.floor(x), MathUtil.floor(y), MathUtil.floor(z)); while (true) { if (entry == null || (compare = entry.compareTo(x, y, z)) > 0) { return null; } else if (compare == 0) { return entry; } else { entry = entry.next; } } } /** * Puts a new entry into this tree. The entry can be reused * for other uses to reduce the memory footprint, since it is immutable. * * @param value * @return previous entry at the coordinates of the entry, if one existed */ @SuppressWarnings("unchecked") public void addEntry(Entry<? extends T> value) { int index = this.tree.getValueIndex(value.getBlockX(), value.getBlockY(), value.getBlockZ(), true); // Retrieve entry, if it is null, then nothing was stored in this 1x1x1 block Entry<T> currentEntry = this.tree.getValueAtIndex(index); if (currentEntry == null) { this.tree.putValueAtIndex(index, (Entry<T>) value); return; } // Go by all the sorted entries in the chain until we find it Entry<T> previous = null; do { int compare = currentEntry.compareTo(value); if (compare >= 0) { // Found an entry equal to or beyond the one we want if (previous == null) { // Insert as first entry in the tree previous = (Entry<T>) value; this.tree.putValueAtIndex(index, previous); } else { // Insert in between the previous and current entry previous.next = (Entry<T>) value; } ((Entry<T>) value).next = currentEntry; return; } // Keep looking previous = currentEntry; currentEntry = currentEntry.next; } while (currentEntry != null); // Append to the end of the chain previous.next = (Entry<T>) value; value.next = null; } /** * Removes an entry stored inside this octree. * * @param entry The entry to remove * @return True if an entry was found and removed, False otherwise */ public boolean removeEntry(Entry<?> entry) { return remove(entry.getX(), entry.getY(), entry.getZ(), entry.getValue()); } /** * Moves an entry from the old position to a new position as efficiently as possible. * The lookup is optimized in several ways to speed this up: * <ul> * <li>If the position is unchanged, only the value is updated * <li>If the old and new position are in the same 1x1x1 block, chain lookup is only done once * <li>Traversing the underlying tree is done while excluding regions that contain neither old nor new entry * </ul> * * @param oldEntry to replace, null to only add a new entry * @param newEntry to replace oldEntry with, null to remove the old entry * @return the result of the move, which will be SUCCESS if the tree was changed */ @SuppressWarnings("unchecked") public boolean moveEntry(Entry<? extends T> oldEntry, Entry<? extends T> newEntry) { // Special cases where we do not move, but instead add or remove if (oldEntry == null) { if (newEntry != null) { this.addEntry(newEntry); } return true; } else if (newEntry == null) { return this.removeEntry(oldEntry); } else if (oldEntry.equals(newEntry)) { return this.containsEntry(oldEntry); } // Find the 1x1x1 block coordinates and value index of the old and new entry int oldBlockX = oldEntry.getBlockX(); int oldBlockY = oldEntry.getBlockY(); int oldBlockZ = oldEntry.getBlockZ(); int newBlockX = newEntry.getBlockX(); int newBlockY = newEntry.getBlockY(); int newBlockZ = newEntry.getBlockZ(); int oldIndex = this.tree.getValueIndex(oldBlockX, oldBlockY, oldBlockZ, false); if (oldIndex == 0) { return false; } // If block is unchanged, we only have to find a single entry and modify the chain if (oldBlockX == newBlockX && oldBlockY == newBlockY && oldBlockZ == newBlockZ) { return moveEntryInChain(oldIndex, (Entry<T>) oldEntry, (Entry<T>) newEntry); } // Remove the entry at the old block { Entry<T> currentEntry = this.tree.getValueAtIndex(oldIndex); int compare = currentEntry.compareTo(oldEntry); if (compare == 0 && currentEntry.valueEquals(oldEntry)) { // First entry of chain, use setValueAtIndex to update it if (currentEntry.next == null) { this.tree.remove(oldBlockX, oldBlockY, oldBlockZ); } else { this.tree.putValueAtIndex(oldIndex, currentEntry.next); } } else if (compare > 0) { // Expected before this entry, so missing return false; } else { // Find it in the chain while (true) { if (currentEntry.next == null || (compare = currentEntry.next.compareTo(oldEntry)) > 0) { return false; } else if (compare == 0 && currentEntry.next.valueEquals(oldEntry)) { currentEntry.next = currentEntry.next.next; break; } else { currentEntry = currentEntry.next; } } } } // Add the new entry this.addEntry(newEntry); return true; } // Moves an entry inside the chain of the same 1x1x1 block private boolean moveEntryInChain(int index, Entry<T> oldEntry, Entry<T> newEntry) { final Entry<T> entryAtIndex = this.tree.getValueAtIndex(index); int compare; // Special care with the very first entry of the chain { // Check whether the old entry is the start of the chain, or 'before' (missing) if ((compare = entryAtIndex.compareTo(oldEntry)) == 0 && entryAtIndex.valueEquals(oldEntry)) { // Shortcut when only a single entry is stored in a 1x1x1 block, or when // the new entry is put in the front of the chain Entry<T> currentEntry = entryAtIndex.next; if (currentEntry == null || (compare = currentEntry.compareTo(newEntry)) > 0) { newEntry.next = currentEntry; this.tree.putValueAtIndex(index, newEntry); return true; } // Find where in the chain we must store the next entry while (currentEntry.next != null && (compare = currentEntry.next.compareTo(newEntry)) < 0) { currentEntry = currentEntry.next; } // Insert after the entry where we stopped newEntry.next = currentEntry.next; currentEntry.next = (Entry<T>) newEntry; this.tree.putValueAtIndex(index, entryAtIndex.next); return true; } else if (compare > 0) { return false; } // Check whether the new entry should be the new start of the chain if ((compare = entryAtIndex.compareTo(newEntry)) >= 0) { // We know entryAtIndex is not oldEntry, but find where the oldEntry is, then Entry<T> currentEntry = entryAtIndex; while (currentEntry.next != null) { compare = currentEntry.next.compareTo(oldEntry); if (compare == 0 && currentEntry.next.valueEquals(oldEntry)) { // Found it! Do the swap! newEntry.next = entryAtIndex; currentEntry.next = currentEntry.next.next; this.tree.putValueAtIndex(index, newEntry); return true; } else if (compare > 0) { // Old entry was expected here, but isn't return false; } else { currentEntry = currentEntry.next; } } // Could not find oldEntry in the chain return false; } } // At this point we know we are replacing entries inside the chain // Do we expect to find a place for the old entry before or after the new entry? if (oldEntry.compareTo(newEntry) < 0) { // We expect to find the old entry before the new entry Entry<T> entryBeforeOldEntry = null; // Loop until we find the old entry Entry<T> currentEntry = entryAtIndex; while (true) { if (currentEntry.next == null || (compare = currentEntry.next.compareTo(oldEntry)) > 0) { return false; } else if (compare == 0 && currentEntry.next.valueEquals(oldEntry)) { entryBeforeOldEntry = currentEntry; currentEntry = currentEntry.next.next; break; } else { currentEntry = currentEntry.next; } } // First loop, check if the new entry directly follows the parent of the old entry // In that case the new entry will replace the old entry if (currentEntry == null || (compare = currentEntry.compareTo(newEntry)) >= 0) { newEntry.next = currentEntry; entryBeforeOldEntry.next = newEntry; return true; } // Loop until we find a place for the new entry while (true) { if (currentEntry.next == null || (compare = currentEntry.next.compareTo(newEntry)) >= 0) { newEntry.next = currentEntry.next; entryBeforeOldEntry.next = entryBeforeOldEntry.next.next; currentEntry.next = newEntry; return true; } else { currentEntry = currentEntry.next; } } } else { // We expect to find the new entry before the old entry Entry<T> entryBeforeNewEntry = null; // Loop until we find a place for the new entry Entry<T> currentEntry = entryAtIndex; while (true) { if (currentEntry.next == null || (compare = currentEntry.next.compareTo(newEntry)) >= 0) { entryBeforeNewEntry = currentEntry; currentEntry = currentEntry.next; break; } else { currentEntry = currentEntry.next; } } // First loop, check if the old entry directly follows the parent of the new entry // In that case we must carefully reorder the entries if (currentEntry == null || (compare = currentEntry.compareTo(oldEntry)) > 0) { return false; } else if (compare == 0 && currentEntry.valueEquals(oldEntry)) { newEntry.next = currentEntry.next; entryBeforeNewEntry.next = newEntry; return true; } // Loop until we find the old entry while (true) { if (currentEntry.next == null || (compare = currentEntry.next.compareTo(oldEntry)) > 0) { return false; } else if (compare == 0 && currentEntry.next.valueEquals(oldEntry)) { newEntry.next = entryBeforeNewEntry.next; currentEntry.next = currentEntry.next.next; entryBeforeNewEntry.next = newEntry; return true; } else { currentEntry = currentEntry.next; } } } } /** * Collection of values at a single x/y/z coordinate. Must store at least one * entry. */ private static final class PositionCollection<T> extends AbstractCollection<T> { private final Entry<T> root; public PositionCollection(Entry<T> root) { this.root = root; } private Entry<T> getNext(Entry<T> entry) { Entry<T> next = entry.next; if (next != null && next.getX() == this.root.getX() && next.getY() == this.root.getY() && next.getZ() == this.root.getZ()) { return next; } else { return null; } } @Override public Iterator<T> iterator() { return new Iterator<T>() { Entry<T> next = root; @Override public boolean hasNext() { return this.next != null; } @Override public T next() { if (this.next == null) { throw new NoSuchElementException("No next element available"); } T result = this.next.getValue(); this.next = getNext(this.next); return result; } }; } @Override public boolean isEmpty() { return false; } @Override public int size() { int size = 0; Entry<T> entry = this.root; do { size++; } while ((entry = getNext(entry)) != null); return size; } } /** * Immutable entry in a Double Octree. * The properties of this object will not change when the tree * is later modified. * * @param <T> value type */ public static final class Entry<T> implements Comparable<Entry<?>> { private final double x; private final double y; private final double z; private final T value; protected Entry<T> next; public Entry(Vector position, T value) { this(position.getX(), position.getY(), position.getZ(), value); } public Entry(double x, double y, double z, T value) { this.x = x; this.y = y; this.z = z; this.value = value; this.next = null; } /** * Gets the X-coordinate of where the value is stored * * @return X-coordinate */ public double getX() { return this.x; } /** * Gets the Y-coordinate of where the value is stored * * @return Y-coordinate */ public double getY() { return this.y; } /** * Gets the Z-coordinate of where the value is stored * * @return Z-coordinate */ public double getZ() { return this.z; } /** * Gets the X-coordinate of the 1x1x1 block where the value is stored * * @return Block X-coordinate */ public int getBlockX() { return MathUtil.floor(this.x); } /** * Gets the Y-coordinate of the 1x1x1 block where the value is stored * * @return Block Y-coordinate */ public int getBlockY() { return MathUtil.floor(this.y); } /** * Gets the Z-coordinate of the 1x1x1 block where the value is stored * * @return Block Z-coordinate */ public int getBlockZ() { return MathUtil.floor(this.z); } /** * Gets a new 3D Vector storing the x/y/z coordinates of where the value is stored * * @return coordinates vector */ public Vector toVector() { return new Vector(this.x, this.y, this.z); } /** * Gets the squared distance between the position of this entry and the * coordinates specified. * * @param x The X-coordinate * @param y The Y-coordinate * @param z The Z-coordinate * @return Distance squared between this entry and the coordinates specified */ public double distanceSquared(double x, double y, double z) { return MathUtil.distanceSquared(this.x, this.y, this.z, x, y, z); } /** * Gets the squared distance between the position of this entry and the * coordinates specified. * * @param pos The coordinates * @return Distance squared between this entry and the coordinates specified */ public double distanceSquared(Vector pos) { return distanceSquared(pos.getX(), pos.getY(), pos.getZ()); } /** * Gets the distance between the position of this entry and the * coordinates specified. * * @param x The X-coordinate * @param y The Y-coordinate * @param z The Z-coordinate * @return Distance between this entry and the coordinates specified */ public double distance(double x, double y, double z) { return Math.sqrt(distanceSquared(x, y, z)); } /** * Gets the distance between the position of this entry and the * coordinates specified. * * @param pos The coordinates * @return Distance between this entry and the coordinates specified */ public double distance(Vector pos) { return distance(pos.getX(), pos.getY(), pos.getZ()); } /** * Gets the value being stored * * @return value */ public T getValue() { return this.value; } /** * Gets whether the value of this entry equals the value specified. * Also returns true if both are null. * * @param value * @return True if equals */ public boolean valueEquals(Object value) { return LogicUtil.bothNullOrEqual(this.value, value); } /** * Gets whether the value of this entry equals the value in the entry specified. * Also returns true if both are null. * * @param value * @return True if equals */ public boolean valueEquals(Entry<?> entry) { return this == entry || valueEquals(entry.getValue()); } @Override public int compareTo(Entry<?> other) { return this.compareTo(other.x, other.y, other.z); } /** * Compares the x/y/z of this entry with the x/y/z specified. * * @param x The X-coordinate * @param y The Y-coordinate * @param z The Z-coordinate * @return 0, less than 0 or greater than 0 depending on order * @see {@link #compareTo(Entry)} */ public int compareTo(double x, double y, double z) { int comp; if ((comp = Double.compare(this.x, x)) == 0) { if ((comp = Double.compare(this.y, y)) == 0) { comp = Double.compare(this.z, z); } } return comp; } /** * Gets whether the x/y/z of this entry equals the x/y/z specified * * @param x The X-coordinate * @param y The Y-coordinate * @param z The Z-coordinate * @return True if the coordinates are equal */ public boolean equalsCoord(double x, double y, double z) { return this.x == x && this.y == y && this.z == z; } /** * Gets whether the x/y/z of this entry equals the x/y/z in the vector specified * * @param pos The coordinates to compare against * @return True if the coordinates are equal */ public boolean equalsCoord(Vector pos) { return this.x == pos.getX() && this.y == pos.getY() && this.z == pos.getZ(); } /** * Gets whether the x/y/z coordinates of the 1x1x1 block this entry is stored in equals * the x/y/z block coordinates specified * * @param x The block X-coordinate * @param y The block Y-coordinate * @param z The block Z-coordinate * @return True if the coordinates are equal */ public boolean equalsBlockCoord(int x, int y, int z) { return this.getBlockX() == x && this.getBlockY() == y && this.getBlockZ() == z; } /** * Gets whether the x/y/z coordinates of the 1x1x1 block this entry is stored in equals * the x/y/z block coordinates specified * * @param blockCoord The coordinates * @return True if the coordinates are equal */ public boolean equalsBlockCoord(IntVector3 blockCoord) { return equalsBlockCoord(blockCoord.x, blockCoord.y, blockCoord.z); } @Override public boolean equals(Object other) { if (other == this) { return true; } else if (other instanceof Entry) { Entry<?> otherEntry = (Entry<?>) other; return this.getX() == otherEntry.getX() && this.getY() == otherEntry.getY() && this.getZ() == otherEntry.getZ() && this.valueEquals(otherEntry.getValue()); } else { return false; } } @Override public int hashCode() { //TODO: Not so good? return Double.hashCode(this.x) + (Double.hashCode(this.z) << 8) + (Double.hashCode(this.y) << 16); } @Override public String toString() { return "{x:" + this.x + ", y:" + this.y + ", z:" + this.z + ", value:" + this.value + "}"; } /** * Creates a new entry * * @param pos The position of the entry * @param value The value of the entry * @return New Entry */ public static <T> Entry<T> create(Vector pos, T value) { return new Entry<T>(pos, value); } /** * Creates a new entry * * @param x The X-coordinate of the entry * @param y The Y-coordinate of the entry * @param z The Z-coordinate of the entry * @param value The value of the entry * @return New Entry */ public static <T> Entry<T> create(double x, double y, double z, T value) { return new Entry<T>(x, y, z, value); } } }
jkuester/ccl-testing
ccl-maven-plugin/src/main/java/com/cerner/ccl/testing/maven/ccl/util/DelegatingOutputStream.java
package com.cerner.ccl.testing.maven.ccl.util; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * An {@link OutputStream} that delegates its work to an underlying collection of {@code OutputStream} objects. * * @author <NAME> * */ public class DelegatingOutputStream extends OutputStream { private final List<OutputStream> streams = new ArrayList<OutputStream>(); /** * Add an output stream. * * @param outputStream * The {@link OutputStream} to be added to this delegate. */ public void addStream(final OutputStream outputStream) { streams.add(outputStream); } @Override public void close() throws IOException { for (final OutputStream stream : streams) stream.close(); } /** * Get the streams that lie beneath this output stream. * * @return An immutable collection of the streams that lie beneath this output stream. */ public Collection<OutputStream> getStreams() { return Collections.unmodifiableCollection(streams); } /** * Determine whether or not this delegate contains the given output stream already, based on its * {@link OutputStream#equals(Object) equals} contract. * * @param outputStream * The {@link OutputStream} whose existence is to be determined. * @return {@code true} if the output stream already exists; {@code false} if otherwise. */ public boolean hasOutputStream(final OutputStream outputStream) { return streams.contains(outputStream); } @Override public void write(final int b) throws IOException { for (final OutputStream stream : streams) stream.write(b); } }
pyracanda/runtime
src/native/corehost/bundle/manifest.cpp
<reponame>pyracanda/runtime<gh_stars>1000+ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include "manifest.h" using namespace bundle; manifest_t manifest_t::read(reader_t& reader, const header_t& header) { manifest_t manifest; for (int32_t i = 0; i < header.num_embedded_files(); i++) { file_entry_t entry = file_entry_t::read(reader, header.major_version(), header.is_netcoreapp3_compat_mode()); manifest.files.push_back(std::move(entry)); manifest.m_files_need_extraction |= entry.needs_extraction(); } return manifest; }
GhostieSpook/lilianne
web/src/reducers/users.js
import { INITIALIZE, SET_CURRENT_SONG, SET_DJ_ORDER } from '../actions'; export default function users(state = {}, action) { switch (action.type) { case INITIALIZE: { const users = { ...state }; const { history, order, current } = action.payload; for (const song of history) { const user = song.player.dj; users[user.id] = user; } for (const user of order) { users[user.id] = user; } if (current) { const user = current.player.dj; users[user.id] = user; } return users; } case SET_CURRENT_SONG: { const song = action.payload; if (!song) return state; const user = song.player.dj; return { ...state, [user.id]: user, }; } case SET_DJ_ORDER: { const users = { ...state }; for (const user of action.payload) { users[user.id] = user; } return users; } default: return state; } } export function getUser(state, id) { return state.users[id]; }
idiomaspuentes/tc-create-app
src/hooks/useStateReducer.js
import { useCallback, useReducer } from 'react'; import { ensureRepo } from 'gitea-react-toolkit'; import { stateReducer } from '../core/state.reducer'; import { saveState } from '../core/persistence'; import defaults from '../core/state.defaults'; export const useStateReducer = ({ authentication, language, sourceRepository, filepath, organization, resourceLinks, contentIsDirty, }) => { const _defaults = { ...defaults, authentication, sourceRepository, language, filepath, organization, resourceLinks, contentIsDirty, }; const [state, dispatch] = useReducer(stateReducer, _defaults); const setOrganization = useCallback((value) => { if (value !== state.organization) { dispatch({ type: 'set_organization', value }); saveState('organization', value); } }, [state.organization]); const setValidationPriority = useCallback((value) => { dispatch({ type: 'set_validation_priority', value }); }, []); const setFontScale = useCallback((value) => { dispatch({ type: 'set_font_scale', value }); }, []); const setExpandedScripture = useCallback((value) => { dispatch({ type: 'set_expanded_scripture', value }); }, []); const setConfig = useCallback((value) => { dispatch({ type: 'set_config', value }); }, []); const setSourceRepository = useCallback((value) => { dispatch({ type: 'set_source_repository', value }); saveState('sourceRepository', value); if (!value) { dispatch({ type: 'set_target_repository' }); } }, []); const setFilepath = useCallback((value) => { console.log('useReducer.setFilepath', value) if (value !== state.filepath) { dispatch({ type: 'set_filepath', value }); saveState('filepath', value); } }, [state.filepath]); const setLanguage = useCallback((value) => { if (value !== state.language) { dispatch({ type: 'set_language', value }); saveState('language', value); if (!value) { setSourceRepository(); } // reset if no language } }, [state.language, setSourceRepository]); const clearState = useCallback(() => { setOrganization(); setSourceRepository(); setLanguage(); setFilepath(); }, [setFilepath, setLanguage, setOrganization, setSourceRepository]); const setAuthentication = useCallback((value) => { if (JSON.stringify(value) !== JSON.stringify(state.authentication)) { dispatch({ type: 'set_authentication', value }); /* saveState('authentication', value); */ if (!value) { //logged out reset state clearState(); } } }, [clearState, state.authentication]); const setTargetRepository = useCallback((value) => { dispatch({ type: 'set_target_repository', value }); }, []); const setTargetRepoFromSourceRepo = useCallback(({ authentication, sourceRepository, language, organization, }) => { if (authentication && sourceRepository && language) { const repositoryNameArray = sourceRepository.name.split('_'); const resourceNameArray = repositoryNameArray.slice(1); const translationRepoName = `${language.languageId}_${resourceNameArray.join('_')}`; const branch = `${authentication.user.username}-tc-create-1`; const owner = organization.username; const { description } = sourceRepository; const params = { owner, repo: translationRepoName, config: authentication.config, settings: { description }, branch, }; ensureRepo(params).then((res) => { const repo = { ...res, branch }; setTargetRepository(repo); }).catch((err) => { setTimeout(() => { clearState(); alert( `The organization "${owner}" does not contain the selected translation ${language.languageName} for the repository "${description}"\nPlease make sure that your repository has been set up correctly by your organization administrator.` ); }, 200); console.error(err); }); } else { setTargetRepository(); }; }, [clearState, setTargetRepository]); const setResourceLinks = useCallback( (value) => { if (value !== state.resourceLinks) { dispatch({ type: 'set_resource_links', value }); saveState('resourceLinks', value); } }, [state.resourceLinks] ); const setContentIsDirty = useCallback((value) => { if (value !== state.contentIsDirty) { dispatch({ type: 'set_content_is_dirty', value }); saveState('contentIsDirty', value); } }, [state.contentIsDirty]); const setCriticalValidationErrors = useCallback((value) => { if (value !== state.criticalValidationErrors) { dispatch({ type: 'set_critical_validation_errors', value }); saveState('criticalValidationErrors', value); }; }, [state.criticalValidationErrors]); const setCacheFileKey = useCallback((value) => { if (value !== state.cacheFileKey) { dispatch({ type: 'set_cache_file_key', value }); saveState('cacheFileKey', value); }; }, [state.cacheFileKey]); const setCacheWarningMessage = useCallback((value) => { if (value !== state.cacheWarningMessage) { dispatch({ type: 'set_cache_warning_message', value }); saveState('cacheWarningMessage', value); }; }, [state.cacheWarningMessage]); const setCachedFile = useCallback((value) => { if (value !== state.cachedFile) { dispatch({ type: 'set_cached_file', value }); saveState('cachedFile', value); }; }, [state.cachedFile]); const clearCachedFile = useCallback(() => { setCachedFile(); }, [setCachedFile]); const actions = { setAuthentication, setLanguage, setFontScale, setExpandedScripture, setConfig, setResourceLinks, setContentIsDirty, setSourceRepository, setTargetRepository, setTargetRepoFromSourceRepo, setFilepath, setOrganization, setValidationPriority, setCriticalValidationErrors, setCacheFileKey, setCacheWarningMessage, setCachedFile, clearCachedFile, }; return { state, actions }; };
FigueroaR/meetup_mock_web_app
node_modules/yaml/dist/schema/Node.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; class Node {} exports.default = Node;
adamdubey/NodeJS30
day6-array-methods/pop.js
arr = [ 5 , 5 , 8 , 7 , 6 ]; console.log(arr); arr.pop(); console.log(arr);
benjmainbit/ECR721
node_modules/@openzeppelin/hardhat-upgrades/dist/upgrade-proxy.js
<filename>node_modules/@openzeppelin/hardhat-upgrades/dist/upgrade-proxy.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeUpgradeProxy = void 0; const upgrades_core_1 = require("@openzeppelin/upgrades-core"); const utils_1 = require("./utils"); function makeUpgradeProxy(hre) { return async function upgradeProxy(proxy, ImplFactory, opts = {}) { const { provider } = hre.network; const proxyAddress = utils_1.getContractAddress(proxy); await upgrades_core_1.setProxyKind(provider, proxyAddress, opts); const upgradeTo = await getUpgrader(proxyAddress, ImplFactory.signer); const nextImpl = await utils_1.deployImpl(hre, ImplFactory, upgrades_core_1.withValidationDefaults(opts), proxyAddress); const upgradeTx = await upgradeTo(nextImpl); const inst = ImplFactory.attach(proxyAddress); // @ts-ignore Won't be readonly because inst was created through attach. inst.deployTransaction = upgradeTx; return inst; }; async function getUpgrader(proxyAddress, signer) { const { provider } = hre.network; const adminAddress = await upgrades_core_1.getAdminAddress(provider, proxyAddress); const adminBytecode = await upgrades_core_1.getCode(provider, adminAddress); if (adminBytecode === '0x') { // No admin contract: use TransparentUpgradeableProxyFactory to get proxiable interface const TransparentUpgradeableProxyFactory = await utils_1.getTransparentUpgradeableProxyFactory(hre, signer); const proxy = TransparentUpgradeableProxyFactory.attach(proxyAddress); return nextImpl => proxy.upgradeTo(nextImpl); } else { // Admin contract: redirect upgrade call through it const manifest = await upgrades_core_1.Manifest.forNetwork(provider); const AdminFactory = await utils_1.getProxyAdminFactory(hre, signer); const admin = AdminFactory.attach(adminAddress); const manifestAdmin = await manifest.getAdmin(); if (admin.address !== (manifestAdmin === null || manifestAdmin === void 0 ? void 0 : manifestAdmin.address)) { throw new Error('Proxy admin is not the one registered in the network manifest'); } return nextImpl => admin.upgrade(proxyAddress, nextImpl); } } } exports.makeUpgradeProxy = makeUpgradeProxy; //# sourceMappingURL=upgrade-proxy.js.map
qdlxs99/Zabbix4j
src/test/java/com/zabbix4j/lldrule/LLDRuleGetTest.java
<filename>src/test/java/com/zabbix4j/lldrule/LLDRuleGetTest.java package com.zabbix4j.lldrule; import com.zabbix4j.ZabbixApiParamter; import com.zabbix4j.ZabbixApiTestBase; import org.junit.Test; import static org.junit.Assert.*; /** * @author <NAME> */ public class LLDRuleGetTest extends ZabbixApiTestBase { public LLDRuleGetTest() { super(); } @Test public void testGet1() throws Exception { ZabbixApiTestDummyLLDRule dummyLLDRule = new ZabbixApiTestDummyLLDRule(zabbixApi); Integer targetId = dummyLLDRule.createLLDRule(); try { LLDRuleGetRequest request = new LLDRuleGetRequest(); LLDRuleGetRequest.Params params = request.getParams(); params.addItemId(targetId); params.setSelectItems(ZabbixApiParamter.QUERY.extend.name()); params.setSelectHosts(ZabbixApiParamter.QUERY.extend.name()); params.setSelectHostPrototypes(ZabbixApiParamter.QUERY.extend.name()); params.setSelectGraphs(ZabbixApiParamter.QUERY.extend.name()); LLDRuleGetResponse response = zabbixApi.lldRule().get(request); assertNotNull(response); logger.debug(getGson().toJson(response)); } finally { dummyLLDRule.deleteLLDRule(targetId); } } }
mayunSaicmotor/saic-carbondata
core/src/main/java/org/apache/carbondata/core/writer/ThriftWriter.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.carbondata.core.writer; import java.io.DataOutputStream; import java.io.IOException; import org.apache.carbondata.core.datastorage.store.impl.FileFactory; import org.apache.carbondata.core.util.CarbonUtil; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.thrift.TBase; import org.apache.thrift.TException; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TIOStreamTransport; /** * Simple class that makes it easy to write Thrift objects to disk. */ public class ThriftWriter { /** * buffer size */ private static final int bufferSize = 2048; /** * File to write to. */ private String fileName; /** * For writing to the file. */ private DataOutputStream dataOutputStream; /** * For binary serialization of objects. */ private TProtocol binaryOut; /** * flag to append to existing file */ private boolean append; /** * Constructor. */ public ThriftWriter(String fileName, boolean append) { this.fileName = fileName; this.append = append; } /** * Open the file for writing. */ public void open() throws IOException { FileFactory.FileType fileType = FileFactory.getFileType(fileName); dataOutputStream = FileFactory.getDataOutputStream(fileName, fileType, bufferSize, append); binaryOut = new TCompactProtocol(new TIOStreamTransport(dataOutputStream)); } /** * This will check whether stream and binary out is open or not. * @return */ public boolean isOpen() { if (null != binaryOut && null != dataOutputStream) { return true; } return false; } /** * Write the object to disk. */ public void write(TBase t) throws IOException { try { t.write(binaryOut); dataOutputStream.flush(); } catch (TException e) { throw new IOException(e); } } /** * Write the offset to the file * * @param offset * @throws IOException */ public void writeOffset(long offset) throws IOException { dataOutputStream.writeLong(offset); } /** * Close the file stream. */ public void close() { CarbonUtil.closeStreams(dataOutputStream); } /** * Flush data to HDFS file */ public void sync() throws IOException { if (dataOutputStream instanceof FSDataOutputStream) { ((FSDataOutputStream) dataOutputStream).hsync(); } } }
IamMayankThakur/test-bigdata
adminmgr/media/code/python/red1/BD_152_554_125_reducer.py
#!/usr/bin/python3 import csv from operator import itemgetter import sys #current_count = 0 #current_key = "" current_key = "" current_wickets = 0 current_balls = 0 results = [] for line in sys.stdin: line = line.strip() line_val = line.split(",") bat, bowl, wickets, balls = line_val[0], line_val[1], line_val[2], line_val[3] key = bat + "," + bowl if current_key == key: current_wickets += int(wickets) current_balls += int(balls) else: if (current_key != ""): value = str(current_wickets) + "," + str(current_balls) if(current_balls > 5): results.append([current_key, current_wickets, current_balls]) current_wickets = int(wickets) current_balls = int(balls) current_key = key else: current_key = key current_wickets = int(wickets) current_balls = int(balls) if current_key == key: value = str(current_wickets) + "," + str(current_balls) if(current_balls > 5): results.append([current_key, current_wickets, current_balls]) results = sorted(results, key = lambda x: (-x[1],x[2],x[0])) for i in range(len(results)): print("%s,%s,%s" % (results[i][0], str(results[i][1]), str(results[i][2])))
alirkaya/programming-textbook-solutions
thinkpython_allen_downey/exercise_10_5.py
def chop(t): del t[0], t[-1] t = [1,2,3,4,5,6] print(chop(t)) print(t)
dongdong-cloud/dd-cloud
dd-blog/src/main/java/fun/imcoder/cloud/blog/service/ArticleCategoryService.java
<filename>dd-blog/src/main/java/fun/imcoder/cloud/blog/service/ArticleCategoryService.java package fun.imcoder.cloud.blog.service; import fun.imcoder.cloud.base.support.BaseService; import fun.imcoder.cloud.blog.model.ArticleCategory; public interface ArticleCategoryService extends BaseService<ArticleCategory> { }
codegen-io/gwt-json-overlay
test/src/test/java/test/InheritanceSubA.java
<filename>test/src/test/java/test/InheritanceSubA.java<gh_stars>0 package test; import com.fasterxml.jackson.annotation.JsonTypeName; @JsonTypeName("a") public interface InheritanceSubA extends InheritanceSuper { String getA(); }
xbai0624/MPD_GEM_View_SSP
gem/include/GEMRootHitTree.h
#ifndef GEM_ROOT_HIT_TREE_H #define GEM_ROOT_HIT_TREE_H #include <TTree.h> #include <TFile.h> #include "GEMStruct.h" #include "GEMSystem.h" //////////////////////////////////////////////////////////////////////////////// // save replayed evio files to root tree #define MAXHITS 20000 class GEMRootHitTree { public: GEMRootHitTree(const char* path); ~GEMRootHitTree(); void Write(); void Fill(GEMSystem *gem_sys, const EventData &ev); private: TTree *pTree = nullptr; TFile *pFile = nullptr; std::string fPath; // information to save int evtID; int nch; int Plane[MAXHITS]; // layer id int Prod[MAXHITS]; // gem id (production id given by UVa) int Module[MAXHITS]; // gem location in layer int Strip[MAXHITS]; // strip index on a single chamber int Axis[MAXHITS]; // x or y plane int adc0[MAXHITS]; int adc1[MAXHITS]; int adc2[MAXHITS]; int adc3[MAXHITS]; int adc4[MAXHITS]; int adc5[MAXHITS]; }; #endif
MonsterENT/EiRas
EiRas/Framework/EiRas/PlatformDependency/OnMetal/Material/GraphicsResourceHeapMetal.h
// // GraphicsResourceHeapMetal.h // EiRasMetalBuild // // Created by MonsterENT on 12/8/19. // Copyright © 2019 MonsterENT. All rights reserved. // #import "BaseMetalObject.h" #include <Material/MaterialLayout.hpp> using namespace MaterialSys; @interface GraphicsResourceHeapMetal : BaseMetalObject -(instancetype)initWithPropCount:(_uint)propCount; @property(strong, nonatomic)id<MTLHeap> resourceHeap; @end
re3turn/twitter-crawling
api/src/models/__init__.py
from . import entity
jiadaizhao/LeetCode
0101-0200/0186-Reverse Words in a String II/0186-Reverse Words in a String II.py
<filename>0101-0200/0186-Reverse Words in a String II/0186-Reverse Words in a String II.py class Solution: def reverseWords(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ def reverseStr(s, start, end): while start < end: s[start], s[end] = s[end], s[start] start += 1 end -= 1 reverseStr(s, 0, len(s) - 1) start = 0 for i, c in enumerate(s): if c == ' ': reverseStr(s, start, i - 1) start = i + 1 reverseStr(s, start, len(s) - 1)
gurfinkel/codeSignal
tournaments/isCorrectSentence/isCorrectSentence.cpp
bool isCorrectSentence(std::string inputString) { char leadChar = inputString[0], endChar = inputString[inputString.size() - 1]; if ('A' <= leadChar && leadChar <= 'Z' && endChar == '.') { return true; } else { return false; } }
stefpetrov/Software-University
First Steps in Coding/zoomagazin.js
function zooshop(input) { let dogFood =(input[0] * 2.5); let catFood =(input[1] * 4); let totalAmount = dogFood + catFood; console.log(`${totalAmount} lv.`) } zooshop(["5", "4"])
Siceron/TFEScheduler
src/main/java/objects/TFE.java
<filename>src/main/java/objects/TFE.java<gh_stars>0 package objects; import java.util.ArrayList; import java.util.List; public class TFE { private String code; private List<Person> students; private List<Jury> advisors; private List<Jury> readers; private int fixedSession; private int bannedSession; public TFE(String code, List<Person> students, List<Jury> advisors, List<Jury> readers) { super(); this.code = code; this.students = students; this.advisors = advisors; this.readers = readers; this.fixedSession = -1; } public TFE(String code, int session, boolean isFixed) { super(); this.code = code; if(isFixed) this.fixedSession = session; else this.bannedSession = session; } public String getCode() { return code; } public List<Person> getStudents() { return students; } public List<Jury> getAdvisors() { return advisors; } public List<Jury> getReaders() { return readers; } public int getFixedSession() { return fixedSession; } public void setFixedSession(int fixedSession) { this.fixedSession = fixedSession; } public int getBannedSession() { return bannedSession; } public boolean containsJury(Jury jury){ for(Jury j : advisors){ if(j.getEmail().equals(jury.getEmail())) return true; } for(Jury j : readers){ if(j.getEmail().equals(jury.getEmail())) return true; } return false; } public List<Jury> getJuryList(){ List<Jury> juryList = new ArrayList<Jury>(); for(Jury j : advisors){ juryList.add(j); } for(Jury j : readers){ juryList.add(j); } return juryList; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((code == null) ? 0 : code.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TFE other = (TFE) obj; if (code == null) { if (other.code != null) return false; } else if (!code.equals(other.code)) return false; return true; } @Override public String toString(){ return code; } }
george-jipa/time-series-math
src/test/java/ro/hasna/ts/math/ml/distance/PlaaEuclideanDistanceTest.java
/* * Copyright 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.hasna.ts.math.ml.distance; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import ro.hasna.ts.math.ml.distance.util.DistanceTester; import ro.hasna.ts.math.normalization.ZNormalizer; import ro.hasna.ts.math.representation.PiecewiseLinearAggregateApproximation; import ro.hasna.ts.math.type.MeanSlopePair; import ro.hasna.ts.math.util.TimeSeriesPrecision; import java.util.Random; /** * @since 1.0 */ public class PlaaEuclideanDistanceTest { private PlaaEuclideanDistance distance; private PiecewiseLinearAggregateApproximation plaa; @Before public void setUp() throws Exception { plaa = new PiecewiseLinearAggregateApproximation(8); distance = new PlaaEuclideanDistance(); } @After public void tearDown() throws Exception { distance = null; plaa = null; } @Test public void testTriangleInequality() throws Exception { new DistanceTester().withGenericDistanceMeasure(distance, plaa) .testTriangleInequality(); } @Test public void testEquality() throws Exception { int n = 128; double a[] = new double[n]; double b[] = new double[n]; Random random = new Random(); for (int i = 0; i < n; i++) { a[i] = i; b[i] = 100 + i + random.nextDouble(); } ZNormalizer normalizer = new ZNormalizer(); double result = distance.compute(plaa.transform(normalizer.normalize(a)), plaa.transform(normalizer.normalize(b))); Assert.assertEquals(0, result, 0.1); } @Test public void testOverflow() throws Exception { MeanSlopePair[] a = new MeanSlopePair[4]; a[0] = new MeanSlopePair(0, 8); a[1] = new MeanSlopePair(4, 8); a[2] = new MeanSlopePair(5, 8); a[3] = new MeanSlopePair(6, 8); MeanSlopePair[] b = new MeanSlopePair[4]; b[0] = new MeanSlopePair(7, 8); b[1] = new MeanSlopePair(2, 4); b[2] = new MeanSlopePair(5, 8); b[3] = new MeanSlopePair(1, 2); double result = distance.compute(a, b, 3); Assert.assertEquals(Double.POSITIVE_INFINITY, result, TimeSeriesPrecision.EPSILON); } }
HMS-Core/hms-ecommerce-demo
app/src/main/java/com/huawei/industrydemo/shopping/page/SplashActivity.java
<gh_stars>10-100 /* Copyright 2020-2021. Huawei Technologies Co., Ltd. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.huawei.industrydemo.shopping.page; import android.os.Build; import android.os.Bundle; import android.view.Window; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import com.huawei.industrydemo.shopping.R; import com.huawei.industrydemo.shopping.base.BaseActivity; import com.huawei.industrydemo.shopping.page.viewmodel.SplashActivityViewModel; /** * Splash AdS Page * * @version [Ecommerce-Demo 1.0.0.300, 2020/9/16] * @since [Ecommerce-Demo 1.0.0.300] */ @RequiresApi(api = Build.VERSION_CODES.Q) public class SplashActivity extends BaseActivity { private SplashActivityViewModel mViewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_splash); mViewModel = new SplashActivityViewModel(this); mViewModel.initView(); mViewModel.startCountDown(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); mViewModel.onRequestPermissionsResult(requestCode, permissions, grantResults); } }
tucci-lee/tucci-sso
sso-server/src/main/java/cn/tucci/sso/server/core/support/TokenCodec.java
<filename>sso-server/src/main/java/cn/tucci/sso/server/core/support/TokenCodec.java package cn.tucci.sso.server.core.support; /** * token编解码器 * * @author tucci.lee */ public interface TokenCodec { /** * 加密token * * @param uid uid * @return token */ String encode(Long uid); /** * 解密token * * @param token token * @return uid */ Long decode(String token); }
sohaibiftikhar/cluster-broccoli
server/src/main/scala/de/frosner/broccoli/nomad/models/WithId.scala
package de.frosner.broccoli.nomad.models /** * Attaches a nomad ID to arbitrary payload. * * @param jobId The nomad ID * @param payload The payload * @tparam T The type of the paylo */ final case class WithId[T](jobId: String, payload: T)
fduminy/intellij-community
java/java-tests/testSrc/com/intellij/projectView/ProjectViewUpdatingTest.java
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.intellij.projectView; import com.intellij.ide.projectView.PresentationData; import com.intellij.ide.projectView.TreeStructureProvider; import com.intellij.ide.projectView.ViewSettings; import com.intellij.ide.projectView.impl.AbstractProjectViewPSIPane; import com.intellij.ide.projectView.impl.ClassesTreeStructureProvider; import com.intellij.ide.util.treeView.AbstractTreeBuilder; import com.intellij.ide.util.treeView.AbstractTreeNode; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.psi.*; import com.intellij.refactoring.rename.RenameProcessor; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.ui.tree.AsyncTreeModel; import com.intellij.ui.tree.TreeVisitor; import com.intellij.uiDesigner.projectView.FormMergerTreeStructureProvider; import com.intellij.util.IncorrectOperationException; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; @SuppressWarnings({"HardCodedStringLiteral"}) public class ProjectViewUpdatingTest extends BaseProjectViewTestCase { public void testStandardProviders() { PsiFile element = JavaDirectoryService.getInstance().getClasses(getPackageDirectory())[0].getContainingFile(); final AbstractProjectViewPSIPane pane = myStructure.createPane(); getProjectTreeStructure().setProviders(); pane.select(element, element.getContainingFile().getVirtualFile(), true); PlatformTestUtil.waitWhileBusy(pane.getTree()); PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + " -PsiDirectory: standardProviders\n" + " -PsiDirectory: src\n" + " -PsiDirectory: com\n" + " -PsiDirectory: package1\n" + " Class1.java\n" + " Class2.java\n" + " Class4.java\n" + " Form1.form\n" + " Form1.java\n" + " Form2.form\n" + getRootFiles() + " +External Libraries\n" ); final PsiClass[] classes = JavaDirectoryService.getInstance() .getPackage(getContentDirectory().findSubdirectory("src").findSubdirectory("com").findSubdirectory("package1")).getClasses(); sortClassesByName(classes); WriteCommandAction.runWriteCommandAction(null, () -> classes[0].delete()); PlatformTestUtil.waitForAlarm(600); PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + " -PsiDirectory: standardProviders\n" + " -PsiDirectory: src\n" + " -PsiDirectory: com\n" + " -PsiDirectory: package1\n" + " Class2.java\n" + " Class4.java\n" + " Form1.form\n" + " Form1.java\n" + " Form2.form\n" + getRootFiles() + " +External Libraries\n"); } public void testUpdateProjectView() { getProjectTreeStructure().setProviders(new ClassesTreeStructureProvider(myProject), new FormMergerTreeStructureProvider(myProject)); final AbstractProjectViewPSIPane pane = myStructure.createPane(); final JTree tree = pane.getTree(); PlatformTestUtil.assertTreeEqual(tree, "-Project\n" + " +PsiDirectory: updateProjectView\n" + getRootFiles() + " +External Libraries\n"); final PsiJavaFile classFile = (PsiJavaFile)getContentDirectory().findSubdirectory("src").findSubdirectory("com").findSubdirectory("package1").findFile("Form1.java"); final PsiClass aClass = classFile.getClasses()[0]; final PsiFile containingFile = aClass.getContainingFile(); pane.select(aClass, containingFile.getVirtualFile(), true); PlatformTestUtil.waitWhileBusy(pane.getTree()); PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + " -PsiDirectory: updateProjectView\n" + " -PsiDirectory: src\n" + " -PsiDirectory: com\n" + " -PsiDirectory: package1\n" + " Class1\n" + " +Class2.java\n" + " Class4.java\n" + " Form2.form\n" + " -Form:Form1\n" + " [Form1]\n" + " Form1.form\n" + getRootFiles() + " +External Libraries\n", true); CommandProcessor.getInstance().executeCommand(myProject, () -> new RenameProcessor(myProject, aClass, "Form1_renamed", false, false).run(), null, null); PlatformTestUtil.waitForAlarm(600); PlatformTestUtil.assertTreeEqual(tree, "-Project\n" + " -PsiDirectory: updateProjectView\n" + " -PsiDirectory: src\n" + " -PsiDirectory: com\n" + " -PsiDirectory: package1\n" + " Class1\n" + " +Class2.java\n" + " Class4.java\n" + " Form2.form\n" + " -Form:Form1_renamed\n" + " Form1.form\n" + " [Form1_renamed]\n" + getRootFiles() + " +External Libraries\n", true); TreeUtil.collapseAll(pane.getTree(), 0); PlatformTestUtil.assertTreeEqual(tree, "-Project\n" + " +PsiDirectory: updateProjectView\n" + getRootFiles() + " +External Libraries\n"); final PsiClass aClass2 = JavaDirectoryService.getInstance() .createClass(getContentDirectory().findSubdirectory("src").findSubdirectory("com").findSubdirectory("package1"), "Class6"); PlatformTestUtil.waitForAlarm(600); final PsiFile containingFile2 = aClass2.getContainingFile(); pane.select(aClass2, containingFile2.getVirtualFile(), true); PlatformTestUtil.waitWhileBusy(pane.getTree()); PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + " -PsiDirectory: updateProjectView\n" + " -PsiDirectory: src\n" + " -PsiDirectory: com\n" + " -PsiDirectory: package1\n" + " Class1\n" + " +Class2.java\n" + " Class4.java\n" + " [Class6]\n" + " Form2.form\n" + " +Form:Form1_renamed\n" + getRootFiles() + " +External Libraries\n", true); } public void testShowClassMembers() { getProjectTreeStructure().setProviders(new ClassesTreeStructureProvider(myProject), new FormMergerTreeStructureProvider(myProject)); final AbstractProjectViewPSIPane pane = myStructure.createPane(); final JTree tree = pane.getTree(); PlatformTestUtil.assertTreeEqual(tree, "-Project\n" + " +PsiDirectory: showClassMembers\n" + getRootFiles() + " +External Libraries\n"); myStructure.setShowMembers(true); PsiJavaFile classFile = (PsiJavaFile)getContentDirectory().findSubdirectory("src").findSubdirectory("com").findSubdirectory("package1").findFile("Class1.java"); PsiClass aClass = classFile.getClasses()[0]; PsiFile containingFile = aClass.getContainingFile(); pane.select(aClass, containingFile.getVirtualFile(), true); PlatformTestUtil.waitWhileBusy(pane.getTree()); PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + " -PsiDirectory: showClassMembers\n" + " -PsiDirectory: src\n" + " -PsiDirectory: com\n" + " -PsiDirectory: package1\n" + " -[Class1]\n" + " +InnerClass\n" + " getValue():int\n" + " myField1:boolean\n" + " myField2:boolean\n" + " +Class2\n" + getRootFiles() + " +External Libraries\n", true); final Document document = FileDocumentManager.getInstance().getDocument(containingFile.getVirtualFile()); final int caretPosition = document.getText().indexOf("public class InnerClass") - 1; ApplicationManager.getApplication().runWriteAction(() -> CommandProcessor.getInstance().executeCommand(myProject, () -> document.insertString(caretPosition, "\n"), "typing", null)); PsiDocumentManager.getInstance(myProject).commitDocument(document); PlatformTestUtil.waitForAlarm(600); PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + " -PsiDirectory: showClassMembers\n" + " -PsiDirectory: src\n" + " -PsiDirectory: com\n" + " -PsiDirectory: package1\n" + " -[Class1]\n" + " +InnerClass\n" + " getValue():int\n" + " myField1:boolean\n" + " myField2:boolean\n" + " +Class2\n" + getRootFiles() + " +External Libraries\n", true); classFile = (PsiJavaFile)getContentDirectory().findSubdirectory("src").findSubdirectory("com").findSubdirectory("package1").findFile("Class1.java"); aClass = classFile.getClasses()[0]; final PsiField lastField = aClass.getFields()[1]; pane.select(lastField, containingFile.getVirtualFile(), true); PlatformTestUtil.waitWhileBusy(pane.getTree()); PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + " -PsiDirectory: showClassMembers\n" + " -PsiDirectory: src\n" + " -PsiDirectory: com\n" + " -PsiDirectory: package1\n" + " -Class1\n" + " +InnerClass\n" + " getValue():int\n" + " myField1:boolean\n" + " [myField2:boolean]\n" + " +Class2\n" + getRootFiles() + " +External Libraries\n", true); CommandProcessor.getInstance().executeCommand(myProject, () -> ApplicationManager.getApplication().runWriteAction(() -> { try { assertEquals("myField2", lastField.getName()); lastField.setName("_firstField"); } catch (IncorrectOperationException e) { fail(e.getMessage()); } }), null, null); PlatformTestUtil.waitForAlarm(600); if (tree.getModel() instanceof AsyncTreeModel) { // TODO:SAM new model loses selection of moved node for now tree.setSelectionPath(PlatformTestUtil.waitForPromise(pane.promisePathToElement(lastField))); } PlatformTestUtil.assertTreeEqual(pane.getTree(), "-Project\n" + " -PsiDirectory: showClassMembers\n" + " -PsiDirectory: src\n" + " -PsiDirectory: com\n" + " -PsiDirectory: package1\n" + " -Class1\n" + " +InnerClass\n" + " getValue():int\n" + " [_firstField:boolean]\n" + " myField1:boolean\n" + " +Class2\n" + getRootFiles() + " +External Libraries\n", true); } public void testAnnoyingScrolling() { getProjectTreeStructure().setProviders(new ClassesTreeStructureProvider(myProject)); final AbstractProjectViewPSIPane pane = myStructure.createPane(); final JTree tree = pane.getTree(); AbstractTreeBuilder builder = pane.getTreeBuilder(); if (builder != null) builder.setPassthroughMode(false); myStructure.setShowMembers(true); PsiJavaFile classFile = (PsiJavaFile)getContentDirectory().findSubdirectory("src").findSubdirectory("com").findSubdirectory("package1").findFile("Class1.java"); PsiClass aClass = classFile.getClasses()[0]; PsiFile containingFile = aClass.getContainingFile(); PsiDirectory directory = containingFile.getContainingDirectory(); pane.select(aClass, containingFile.getVirtualFile(), true); Point viewPosition = ((JViewport)tree.getParent()).getViewPosition(); for (int i=0;i<100;i++) { JavaDirectoryService.getInstance().createClass(directory, "A" + i); } PlatformTestUtil.waitForAlarm(600); Point viewPositionAfter = ((JViewport)tree.getParent()).getViewPosition(); assertEquals(viewPosition, viewPositionAfter); } class NodeWrapper extends AbstractTreeNode<Object> { String myName; List<NodeWrapper> myChildren = new ArrayList<>(); public NodeWrapper(final Project project, final String value) { super(project, new Object()); myName = value; } @Override @NotNull public Collection<? extends AbstractTreeNode> getChildren() { return myChildren; } @Override protected void update(final PresentationData presentation) { presentation.setPresentableText(myName); } public void addChild(final NodeWrapper nodeWrapper) { myChildren.add(nodeWrapper); } public void setName(final String s) { myName = s; } } public void testUpdatingAfterRename() { final NodeWrapper rootWrapper = new NodeWrapper(myProject, "1"); final NodeWrapper wr11 = new NodeWrapper(myProject, "1.1"); final NodeWrapper wr12 = new NodeWrapper(myProject, "1.2"); final NodeWrapper wr13 = new NodeWrapper(myProject, "1.3"); final NodeWrapper wr111 = new NodeWrapper(myProject, "1.1.1"); final NodeWrapper wr112 = new NodeWrapper(myProject, "1.1.2"); final NodeWrapper wr113 = new NodeWrapper(myProject, "1.1.3"); final NodeWrapper wr121 = new NodeWrapper(myProject, "1.2.1"); final NodeWrapper wr122 = new NodeWrapper(myProject, "1.2.2"); final NodeWrapper wr123 = new NodeWrapper(myProject, "1.2.3"); final NodeWrapper wr131 = new NodeWrapper(myProject, "1.3.1"); final NodeWrapper wr132 = new NodeWrapper(myProject, "1.3.2"); final NodeWrapper wr133 = new NodeWrapper(myProject, "1.3.3"); rootWrapper.addChild(wr11); rootWrapper.addChild(wr12); rootWrapper.addChild(wr13); wr11.addChild(wr111); wr11.addChild(wr112); wr11.addChild(wr113); wr12.addChild(wr121); wr12.addChild(wr122); wr12.addChild(wr123); wr13.addChild(wr131); wr13.addChild(wr132); wr13.addChild(wr133); getProjectTreeStructure().setProviders(createWrapProvider(rootWrapper)); final AbstractProjectViewPSIPane pane = myStructure.createPane(); final JTree tree = pane.getTree(); pane.installComparator((o1, o2) -> { if (o1 instanceof NodeWrapper && o2 instanceof NodeWrapper) { return ((NodeWrapper)o1).getName().compareTo(((NodeWrapper)o2).getName()); } else { return 0; } }); PlatformTestUtil.expand(tree, 0, 2); TreeUtil.selectPath(tree, tree.getPathForRow(4)); PlatformTestUtil.assertTreeEqual(tree, "-Project\n" + " -1\n" + " +1.1\n" + " -1.2\n" + " 1.2.1\n" + " [1.2.2]\n" + " 1.2.3\n" + " +1.3\n", true); wr12.setName("01.2"); wr122.setName("01.2.2"); AbstractTreeBuilder builder = pane.getTreeBuilder(); if (builder == null) { // TODO:SAM new model loses selection of moved node for now TreeVisitor visitor = new TreeVisitor.ByTreePath<>(tree.getSelectionPath(), o -> o); PlatformTestUtil.waitForCallback(pane.updateFromRoot(false)); tree.setSelectionPath(PlatformTestUtil.waitForPromise(TreeUtil.promiseMakeVisible(tree, visitor))); } else { builder.updateFromRoot(); } PlatformTestUtil.assertTreeEqual(tree, "-Project\n" + " -1\n" + " -01.2\n" + " [01.2.2]\n" + " 1.2.1\n" + " 1.2.3\n" + " +1.1\n" + " +1.3\n", true); } private TreeStructureProvider createWrapProvider(final NodeWrapper rootWrapper) { return new TreeStructureProvider() { @NotNull @Override public Collection<AbstractTreeNode> modify(@NotNull AbstractTreeNode parent, @NotNull Collection<AbstractTreeNode> children, ViewSettings settings) { if (parent instanceof NodeWrapper) { return children; } List<AbstractTreeNode> result = new ArrayList<>(); result.add(rootWrapper); return result; } }; } public void testHideEmptyMiddlePackages() { myStructure.setProviders(new ClassesTreeStructureProvider(myProject)); myStructure.setHideEmptyMiddlePackages(true); myStructure.setShowMembers(true); myStructure.setShowLibraryContents(false); PsiDirectory directory = getPackageDirectory("com/company"); AbstractProjectViewPSIPane pane = myStructure.createPane(); JTree tree = pane.getTree(); assertTreeEqual(tree, " +PsiDirectory: hideEmptyMiddlePackages\n"); TreeUtil.promiseExpandAll(tree); assertTreeEqual(tree, " -PsiDirectory: hideEmptyMiddlePackages\n" + " -PsiDirectory: src\n" + " -PsiDirectory: name\n" + // com.company.name " -I\n" + " m():void\n"); directory = createSubdirectory(directory, "a"); // PSI listener is notified synchronously and starts modifying new tree model // unfortunately this approach does not work for old tree builders AbstractTreeBuilder builder = pane.getTreeBuilder(); if (builder != null) builder.queueUpdateFrom(directory, true); PlatformTestUtil.waitWhileBusy(tree); TreeUtil.promiseExpandAll(tree); assertTreeEqual(tree, " -PsiDirectory: hideEmptyMiddlePackages\n" + " -PsiDirectory: src\n" + " -PsiDirectory: company\n" + // com.company " PsiDirectory: a\n" + " -PsiDirectory: name\n" + " -I\n" + " m():void\n"); directory = createSubdirectory(directory, "b"); if (builder != null) builder.queueUpdateFrom(directory, true); assertTreeEqual(tree, " -PsiDirectory: hideEmptyMiddlePackages\n" + " -PsiDirectory: src\n" + " -PsiDirectory: company\n" + // com.company " PsiDirectory: b\n" + // a.b " -PsiDirectory: name\n" + " -I\n" + " m():void\n"); directory = createSubdirectory(directory, "z"); if (builder != null) builder.queueUpdateFrom(directory, true); assertTreeEqual(tree, " -PsiDirectory: hideEmptyMiddlePackages\n" + " -PsiDirectory: src\n" + " -PsiDirectory: company\n" + // com.company " PsiDirectory: z\n" + // a.b.z " -PsiDirectory: name\n" + " -I\n" + " m():void\n"); } private void assertTreeEqual(@NotNull JTree tree, @NotNull String expected) { PlatformTestUtil.waitWhileBusy(tree); PlatformTestUtil.assertTreeEqual(tree, "-Project\n" + expected + getRootFiles()); } private static PsiDirectory createSubdirectory(@NotNull PsiDirectory directory, @NotNull String name) { return compute(directory.getProject(), () -> directory.createSubdirectory(name)); } private static <T> T compute(@NotNull Project project, @NotNull Computable<T> computable) { return WriteCommandAction.runWriteCommandAction(project, computable); } }
barboras7/drools
drools-core/src/main/java/org/drools/core/command/SetVariableCommandFromLastReturn.java
<reponame>barboras7/drools /* * Copyright 2010 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.core.command; import org.drools.core.command.impl.ExecutableCommand; import org.drools.core.command.impl.RegistryContext; import org.drools.core.common.InternalFactHandle; import org.kie.api.runtime.rule.FactHandle; import org.kie.api.runtime.Context; import org.kie.api.runtime.builder.Scope; import java.util.HashMap; import java.util.Map; public class SetVariableCommandFromLastReturn implements ExecutableCommand<Object> { private String identifier; private String contextName; private Scope scope = Scope.REQUEST; public SetVariableCommandFromLastReturn(String identifier) { this.identifier = identifier; } public SetVariableCommandFromLastReturn(String contextName, String identifier) { this.identifier = identifier; this.contextName = contextName; } public SetVariableCommandFromLastReturn(String contextName, String identifier, Scope scope) { this.identifier = identifier; this.contextName = contextName; this.scope = scope; } public Object execute(Context context) { Context targetCtx; if ( this.contextName == null ) { targetCtx = context; } else { targetCtx = ( (RegistryContext) context ).getContextManager().getContext( this.contextName ); } GetDefaultValue sim = (GetDefaultValue) context.get( "simulator" ); Object o = sim.getObject(); // for FactHandle's we store the handle on a map and the actual object as if ( o instanceof FactHandle ) { Map<String, FactHandle> handles = (Map<String, FactHandle>) targetCtx.get( "h" ); if ( handles == null ) { handles = new HashMap<String, FactHandle>(); targetCtx.set( "h", handles ); } handles.put( identifier, (FactHandle) o ); o = ((InternalFactHandle) o).getObject(); } targetCtx.set( identifier, o ); return o; } }
xinbaojian/demo-template
manage-websocket/src/main/java/com/qitech/websocket/controller/WebSocketController.java
package com.qitech.websocket.controller; import com.qitech.constant.UrlConstants; import com.qitech.websocket.endpoint.PublishService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @author xin.bj * @program security-parent * @description WebSocket Controller 接口 * @create 2019-04-11 16:36 **/ @Api(value = UrlConstants.ROOT_URL + "/socket", tags = "WebSocket接口管理") @Slf4j @RestController @RequestMapping(UrlConstants.ROOT_URL + "/socket") public class WebSocketController { @ApiOperation(value = "群发Socket消息") @GetMapping("/send") public ResponseEntity sendMsg(@ApiParam(name = "channel", value = "频道", required = true) @RequestParam(name = "channel") String channel, @ApiParam(name = "msg", value = "消息", required = true) @RequestParam(name = "msg") String msg) { PublishService ps = new PublishService(); ps.publish(channel, msg); return new ResponseEntity(HttpStatus.OK); } }
divenswu/proximabilin
src/repository/binlog/table_reader.cc
/** * Copyright 2021 Alibaba, Inc. and its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * \author Hongqing.hu * \date Nov 2020 * \brief Table reader interface implementation for proxima search engine */ #include "table_reader.h" #include "repository_common/error_code.h" #include "repository_common/logger.h" #include "binlog_common.h" #include "sql_builder.h" namespace proxima { namespace be { namespace repository { TableReader::TableReader(const std::string &table_name, InfoFetcherPtr info_fetcher, MysqlConnectorManagerPtr mgr) : MysqlConnectorProxy(std::move(mgr)), table_name_(table_name), info_fetcher_(std::move(info_fetcher)) {} int TableReader::init() { RLOG_INFO("Begin init TableReader."); int ret = init_connector(); if (ret != 0) { LOG_ERROR("Mysql connector proxy init failed."); return ret; } ret = info_fetcher_->get_table_schema(table_name_, &table_schema_); if (ret != 0) { RLOG_ERROR("Info fetcher get table schema failed."); return ret; } RLOG_INFO("Table reader init success."); return 0; } int TableReader::start(const LsnContext &context) { RLOG_INFO("Begin start TableReader. seq_id[%zu]", (size_t)context.seq_id); int ret = prepare_reader(context.seq_id); if (ret != 0) { RLOG_ERROR("Prepare table reader failed."); return ret; } sequence_id_ = context.seq_id; RLOG_INFO("End start TableReader success."); return 0; } int TableReader::get_next_row_data(WriteRequest::Row *row_data, LsnContext *context) { if (need_reconnect_) { if (connector_->reconnect() && prepare_reader(sequence_id_) == 0) { need_reconnect_ = false; } else { return ErrorCode_ConnectMysql; } } MysqlRow *row = result_wrappeer_->next(); if (!row) { if (!result_wrappeer_->has_error()) { context->status = RowDataStatus::NO_MORE_DATA; return 0; } else { need_reconnect_ = true; return ErrorCode_FetchMysqlResult; } } build_row_data(row, row_data, context); context->status = RowDataStatus::NORMAL; sequence_id_ = context->seq_id; // Debug RLOG_INFO("primary_key: %zu", (size_t)row_data->primary_key()); return 0; } int TableReader::build_row_data(MysqlRow *row, WriteRequest::Row *row_data, LsnContext *context) { // set operation type row_data->set_operation_type(proto::OP_INSERT); const std::vector<FieldPtr> &fields = table_schema_->selected_fields(); uint32_t max_index_id = table_schema_->max_index_id(); unsigned int fields_num = result_wrappeer_->fields_num(); for (unsigned int i = 1; i < fields_num; ++i) { GenericValue *forward_value = nullptr; if (i - 1 >= max_index_id && fields[i - 1]->is_forward()) { forward_value = row_data->mutable_forward_column_values()->add_values(); fields[i - 1]->unpack_text(row->field_value(i), row->field_length(i), forward_value); } if (i - 1 < max_index_id && fields[i - 1]->is_index()) { GenericValue *index_value = row_data->mutable_index_column_values()->add_values(); fields[i - 1]->unpack_text(row->field_value(i), row->field_length(i), index_value); } } // process primary key GenericValue value; const FieldPtr &auto_increment_field = table_schema_->auto_increment_field(); auto_increment_field->unpack_text(row->field_value(0), row->field_length(0), &value); uint64_t auto_increment_id = get_auto_increment_id(value); if (auto_increment_id == INVALID_PRIMARY_KEY) { RLOG_ERROR("Get auto increment id failed."); return ErrorCode_RuntimeError; } row_data->set_primary_key(auto_increment_id); // process auto increment field context->seq_id = auto_increment_id; return 0; } int TableReader::prepare_reader(uint64_t seq_id) { // Get select fields std::vector<std::string> selected_fields; const std::vector<FieldPtr> &fields = table_schema_->selected_fields(); for (auto it = fields.begin(); it != fields.end(); ++it) { selected_fields.emplace_back((*it)->select_field()); } // Build scan table sql const std::string &auto_inc_field = table_schema_->auto_increment_field()->field_name(); const std::string &db = info_fetcher_->database(); std::string select_sql = SqlBuilder::BuildScanTableSql( db, table_name_, auto_inc_field, selected_fields, seq_id); // Execute select sql int ret = connector_->execute_query(select_sql, &result_wrappeer_, false); if (ret != 0) { RLOG_ERROR("Connector execute query failed. sql[%s]", select_sql.c_str()); return ret; } return 0; } uint64_t TableReader::get_auto_increment_id(const GenericValue &value) { switch (value.value_oneof_case()) { case GenericValue::kInt32Value: return (uint64_t)value.int32_value(); case GenericValue::kInt64Value: return (uint64_t)value.int64_value(); case GenericValue::kUint32Value: return (uint64_t)value.uint32_value(); case GenericValue::kUint64Value: return (uint64_t)value.uint64_value(); default: RLOG_ERROR("Unsupported auto_increment data type %d.", value.value_oneof_case()); return INVALID_PRIMARY_KEY; } } } // end namespace repository } // namespace be } // end namespace proxima
wwkenwong/piecewise
src/glibc-2.23/sysdeps/unix/bsd/bsd4.4/kfreebsd/setrlimit64.c
/* 'setrlimit64' is the same as 'setrlimit', because __rlim64_t == __rlim_t. */
fjpavm/ChilliSource
Projects/Tools/PNGAlphaPremultiplier/src/com/chilliworks/chillisource/pngalphapremultiplier/PngPremultiplier.java
<reponame>fjpavm/ChilliSource /** * PngPremultiplier.java * Chilli Source * Created by <NAME> on 30/01/2013. * * The MIT License (MIT) * * Copyright (c) 2013 Tag Games Limited * * 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. */ package com.chilliworks.chillisource.pngalphapremultiplier; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.security.CodeSource; import java.util.LinkedList; import com.chilliworks.chillisource.coreutils.Logging; import com.chilliworks.chillisource.coreutils.StringUtils; public class PngPremultiplier { //------------------------------------------------- /// Premultiply /// /// This uses the native tool to pre-multiply the /// pngs and keeps caches the png if requested. /// /// @param the pre-multiplication options. //------------------------------------------------- public static void Premultiply(PremultiplicationOptions insOptions) { try { String strInput = StringUtils.standardiseFilePath(insOptions.strInputFilename); String strOutput = StringUtils.standardiseFilePath(insOptions.strOutputFilename); //build the command list LinkedList<String> astrCommands = new LinkedList<String>(); astrCommands.add(GetExecutableName()); astrCommands.add("--input"); astrCommands.add(strInput); astrCommands.add("--output"); astrCommands.add(strOutput); //add the logging level to the command list switch (Logging.getLoggingLevel()) { case NONE: astrCommands.add("--logginglevel"); astrCommands.add("none"); break; case FATAL: astrCommands.add("--logginglevel"); astrCommands.add("fatal"); break; case ERROR: astrCommands.add("--logginglevel"); astrCommands.add("error"); break; case WARNING: astrCommands.add("--logginglevel"); astrCommands.add("warning"); break; case VERBOSE: astrCommands.add("--logginglevel"); astrCommands.add("warning"); break; } Logging.logVerbose("Premultiplying " + strInput); //run the application final Process process = new ProcessBuilder(astrCommands).start(); //create runnables for polling the error streams. Runnable errorRunnable = new Runnable() { @Override public void run() { ReadErrorStream(process); } }; //start these runnables. Thread errorThread = new Thread(errorRunnable); errorThread.start(); //wait for the threads to finish errorThread.join(); //end the process process.destroy(); } catch (Exception e) { Logging.logFatal("Exception occurred in Premultiply(): \n" + StringUtils.convertExceptionToString(e)); } } /** * Get the directory path that contains this jar file * * @author <NAME> * * @return Directory path to jar folder */ private static String getJarDirectoryPath() { String jarDir = ""; CodeSource codeSource = PngPremultiplier.class.getProtectionDomain().getCodeSource(); File jarFile; try { jarFile = new File(codeSource.getLocation().toURI().getPath()); jarDir = jarFile.getParentFile().getPath() + File.separator; } catch (URISyntaxException e) { e.printStackTrace(); } return jarDir; } //------------------------------------------------------ /// GetExecutableName /// /// @return returns the name of the executable that /// should be used for this platform. //------------------------------------------------------ private static String GetExecutableName() { String strExecutableName = ""; try { //get the path to the jar String strPathToHere = getJarDirectoryPath(); //get which version of the executable should be used. String strOS = System.getProperty("os.name"); if (strOS.startsWith("Windows") == true) strExecutableName = strPathToHere + "PNGAlphaPremultiplier\\PNGAlphaPremultiplierWindows.exe"; else if (strOS.startsWith("Mac") == true) strExecutableName = strPathToHere + "PNGAlphaPremultiplier/PNGAlphaPremultiplierOSX"; else if (strOS.startsWith("Linux") == true) strExecutableName = strPathToHere + "PNGAlphaPremultiplier/PNGAlphaPremultiplierLinux"; else Logging.logFatal("This platform is not supported!"); } catch (Exception e) { Logging.logFatal("Exception occurred in GetExecutableName(): \n" + StringUtils.convertExceptionToString(e)); } return strExecutableName; } //------------------------------------------------------ /// Read Error Stream /// /// reads and outputs the processes error stream. /// /// @param the process that owns the error stream. //------------------------------------------------------ private static void ReadErrorStream(Process inProcess) { try { InputStream errorStream = inProcess.getErrorStream(); InputStreamReader errorStreamReader = new InputStreamReader(errorStream); BufferedReader bufferedErrorReader = new BufferedReader(errorStreamReader); String errorLine = null; do { errorLine = bufferedErrorReader.readLine(); if (errorLine != null) { if (errorLine.startsWith("WARNING:") == true) { Logging.logWarning(errorLine.substring(8)); } else if (errorLine.startsWith("ERROR:") == true) { Logging.logError(errorLine.substring(6)); } else if (errorLine.startsWith("FATAL:") == true) { Logging.logFatal(errorLine.substring(6)); } } } while (errorLine != null); } catch (Exception e) { Logging.logFatal("Something has gone wrong while reading the error stream!\n" + StringUtils.convertExceptionToString(e)); } } }
cheshire137/hue-steamer
app.js
<filename>app.js var hue = require('node-hue-api'), // Converter = require('./converter'), HueApi = hue.HueApi, lightState = hue.lightState, bridgeIP, username; var argCount = process.argv.length; for (var i = 0; i < argCount; i++) { var arg = process.argv[i]; if (arg === '-b' && i + 1 < argCount) { bridgeIP = process.argv[i + 1]; } else if (arg === '-u' && i + 1 < argCount) { username = process.argv[i + 1]; } } if (typeof bridgeIP === 'undefined') { console.error('Provide a Hue bridge IP address with -b flag.'); console.log('Example: node app.js -b 192.168.1.100'); process.exit(1); } if (typeof username === 'undefined') { console.error('Provide a Hue bridge user with -u flag.'); console.log('Example: node app.js -u 123abc'); process.exit(1); } console.log('Connecting to bridge ' + bridgeIP + ' as user ' + username); var api = new HueApi(bridgeIP, username); var displayError = function(err) { console.error(err); }; var displayLight = function(light) { var state = light.state; console.log("\t" + light.name + ' model ' + light.modelid); if (state.on) { var x = state.xy[0]; var y = state.xy[1]; console.log("\tx: " + x + ', y: ' + y + ', brightness: ' + state.bri); var rgb = Converter.CIE1931ToRGB(x, y, state.bri); console.log("\trgb(" + rgb[0] + ', ' + rgb[1] + ', ' + rgb[2] + ')'); var hex = Converter.CIE1931ToHex(x, y, state.bri); console.log("\t#" + hex); } else { console.log('\toff'); } }; var getLightStatus = function(lightID) { api.lightStatus(lightID). then(function(result) { console.log("\nLight #" + lightID); displayLight(result); }).fail(displayError).done(); }; var displayGroup = function(group) { console.log("\t# lights: " + group.lights.length); for (var i = 0; i < group.lights.length; i++) { getLightStatus(group.lights[i]); } }; var displayBridge = function(bridge) { console.log('Bridge "' + bridge.name + '"'); console.log("\tTime: " + bridge.localtime); console.log("\tAPI version: " + bridge.apiversion); api.getGroup('0').then(displayGroup).done(); }; // api.config().then(displayBridge).done(); var displayBridges = function(bridge) { console.log("Hue Bridges Found: " + JSON.stringify(bridge)); }; hue.upnpSearch(2000).then(displayBridges).done(); // // var redX = 0.6417, redY = 0.304; // // var blueX = 0.168, blueY = 0.041; // // // var state = lightState.create().on().xy(redX, redY); // // var state = lightState.create().on().effect('none'); // // api.setLightState(lightID, state). // // then(displayLightState).fail(displayError).done();
klinker24/Android-SlidingMessaging
src/main/java/com/klinker/android/messaging_donate/floating_notifications/EmojiDialogActivity.java
<reponame>klinker24/Android-SlidingMessaging package com.klinker.android.messaging_donate.floating_notifications; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; import android.view.WindowManager; import android.widget.*; import com.klinker.android.messaging_donate.MainActivity; import com.klinker.android.messaging_donate.R; import com.klinker.android.messaging_donate.utils.ContactUtil; import com.klinker.android.messaging_donate.utils.SendUtil; import com.klinker.android.messaging_sliding.emojis.EmojiAdapter; import com.klinker.android.messaging_sliding.emojis.EmojiAdapter2; import com.klinker.android.messaging_sliding.emojis.EmojiConverter; import com.klinker.android.messaging_sliding.emojis.EmojiConverter2; import com.tonicartos.widget.stickygridheaders.StickyGridHeadersGridView; import robj.floating.notifications.Extension; public class EmojiDialogActivity extends Activity { public EditText editText; public String message; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); final long id = getIntent().getLongExtra("id", -1); final Context context = this; message = getIntent().getStringExtra("message"); setTitle("Insert Emojis"); setContentView(R.layout.emoji_frame); editText = (EditText) findViewById(R.id.emoji_text); ImageButton peopleButton = (ImageButton) findViewById(R.id.peopleButton); ImageButton objectsButton = (ImageButton) findViewById(R.id.objectsButton); ImageButton natureButton = (ImageButton) findViewById(R.id.natureButton); ImageButton placesButton = (ImageButton) findViewById(R.id.placesButton); ImageButton symbolsButton = (ImageButton) findViewById(R.id.symbolsButton); final StickyGridHeadersGridView emojiGrid = (StickyGridHeadersGridView) findViewById(R.id.emojiGrid); Button okButton = (Button) findViewById(R.id.emoji_ok); if (sharedPrefs.getBoolean("emoji_type", true)) { emojiGrid.setAdapter(new EmojiAdapter2(context)); emojiGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { editText.setText(EmojiConverter2.getSmiledText(context, editText.getText().toString() + EmojiAdapter2.mEmojiTexts[position])); editText.setSelection(editText.getText().length()); } }); peopleButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { emojiGrid.setSelection(0); } }); objectsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { emojiGrid.setSelection(153 + (2 * 7)); } }); natureButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { emojiGrid.setSelection(153 + 162 + (3 * 7)); } }); placesButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { emojiGrid.setSelection(153 + 162 + 178 + (5 * 7)); } }); symbolsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { emojiGrid.setSelection(153 + 162 + 178 + 122 + (7 * 7)); } }); } else { emojiGrid.setAdapter(new EmojiAdapter(context)); emojiGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { editText.setText(EmojiConverter.getSmiledText(context, editText.getText().toString() + EmojiAdapter.mEmojiTexts[position])); editText.setSelection(editText.getText().length()); } }); peopleButton.setMaxHeight(0); objectsButton.setMaxHeight(0); natureButton.setMaxHeight(0); placesButton.setMaxHeight(0); symbolsButton.setMaxHeight(0); LinearLayout buttons = (LinearLayout) findViewById(R.id.linearLayout); buttons.setMinimumHeight(0); buttons.setVisibility(View.GONE); } okButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String editTextHint = context.getResources().getString(R.string.reply_to) + " " + ContactUtil.findContactName(FNReceiver.messages.get(id)[0], context); final String previousText = FNReceiver.messages.get(id)[1]; final Bitmap image = ContactUtil.getFacebookPhoto(FNReceiver.messages.get(id)[0], context); final Extension.onClickListener imageOnClick = new Extension.onClickListener() { @Override public void onClick() { Intent intent = new Intent(context, MainActivity.class); intent.putExtra("com.klinker.android.OPEN_THREAD", FNReceiver.messages.get(id)[0]); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); FNReceiver.messages.remove(id); Extension.remove(id, context); finish(); } }; final Extension.onClickListener sendOnClick = new Extension.onClickListener() { @Override public void onClick(String str) { SendUtil.sendMessage(context, FNReceiver.messages.get(id)[0], str); Extension.remove(id, context); FNReceiver.messages.remove(id); finish(); } }; final Bitmap extraButton = BitmapFactory.decodeResource(context.getResources(), R.drawable.emo_im_smirk); Extension.onClickListener extraOnClick = new Extension.onClickListener() { @Override public void onClick(final String str) { Intent emojiDialog = new Intent(context, EmojiDialogActivity.class); emojiDialog.putExtra("id", id); emojiDialog.putExtra("message", str); message = str; emojiDialog.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(emojiDialog); } }; Extension.replyOverlay(editTextHint, previousText, image, imageOnClick, sendOnClick, extraOnClick, true, extraButton, context, false, editText.getText().toString()); Extension.hideAll(id, context); } }); } @Override public void onResume() { super.onResume(); try { editText.setText(message); editText.setSelection(message.length()); } catch (Exception e) { } } }
sky5454/30daysMakeOS-Origin-ISOfiles
30days-Origin-ISOfiles/omake/tolsrc/go_0023s/gcc/insn-flags.h
<gh_stars>10-100 /* Generated automatically by the program `genflags' from the machine description file `md'. */ #ifndef GCC_INSN_FLAGS_H #define GCC_INSN_FLAGS_H #define HAVE_cmpdi_ccno_1_rex64 (TARGET_64BIT && ix86_match_ccmode (insn, CCNOmode)) #define HAVE_cmpdi_1_insn_rex64 (TARGET_64BIT && ix86_match_ccmode (insn, CCmode)) #define HAVE_cmpqi_ext_3_insn (!TARGET_64BIT && ix86_match_ccmode (insn, CCmode)) #define HAVE_cmpqi_ext_3_insn_rex64 (TARGET_64BIT && ix86_match_ccmode (insn, CCmode)) #define HAVE_x86_fnstsw_1 (TARGET_80387) #define HAVE_x86_sahf_1 (!TARGET_64BIT) #define HAVE_popsi1 (!TARGET_64BIT) #define HAVE_movsi_insv_1 (!TARGET_64BIT) #define HAVE_pushdi2_rex64 (TARGET_64BIT) #define HAVE_popdi1 (TARGET_64BIT) #define HAVE_swapxf 1 #define HAVE_swaptf 1 #define HAVE_zero_extendhisi2_and (TARGET_ZERO_EXTEND_WITH_AND && !optimize_size) #define HAVE_zero_extendsidi2_32 (!TARGET_64BIT) #define HAVE_zero_extendsidi2_rex64 (TARGET_64BIT) #define HAVE_zero_extendhidi2 (TARGET_64BIT) #define HAVE_zero_extendqidi2 (TARGET_64BIT) #define HAVE_extendsidi2_rex64 (TARGET_64BIT) #define HAVE_extendhidi2 (TARGET_64BIT) #define HAVE_extendqidi2 (TARGET_64BIT) #define HAVE_extendhisi2 1 #define HAVE_extendqihi2 1 #define HAVE_extendqisi2 1 #define HAVE_truncdfsf2_3 (TARGET_80387) #define HAVE_truncdfsf2_sse_only (!TARGET_80387 && TARGET_SSE2) #define HAVE_fix_truncdi_nomemory (TARGET_80387 && FLOAT_MODE_P (GET_MODE (operands[1])) \ && (!SSE_FLOAT_MODE_P (GET_MODE (operands[1])) || !TARGET_64BIT)) #define HAVE_fix_truncdi_memory (TARGET_80387 && FLOAT_MODE_P (GET_MODE (operands[1])) \ && (!SSE_FLOAT_MODE_P (GET_MODE (operands[1])) || !TARGET_64BIT)) #define HAVE_fix_truncsfdi_sse (TARGET_64BIT && TARGET_SSE) #define HAVE_fix_truncdfdi_sse (TARGET_64BIT && TARGET_SSE2) #define HAVE_fix_truncsi_nomemory (TARGET_80387 && FLOAT_MODE_P (GET_MODE (operands[1])) \ && !SSE_FLOAT_MODE_P (GET_MODE (operands[1]))) #define HAVE_fix_truncsi_memory (TARGET_80387 && FLOAT_MODE_P (GET_MODE (operands[1])) \ && !SSE_FLOAT_MODE_P (GET_MODE (operands[1]))) #define HAVE_fix_truncsfsi_sse (TARGET_SSE) #define HAVE_fix_truncdfsi_sse (TARGET_SSE2) #define HAVE_fix_trunchi_nomemory (TARGET_80387 && FLOAT_MODE_P (GET_MODE (operands[1])) \ && !SSE_FLOAT_MODE_P (GET_MODE (operands[1]))) #define HAVE_fix_trunchi_memory (TARGET_80387 && FLOAT_MODE_P (GET_MODE (operands[1])) \ && !SSE_FLOAT_MODE_P (GET_MODE (operands[1]))) #define HAVE_x86_fnstcw_1 (TARGET_80387) #define HAVE_x86_fldcw_1 (TARGET_80387) #define HAVE_floathisf2 (TARGET_80387 && !TARGET_SSE) #define HAVE_floathidf2 (TARGET_80387 && !TARGET_SSE2) #define HAVE_floathixf2 (!TARGET_64BIT && TARGET_80387) #define HAVE_floathitf2 (TARGET_80387) #define HAVE_floatsixf2 (!TARGET_64BIT && TARGET_80387) #define HAVE_floatsitf2 (TARGET_80387) #define HAVE_floatdixf2 (!TARGET_64BIT && TARGET_80387) #define HAVE_floatditf2 (TARGET_80387) #define HAVE_addqi3_cc (ix86_binary_operator_ok (PLUS, QImode, operands)) #define HAVE_addsi_1_zext (TARGET_64BIT && ix86_binary_operator_ok (PLUS, SImode, operands)) #define HAVE_addqi_ext_1 (!TARGET_64BIT) #define HAVE_subdi3_carry_rex64 (TARGET_64BIT && ix86_binary_operator_ok (MINUS, DImode, operands)) #define HAVE_subsi3_carry (ix86_binary_operator_ok (MINUS, SImode, operands)) #define HAVE_subsi3_carry_zext (TARGET_64BIT && ix86_binary_operator_ok (MINUS, SImode, operands)) #define HAVE_divqi3 (TARGET_QIMODE_MATH) #define HAVE_udivqi3 (TARGET_QIMODE_MATH) #define HAVE_divmodhi4 (TARGET_HIMODE_MATH) #define HAVE_udivmoddi4 (TARGET_64BIT) #define HAVE_udivmodsi4 1 #define HAVE_testsi_1 (ix86_match_ccmode (insn, CCNOmode)) #define HAVE_andqi_ext_0 ((unsigned HOST_WIDE_INT)INTVAL (operands[2]) <= 0xff) #define HAVE_negsf2_memory (ix86_unary_operator_ok (NEG, SFmode, operands)) #define HAVE_negsf2_ifs (TARGET_SSE \ && (reload_in_progress || reload_completed \ || (register_operand (operands[0], VOIDmode) \ && register_operand (operands[1], VOIDmode)))) #define HAVE_negdf2_memory (ix86_unary_operator_ok (NEG, DFmode, operands)) #define HAVE_negdf2_ifs (!TARGET_64BIT && TARGET_SSE2 \ && (reload_in_progress || reload_completed \ || (register_operand (operands[0], VOIDmode) \ && register_operand (operands[1], VOIDmode)))) #define HAVE_abssf2_memory (ix86_unary_operator_ok (ABS, SFmode, operands)) #define HAVE_abssf2_ifs (TARGET_SSE \ && (reload_in_progress || reload_completed \ || (register_operand (operands[0], VOIDmode) \ && register_operand (operands[1], VOIDmode)))) #define HAVE_absdf2_memory (ix86_unary_operator_ok (ABS, DFmode, operands)) #define HAVE_absdf2_ifs (!TARGET_64BIT && TARGET_SSE2 \ && (reload_in_progress || reload_completed \ || (register_operand (operands[0], VOIDmode) \ && register_operand (operands[1], VOIDmode)))) #define HAVE_ashldi3_1 (!TARGET_64BIT && TARGET_CMOVE) #define HAVE_x86_shld_1 1 #define HAVE_ashrdi3_63_rex64 (TARGET_64BIT && INTVAL (operands[2]) == 63 && (TARGET_USE_CLTD || optimize_size) \ && ix86_binary_operator_ok (ASHIFTRT, DImode, operands)) #define HAVE_ashrdi3_1 (!TARGET_64BIT && TARGET_CMOVE) #define HAVE_x86_shrd_1 1 #define HAVE_ashrsi3_31 (INTVAL (operands[2]) == 31 && (TARGET_USE_CLTD || optimize_size) \ && ix86_binary_operator_ok (ASHIFTRT, SImode, operands)) #define HAVE_lshrdi3_1 (!TARGET_64BIT && TARGET_CMOVE) #define HAVE_setcc_2 1 #define HAVE_jump 1 #define HAVE_doloop_end_internal (!TARGET_64BIT && TARGET_USE_LOOP) #define HAVE_blockage 1 #define HAVE_return_internal (reload_completed) #define HAVE_return_pop_internal (reload_completed) #define HAVE_return_indirect_internal (reload_completed) #define HAVE_nop 1 #define HAVE_prologue_set_got (!TARGET_64BIT) #define HAVE_prologue_get_pc (!TARGET_64BIT) #define HAVE_eh_return_si (!TARGET_64BIT) #define HAVE_eh_return_di (TARGET_64BIT) #define HAVE_leave (!TARGET_64BIT) #define HAVE_leave_rex64 (TARGET_64BIT) #define HAVE_ffssi_1 1 #define HAVE_sqrtsf2_1 (! TARGET_NO_FANCY_MATH_387 && TARGET_80387 \ && (TARGET_SSE_MATH && TARGET_MIX_SSE_I387)) #define HAVE_sqrtsf2_1_sse_only (TARGET_SSE_MATH && (!TARGET_80387 || !TARGET_MIX_SSE_I387)) #define HAVE_sqrtsf2_i387 (! TARGET_NO_FANCY_MATH_387 && TARGET_80387 \ && !TARGET_SSE_MATH) #define HAVE_sqrtdf2_1 (! TARGET_NO_FANCY_MATH_387 && TARGET_80387 \ && (TARGET_SSE2 && TARGET_SSE_MATH && TARGET_MIX_SSE_I387)) #define HAVE_sqrtdf2_1_sse_only (TARGET_SSE2 && TARGET_SSE_MATH && (!TARGET_80387 || !TARGET_MIX_SSE_I387)) #define HAVE_sqrtdf2_i387 (! TARGET_NO_FANCY_MATH_387 && TARGET_80387 \ && (!TARGET_SSE2 || !TARGET_SSE_MATH)) #define HAVE_sqrtxf2 (!TARGET_64BIT && TARGET_80387 && !TARGET_NO_FANCY_MATH_387 \ && (TARGET_IEEE_FP || flag_unsafe_math_optimizations) ) #define HAVE_sqrttf2 (! TARGET_NO_FANCY_MATH_387 && TARGET_80387 \ && (TARGET_IEEE_FP || flag_unsafe_math_optimizations) ) #define HAVE_sindf2 (! TARGET_NO_FANCY_MATH_387 && TARGET_80387 \ && flag_unsafe_math_optimizations) #define HAVE_sinsf2 (! TARGET_NO_FANCY_MATH_387 && TARGET_80387 \ && flag_unsafe_math_optimizations) #define HAVE_sinxf2 (!TARGET_64BIT && TARGET_80387 && !TARGET_NO_FANCY_MATH_387 \ && flag_unsafe_math_optimizations) #define HAVE_sintf2 (! TARGET_NO_FANCY_MATH_387 && TARGET_80387 \ && flag_unsafe_math_optimizations) #define HAVE_cosdf2 (! TARGET_NO_FANCY_MATH_387 && TARGET_80387 \ && flag_unsafe_math_optimizations) #define HAVE_cossf2 (! TARGET_NO_FANCY_MATH_387 && TARGET_80387 \ && flag_unsafe_math_optimizations) #define HAVE_cosxf2 (! TARGET_NO_FANCY_MATH_387 && TARGET_80387 \ && flag_unsafe_math_optimizations) #define HAVE_costf2 (! TARGET_NO_FANCY_MATH_387 && TARGET_80387 \ && flag_unsafe_math_optimizations) #define HAVE_cld 1 #define HAVE_strmovdi_rex_1 (TARGET_64BIT && (TARGET_SINGLE_STRINGOP || optimize_size)) #define HAVE_strmovsi_1 (!TARGET_64BIT && (TARGET_SINGLE_STRINGOP || optimize_size)) #define HAVE_strmovsi_rex_1 (TARGET_64BIT && (TARGET_SINGLE_STRINGOP || optimize_size)) #define HAVE_strmovhi_1 (!TARGET_64BIT && (TARGET_SINGLE_STRINGOP || optimize_size)) #define HAVE_strmovhi_rex_1 (TARGET_64BIT && (TARGET_SINGLE_STRINGOP || optimize_size)) #define HAVE_strmovqi_1 (!TARGET_64BIT && (TARGET_SINGLE_STRINGOP || optimize_size)) #define HAVE_strmovqi_rex_1 (TARGET_64BIT && (TARGET_SINGLE_STRINGOP || optimize_size)) #define HAVE_rep_movdi_rex64 (TARGET_64BIT) #define HAVE_rep_movsi (!TARGET_64BIT) #define HAVE_rep_movsi_rex64 (TARGET_64BIT) #define HAVE_rep_movqi (!TARGET_64BIT) #define HAVE_rep_movqi_rex64 (TARGET_64BIT) #define HAVE_strsetdi_rex_1 (TARGET_64BIT && (TARGET_SINGLE_STRINGOP || optimize_size)) #define HAVE_strsetsi_1 (!TARGET_64BIT && (TARGET_SINGLE_STRINGOP || optimize_size)) #define HAVE_strsetsi_rex_1 (TARGET_64BIT && (TARGET_SINGLE_STRINGOP || optimize_size)) #define HAVE_strsethi_1 (!TARGET_64BIT && (TARGET_SINGLE_STRINGOP || optimize_size)) #define HAVE_strsethi_rex_1 (TARGET_64BIT && (TARGET_SINGLE_STRINGOP || optimize_size)) #define HAVE_strsetqi_1 (!TARGET_64BIT && (TARGET_SINGLE_STRINGOP || optimize_size)) #define HAVE_strsetqi_rex_1 (TARGET_64BIT && (TARGET_SINGLE_STRINGOP || optimize_size)) #define HAVE_rep_stosdi_rex64 (TARGET_64BIT) #define HAVE_rep_stossi (!TARGET_64BIT) #define HAVE_rep_stossi_rex64 (TARGET_64BIT) #define HAVE_rep_stosqi (!TARGET_64BIT) #define HAVE_rep_stosqi_rex64 (TARGET_64BIT) #define HAVE_cmpstrqi_nz_1 (!TARGET_64BIT) #define HAVE_cmpstrqi_nz_rex_1 (TARGET_64BIT) #define HAVE_cmpstrqi_1 (!TARGET_64BIT) #define HAVE_cmpstrqi_rex_1 (TARGET_64BIT) #define HAVE_strlenqi_1 (!TARGET_64BIT) #define HAVE_strlenqi_rex_1 (TARGET_64BIT) #define HAVE_x86_movdicc_0_m1_rex64 (TARGET_64BIT) #define HAVE_x86_movsicc_0_m1 1 #define HAVE_pro_epilogue_adjust_stack_rex64 (TARGET_64BIT) #define HAVE_sse_movsfcc (TARGET_SSE \ && (GET_CODE (operands[2]) != MEM || GET_CODE (operands[3]) != MEM) \ && (!TARGET_IEEE_FP \ || (GET_CODE (operands[1]) != EQ && GET_CODE (operands[1]) != NE))) #define HAVE_sse_movsfcc_eq (TARGET_SSE \ && (GET_CODE (operands[2]) != MEM || GET_CODE (operands[3]) != MEM)) #define HAVE_sse_movdfcc (TARGET_SSE2 \ && (GET_CODE (operands[2]) != MEM || GET_CODE (operands[3]) != MEM) \ && (!TARGET_IEEE_FP \ || (GET_CODE (operands[1]) != EQ && GET_CODE (operands[1]) != NE))) #define HAVE_sse_movdfcc_eq (TARGET_SSE \ && (GET_CODE (operands[2]) != MEM || GET_CODE (operands[3]) != MEM)) #define HAVE_allocate_stack_worker_1 (!TARGET_64BIT && TARGET_STACK_PROBE) #define HAVE_allocate_stack_worker_rex64 (TARGET_64BIT && TARGET_STACK_PROBE) #define HAVE_trap 1 #define HAVE_movv4sf_internal (TARGET_SSE) #define HAVE_movv4si_internal (TARGET_SSE) #define HAVE_movv8qi_internal (TARGET_MMX) #define HAVE_movv4hi_internal (TARGET_MMX) #define HAVE_movv2si_internal (TARGET_MMX) #define HAVE_movv2sf_internal (TARGET_3DNOW) #define HAVE_movti_internal (TARGET_SSE && !TARGET_64BIT) #define HAVE_sse_movaps (TARGET_SSE) #define HAVE_sse_movups (TARGET_SSE) #define HAVE_sse_movmskps (TARGET_SSE) #define HAVE_mmx_pmovmskb (TARGET_SSE || TARGET_3DNOW_A) #define HAVE_mmx_maskmovq ((TARGET_SSE || TARGET_3DNOW_A) && !TARGET_64BIT) #define HAVE_mmx_maskmovq_rex ((TARGET_SSE || TARGET_3DNOW_A) && TARGET_64BIT) #define HAVE_sse_movntv4sf (TARGET_SSE) #define HAVE_sse_movntdi (TARGET_SSE || TARGET_3DNOW_A) #define HAVE_sse_movhlps (TARGET_SSE) #define HAVE_sse_movlhps (TARGET_SSE) #define HAVE_sse_movhps (TARGET_SSE \ && (GET_CODE (operands[1]) == MEM || GET_CODE (operands[2]) == MEM)) #define HAVE_sse_movlps (TARGET_SSE \ && (GET_CODE (operands[1]) == MEM || GET_CODE (operands[2]) == MEM)) #define HAVE_sse_loadss (TARGET_SSE) #define HAVE_sse_movss (TARGET_SSE) #define HAVE_sse_storess (TARGET_SSE) #define HAVE_sse_shufps (TARGET_SSE) #define HAVE_addv4sf3 (TARGET_SSE) #define HAVE_vmaddv4sf3 (TARGET_SSE) #define HAVE_subv4sf3 (TARGET_SSE) #define HAVE_vmsubv4sf3 (TARGET_SSE) #define HAVE_mulv4sf3 (TARGET_SSE) #define HAVE_vmmulv4sf3 (TARGET_SSE) #define HAVE_divv4sf3 (TARGET_SSE) #define HAVE_vmdivv4sf3 (TARGET_SSE) #define HAVE_rcpv4sf2 (TARGET_SSE) #define HAVE_vmrcpv4sf2 (TARGET_SSE) #define HAVE_rsqrtv4sf2 (TARGET_SSE) #define HAVE_vmrsqrtv4sf2 (TARGET_SSE) #define HAVE_sqrtv4sf2 (TARGET_SSE) #define HAVE_vmsqrtv4sf2 (TARGET_SSE) #define HAVE_sse_andti3 (TARGET_SSE && !TARGET_SSE2 \ && (GET_CODE (operands[1]) != MEM || GET_CODE (operands[2]) != MEM)) #define HAVE_sse_nandti3 (TARGET_SSE && !TARGET_SSE2) #define HAVE_sse_iorti3 (TARGET_SSE && !TARGET_SSE2 \ && (GET_CODE (operands[1]) != MEM || GET_CODE (operands[2]) != MEM)) #define HAVE_sse_xorti3 (TARGET_SSE && !TARGET_SSE2 \ && (GET_CODE (operands[1]) != MEM || GET_CODE (operands[2]) != MEM)) #define HAVE_sse_clrv4sf (TARGET_SSE) #define HAVE_maskcmpv4sf3 (TARGET_SSE) #define HAVE_maskncmpv4sf3 (TARGET_SSE) #define HAVE_vmmaskcmpv4sf3 (TARGET_SSE) #define HAVE_vmmaskncmpv4sf3 (TARGET_SSE) #define HAVE_sse_comi (TARGET_SSE) #define HAVE_sse_ucomi (TARGET_SSE) #define HAVE_sse_unpckhps (TARGET_SSE) #define HAVE_sse_unpcklps (TARGET_SSE) #define HAVE_smaxv4sf3 (TARGET_SSE) #define HAVE_vmsmaxv4sf3 (TARGET_SSE) #define HAVE_sminv4sf3 (TARGET_SSE) #define HAVE_vmsminv4sf3 (TARGET_SSE) #define HAVE_cvtpi2ps (TARGET_SSE) #define HAVE_cvtps2pi (TARGET_SSE) #define HAVE_cvttps2pi (TARGET_SSE) #define HAVE_cvtsi2ss (TARGET_SSE) #define HAVE_cvtss2si (TARGET_SSE) #define HAVE_cvttss2si (TARGET_SSE) #define HAVE_addv8qi3 (TARGET_MMX) #define HAVE_addv4hi3 (TARGET_MMX) #define HAVE_addv2si3 (TARGET_MMX) #define HAVE_ssaddv8qi3 (TARGET_MMX) #define HAVE_ssaddv4hi3 (TARGET_MMX) #define HAVE_usaddv8qi3 (TARGET_MMX) #define HAVE_usaddv4hi3 (TARGET_MMX) #define HAVE_subv8qi3 (TARGET_MMX) #define HAVE_subv4hi3 (TARGET_MMX) #define HAVE_subv2si3 (TARGET_MMX) #define HAVE_sssubv8qi3 (TARGET_MMX) #define HAVE_sssubv4hi3 (TARGET_MMX) #define HAVE_ussubv8qi3 (TARGET_MMX) #define HAVE_ussubv4hi3 (TARGET_MMX) #define HAVE_mulv4hi3 (TARGET_MMX) #define HAVE_smulv4hi3_highpart (TARGET_MMX) #define HAVE_umulv4hi3_highpart (TARGET_SSE || TARGET_3DNOW_A) #define HAVE_mmx_pmaddwd (TARGET_MMX) #define HAVE_mmx_iordi3 (TARGET_MMX) #define HAVE_mmx_xordi3 (TARGET_MMX) #define HAVE_mmx_clrdi (TARGET_MMX) #define HAVE_mmx_anddi3 (TARGET_MMX) #define HAVE_mmx_nanddi3 (TARGET_MMX) #define HAVE_mmx_uavgv8qi3 (TARGET_SSE || TARGET_3DNOW_A) #define HAVE_mmx_uavgv4hi3 (TARGET_SSE || TARGET_3DNOW_A) #define HAVE_mmx_psadbw (TARGET_SSE || TARGET_3DNOW_A) #define HAVE_mmx_pinsrw (TARGET_SSE || TARGET_3DNOW_A) #define HAVE_mmx_pextrw (TARGET_SSE || TARGET_3DNOW_A) #define HAVE_mmx_pshufw (TARGET_SSE || TARGET_3DNOW_A) #define HAVE_eqv8qi3 (TARGET_MMX) #define HAVE_eqv4hi3 (TARGET_MMX) #define HAVE_eqv2si3 (TARGET_MMX) #define HAVE_gtv8qi3 (TARGET_MMX) #define HAVE_gtv4hi3 (TARGET_MMX) #define HAVE_gtv2si3 (TARGET_MMX) #define HAVE_umaxv8qi3 (TARGET_SSE || TARGET_3DNOW_A) #define HAVE_smaxv4hi3 (TARGET_SSE || TARGET_3DNOW_A) #define HAVE_uminv8qi3 (TARGET_SSE || TARGET_3DNOW_A) #define HAVE_sminv4hi3 (TARGET_SSE || TARGET_3DNOW_A) #define HAVE_ashrv4hi3 (TARGET_MMX) #define HAVE_ashrv2si3 (TARGET_MMX) #define HAVE_lshrv4hi3 (TARGET_MMX) #define HAVE_lshrv2si3 (TARGET_MMX) #define HAVE_mmx_lshrdi3 (TARGET_MMX) #define HAVE_ashlv4hi3 (TARGET_MMX) #define HAVE_ashlv2si3 (TARGET_MMX) #define HAVE_mmx_ashldi3 (TARGET_MMX) #define HAVE_mmx_packsswb (TARGET_MMX) #define HAVE_mmx_packssdw (TARGET_MMX) #define HAVE_mmx_packuswb (TARGET_MMX) #define HAVE_mmx_punpckhbw (TARGET_MMX) #define HAVE_mmx_punpckhwd (TARGET_MMX) #define HAVE_mmx_punpckhdq (TARGET_MMX) #define HAVE_mmx_punpcklbw (TARGET_MMX) #define HAVE_mmx_punpcklwd (TARGET_MMX) #define HAVE_mmx_punpckldq (TARGET_MMX) #define HAVE_emms (TARGET_MMX) #define HAVE_ldmxcsr (TARGET_MMX) #define HAVE_stmxcsr (TARGET_MMX) #define HAVE_addv2sf3 (TARGET_3DNOW) #define HAVE_subv2sf3 (TARGET_3DNOW) #define HAVE_subrv2sf3 (TARGET_3DNOW) #define HAVE_gtv2sf3 (TARGET_3DNOW) #define HAVE_gev2sf3 (TARGET_3DNOW) #define HAVE_eqv2sf3 (TARGET_3DNOW) #define HAVE_pfmaxv2sf3 (TARGET_3DNOW) #define HAVE_pfminv2sf3 (TARGET_3DNOW) #define HAVE_mulv2sf3 (TARGET_3DNOW) #define HAVE_femms (TARGET_3DNOW) #define HAVE_pf2id (TARGET_3DNOW) #define HAVE_pf2iw (TARGET_3DNOW_A) #define HAVE_pfacc (TARGET_3DNOW) #define HAVE_pfnacc (TARGET_3DNOW_A) #define HAVE_pfpnacc (TARGET_3DNOW_A) #define HAVE_pi2fw (TARGET_3DNOW_A) #define HAVE_floatv2si2 (TARGET_3DNOW) #define HAVE_pavgusb (TARGET_3DNOW) #define HAVE_pfrcpv2sf2 (TARGET_3DNOW) #define HAVE_pfrcpit1v2sf3 (TARGET_3DNOW) #define HAVE_pfrcpit2v2sf3 (TARGET_3DNOW) #define HAVE_pfrsqrtv2sf2 (TARGET_3DNOW) #define HAVE_pfrsqit1v2sf3 (TARGET_3DNOW) #define HAVE_pmulhrwv4hi3 (TARGET_3DNOW) #define HAVE_pswapdv2si2 (TARGET_3DNOW_A) #define HAVE_pswapdv2sf2 (TARGET_3DNOW_A) #define HAVE_cmpdi 1 #define HAVE_cmpsi 1 #define HAVE_cmphi 1 #define HAVE_cmpqi (TARGET_QIMODE_MATH) #define HAVE_cmpdi_1_rex64 (TARGET_64BIT) #define HAVE_cmpsi_1 1 #define HAVE_cmpqi_ext_3 1 #define HAVE_cmpxf (!TARGET_64BIT && TARGET_80387) #define HAVE_cmptf (TARGET_80387) #define HAVE_cmpdf (TARGET_80387 || TARGET_SSE2) #define HAVE_cmpsf (TARGET_80387 || TARGET_SSE) #define HAVE_movsi 1 #define HAVE_movhi 1 #define HAVE_movstricthi (! TARGET_PARTIAL_REG_STALL || optimize_size) #define HAVE_movqi 1 #define HAVE_reload_outqi 1 #define HAVE_movstrictqi (! TARGET_PARTIAL_REG_STALL) #define HAVE_movdi 1 #define HAVE_movsf 1 #define HAVE_movdf 1 #define HAVE_movxf (!TARGET_64BIT) #define HAVE_movtf 1 #define HAVE_zero_extendhisi2 1 #define HAVE_zero_extendqihi2 1 #define HAVE_zero_extendqisi2 1 #define HAVE_zero_extendsidi2 1 #define HAVE_extendsidi2 1 #define HAVE_extendsfdf2 (TARGET_80387 || TARGET_SSE2) #define HAVE_extendsfxf2 (!TARGET_64BIT && TARGET_80387) #define HAVE_extendsftf2 (TARGET_80387) #define HAVE_extenddfxf2 (!TARGET_64BIT && TARGET_80387) #define HAVE_extenddftf2 (TARGET_80387) #define HAVE_truncdfsf2 (TARGET_80387 || TARGET_SSE2) #define HAVE_truncxfsf2 (!TARGET_64BIT && TARGET_80387) #define HAVE_trunctfsf2 (TARGET_80387) #define HAVE_truncxfdf2 (!TARGET_64BIT && TARGET_80387) #define HAVE_trunctfdf2 (TARGET_80387) #define HAVE_fix_truncxfdi2 (!TARGET_64BIT && TARGET_80387) #define HAVE_fix_trunctfdi2 (TARGET_80387) #define HAVE_fix_truncdfdi2 (TARGET_80387 || (TARGET_SSE2 && TARGET_64BIT)) #define HAVE_fix_truncsfdi2 (TARGET_80387 || (TARGET_SSE && TARGET_64BIT)) #define HAVE_fix_truncxfsi2 (!TARGET_64BIT && TARGET_80387) #define HAVE_fix_trunctfsi2 (TARGET_80387) #define HAVE_fix_truncdfsi2 (TARGET_80387 || TARGET_SSE2) #define HAVE_fix_truncsfsi2 (TARGET_80387 || TARGET_SSE) #define HAVE_fix_truncxfhi2 (!TARGET_64BIT && TARGET_80387) #define HAVE_fix_trunctfhi2 (TARGET_80387) #define HAVE_fix_truncdfhi2 (TARGET_80387 && !TARGET_SSE2) #define HAVE_fix_truncsfhi2 (TARGET_80387 && !TARGET_SSE) #define HAVE_floatsisf2 (TARGET_SSE || TARGET_80387) #define HAVE_floatdisf2 ((TARGET_64BIT && TARGET_SSE) || TARGET_80387) #define HAVE_floatsidf2 (TARGET_80387 || TARGET_SSE2) #define HAVE_floatdidf2 ((TARGET_64BIT && TARGET_SSE2) || TARGET_80387) #define HAVE_adddi3 1 #define HAVE_addsi3 1 #define HAVE_addhi3 (TARGET_HIMODE_MATH) #define HAVE_addqi3 (TARGET_QIMODE_MATH) #define HAVE_addxf3 (!TARGET_64BIT && TARGET_80387) #define HAVE_addtf3 (TARGET_80387) #define HAVE_adddf3 (TARGET_80387 || (TARGET_SSE2 && TARGET_SSE_MATH)) #define HAVE_addsf3 (TARGET_80387 || TARGET_SSE_MATH) #define HAVE_subdi3 1 #define HAVE_subsi3 1 #define HAVE_subhi3 (TARGET_HIMODE_MATH) #define HAVE_subqi3 (TARGET_QIMODE_MATH) #define HAVE_subxf3 (!TARGET_64BIT && TARGET_80387) #define HAVE_subtf3 (TARGET_80387) #define HAVE_subdf3 (TARGET_80387 || (TARGET_SSE2 && TARGET_SSE_MATH)) #define HAVE_subsf3 (TARGET_80387 || TARGET_SSE_MATH) #define HAVE_muldi3 (TARGET_64BIT) #define HAVE_mulsi3 1 #define HAVE_mulhi3 (TARGET_HIMODE_MATH) #define HAVE_mulqi3 (TARGET_QIMODE_MATH) #define HAVE_umulqihi3 (TARGET_QIMODE_MATH) #define HAVE_mulqihi3 (TARGET_QIMODE_MATH) #define HAVE_umulditi3 (TARGET_64BIT) #define HAVE_umulsidi3 (!TARGET_64BIT) #define HAVE_mulditi3 (TARGET_64BIT) #define HAVE_mulsidi3 (!TARGET_64BIT) #define HAVE_umuldi3_highpart (TARGET_64BIT) #define HAVE_umulsi3_highpart 1 #define HAVE_smuldi3_highpart (TARGET_64BIT) #define HAVE_smulsi3_highpart 1 #define HAVE_mulxf3 (!TARGET_64BIT && TARGET_80387) #define HAVE_multf3 (TARGET_80387) #define HAVE_muldf3 (TARGET_80387 || (TARGET_SSE2 && TARGET_SSE_MATH)) #define HAVE_mulsf3 (TARGET_80387 || TARGET_SSE_MATH) #define HAVE_divxf3 (!TARGET_64BIT && TARGET_80387) #define HAVE_divtf3 (TARGET_80387) #define HAVE_divdf3 (TARGET_80387 || (TARGET_SSE2 && TARGET_SSE_MATH)) #define HAVE_divsf3 (TARGET_80387 || TARGET_SSE_MATH) #define HAVE_divmoddi4 (TARGET_64BIT) #define HAVE_divmodsi4 1 #define HAVE_udivmodhi4 (TARGET_HIMODE_MATH) #define HAVE_testsi_ccno_1 1 #define HAVE_testqi_ccz_1 1 #define HAVE_testqi_ext_ccno_0 1 #define HAVE_anddi3 (TARGET_64BIT) #define HAVE_andsi3 1 #define HAVE_andhi3 (TARGET_HIMODE_MATH) #define HAVE_andqi3 (TARGET_QIMODE_MATH) #define HAVE_iordi3 (TARGET_64BIT) #define HAVE_iorsi3 1 #define HAVE_iorhi3 (TARGET_HIMODE_MATH) #define HAVE_iorqi3 (TARGET_QIMODE_MATH) #define HAVE_xordi3 (TARGET_64BIT) #define HAVE_xorsi3 1 #define HAVE_xorhi3 (TARGET_HIMODE_MATH) #define HAVE_xorqi3 (TARGET_QIMODE_MATH) #define HAVE_xorqi_cc_ext_1 1 #define HAVE_negdi2 1 #define HAVE_negsi2 1 #define HAVE_neghi2 (TARGET_HIMODE_MATH) #define HAVE_negqi2 (TARGET_QIMODE_MATH) #define HAVE_negsf2 (TARGET_80387) #define HAVE_negdf2 (TARGET_80387) #define HAVE_negxf2 (!TARGET_64BIT && TARGET_80387) #define HAVE_negtf2 (TARGET_80387) #define HAVE_abssf2 (TARGET_80387) #define HAVE_absdf2 (TARGET_80387) #define HAVE_absxf2 (!TARGET_64BIT && TARGET_80387) #define HAVE_abstf2 (TARGET_80387) #define HAVE_one_cmpldi2 (TARGET_64BIT) #define HAVE_one_cmplsi2 1 #define HAVE_one_cmplhi2 (TARGET_HIMODE_MATH) #define HAVE_one_cmplqi2 (TARGET_QIMODE_MATH) #define HAVE_ashldi3 1 #define HAVE_x86_shift_adj_1 (TARGET_CMOVE) #define HAVE_x86_shift_adj_2 1 #define HAVE_ashlsi3 1 #define HAVE_ashlhi3 (TARGET_HIMODE_MATH) #define HAVE_ashlqi3 (TARGET_QIMODE_MATH) #define HAVE_ashrdi3 1 #define HAVE_x86_shift_adj_3 1 #define HAVE_ashrsi3 1 #define HAVE_ashrhi3 (TARGET_HIMODE_MATH) #define HAVE_ashrqi3 (TARGET_QIMODE_MATH) #define HAVE_lshrdi3 1 #define HAVE_lshrsi3 1 #define HAVE_lshrhi3 (TARGET_HIMODE_MATH) #define HAVE_lshrqi3 (TARGET_QIMODE_MATH) #define HAVE_rotldi3 (TARGET_64BIT) #define HAVE_rotlsi3 1 #define HAVE_rotlhi3 (TARGET_HIMODE_MATH) #define HAVE_rotlqi3 (TARGET_QIMODE_MATH) #define HAVE_rotrdi3 (TARGET_64BIT) #define HAVE_rotrsi3 1 #define HAVE_rotrhi3 (TARGET_HIMODE_MATH) #define HAVE_rotrqi3 (TARGET_QIMODE_MATH) #define HAVE_extv 1 #define HAVE_extzv 1 #define HAVE_insv 1 #define HAVE_seq 1 #define HAVE_sne 1 #define HAVE_sgt 1 #define HAVE_sgtu 1 #define HAVE_slt 1 #define HAVE_sltu 1 #define HAVE_sge 1 #define HAVE_sgeu 1 #define HAVE_sle 1 #define HAVE_sleu 1 #define HAVE_sunordered (TARGET_80387 || TARGET_SSE) #define HAVE_sordered (TARGET_80387) #define HAVE_suneq (TARGET_80387 || TARGET_SSE) #define HAVE_sunge (TARGET_80387 || TARGET_SSE) #define HAVE_sungt (TARGET_80387 || TARGET_SSE) #define HAVE_sunle (TARGET_80387 || TARGET_SSE) #define HAVE_sunlt (TARGET_80387 || TARGET_SSE) #define HAVE_sltgt (TARGET_80387 || TARGET_SSE) #define HAVE_beq 1 #define HAVE_bne 1 #define HAVE_bgt 1 #define HAVE_bgtu 1 #define HAVE_blt 1 #define HAVE_bltu 1 #define HAVE_bge 1 #define HAVE_bgeu 1 #define HAVE_ble 1 #define HAVE_bleu 1 #define HAVE_bunordered (TARGET_80387 || TARGET_SSE) #define HAVE_bordered (TARGET_80387 || TARGET_SSE) #define HAVE_buneq (TARGET_80387 || TARGET_SSE) #define HAVE_bunge (TARGET_80387 || TARGET_SSE) #define HAVE_bungt (TARGET_80387 || TARGET_SSE) #define HAVE_bunle (TARGET_80387 || TARGET_SSE) #define HAVE_bunlt (TARGET_80387 || TARGET_SSE) #define HAVE_bltgt (TARGET_80387 || TARGET_SSE) #define HAVE_indirect_jump 1 #define HAVE_tablejump 1 #define HAVE_doloop_end (!TARGET_64BIT && TARGET_USE_LOOP) #define HAVE_call_pop (!TARGET_64BIT) #define HAVE_call 1 #define HAVE_call_exp 1 #define HAVE_call_value_pop (!TARGET_64BIT) #define HAVE_call_value 1 #define HAVE_call_value_exp 1 #define HAVE_untyped_call 1 #define HAVE_return (ix86_can_use_return_insn_p ()) #define HAVE_prologue 1 #define HAVE_epilogue 1 #define HAVE_sibcall_epilogue 1 #define HAVE_eh_return 1 #define HAVE_ffssi2 1 #define HAVE_sqrtsf2 ((! TARGET_NO_FANCY_MATH_387 && TARGET_80387) || TARGET_SSE_MATH) #define HAVE_sqrtdf2 ((! TARGET_NO_FANCY_MATH_387 && TARGET_80387) \ || (TARGET_SSE2 && TARGET_SSE_MATH)) #define HAVE_movstrsi 1 #define HAVE_movstrdi (TARGET_64BIT) #define HAVE_strmovdi_rex64 (TARGET_64BIT) #define HAVE_strmovsi 1 #define HAVE_strmovsi_rex64 (TARGET_64BIT) #define HAVE_strmovhi 1 #define HAVE_strmovhi_rex64 (TARGET_64BIT) #define HAVE_strmovqi 1 #define HAVE_strmovqi_rex64 (TARGET_64BIT) #define HAVE_clrstrsi 1 #define HAVE_clrstrdi (TARGET_64BIT) #define HAVE_strsetdi_rex64 (TARGET_64BIT) #define HAVE_strsetsi 1 #define HAVE_strsetsi_rex64 (TARGET_64BIT) #define HAVE_strsethi 1 #define HAVE_strsethi_rex64 (TARGET_64BIT) #define HAVE_strsetqi 1 #define HAVE_strsetqi_rex64 (TARGET_64BIT) #define HAVE_cmpstrsi 1 #define HAVE_cmpintqi 1 #define HAVE_strlensi 1 #define HAVE_strlendi 1 #define HAVE_movdicc (TARGET_64BIT) #define HAVE_movsicc 1 #define HAVE_movhicc (TARGET_CMOVE && TARGET_HIMODE_MATH) #define HAVE_movsfcc (TARGET_CMOVE) #define HAVE_movdfcc (TARGET_CMOVE) #define HAVE_movxfcc (!TARGET_64BIT && TARGET_CMOVE) #define HAVE_movtfcc (TARGET_CMOVE) #define HAVE_minsf3 (TARGET_SSE) #define HAVE_mindf3 (TARGET_SSE2 && TARGET_SSE_MATH) #define HAVE_maxsf3 (TARGET_SSE) #define HAVE_maxdf3 (TARGET_SSE2 && TARGET_SSE_MATH) #define HAVE_pro_epilogue_adjust_stack 1 #define HAVE_allocate_stack_worker (TARGET_STACK_PROBE) #define HAVE_allocate_stack (TARGET_STACK_PROBE) #define HAVE_builtin_setjmp_receiver (!TARGET_64BIT && flag_pic) #define HAVE_conditional_trap 1 #define HAVE_movti (TARGET_SSE || TARGET_64BIT) #define HAVE_movv4sf (TARGET_SSE) #define HAVE_movv4si (TARGET_MMX) #define HAVE_movv2si (TARGET_MMX) #define HAVE_movv4hi (TARGET_MMX) #define HAVE_movv8qi (TARGET_MMX) #define HAVE_movv2sf (TARGET_3DNOW) #define HAVE_sfence (TARGET_SSE || TARGET_3DNOW_A) #define HAVE_sse_prologue_save (TARGET_64BIT) #define HAVE_prefetch (TARGET_PREFETCH_SSE || TARGET_3DNOW) struct rtx_def; extern struct rtx_def *gen_cmpdi_ccno_1_rex64 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpdi_1_insn_rex64 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpqi_ext_3_insn PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpqi_ext_3_insn_rex64 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_x86_fnstsw_1 PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_x86_sahf_1 PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_popsi1 PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_movsi_insv_1 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pushdi2_rex64 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_popdi1 PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_swapxf PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_swaptf PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_zero_extendhisi2_and PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_zero_extendsidi2_32 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_zero_extendsidi2_rex64 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_zero_extendhidi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_zero_extendqidi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_extendsidi2_rex64 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_extendhidi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_extendqidi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_extendhisi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_extendqihi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_extendqisi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_truncdfsf2_3 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_truncdfsf2_sse_only PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncdi_nomemory PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncdi_memory PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncsfdi_sse PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncdfdi_sse PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncsi_nomemory PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncsi_memory PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncsfsi_sse PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncdfsi_sse PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_trunchi_nomemory PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_trunchi_memory PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_x86_fnstcw_1 PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_x86_fldcw_1 PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_floathisf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_floathidf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_floathixf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_floathitf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_floatsixf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_floatsitf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_floatdixf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_floatditf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_addqi3_cc PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_addsi_1_zext PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_addqi_ext_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subdi3_carry_rex64 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subsi3_carry PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subsi3_carry_zext PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_divqi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_udivqi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_divmodhi4 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_udivmoddi4 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_udivmodsi4 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_testsi_1 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_andqi_ext_0 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_negsf2_memory PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_negsf2_ifs PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_negdf2_memory PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_negdf2_ifs PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_abssf2_memory PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_abssf2_ifs PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_absdf2_memory PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_absdf2_ifs PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashldi3_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_x86_shld_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashrdi3_63_rex64 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashrdi3_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_x86_shrd_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashrsi3_31 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_lshrdi3_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_setcc_2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_jump PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_doloop_end_internal PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_blockage PARAMS ((void)); extern struct rtx_def *gen_return_internal PARAMS ((void)); extern struct rtx_def *gen_return_pop_internal PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_return_indirect_internal PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_nop PARAMS ((void)); extern struct rtx_def *gen_prologue_set_got PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_prologue_get_pc PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_eh_return_si PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_eh_return_di PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_leave PARAMS ((void)); extern struct rtx_def *gen_leave_rex64 PARAMS ((void)); extern struct rtx_def *gen_ffssi_1 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sqrtsf2_1 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sqrtsf2_1_sse_only PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sqrtsf2_i387 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sqrtdf2_1 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sqrtdf2_1_sse_only PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sqrtdf2_i387 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sqrtxf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sqrttf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sindf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sinsf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sinxf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sintf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cosdf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cossf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cosxf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_costf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cld PARAMS ((void)); extern struct rtx_def *gen_strmovdi_rex_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strmovsi_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strmovsi_rex_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strmovhi_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strmovhi_rex_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strmovqi_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strmovqi_rex_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rep_movdi_rex64 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rep_movsi PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rep_movsi_rex64 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rep_movqi PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rep_movqi_rex64 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strsetdi_rex_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strsetsi_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strsetsi_rex_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strsethi_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strsethi_rex_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strsetqi_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strsetqi_rex_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rep_stosdi_rex64 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rep_stossi PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rep_stossi_rex64 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rep_stosqi PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rep_stosqi_rex64 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpstrqi_nz_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpstrqi_nz_rex_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpstrqi_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpstrqi_rex_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strlenqi_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strlenqi_rex_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_x86_movdicc_0_m1_rex64 PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_x86_movsicc_0_m1 PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_pro_epilogue_adjust_stack_rex64 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_movsfcc PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_movsfcc_eq PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_movdfcc PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_movdfcc_eq PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_allocate_stack_worker_1 PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_allocate_stack_worker_rex64 PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_trap PARAMS ((void)); extern struct rtx_def *gen_movv4sf_internal PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movv4si_internal PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movv8qi_internal PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movv4hi_internal PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movv2si_internal PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movv2sf_internal PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movti_internal PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_movaps PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_movups PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_movmskps PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_pmovmskb PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_maskmovq PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_maskmovq_rex PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_movntv4sf PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_movntdi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_movhlps PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_movlhps PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_movhps PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_movlps PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_loadss PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_movss PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_storess PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_shufps PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_addv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_vmaddv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_vmsubv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mulv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_vmmulv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_divv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_vmdivv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rcpv4sf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_vmrcpv4sf2 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rsqrtv4sf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_vmrsqrtv4sf2 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sqrtv4sf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_vmsqrtv4sf2 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_andti3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_nandti3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_iorti3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_xorti3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_clrv4sf PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_maskcmpv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_maskncmpv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_vmmaskcmpv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_vmmaskncmpv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_comi PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_ucomi PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_unpckhps PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sse_unpcklps PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_smaxv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_vmsmaxv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sminv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_vmsminv4sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cvtpi2ps PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cvtps2pi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cvttps2pi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cvtsi2ss PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cvtss2si PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cvttss2si PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_addv8qi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_addv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_addv2si3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ssaddv8qi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ssaddv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_usaddv8qi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_usaddv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subv8qi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subv2si3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sssubv8qi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sssubv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ussubv8qi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ussubv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mulv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_smulv4hi3_highpart PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_umulv4hi3_highpart PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_pmaddwd PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_iordi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_xordi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_clrdi PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_mmx_anddi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_nanddi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_uavgv8qi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_uavgv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_psadbw PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_pinsrw PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_pextrw PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_pshufw PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_eqv8qi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_eqv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_eqv2si3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_gtv8qi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_gtv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_gtv2si3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_umaxv8qi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_smaxv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_uminv8qi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sminv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashrv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashrv2si3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_lshrv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_lshrv2si3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_lshrdi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashlv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashlv2si3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_ashldi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_packsswb PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_packssdw PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_packuswb PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_punpckhbw PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_punpckhwd PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_punpckhdq PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_punpcklbw PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_punpcklwd PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mmx_punpckldq PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_emms PARAMS ((void)); extern struct rtx_def *gen_ldmxcsr PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_stmxcsr PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_addv2sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subv2sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subrv2sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_gtv2sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_gev2sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_eqv2sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pfmaxv2sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pfminv2sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mulv2sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_femms PARAMS ((void)); extern struct rtx_def *gen_pf2id PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pf2iw PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pfacc PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pfnacc PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pfpnacc PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pi2fw PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_floatv2si2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pavgusb PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pfrcpv2sf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pfrcpit1v2sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pfrcpit2v2sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pfrsqrtv2sf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pfrsqit1v2sf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pmulhrwv4hi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pswapdv2si2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pswapdv2sf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpdi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpsi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmphi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpqi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpdi_1_rex64 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpsi_1 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpqi_ext_3 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpxf PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmptf PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpdf PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpsf PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movsi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movhi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movstricthi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movqi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_reload_outqi PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movstrictqi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movdi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movsf PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movdf PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movxf PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movtf PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_zero_extendhisi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_zero_extendqihi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_zero_extendqisi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_zero_extendsidi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_extendsidi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_extendsfdf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_extendsfxf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_extendsftf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_extenddfxf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_extenddftf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_truncdfsf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_truncxfsf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_trunctfsf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_truncxfdf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_trunctfdf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncxfdi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_trunctfdi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncdfdi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncsfdi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncxfsi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_trunctfsi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncdfsi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncsfsi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncxfhi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_trunctfhi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncdfhi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_fix_truncsfhi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_floatsisf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_floatdisf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_floatsidf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_floatdidf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_adddi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_addsi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_addhi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_addqi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_addxf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_addtf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_adddf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_addsf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subdi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subsi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subhi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subqi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subxf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subtf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subdf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_subsf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_muldi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mulsi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mulhi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mulqi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_umulqihi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mulqihi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_umulditi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_umulsidi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mulditi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mulsidi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_umuldi3_highpart PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_umulsi3_highpart PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_smuldi3_highpart PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_smulsi3_highpart PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mulxf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_multf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_muldf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mulsf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_divxf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_divtf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_divdf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_divsf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_divmoddi4 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_divmodsi4 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_udivmodhi4 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_testsi_ccno_1 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_testqi_ccz_1 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_testqi_ext_ccno_0 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_anddi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_andsi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_andhi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_andqi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_iordi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_iorsi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_iorhi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_iorqi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_xordi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_xorsi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_xorhi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_xorqi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_xorqi_cc_ext_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_negdi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_negsi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_neghi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_negqi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_negsf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_negdf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_negxf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_negtf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_abssf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_absdf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_absxf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_abstf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_one_cmpldi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_one_cmplsi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_one_cmplhi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_one_cmplqi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashldi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_x86_shift_adj_1 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_x86_shift_adj_2 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashlsi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashlhi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashlqi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashrdi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_x86_shift_adj_3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashrsi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashrhi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ashrqi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_lshrdi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_lshrsi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_lshrhi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_lshrqi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rotldi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rotlsi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rotlhi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rotlqi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rotrdi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rotrsi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rotrhi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_rotrqi3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_extv PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_extzv PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_insv PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_seq PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_sne PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_sgt PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_sgtu PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_slt PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_sltu PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_sge PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_sgeu PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_sle PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_sleu PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_sunordered PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_sordered PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_suneq PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_sunge PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_sungt PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_sunle PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_sunlt PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_sltgt PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_beq PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_bne PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_bgt PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_bgtu PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_blt PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_bltu PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_bge PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_bgeu PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_ble PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_bleu PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_bunordered PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_bordered PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_buneq PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_bunge PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_bungt PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_bunle PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_bunlt PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_bltgt PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_indirect_jump PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_tablejump PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_doloop_end PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); #define GEN_CALL_POP(A, B, C, D) gen_call_pop ((A), (B), (C), (D)) extern struct rtx_def *gen_call_pop PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); #define GEN_CALL(A, B, C, D) gen_call ((A), (B), (C)) extern struct rtx_def *gen_call PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_call_exp PARAMS ((struct rtx_def *, struct rtx_def *)); #define GEN_CALL_VALUE_POP(A, B, C, D, E) gen_call_value_pop ((A), (B), (C), (D), (E)) extern struct rtx_def *gen_call_value_pop PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); #define GEN_CALL_VALUE(A, B, C, D, E) gen_call_value ((A), (B), (C), (D)) extern struct rtx_def *gen_call_value PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_call_value_exp PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_untyped_call PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_return PARAMS ((void)); extern struct rtx_def *gen_prologue PARAMS ((void)); extern struct rtx_def *gen_epilogue PARAMS ((void)); extern struct rtx_def *gen_sibcall_epilogue PARAMS ((void)); extern struct rtx_def *gen_eh_return PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_ffssi2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sqrtsf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sqrtdf2 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movstrsi PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movstrdi PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strmovdi_rex64 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strmovsi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strmovsi_rex64 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strmovhi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strmovhi_rex64 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strmovqi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strmovqi_rex64 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_clrstrsi PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_clrstrdi PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strsetdi_rex64 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strsetsi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strsetsi_rex64 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strsethi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strsethi_rex64 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strsetqi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strsetqi_rex64 PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpstrsi PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_cmpintqi PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_strlensi PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_strlendi PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movdicc PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movsicc PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movhicc PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movsfcc PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movdfcc PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movxfcc PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movtfcc PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_minsf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_mindf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_maxsf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_maxdf3 PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_pro_epilogue_adjust_stack PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_allocate_stack_worker PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_allocate_stack PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_builtin_setjmp_receiver PARAMS ((struct rtx_def *)); extern struct rtx_def *gen_conditional_trap PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movti PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movv4sf PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movv4si PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movv2si PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movv4hi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movv8qi PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_movv2sf PARAMS ((struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_sfence PARAMS ((void)); extern struct rtx_def *gen_sse_prologue_save PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *, struct rtx_def *)); extern struct rtx_def *gen_prefetch PARAMS ((struct rtx_def *, struct rtx_def *, struct rtx_def *)); #endif /* GCC_INSN_FLAGS_H */
BuckWang0509/codeforces-go
main/1600-1699/1620A_test.go
<reponame>BuckWang0509/codeforces-go package main import ( "github.com/EndlessCheng/codeforces-go/main/testutil" "testing" ) // http://codeforces.com/problemset/problem/1620/A // https://codeforces.com/problemset/status/1620/problem/A func TestCF1620A(t *testing.T) { // just copy from website rawText := ` inputCopy 4 EEE EN ENNEENE NENN outputCopy YES NO YES YES` testutil.AssertEqualCase(t, rawText, 0, CF1620A) }
reneelpetit/codestream-server
inbound_email/test/test.js
// unit tests concerning the inbound email server 'use strict'; const InboundEmailServerConfig = require(process.env.CSSVC_BACKEND_ROOT + '/inbound_email/config/config'); const EmailTest = require('./email_test'); const Async = require('async'); const EmailTests = require('./email_tests'); var Config; // make eslint happy /* globals describe, before, after, it */ // we'll execute a series of tests, each of which plants a particular email file // in the inbound emails directory and expects certain text in the post as a result, // we'll listen for the post on a pubnub client. Alternatively, there are some // tests where we expect processing the file to fail, and we expect no post as // as result describe('Inbound Email', function() { this.timeout(30000); before(async () => { Config = Config || await InboundEmailServerConfig.loadPreferredConfig(); await new Promise(resolve => { setTimeout(() => { resolve(); }, 15000); }); }); Async.forEachSeries( EmailTests, (test, forEachCallback) => { // invoke an instance of the test class, define before callback, // and then define the actual test let emailTest = new EmailTest(test, Config); describe(emailTest.description, () => { before(callback => { emailTest.setConfig(Config); emailTest.before(callback); }); after(emailTest.after.bind(emailTest)); it(emailTest.it, itCallback => { emailTest.run(itCallback); }); }); forEachCallback(); } ); });
datavetaren/epilog
src/common/garbage_collector.hpp
#pragma once #ifndef _common_garbage_collector_hpp #define _common_garbage_collector_hpp #include <bitset> #include <vector> #include <map> namespace epilog { namespace common { class garbage_collector { public: garbage_collector(heap &h) : heap_(h) {}; // Garbage collects and returns number of collected bytes. size_t do_collection(std::vector<ptr_cell *> &roots); private: typedef std::bitset<heap_block::MAX_SIZE> * live_block_t; typedef std::vector<live_block_t> live_t; heap &heap_; live_block_t get_live_block(live_t &live, size_t index); void set_live_block(live_t &live, size_t index, live_block_t block); live_block_t mark_live_block(live_t &live, size_t block_index); bool mark_live_word(live_t &live, size_t index); void mark(std::vector<ptr_cell *> &roots, live_t &live); void push_children(size_t index, std::vector<size_t> &worklist); size_t calculate_deltas(std::unordered_map<size_t, size_t> &block_index_to_delta, live_t &live); size_t calculate_new_index(std::unordered_map<size_t, size_t> &block_index_to_delta, size_t index); void rewrite_cell(size_t i, heap_block &block, std::unordered_map<size_t, size_t> &block_index_to_delta); void rewrite_blocks(std::unordered_map<size_t, size_t> &block_index_to_delta, live_t &live); void rewrite_roots(std::unordered_map<size_t, size_t> &block_index_to_delta, std::vector<ptr_cell *> &roots); void cleanup_blocks(live_t &live); void free_live_sets(live_t &live); void dump_marked(live_t &live); size_t collect(live_t &live, std::vector<ptr_cell *> &roots); }; }} #endif
RachelleH/-hmcts-ia-case-documents-api
src/main/java/uk/gov/hmcts/reform/iacasedocumentsapi/domain/DateProvider.java
<gh_stars>1-10 package uk.gov.hmcts.reform.iacasedocumentsapi.domain; import java.time.LocalDate; import java.time.LocalDateTime; public interface DateProvider { LocalDate now(); LocalDateTime nowWithTime(); }
cindy1764/pouch
apis/types/image_info.go
<reponame>cindy1764/pouch // Code generated by go-swagger; DO NOT EDIT. package types // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( strfmt "github.com/go-openapi/strfmt" "github.com/go-openapi/errors" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) // ImageInfo An object containing all details of an image at API side // swagger:model ImageInfo type ImageInfo struct { // the CPU architecture. Architecture string `json:"Architecture,omitempty"` // config Config *ContainerConfig `json:"Config,omitempty"` // time of image creation. CreatedAt string `json:"CreatedAt,omitempty"` // digest of image. Digest string `json:"Digest,omitempty"` // ID of an image. ID string `json:"ID,omitempty"` // name of an image. Name string `json:"Name,omitempty"` // the name of the operating system. Os string `json:"Os,omitempty"` // root f s RootFS *ImageInfoRootFS `json:"RootFS,omitempty"` // size of image's taking disk space. Size int64 `json:"Size,omitempty"` // tag of an image. Tag string `json:"Tag,omitempty"` } /* polymorph ImageInfo Architecture false */ /* polymorph ImageInfo Config false */ /* polymorph ImageInfo CreatedAt false */ /* polymorph ImageInfo Digest false */ /* polymorph ImageInfo ID false */ /* polymorph ImageInfo Name false */ /* polymorph ImageInfo Os false */ /* polymorph ImageInfo RootFS false */ /* polymorph ImageInfo Size false */ /* polymorph ImageInfo Tag false */ // Validate validates this image info func (m *ImageInfo) Validate(formats strfmt.Registry) error { var res []error if err := m.validateConfig(formats); err != nil { // prop res = append(res, err) } if err := m.validateRootFS(formats); err != nil { // prop res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *ImageInfo) validateConfig(formats strfmt.Registry) error { if swag.IsZero(m.Config) { // not required return nil } if m.Config != nil { if err := m.Config.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("Config") } return err } } return nil } func (m *ImageInfo) validateRootFS(formats strfmt.Registry) error { if swag.IsZero(m.RootFS) { // not required return nil } if m.RootFS != nil { if err := m.RootFS.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("RootFS") } return err } } return nil } // MarshalBinary interface implementation func (m *ImageInfo) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *ImageInfo) UnmarshalBinary(b []byte) error { var res ImageInfo if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil } // ImageInfoRootFS the rootfs key references the layer content addresses used by the image. // swagger:model ImageInfoRootFS type ImageInfoRootFS struct { // the base layer content hash. BaseLayer string `json:"BaseLayer,omitempty"` // an array of layer content hashes Layers []string `json:"Layers"` // type of the rootfs // Required: true Type string `json:"Type"` } /* polymorph ImageInfoRootFS BaseLayer false */ /* polymorph ImageInfoRootFS Layers false */ /* polymorph ImageInfoRootFS Type false */ // Validate validates this image info root f s func (m *ImageInfoRootFS) Validate(formats strfmt.Registry) error { var res []error if err := m.validateLayers(formats); err != nil { // prop res = append(res, err) } if err := m.validateType(formats); err != nil { // prop res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *ImageInfoRootFS) validateLayers(formats strfmt.Registry) error { if swag.IsZero(m.Layers) { // not required return nil } return nil } func (m *ImageInfoRootFS) validateType(formats strfmt.Registry) error { if err := validate.RequiredString("RootFS"+"."+"Type", "body", string(m.Type)); err != nil { return err } return nil } // MarshalBinary interface implementation func (m *ImageInfoRootFS) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *ImageInfoRootFS) UnmarshalBinary(b []byte) error { var res ImageInfoRootFS if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
gavin2lee/incubator-gl
mnis/core/src/main/java/com/lachesis/mnis/core/sysDic/entity/repository/SysDicRepository.java
package com.lachesis.mnis.core.sysDic.entity.repository; import java.util.List; import com.lachesis.mnis.core.sysDic.entity.SysDic; public interface SysDicRepository { int save(SysDic record); List<SysDic> queryAll(); List<String> queryDicTypes(); }
Syncena/Maven-firmware
src/cortexm/cortexm.h
/* * Copyright (c) 2022, <NAME>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CORTEXM_H #define CORTEXM_H #include "adiv5.h" #include "target.h" #include "microchip_dsu.h" #include "bitmap.h" #ifdef CONFIG_USE_NETWORK #include "network.h" #ifdef NETWORK_OPT_HTTPD #include "stringio.h" #endif #endif /* CONFIG_USE_NETWORK */ struct cortexm; typedef struct cortexm *cortexm_t; struct cortexm_txml_regmap; struct cortexm { target_t cm_target; char cm_core_name[32]; u_int cm_flags; #define CORTEXM_FLAG_ARCH_MASK (3u << 0) #define CORTEXM_FLAG_ARCH(cm) ((cm)->cm_flags&CORTEXM_FLAG_ARCH_MASK) #define CORTEXM_FLAG_ARCH_V6M 0u #define CORTEXM_FLAG_ARCH_V7M 1u #define CORTEXM_FLAG_ARCH_V8M 2u #define CORTEXM_FLAG_V8M_EXT_BASE (0u << 2) #define CORTEXM_FLAG_V8M_EXT_MAIN (1u << 2) #define CORTEXM_FLAG_V8M_EXT_SECURITY (1u << 3) #define CORTEXM_FLAG_V8M_EXT_DSP (1u << 4) #define CORTEXM_FLAG_HAS_FPU (1u << 8) #define CORTEXM_FLAG_FPU_DP (1u << 9) #define CORTEXM_FLAG_HAS_ARM_CACHE (1u << 10) #define CORTEXM_FLAG_HAS_SOC_CACHE (1u << 11) #define CORTEXM_FLAG_HAS_MPU (1u << 12) #define CORTEXM_FLAG_ATTACHED (1u << 13) #define CORTEXM_FLAG_BKPT (1u << 14) #define CORTEXM_FLAG_SINGLE_STEP (1u << 15) #define CORTEXM_FLAG_COMP_V2 (1u << 16) #define CORTEXM_FLAG_APPLET_RUNNING (1u << 17) #define CORTEXM_FLAG_UNTRUSTED_ONLY (1u << 18) #define CORTEXM_FLAG_RESUME_CALLED (1u << 19) #define CORTEXM_FLAG_NO_RESET (1u << 20) uint32_t cm_cpuid; uint32_t cm_ccr; /* Valid only when core halted. */ uint32_t cm_fpccr; /* Valid only when core halted. */ uint32_t cm_fpcar; /* Valid only when core halted. */ uint32_t cm_ctr; uint32_t cm_clidr; uint32_t cm_demcr; uint32_t cm_demcr_cfg_bits; uint32_t cm_mpu_regions; uint32_t cm_mpu_ctrl_save; u_int cm_last_halt_reason; struct target_watchbreak cm_last_watchbreak; struct target_syscall cm_syscall; /* RTOS stack frame support. */ const struct cortexm_txml_regframe *cm_rtos_frame; bool cm_rtos_frame_dynamic; unsigned int cm_rtos_frame_count; target_addr_t cm_rtos_frame_base; /* System peripheral bases. */ uint32_t cm_scs_base; uint32_t cm_fpb_base; uint32_t cm_dwt_base; u_int cm_features; const struct cortexm_txml_regmap *cm_regmap_arch; const struct cortexm_txml_regmap *cm_regmap_security; void *cm_soc; void (*cm_soc_free)(cortexm_t); int (*cm_soc_ctl)(cortexm_t, uint32_t *, void *); void (*cm_soc_state_changed)(cortexm_t, u_int); int (*cm_core_reset)(cortexm_t, int); /* More than enough h/w watchpoints for any extant Cortex-M device. */ #define CORTEXM_MAX_WATCHPOINTS 16 unsigned int cm_num_hw_watchpoints; BITMAP_DECLARE(cm_hw_watchpoints, CORTEXM_MAX_WATCHPOINTS); /* More than enough h/w breakpoints for any supported Cortex-M device. */ #define CORTEXM_MAX_HW_BREAKPOINTS 16 unsigned int cm_num_hw_breakpoints; BITMAP_DECLARE(cm_hw_breakpoints, CORTEXM_MAX_HW_BREAKPOINTS); /* * Don't get carried away with the number of s/w breakpoints. We need to * clear them every time the CPU core halts, and restore them on resume. * This will slow things down if the user sets a whole bunch of them. */ #define CORTEXM_MAX_SW_BREAKPOINTS 64 BITMAP_DECLARE(cm_sw_breakpoints, CORTEXM_MAX_SW_BREAKPOINTS); uint16_t cm_sw_breakpoint_insn[CORTEXM_MAX_SW_BREAKPOINTS]; target_addr_t cm_sw_breakpoint_addr[CORTEXM_MAX_SW_BREAKPOINTS]; #define CORTEXM_IS_BKPT_INSN(i) (((i) & 0xff00u) == 0xbe00u) #define CORTEXM_MAKE_BKPT_INSN(id) (0xbe00u | ((id) & 0x7fu)) #define CORTEXM_BKPT_ID(i) ((i) & 0xffu) #define CORTEXM_BKPT_SEMIHOSTING 0xabu }; #define CORTEXM_V8M_HAS_EXT_MAIN(cm) \ (((cm)->cm_flags & \ (CORTEXM_FLAG_ARCH_MASK | CORTEXM_FLAG_V8M_EXT_MAIN)) == \ (CORTEXM_FLAG_ARCH_V8M | CORTEXM_FLAG_V8M_EXT_MAIN)) #define CORTEXM_V8M_HAS_EXT_SECURITY(cm) \ (((cm)->cm_flags & \ (CORTEXM_FLAG_ARCH_MASK | CORTEXM_FLAG_V8M_EXT_SECURITY)) == \ (CORTEXM_FLAG_ARCH_V8M | CORTEXM_FLAG_V8M_EXT_SECURITY)) #define CORTEXM_V8M_HAS_EXT_DSP(cm) \ (((cm)->cm_flags & \ (CORTEXM_FLAG_ARCH_MASK | CORTEXM_FLAG_V8M_EXT_DSP)) == \ (CORTEXM_FLAG_ARCH_V8M | CORTEXM_FLAG_V8M_EXT_DSP)) #define CORTEXM_HAS_MAIN(cm) \ ((CORTEXM_FLAG_ARCH(cm) == CORTEXM_FLAG_ARCH_V7M) || \ CORTEXM_V8M_HAS_EXT_MAIN(cm)) extern uint32_t cortexm_core_reg_read(cortexm_t cm, u_int reg); extern void cortexm_core_reg_write(cortexm_t cm, u_int reg, uint32_t v); extern int cortexm_attach(target_t, target_addr_t); #define CORTEXM_SOC_ATTACH_OK 1 #define CORTEXM_SOC_ATTACH_NO_MATCH 0 #define CORTEXM_SOC_ATTACH_RESCAN (-1) extern bool cortexm_v8m_secure_debug_available(cortexm_t); /* * Cortex-M CTL codes, used to query SoC-specific code. */ /* 'arg' points to struct cortexm_cache_params */ #define CORTEXM_CTL_CACHE_PARAMS 100 struct cortexm_cache_params { const char *cp_type; uint32_t cp_sets; uint16_t cp_ways; uint16_t cp_linesize; }; #ifdef NETWORK_OPT_HTTPD extern int cortexm_update_settings(int, const struct network_http_furl_key_value *); extern void cortexm_debug_update(stringio_t); #endif extern void cortexm_load_defaults(void); #ifndef CONFIG_USE_CONFIGDB #define CORTEXM_GLOBAL_VARS \ uint32_t glob_cortexm_vc; \ unsigned int glob_cortexm_flags; #endif extern uint32_t cortexm_hw_cfg_extra_set, cortexm_hw_cfg_extra_clr; #endif /* CORTEXM_H */
longuyen1/maven
maven-core/src/main/java/org/apache/maven/plugin/PluginContainerException.java
package org.apache.maven.plugin; /* * 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. */ import org.apache.maven.model.Plugin; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.component.repository.exception.ComponentRepositoryException; import org.codehaus.plexus.configuration.PlexusConfigurationException; /** * Exception which occurs to indicate that the plugin cannot be initialized due * to some deeper problem with Plexus. Context information includes the groupId, * artifactId, and version for the plugin; at times, the goal name for which * execution failed; a message detailing the problem; the ClassRealm used to * lookup the plugin; and the Plexus exception that caused this error. * * @author jdcasey * */ public class PluginContainerException extends PluginManagerException { private ClassRealm pluginRealm; public PluginContainerException( MojoDescriptor mojoDescriptor, ClassRealm pluginRealm, String message, Throwable e ) { super( mojoDescriptor, message, e ); this.pluginRealm = pluginRealm; } public PluginContainerException( MojoDescriptor mojoDescriptor, ClassRealm pluginRealm, String message, ComponentLookupException e ) { super( mojoDescriptor, message, e ); this.pluginRealm = pluginRealm; } public PluginContainerException( Plugin plugin, ClassRealm pluginRealm, String message, Throwable e ) { super( plugin, message, e ); this.pluginRealm = pluginRealm; } public PluginContainerException( Plugin plugin, ClassRealm pluginRealm, String message, PlexusConfigurationException e ) { super( plugin, message, e ); this.pluginRealm = pluginRealm; } public PluginContainerException( Plugin plugin, ClassRealm pluginRealm, String message, ComponentRepositoryException e ) { super( plugin, message, e ); this.pluginRealm = pluginRealm; } public ClassRealm getPluginRealm() { return pluginRealm; } }
hoantran-it/Utility-Library
utility-library/src/main/java/com/github/hoantran/lib/utility/query/RestParams.java
<reponame>hoantran-it/Utility-Library<gh_stars>1-10 /** * Created by <NAME> @ http://hoantran-it.blogspot.com * * Any modifications to this file must keep this entire header intact. * */ package com.github.hoantran.lib.utility.query; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; /** * Rest params util. * * @author HoanTran */ public class RestParams { public static final String DEFAULT_CHARACTER_ENCODING = "UTF-8"; /** * Build query params. * * @param queryMap * @return example name=abc&id=123 * @throws UnsupportedEncodingException */ public static String buildQueryParams(Map<String, String> queryMap) throws UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); for (HashMap.Entry<String, String> e : queryMap.entrySet()) { if (sb.length() > 0) { sb.append('&'); } sb.append(URLEncoder.encode(e.getKey(), DEFAULT_CHARACTER_ENCODING)).append('=').append(URLEncoder.encode(e.getValue(), DEFAULT_CHARACTER_ENCODING)); } return sb.toString(); } public static String buildPageFilter(int page, int size, Map<String, String> sort) throws UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); sb.append(MessageFormat.format("page={0}&size={1}", page, size)); for (HashMap.Entry<String, String> e : sort.entrySet()) { if (sb.length() > 0) { sb.append('&'); } sb.append("sort=").append(e.getKey()).append(',').append(e.getValue()); } return sb.toString(); } public static String buildPageFilter(int page, int size) throws UnsupportedEncodingException { return MessageFormat.format("page={0}&size={1}", page, size); } }
yz0426/yangyu
yangyu-1-api/src/main/java/com/yangyu/fallback/IRoleFallback.java
package com.yangyu.fallback; import com.yangyu.api.RoleApi; import com.yangyu.user.api.vo.RoleVo; import feign.hystrix.FallbackFactory; import org.springframework.stereotype.Component; import java.util.List; @Component public class IRoleFallback implements FallbackFactory<RoleApi> { @Override public RoleApi create(Throwable throwable) { return new RoleApi() { @Override public List<RoleVo> selectByUser(Long id) { return RoleVo.defaultRole(); } }; } }
ExpressAI/DataLab
datasets/sdqa/sdqa.py
# coding=utf-8 # Copyright 2022 The TensorFlow datasets Authors and the HuggingFace datasets, DataLab Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """SQUAD: The Stanford Question Answering Dataset.""" import json import textwrap import os import datalabs from datalabs import get_task, TaskType logger = datalabs.logging.get_logger(__name__) _CITATION = """\ @inproceedings{faisal-etal-21-sdqa, title = {{SD-QA}: {S}poken {D}ialectal {Q}uestion {A}nswering for the {R}eal {W}orld}, author = {<NAME> <NAME>, <NAME> Anastasopoulos, Antonios}, url={https://arxiv.org/abs/2109.12072}, year = {2021}, booktitle = {Findings of the 2021 Conference on Empirical Methods in Natural Language Processing (EMNLP Findings)}, publisher = {Association for Computational Linguistics}, month = {November}, } """ _DESCRIPTION = """\ SDQA: : Spoken Dialectal Question Answering for the Real World is a multi-dialect, spoken QA benchmark on five languages (Arabic, Bengali, English, Korean, Kiswahili) with more than 68k audio prompts in 22 dialects from 245 speakers. Google Speech API with regional units (eg. en-US, sw-TZ) are used to perform speech to text conversion of the questions. These questions are replaced in place of the original TyDiQA gold questions to prepare dialectal development and test set. As a benchmark train set, a discarded version of original TyDiQA training set is used. """ # LANG_URLS = { # "ar": "https://drive.google.com/uc?export=download&id=1tUsnP9xPFEsLjShtnsN1osgK84jPc3ED", # "bn": "https://drive.google.com/uc?export=download&id=1qqOiZy1lz0pIzw_rgrVHwx2XJveIJzGb", # "en": "https://drive.google.com/uc?export=download&id=1WGfgc7_0DCkxBsheaxfke4TK_j1G5OFT", # "fi": "https://drive.google.com/uc?export=download&id=1-pbAbt-v2QHWDj2dnbKcOSNbJHLEiGpd", # "id": "https://drive.google.com/uc?export=download&id=1QuMrKvWJ74sl-MrTAo6Mz-_bs953YZM6", # "ko": "https://drive.google.com/uc?export=download&id=1PzbuXVeCuYU3CBPLgqjM4GuRvY1fCvVl", # "ru": "https://drive.google.com/uc?export=download&id=1NIlGs1o_1AYPlyIIcBnXJHIRh5Zi9nU1", # "sw": "https://drive.google.com/uc?export=download&id=1JkXf6rHyFRWyQGTCdwIxPVuRoY2dmDwd", # "te": "https://drive.google.com/uc?export=download&id=1NyliC5GairK8TvxrQOvH-ktNgsKbA5Fz", # } # DATA_URL="https://drive.google.com/uc?export=download&id=1_kGzqqiJJLGpKN6pfNzguyzG_vU8figf" # TRAIN_LANGS = {'en':'english','bn':'bengali','sw':'swahili','ko':'korean','ar':'arabic','fi':'finnish','te':'telugu','id':'indonesian','ru':'russian'} # TRAIN_LANGS = {'en':'english','bn':'bengali'} # SDQA_LANGS = {'en':'english','bn':'bengali','sw':'swahili','ko':'korean','ar':'arabic'} # DIALECTS = { # 'english':['nga','nzl','usa','ind_s','ind_n','irl','kenya','gbr','zaf','aus','phl'], # 'arabic':['bhr','dza','egy','jor','mar','sau','tun'], # 'swahili':['kenya','tanzania'], # 'bengali':['dhaka','ind'], # 'korean':['korn','kors'] # } _URLS = { "train": "https://drive.google.com/uc?export=download&id=16M6bglY6ttiMcYximOkQ5jKX12KyRYxL", "dev": "https://drive.google.com/uc?export=download&id=18SNCH2uQ7PBKAeOWgyRlWS_QmbJi3oDj", "test": "https://drive.google.com/uc?export=download&id=18iyLut6C6SVu3cZFlocBGtarFgQ03qzn", } class SdqaConfig(datalabs.BuilderConfig): """BuilderConfig for SQUAD.""" def __init__(self, **kwargs): """BuilderConfig for SQUADV2. Args: **kwargs: keyword arguments forwarded to super. """ super(SdqaConfig, self).__init__(**kwargs) class Sdqa(datalabs.GeneratorBasedBuilder): """TODO(squad_v2): Short description of my dataset.""" # TODO(squad_v2): Set up version. BUILDER_CONFIGS = [ SdqaConfig(name="sdqa", version=datalabs.Version("1.0.0"), description="SDQA 1.0.0"), ] def _info(self): # TODO(squad_v2): Specifies the datalab.DatasetInfo object return datalabs.DatasetInfo( # This is the description that will appear on the datalab page. description=_DESCRIPTION, # datalab.features.FeatureConnectors features=datalabs.Features( { "id": datalabs.Value("string"), "title": datalabs.Value("string"), "context": datalabs.Value("string"), "question": datalabs.Value("string"), "answers": { "text": datalabs.features.Sequence(datalabs.Value("string")), "answer_start": datalabs.features.Sequence(datalabs.Value("int32")), } # These are the features of your dataset like images, labels ... } ), # If there's a common (input, target) tuple from the features, # specify them here. They'll be used if as_supervised=True in # builder.as_dataset. supervised_keys=None, # Homepage of the dataset for documentation homepage="https://nlp.cs.gmu.edu/publication/faisal-etal-21-sdqa/", citation=_CITATION, languages=["en","ar","bn","sw","ko"], task_templates=[ get_task(TaskType.qa_extractive)( question_column="question", context_column="context", answers_column="answers" ) ], ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" # TODO(squad_v2): Downloads the data and defines the splits # dl_manager is a datalab.download.DownloadManager that can be used to # download and extract URLs urls_to_download = _URLS downloaded_files = dl_manager.download_and_extract(urls_to_download) return [ datalabs.SplitGenerator(name=datalabs.Split.TRAIN, gen_kwargs={"filepath": downloaded_files["train"]}), datalabs.SplitGenerator(name=datalabs.Split.VALIDATION, gen_kwargs={"filepath": downloaded_files["dev"]}), datalabs.SplitGenerator(name=datalabs.Split.TEST, gen_kwargs={"filepath": downloaded_files["test"]}), ] def _generate_examples(self, filepath): """Yields examples.""" # TODO(squad_v2): Yields (key, example) tuples from the dataset with open(filepath, encoding="utf-8") as f: squad = json.load(f) for example in squad["data"]: title = example.get("title", "") for paragraph in example["paragraphs"]: context = paragraph["context"] # do not strip leading blank spaces GH-2585 for qa in paragraph["qas"]: question = qa["question"] id_ = qa["id"] answer_starts = [answer["answer_start"] for answer in qa["answers"]] answers = [answer["text"] for answer in qa["answers"]] # Features currently used are "context", "question", and "answers". # Others are extracted here for the ease of future expansions. yield id_, { "title": title, "context": context, "question": question, "id": id_, "answers": { "answer_start": answer_starts, "text": answers, }, }
xuzhikethinker/t4f-data
structure/core/src/main/java/aos/data/structure/CircularListIterator.java
/**************************************************************** * Licensed to the AOS Community (AOS) under one or more * * contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The AOS 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. * ****************************************************************/ // A private iterator for circular lists. // (c) 1998, 2001 <NAME> package aos.data.structure; /** * An implementation of an iterator over a circular list. * * @version $Id: CircularListIterator.java 31 2007-08-06 17:19:56Z bailey $ * @author, 2001 <NAME> */ class CircularListIterator extends AbstractIterator { /** * The tail of the traversed list. */ protected Node tail; /** * The current value of the iterator. */ protected Node current; /** * Constructs an iterator over circular list whose tail is t * * @pre t is a reference to a circular list element * @post constructs an iterator for traversing circular list * * @param t The tail of the list to be traversed. */ public CircularListIterator(Node t) { tail = t; reset(); } /** * Resets iterator to consider the head of the list. * * @post rests iterator to point to head of list */ public void reset() { if (tail == null) current = null; else current = tail.next(); } /** * Determine if there are unconsidered elements. * * @post returns true if some elements not visited * * @return True iff some element has not been considered. */ public boolean hasNext() { return current != null; } /** * Return the current value and increment iterator. * * @pre hasNext() * @post returns current element, increments iterator * * @return The current value before incrementing. */ public Object next() { Object result = current.value(); if (current == tail) current = null; else current = current.next(); return result; } /** * Determine the current value of iterator. * * @pre hasNext() * @post returns current value * * @return The current value of the iterator. */ public Object get() { return current.value(); } }
echo80313/grpc
src/core/ext/upb-generated/envoy/service/load_stats/v3/lrs.upb.h
/* This file was generated by upbc (the upb compiler) from the input * file: * * envoy/service/load_stats/v3/lrs.proto * * Do not edit -- your changes will be discarded when the file is * regenerated. */ #ifndef ENVOY_SERVICE_LOAD_STATS_V3_LRS_PROTO_UPB_H_ #define ENVOY_SERVICE_LOAD_STATS_V3_LRS_PROTO_UPB_H_ #include "upb/msg_internal.h" #include "upb/decode.h" #include "upb/decode_fast.h" #include "upb/encode.h" #include "upb/port_def.inc" #ifdef __cplusplus extern "C" { #endif struct envoy_service_load_stats_v3_LoadStatsRequest; struct envoy_service_load_stats_v3_LoadStatsResponse; typedef struct envoy_service_load_stats_v3_LoadStatsRequest envoy_service_load_stats_v3_LoadStatsRequest; typedef struct envoy_service_load_stats_v3_LoadStatsResponse envoy_service_load_stats_v3_LoadStatsResponse; extern const upb_MiniTable envoy_service_load_stats_v3_LoadStatsRequest_msginit; extern const upb_MiniTable envoy_service_load_stats_v3_LoadStatsResponse_msginit; struct envoy_config_core_v3_Node; struct envoy_config_endpoint_v3_ClusterStats; struct google_protobuf_Duration; extern const upb_MiniTable envoy_config_core_v3_Node_msginit; extern const upb_MiniTable envoy_config_endpoint_v3_ClusterStats_msginit; extern const upb_MiniTable google_protobuf_Duration_msginit; /* envoy.service.load_stats.v3.LoadStatsRequest */ UPB_INLINE envoy_service_load_stats_v3_LoadStatsRequest* envoy_service_load_stats_v3_LoadStatsRequest_new(upb_Arena* arena) { return (envoy_service_load_stats_v3_LoadStatsRequest*)_upb_Message_New(&envoy_service_load_stats_v3_LoadStatsRequest_msginit, arena); } UPB_INLINE envoy_service_load_stats_v3_LoadStatsRequest* envoy_service_load_stats_v3_LoadStatsRequest_parse(const char* buf, size_t size, upb_Arena* arena) { envoy_service_load_stats_v3_LoadStatsRequest* ret = envoy_service_load_stats_v3_LoadStatsRequest_new(arena); if (!ret) return NULL; if (upb_Decode(buf, size, ret, &envoy_service_load_stats_v3_LoadStatsRequest_msginit, NULL, 0, arena) != kUpb_DecodeStatus_Ok) { return NULL; } return ret; } UPB_INLINE envoy_service_load_stats_v3_LoadStatsRequest* envoy_service_load_stats_v3_LoadStatsRequest_parse_ex(const char* buf, size_t size, const upb_ExtensionRegistry* extreg, int options, upb_Arena* arena) { envoy_service_load_stats_v3_LoadStatsRequest* ret = envoy_service_load_stats_v3_LoadStatsRequest_new(arena); if (!ret) return NULL; if (upb_Decode(buf, size, ret, &envoy_service_load_stats_v3_LoadStatsRequest_msginit, extreg, options, arena) != kUpb_DecodeStatus_Ok) { return NULL; } return ret; } UPB_INLINE char* envoy_service_load_stats_v3_LoadStatsRequest_serialize(const envoy_service_load_stats_v3_LoadStatsRequest* msg, upb_Arena* arena, size_t* len) { return upb_Encode(msg, &envoy_service_load_stats_v3_LoadStatsRequest_msginit, 0, arena, len); } UPB_INLINE char* envoy_service_load_stats_v3_LoadStatsRequest_serialize_ex(const envoy_service_load_stats_v3_LoadStatsRequest* msg, int options, upb_Arena* arena, size_t* len) { return upb_Encode(msg, &envoy_service_load_stats_v3_LoadStatsRequest_msginit, options, arena, len); } UPB_INLINE bool envoy_service_load_stats_v3_LoadStatsRequest_has_node(const envoy_service_load_stats_v3_LoadStatsRequest* msg) { return _upb_hasbit(msg, 1); } UPB_INLINE void envoy_service_load_stats_v3_LoadStatsRequest_clear_node(const envoy_service_load_stats_v3_LoadStatsRequest* msg) { *UPB_PTR_AT(msg, UPB_SIZE(4, 8), const upb_Message*) = NULL; } UPB_INLINE const struct envoy_config_core_v3_Node* envoy_service_load_stats_v3_LoadStatsRequest_node(const envoy_service_load_stats_v3_LoadStatsRequest* msg) { return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), const struct envoy_config_core_v3_Node*); } UPB_INLINE bool envoy_service_load_stats_v3_LoadStatsRequest_has_cluster_stats(const envoy_service_load_stats_v3_LoadStatsRequest* msg) { return _upb_has_submsg_nohasbit(msg, UPB_SIZE(8, 16)); } UPB_INLINE void envoy_service_load_stats_v3_LoadStatsRequest_clear_cluster_stats(const envoy_service_load_stats_v3_LoadStatsRequest* msg) { _upb_array_detach(msg, UPB_SIZE(8, 16)); } UPB_INLINE const struct envoy_config_endpoint_v3_ClusterStats* const* envoy_service_load_stats_v3_LoadStatsRequest_cluster_stats(const envoy_service_load_stats_v3_LoadStatsRequest* msg, size_t* len) { return (const struct envoy_config_endpoint_v3_ClusterStats* const*)_upb_array_accessor(msg, UPB_SIZE(8, 16), len); } UPB_INLINE void envoy_service_load_stats_v3_LoadStatsRequest_set_node(envoy_service_load_stats_v3_LoadStatsRequest *msg, struct envoy_config_core_v3_Node* value) { _upb_sethas(msg, 1); *UPB_PTR_AT(msg, UPB_SIZE(4, 8), struct envoy_config_core_v3_Node*) = value; } UPB_INLINE struct envoy_config_core_v3_Node* envoy_service_load_stats_v3_LoadStatsRequest_mutable_node(envoy_service_load_stats_v3_LoadStatsRequest* msg, upb_Arena* arena) { struct envoy_config_core_v3_Node* sub = (struct envoy_config_core_v3_Node*)envoy_service_load_stats_v3_LoadStatsRequest_node(msg); if (sub == NULL) { sub = (struct envoy_config_core_v3_Node*)_upb_Message_New(&envoy_config_core_v3_Node_msginit, arena); if (!sub) return NULL; envoy_service_load_stats_v3_LoadStatsRequest_set_node(msg, sub); } return sub; } UPB_INLINE struct envoy_config_endpoint_v3_ClusterStats** envoy_service_load_stats_v3_LoadStatsRequest_mutable_cluster_stats(envoy_service_load_stats_v3_LoadStatsRequest* msg, size_t* len) { return (struct envoy_config_endpoint_v3_ClusterStats**)_upb_array_mutable_accessor(msg, UPB_SIZE(8, 16), len); } UPB_INLINE struct envoy_config_endpoint_v3_ClusterStats** envoy_service_load_stats_v3_LoadStatsRequest_resize_cluster_stats(envoy_service_load_stats_v3_LoadStatsRequest* msg, size_t len, upb_Arena* arena) { return (struct envoy_config_endpoint_v3_ClusterStats**)_upb_Array_Resize_accessor2(msg, UPB_SIZE(8, 16), len, UPB_SIZE(2, 3), arena); } UPB_INLINE struct envoy_config_endpoint_v3_ClusterStats* envoy_service_load_stats_v3_LoadStatsRequest_add_cluster_stats(envoy_service_load_stats_v3_LoadStatsRequest* msg, upb_Arena* arena) { struct envoy_config_endpoint_v3_ClusterStats* sub = (struct envoy_config_endpoint_v3_ClusterStats*)_upb_Message_New(&envoy_config_endpoint_v3_ClusterStats_msginit, arena); bool ok = _upb_Array_Append_accessor2(msg, UPB_SIZE(8, 16), UPB_SIZE(2, 3), &sub, arena); if (!ok) return NULL; return sub; } /* envoy.service.load_stats.v3.LoadStatsResponse */ UPB_INLINE envoy_service_load_stats_v3_LoadStatsResponse* envoy_service_load_stats_v3_LoadStatsResponse_new(upb_Arena* arena) { return (envoy_service_load_stats_v3_LoadStatsResponse*)_upb_Message_New(&envoy_service_load_stats_v3_LoadStatsResponse_msginit, arena); } UPB_INLINE envoy_service_load_stats_v3_LoadStatsResponse* envoy_service_load_stats_v3_LoadStatsResponse_parse(const char* buf, size_t size, upb_Arena* arena) { envoy_service_load_stats_v3_LoadStatsResponse* ret = envoy_service_load_stats_v3_LoadStatsResponse_new(arena); if (!ret) return NULL; if (upb_Decode(buf, size, ret, &envoy_service_load_stats_v3_LoadStatsResponse_msginit, NULL, 0, arena) != kUpb_DecodeStatus_Ok) { return NULL; } return ret; } UPB_INLINE envoy_service_load_stats_v3_LoadStatsResponse* envoy_service_load_stats_v3_LoadStatsResponse_parse_ex(const char* buf, size_t size, const upb_ExtensionRegistry* extreg, int options, upb_Arena* arena) { envoy_service_load_stats_v3_LoadStatsResponse* ret = envoy_service_load_stats_v3_LoadStatsResponse_new(arena); if (!ret) return NULL; if (upb_Decode(buf, size, ret, &envoy_service_load_stats_v3_LoadStatsResponse_msginit, extreg, options, arena) != kUpb_DecodeStatus_Ok) { return NULL; } return ret; } UPB_INLINE char* envoy_service_load_stats_v3_LoadStatsResponse_serialize(const envoy_service_load_stats_v3_LoadStatsResponse* msg, upb_Arena* arena, size_t* len) { return upb_Encode(msg, &envoy_service_load_stats_v3_LoadStatsResponse_msginit, 0, arena, len); } UPB_INLINE char* envoy_service_load_stats_v3_LoadStatsResponse_serialize_ex(const envoy_service_load_stats_v3_LoadStatsResponse* msg, int options, upb_Arena* arena, size_t* len) { return upb_Encode(msg, &envoy_service_load_stats_v3_LoadStatsResponse_msginit, options, arena, len); } UPB_INLINE void envoy_service_load_stats_v3_LoadStatsResponse_clear_clusters(const envoy_service_load_stats_v3_LoadStatsResponse* msg) { _upb_array_detach(msg, UPB_SIZE(4, 8)); } UPB_INLINE upb_StringView const* envoy_service_load_stats_v3_LoadStatsResponse_clusters(const envoy_service_load_stats_v3_LoadStatsResponse* msg, size_t* len) { return (upb_StringView const*)_upb_array_accessor(msg, UPB_SIZE(4, 8), len); } UPB_INLINE bool envoy_service_load_stats_v3_LoadStatsResponse_has_load_reporting_interval(const envoy_service_load_stats_v3_LoadStatsResponse* msg) { return _upb_hasbit(msg, 1); } UPB_INLINE void envoy_service_load_stats_v3_LoadStatsResponse_clear_load_reporting_interval(const envoy_service_load_stats_v3_LoadStatsResponse* msg) { *UPB_PTR_AT(msg, UPB_SIZE(8, 16), const upb_Message*) = NULL; } UPB_INLINE const struct google_protobuf_Duration* envoy_service_load_stats_v3_LoadStatsResponse_load_reporting_interval(const envoy_service_load_stats_v3_LoadStatsResponse* msg) { return *UPB_PTR_AT(msg, UPB_SIZE(8, 16), const struct google_protobuf_Duration*); } UPB_INLINE void envoy_service_load_stats_v3_LoadStatsResponse_clear_report_endpoint_granularity(const envoy_service_load_stats_v3_LoadStatsResponse* msg) { *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = 0; } UPB_INLINE bool envoy_service_load_stats_v3_LoadStatsResponse_report_endpoint_granularity(const envoy_service_load_stats_v3_LoadStatsResponse* msg) { return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool); } UPB_INLINE void envoy_service_load_stats_v3_LoadStatsResponse_clear_send_all_clusters(const envoy_service_load_stats_v3_LoadStatsResponse* msg) { *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool) = 0; } UPB_INLINE bool envoy_service_load_stats_v3_LoadStatsResponse_send_all_clusters(const envoy_service_load_stats_v3_LoadStatsResponse* msg) { return *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool); } UPB_INLINE upb_StringView* envoy_service_load_stats_v3_LoadStatsResponse_mutable_clusters(envoy_service_load_stats_v3_LoadStatsResponse* msg, size_t* len) { return (upb_StringView*)_upb_array_mutable_accessor(msg, UPB_SIZE(4, 8), len); } UPB_INLINE upb_StringView* envoy_service_load_stats_v3_LoadStatsResponse_resize_clusters(envoy_service_load_stats_v3_LoadStatsResponse* msg, size_t len, upb_Arena* arena) { return (upb_StringView*)_upb_Array_Resize_accessor2(msg, UPB_SIZE(4, 8), len, UPB_SIZE(3, 4), arena); } UPB_INLINE bool envoy_service_load_stats_v3_LoadStatsResponse_add_clusters(envoy_service_load_stats_v3_LoadStatsResponse* msg, upb_StringView val, upb_Arena* arena) { return _upb_Array_Append_accessor2(msg, UPB_SIZE(4, 8), UPB_SIZE(3, 4), &val, arena); } UPB_INLINE void envoy_service_load_stats_v3_LoadStatsResponse_set_load_reporting_interval(envoy_service_load_stats_v3_LoadStatsResponse *msg, struct google_protobuf_Duration* value) { _upb_sethas(msg, 1); *UPB_PTR_AT(msg, UPB_SIZE(8, 16), struct google_protobuf_Duration*) = value; } UPB_INLINE struct google_protobuf_Duration* envoy_service_load_stats_v3_LoadStatsResponse_mutable_load_reporting_interval(envoy_service_load_stats_v3_LoadStatsResponse* msg, upb_Arena* arena) { struct google_protobuf_Duration* sub = (struct google_protobuf_Duration*)envoy_service_load_stats_v3_LoadStatsResponse_load_reporting_interval(msg); if (sub == NULL) { sub = (struct google_protobuf_Duration*)_upb_Message_New(&google_protobuf_Duration_msginit, arena); if (!sub) return NULL; envoy_service_load_stats_v3_LoadStatsResponse_set_load_reporting_interval(msg, sub); } return sub; } UPB_INLINE void envoy_service_load_stats_v3_LoadStatsResponse_set_report_endpoint_granularity(envoy_service_load_stats_v3_LoadStatsResponse *msg, bool value) { *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value; } UPB_INLINE void envoy_service_load_stats_v3_LoadStatsResponse_set_send_all_clusters(envoy_service_load_stats_v3_LoadStatsResponse *msg, bool value) { *UPB_PTR_AT(msg, UPB_SIZE(2, 2), bool) = value; } extern const upb_MiniTable_File envoy_service_load_stats_v3_lrs_proto_upb_file_layout; #ifdef __cplusplus } /* extern "C" */ #endif #include "upb/port_undef.inc" #endif /* ENVOY_SERVICE_LOAD_STATS_V3_LRS_PROTO_UPB_H_ */
Gaia3D/F4DConverter
F4DConverter/converter/util/utility.h
#pragma once #include <vector> #define M_PI 3.14159265358979323846 namespace gaia3d { class GeometryUtility { public: ///< 점 3개로 이루어진 평면의 normal vector를 계산 static void calculatePlaneNormal(double& x0, double& y0, double& z0, double& x1, double& y1, double& z1, double& x2, double& y2, double& z2, double& nX, double& nY, double& nZ, bool bNormalize); static void crossProduct(double x0, double y0, double z0, double x1, double y1, double z1, double& nX, double& nY, double& nZ); enum GeomType {POLYHEDRON, TRIANGLE, POINT}; static bool areTwoCongruentWithEachOther(void* geom1, void* geom2, void* transform, double tolerance, GeomType geomType); static double angleBetweenTwoVectors(double x1, double y1, double z1, double x2, double y2, double z2); static bool isInsideBox(double x, double y, double z, double minX, double minY, double minZ, double maxX, double maxY, double maxZ); static bool doesTriangleIntersectWithBox(double& x1, double& y1, double& z1, double& x2, double& y2, double& z2, double& x3, double& y3, double& z3, double& minX, double& minY, double& minZ, double& maxX, double& maxY, double& maxZ); static void wgs84ToAbsolutePosition(double&lon, double& lat, double& alt, double* result); static void normalAtAbsolutePosition(double& x, double& y, double& z, double* result); static void transformMatrixAtAbsolutePosition(double& x, double& y, double& z, double* m); static bool earCut(double** xs, double** ys, double** zs, std::vector<size_t>& eachRingPointCount, std::vector<std::pair<size_t, size_t>>& result, bool bDebug = false); static void tessellate(double* xs, double* ys, double* zs, size_t vertexCount, std::vector<size_t>& polygonIndices, std::vector<size_t>& indices); }; class StringUtility { public: static std::string convertWideStringToUtf8(std::wstring& sourceString); static std::wstring convertUtf8ToWideString(std::string& sourceString); #ifdef _WIN32 static std::string convertMultibyteToUtf8(std::string& sourceString); #endif }; class ImageUtility { public: static void writeMemoryImageToFile(unsigned char* buffer, int width, int height, const char* fullPath); }; }
altshiftcreative/checkout-sdk-java
src/main/java/com/checkout/workflows/four/conditions/response/EntityWorkflowConditionResponse.java
package com.checkout.workflows.four.conditions.response; import com.checkout.workflows.four.conditions.WorkflowConditionType; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.util.List; @Getter @Setter @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public final class EntityWorkflowConditionResponse extends WorkflowConditionResponse { private List<String> entities; public EntityWorkflowConditionResponse() { super(WorkflowConditionType.ENTITY); } }
ckamtsikis/cmssw
PhysicsTools/TagAndProbe/test/utilities/RooPowLaw.cxx
<reponame>ckamtsikis/cmssw /***************************************************************************** * Project: RooFit * * * * Copyright (c) 2000-2005, Regents of the University of California * * and Stanford University. All rights reserved. * * * * Redistribution and use in source and binary forms, * * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ // -- CLASS DESCRIPTION [PDF] -- // Your description goes here... #include "Riostream.h" #include "RooPowLaw.h" #include "RooAbsReal.h" #include "RooAbsCategory.h" ClassImp(RooPowLaw); RooPowLaw::RooPowLaw(const char *name, const char *title, RooAbsReal& _m, RooAbsReal& _alpha ) : RooAbsPdf(name,title), m("m","m",this,_m), alpha(" alpha"," alpha",this,_alpha) { } RooPowLaw::RooPowLaw(const RooPowLaw& other, const char* name) : RooAbsPdf(other,name), m("m",this,other.m), alpha(" alpha",this,other. alpha) { } Double_t RooPowLaw::evaluate() const { // ENTER EXPRESSION IN TERMS OF VARIABLE ARGUMENTS HERE if(m <= 0.0 ){ return 1000.0; } else{ return TMath::Power(m, alpha); } }
leewcc/gduthacker
src/com/hackerspace/model/ClassroomApply.java
package com.hackerspace.model; import java.sql.Date; import java.sql.Timestamp; import java.text.ParseException; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import com.hackerspace.util.TimeParseUtil; /** * Created by tianx on 2016/2/29. */ @Entity @Table(name = "t_classroom_apply") public class ClassroomApply { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Basic @Column(name = "team",columnDefinition="varchar(100) default ''") private String team; @Basic @Column(name = "classroom_status",columnDefinition="int(11) default -1") private int status; //1-早上 2-下午 3-晚上 4-全天 @Basic @Column(name = "classroom_apply_date",columnDefinition="datetime default '0000-00-00 00:00:00'") private Date date; //申请日期 @Basic @Column(name = "classroom_isopen",columnDefinition="bit default 0") private byte classroomIsOpen; @Column(name="classroom_user" , columnDefinition="varchar(50) default ''") private String user; //申请人名字 @Column(name="classroom_contact" , columnDefinition="varchar(50) default ''") private String contact; //申请人联系方式 @Column(name ="classroom_ispass" , columnDefinition="tinyint default -2") private Integer isPass; // -1: 未处理; 0: 未通过; 1: 已通过 @Column(name="classroom_reason" , columnDefinition="varchar(400) default ''") private String reason; @Column(name="post_time", columnDefinition="datetime default '2016-01-01 00:00:00'") private Timestamp postTime; @Transient private String position; @Transient private String number; // 申请课室号 @ManyToOne @JoinColumn(name="classroom_id", referencedColumnName="id") private Classroom classroom; public ClassroomApply() { } public ClassroomApply(Integer id, String user, String team, Object date, Integer status, Classroom classroom, Object postTime, Integer isPass) { this.id = id; this.user = user; this.team = team; this.date = (Date)date; this.status = status; this.classroom = classroom; this.postTime = (Timestamp) postTime; this.isPass = isPass; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void setNumber(String number) { this.number = number; } public String getNumber() { return number; } public void setPosition(String position) { this.position = position; } public String getPosition() { return position; } public void setPostTime(Timestamp postTime) { this.postTime = postTime; } public Timestamp getPostTime() { return postTime; } public String getTeam() { return team; } public void setTeam(String team) { this.team = team; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public void setStatus(String status) throws NumberFormatException{ this.status = Integer.valueOf(status); } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public void setDate(String date) throws ParseException { this.date = TimeParseUtil.StringtoDate(date); } public byte getClassroomIsOpen() { return classroomIsOpen; } public void setClassroomIsOpen(byte classroomIsOpen) { this.classroomIsOpen = classroomIsOpen; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public Integer isPass() { return isPass; } public void setPass(Integer isPass) { this.isPass = isPass; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public Classroom getClassroom() { return classroom; } public void setClassroom(Classroom classroom) { this.classroom = classroom; } }
Brimes7/Synaps-FE
src/components/Uploader/Uploader.js
import React, {useEffect, useState} from 'react'; import styled from 'styled-components'; import {message, Upload} from 'antd'; import {uploadImage} from '../../actions/photo'; import {UploadIcon} from './UploadIcon.js'; import * as PropTypes from 'prop-types'; import {useAppHooks} from '../../customHooks/useAppHooks.js'; /** * Image Uploader * @component * @example * return ( * <Uploader id={"1"} /> * ) */ export const Uploader = props => { /** * @type PhotoReducerState */ const {photosState, usersState, dispatch} = useAppHooks('Uploader'); const [photoObject, setPhotoObject] = useState(false); useEffect(() => { Object.values(photosState.photos).forEach(photoObject => { if (photoObject.id === props.id) { setPhotoObject(photoObject); } }); }, [photosState, props.id]); const customRequest = file => { file.id = props.id; dispatch(uploadImage(file)); }; const getUrl = () => { if (photoObject) { if (photoObject.file.uid) { if (photoObject.file.type && photoObject.file.type.includes('png')) { photoObject.file.uid += '.png'; } else if (photoObject.file.type && photoObject.file.type.includes('jpg')) { photoObject.file.uid += '.jpg'; } return ( 'https://res.cloudinary.com/www-synapsapp-com/image/upload/v1582468332/' + photoObject.file.uid ); } } return undefined; }; const loadImage = photoObject && photoObject.file && photoObject.file.uid; return ( <div data-testid="upload"> <StyledUpload name="file" listType="picture-card" showUploadList={false} beforeUpload={beforeUpload} customRequest={customRequest} > {loadImage ? ( <img src={getUrl()} alt="card-image" style={{width: '100%'}} data-testid="upload-image" /> ) : ( <UploadIcon/> )} </StyledUpload> </div> ); }; Uploader.propTypes = { id: PropTypes.string, }; const StyledUpload = styled(Upload)` && { > .ant-upload.ant-upload-select-picture-card { border: none; background-color: transparent; width: 67px; height: 59px; } } `; function beforeUpload (file) { const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'; if (!isJpgOrPng) { message.error('You can only upload JPG/PNG file!'); } const isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { message.error('Image must smaller than 2MB!'); } return isJpgOrPng && isLt2M; }
iansjk/akdata
_docs/test.js
<reponame>iansjk/akdata // UA test let ua = navigator.userAgent; document.getElementById("user_agent").innerText = ua; $("#jquery").text($.fn.jquery); $("#vue").html("Vue: {{ error }} <br> <div v-html='content' class='row'></div> <br> {{ char }}"); let vue_app = new Vue({ el: "#vue", data: { error: Vue.version, content: "test content", char: "" } }); // AKDATA load test function init() { AKDATA.load([ 'excel/character_table.json', 'excel/skill_table.json', 'excel/char_patch_table.json', 'excel/skill_table.json', '../version.json', '../customdata/dps_specialtags_v2.json', '../customdata/dps_options.json', '../resources/dps_actions.js', '../resources/dpsv2.js', //'../resources/attributes.js' ], load); } function load() { AKDATA.patchAllChars(); //test_dps_all(); //find_skills(x => x.indexOf("instant") >= 0); AKDATA.showSelectCharDialog(); AKDATA.selectCharCallback = function (id) { vue_app.char = id; }; } pmBase.hook.on('init', init); function card(title, str) { return ` <div class="card col-3"> <div class="card-header"> <div class="card-title mb-0">${title}</div> </div> ${str} </div>`; } // dpsv2 test function test_dps() { var ch = "char_126_shotst"; var sk = 'skchr_shotst_1'; var options = { cond: true }; var dps = new AKDATA.Dps.DpsCalculator(); var char = { charId: ch, skillId: sk, options }; var enemy = { def: 200, magicResistance: 20, count: 1 }; vue_app.content = ""; console.log (`-- ${ch} - ${sk}`); dps.calculateDps(char, enemy); vue_app.content += card(`${ch} - ${sk}`, "<pre>" + JSON.stringify(dps.summary, null, 2) + "</pre>"); } function test_dps_all() { vue_app.content = ""; Object.keys(AKDATA.Data.character_table).forEach(ch => { var charData = AKDATA.Data.character_table[ch]; charData.skills.map(x => x.skillId).forEach(sk => { var options = { cond: true }; var char = { charId: ch, skillId: sk, options }; var enemy = { def: 200, magicResistance: 20, count: 1 }; var dps = new AKDATA.Dps.DpsCalculator(); if (ch.startsWith("char")) { console.log (`-- ${ch} - ${sk}`); dps.calculateDps(char, enemy); vue_app.content += card(`${ch} - ${sk}`, "<pre>" + JSON.stringify(dps.summary, null, 2) + "</pre>"); } }); }); } function find_skills(filter) { var results = []; Object.keys(AKDATA.Data.character_table).forEach(ch => { var charData = AKDATA.Data.character_table[ch]; charData.skills.map(x => x.skillId).forEach(sk => { var skillData = AKDATA.Data.skill_table[sk]; var char = { charId: ch, skillId: sk, skillLevel: 0 }; try { var result = AKDATA.attributes.calculateDps(char, null, null).skill; var tag = result.dur.tags; if (filter(tag)) results.push({ charId: ch, skillId: sk, name: charData.name, skillName: skillData.levels[0].name }); } catch { console.log("Error ->", charData.name, sk); } }); }); //vue_app.content = JSON.stringify(results).replace(new RegExp('\n', "g"), "<br>"); var lines = ["charId, charName, skillId, skillName"]; results.forEach(x => { lines.push([x.charId, x.name, x.skillId, x.skillName].join(', ')); }); vue_app.content = lines.join("<br>"); }
sechel/jtem-halfedgetools
src/de/jtem/halfedgetools/plugin/image/ImageHook.java
package de.jtem.halfedgetools.plugin.image; import static java.awt.Image.SCALE_SMOOTH; import static java.awt.image.BufferedImage.TYPE_INT_ARGB; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.Icon; import javax.swing.ImageIcon; import de.jreality.util.LoggingSystem; /** * An image loader for jar files * <p> * Copyright 2005 <a href="http://www.sechel.de"><NAME></a> * <a href="http://www.math.tu-berlin.de/geometrie">TU-Berlin</a> * @author <NAME> */ public class ImageHook { private static Logger log = LoggingSystem.getLogger(ImageHook.class); public static Image getImage(String filename){ InputStream in = ImageHook.class.getResourceAsStream(filename); if (in == null) return null; Image result = null; try { result = ImageIO.read(in); } catch (IOException e) { log.warning(e.getLocalizedMessage()); } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return result; } public static Image getImage(String filename, int width, int height) { Image image = getImage(filename); if (image == null) { return null; } else { return image.getScaledInstance(width, height, SCALE_SMOOTH); } } public static Icon getIcon(String filename) { Image image = getImage(filename); if (image == null) { return null; } else { return new ImageIcon(image); } } public static Icon getIcon(String filename, int width, int height) { Image image = getImage(filename, width, height); if (image == null) { return null; } else { return new ImageIcon(image); } } public static Image renderIcon(Icon icon) { BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconWidth(), TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); icon.paintIcon(null, g, 0, 0); return image; } public static Icon scaleIcon(Icon icon, int width, int height) { Image imageNewSize = null; if (icon instanceof ImageIcon) { ImageIcon imageIcon = (ImageIcon)icon; imageNewSize = imageIcon.getImage().getScaledInstance(width, height, SCALE_SMOOTH); } else { Image image = renderIcon(icon); imageNewSize = scaleImage(image, width, height); } return new ImageIcon(imageNewSize); } public static Image scaleImage(Image image, int width, int height) { return image.getScaledInstance(width, height, SCALE_SMOOTH); } }
GrowMoi/haedus
app/controllers/api/users/storages_controller.rb
<filename>app/controllers/api/users/storages_controller.rb module Api module Users class StoragesController < BaseController before_action :authenticate_user! respond_to :json api :PUT, "/users/storages", "update user data" param :frontendValues, String, required: true, desc: %{ needs to be a JSON-encoded string having the following format: { "tree":{ "advices": 1 "vinetas": 1 } } } def update storageData = JSON.parse(params[:frontendValues]) if !storageData.empty? current_user.update_storage(storageData) render nothing: true, status: :accepted else render nothing: true, status: :unprocessable_entity end end api :GET, "/users/storages", "show user data" def show respond_with(storage: current_user.storage ? current_user.storage.frontendValues: {}) end end end end
abfeldman/lydia
tools/cnf2dimacs/pp.c
#include <assert.h> #include <string.h> #include "pp_variable.h" #include "tv.h" static void pp_clause_list(FILE *fp, const_tv_clause_list clauses, const_variable_list variables) { unsigned int ix, iy; for (ix = 0; ix < variables->sz; ix++) { fprintf(fp, "c variable %d: ", ix + 1); pp_variable_name(fp, variables->arr[ix]->name); fprintf(fp, "\n"); } fprintf(fp, "p cnf %d %d\n", variables->sz, clauses->sz); for (ix = 0; ix < clauses->sz; ix++) { const_int_list pos = clauses->arr[ix]->pos; const_int_list neg = clauses->arr[ix]->neg; int first = 1; for (iy = 0; iy < pos->sz; iy++) { if (!first) { fprintf(fp, " "); } else { first = 0; } fprintf(fp, "%d", pos->arr[iy] + 1); } for (iy = 0; iy < neg->sz; iy++) { if (!first) { fprintf(fp, " "); } else { first = 0; } fprintf(fp, "-%d", neg->arr[iy] + 1); } if (!first) { fprintf(fp, " "); } fprintf(fp, "%d\n", 0); } } void pp_cnf(FILE *fp, const_tv_cnf cnf) { pp_clause_list(fp, cnf->clauses, cnf->variables); }
ZhouGuixin/CicadaPlayer
framework/base/media/PBAFFrame.cpp
// // Created by moqi on 2019-08-28. // #include "PBAFFrame.h" extern "C" { #include <libavutil/frame.h> #include <libavutil/imgutils.h> } PBAFFrame::operator AVAFFrame *() { CVReturn err; uint8_t *data[4] = {nullptr}; int linesize[4] = {0}; int planes, ret, i; OSType pixel_format = CVPixelBufferGetPixelFormatType(mPBuffer); if (pixel_format != kCVPixelFormatType_420YpCbCr8Planar) return nullptr; AVFrame *pFrame = av_frame_alloc(); pFrame->format = AV_PIX_FMT_YUV420P; pFrame->width = (int) CVPixelBufferGetWidth(mPBuffer); pFrame->height = (int) CVPixelBufferGetHeight(mPBuffer); ret = av_frame_get_buffer(pFrame, 32); if (ret < 0) { av_frame_free(&pFrame); return nullptr; } err = CVPixelBufferLockBaseAddress(mPBuffer, kCVPixelBufferLock_ReadOnly); if (err != kCVReturnSuccess) { av_frame_free(&pFrame); return nullptr; } if (CVPixelBufferIsPlanar(mPBuffer)) { planes = (int)CVPixelBufferGetPlaneCount(mPBuffer); for (i = 0; i < planes; i++) { data[i] = static_cast<uint8_t *>(CVPixelBufferGetBaseAddressOfPlane(mPBuffer, i)); linesize[i] = (int)CVPixelBufferGetBytesPerRowOfPlane(mPBuffer, i); } } else { data[0] = static_cast<uint8_t *>(CVPixelBufferGetBaseAddress(mPBuffer)); linesize[0] = (int)CVPixelBufferGetBytesPerRow(mPBuffer); } av_image_copy(pFrame->data, pFrame->linesize, (const uint8_t **) data, linesize, static_cast<AVPixelFormat>(pFrame->format), pFrame->width, pFrame->height); CVPixelBufferUnlockBaseAddress(mPBuffer, kCVPixelBufferLock_ReadOnly); pFrame->pts = mInfo.pts; AVAFFrame *pAvFrame = new AVAFFrame(pFrame, FrameTypeVideo); av_frame_free(&pFrame); return pAvFrame; }
oldDing666/BiShiLianXi
src/JZOffer_v1/T_14_1.java
<filename>src/JZOffer_v1/T_14_1.java package JZOffer_v1; /** * @author: afuya * @program: BiShiLianXi * @date: 2021/9/15 4:19 下午 */ public class T_14_1 { public int cuttingRope(int n) { if (n == 2) return 1; else if (n == 3) return 2; int n1 = n % 3; int n2 = n / 3; int sum = 1; if (n1 == 0) { for (int i = 0; i < n2; i++) { sum *= 3; } } else if (n1 == 2) { for (int i = 0; i < n2; i++) { sum *= 3; } sum *= 2; } else if (n1 == 1) { for (int i = 0; i < n2 - 1; i++) { sum *= 3; } sum *= 4; } return sum; } }
svvsdIC/Poseidon-raspberryPi
src/plugins/input-configurator/public/js/input-configurator-widgets-autodiscovery.js
/* Running this within a function prevents leaking variables in to the global namespace. */ (function(window) { 'use strict'; var widgets = namespace('widgets'); widgets['orov-input-configurator'] = { name:'orov-input-configurator', defaultUISymantic: 'multipurpose-display', url: 'input-configurator/orov-input-configurator.html' }; } // The line below both ends the anonymous function and then calls // it passing in the required depenencies. )(window);
codejyhuang/huang
hrym-app/hrym-app-dao/src/main/java/com/hrym/rpc/auth/dao/mapper/lesson/TaskAreaLessonMapper.java
package com.hrym.rpc.auth.dao.mapper.lesson; import com.hrym.common.annotation.DataSource; import com.hrym.rpc.app.dao.model.VO.lessonVO.TaskAreaLessonVO; import org.apache.ibatis.annotations.Select; import java.util.List; /** * Created by hrym13 on 2018/6/25. * 推荐功课 */ public interface TaskAreaLessonMapper { /** * 推荐功课列表 * @param areaType * @return */ @DataSource("slave") @Select(" SELECT a.create_time,a.area_id,a.title_name,a.item_id,a.area_type,a.title_desc,a.article_url,a.update_time,n.online_num,n.order_num,n.item_pic FROM t_resource_area a \n" + " LEFT JOIN t_resource_item_lesson n ON n.item_id=a.item_id \n" + " WHERE a.area_type = #{areaType} ") List<TaskAreaLessonVO> findTaskAreaLessonByAreaType(Integer areaType); }
Chronotron/chaos-beast
CS219/src/PolyMorphismDiscussion.java
import java.util.ArrayList; /*************************************************** * PolymorphismDiscussion.java * <NAME> * <p> * Demonstrates the concept of Polymorphism ****************************************************/ public class PolyMorphismDiscussion { public static void main(String[] args) { NullPlumbus nullPlumbus = new NullPlumbus(); // standard null plumbus created as such IPlumbus nameBrandPlumbus = new NameBrandPlumbus("The Original Plumbus", 5.99); // plumbus interface created as a NameBrandPlumbus NullPlumbus offBrandPlumbus = new OffBrandPlumbus(); // a null plubmus created as an off brand plumbus ArrayList<IPlumbus> plumbuses = new ArrayList<IPlumbus>(); // collection of the plumbus interface // add all plumbuses to the array plumbuses.add(nullPlumbus); plumbuses.add(nameBrandPlumbus); plumbuses.add(offBrandPlumbus); for (IPlumbus plumbus : plumbuses) { System.out.println("Plumbus Diagnostic"); System.out.println("**************************"); String name = plumbus.getBrandName() != null ? plumbus.getBrandName() : "<NONE>"; double plumbusRatio = plumbus.getPlumbusRatio(); System.out.printf("Brand name: %s%n", name); System.out.printf("Price: %.2f%n", plumbus.getPrice()); System.out.printf("Plumbus ratio: %.2f%n", plumbusRatio); if (plumbusRatio >= 90.00) { System.out.println("This is a true plumbus"); } else if (plumbus instanceof NullPlumbus) { System.out.println("We've found a null plumbus"); } System.out.println("**************************"); System.out.println(""); } } }
insertish/ppa-cw3
src/main/java/gay/oss/cw3/renderer/shaders/LevelOfDetail.java
<reponame>insertish/ppa-cw3<filename>src/main/java/gay/oss/cw3/renderer/shaders/LevelOfDetail.java package gay.oss.cw3.renderer.shaders; /** * Enumeration representing the level of detail to render a model at. * * @author <NAME> (K21002534) * @author <NAME> (K21003008) */ public enum LevelOfDetail { High(20), Medium(70), Low(250), DoNotRender(0); int maximumDistance; /** * Construct new LevelOfDetail * @param maximumDistance Maximum distance that models are rendered at this LOD for */ private LevelOfDetail(int maximumDistance) { this.maximumDistance = maximumDistance; } /** * Get the maximum distance that models are rendered at this LOD for * @return Maximum Distance */ public int getMinimumDistance() { return this.maximumDistance; } /** * Natural ordering of detail levels */ public static final LevelOfDetail[] ORDERING = new LevelOfDetail[] { High, Medium, Low }; /** * Convert a given distance to a Level of Detail * @param distance Distance * @return Level of Detail to use */ public static LevelOfDetail fromDistance(int distance) { for (LevelOfDetail lod : ORDERING) { if (distance < lod.maximumDistance) { return lod; } } return DoNotRender; } }
guozimao/maoziguo-system
ruoyi-system/src/main/java/com/ruoyi/groupcompany/service/impl/DtBusinessTaskServiceImpl.java
<filename>ruoyi-system/src/main/java/com/ruoyi/groupcompany/service/impl/DtBusinessTaskServiceImpl.java<gh_stars>1-10 package com.ruoyi.groupcompany.service.impl; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.*; import com.ruoyi.businessteam.domain.MerchantShopRelation; import com.ruoyi.businessteam.mapper.DtSalesmanMapper; import com.ruoyi.common.exception.BusinessException; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.oss.OssClientUtils; import com.ruoyi.groupcompany.domain.reponse.DtGroupBusinessTaskDetailRespDto; import com.ruoyi.groupcompany.domain.reponse.DtGroupBusinessTaskRespDto; import com.ruoyi.groupcompany.domain.request.AssginReqDto; import com.ruoyi.groupcompany.domain.request.DtGroupBusinessTaskReqDto; import com.ruoyi.system.domain.SysDept; import com.ruoyi.system.domain.SysUser; import com.ruoyi.system.mapper.DtMerchantMapper; import com.ruoyi.system.mapper.SysDeptMapper; import com.ruoyi.system.mapper.SysUserMapper; import org.apache.commons.collections4.MultiValuedMap; import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.stream.Collectors; import com.ruoyi.common.utils.StringUtils; import org.springframework.transaction.annotation.Transactional; import com.ruoyi.groupcompany.domain.DtBusinessTaskDetail; import com.ruoyi.groupcompany.mapper.DtBusinessTaskMapper; import com.ruoyi.groupcompany.domain.DtBusinessTask; import com.ruoyi.groupcompany.service.IDtBusinessTaskService; import com.ruoyi.common.core.text.Convert; /** * 商业任务信息Service业务层处理 * * @author zimao * @date 2020-08-27 */ @Service public class DtBusinessTaskServiceImpl implements IDtBusinessTaskService { private static final Logger log = LoggerFactory.getLogger(DtBusinessTaskServiceImpl.class); @Autowired private DtBusinessTaskMapper dtBusinessTaskMapper; @Autowired private SysDeptMapper sysDeptMapper; @Autowired private DtSalesmanMapper dtSalesmanMapper; @Autowired private SysUserMapper sysUserMapper; @Autowired private DtMerchantMapper dtMerchantMapper; /** * 查询商业任务信息 * * @param id 商业任务信息ID * @return 商业任务信息 */ @Override public DtBusinessTask selectDtBusinessTaskById(Long id) { DtBusinessTask dtBusinessTask = dtBusinessTaskMapper.selectDtBusinessTaskById(id); doProcessUrl4BusinessTask(dtBusinessTask); return dtBusinessTask; } private void doProcessUrl4BusinessTask(DtBusinessTask dtBusinessTask) { if(StringUtils.isNotEmpty(dtBusinessTask.getFeedbackPictureUrl1())){ dtBusinessTask.setFeedbackPictureUrl1(OssClientUtils.getPictureUrlByOssParam(dtBusinessTask.getFeedbackPictureUrl1())); } if(StringUtils.isNotEmpty(dtBusinessTask.getFeedbackPictureUrl2())){ dtBusinessTask.setFeedbackPictureUrl2(OssClientUtils.getPictureUrlByOssParam(dtBusinessTask.getFeedbackPictureUrl2())); } if(StringUtils.isNotEmpty(dtBusinessTask.getFeedbackPictureUrl3())){ dtBusinessTask.setFeedbackPictureUrl3(OssClientUtils.getPictureUrlByOssParam(dtBusinessTask.getFeedbackPictureUrl3())); } if(StringUtils.isNotEmpty(dtBusinessTask.getFeedbackPictureUrl4())){ dtBusinessTask.setFeedbackPictureUrl4(OssClientUtils.getPictureUrlByOssParam(dtBusinessTask.getFeedbackPictureUrl4())); } if(StringUtils.isNotEmpty(dtBusinessTask.getFeedbackPictureUrl5())){ dtBusinessTask.setFeedbackPictureUrl5(OssClientUtils.getPictureUrlByOssParam(dtBusinessTask.getFeedbackPictureUrl5())); } } @Override public List<DtBusinessTask> selectDtBusinessTaskList(DtBusinessTask dtBusinessTask) { return dtBusinessTaskMapper.selectDtBusinessTaskList(dtBusinessTask); } /** * 查询商业任务信息列表 * * @param dtGroupBusinessTaskReqDto 商业任务信息 * @return 商业任务信息 */ @Override public List<DtGroupBusinessTaskRespDto> selectGroupDtBusinessTaskDtoList(DtGroupBusinessTaskReqDto dtGroupBusinessTaskReqDto) { List<DtGroupBusinessTaskRespDto> resultList = dtBusinessTaskMapper.selectGroupDtBusinessTaskDtoList(dtGroupBusinessTaskReqDto); doProcessDetail4GroupBusinessTaskRespDto(resultList); List<Long> deptIds = resultList.stream().map(DtGroupBusinessTaskRespDto::getDeptId).collect(Collectors.toList()); List<SysDept> depts = deptIds.size() > 0 ? sysDeptMapper.selectDeptListByIds(deptIds) : Collections.emptyList(); Map<Long,String> deptIdAndNameMap = depts.stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getDeptName, (key1, key2) -> key2)); formatDto4DtGroupBusinessTaskRespDto(resultList,deptIdAndNameMap); return resultList; } private void doProcessDetail4GroupBusinessTaskRespDto(List<DtGroupBusinessTaskRespDto> resultList) { List<Long> taskIds = resultList.stream().map(DtGroupBusinessTaskRespDto::getId).collect(Collectors.toList()); if(taskIds.size() == 0){ return; } List<DtGroupBusinessTaskDetailRespDto> details = dtBusinessTaskMapper.selectGroupBusinessTaskDetailDtoByTaskIds(taskIds); MultiValuedMap<Long,DtGroupBusinessTaskDetailRespDto> taskIdAndDetailListMap = new ArrayListValuedHashMap<>(); for(DtGroupBusinessTaskDetailRespDto detail:details){ taskIdAndDetailListMap.put(detail.getTaskId(),detail); } for(DtGroupBusinessTaskRespDto dto:resultList){ dto.setDtGroupBusinessTaskDetailRespDtoList((List<DtGroupBusinessTaskDetailRespDto>)taskIdAndDetailListMap.get(dto.getId())); } } @Override public int assginDept(AssginReqDto assginReqDto) { Long[] taskIds = Convert.toLongArray(assginReqDto.getIds()); int count = 0; SysDept dept = sysDeptMapper.selectDeptById(assginReqDto.getDeptId()); if(StringUtils.isNull(dept.getLeaderId())){ throw new BusinessException("该团队没组长,无法分配"); } List<DtBusinessTaskDetail> details = dtBusinessTaskMapper.selectDtBusinessTaskDetailListByTaskIds(taskIds); List<DtBusinessTaskDetail> hasGavelTaskDetailList = details.stream().filter(t -> t.getHasNicknameVerification().equals("0")).collect(Collectors.toList()); if(hasGavelTaskDetailList.size() > 0){ throw new BusinessException("存在呢称验证完成的订单,无法重新调配任务"); } //清空业务组长分配后的数据 List<DtBusinessTask> dtBusinessTasks = dtBusinessTaskMapper.selectDtBusinessTaskListWithAllocateTimeByIds(taskIds); if(dtBusinessTasks.size() > 0){ List<Long> setNullTaskList = dtBusinessTasks.stream().map(DtBusinessTask::getId).collect(Collectors.toList()); dtBusinessTaskMapper.clearAllocateTimeByIds(setNullTaskList); List<DtBusinessTaskDetail> dtBusinessTaskDetails = dtBusinessTaskMapper.selectDtBusinessTaskDetailListByTaskIds(setNullTaskList.toArray(new Long[setNullTaskList.size()])); List<Long> setNullTaskDetailList = dtBusinessTaskDetails.stream().map(DtBusinessTaskDetail::getId).collect(Collectors.toList()); dtBusinessTaskMapper.clearSalesmanInfo(setNullTaskDetailList); } for(DtBusinessTaskDetail detail: details){ detail.setSalesmanLeaderUserId(dept.getLeaderId()); dtBusinessTaskMapper.updateDtBusinessTaskDetail(detail); } for(Long taskId:taskIds){ DtBusinessTask dtBusinessTask = new DtBusinessTask(); dtBusinessTask.setDeptId(assginReqDto.getDeptId()); dtBusinessTask.setId(taskId); dtBusinessTask.setGroupAllocateTime(new Date()); count = count + dtBusinessTaskMapper.updateDtBusinessTask(dtBusinessTask); } return count; } @Override @Transactional public String batchInsertTask(List<List<DtBusinessTaskDetail>> list, List<DtBusinessTaskDetail> vaildList) { vaildBusinessTaskDetailList(vaildList); int successNum = 0; int failureNum = 0; StringBuilder successMsg = new StringBuilder(); StringBuilder failureMsg = new StringBuilder(); for (List<DtBusinessTaskDetail> taskDetailList : list) { try { doProcessDetail4MerchantId(taskDetailList); DtBusinessTask dtBusinessTask = new DtBusinessTask(); dtBusinessTask.setOrderStatus("1"); dtBusinessTask.setRequiredCompletionDate(vaildList.get(0).getOrderDate()); dtBusinessTaskMapper.insertDtBusinessTask(dtBusinessTask); dtBusinessTaskMapper.batchInsertDtBusinessTaskDetail(dtBusinessTask.getId(),taskDetailList); successNum++; successMsg.append("<br/>" + successNum + "、任务编码:" + dtBusinessTask.getId() +" 产生,导入成功"); } catch (Exception e) { failureNum++; String msg = "导入失败!"; failureMsg.append(msg + e.getMessage()); log.error(msg, e); } } if (failureNum > 0) { failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:"); throw new BusinessException(failureMsg.toString()); } else { successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:"); } return successMsg.toString(); } private void doProcessDetail4MerchantId(List<DtBusinessTaskDetail> taskDetailList) { Set<String> shopNames = taskDetailList.stream().map(DtBusinessTaskDetail::getShopName).collect(Collectors.toSet()); if(taskDetailList.size() != shopNames.size()){ throw new BusinessException("<br/>任务中的店铺名,存在重复"); } List<MerchantShopRelation> merchantShopRelations = dtMerchantMapper.selectMerchantShopRelationByShopNames(shopNames); if(taskDetailList.size() != merchantShopRelations.size()){ throw new BusinessException("<br/>存在导入的店铺名没有绑定商家,所以无法导入该任务"); } Map<String,Long> shopnameAndMerchantUserIdMap = merchantShopRelations.stream().collect(Collectors.toMap(MerchantShopRelation::getShopName,MerchantShopRelation::getMerchantUserId,(k1,k2) -> k2)); for(DtBusinessTaskDetail detail:taskDetailList){ detail.setMerchantUserId(shopnameAndMerchantUserIdMap.get(detail.getShopName())); } } @Override public List<DtBusinessTaskDetail> selectDtBusinessTaskDetailList(Long id) { List<DtBusinessTaskDetail> resultList = dtBusinessTaskMapper.selectDtBusinessTaskDetailListByTaskId(id); Set<Long> merchantUserIds = resultList.stream().map(DtBusinessTaskDetail::getMerchantUserId).collect(Collectors.toSet()); Set<Long> salesmanUserIds = resultList.stream().map(DtBusinessTaskDetail::getSalesmanLeaderUserId).collect(Collectors.toSet()); salesmanUserIds.addAll(merchantUserIds); List<Long> userIds = salesmanUserIds.stream().collect(Collectors.toList()); List<SysUser> sysUsers = sysUserMapper.selectUserListByIds(userIds); Map<Long,String> userIdAndNameMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getUserId,SysUser::getUserName,(k1,k2) -> k2)); for (DtBusinessTaskDetail detail:resultList){ detail.setSalesmanLeaderUserName(userIdAndNameMap.get(detail.getSalesmanLeaderUserId())); detail.setMerchatUserName(userIdAndNameMap.get(detail.getMerchantUserId())); detail.setPictureUrl(OssClientUtils.getPictureUrlByOssParam(detail.getPictureUrl())); detail.setSalesmanCommitUrl(OssClientUtils.getPictureUrlByOssParam(detail.getSalesmanCommitUrl())); } return resultList; } @Override public int updateDtBusinessTaskDetail(DtBusinessTaskDetail dtBusinessTaskDetail) { if(!DateUtils.isSameDay(new Date(),dtBusinessTaskDetail.getOrderDate())){ throw new BusinessException("能操作的数据日期是" + DateUtils.getDate()); } return dtBusinessTaskMapper.updateDtBusinessTaskDetail(dtBusinessTaskDetail); } private void vaildBusinessTaskDetailList(List<DtBusinessTaskDetail> vaildList) { if (StringUtils.isNull(vaildList) || vaildList.size() == 0) { throw new BusinessException("导入的任务数据不能为空!"); } StringBuffer vailedMsg = new StringBuffer(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Set<String> dateSet = new HashSet<>(); for(DtBusinessTaskDetail dtBusinessTaskDetail:vaildList){ if(StringUtils.isEmpty(dtBusinessTaskDetail.getTaskNo())){ vailedMsg.append("<br/>" + dtBusinessTaskDetail.getShopName()).append("任务代码不能为空"); } if(StringUtils.isNull(dtBusinessTaskDetail.getOrderDate())){ vailedMsg.append("<br/>" + dtBusinessTaskDetail.getShopName()).append("日期不能为空"); } if(StringUtils.isEmpty(dtBusinessTaskDetail.getShopName())){ vailedMsg.append("<br/>" + dtBusinessTaskDetail.getTaskNo()).append("店铺名不能为空"); } if(StringUtils.isNull(dtBusinessTaskDetail.getUnitPrice())){ vailedMsg.append("<br/>" + dtBusinessTaskDetail.getShopName()).append("单价不能为空"); } dateSet.add(sdf.format(dtBusinessTaskDetail.getOrderDate())); } if(dateSet.size() >1){ vailedMsg.insert(0,"存在多个订单日期"+ dateSet.toString() + "日期"); } String msg = vailedMsg.toString(); if(StringUtils.isNotEmpty(msg)){ throw new BusinessException(msg); } } private void formatDto4DtGroupBusinessTaskRespDto(List<DtGroupBusinessTaskRespDto> resultList, Map<Long,String> deptIdAndNameMap) { for(DtGroupBusinessTaskRespDto dto: resultList){ dto.setDeptName(deptIdAndNameMap.get(dto.getDeptId())); List<DtGroupBusinessTaskDetailRespDto> detailRespDto = dto.getDtGroupBusinessTaskDetailRespDtoList(); dto.setOrderNumber(detailRespDto.size()); List<BigDecimal> principalList = detailRespDto.stream().map(DtGroupBusinessTaskDetailRespDto::getUnitPrice).collect(Collectors.toList()); dto.setTotalPrincipal(principalList.stream().reduce(new BigDecimal(0),(acc,item) -> { BigDecimal result = acc.add(item); return result; })); List<BigDecimal> actualPrincipalList = detailRespDto.stream().map(DtGroupBusinessTaskDetailRespDto::getPromotersModifyUnitPrice).collect(Collectors.toList()); dto.setActualTotalPrincipal(actualPrincipalList.stream().reduce(new BigDecimal(0),(acc,item) ->{ BigDecimal result = acc.add(item); return result; })); } } /** * 新增商业任务信息 * * @param dtBusinessTask 商业任务信息 * @return 结果 */ @Transactional @Override public int insertDtBusinessTask(DtBusinessTask dtBusinessTask) { /*dtBusinessTask.setCreateTime(DateUtils.getNowDate()); int rows = dtBusinessTaskMapper.insertDtBusinessTask(dtBusinessTask); insertDtBusinessTaskDetail(dtBusinessTask); return rows;*/ return 0; } /** * 修改商业任务信息 * * @param dtBusinessTask 商业任务信息 * @return 结果 */ @Transactional @Override public int updateDtBusinessTask(DtBusinessTask dtBusinessTask) { dtBusinessTaskMapper.deleteDtBusinessTaskDetailByTaskId(dtBusinessTask.getId()); insertDtBusinessTaskDetail(dtBusinessTask); return dtBusinessTaskMapper.updateDtBusinessTask(dtBusinessTask); } /** * 删除商业任务信息对象 * * @param ids 需要删除的数据ID * @return 结果 */ @Transactional @Override public int deleteDtBusinessTaskByIds(String ids) { dtBusinessTaskMapper.deleteDtBusinessTaskDetailByTaskIds(Convert.toStrArray(ids)); return dtBusinessTaskMapper.deleteDtBusinessTaskByIds(Convert.toStrArray(ids)); } /** * 删除商业任务信息信息 * * @param id 商业任务信息ID * @return 结果 */ @Override public int deleteDtBusinessTaskById(Long id) { dtBusinessTaskMapper.deleteDtBusinessTaskDetailByTaskId(id); return dtBusinessTaskMapper.deleteDtBusinessTaskById(id); } /** * 新增商业任务信息明细信息 * * @param dtBusinessTask 商业任务信息对象 */ public void insertDtBusinessTaskDetail(DtBusinessTask dtBusinessTask) { List<DtBusinessTaskDetail> dtBusinessTaskDetailList = dtBusinessTask.getDtBusinessTaskDetailList(); Long id = dtBusinessTask.getId(); if (StringUtils.isNotNull(dtBusinessTaskDetailList)) { List<DtBusinessTaskDetail> list = new ArrayList<DtBusinessTaskDetail>(); for (DtBusinessTaskDetail dtBusinessTaskDetail : dtBusinessTaskDetailList) { dtBusinessTaskDetail.setId(id); list.add(dtBusinessTaskDetail); } if (list.size() > 0) { dtBusinessTaskMapper.batchDtBusinessTaskDetail(list); } } } }
baderzone/biopartsdb
test/unit/helpers/pcr_gel_image_annotations_helper_test.rb
<gh_stars>1-10 require 'test_helper' class PcrGelImageAnnotationsHelperTest < ActionView::TestCase end
MaximeBaudette/PyCIM
CIM15/IEC61970/Informative/InfCommon/Bank.py
<reponame>MaximeBaudette/PyCIM # Copyright (C) 2010-2011 <NAME> # # 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. from CIM15.IEC61968.Common.Organisation import Organisation class Bank(Organisation): """Organisation that is a commercial bank, agency, or other institution that offers a similar service.Organisation that is a commercial bank, agency, or other institution that offers a similar service. """ def __init__(self, bic='', iban='', branchCode='', BankAccounts=None, *args, **kw_args): """Initialises a new 'Bank' instance. @param bic: Bank identifier code as defined in ISO 9362; for use in countries wher IBAN is not yet in operation. @param iban: International bank account number defined in ISO 13616; for countries where IBAN is not in operation, the existing BIC or SWIFT codes may be used instead (see ISO 9362). @param branchCode: Codified reference to the particular branch of the bank where BankAccount is held. @param BankAccounts: All BankAccounts this Bank provides. """ #: Bank identifier code as defined in ISO 9362; for use in countries wher IBAN is not yet in operation. self.bic = bic #: International bank account number defined in ISO 13616; for countries where IBAN is not in operation, the existing BIC or SWIFT codes may be used instead (see ISO 9362). self.iban = iban #: Codified reference to the particular branch of the bank where BankAccount is held. self.branchCode = branchCode self._BankAccounts = [] self.BankAccounts = [] if BankAccounts is None else BankAccounts super(Bank, self).__init__(*args, **kw_args) _attrs = ["bic", "iban", "branchCode"] _attr_types = {"bic": str, "iban": str, "branchCode": str} _defaults = {"bic": '', "iban": '', "branchCode": ''} _enums = {} _refs = ["BankAccounts"] _many_refs = ["BankAccounts"] def getBankAccounts(self): """All BankAccounts this Bank provides. """ return self._BankAccounts def setBankAccounts(self, value): for x in self._BankAccounts: x.Bank = None for y in value: y._Bank = self self._BankAccounts = value BankAccounts = property(getBankAccounts, setBankAccounts) def addBankAccounts(self, *BankAccounts): for obj in BankAccounts: obj.Bank = self def removeBankAccounts(self, *BankAccounts): for obj in BankAccounts: obj.Bank = None
Ubpa/DustEngine
include/Utopia/Core/Components/WorldTime.h
#pragma once namespace Ubpa::Utopia { // singleton struct WorldTime { double elapsedTime; // in seconds float deltaTime; // in seconds }; }
taegyunkim/front-end
rewriting/src/test/scala/org/opencypher/v9_0/rewriting/ReplaceLiteralDynamicPropertyLookupsTest.scala
/* * Copyright (c) Neo4j Sweden AB (http://neo4j.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opencypher.v9_0.rewriting import org.opencypher.v9_0.ast.AstConstructionTestSupport import org.opencypher.v9_0.util.ASTNode import org.opencypher.v9_0.util.test_helpers.CypherFunSuite import org.opencypher.v9_0.rewriting.rewriters.replaceLiteralDynamicPropertyLookups class ReplaceLiteralDynamicPropertyLookupsTest extends CypherFunSuite with AstConstructionTestSupport { test("Replaces literal dynamic property lookups") { val input: ASTNode = containerIndex(varFor("a"), literalString("name")) val output: ASTNode = prop("a", "name") replaceLiteralDynamicPropertyLookups(input) should equal(output) } test("Does not replaces non-literal dynamic property lookups") { val input: ASTNode = containerIndex(varFor("a"), varFor("b")) replaceLiteralDynamicPropertyLookups(input) should equal(input) } }
abdelillah-tech/ui
packages/components/src/ObjectViewer/Table/Table.component.js
import PropTypes from 'prop-types'; import React from 'react'; import classNames from 'classnames'; import union from 'lodash/union'; import toFlat from '../toflat'; import JSONLike from '../JSONLike'; import theme from './Table.scss'; /** * @param {Object} data * @param {Bool} isFlat * @return {Array<String>} */ export function getKeys(data, isFlat) { if (isFlat) { return Object.keys(toFlat(data)); } return Object.keys(data); } export function getAbsolutePath(index, key, flat) { if (flat) { return `$[${index}]${key.replace('$', '')}`; } return `$[${index}]['${key}']`; } export function getHeaders(keys, isFlat, baseId) { return keys.map(key => { // This transforms $['id'][0]['foo'] into id[0].foo const adaptedKey = isFlat ? key .replace(/^\$\['/g, '') .replace(/']\['/g, '.') .replace(/]\['/g, '].') .replace(/']\[/g, '[') .replace(/']/g, '') : key; return { id: `${baseId}-${adaptedKey}`, key, header: adaptedKey, }; }); } /** * We construct the jsx dispayed for the header. * If there is a type we add it. * @param {array} headersDefinitions * @param {object} schema */ export function buildContentHeaders(headersDefinitions, schema) { return headersDefinitions.map(({ header, id }, index) => { let type; if (schema) { type = schema.get(header); } if (!type) { return ( <th key={index} id={id}> {header} </th> ); } return ( <th key={index} id={id}> <div>{header}</div> <div className={classNames('text-right')}>{type}</div> </th> ); }); } function Table({ flat, data, title, ...props }) { if (!Array.isArray(data) && !Array.isArray(data.dataset)) { return null; } // The datas can be an array or an array in an object. We assign the value correctly here. const dataset = Array.isArray(data) ? data : data.dataset; /** * because we want to display all the possible table header keys * for each row of the dataset we try to find each possible key * and merge them into a array of unique values * this may not be performant or good UX for huge heterogenous datasets * because it require to run a recursive exploratory function on each member of the dataset * and it may show to many column to the end user */ const keys = dataset.reduce( (accumulator, currentValue) => union(getKeys(currentValue, flat), accumulator), [], ); const headers = getHeaders(keys, flat, props.id); const tableClassName = classNames( theme.table, 'tc-object-viewer', 'table table-bordered table-striped table-hover', ); return ( <table className={tableClassName} id={props.id}> <caption className="sr-only">{title}</caption> <thead> <tr>{buildContentHeaders(headers, data.schema)}</tr> </thead> <tbody> {dataset.map((row, index) => { const flattenRow = flat ? toFlat(row) : row; return ( <tr key={index}> {headers.map(({ key, id }, j) => { const path = getAbsolutePath(index, key, flat); return ( <td key={j} headers={id}> <JSONLike data={flattenRow[key]} {...props} jsonpath={path} nativeValueClassName={theme.nativevalue} /> </td> ); })} </tr> ); })} </tbody> </table> ); } Table.displayName = 'Table'; Table.propTypes = { id: PropTypes.string.isRequired, title: PropTypes.string.isRequired, flat: PropTypes.bool, data: PropTypes.oneOfType([ PropTypes.bool, PropTypes.number, PropTypes.string, PropTypes.object, PropTypes.array, ]).isRequired, }; export default Table;
syoyo/lucille
src/render/shader.c
#ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <assert.h> /* for performance analizer */ #if defined(__APPLE__) && defined(__MACH__) //#include <ppc_intrinsics.h> #endif #include "vector.h" #include "shader.h" #include "raytrace.h" #include "noise.h" #include "memory.h" #include "random.h" #include "reflection.h" #include "thread.h" #include "texture.h" #ifndef M_PI #define M_PI 3.141592 #endif static int typesize[] = { sizeof(ri_float_t) * 4 /* TYPEVECTOR */ , sizeof(char) /* TYPESTRING */ , sizeof(ri_float_t) /* TYPEFLOAT */ }; typedef struct _lightsource_info_t { ri_light_t *light; int sample_index; int nsamples; ri_lightsource_t samples[1024]; ri_vector_t basis[3]; ri_vector_t N; } lightsource_info_t; static unsigned int hash (const char *str); static void status_copy (ri_status_t *dst, const ri_status_t *src); static ri_light_t *get_light(ri_render_t *render); static void init_lightsource(const ri_status_t *status, const ri_vector_t P, const ri_vector_t N, ri_float_t angle); static lightsource_info_t glightinfo[RI_MAX_THREADS]; static int glight_initialized[RI_MAX_THREADS]; #ifdef WITH_ALTIVEC #define vcomp(v, n) (*(((ri_float_t *)&(v)) + n)) /* codes from AltiVec tutorial by <NAME> */ static inline vector float vec_div(vector float v) { vector float reciprocal = vec_re(v); return vec_madd(reciprocal, vec_nmsub(reciprocal, v, vec_ctf(vec_splat_u32(1), 0)), reciprocal); } //Generate a vector full of -0.0 inline vector float vec_neg_zero(void) { vector unsigned int result = vec_splat_u32(-1); return (vector float)vec_sl(result, result); } //Calculate the full precision reciprocal square root of v inline vector float vec_recioprocal_sqrt(vector float v) { const vector float kMinusZero = vec_neg_zero(); const vector float kOne = vec_ctf(vec_splat_u32(1), 0); const vector float kOneHalf = vec_ctf(vec_splat_u32(1), 1); //Calculate 1/denomenator using newton rapheson //refined reciprocal estimate vector float sqrtReciprocalEstimate = vec_rsqrte(v); vector float reciprocalEstimate = vec_madd(sqrtReciprocalEstimate, sqrtReciprocalEstimate, kMinusZero); vector float halfSqrtReciprocalEst = vec_madd(sqrtReciprocalEstimate, kOneHalf, kMinusZero); vector float term1 = vec_nmsub(v, reciprocalEstimate, kOne); return vec_madd(term1, halfSqrtReciprocalEst, sqrtReciprocalEstimate); } #endif /* * Function: ri_shader_dup * * Duplicates shader. * * Parameters: * * *src - Src address of shader. * * Returns: * * Duplicated and memory allocated shader. * */ ri_shader_t * ri_shader_dup(const ri_shader_t *src) { ri_shader_t *p; if (!src) return NULL; p = (ri_shader_t *)ri_mem_alloc(sizeof(ri_shader_t)); p->initparamproc = src->initparamproc; p->shaderproc = src->shaderproc; p->param = ri_param_dup(src->param); return p; } /* * Function: ri_param_new * * Allocates memory for shader parameter list and initialize it with zero. * * Parameters: * * None. * * Returns: * * Memory allocated shader parameter list. * */ ri_parameter_t * ri_param_new() { ri_parameter_t *p; p = (ri_parameter_t *)ri_mem_alloc(sizeof(ri_parameter_t)); memset(p, 0, sizeof(ri_parameter_t)); return p; } /* * Function: ri_param_free * * Frees memory allocated for shader parameter list. * * Parameters: * * *param - Parameter list it's allocated memory to be freed. * * Returns: * * None. * */ void ri_param_free(ri_parameter_t *param) { int i; ri_paramnode_t *p; for (i = 0; i < PARAMHASH_SIZE; i++) { p = param->paramnodes[i]; for ( ; p != NULL; p = p->next) { ri_mem_free(p->val); } } ri_mem_free(param); } /* * Function: ri_param_dup * * Duplicates shader parameter list. * * Parameters: * * *param - Reference parameter list to be duplicated. * * Returns: * * Memory allocated duplication of input parameter list. * */ ri_parameter_t * ri_param_dup(const ri_parameter_t *param) { int i; ri_parameter_t *newparam; ri_paramnode_t *p; ri_paramnode_t *np; if (!param) return NULL; newparam = ri_param_new(); for (i = 0; i < PARAMHASH_SIZE; i++) { p = param->paramnodes[i]; for ( ; p != NULL; p = p->next) { np = (ri_paramnode_t *)malloc(sizeof(ri_paramnode_t)); np->name = strdup((const char *)(p->name)); np->type = p->type; if (p->type == TYPESTRING) { np->size = typesize[p->type] * (strlen((char *)(p->val)) + 1); np->val = malloc(np->size); memcpy(np->val, p->val, p->size); } else { np->size = typesize[p->type]; np->val = malloc(p->size); memcpy(np->val, p->val, p->size); } np->next = newparam->paramnodes[i]; newparam->paramnodes[i] = np; } } return newparam; } /* * Function: ri_param_eval * * Evaluates and returns shader parameter variables specified by name. * * Parameters: * * *data - Returned value of parameter variable. * *param - Shader parameter list investigated. * *name - Shader parameter variable name. * * * Returns: * * None. * */ void ri_param_eval(void *data, const ri_parameter_t *param, const char *name) { unsigned int h; int len; ri_paramnode_t *p; h = hash(name); p = param->paramnodes[h]; len = strlen(name); for ( ; p != NULL && p->len != len && strcmp(p->name, name) != 0; p = p->next); if (p) { if (p->type == TYPESTRING) { *((char **)data) = (char *)p->val; } else { memcpy(data, p->val, p->size); } } else { fprintf(stderr, "no entries\n"); exit(-1); } } /* * Function: ri_param_add * * Adds variables to shader parameter list. * * Parameters: * * *param - Shader parameter list. * *name - Shader parameter variable name. * type - Type of parameter variable. * val - Value of parameter variable. * * Returns: * * None. * */ void ri_param_add(ri_parameter_t *param, const char *name, int type, const void *val) { unsigned int h; int len; ri_paramnode_t *p; h = hash(name); p = param->paramnodes[h]; len = strlen(name); for ( ; p != NULL && p->len != len && strcmp(p->name, name) != 0; p = p->next); if (p) { /* ??? */ fprintf(stderr, "duplicated declaration.\n"); exit(-1); } else { p = (ri_paramnode_t *)malloc(sizeof(ri_paramnode_t)); p->name = strdup((const char *)name); p->type = type; if (type == TYPESTRING) { p->size = typesize[type] * (strlen((char *)val) + 1); p->val = malloc(p->size); memcpy(p->val, val, p->size); } else { p->size = typesize[type]; p->val = malloc(p->size); memcpy(p->val, val, p->size); } p->next = param->paramnodes[h]; param->paramnodes[h] = p; } } /* * Function: ri_param_override * * Overrides value of shader parameter variable. * * Parameters: * * *param - Shader parameter list. * *name - Shader parameter variable name overrided. * val - New value of parameter variable. * * Returns: * * None. * */ void ri_param_override(ri_parameter_t *param, const char *name, const void *val) { char **tokp; unsigned int h; int len; ri_paramnode_t *p; ri_vector_t v; h = hash(name); p = param->paramnodes[h]; len = strlen(name); for ( ; p != NULL && p->len != len && strcmp(p->name, name) != 0; p = p->next); if (!p) { /* ??? */ fprintf(stderr, "no variable name [ %s ] in shader parameter list\n", name); return; } if (p->type == TYPESTRING) { free(p->val); tokp = (char **)val; p->size = typesize[p->type] * (strlen(*tokp) + 1); p->val = malloc(p->size); memcpy(p->val, *tokp, p->size); printf("%s: override value with %s\n", p->name, *tokp); } else { if (p->type == TYPEFLOAT) { memcpy(p->val, val, typesize[TYPEFLOAT]); } else { /* vector type */ v[0] = ((ri_float_t *)val)[0]; v[1] = ((ri_float_t *)val)[1]; v[2] = ((ri_float_t *)val)[2]; v[3] = 1.0; ri_vector_print(v); memcpy(p->val, &v, typesize[TYPEVECTOR]); } } } /* * Function: ri_param_type * * Returns type of parameter variable. * * Parameters: * * *type - Type of parameter variable returned. * *param - Parameter lists variable contains. * name - Name of parameter variable. * * Returns: * * 0 if parameter variable is not found in param, * 1 if found. * */ int ri_param_type(int *type, const ri_parameter_t *param, const char *name) { unsigned int h; int len; ri_paramnode_t *p; h = hash(name); p = param->paramnodes[h]; len = strlen(name); for ( ; p != NULL && p->len != len && strcmp(p->name, name) != 0; p = p->next); if (!p) { /* parameter variable is not found. */ return 0; } *type = p->type; return 1; } void faceforward( ri_vector_t dst, const ri_vector_t N, const ri_vector_t I) { double dot; ri_vector_t eye; ri_vector_copy(dst, N); ri_vector_copy(eye, I); ri_vector_neg(eye); dot = ri_vector_dot(N, eye); if (dot < -2.0e-1) { /* TODO: consider machine epsilon */ dst[0] = -dst[0]; dst[1] = -dst[1]; dst[2] = -dst[2]; } } void normalize( ri_vector_t dst, const ri_vector_t N) { ri_vector_copy(dst, N); ri_vector_normalize(dst); } void ambient( const ri_status_t *status, ri_color_t dst) { ri_vector_t ambcol; ambcol[0] = 0.2f; ambcol[1] = 0.2f; ambcol[2] = 0.2f; ambcol[3] = 1.0f; ri_vector_copy(dst, ambcol); (void)status; } void diffuse( const ri_status_t *status, ri_color_t dst, const ri_vector_t N) { double dot; ri_vector_t light; ri_vector_copy(light, status->input.L); ri_vector_normalize(light); dot = ri_vector_dot(N, light); if (dot <= 0.0) { dst[0] = 0.0f; dst[1] = 0.0f; dst[2] = 0.0f; } else { dst[0] = (ri_float_t)dot; dst[1] = (ri_float_t)dot; dst[2] = (ri_float_t)dot; } } void specular( const ri_status_t *status, ri_color_t dst, const ri_vector_t N, const ri_vector_t V, float roughness) { double dot; double coeff; ri_vector_t light; ri_vector_t half; ri_vector_copy(light, status->input.L); ri_vector_normalize(light); ri_vector_add(half, light, V); ri_vector_normalize(half); dot = ri_vector_dot(N, half); if (dot < 0.0) dot = 0.0; if (roughness != 0.0) { coeff = pow(dot, 1.0 / roughness); } else { coeff = dot; } ri_vector_set1(dst, coeff); } void reflect( ri_vector_t dst, const ri_vector_t I, const ri_vector_t N) { ri_reflect(dst, I, N); } void refract( ri_vector_t dst, const ri_vector_t I, const ri_vector_t N, float eta) { ri_refract(dst, I, N, eta); } void transform( ri_vector_t dst, const char *tospace, const ri_vector_t src) { /* TODO: not yet implemented. */ ri_vector_copy(dst, src); (void)tospace; (void)src; } void vtransform( ri_vector_t dst, const char *from, const char *to, const ri_vector_t src) { /* TODO: not yet implemented. */ ri_vector_copy(dst, src); (void)from; (void)to; (void)src; } void environment( const ri_status_t *status, ri_color_t dst, const char *name, const ri_vector_t coords) { double m; ri_vector_t tex_coords; m = 2.0 * sqrt(coords[0] * coords[0] + coords[1] * coords[1] + (coords[2] + 1.0) * (coords[2] + 1.0)); if (m != 0.0) { tex_coords[0] = coords[0] / m + 0.5; tex_coords[1] = coords[1] / m + 0.5; } else { tex_coords[0] = 0.5; tex_coords[1] = 0.5; } texture_coords(status, dst, name, tex_coords); } void texture( const ri_status_t *status, ri_color_t dst, const char *name) { /* TODO cached texture access */ ri_texture_t *texture = NULL; texture = ri_texture_load(name); if (!texture) return; ri_texture_fetch(dst, texture, (double)status->input.s, (double)status->input.t); } void texture_coords( const ri_status_t *status, ri_color_t dst, const char *name, const ri_vector_t coords) { const int step = 0x8; const int texwidth = 64; int u, v; int c; u = (int)(texwidth * coords[0]) % texwidth; v = (int)(texwidth * coords[1]) % texwidth; if (u < 0) u = texwidth + u; if (v < 0) v = texwidth + v; /* checker board pattern */ c = ((u & step) == 0) ^ ((v & step) == 0); dst[0] = (ri_float_t)c; dst[1] = (ri_float_t)c; dst[2] = (ri_float_t)c; (void)name; (void)status; } float occlusion( const ri_status_t *status, const ri_vector_t P, const ri_vector_t N, float nsamples) { int i, j, k; int hit; int coverage; int ntheta, nphi; double theta, phi; ri_vector_t dir; ri_vector_t basis[3]; ri_ray_t ray; ri_intersection_state_t state; #if defined(__APPLE__) && defined(__MACH__) //int inst; #endif #if defined(__APPLE__) && defined(__MACH__) //inst = __mfspr(1023); #endif coverage = 0; /* nphi = 3 * ntheta, * nsamples = nphi * ntheta */ ntheta = nsamples / 3.0; ntheta = (int)sqrt((double)ntheta); if (ntheta < 1) ntheta = 1; nphi = 3 * ntheta; #if defined(__APPLE__) && defined(__MACH__) //inst |= __mfspr(1023); //exit(1); #endif /* generate orhonormal basis with its z-axis corresponds to * surdace normal. */ ri_ortho_basis(basis, N); /* generate samples on hemisphere with * Probability DistributionFunction = cos(theta)/Pi */ for (j = 0; j < nphi; j++) { for (i = 0; i < (int)ntheta; i++) { theta = sqrt((double)i + randomMT()) / (double)ntheta ; phi = 2.0 * M_PI * ((double)j + randomMT()) / (double)nphi; dir[0] = cos(phi) * theta; dir[1] = sin(phi) * theta; dir[2] = sqrt(1.0 - theta * theta); for (k = 0; k < 3; k++) { ray.dir[k] = dir[0] * basis[0][k] + dir[1] * basis[1][k] + dir[2] * basis[2][k]; } ri_vector_normalize(ray.dir); ri_vector_copy(ray.org, P); // slightly moves the ray position towards // the ray direction ray.org[0] += 0.0001 * ray.dir[0]; ray.org[1] += 0.0001 * ray.dir[1]; ray.org[2] += 0.0001 * ray.dir[2]; ray.thread_num = status->thread_num; hit = ri_raytrace(ri_render_get(), &ray, &state); if (hit) { /* there is a occluder. */ coverage++; } } } if (coverage > (int)nsamples) coverage = (int)nsamples; return (ri_float_t)coverage / (ri_float_t)nsamples; } /* AltiVec version */ #if 0 #ifdef WITH_ALTIVEC ri_float_t occlusion_altivec(const ri_status_t *status, const ri_vector_t P, const ri_vector_t N, ri_float_t nsamples) { int i, j, k; int hit; int coverage; int ntheta, nphi; ri_float_t inv_ntheta, inv_nphi; //double theta, phi; ri_vector_t dir; ri_vector_t basis[3]; ri_ray_t ray; ri_surface_info_t surfinfo; vector float theta, phi; vector float vntheta, vnphi; vector float v; //#if defined(__APPLE__) && defined(__MACH__) // int inst; //#endif coverage = 0; /* nphi = 3 * ntheta, * nsamples = nphi * ntheta */ nsamples = 48; ntheta = nsamples / 3.0; ntheta = (int)sqrt((double)ntheta); if (ntheta < 1) ntheta = 1; nphi = 3 * ntheta; vcomp(vntheta, 0) = ntheta; vcomp(vntheta, 1) = ntheta; vcomp(vntheta, 2) = ntheta; vcomp(vntheta, 3) = ntheta; inv_ntheta = 1.0 / ntheta; inv_nphi = 1.0 / nphi; //#if defined(__APPLE__) && defined(__MACH__) //inst |= __mfspr(1023); //exit(1); //#endif /* generate orhonormal basis with its z-axis corresponds to * surdace normal. */ ri_ortho_basis(basis, N); /* generate samples on hemisphere with * Probability DistributionFunction = cos(theta)/Pi */ for (j = 0; j < nphi; j++) { for (i = 0; i < (int)ntheta/4; i++) { //#if defined(__APPLE__) && defined(__MACH__) inst = __mfspr(1023); //#endif vcomp(v, 0) = 4 * i + 0 + randomMT(); vcomp(v, 1) = 4 * i + 1 + randomMT(); vcomp(v, 2) = 4 * i + 2 + randomMT(); vcomp(v, 3) = 4 * i + 3 + randomMT(); // sqrt(v) = 1.0/sqrt(1/v) v = vec_div(v); theta = vec_recioprocal_sqrt(v); // dummy inst theta = vec_mad(theta, vec_div(ntheta), vec_neg_zero()); vcomp(v, 0) = j + randomMT(); vcomp(v, 1) = vcomp(v, 0); vcomp(v, 2) = vcomp(v, 0); vcomp(v, 3) = vcomp(v, 0); v = vec_div(v); phi = //#if defined(__APPLE__) && defined(__MACH__) inst |= __mfspr(1023); //#endif //#if 1 phi = 2.0 * M_PI * ((double)j + randomMT()) / (double)nphi; dir[0] = cos(phi) * theta; dir[1] = sin(phi) * theta; dir[2] = sqrt(1.0 - theta * theta); for (k = 0; k < 3; k++) { ray.dir[k] = dir[0] * basis[0][k] + dir[1] * basis[1][k] + dir[2] * basis[2][k]; } ri_vector_normalize(ray.dir); ri_vector_copy(ray.org, P); ray.thread_num = status->thread_num; hit = ri_raytrace(ri_render_get(), &ray, &surfinfo); if (hit) { /* there is a occluder. */ coverage++; } //#endif } } if (coverage > (int)nsamples) coverage = (int)nsamples; return (ri_float_t)coverage / (ri_float_t)nsamples; } #endif #endif void trace( const ri_status_t *status, ri_vector_t dst, const ri_vector_t P, const ri_vector_t R) { int hit; ri_vector_t eye; ri_status_t newstatus; ri_shader_t *shader; ri_light_t *light; ri_output_t out; //ri_float_t opa; /* opacity */ ri_ray_t ray; ri_intersection_state_t state; if (status->ray_depth > 3) { ri_vector_setzero(dst); return; } ri_vector_copy(ray.dir, R); ri_vector_copy(ray.org, P); ray.org[0] += 0.0001 * ray.dir[0]; ray.org[1] += 0.0001 * ray.dir[1]; ray.org[2] += 0.0001 * ray.dir[2]; ray.thread_num = status->thread_num; hit = ri_raytrace(ri_render_get(), &ray, &state); if (!hit) { light = get_light(ri_render_get()); if (light && ((light->type == LIGHTTYPE_IBL) | (light->type == LIGHTTYPE_SUNSKY))) { /* Use IBL HDRI */ ri_texture_ibl_fetch(dst, light->texture, ray.dir); } else { ri_vector_setzero(dst); } return; } /* ray hits the surface. * get a shader at the hit point. */ shader = state.geom->shader; if (!shader) { ri_vector_setzero(dst); return; } ri_vector_sub(eye, state.P, P); ri_vector_normalize(eye); /* Set up the status for evaluating the shader at the hit point. */ status_copy(&newstatus, status); newstatus.ray_depth++; /* increment ray depth */ ri_vector_copy(newstatus.input.Cs, state.color); ri_vector_copy(newstatus.input.P, state.P); ri_vector_copy(newstatus.input.N, state.Ns); ri_vector_copy(newstatus.input.Ng, state.Ng); ri_vector_copy(newstatus.input.dPdu, state.tangent); ri_vector_copy(newstatus.input.dPdv, state.binormal); ri_vector_copy(newstatus.input.I, eye); newstatus.input.s = state.u; newstatus.input.t = state.v; //opa = state.opacity; //ri_vector_set4(&newstatus.input.Os, opa, opa, opa, opa); /* call a shader at the hit point */ shader->shaderproc(&out, &newstatus, shader->param); ri_vector_copy(dst, out.Ci); //ri_vector_copy(dst, state.color); } float inversesqrt(float x) { if (x < 0.0) return 1.0; if (x < 0.001) return 1.0; return 1.0f / (float)sqrt(x); } float mod(float a, float b) { int n; float c; n = (int)(a / b); c = a - n * b; if (c < 0.0f) c += b; return c; } float minf(float a, float b) { if (a < b) return a; return b; } float clampf(float a, float min, float max) { if (a < min) return min; if (a > max) return max; return a; } float noise1d(float f) { ri_float_t val; val = noise1(f); return ((ri_float_t)val + 1.0) * 0.5; } float noise3d(const ri_vector_t v) { float arg[3]; float val; arg[0] = v[0]; arg[1] = v[1]; arg[2] = v[2]; val = noise3(arg); return (val + 1.0) * 0.5; } float step(float min, float value) { if (value < min) return 0.0; return 1.0; } float smoothstep(float min, float max, float value) { double t; if (value < min) { t = 0.0; } else if (value >= max) { t = 1.0; } else { /* Hermite interpolation */ t = (value - min) / (max - min); t = t * t * (3.0 - 2.0 * t); } return t; } void mixv( ri_vector_t dst, const ri_vector_t x, const ri_vector_t y, float alpha) { dst[0] = (1.0 - alpha) * x[0] + alpha * y[0]; dst[1] = (1.0 - alpha) * x[1] + alpha * y[1]; dst[2] = (1.0 - alpha) * x[2] + alpha * y[2]; } float distant( const ri_vector_t p1, const ri_vector_t p2) { ri_vector_t d; ri_vector_sub(d, p1, p2); return length(d); } float area(const ri_vector_t P) { /* TODO: implement this function */ (void)P; return 1.0; } /* return the depth of the point P in camera coordinates. * the depth is normalized to lie between 0(at the near clipping plane) * and 1(aat the far clipping plane). */ float depth(const ri_vector_t P) { /* TODO implement this function */ (void)P; return 1.0; } ri_lightsource_t * next_lightsource( const ri_status_t *status, const ri_vector_t P, const ri_vector_t N, ri_float_t angle) { /* TODO: currently only accounts for IBL light source */ int hit; int tid; /* thread number */ ri_float_t ndotl; ri_lightsource_t *l = NULL; ri_ray_t ray; ri_intersection_state_t state; tid = status->thread_num; if (!glight_initialized[tid]) { init_lightsource(status, P, N, angle); glight_initialized[tid] = 1; } ri_vector_copy(ray.org, P); ray.org[0] += N[0] * 0.0001; ray.org[1] += N[1] * 0.0001; ray.org[2] += N[2] * 0.0001; ray.thread_num = tid; if (glightinfo[tid].light->type == LIGHTTYPE_IBL) { while (glightinfo[tid].sample_index < glightinfo[tid].nsamples) { l = &glightinfo[tid].samples[glightinfo[tid].sample_index]; glightinfo[tid].sample_index++; ndotl = ri_vector_dot(l->L, N); if (ndotl <= 0.0) continue; /* test if the angle between L and N is inside a cone */ if (acos(ndotl) >= angle) { continue; } /* occlusion test */ ri_vector_copy(ray.dir, l->L); ri_vector_normalize(ray.dir); hit = ri_raytrace(ri_render_get(), &ray, &state); if (hit) { /* there is a occluder */ continue; } //ri_vector_scale(&l->Cl, (1.0f / ndotl) * M_PI ); break; } if (glightinfo[tid].sample_index >= glightinfo[tid].nsamples) { /* run out of light sources. * prepare for next illuminance() loop */ glight_initialized[tid] = 0; return NULL; } } if (l == NULL) { /* prepare for next illuminance() loop */ glight_initialized[tid] = 0; } return l; } /* --- private functions --- */ static unsigned int hash(const char *str) { const char *p = str; unsigned long h = *p; if (h) { for (p += 1; *p != '\0'; p++) { h = (h << 5) - h + *p; } } return h % PARAMHASH_SIZE; } static void status_copy(ri_status_t *dst, const ri_status_t *src) { memcpy(dst, src, sizeof(ri_status_t)); } static ri_light_t * get_light(ri_render_t *render) { /* TODO: multiple light source */ ri_light_t *light; if (!ri_list_first(render->scene->light_list)) { //ri_log("warning", "no light exist.\n"); return NULL; } light = (ri_light_t *)ri_list_first(render->scene->light_list)->data; return light; } static void init_lightsource( const ri_status_t *status, const ri_vector_t P, const ri_vector_t N, ri_float_t angle) { int i, j, k; int count = 0; int ntheta, nphi; int nsamples; int tid; /* thread number */ ri_float_t theta, phi; ri_vector_t dir; ri_vector_t ldir; ri_option_t *opt; (void)P; tid = status->thread_num; /* TODO: currently only acocunts for IBL light source */ glightinfo[tid].light = get_light(ri_render_get()); glightinfo[tid].sample_index = 0; opt = ri_render_get()->context->option; ri_vector_copy(glightinfo[tid].N, N); ri_ortho_basis(glightinfo[tid].basis, N); nsamples = opt->narealight_rays; ntheta = nsamples / 3.0; ntheta = (int)sqrt((double)ntheta); if (ntheta < 1) ntheta = 1; nphi = 3 * ntheta; glightinfo[tid].nsamples = ntheta * nphi; for (j = 0; j < nphi; j++) { for (i = 0; i < ntheta; i++) { theta = sqrt(((double)i + randomMT()) / (double)ntheta); phi = 2.0 * M_PI * ((double)j + randomMT()) / (double)nphi; dir[0] = cos(phi) * theta; dir[1] = sin(phi) * theta; dir[2] = sqrt(1.0 - theta * theta); //assert(!isnan(dir[0])); //assert(!isnan(dir[1])); //assert(!isnan(dir[2])); for (k = 0; k < 3; k++) { ldir[k] = dir[0] * glightinfo[tid].basis[0][k] + dir[1] * glightinfo[tid].basis[1][k] + dir[2] * glightinfo[tid].basis[2][k]; } ldir[3] = 0.0; ri_vector_normalize(ldir); ri_vector_copy(glightinfo[tid].samples[count].L, ldir); /* get light color from IBL image */ ri_texture_ibl_fetch( glightinfo[tid].samples[count].Cl, glightinfo[tid].light->texture, ldir); #if defined(LINUX) || defined(__APPLE__) if (isnan(glightinfo[tid].samples[count].Cl[0])) { printf("ldir = "); ri_vector_print(ldir); } #endif /* scacle light power */ ri_vector_scale(glightinfo[tid].samples[count].Cl, glightinfo[tid].samples[count].Cl, 1.0f / (ri_float_t)glightinfo[tid].nsamples); /* Ol is not yet implemented */ ri_vector_setzero(glightinfo[tid].samples[count].Ol); count++; } } }
EthanGrahn/geo-data-portal
gdp-common-utilities/src/main/java/gov/usgs/cida/gdp/urs/URSLoginProvider.java
package gov.usgs.cida.gdp.urs; import gov.usgs.cida.gdp.constants.AppConstant; import gov.usgs.cida.proxy.registration.HttpLoginProvider; import java.io.IOException; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.X509Certificate; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CookieStore; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.HttpClientUtils; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author <NAME> <<EMAIL>> */ public class URSLoginProvider implements HttpLoginProvider { private static final Logger log = LoggerFactory.getLogger(URSLoginProvider.class); private static final int SSL_PORT = 443; private String ursHost; private ClientConnectionManager ccm; private CredentialsProvider credentialStore; private CookieStore cookieStore; private boolean ursProtected = false; private boolean loggedIn = false; public URSLoginProvider() { this(AppConstant.URS_USERNAME.getValue(), AppConstant.URS_PASSWORD.getValue(), AppConstant.URS_HOST.getValue()); } public URSLoginProvider(String username, String password, String ursHost) { this.ursHost = ursHost; this.credentialStore = new BasicCredentialsProvider(); this.credentialStore.setCredentials(new AuthScope(ursHost, SSL_PORT), new UsernamePasswordCredentials(username, password)); this.cookieStore = new BasicCookieStore(); initClientConnectionManager(); // TODO add trust store to avoid trusting everything } @Override public boolean checkResource(URL resource) { try { String currentResource = resource.toString(); int statusCode = 302; int redirects = 0; while (statusCode == 302 && redirects < 10) { redirects++; HttpParams params = new BasicHttpParams(); params.setParameter("http.protocol.handle-redirects", false); HttpClient client = getClient(params); HttpGet get = new HttpGet(currentResource); HttpResponse response = null; try { response = client.execute(get); statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 302) { Header location = response.getLastHeader("Location"); if (location != null) { URL url = new URL(location.getValue()); if (ursHost.equals(url.getHost())) { ursProtected = true; } currentResource = location.getValue(); } else { throw new IllegalStateException("Received redirect without Location header"); } } else if (statusCode >= 400) { throw new RuntimeException(response.getStatusLine().getReasonPhrase()); } } finally { HttpClientUtils.closeQuietly(response); } } if (statusCode == 200) { loggedIn = true; } } catch (IOException ex) { log.error("Error getting resource", ex); } return ursProtected && loggedIn; } @Override public HttpClient getClient(HttpParams params) { DefaultHttpClient client = new DefaultHttpClient(ccm, params); client.setCookieStore(cookieStore); client.setCredentialsProvider(credentialStore); return client; } @Override public void close() { cookieStore.clear(); credentialStore.clear(); if (ccm != null) { ccm.shutdown(); } } private void initClientConnectionManager() { SSLSocketFactory socketFactory = null; try { socketFactory = new SSLSocketFactory((X509Certificate[] xcs, String string) -> true, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) { throw new RuntimeException("Couldn't create socket factory", ex); } SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, new PlainSocketFactory())); registry.register(new Scheme("https", 443, socketFactory)); ccm = new PoolingClientConnectionManager(registry); } }
zjxkenshine/codedemo
springboot-demo/springbootdemo06-SQL/src/main/java/com/kenshine/jdbc/service/impl/UserServiceImpl.java
<gh_stars>1-10 package com.kenshine.jdbc.service.impl; import com.kenshine.jdbc.dao.IUserDao; import com.kenshine.jdbc.domain.User; import com.kenshine.jdbc.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author :kenshine * @date :Created in 2021/10/20 10:30 * @description:用户业务接口实现 * @modified By: * @version: $ */ @Service public class UserServiceImpl implements IUserService { @Autowired private IUserDao userDao; @Override public int add(User user) { return userDao.add(user); } @Override public int update(User user) { return userDao.update(user); } @Override public int delete(int id) { return userDao.delete(id); } @Override public User findUserById(int id) { return userDao.findUserById(id); } @Override public List<User> findUserList() { return userDao.findUserList(); } }
sarang-apps/darshan_browser
fuchsia/engine/common/web_engine_content_client.cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "fuchsia/engine/common/web_engine_content_client.h" #include "base/command_line.h" #include "fuchsia/base/fuchsia_dir_scheme.h" #include "fuchsia/engine/switches.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" WebEngineContentClient::WebEngineContentClient() = default; WebEngineContentClient::~WebEngineContentClient() = default; base::string16 WebEngineContentClient::GetLocalizedString(int message_id) { return l10n_util::GetStringUTF16(message_id); } base::StringPiece WebEngineContentClient::GetDataResource( int resource_id, ui::ScaleFactor scale_factor) { return ui::ResourceBundle::GetSharedInstance().GetRawDataResourceForScale( resource_id, scale_factor); } base::RefCountedMemory* WebEngineContentClient::GetDataResourceBytes( int resource_id) { return ui::ResourceBundle::GetSharedInstance().LoadDataResourceBytes( resource_id); } gfx::Image& WebEngineContentClient::GetNativeImageNamed(int resource_id) { return ui::ResourceBundle::GetSharedInstance().GetNativeImageNamed( resource_id); } blink::OriginTrialPolicy* WebEngineContentClient::GetOriginTrialPolicy() { NOTIMPLEMENTED_LOG_ONCE(); return nullptr; } void WebEngineContentClient::AddAdditionalSchemes(Schemes* schemes) { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kContentDirectories)) { schemes->standard_schemes.push_back(cr_fuchsia::kFuchsiaDirScheme); } }
StudyNoteOfTu/manlife
app/src/main/java/com/example/tufengyi/manlife/utils/tools/ObjectsAdapter.java
package com.example.tufengyi.manlife.utils.tools; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.tufengyi.manlife.R; import com.example.tufengyi.manlife.activities.FlagsActivity; import com.example.tufengyi.manlife.activities.MainActivity; import com.example.tufengyi.manlife.bean.Empty; import com.example.tufengyi.manlife.bean.HeadTitle; import com.example.tufengyi.manlife.bean.PunchedAss; import com.example.tufengyi.manlife.bean.SubTitle; import java.util.List; public class ObjectsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{ private int ITEM_HEADTITLE = 1; private int ITEM_SUBTITLE = 2; private int ITEM_PUNCHEDASS = 3; private int ITEM_EMPTY = 4; private List<Object> objects; private Context context; private int[] icons = { R.drawable.apples, R.drawable.vocabulary, R.drawable.water, R.drawable.breakfirst, R.drawable.makeup, R.drawable.night, R.drawable.read, R.drawable.shower, R.drawable.doctor, R.drawable.dailyarticle }; public ObjectsAdapter(List<Object> objects,Context context){ this.objects=objects; this.context = context; } @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType){ View view = null; RecyclerView.ViewHolder holder = null; if(viewType == ITEM_HEADTITLE){ view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler_toptitle,parent,false); holder = new ViewHolderTopTitle(view); }else if(viewType == ITEM_SUBTITLE){ view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler_title,parent,false); holder = new ViewHolderSubTitle(view); }else if(viewType == ITEM_PUNCHEDASS){ view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler_test,parent,false); holder = new ViewHolderPunched(view); }else if(viewType == ITEM_EMPTY){ view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler_empty,parent,false); holder = new ViewHolderEmpty(view); } return holder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position){ if(holder instanceof ViewHolderTopTitle){ HeadTitle ht= (HeadTitle) objects.get(position); ((ViewHolderTopTitle)holder).tv_topTitle.setText(ht.getDate()); }else if(holder instanceof ViewHolderSubTitle){ SubTitle st = (SubTitle) objects.get(position); //这里记得改 ((ViewHolderSubTitle)holder).tv_subTitle.setText(st.getDate()+"th"); }else if(holder instanceof ViewHolderPunched){ final PunchedAss pAss = (PunchedAss) objects.get(position); ((ViewHolderPunched)holder).img_ass.setBackgroundResource(icons[pAss.getIcon()]); ((ViewHolderPunched)holder).tv_ass.setText(pAss.getTitle()); }else if(holder instanceof ViewHolderEmpty){ Empty ep = (Empty) objects.get(position); } } @Override public int getItemViewType(int position){ if(objects.get(position) instanceof HeadTitle){ return ITEM_HEADTITLE; }else if(objects.get(position) instanceof SubTitle){ return ITEM_SUBTITLE; }else if(objects.get(position) instanceof PunchedAss){ return ITEM_PUNCHEDASS; }else if(objects.get(position) instanceof Empty){ return ITEM_EMPTY; } return super.getItemViewType(position); } @Override public int getItemCount(){ return objects ==null? 0:objects.size(); } }
Sledro/College-Programs
Year-2/Java/Object Oriented Programs/AssessOne/src/Product.java
<filename>Year-2/Java/Object Oriented Programs/AssessOne/src/Product.java /* @author <NAME> Student Number: C00137009 Date: November '15 Purpose: Assessemnt One */ public abstract class Product { //Start variables private int productID; private String productName; private String productDescription; @SuppressWarnings("unused") private float price; @SuppressWarnings("unused") private float qty; //Constructor public Product(int productID, String productName,String productDescription, float price, float qty) { super(); this.productID = productID; this.productName = productName; this.productDescription = productDescription; this.price = price; this.qty = qty; } //Set abstract method public abstract void calcExVat(float price); //Start setters and getters even though they are not used yet. /** * @return the productID */ public int getProductID() { return productID; } /** * @param productID the productID to set */ public void setProductID(int productID) { this.productID = productID; } /** * @return the productName */ public String getProductName() { return productName; } /** * @param productName the productName to set */ public void setProductName(String productName) { this.productName = productName; } /** * @return the productDescription */ public String getProductDescription() { return productDescription; } /** * @param productDescription the productDescription to set */ public void setProductDescription(String productDescription) { this.productDescription = productDescription; } /* (non-Javadoc) * @see java.lang.Object#toString() */ }
yingyingtang-brex/go-server-sdk
internal/datastore/data_store_eval_impl.go
package datastore import ( "gopkg.in/launchdarkly/go-sdk-common.v2/ldlog" ldeval "gopkg.in/launchdarkly/go-server-sdk-evaluation.v1" "gopkg.in/launchdarkly/go-server-sdk-evaluation.v1/ldmodel" "gopkg.in/launchdarkly/go-server-sdk.v5/interfaces" "gopkg.in/launchdarkly/go-server-sdk.v5/internal/datakinds" ) type dataStoreEvaluatorDataProviderImpl struct { store interfaces.DataStore loggers ldlog.Loggers } // NewDataStoreEvaluatorDataProviderImpl creates the internal implementation of the adapter that connects // the Evaluator (from go-server-sdk-evaluation) with the data store. func NewDataStoreEvaluatorDataProviderImpl(store interfaces.DataStore, loggers ldlog.Loggers) ldeval.DataProvider { return dataStoreEvaluatorDataProviderImpl{store, loggers} } func (d dataStoreEvaluatorDataProviderImpl) GetFeatureFlag(key string) *ldmodel.FeatureFlag { item, err := d.store.Get(datakinds.Features, key) if err == nil && item.Item != nil { data := item.Item if flag, ok := data.(*ldmodel.FeatureFlag); ok { return flag } d.loggers.Errorf("unexpected data type (%T) found in store for feature key: %s. Returning default value", data, key) } return nil } func (d dataStoreEvaluatorDataProviderImpl) GetSegment(key string) *ldmodel.Segment { item, err := d.store.Get(datakinds.Segments, key) if err == nil && item.Item != nil { data := item.Item if segment, ok := data.(*ldmodel.Segment); ok { return segment } d.loggers.Errorf("unexpected data type (%T) found in store for segment key: %s. Returning default value", data, key) } return nil }
ShaderKitty/geodesuka
inc/geodesuka/core/math.h
<reponame>ShaderKitty/geodesuka #pragma once #ifndef GEODESUKA_CORE_MATH_H #define GEODESUKA_CORE_MATH_H /*\\ ---------------------------------------- gclm.h ---------------------------------------- \\// Vector Notation: Vectors are to be treated as column vectors, but there is flexibility in left multiplication where the vector will serve as a row vector Matrix Notation: Memory Layout of these objects is by default column major, define ROW_MAJOR_MEMORY_LAYOUT in mconfig.h if row major memory layout is preferred. Row Count: M Column Count: N realMxN is a M x N matrix (aka real[ROWS]x[COLUMNS]) TODO List: //\\ ---------------------------------------- gclm.h ---------------------------------------- \\*/ #include <cmath> /* This header configures usage. */ #include "math/config.h" /* Basic Internal Utility Functions */ #include "math/util/isupport.h" /* -------------------- All Types Included here -------------------- */ /* Number Types */ #include "math/numbers/boolean.h" #include "math/numbers/natural.h" #include "math/numbers/integer.h" //#include "rational.h" Dumb Type #include "math/numbers/real.h" #include "math/numbers/complex.h" #include "math/numbers/quaternion.h" /* Built In Numerical Constants */ #include "math/numbers/constants.h" /* Vector Types */ #include "math/vectors/natural2.h" #include "math/vectors/natural3.h" #include "math/vectors/natural4.h" #include "math/vectors/integer2.h" #include "math/vectors/integer3.h" #include "math/vectors/integer4.h" #include "math/vectors/real2.h" #include "math/vectors/real3.h" #include "math/vectors/real4.h" /* Matrix Types */ /* * When accessing matrix elements, the notation is * math::realmxn A; * * Value = A(Row,Column); */ #include "math/matrices/real2x2.h" #include "math/matrices/real2x3.h" #include "math/matrices/real2x4.h" #include "math/matrices/real3x2.h" #include "math/matrices/real3x3.h" #include "math/matrices/real3x4.h" #include "math/matrices/real4x2.h" #include "math/matrices/real4x3.h" #include "math/matrices/real4x4.h" /* Inter-Matrix Multiplication */ #include "math/util/matrix_multiply.h" /* Matrix Multiplication Functions */ /* Scalar Field Types */ //#include "R1.h" //#include "R2.h" //#include "R3.h" //#include "R4.h" /* Vector Field Types */ //#include "real2_field.h" //#include "real3_field.h" //#include "real4_field.h" /* -------------------- Extended Functions -------------------- */ /* Utility Functions */ #include "math/util/fsupport.h" #endif // !GEODESUKA_CORE_MATH_H
phantomjinx/modeshape
integration/modeshape-jbossas-integration-tests/src/test/java/org/modeshape/test/integration/JdbcDriverIntegrationTest.java
<reponame>phantomjinx/modeshape /* * ModeShape (http://www.modeshape.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.modeshape.test.integration; import org.jboss.arquillian.junit.Arquillian; import org.junit.runner.RunWith; import org.modeshape.jdbc.JcrHttpDriverIntegrationTest; /** * Extension of the {@link JcrHttpDriverIntegrationTest} which runs the same tests, via Arquillian, in an AS7 container with the * ModeShape distribution kit deployed. * * @author <NAME> */ @RunWith( Arquillian.class ) public class JdbcDriverIntegrationTest extends JcrHttpDriverIntegrationTest { @Override protected String getWorkspaceName() { //must match the default config from standalone.xml return "default"; } @Override protected String getUserName() { //must be a valid user name from the ModeShape AS security domain return "admin"; } @Override protected String getRepositoryName() { //must match the default config from standalone.xml return "sample"; } @Override protected String getPassword() { //must be a password for the above user, from the ModeShape AS security domain return "<PASSWORD>"; } @Override protected String getContextPathUrl() { //this should be the context of the web application deployed inside AS7 return"localhost:8080/modeshape-rest"; } }
Ricky-Nz/knocknock-web
src/utils.js
<gh_stars>1-10 import Relay from 'react-relay'; export const preparePageParams = ({query}) => { if (query.first) { return { first: parseInt(query.first||5), after: query.after||null, search: query.search||null }; } else { return { last: parseInt(query.last||5), before: query.before||null, search: query.search||null }; } }; export function paginationVariables(additionalParams, prepareParams) { return { initialVariables: { search: '', first: 10, last: 0, after: null, before: null, reverse: false, ...additionalParams }, prepareVariables: (variables) => { return { ...variables, reverse: variables.last > 0, ...prepareParams&&prepareParams(variables) } } }; } export const pageInfoFragment = Relay.QL` fragment on PageInfo { hasNextPage hasPreviousPage endCursor startCursor } `;
1056215801/-MITC-YING_TAN
modules/MIT-Cloud/MIT-Cloud-server/src/main/java/com/mit/cloud/service/TestBookService.java
package com.mit.cloud.service; import com.baomidou.mybatisplus.plugins.Page; import com.mit.cloud.dao.TestBookMapper; import com.mit.cloud.model.TestBook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * 测试Service * * @author shuyy * @date 2018/11/9 * @company mitesofor */ @Service public class TestBookService { @Autowired private TestBookMapper testBookMapper; public void insert(){ TestBook testBook = new TestBook(); testBook.setName("舒园园"); testBook.setAuthor("金庸"); testBook.setPrice(1000); testBookMapper.insert(testBook); if(testBook != null){ throw new RuntimeException("错误"); } } public Page<TestBook> listPage(Integer pageNum, Integer pageSize){ Page<TestBook> page = new Page<>(); page.setCurrent(pageNum); page.setSize(pageSize); testBookMapper.selectPage(page, null); return null; } }
Chulei799/work
src/main/java/com/qaprosoft/carina/work/mobile/gui/pages/common/AddMealPageBase.java
package com.qaprosoft.carina.work.mobile.gui.pages.common; import com.qaprosoft.carina.core.gui.AbstractPage; import com.qaprosoft.carina.work.mobile.gui.pages.constants.IConstants; import org.openqa.selenium.WebDriver; public abstract class AddMealPageBase extends AbstractPage implements IConstants { public AddMealPageBase(WebDriver driver) { super(driver); } public abstract DiaryPageBase submitMeal(); }
liuyahui0519/iBase4J
iBase4J-SYS-Service/src/main/java/org/ibase4j/core/listener/SysServerListener.java
<gh_stars>0 package org.ibase4j.core.listener; import javax.servlet.ServletContextEvent; import org.ibase4j.service.ISysCacheService; import org.ibase4j.service.ISysDicService; import org.ibase4j.service.ISysUserService; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; import com.weibo.api.motan.common.MotanConstants; import com.weibo.api.motan.util.MotanSwitcherUtil; import top.ibase4j.core.listener.ServerListener; /** * @author ShenHuaJie * @since 2018年3月3日 下午7:28:29 */ @SuppressWarnings("deprecation") public class SysServerListener extends ServerListener { public void contextInitialized(ServletContextEvent contextEvent) { MotanSwitcherUtil.setSwitcherValue(MotanConstants.REGISTRY_HEARTBEAT_SWITCHER, true); WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext(); context.getBean(ISysCacheService.class).flush(); context.getBean(ISysUserService.class).init(); context.getBean(ISysDicService.class).getAllDic(); super.contextInitialized(contextEvent); } }
cirope/mawidabp
app/controllers/conclusion_draft_reviews_controller.rb
<gh_stars>1-10 class ConclusionDraftReviewsController < ApplicationController before_action :auth, :load_privileges, :check_privileges before_action :set_conclusion_draft_review, only: [ :show, :edit, :update, :export_to_pdf, :export_to_rtf, :score_sheet, :download_work_papers, :create_bundle, :compose_email, :send_by_email ] layout proc{ |controller| controller.request.xhr? ? false : 'application' } # Lista los informes borradores # # * GET /conclusion_draft_reviews def index @title = t 'conclusion_draft_review.index_title' @conclusion_draft_reviews = ConclusionDraftReview.list.includes( review: [ :period, :conclusion_final_review, plan_item: :business_unit ] ).search( **search_params ).references( :reviews, :business_units ).merge( PlanItem.allowed_by_business_units ).order_by.page params[:page] respond_to do |format| format.html end end # Muestra el detalle de un informe borrador # # * GET /conclusion_draft_reviews/1 def show @title = t 'conclusion_draft_review.show_title' respond_to do |format| format.html # show.html.erb end end # Permite ingresar los datos para crear un nuevo informe borrador # # * GET /conclusion_draft_reviews/new def new @title = t 'conclusion_draft_review.new_title' @conclusion_draft_review = ConclusionDraftReview.new(review_id: params[:review]) @conclusion_draft_review.review&.build_best_practice_comments respond_to do |format| format.html # new.html.erb format.js # new.js.erb end end # Recupera los datos para modificar un informe borrador # # * GET /conclusion_draft_reviews/1/edit def edit @title = t 'conclusion_draft_review.edit_title' @conclusion_draft_review.review.build_best_practice_comments end # Crea un nuevo informe borrador siempre que cumpla con las validaciones. # # * POST /conclusion_draft_reviews def create @title = t 'conclusion_draft_review.new_title' @conclusion_draft_review = ConclusionDraftReview.list.new( conclusion_draft_review_params) respond_to do |format| if @conclusion_draft_review.save flash.notice = t 'conclusion_draft_review.correctly_created' format.html { redirect_to(edit_conclusion_draft_review_url(@conclusion_draft_review)) } else format.html { render action: :new } end end end # Actualiza el contenido de un informe borrador siempre que cumpla con las # validaciones. # # * PATCH /conclusion_draft_reviews/1 def update @title = t 'conclusion_draft_review.edit_title' respond_to do |format| if @conclusion_draft_review.update(conclusion_draft_review_params) flash.notice = t 'conclusion_draft_review.correctly_updated' format.html { redirect_to(edit_conclusion_draft_review_url(@conclusion_draft_review)) } else format.html { render action: :edit } end end rescue ActiveRecord::StaleObjectError flash.alert = t 'conclusion_draft_review.stale_object_error' redirect_to edit_conclusion_draft_review_url(@conclusion_draft_review) end # Exporta el informe en formato PDF # # * GET /conclusion_draft_reviews/export_to_pdf/1 def export_to_pdf options = params[:export_options]&.to_unsafe_h @conclusion_draft_review.to_pdf(current_organization, options) respond_to do |format| format.html { redirect_to @conclusion_draft_review.relative_pdf_path } end end # Exporta el informe en formato RTF # # * GET /conclusion_draft_reviews/export_to_rtf/1 def export_to_rtf respond_to do |format| format.rtf do render rtf: @conclusion_draft_review.to_rtf(current_organization), filename: @conclusion_draft_review.rtf_name end end end # Crea la planilla de calificación del informe en formato PDF # # * GET /conclusion_draft_reviews/score_sheet/1 def score_sheet review = @conclusion_draft_review.review if params[:global].blank? review.score_sheet(current_organization, draft: true) redirect_to review.relative_score_sheet_path else review.global_score_sheet(current_organization, draft: true) redirect_to review.relative_global_score_sheet_path end end # Devuelve los papeles de trabajo del informe # # * GET /conclusion_draft_reviews/download_work_papers/1 def download_work_papers review = @conclusion_draft_review.review review.zip_all_work_papers current_organization redirect_to review.relative_work_papers_zip_path end # Crea el legajo completo del informe # # * POST /conclusion_draft_reviews/create_bundle def create_bundle @conclusion_draft_review.create_bundle_zip current_organization, params[:index_items] @report_path = @conclusion_draft_review.relative_bundle_zip_path respond_to do |format| format.html { redirect_to @report_path } format.js { render 'shared/pdf_report' } end end # Confecciona el correo con el informe # # * GET /conclusion_draft_reviews/compose_email/1 def compose_email @title = t 'conclusion_draft_review.send_by_email' end # Envia por correo el informe a los usuarios indicados # # * POST /conclusion_draft_reviews/send_by_email/1 def send_by_email @title = t 'conclusion_draft_review.send_by_email' if @conclusion_draft_review.try(:review).try(:can_be_sended?) users = [] export_options = params[:export_options] || {} if params[:conclusion_review] include_score_sheet = params[:conclusion_review][:include_score_sheet] == '1' include_global_score_sheet = params[:conclusion_review][:include_global_score_sheet] == '1' note = params[:conclusion_review][:email_note] review_type = params[:conclusion_review][:review_type] if review_type == 'brief' export_options[:brief] = '1' elsif review_type == 'without_score' export_options[:hide_score] = '1' end end @conclusion_draft_review.to_pdf(current_organization, export_options) if include_score_sheet @conclusion_draft_review.review.score_sheet current_organization, draft: true end if include_global_score_sheet @conclusion_draft_review.review.global_score_sheet(current_organization, draft: true) end (params[:user].try(:values).try(:reject, &:blank?) || []).each do |user_data| user = User.find_by(id: user_data[:id]) if user_data[:id] send_options = { note: note, include_score_sheet: include_score_sheet, include_global_score_sheet: include_global_score_sheet } if user && !users.include?(user) @conclusion_draft_review.send_by_email_to(user, send_options) users << user end end unless users.blank? flash.notice = t('conclusion_review.review_sended') redirect_to edit_conclusion_draft_review_url( @conclusion_draft_review) else render action: :compose_email end elsif @conclusion_draft_review.try(:review) flash.alert = t('conclusion_review.review_not_approved') render action: :compose_email else redirect_to conclusion_draft_reviews_url end end def check_for_approval if params[:id] && params[:id].to_i > 0 review = Review.includes(:period).where( id: params[:id], "#{Period.table_name}.organization_id" => current_organization.id ).references(:periods).first response = { approved: review.is_approved?, can_be_approved_by_force: review.can_be_approved_by_force, errors: review.approval_errors } else response = {} end respond_to do |format| format.json { render json: response } end end def corrective_actions_update respond_to do |format| format.js end end private def set_conclusion_draft_review @conclusion_draft_review = ConclusionDraftReview.list.includes( review: [ :period, :conclusion_final_review, :plan_item, { control_objective_items: [:control, :weaknesses, :oportunities] } ] ).find(params[:id]) @conclusion_draft_review = nil if @conclusion_draft_review.has_final_review? end def conclusion_draft_review_params params.require(:conclusion_draft_review).permit( :review_id, :issue_date, :close_date, :applied_procedures, :conclusion, :recipients, :sectors, :evolution, :evolution_justification, :observations, :main_weaknesses_text, :corrective_actions, :affects_compliance, :collapse_control_objectives, :force_approval, :reference, :scope, :previous_identification, :previous_date, :main_recommendations, :effectiveness_notes, :additional_comments, :lock_version, review_attributes: [ :id, :manual_score, :description, :lock_version, best_practice_comments_attributes: [ :id, :best_practice_id, :auditor_comment ] ], annexes_attributes: [ :id, :title, :description, :_destroy, image_models_attributes: [ :id, :image, :image_cache, :_destroy ] ] ) end def load_privileges @action_privileges.update( export_to_pdf: :read, score_sheet: :read, download_work_papers: :read, bundle: :read, create_bundle: :read, check_for_approval: :read, compose_email: :modify, send_by_email: :modify ) end end
liambaloh/OpenEOB
Assets/StreamingAssets/tgui/packages/tgui/interfaces/AtmosMixer.js
import { useBackend } from '../backend'; import { Button, LabeledList, NumberInput, Section } from '../components'; import { Window } from '../layouts'; export const AtmosMixer = (props, context) => { const { act, data } = useBackend(context); return ( <Window> <Window.Content> <Section> <LabeledList> <LabeledList.Item label="Power"> <Button icon={data.on ? 'power-off' : 'times'} content={data.on ? 'On' : 'Off'} selected={data.on} onClick={() => act('power')} /> </LabeledList.Item> <LabeledList.Item label="Output Pressure"> <NumberInput animated value={parseFloat(data.set_pressure)} unit="kPa" width="75px" minValue={0} maxValue={4500} step={10} onChange={(e, value) => act('pressure', { pressure: value, })} /> <Button ml={1} icon="plus" content="Max" disabled={data.set_pressure === data.max_pressure} onClick={() => act('pressure', { pressure: 'max', })} /> </LabeledList.Item> <LabeledList.Item label="Node 1"> <NumberInput animated value={data.node1_concentration} unit="%" width="60px" minValue={0} maxValue={100} stepPixelSize={2} onDrag={(e, value) => act('node1', { concentration: value, })} /> </LabeledList.Item> <LabeledList.Item label="Node 2"> <NumberInput animated value={data.node2_concentration} unit="%" width="60px" minValue={0} maxValue={100} stepPixelSize={2} onDrag={(e, value) => act('node2', { concentration: value, })} /> </LabeledList.Item> </LabeledList> </Section> </Window.Content> </Window> ); };
Neusoft-Technology-Solutions/aws-sdk-cpp
aws-cpp-sdk-mq/include/aws/mq/model/ListConfigurationRevisionsRequest.h
<filename>aws-cpp-sdk-mq/include/aws/mq/model/ListConfigurationRevisionsRequest.h<gh_stars>0 /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/mq/MQ_EXPORTS.h> #include <aws/mq/MQRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Http { class URI; } //namespace Http namespace MQ { namespace Model { /** */ class AWS_MQ_API ListConfigurationRevisionsRequest : public MQRequest { public: ListConfigurationRevisionsRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "ListConfigurationRevisions"; } Aws::String SerializePayload() const override; void AddQueryStringParameters(Aws::Http::URI& uri) const override; /** * The unique ID that Amazon MQ generates for the configuration. */ inline const Aws::String& GetConfigurationId() const{ return m_configurationId; } /** * The unique ID that Amazon MQ generates for the configuration. */ inline bool ConfigurationIdHasBeenSet() const { return m_configurationIdHasBeenSet; } /** * The unique ID that Amazon MQ generates for the configuration. */ inline void SetConfigurationId(const Aws::String& value) { m_configurationIdHasBeenSet = true; m_configurationId = value; } /** * The unique ID that Amazon MQ generates for the configuration. */ inline void SetConfigurationId(Aws::String&& value) { m_configurationIdHasBeenSet = true; m_configurationId = std::move(value); } /** * The unique ID that Amazon MQ generates for the configuration. */ inline void SetConfigurationId(const char* value) { m_configurationIdHasBeenSet = true; m_configurationId.assign(value); } /** * The unique ID that Amazon MQ generates for the configuration. */ inline ListConfigurationRevisionsRequest& WithConfigurationId(const Aws::String& value) { SetConfigurationId(value); return *this;} /** * The unique ID that Amazon MQ generates for the configuration. */ inline ListConfigurationRevisionsRequest& WithConfigurationId(Aws::String&& value) { SetConfigurationId(std::move(value)); return *this;} /** * The unique ID that Amazon MQ generates for the configuration. */ inline ListConfigurationRevisionsRequest& WithConfigurationId(const char* value) { SetConfigurationId(value); return *this;} /** * The maximum number of configurations that Amazon MQ can return per page (20 by * default). This value must be an integer from 5 to 100. */ inline int GetMaxResults() const{ return m_maxResults; } /** * The maximum number of configurations that Amazon MQ can return per page (20 by * default). This value must be an integer from 5 to 100. */ inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; } /** * The maximum number of configurations that Amazon MQ can return per page (20 by * default). This value must be an integer from 5 to 100. */ inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; } /** * The maximum number of configurations that Amazon MQ can return per page (20 by * default). This value must be an integer from 5 to 100. */ inline ListConfigurationRevisionsRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;} /** * The token that specifies the next page of results Amazon MQ should return. To * request the first page, leave nextToken empty. */ inline const Aws::String& GetNextToken() const{ return m_nextToken; } /** * The token that specifies the next page of results Amazon MQ should return. To * request the first page, leave nextToken empty. */ inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; } /** * The token that specifies the next page of results Amazon MQ should return. To * request the first page, leave nextToken empty. */ inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; } /** * The token that specifies the next page of results Amazon MQ should return. To * request the first page, leave nextToken empty. */ inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); } /** * The token that specifies the next page of results Amazon MQ should return. To * request the first page, leave nextToken empty. */ inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); } /** * The token that specifies the next page of results Amazon MQ should return. To * request the first page, leave nextToken empty. */ inline ListConfigurationRevisionsRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;} /** * The token that specifies the next page of results Amazon MQ should return. To * request the first page, leave nextToken empty. */ inline ListConfigurationRevisionsRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;} /** * The token that specifies the next page of results Amazon MQ should return. To * request the first page, leave nextToken empty. */ inline ListConfigurationRevisionsRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;} private: Aws::String m_configurationId; bool m_configurationIdHasBeenSet; int m_maxResults; bool m_maxResultsHasBeenSet; Aws::String m_nextToken; bool m_nextTokenHasBeenSet; }; } // namespace Model } // namespace MQ } // namespace Aws