text
stringlengths
1
1.05M
<gh_stars>0 /* * Copyright (C) 2012 Atlassian * * 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.atlassian.jira.tests.rules; import com.atlassian.jira.functest.framework.WebTestDescription; import com.atlassian.jira.functest.framework.suite.JUnit4WebTestDescription; import com.atlassian.jira.pageobjects.JiraTestedProduct; import com.atlassian.jira.pageobjects.config.TestEnvironment; import com.atlassian.webdriver.AtlassianWebDriver; import com.atlassian.webdriver.browsers.WebDriverBrowserAutoInstall; import org.apache.commons.io.FileUtils; import org.hamcrest.StringDescription; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; public class WebDriverScreenshot extends TestWatcher { private static final Logger logger = LoggerFactory.getLogger(WebDriverScreenshot.class); private final WebDriver driver; private final TestEnvironment testEnvironment = new TestEnvironment(); public WebDriverScreenshot(AtlassianWebDriver webDriver) { this.driver = webDriver.getDriver(); } public WebDriverScreenshot(JiraTestedProduct product) { this(product.getTester().getDriver()); } public WebDriverScreenshot() { this(WebDriverBrowserAutoInstall.INSTANCE.getDriver()); } @Override protected void failed(Throwable e, Description description) { attemptScreenshot(new JUnit4WebTestDescription(description)); } private void attemptScreenshot(WebTestDescription description) { if (!isScreenshotCapable()) { logger.warn(new StringDescription().appendText("Unable to take screenshot: WebDriver ") .appendValue(driver).appendText(" is not instance of TakesScreenshot").toString()); return; } takeScreenshot(description); } private void takeScreenshot(WebTestDescription description) { try { TakesScreenshot takingScreenshot = (TakesScreenshot) driver; File screenshot = takingScreenshot.getScreenshotAs(OutputType.FILE); File target = new File(testEnvironment.artifactDirectory(), fileName(description)); FileUtils.copyFile(screenshot, target); logger.info("A screenshot of the page has been stored under " + target.getAbsolutePath()); } catch(Exception e) { logger.error(new StringDescription().appendText("Unable to take screenshot for failed test ") .appendValue(description).toString(), e); } } private String fileName(WebTestDescription description) { return description.testClass().getSimpleName() + "." + description.methodName() + ".png"; } private boolean isScreenshotCapable() { return driver instanceof TakesScreenshot; } }
<reponame>daniel-baf/magazine-app<filename>Magazine-Api/src/main/java/DB/DAOs/Magazine/Financials/CommentInsert.java<gh_stars>0 package DB.DAOs.Magazine.Financials; import DB.DBConnection; import DB.Domain.Magazine.Comment; import BackendUtilities.Parser; import java.sql.PreparedStatement; import java.sql.SQLException; /** * This class insert comments to DB * * @author jefemayoneso */ public class CommentInsert { private String SQL_INSERT_COMMENT = "INSERT INTO Comment (date, text, user, magazine) VALUES (?, ?, ?, ?)"; public int insert(Comment comment) { try ( PreparedStatement ps = DBConnection.getConnection().prepareStatement(SQL_INSERT_COMMENT)) { configurePsInsert(ps, comment); return ps.executeUpdate(); } catch (Exception e) { System.out.println("Error while trying to insert COmment at [CommentInsert] " + e.getMessage()); return 0; } } /** * COnfigure a PS with a Comment object for inserts * * @param ps * @param comment * @throws SQLException */ private void configurePsInsert(PreparedStatement ps, Comment comment) throws SQLException { Parser parser = new Parser(); ps.setDate(1, parser.toDate(comment.getDate())); ps.setString(2, comment.getText()); ps.setString(3, comment.getUser()); ps.setString(4, comment.getMagazine()); } }
<reponame>pjmolina/event-backend angular.module('myApp').filter('checkmark', function() { return function(input) { if (input == null) { return '-'; } return input ? '\u2713' : '\u2718'; }; });
def mean(arr): return sum(arr)/len(arr) arr = [2, 4, 5, 7] mean_val = mean(arr) print("Mean of the array is", mean_val) # Output: Mean of the array is 4.5
#!/bin/bash cat << EOF > ${zfs_pkgbuild_path}/PKGBUILD ${header} pkgbase="${zfs_pkgname}" pkgname=("${zfs_pkgname}" "${zfs_pkgname}-headers") ${zfs_set_commit} _zfsver="${zfs_pkgver}" _kernelver="${kernel_version}" _extramodules="${kernel_mod_path}" pkgver="\${_zfsver}_\$(echo \${_kernelver} | sed s/-/./g)" pkgrel=${zfs_pkgrel} makedepends=(${linux_headers_depends} ${zfs_makedepends}) arch=("x86_64") url="https://zfsonlinux.org/" source=("${zfs_src_target}") sha256sums=("${zfs_src_hash}") license=("CDDL") depends=("kmod" "${zfs_utils_pkgname}" ${linux_depends}) build() { cd "${zfs_workdir}" ./autogen.sh ./configure --prefix=/usr --sysconfdir=/etc --sbindir=/usr/bin --libdir=/usr/lib \\ --datadir=/usr/share --includedir=/usr/include --with-udevdir=/usr/lib/udev \\ --libexecdir=/usr/lib --with-config=kernel \\ --with-linux=/usr/lib/modules/\${_extramodules}/build \\ --with-linux-obj=/usr/lib/modules/\${_extramodules}/build make } package_${zfs_pkgname}() { pkgdesc="Kernel modules for the Zettabyte File System." install=zfs.install provides=("zfs" "spl") groups=("${archzfs_package_group}") conflicts=("zfs-dkms" "zfs-dkms-git" "zfs-dkms-rc" "spl-dkms" "spl-dkms-git" ${zfs_conflicts}) ${zfs_replaces} cd "${zfs_workdir}" make DESTDIR="\${pkgdir}" INSTALL_MOD_PATH=/usr install # Remove src dir rm -r "\${pkgdir}"/usr/src } package_${zfs_pkgname}-headers() { pkgdesc="Kernel headers for the Zettabyte File System." provides=("zfs-headers" "spl-headers") conflicts=("zfs-headers" "zfs-dkms" "zfs-dkms-git" "zfs-dkms-rc" "spl-dkms" "spl-dkms-git" "spl-headers") cd "${zfs_workdir}" make DESTDIR="\${pkgdir}" install rm -r "\${pkgdir}/lib" # Remove reference to \${srcdir} sed -i "s+\${srcdir}++" \${pkgdir}/usr/src/zfs-*/\${_extramodules}/Module.symvers } EOF pkgbuild_cleanup "${zfs_pkgbuild_path}/PKGBUILD"
public class UniqueCharacters { public static void main(String[] args) { String s = "hello"; char[] arr = s.toCharArray(); Arrays.sort(arr); Set<Character> characters = new HashSet<Character>(); for (Character c : arr) { characters.add(c); } System.out.println("Unique characters in the string: "+ characters); } }
SELECT FirstName, LastName, Gender FROM people ORDER BY Age DESC LIMIT 1;
<gh_stars>0 package domaine.ucc; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import core.AppContext; import core.config.AppConfig; import core.exceptions.BizzException; import core.injecteur.InjecteurDependance.Injecter; import dal.dao.core.DaoFactoryImpl; import domaine.dto.AnnulationDto; import domaine.dto.ChoixMobiliteDto; import domaine.dto.ChoixMobiliteDto.Etat; import domaine.dto.DemandeMobiliteDto; import domaine.dto.DepartementDto; import domaine.dto.DocumentDto; import domaine.dto.LogicielDto; import domaine.dto.PartenaireDto; import domaine.dto.PaysDto; import domaine.dto.ProgrammeDto; import domaine.dto.TypeProgrammeDto; import domaine.dto.UserDto; import domaine.dto.UserInfoDto; import domaine.factory.EntiteFactory; import domaine.ucc.interfaces.EtudiantUcc; import domaine.ucc.interfaces.ProfesseurUcc; import domaine.ucc.interfaces.QuidamUcc; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; public class EtudiantUccTest { private static AppContext ct; @Injecter private EntiteFactory factory; @Injecter private EtudiantUcc etudUcc; @Injecter private QuidamUcc quidUcc; @Injecter private ProfesseurUcc profUcc; private DemandeMobiliteDto demandeMob; private ChoixMobiliteDto choixMob; private UserDto user; private PartenaireDto partenaire; private UserInfoDto userInfos; private DepartementDto departement; private AnnulationDto annulation; private DocumentDto document; @BeforeClass public static void setUpBeforeClass() { ct = new AppContext(AppContext.Profil.TEST, "Gerasmus"); } @Before public void setUp() { ct.getInjector().removeFromCache(DaoFactoryImpl.class); ct.getInjector().removeFromCache(EtudiantUccImpl.class); ct.getInjector().removeFromCache(ProfesseurUccImpl.class); ct.getInjector().removeFromCache(QuidamUccImpl.class); ct.getInjector().injectByAnnotedField(this); demandeMob = factory.getDemandeMobilite(); choixMob = factory.getChoixMobilite(); user = factory.getUser(); partenaire = factory.getPartenaire(); userInfos = factory.getUserInfo(); departement = factory.getDepartement(); annulation = factory.getAnnulation(); document = factory.getDocument(); } @Test(expected = BizzException.class) public void testChangerEtatParametres() { etudUcc.changerEtat(null); } @Test(expected = BizzException.class) public void testChangerEtatCompteManquant() { quidUcc.inscrire(user); choixMob.setEtat(Etat.CONFIRME); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); userInfos.setCompteBancaire(null); etudUcc.encoderInformationsPersonnelles(userInfos); choixMob.setEtat(Etat.DEMANDE_PAYEMENT); etudUcc.changerEtat(choixMob); } @Test(expected = BizzException.class) public void testChangerEtatMobiliteObsolete() { quidUcc.inscrire(user); choixMob.setEtat(Etat.CONFIRME); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); etudUcc.encoderInformationsPersonnelles(userInfos); choixMob.setEtat(Etat.DEMANDE_PAYEMENT); ChoixMobiliteDto choixMob2 = factory.getChoixMobilite(); choixMob2.setEtat(Etat.DEMANDE_PAYEMENT_SOLDE); choixMob2.setNumeroVersion(1); choixMob.setNumeroVersion(choixMob2.getNumeroVersion()); etudUcc.changerEtat(choixMob2); etudUcc.changerEtat(choixMob); } @Test public void testChangerEtatValide() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); etudUcc.confirmerPartenaire(choixMob); userInfos.setUtilisateur(user); etudUcc.encoderInformationsPersonnelles(userInfos); ChoixMobiliteDto choixMob2 = factory.getChoixMobilite(); choixMob2.setEtat(Etat.A_PAYER); etudUcc.changerEtat(choixMob2); List<ChoixMobiliteDto> liste = etudUcc.recupererMobilitesPourDemande(demandeMob); assertEquals("L'etat de la mobilité doit correspondre.", choixMob.getEtat(), liste.get(0).getEtat()); } @Test(expected = Exception.class) public void testDeclarerChoixParametres() { etudUcc.declarerChoix(null); } @Test(expected = BizzException.class) public void testDeclarerChoixDemandeExisteDeja() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); choixMob.setId(2); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); } @Test(expected = BizzException.class) public void testDeclarerChoixDemandeUtilisateurInexistant() { demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); } @Test(expected = BizzException.class) public void testDeclarerChoixDemandeMobiliteNull() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList((ChoixMobiliteDto) null)); etudUcc.declarerChoix(demandeMob); } @Test public void testDeclarerChoixDemandeInvalide() { quidUcc.inscrire(user); DemandeMobiliteDto demande = factory.getDemandeMobilite(); try { demande.setChoixMobilites(Arrays.asList(choixMob)); demande.setAnneeAcademique(0); etudUcc.declarerChoix(demande); fail("L'année académique doit être supérieur à zéro."); } catch (Exception e) { assertTrue(true); } try { demande = factory.getDemandeMobilite(); demande.setChoixMobilites(Arrays.asList(choixMob)); demande.setEtudiant(null); etudUcc.declarerChoix(demande); fail("Il doit y avoir un créateur pour la demande de mobilité."); } catch (Exception e) { assertTrue(true); } } @Test public void testDeclarerChoixDemandeValide() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); List<ChoixMobiliteDto> liste = etudUcc.recupererMobilitesPourDemande(demandeMob); assertEquals("L'etat de la mobilité doit correspondre.", choixMob.getEtat(), liste.get(0).getEtat()); assertEquals("La demande doit correspondre.", choixMob.getDemande().getId(), liste.get(0).getDemande().getId()); } @Test public void testAjouterPartenaireParametres() { try { etudUcc.ajouterPartenaire(null, null); fail("L'utilisateur et le partenaire ne peut être nulle."); } catch (BizzException e) { assertTrue(true); } try { etudUcc.ajouterPartenaire(null, partenaire); fail("L'utilisateur ne peut être nulle."); } catch (BizzException e) { assertTrue(true); } try { etudUcc.ajouterPartenaire(user, null); fail("Le partenaire ne peut être nulle."); } catch (BizzException e) { assertTrue(true); } } @Test public void testAjouterPartenaireChampManquant() { quidUcc.inscrire(user); try { partenaire.setNomLegal(null); etudUcc.ajouterPartenaire(user, partenaire); fail("Le nom légale du partenaire ne doit pas être nulle."); } catch (BizzException e) { assertTrue(true); } try { partenaire.setNomAffaire(null); etudUcc.ajouterPartenaire(user, partenaire); fail("Le nom d'affaire du partenaire ne doit pas être nulle."); } catch (BizzException e) { assertTrue(true); } try { partenaire.setPays(null); etudUcc.ajouterPartenaire(user, partenaire); fail("Le nom légale du partenaire ne doit pas être nulle."); } catch (BizzException e) { assertTrue(true); } try { partenaire.setVille(null); etudUcc.ajouterPartenaire(user, partenaire); fail("La ville du partenaire ne doit pas être nulle."); } catch (BizzException e) { assertTrue(true); } try { partenaire.setMail(null); etudUcc.ajouterPartenaire(user, partenaire); fail("L'adresse mail du partenaire ne doit pas être nulle."); } catch (BizzException e) { assertTrue(true); } } @Test(expected = BizzException.class) public void testAjouterPartenaireUtilisateurInexistant() { etudUcc.ajouterPartenaire(user, partenaire); } @Test public void testAjouterPartenaireUtilisateurCorrespondant() { quidUcc.inscrire(user); partenaire.setIplDepartements(new ArrayList<DepartementDto>(Arrays.asList(departement))); PartenaireDto part = etudUcc.ajouterPartenaire(user, partenaire); assertEquals("L'utilisateur ne correspondant pas au créateur du partenaire.", user.getId(), part.getCreateur().getId()); } @Test public void testAjouterPartenaireChampOptionelle() { UserDto userDto = factory.getUser(); quidUcc.inscrire(userDto); PartenaireDto part1 = factory.getPartenaire(); part1.setCodePostal(null); part1.setIplDepartements(new ArrayList<DepartementDto>(Arrays.asList(departement))); try { etudUcc.ajouterPartenaire(userDto, part1); assertTrue(true); } catch (Exception e) { fail("Le code postal du partenaire est un champ optionelle."); } PartenaireDto part2 = factory.getPartenaire(); part2.setNomcomplet(null); part2.setIplDepartements(new ArrayList<DepartementDto>(Arrays.asList(departement))); try { etudUcc.ajouterPartenaire(userDto, part2); assertTrue(true); } catch (Exception e) { fail("Le nom complet du partenaire est un champ optionelle."); } PartenaireDto part3 = factory.getPartenaire(); part3.setNbEmploye(0); part3.setIplDepartements(new ArrayList<DepartementDto>(Arrays.asList(departement))); try { etudUcc.ajouterPartenaire(userDto, part3); assertTrue(true); } catch (Exception e) { fail("Le nombre d'employé du partenaire est un champ optionelle."); } } @Test public void testAjouterPartenaireUtilisateurProfNonCorrespondant() { quidUcc.inscrire(user); user.setProf(true); partenaire.setIplDepartements(new ArrayList<DepartementDto>(Arrays.asList(departement))); PartenaireDto part = etudUcc.ajouterPartenaire(user, partenaire); assertNull("Le partenaire ne doit pas avoir d'utilisateur-créateur.", part.getCreateur()); } @Test(expected = BizzException.class) public void testAnnulerChoixMobiliterParametres() { etudUcc.annulerChoixMobilite(null); } @Test(expected = BizzException.class) public void testAnnulerChoixMobiliterUtilisateurInexistant() { choixMob.setMotifAnnulation(annulation); etudUcc.annulerChoixMobilite(choixMob); } @Test(expected = BizzException.class) public void testAnnulerChoixMobiliterDemandeInexistante() { quidUcc.inscrire(user); choixMob.setMotifAnnulation(annulation); etudUcc.annulerChoixMobilite(choixMob); } @Test(expected = BizzException.class) public void testAnnulerChoixMobiliterUtilisateurPasCreateur() { UserDto user2 = factory.getUser(); user2.setId(2); quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); quidUcc.inscrire(user2); annulation.setCreateur(user2); choixMob.setMotifAnnulation(annulation); etudUcc.annulerChoixMobilite(choixMob); } @Test public void testAnnulerChoixMobiliterAnnulationChampVide() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); AnnulationDto annulation2 = factory.getAnnulation(); try { annulation2.setCreateur(null); choixMob.setMotifAnnulation(annulation2); etudUcc.annulerChoixMobilite(choixMob); fail("Il doit y avoir un créateur pour l'annulation."); } catch (Exception e) { assertTrue(true); } try { annulation2 = factory.getAnnulation(); user.setId(0); annulation2.setCreateur(user); choixMob.setMotifAnnulation(annulation2); etudUcc.annulerChoixMobilite(choixMob); fail("Il doit y avoir un créateur pour l'annulation."); } catch (Exception e) { assertTrue(true); } } @Test(expected = BizzException.class) public void testAnnulerChoixMobiliterObsolete() { AnnulationDto annulation2 = factory.getAnnulation(); annulation2.setId(2); choixMob.setNumeroVersion(1); ChoixMobiliteDto choixMob2 = factory.getChoixMobilite(); choixMob2.setNumeroVersion(choixMob.getNumeroVersion()); quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); choixMob.setMotifAnnulation(annulation); etudUcc.annulerChoixMobilite(choixMob); choixMob2.setMotifAnnulation(annulation2); etudUcc.annulerChoixMobilite(choixMob2); } @Test public void testAnnulerChoixMobiliterValide() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); choixMob.setMotifAnnulation(annulation); etudUcc.annulerChoixMobilite(choixMob); assertEquals("L'annulation de mobilité ne correspond pas.", annulation.getId(), etudUcc.recupererMobilitesPourDemande(demandeMob).get(0).getMotifAnnulation().getId()); } @Test(expected = BizzException.class) public void testConfirmerPartenaireParametres() { etudUcc.confirmerPartenaire(null); } @Test(expected = BizzException.class) public void testConfirmerPartenaireMobiliteExistant() { ChoixMobiliteDto choixMob2 = factory.getChoixMobilite(); quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob, choixMob2)); etudUcc.declarerChoix(demandeMob); etudUcc.confirmerPartenaire(choixMob); etudUcc.confirmerPartenaire(choixMob2); } @Test(expected = BizzException.class) public void testConfirmerPartenaireMobiliteEtaIncorrecte() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); choixMob.setEtat(Etat.A_PAYER_SOLDE); etudUcc.confirmerPartenaire(choixMob); } @Test public void testConfirmerPartenaireExistantValide() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); etudUcc.confirmerPartenaire(choixMob); assertEquals("L'état de la mobilité ne correspond pas.", choixMob.getEtat(), etudUcc.recupererMobilitesPourDemande(demandeMob).get(0).getEtat()); } @Test public void testConfirmerPartenaireNonExistantValide() { quidUcc.inscrire(user); partenaire.setId(2); choixMob.setPartenaire(partenaire); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); etudUcc.confirmerPartenaire(choixMob); assertEquals("L'état de la mobilité ne correspond pas.", choixMob.getEtat(), etudUcc.recupererMobilitesPourDemande(demandeMob).get(0).getEtat()); assertEquals("Le partenaire de la mobilité ne correspond pas.", partenaire.getId(), etudUcc.recupererPartenaireParId(partenaire).getId()); } @Test(expected = BizzException.class) public void testListerMobilitesPourEtudParametres() { etudUcc.listerMobilitesPourEtud(null); } @Test public void testListerMobilitesPourEtudValide() { quidUcc.inscrire(user); DemandeMobiliteDto demandeMob2 = factory.getDemandeMobilite(); ChoixMobiliteDto choixMob2 = factory.getChoixMobilite(); choixMob2.setId(2); demandeMob2.setId(2); demandeMob2.setAnneeAcademique(2016); demandeMob2.setChoixMobilites(Arrays.asList(choixMob2)); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); etudUcc.declarerChoix(demandeMob2); List<DemandeMobiliteDto> liste = etudUcc.listerMobilitesPourEtud(user); assertEquals("La demande de mobilité ne correspond pas.", demandeMob.getId(), liste.get(0).getId()); assertEquals("La demande de mobilité ne correspond pas.", demandeMob2.getId(), liste.get(1).getId()); assertEquals("Le nombre de demande de mobilité ne correspond pas.", 2, liste.size()); } @Test(expected = BizzException.class) public void testListerPartenairesPourEtudiant() { etudUcc.listerPartenairesPourEtudiant(null); } @Test public void testListerPartenairesPourEtudiantValide() { quidUcc.inscrire(user); etudUcc.ajouterPartenaire(user, partenaire); List<PartenaireDto> liste = etudUcc.listerPartenairesPourEtudiant(user); assertEquals("Le partenaire ne correspond pas.", 1, liste.get(0).getId()); assertEquals("Le nombre de partenaire est incorrecte.", 1, liste.size()); } @Test(expected = BizzException.class) public void testEncoderInformationsPersonnellesParametres() { etudUcc.encoderInformationsPersonnelles(null); } @Test(expected = BizzException.class) public void testEncoderInformationsPersonnellesMobiliteNonConfirme() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); etudUcc.encoderInformationsPersonnelles(userInfos); } @Test public void testEncoderInformationsPersonnellesChampInvalide() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); UserInfoDto userInfo2 = factory.getUserInfo(); try { userInfo2.setAdresse(null); etudUcc.encoderInformationsPersonnelles(userInfo2); fail("Il doit y avoir une adresse pour les informations personnelles de l'utilisateur."); } catch (Exception e) { assertTrue(true); } try { userInfo2 = factory.getUserInfo(); userInfo2.setBanque(null); etudUcc.encoderInformationsPersonnelles(userInfo2); fail("Il doit y avoir une banque pour les informations personnelles de l'utilisateur."); } catch (Exception e) { assertTrue(true); } try { userInfo2 = factory.getUserInfo(); userInfo2.setBic(null); etudUcc.encoderInformationsPersonnelles(userInfo2); fail("Il doit y avoir un bic pour les informations personnelles de l'utilisateur."); } catch (Exception e) { assertTrue(true); } try { userInfo2 = factory.getUserInfo(); userInfo2.setCompteBancaire(null); etudUcc.encoderInformationsPersonnelles(userInfo2); fail( "Il doit y avoir un compte bancaire pour les informations personnelles de l'utilisateur."); } catch (Exception e) { assertTrue(true); } try { userInfo2 = factory.getUserInfo(); userInfo2.setDateNais(null); etudUcc.encoderInformationsPersonnelles(userInfo2); fail( "Il doit y avoir une date de naissance pour les informations personnelles de l'utilisateur."); } catch (Exception e) { assertTrue(true); } try { userInfo2 = factory.getUserInfo(); userInfo2.setEmail(null); etudUcc.encoderInformationsPersonnelles(userInfo2); fail("Il doit y avoir un mail valide pour les informations personnelles de l'utilisateur."); } catch (Exception e) { assertTrue(true); } try { userInfo2 = factory.getUserInfo(); userInfo2.setNationalite(null); etudUcc.encoderInformationsPersonnelles(userInfo2); fail("Il doit y avoir une nationalité pour les informations personnelles de l'utilisateur."); } catch (Exception e) { assertTrue(true); } try { userInfo2 = factory.getUserInfo(); userInfo2.setTel(null); etudUcc.encoderInformationsPersonnelles(userInfo2); fail( "Il doit y avoir un numéro de téléphone pour les informations personnelles de l'utilisateur."); } catch (Exception e) { assertTrue(true); } try { userInfo2 = factory.getUserInfo(); userInfo2.setTitulaire(null); etudUcc.encoderInformationsPersonnelles(userInfo2); fail("Il doit y avoir un titulaire pour les informations personnelles de l'utilisateur."); } catch (Exception e) { assertTrue(true); } } @Test public void testEncoderInformationsPersonnellesValideInsert() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); etudUcc.confirmerPartenaire(choixMob); userInfos.setUtilisateur(user); etudUcc.encoderInformationsPersonnelles(userInfos); assertEquals("Infos utilisateurs ne correspondent pas.", userInfos.getId(), etudUcc.recupererUserInfoParUId(user).getId()); } @Test public void testEncoderInformationsPersonnellesValideUpdate() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); etudUcc.confirmerPartenaire(choixMob); userInfos.setNumeroVersion(1); userInfos.setUtilisateur(user); etudUcc.encoderInformationsPersonnelles(userInfos); UserInfoDto userInfos2 = factory.getUserInfo(); userInfos2.setNumeroVersion(userInfos.getNumeroVersion()); userInfos2.setUtilisateur(userInfos.getUtilisateur()); userInfos2.setAdresse("Nulle part"); etudUcc.encoderInformationsPersonnelles(userInfos2); assertEquals("Infos utilisateurs ne correspondent pas.", userInfos2.getId(), etudUcc.recupererUserInfoParUId(user).getId()); assertEquals("L'adresse de l'utilisateur ne correspond pas.", userInfos2.getAdresse(), etudUcc.recupererUserInfoParUId(user).getAdresse()); } @Test(expected = BizzException.class) public void testEncoderInformationsPersonnellesDonneesObsoletes() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); etudUcc.confirmerPartenaire(choixMob); userInfos.setNumeroVersion(1); etudUcc.encoderInformationsPersonnelles(userInfos); UserInfoDto userInfos2 = factory.getUserInfo(); userInfos2.setNumeroVersion(userInfos.getNumeroVersion()); userInfos2.setAdresse("Nulle part"); etudUcc.encoderInformationsPersonnelles(userInfos2); } @Test(expected = BizzException.class) public void testRechercherMobiliteParametres() { etudUcc.rechercherMobilite(null); } @Test public void testRechercherMobiliteResultat1() { quidUcc.inscrire(user); ChoixMobiliteDto choixMob2 = factory.getChoixMobilite(); choixMob2.setId(2); demandeMob.setChoixMobilites(Arrays.asList(choixMob, choixMob2)); etudUcc.declarerChoix(demandeMob); List<ChoixMobiliteDto> liste = etudUcc.rechercherMobilite(choixMob); assertEquals("Les choix de mobilités ne correspondent pas.", choixMob.getId(), liste.get(0).getId()); assertEquals("Les choix de mobilités ne correspondent pas.", choixMob2.getId(), liste.get(1).getId()); assertEquals("Nombre de choix de mobilités trouvés incorrectes", 2, liste.size()); } @Test public void testRechercherMobiliteResultat2() { quidUcc.inscrire(user); ChoixMobiliteDto choixMob2 = factory.getChoixMobilite(); choixMob2.setId(2); ChoixMobiliteDto choixMob3 = factory.getChoixMobilite(); choixMob3.setId(3); demandeMob.setChoixMobilites(Arrays.asList(choixMob, choixMob2, choixMob3)); etudUcc.declarerChoix(demandeMob); choixMob3.setEtat(Etat.A_PAYER); List<ChoixMobiliteDto> liste = etudUcc.rechercherMobilite(choixMob3); assertEquals("Les choix de mobilités ne correspondent pas.", choixMob3.getId(), liste.get(0).getId()); assertEquals("Nombre de choix de mobilités trouvés incorrectes", 1, liste.size()); } @Test public void testRechercherMobiliteResultat3() { quidUcc.inscrire(user); ChoixMobiliteDto choixMob2 = factory.getChoixMobilite(); choixMob2.setId(2); ChoixMobiliteDto choixMob3 = factory.getChoixMobilite(); choixMob3.setId(3); demandeMob.setChoixMobilites(Arrays.asList(choixMob, choixMob2)); etudUcc.declarerChoix(demandeMob); choixMob3.setEtat(Etat.A_PAYER); List<ChoixMobiliteDto> liste = etudUcc.rechercherMobilite(choixMob3); assertNull("Le nombre de mobilités trouvées doit être nulle.", liste); } @Test(expected = BizzException.class) public void testRecupererMobilitesPourDemandeParametres() { etudUcc.recupererMobilitesPourDemande(null); } @Test public void testRecupererMobilitesPourDemande() { quidUcc.inscrire(user); ChoixMobiliteDto choixMob2 = factory.getChoixMobilite(); choixMob2.setId(2); demandeMob.setChoixMobilites(Arrays.asList(choixMob, choixMob2)); etudUcc.declarerChoix(demandeMob); List<ChoixMobiliteDto> liste = etudUcc.recupererMobilitesPourDemande(demandeMob); assertEquals("Le choix de mobilité ne correspond pas.", choixMob.getId(), liste.get(0).getId()); assertEquals("Le choix de mobilité ne correspond pas.", choixMob2.getId(), liste.get(1).getId()); assertEquals("Le nombre de mobilités ne correspond pas.", 2, liste.size()); } @Test(expected = BizzException.class) public void testRechercherUserParametres() { etudUcc.rechercherUser(null); } @Test public void testRechercherUserCorrespondant1() { user.setNom("Connue"); user.setPrenom("Non connue"); UserDto user2 = factory.getUser(); user2.setId(2); user2.setNom("Connue"); user2.setPrenom("Non connue"); user2.setMail("<EMAIL>"); user2.setPseudo("test2"); UserDto user3 = factory.getUser(); user3.setId(3); user3.setNom("Inconnue"); user3.setMail("<EMAIL>"); user3.setPseudo("test3"); quidUcc.inscrire(user); quidUcc.inscrire(user2); quidUcc.inscrire(user3); List<UserDto> liste = etudUcc.rechercherUser(user); assertEquals("Le nom des utilisateurs ne correspondent pas.", user.getNom(), liste.get(0).getNom()); assertEquals("Le prenom des utilisateurs ne correspondent pas.", user.getPrenom(), liste.get(0).getPrenom()); assertEquals("Le nom des utilisateurs ne correspondent pas.", user.getNom(), liste.get(1).getNom()); assertEquals("Le prenom des utilisateurs ne correspondent pas.", user.getPrenom(), liste.get(1).getPrenom()); assertEquals("Nombre d'utilisateurs trouvés incorrectes", 2, liste.size()); } @Test public void testRechercherUserCorrespondant2() { user.setNom("Connue"); user.setPrenom("dqsdq"); UserDto user2 = factory.getUser(); user2.setId(2); user2.setNom("Inconnue"); user2.setPrenom("Non connue"); user2.setMail("<EMAIL>"); user2.setPseudo("test2"); UserDto user3 = factory.getUser(); user3.setId(3); user3.setNom("Connue"); user3.setPrenom("fgdfgd"); user3.setMail("<EMAIL>"); user3.setPseudo("test3"); quidUcc.inscrire(user); quidUcc.inscrire(user2); quidUcc.inscrire(user3); List<UserDto> liste = etudUcc.rechercherUser(user); assertEquals("Le nom des utilisateurs ne correspondent pas.", user.getNom(), liste.get(1).getNom()); assertEquals("Nombre d'utilisateurs trouvés incorrectes", 2, liste.size()); } @Test public void testRechercherUserCorrespondant3() { user.setNom("dqsdqs"); user.setPrenom("Connue"); UserDto user2 = factory.getUser(); user2.setId(2); user2.setNom("Connue"); user2.setPrenom("Non connue"); user2.setMail("<EMAIL>"); user2.setPseudo("test2"); UserDto user3 = factory.getUser(); user3.setId(3); user3.setNom("Connue"); user3.setPrenom("dsqdq"); user3.setMail("<EMAIL>"); user3.setPseudo("test3"); quidUcc.inscrire(user); quidUcc.inscrire(user2); quidUcc.inscrire(user3); List<UserDto> liste = etudUcc.rechercherUser(user); assertEquals("Le prenom des utilisateurs ne correspondent pas.", user.getPrenom(), liste.get(0).getPrenom()); assertEquals("Nombre d'utilisateurs trouvés incorrectes", 1, liste.size()); } @Test public void testRechercherUserResultatVide() { user.setNom("Connue"); user.setPrenom("dsqdqsd"); UserDto user2 = factory.getUser(); user2.setId(2); user2.setNom("dsqdza"); user2.setPrenom("Non connue"); user2.setMail("<EMAIL>"); user2.setPseudo("test2"); UserDto user3 = factory.getUser(); user3.setId(3); user3.setNom("dsqlkdzoa"); user3.setPrenom("dqsdqsd"); user3.setMail("<EMAIL>"); user3.setPseudo("test3"); quidUcc.inscrire(user2); quidUcc.inscrire(user3); List<UserDto> liste = etudUcc.rechercherUser(user); assertNull("Nombre d'utilisateurs trouvés doit être null", liste); } @Test(expected = BizzException.class) public void testRecupererUserParIdParametres() { etudUcc.recupererUserParId(null); } @Test public void testRecupererUserParIdCorrespondant() { UserDto user2 = factory.getUser(); user2.setId(2); user2.setPseudo("dsqdqs"); user2.setMail("<EMAIL>"); quidUcc.inscrire(user); quidUcc.inscrire(user2); assertEquals("Ces utilisateurs doivent correspondre.", user.getId(), etudUcc.recupererUserParId(user).getId()); assertEquals("Ces utilisateurs doivent correspondre.", user2.getId(), etudUcc.recupererUserParId(user2).getId()); assertNotEquals("Ces utilisateurs ne doivent pas corresponddre.", user.getId(), etudUcc.recupererUserParId(user2).getId()); } @Test(expected = BizzException.class) public void testRecupererUserParIdInvalide() { etudUcc.recupererUserParId(user).getId(); } @Test(expected = BizzException.class) public void testRecupererUserInfoParUIdParametres1() { etudUcc.recupererUserInfoParUId(null); } @Test public void testRecupererUserInfoParUIdInfosExiste() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); etudUcc.confirmerPartenaire(choixMob); userInfos.setUtilisateur(user); etudUcc.encoderInformationsPersonnelles(userInfos); assertEquals("Infos utilisateurs non correspondant.", userInfos.getId(), etudUcc.recupererUserInfoParUId(user).getId()); } @Test public void testRecupererUserInfoParUIdInfosExistePas() { assertNull("Infos utilisateurs non existant.", etudUcc.recupererUserInfoParUId(user)); } @Test public void testRecupererUserInfoParUId_ModifInfosCorrespondant() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); etudUcc.confirmerPartenaire(choixMob); userInfos.setUtilisateur(user); etudUcc.encoderInformationsPersonnelles(userInfos); userInfos.setAdresse("qsdqs dsqdq"); etudUcc.encoderInformationsPersonnelles(userInfos); assertEquals("Infos utilisateurs non correspondant.", userInfos.getAdresse(), etudUcc.recupererUserInfoParUId(user).getAdresse()); } @Test(expected = BizzException.class) public void testRecupererPartenaireParIdParametres() { etudUcc.recupererPartenaireParId(null); } @Test public void testRecupererPartenaireParIdCorrespondant() { partenaire.setIplDepartements(Arrays.asList(departement)); quidUcc.inscrire(user); etudUcc.ajouterPartenaire(user, partenaire); assertEquals("Les partenaires doivent correspondre.", partenaire.getId(), etudUcc.recupererPartenaireParId(partenaire).getId()); } @Test(expected = BizzException.class) public void testRechercherPartenaireParametres() { etudUcc.rechercherPartenaire(null); } @Test public void testRechercherPartenaireCorrespondant() { partenaire.setIplDepartements(new ArrayList<DepartementDto>(Arrays.asList(departement))); quidUcc.inscrire(user); etudUcc.ajouterPartenaire(user, partenaire); partenaire.setNomLegal("Entreprise"); PartenaireDto part1 = factory.getPartenaire(); part1.setIplDepartements(new ArrayList<DepartementDto>(Arrays.asList(departement))); UserDto user2 = factory.getUser(); user2.setId(2); user2.setMail("<EMAIL>"); user2.setPseudo("test2"); quidUcc.inscrire(user2); etudUcc.ajouterPartenaire(user2, part1); PartenaireDto part2 = factory.getPartenaire(); part2.setIplDepartements(new ArrayList<DepartementDto>(Arrays.asList(departement))); part2.setNomLegal("Entreprise"); UserDto user3 = factory.getUser(); user3.setId(3); user3.setMail("<EMAIL>"); user3.setPseudo("test3"); quidUcc.inscrire(user3); etudUcc.ajouterPartenaire(user3, part2); List<PartenaireDto> liste = etudUcc.rechercherPartenaire(partenaire); assertEquals("Les partenaires recherchés doivent correspondre.", partenaire.getNomLegal(), liste.get(2).getNomLegal()); } @Test public void testRechercherPartenaireResultatVide() { partenaire.setIplDepartements(new ArrayList<DepartementDto>(Arrays.asList(departement))); quidUcc.inscrire(user); partenaire.setNomLegal("Entreprise"); partenaire.setVille("Nulle part"); PaysDto pays = factory.getPays(); pays.setNom("Nulle part"); partenaire.setPays(pays); PartenaireDto part1 = factory.getPartenaire(); part1.setIplDepartements(new ArrayList<DepartementDto>(Arrays.asList(departement))); UserDto user2 = factory.getUser(); user2.setId(2); user2.setMail("<EMAIL>"); user2.setPseudo("test2"); quidUcc.inscrire(user2); etudUcc.ajouterPartenaire(user2, part1); List<PartenaireDto> liste = etudUcc.rechercherPartenaire(partenaire); assertNull("Il ne devrait y avoir aucun partenaire de trouvé.", liste); } @Test public void testListerDepartementsCorrespondant() { List<DepartementDto> liste = etudUcc.listerDepartements(); assertEquals("Les départements devraient être identique.", AppConfig.getValueOf("code_dep"), liste.get(0).getCode()); assertEquals("Les départements devraient être identique.", AppConfig.getValueOf("code2_dep"), liste.get(1).getCode()); assertEquals("Les départements devraient être identique.", AppConfig.getValueOf("code3_dep"), liste.get(2).getCode()); assertEquals("Les départements devraient être identique.", AppConfig.getValueOf("code4_dep"), liste.get(3).getCode()); assertEquals("Il devrait y avoir 4 departement enregistrés.", 4, liste.size()); } @Test public void testListerPays() { List<PaysDto> liste = etudUcc.listerPays(); assertEquals("Les pays devraient être identique.", AppConfig.getValueOf("code3_pays"), liste.get(0).getCode()); assertEquals("Les pays devraient être identique.", AppConfig.getValueOf("code_pays"), liste.get(1).getCode()); assertEquals("Les pays devraient être identique.", AppConfig.getValueOf("code2_pays"), liste.get(2).getCode()); assertEquals("Les pays devraient être identique.", AppConfig.getValueOf("code4_pays"), liste.get(3).getCode()); assertEquals("Il devrait y avoir 4 pays enregistrés.", 4, liste.size()); } @Test public void testListerProgrammes() { List<ProgrammeDto> liste = etudUcc.listerProgrammes(); assertEquals("Les programmes devraient être identique.", "HTTP", liste.get(0).getNom()); assertEquals("Les programmes devraient être identique.", "FTP", liste.get(1).getNom()); assertEquals("Les programmes devraient être identique.", "SMTP", liste.get(2).getNom()); assertEquals("Les programmes devraient être identique.", "TELENET", liste.get(3).getNom()); assertEquals("Il devrait y avoir 4 programmes enregistrés.", 4, liste.size()); } @Test public void testListerTypesProgramme() { List<TypeProgrammeDto> liste = etudUcc.listerTypesProgramme(); assertEquals("Les types de programme devraient être identique.", AppConfig.getValueOf("nom_type_prog"), liste.get(0).getNom()); assertEquals("Les types de programme devraient être identique.", AppConfig.getValueOf("nom2_type_prog"), liste.get(1).getNom()); assertEquals("Les types de programme devraient être identique.", AppConfig.getValueOf("nom3_type_prog"), liste.get(2).getNom()); assertEquals("Les types de programme devraient être identique.", AppConfig.getValueOf("nom4_type_prog"), liste.get(3).getNom()); assertEquals("Il devrait y avoir 4 type de programme enregistrés.", 4, liste.size()); } @Test public void testListerAnneesAcademiqueIntroduites() { quidUcc.inscrire(user); demandeMob.setChoixMobilites(Arrays.asList(choixMob)); etudUcc.declarerChoix(demandeMob); DemandeMobiliteDto dem = factory.getDemandeMobilite(); dem.setId(2); UserDto user2 = factory.getUser(); user2.setId(2); user2.setMail("<EMAIL>"); user2.setPseudo("test2"); quidUcc.inscrire(user2); dem.setEtudiant(user2); dem.setChoixMobilites(Arrays.asList(choixMob)); dem.setAnneeAcademique(2016); etudUcc.declarerChoix(dem); List<Integer> liste = etudUcc.listerAnneesAcademiqueDejaIntroduites(); assertEquals("L'année académique devrait être identique.", (Integer) 2015, liste.get(0)); assertEquals("L'année académique devrait être identique.", (Integer) 2016, liste.get(1)); assertEquals("Il devrait y avoir 2 demande de mobilité enregistré.", 2, liste.size()); } @Test public void testListerAnneesAcademiqueIntroduitesResultatVide() { List<Integer> liste = etudUcc.listerAnneesAcademiqueDejaIntroduites(); assertNull("Il ne devrait pas y avoir de demande de mobilité introduite.", liste); } @Test(expected = BizzException.class) public void testListerEtatDocumentsParametres() { etudUcc.listerEtatDocuments(null); } @Test public void testListerEtatDocuments() { DocumentDto document2 = factory.getDocument(); document2.setId(2); Map<DocumentDto, Boolean> liste = etudUcc.listerEtatDocuments(choixMob); assertTrue("Ce document devrait être rempli.", liste.get(document)); assertFalse("Ce document ne devrait pas être rempli.", liste.get(document2)); } @Test(expected = BizzException.class) public void testListerEtatLogicielsEncodesParametres() { etudUcc.listerEtatLogicielsEncodes(null); } @Test public void testListerEtatLogicielsEncodes() { LogicielDto logiciel1 = factory.getLogiciel(); LogicielDto logiciel2 = factory.getLogiciel(); logiciel2.setId(2); choixMob.setLogiciels(Arrays.asList(logiciel1)); profUcc.gererEncodageLogiciels(choixMob); Map<LogicielDto, Boolean> liste = etudUcc.listerEtatLogicielsEncodes(choixMob); assertTrue("Il devrait y avoir un logiciel encodé pour cette mobilité.", liste.get(logiciel1)); assertFalse("Il ne devrait pas y avoir de logiciel encodé pour cette mobilité.", liste.get(logiciel2)); } }
<gh_stars>1-10 function PencilBrush(ctx) { this.draw = function (event) { if (wacom.isLoaded) { // this value is arbitrary and has nothing to do with // the brush's radius. // if a user interface feature is ever implemented to // adapt brush radius, it won't work with wacom, only with mouse. ctx.lineWidth = wacom.getPressure() * 12; } ctx.beginPath(); ctx.moveTo(event.previousMousePosition.offsetX, event.previousMousePosition.offsetY); ctx.lineTo(event.offsetX, event.offsetY); ctx.stroke(); ctx.closePath(); }; this.name = "pencil"; } toolbox.addNewBrush(new PencilBrush(ctx));
/* * Copyright (c) 2018 https://www.reactivedesignpatterns.com/ * * Copyright (c) 2018 https://rdp.reactiveplatform.xyz/ * */ package chapter15; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketAddress; // 代码清单15-1 // Listing 15.1 Server responding to the address that originated the request // #snip public class Server { static final int SERVER_PORT = 8888; public static void main(String[] args) throws IOException { // bind a socket for receiving packets try (final DatagramSocket socket = new DatagramSocket(SERVER_PORT)) { // receive one packet final byte[] buffer = new byte[1500]; final DatagramPacket packet1 = new DatagramPacket(buffer, buffer.length); socket.receive(packet1); final SocketAddress sender = packet1.getSocketAddress(); System.out.println("server: received " + new String(packet1.getData())); System.out.println("server: sender was " + sender); // send response back final byte[] response = "got it!".getBytes(); final DatagramPacket packet2 = new DatagramPacket(response, response.length, sender); socket.send(packet2); } } } // #snip
'use strict'; module.exports = (_, model, state) => [ _.field({label: 'Disable media'}, _.checkbox({tooltip: 'Hides the media picker if enabled', name: 'isMediaDisabled', value: model.config.isMediaDisabled || false, onchange: _.onChangeConfig}) ), _.field({label: 'Disable markdown'}, _.checkbox({tooltip: 'Hides the markdown tab if enabled', name: 'isMarkdownDisabled', value: model.config.isMarkdownDisabled || false, onchange: _.onChangeConfig}) ), _.field({label: 'Disable HTML'}, _.checkbox({tooltip: 'Hides the HTML tab if enabled', name: 'isHtmlDisabled', value: model.config.isHtmlDisabled || false, onchange: _.onChangeConfig}) ), _.field({label: 'WYSIWYG'}, _.popup({multiple: true, options: state.wysiwygToolbarOptions, value: state.wysiwygToolbarValue, onchange: _.onChangeConfigWysiwyg}) ) ]
<reponame>KarolinDuerr/MA-CNA-ModelingSupport import { Endpoint, endpointTypes } from "./endpoint.js"; /** * The module for aspects related to a External Endpoint quality model Entity. * @module entities/externalEndpoint */ /** * Class representing an External Endpoint entity. * @class * @extends Endpoint An {@link Endpoint} entity */ class ExternalEndpoint extends Endpoint { // TODO ref Component here? /** * Create an External Endpoint entity. * @param {modelId} modelId The ID, the respective entity representation has in the joint.dia.Graph model. * @param {endpointType} endpointType The type of the endpoint entity, e.g. a GET or SEND_TO {@link endpointTypes}. * @param {string} endpointName The actual endpoint, e.g. /helloWorld. * @param {number} port The port at which the External Endpoint is available. * @param {string} parentName The name of the parent Entity. */ constructor(modelId, endpointType, endpointName, port, parentName) { super(modelId, endpointType, endpointName, port, parentName); } /** * Transforms the ExternalEndpoint object into a String. * @returns {string} */ toString() { return "ExternalEndpoint " + JSON.stringify(this); } } export { ExternalEndpoint };
from pypy.rpython.ootypesystem.ootype import * import py def test_simple(): assert typeOf(1) is Signed def test_class_hash(): M = Meth([Signed], Signed) def m_(self, b): return self.a + b m = meth(M, _name="m", _callable=m_) I = Instance("test", ROOT, {"a": Signed}, {"m": m}) assert type(hash(I)) == int def test_simple_class(): I = Instance("test", ROOT, {"a": Signed}) i = new(I) py.test.raises(TypeError, "i.z") py.test.raises(TypeError, "i.a = 3.0") i.a = 3 assert i.a == 3 def test_assign_super_attr(): C = Instance("test", ROOT, {"a": (Signed, 3)}) D = Instance("test2", C, {}) d = new(D) d.a = 1 assert d.a == 1 def test_runtime_instantiation(): I = Instance("test", ROOT, {"a": Signed}) c = runtimeClass(I) i = runtimenew(c) assert typeOf(i) == I assert typeOf(c) == Class def test_runtime_record_instantiation(): R = Record({"a": Signed}) c = runtimeClass(R) r = runtimenew(c) assert typeOf(r) == R assert typeOf(c) == Class def test_class_records(): R1 = Record({"a": Signed}) R2 = Record({"a": Signed}) assert R1 == R2 assert runtimeClass(R1) is runtimeClass(R2) def test_class_builtintype(): L1 = List(Signed) L2 = List(Signed) assert L1 == L2 assert runtimeClass(L1) is runtimeClass(L2) def test_class_class(): L = List(Signed) R = Record({"a": Signed}) c1 = runtimeClass(L) c2 = runtimeClass(R) C1 = typeOf(c1) C2 = typeOf(c2) assert runtimeClass(C1) is runtimeClass(C2) def test_classof(): I = Instance("test", ROOT, {"a": Signed}) c = runtimeClass(I) i = new(I) assert classof(i) == c j = new(I) assert classof(i) is classof(j) I2 = Instance("test2", I, {"b": Signed}) i2 = new(I2) assert classof(i2) is not classof(i) assert classof(i2) != classof(i) def test_dynamictype(): A = Instance("A", ROOT) B = Instance("B", A) a = new(A) b = new(B) assert dynamicType(a) is A assert dynamicType(b) is B b = ooupcast(A, b) assert dynamicType(b) is B def test_simple_default_class(): I = Instance("test", ROOT, {"a": (Signed, 3)}) i = new(I) assert i.a == 3 py.test.raises(TypeError, "Instance('test', ROOT, {'a': (Signed, 3.0)})") def test_overridden_default(): A = Instance("A", ROOT, {"a": (Signed, 3)}) B = Instance("B", A) overrideDefaultForFields(B, {"a": (Signed, 5)}) b = new(B) assert b.a == 5 def test_simple_null(): C = Instance("test", ROOT, {"a": Signed}) c = null(C) assert typeOf(c) == C py.test.raises(RuntimeError, "c.a") def test_simple_class_field(): C = Instance("test", ROOT, {}) D = Instance("test2", ROOT, {"a": C}) d = new(D) assert typeOf(d.a) == C assert d.a == null(C) def test_simple_recursive_class(): C = Instance("test", ROOT, {}) addFields(C, {"inst": C}) c = new(C) assert c.inst == null(C) def test_simple_super(): C = Instance("test", ROOT, {"a": (Signed, 3)}) D = Instance("test2", C, {}) d = new(D) assert d.a == 3 def test_simple_field_shadowing(): C = Instance("test", ROOT, {"a": (Signed, 3)}) py.test.raises(TypeError, """D = Instance("test2", C, {"a": (Signed, 3)})""") def test_simple_static_method(): F = StaticMethod([Signed, Signed], Signed) def f_(a, b): return a+b f = static_meth(F, "f", _callable=f_) assert typeOf(f) == F result = f(2, 3) assert typeOf(result) == Signed assert result == 5 def test_static_method_args(): F = StaticMethod([Signed, Signed], Signed) def f_(a, b): return a+b f = static_meth(F, "f", _callable=f_) py.test.raises(TypeError, "f(2.0, 3.0)") py.test.raises(TypeError, "f()") py.test.raises(TypeError, "f(1, 2, 3)") null_F = null(F) py.test.raises(RuntimeError, "null_F(1,2)") def test_class_method(): M = Meth([Signed], Signed) def m_(self, b): return self.a + b m = meth(M, _name="m", _callable=m_) C = Instance("test", ROOT, {"a": (Signed, 2)}, {"m": m}) c = new(C) assert c.m(3) == 5 py.test.raises(TypeError, "c.m(3.0)") py.test.raises(TypeError, "c.m()") py.test.raises(TypeError, "c.m(1, 2, 3)") def test_class_method_field_clash(): M = Meth([Signed], Signed) def m_(self, b): return self.a + b m = meth(M, _name="m", _callable=m_) py.test.raises(TypeError, """Instance("test", ROOT, {"a": M})""") py.test.raises(TypeError, """Instance("test", ROOT, {"m": Signed}, {"m":m})""") def test_simple_recursive_meth(): C = Instance("test", ROOT, {"a": (Signed, 3)}) M = Meth([C], Signed) def m_(self, other): return self.a + other.a m = meth(M, _name="m", _callable=m_) addMethods(C, {"m": m}) c = new(C) assert c.m(c) == 6 def test_overloaded_method(): C = Instance("test", ROOT, {'a': (Signed, 3)}) def m1(self, x): return self.a+x def m2(self, x, y): return self.a+x+y def m3(self, x): return self.a*x m = overload(meth(Meth([Signed], Signed), _callable=m1, _name='m'), meth(Meth([Signed, Signed], Signed), _callable=m2, _name='m'), meth(Meth([Float], Float), _callable=m3, _name='m')) addMethods(C, {"m": m}) c = new(C) assert c.m(1) == 4 assert c.m(2, 3) == 8 assert c.m(2.0) == 6 def test_overloaded_method_upcast(): def m(self, dummy): return 42 C = Instance("base", ROOT, {}, { 'foo': overload(meth(Meth([ROOT], String), _callable=m))}) c = new(C) assert c.foo(c) == 42 def test_method_selftype(): LIST = List(Signed) _, meth = LIST._lookup('ll_setitem_fast') METH = typeOf(meth) assert METH.SELFTYPE is LIST def test_bound_method_name(): LIST = List(Signed) lst = new(LIST) meth = lst.ll_getitem_fast assert meth._name == 'll_getitem_fast' def test_explicit_name_clash(): C = Instance("test", ROOT, {}) addFields(C, {"a": (Signed, 3)}) M = Meth([Signed], Signed) m = meth(M, _name="m") py.test.raises(TypeError, """addMethods(C, {"a": m})""") addMethods(C, {"b": m}) py.test.raises(TypeError, """addFields(C, {"b": Signed})""") def test_instanceof(): C = Instance("test", ROOT, {}) D = Instance("test2", C, {}) c = new(C) d = new(D) assert instanceof(c, C) assert instanceof(d, D) assert not instanceof(c, D) assert instanceof(d, C) def test_superclass_meth_lookup(): C = Instance("test", ROOT, {"a": (Signed, 3)}) M = Meth([C], Signed) def m_(self, other): return self.a + other.a m = meth(M, _name="m", _callable=m_) addMethods(C, {"m": m}) D = Instance("test2", C, {}) d = new(D) assert d.m(d) == 6 def m_(self, other): return self.a * other.a m = meth(M, _name="m", _callable=m_) addMethods(D, {"m": m}) d = new(D) assert d.m(d) == 9 def test_isSubclass(): A = Instance("A", ROOT) B = Instance("B", A) C = Instance("C", A) D = Instance("D", C) assert isSubclass(A, A) assert isSubclass(B, A) assert isSubclass(C, A) assert not isSubclass(A, B) assert not isSubclass(B, C) assert isSubclass(D, C) assert isSubclass(D, A) assert not isSubclass(D, B) def test_commonBaseclass(): A = Instance("A", ROOT) B = Instance("B", A) C = Instance("C", A) D = Instance("D", C) E = Instance("E", ROOT) F = Instance("F", E) assert commonBaseclass(A, A) == A assert commonBaseclass(A, B) == A assert commonBaseclass(B, A) == A assert commonBaseclass(B, B) == B assert commonBaseclass(B, C) == A assert commonBaseclass(C, B) == A assert commonBaseclass(C, A) == A assert commonBaseclass(D, A) == A assert commonBaseclass(D, B) == A assert commonBaseclass(D, C) == C assert commonBaseclass(A, D) == A assert commonBaseclass(B, D) == A assert commonBaseclass(C, D) == C assert commonBaseclass(E, A) is ROOT assert commonBaseclass(E, B) is ROOT assert commonBaseclass(F, A) is ROOT def test_equality(): A = Instance("A", ROOT) B = Instance("B", A) a1 = new(A) a2 = new(A) b1 = new(B) az = null(A) bz = null(B) assert a1 assert a2 assert not az assert not bz result = [] for first in [a1, a2, b1, az, bz]: for second in [a1, a2, b1, az, bz]: eq = first == second assert (first != second) == (not eq) result.append(eq) assert result == [ 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, ] def test_subclassof(): A = Instance("A", ROOT) B = Instance("B", A) C = Instance("C", B) result = [] for first in [A, B, C]: for second in [A, B, C]: result.append(subclassof(runtimeClass(first), runtimeClass(second))) assert result == [ 1, 0, 0, 1, 1, 0, 1, 1, 1, ] def test_static_method_equality(): SM = StaticMethod([], Signed) SM1 = StaticMethod([], Signed) assert SM == SM1 sm = static_meth(SM, 'f', graph='graph') sm1 = static_meth(SM1, 'f', graph='graph') assert sm == sm1 def test_casts(): A = Instance('A', ROOT) B = Instance('B', A) b = new(B) assert instanceof(b, B) assert instanceof(b, A) assert typeOf(b) == B bA = ooupcast(A, b) assert instanceof(bA, B) if STATICNESS: assert typeOf(bA) == A bB = oodowncast(B, bA) assert instanceof(bB, A) assert instanceof(bB, B) assert typeOf(bB) == B def test_visibility(): if not STATICNESS: py.test.skip("static types not enforced in ootype") M = Meth([], Signed) def mA_(a): return 1 def mB_(b): return 2 def nB_(b): return 3 mA = meth(M, name="m", _callable=mA_) mB = meth(M, name="m", _callable=mB_) nB = meth(M, name="n", _callable=nB_) A = Instance('A', ROOT, {}, {'m': mA}) B = Instance('B', A, {}, {'m': mB, 'n': nB}) b = new(B) assert b.m() == 2 assert b.n() == 3 bA = ooupcast(A, b) assert bA.m() == 2 py.test.raises(TypeError, "bA.n()") assert oodowncast(B, bA).n() == 3 M = Meth([A], Signed) def xA_(slf, a): return a.n() xA = meth(M, name="x", _callable=xA_) addMethods(A, {'x': xA}) a = new(A) py.test.raises(TypeError, "a.x(b)") def yA_(slf, a): if instanceof(a, B): return oodowncast(B, a).n() return a.m() yA = meth(M, name="y", _callable=yA_) addMethods(A, {'y': yA}) assert a.y(a) == 1 assert a.y(b) == 3 # M = Meth([], Signed) def zA_(slf): return slf.n() zA = meth(M, name="z", _callable=zA_) addMethods(A, {'z': zA}) py.test.raises(TypeError, "b.z()") def zzA_(slf): if instanceof(slf, B): return oodowncast(B, slf).n() return slf.m() zzA = meth(M, name="zz", _callable=zzA_) addMethods(A, {'zz': zzA}) assert a.zz() == 1 assert b.zz() == 3 def test_view_instance_hash(): I = Instance("Foo", ROOT) inst = new(I) inst_up = ooupcast(ROOT, inst) inst_up2 = ooupcast(ROOT, inst) assert inst_up == inst_up2 assert hash(inst_up) == hash(inst_up2) def test_instance_equality(): A = Instance("Foo", ROOT) B = Instance("Foo", ROOT) # Instance compares by reference assert not A == B assert A != B def test_subclasses(): A = Instance("A", ROOT) B = Instance("B", A) C = Instance("C", A) D = Instance("D", C) assert A in ROOT._subclasses assert B in A._subclasses assert not B._subclasses assert C in A._subclasses assert D in C._subclasses def test_canraise(): LT = List(Signed) _, meth = LT._lookup('ll_length') assert meth._can_raise == False DT = DictItemsIterator(String, Signed) _, meth = DT._lookup('ll_go_next') assert meth._can_raise == True def test_cast_null(): A = Instance("A", ROOT) B = Instance("B", ROOT) rootnull = null(ROOT) anull = oodowncast(A, rootnull) assert typeOf(anull) is A assert ooupcast(ROOT, anull) == rootnull py.test.raises(AssertionError, oodowncast, B, anull) def test_weak_reference(): import gc A = Instance("A", ROOT) obj = new(A) ref = new(WeakReference) ref.ll_set(obj) assert oodowncast(A, ref.ll_deref()) == obj del obj gc.collect() assert ref.ll_deref() is null(ROOT) def test_dead_wref(): ref = new(WeakReference) assert ref.ll_deref() is null(ROOT) # we use the translator for this test because it's much easier to get # a class hierarchy with methods and graphs by using it than # constructing it by hand def test_lookup_graphs(): from pypy.translator.translator import TranslationContext, graphof class A: def foo(self): pass def bar(self): pass class B(A): def foo(self): pass def fn(flag): obj = flag and A() or B() obj.foo() obj.bar() return obj t = TranslationContext() t.buildannotator().build_types(fn, [int]) t.buildrtyper(type_system='ootype').specialize() graph = graphof(t, fn) TYPE_A = graph.getreturnvar().concretetype TYPE_B = TYPE_A._subclasses[0] assert len(TYPE_A._lookup_graphs('ofoo')) == 2 assert len(TYPE_B._lookup_graphs('ofoo')) == 1 assert len(TYPE_A._lookup_graphs('obar')) == 1 assert len(TYPE_B._lookup_graphs('obar')) == 1 def test_lookup_graphs_abstract(): from pypy.translator.translator import TranslationContext, graphof class A: pass class B(A): def foo(self): pass class C(A): def foo(self): pass def fn(flag): obj = flag and B() or C() obj.foo() return obj t = TranslationContext() t.buildannotator().build_types(fn, [int]) t.buildrtyper(type_system='ootype').specialize() graph = graphof(t, fn) TYPE_A = graph.getreturnvar().concretetype TYPE_B = TYPE_A._subclasses[0] TYPE_C = TYPE_A._subclasses[1] assert len(TYPE_A._lookup_graphs('ofoo')) == 2 assert len(TYPE_B._lookup_graphs('ofoo')) == 1 assert len(TYPE_C._lookup_graphs('ofoo')) == 1 def test_cast_object_instance(): A = Instance("Foo", ROOT) a = new(A) obj = cast_to_object(a) assert typeOf(obj) is Object assert cast_from_object(A, obj) == a a2 = cast_from_object(ROOT, obj) assert typeOf(a2) is ROOT assert a2 == ooupcast(ROOT, a) def test_cast_object_record(): R = Record({'x': Signed}) r = new(R) r.x = 42 obj = cast_to_object(r) assert typeOf(obj) is Object r2 = cast_from_object(R, obj) assert typeOf(r2) is R assert r == r2 def test_cast_object_null(): A = Instance("Foo", ROOT) B = Record({'x': Signed}) a = null(A) b = null(B) obj1 = cast_to_object(a) obj2 = cast_to_object(b) assert obj1 is obj2 assert obj1 is NULL assert cast_from_object(A, obj1) == a assert cast_from_object(B, obj2) == b def test_cast_object_compare_null(): A = Instance("Foo", ROOT) a = new(A) obj1 = cast_to_object(a) assert NULL != obj1 assert obj1 != NULL def test_cast_object_class(): A = Instance("Foo", ROOT) cls = runtimeClass(A) obj = cast_to_object(cls) cls2 = cast_from_object(Class, obj) assert cls is cls2 def test_object_identityhash(): A = Instance("Foo", ROOT) a = new(A) obj1 = cast_to_object(a) obj2 = cast_to_object(a) assert identityhash(obj1) == identityhash(obj2) def test_object_identityhash_sm(): M = StaticMethod([Signed], Signed) def m_(x): return x m = static_meth(M, "m", _callable=m_) obj1 = cast_to_object(m) obj2 = cast_to_object(m) assert identityhash(obj1) == identityhash(obj2) def test_identityhash_array(): A = Array(Signed) a = oonewarray(A, 10) b = oonewarray(A, 10) assert identityhash(a) != identityhash(b) # likely def test_bool_class(): A = Instance("Foo", ROOT) cls = runtimeClass(A) assert bool(cls) assert not bool(nullruntimeclass) def test_bool_default_sm(): SM = StaticMethod([], Void) sm = SM._defl() assert not bool(sm) def test_get_fields_with_default(): A = Instance("A", ROOT) addFields(A, {"a": (Signed, 3)}, with_default=True) addFields(A, {"b": (Signed, 0)}, with_default=True) addFields(A, {"c": (Signed, 0)}, with_default=False) fields = A._get_fields_with_default() assert fields == [("a", (Signed, 3)), ("b", (Signed, 0)) ] B = Instance("B", A) addFields(B, {"d": (Signed, 4)}, with_default=True) fields = B._get_fields_with_default() assert fields == [("a", (Signed, 3)), ("b", (Signed, 0)), ("d", (Signed, 4)), ]
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Boj14504 { private static int[] tree; private static int[] lazy; private static int N, K, S = 1; private static final String NEW_LINE = "\n"; public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); K = Integer.parseInt(st.nextToken()); init(); st = new StringTokenizer(br.readLine()); for(int i = S; i < S + N; i++){ tree[i] = Integer.parseInt(st.nextToken()); } for(int i = S - 1; i > 0; i--){ int[] son = makeSon(i); tree[i] = tree[son[0]] | tree[son[1]]; } StringBuilder sb = new StringBuilder(); int M = Integer.parseInt(br.readLine()); while(M-- > 0){ st = new StringTokenizer(br.readLine()); int cmd = Integer.parseInt(st.nextToken()); int i = Integer.parseInt(st.nextToken()) - 1; int j = Integer.parseInt(st.nextToken()) - 1; int k = Integer.parseInt(st.nextToken()); if(cmd == 2){ update(i, i, k, 1, 0, N - 1); } else{ sb.append(compare(i, j, 1, 0, N - 1)).append(NEW_LINE); } } System.out.println(sb.toString()); } private static void init(){ while(S <= N) S <<= 1; tree = new int[S * 2]; lazy = new int[S * 2]; } private static int[] makeSon(int node){ int son = node * 2; return new int[]{son, ++son}; } private static void propagation(int node, int start, int end, boolean flag){ if(lazy[node] == 0) return; if(start != end){ int[] son = makeSon(node); lazy[son[0]] = Math.max(lazy[node], lazy[son[0]]); lazy[son[1]] = Math.max(lazy[node], lazy[son[1]]); } if(flag) { tree[node] = lazy[node]; lazy[node] = 0; } } private static void update(int left, int right, int val, int node, int start, int end){ propagation(node, start ,end, false); if(right < start || end < left) return; if(left <= start && end < right){ lazy[node] = val; propagation(node, start, end, false); return; } int[] son = makeSon(node); int mid = (start + end) / 2; update(left, right, val, son[0], start, mid); update(left, right, val, son[1], mid + 1, end); tree[node] = val; } private static int compare(int left, int right, int node, int start, int end){ propagation(node, start, end, true); if(right < start || end < left) return 0; if(left <= start && end < right) return tree[node]; int[] son = makeSon(node); int mid = (start + end) / 2; return compare(left, right, son[0], start, mid) | compare(left, right, son[1], mid + 1, end); } }
<reponame>cemayan/earthquake_collector<gh_stars>1-10 package com.cayan.pushservice.service; import com.cayan.pushservice.interfaces.IKafkaService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.support.SendResult; import org.springframework.stereotype.Service; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; @Service public class KafkaService implements IKafkaService { @Autowired private KafkaTemplate<String, String> kafkaTemplate; @Value("${kafka.topic}") private String topic; @Override public void sendMessage(String msg) { ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(topic, msg); future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() { @Override public void onSuccess(SendResult<String, String> result) { System.out.println("Sent message=[" + msg + "] with offset=[" + result.getRecordMetadata().offset() + "]"); } @Override public void onFailure(Throwable ex) { System.out.println("Unable to send message=[" + msg + "] due to : " + ex.getMessage()); } }); } }
package com.bv.eidss.barcode; import android.content.Context; import android.content.Intent; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.util.AttributeSet; import android.util.TypedValue; import android.view.MenuItem; import android.view.ViewGroup; import android.support.v7.app.AppCompatActivity; import com.bv.eidss.R; import com.bv.eidss.barcode.core.IViewFinder; import com.bv.eidss.barcode.core.ZXingScannerView; import com.google.zxing.Result; public class BarcodeScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler { private ZXingScannerView mScannerView; @Override public void onCreate(Bundle state) { super.onCreate(state); setContentView(R.layout.activity_barcode_scanner); setupToolbar(); ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame); mScannerView = new ZXingScannerView(this) { @Override protected IViewFinder createViewFinderView(Context context) { return new CustomViewFinderView(context); } }; contentFrame.addView(mScannerView); } @Override public void onResume() { super.onResume(); mScannerView.setResultHandler(this); mScannerView.startCamera(); } @Override public void onPause() { super.onPause(); mScannerView.stopCamera(); } @Override public void handleResult(Result rawResult) { Intent intent = getIntent(); intent.putExtra("barcode", rawResult.getText()); setResult(RESULT_OK, intent); finish(); } public void setupToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); final ActionBar ab = getSupportActionBar(); if(ab != null) { ab.setDisplayHomeAsUpEnabled(true); ab.setTitle(R.string.ApplicationName); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } }
<reponame>minuk8932/Algorithm_BaekJoon package segment_tree; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; /** * * @author exponential-e * 백준 14288번: 내리 갈굼 4 * * @see https://www.acmicpc.net/problem/14288/ * */ public class Boj14288 { private static ArrayList<Integer>[] link; private static int[][] tree; private static int[][] lazy; private static int[] start, end; private static int N, S = 1; private static int count = -1; private static final String NEW_LINE = "\n"; public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); init(); st = new StringTokenizer(br.readLine()); for(int i = 0; i < N; i++){ int val = Integer.parseInt(st.nextToken()); if(val == -1) continue; link[--val].add(i); } dfs(0); StringBuilder sb = new StringBuilder(); boolean flag = false; while(M-- > 0){ st = new StringTokenizer(br.readLine()); int cmd = Integer.parseInt(st.nextToken()); if(cmd == 3){ flag = !flag; continue; } int i = Integer.parseInt(st.nextToken()) - 1; if(cmd == 1){ int w = Integer.parseInt(st.nextToken()); if(flag) add(start[i], start[i], w, 1, 0, N - 1, 0); // back else add(start[i], end[i], w, 1, 0, N - 1, 1); // for } else { sb.append(sum(start[i], end[i], 1, 0, N - 1, 0) // for + back cases + sum(start[i], start[i], 1, 0, N - 1, 1)).append(NEW_LINE); } } System.out.println(sb.toString()); } private static void init(){ while(S <= N) S <<= 1; tree = new int[S * 2][2]; // divide to For, Back lazy = new int[S * 2][2]; start = new int[N]; end = new int[N]; link = new ArrayList[N]; for(int i = 0; i < N; i++){ link[i] = new ArrayList<>(); } } private static void dfs(int current){ start[current] = ++count; for(int next: link[current]){ dfs(next); } end[current] = count; } private static int[] makeSon(int node){ int son = node * 2; return new int[]{son, ++son}; } private static void propagation(int node, int start, int end, int idx){ if(lazy[node][idx] == 0) return; if(start != end){ int[] son = makeSon(node); lazy[son[0]][idx] += lazy[node][idx]; lazy[son[1]][idx] += lazy[node][idx]; } tree[node][idx] += lazy[node][idx] * (end - start + 1); lazy[node][idx] = 0; } private static void add(int left, int right, int val, int node, int start, int end, int idx){ propagation(node, start, end, idx); if(right < start || end < left) return; if(left <= start && end <= right) { lazy[node][idx] += val; propagation(node, start, end, idx); return; } int[] son = makeSon(node); int mid = (start + end) / 2; add(left, right, val, son[0], start, mid, idx); add(left, right, val, son[1], mid + 1, end, idx); tree[node][idx] = tree[son[0]][idx] + tree[son[1]][idx]; } private static int sum(int left, int right, int node, int start, int end, int idx){ propagation(node, start, end, idx); if(right < start || end < left) return 0; if(left <= start && end <= right) return tree[node][idx]; int[] son = makeSon(node); int mid = (start + end) / 2; return sum(left, right, son[0], start, mid, idx) + sum(left, right, son[1], mid + 1, end, idx); } }
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { private static Scanner scan = new Scanner(System.in); public static void main(String[] args) { int size = scan.nextInt(); int resp = 0, sum = 0; int[] vec = new int[size]; for(int i = 0; i < size; ++i){ vec[i] = scan.nextInt(); if(vec[i] < 0) resp++; } for(int i = 2; i <= size; ++i){ for(int j = 0; j < size - i + 1; ++j){ sum = 0; for(int k = 0; k < i; ++k){ sum += vec[j + k]; } // System.out.println(sum); if(sum < 0) resp++; } } System.out.println(resp); } }
#!/bin/bash # echo "The following are the regions available for deleting stacks : " # REGIONS=$(aws ec2 describe-regions | jq '.Regions') # echo $REGIONS | jq -c '.[]' | while read i; do # REGION=$(echo $i | jq -r '.RegionName') # echo "$REGION" # done # echo "Lets first configure your AWS account" # aws configure StackList=$(aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE UPDATE_IN_PROGRESS CREATE_IN_PROGRESS --query 'StackSummaries[].StackName' --output text ) if [[ -z "$StackList" ]] then echo " Empty Stack List!" exit 1 else echo "Available stacks :" echo $StackList echo "Enter Stack name to be deleted" read StackName fi #Check if user has entered correct Stack Name flag=0 # if [[ stacknameLen -eq stacklistlen ]] # then if [[ " ${StackList[*]} " = *$StackName* ]]; then flag=1 else echo "Invalid parameter provided, please input again" fi #fi if [ $flag == 0 ] then echo "Error: Invalid StackName - $StackName" exit fi echo "Deleting Stack $StackName" ResponseDelete=$(aws cloudformation delete-stack --stack-name $StackName) if [ $? -ne "0" ] then echo "$StackName stack is not deleted....." echo "$ResponseDelete" exit 1 else echo "Stack deletion is in process! Please wait!" fi ResponseSuccess=$(aws cloudformation wait stack-delete-complete --stack-name $StackName) if [[ -z "$Success" ]] then echo "Stack $StackName is deleted successfully" else echo "Failed to delete stack $StackName ! Please try again!" echo "$ResponseSuccess" exit 1 fi
// This file is part of the Orbbec Astra SDK [https://orbbec3d.com] // Copyright (c) 2015 Or<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. // // Be excellent to each other. #ifndef ASTRA_STREAM_READER_H #define ASTRA_STREAM_READER_H #include <astra_core/capi/astra_types.h> #include "astra_registry.hpp" #include <unordered_map> #include <vector> #include <cassert> #include "astra_signal.hpp" #include "astra_private.h" #include "astra_stream_connection.hpp" namespace astra { class streamset_connection; //class stream_connection; class stream_desc_hash { public: std::size_t operator()(const astra_stream_desc_t desc) const { std::size_t h1 = std::hash<astra_stream_type_t>()(desc.type); std::size_t h2 = std::hash<astra_stream_subtype_t>()(desc.subtype); return h1 ^ (h2 << 1); } }; class stream_desc_equal_to { public: std::size_t operator()(const astra_stream_desc_t& lhs, const astra_stream_desc_t& rhs) const { return lhs.type == rhs.type && lhs.subtype == rhs.subtype; } }; struct reader_connection_data { stream_connection* connection; astra_callback_id_t scFrameReadyCallbackId; bool isNewFrameReady; astra_frame_index_t currentFrameIndex; }; class stream_reader : public tracked_instance<stream_reader> { public: stream_reader(streamset_connection& connection); ~stream_reader(); stream_reader& operator=(const stream_reader& rhs) = delete; stream_reader(const stream_reader& reader) = delete; inline streamset_connection& get_connection() const { return connection_; } inline astra_reader_t get_handle() { return reinterpret_cast<astra_reader_t>(this); } stream_connection* get_stream(astra_stream_desc_t& desc); astra_frame_t* get_subframe(astra_stream_desc_t& desc); astra_callback_id_t register_frame_ready_callback(astra_frame_ready_callback_t callback, void* clientTag); void unregister_frame_ready_callback(astra_callback_id_t& callbackId); //TODO: locking currently not threadsafe astra_status_t lock(int timeoutMillis, astra_reader_frame_t& readerFrame); astra_status_t unlock(astra_reader_frame_t& readerFrame); static inline stream_reader* get_ptr(astra_reader_t reader) { return registry::get<stream_reader>(reader); } static inline stream_reader* from_frame(astra_reader_frame_t& frame) { if (frame == nullptr) { return nullptr; } return get_ptr(frame->reader); } private: enum class block_result { TIMEOUT, FRAMEREADY }; block_result block_until_frame_ready_or_timeout(int timeoutMillis); astra_reader_frame_t lock_frame_for_event_callback(); astra_reader_frame_t lock_frame_for_poll(); astra_reader_frame_t acquire_available_reader_frame(); astra_status_t unlock_frame_and_check_connections(astra_reader_frame_t& readerFrame); astra_status_t return_locked_frame(astra_reader_frame_t& readerFrame); void ensure_connections_locked(); astra_status_t unlock_connections_if_able(); stream_connection* find_stream_of_type(astra_stream_desc_t& desc); stream_connection::FrameReadyCallback get_sc_frame_ready_callback(); void on_connection_frame_ready(stream_connection* connection, astra_frame_index_t frameIndex); void check_for_all_frames_ready(); void raise_frame_ready(); bool locked_{false}; bool isFrameReadyForLock_{false}; astra_frame_index_t lastFrameIndex_{-1}; streamset_connection& connection_; using ConnectionMap = std::unordered_map<astra_stream_desc_t, reader_connection_data*, stream_desc_hash, stream_desc_equal_to>; ConnectionMap streamMap_; using FramePtr = std::unique_ptr<_astra_reader_frame>; using FrameList = std::vector<FramePtr>; FrameList frameList_; int32_t lockedFrameCount_{0}; signal<astra_reader_t, astra_reader_frame_t> frameReadySignal_; stream_connection::FrameReadyCallback scFrameReadyCallback_; }; } #endif /* ASTRA_STREAM_READER_H */
#!/bin/bash # builds the project and deploys it echo "compile" GOARCH=amd64 GOOS=linux go build -o api ./service/api echo "package" sam package --template-file template.yaml --s3-bucket $S3_BUCKET --output-template-file packaged.yaml echo "deploy" sam deploy --stack-name $STACK_NAME --template-file packaged.yaml --capabilities CAPABILITY_IAM echo "done"
package io.swagger.model.geno; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; /** * VendorOrderSubmissionRequest */ @Validated @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2020-03-20T16:32:53.794Z[GMT]") public class VendorOrderSubmissionRequest extends VendorPlateSubmissionRequest { @JsonProperty("requiredServiceInfo") @Valid private Map<String, String> requiredServiceInfo = null; @JsonProperty("serviceIds") @Valid private List<String> serviceIds = new ArrayList<String>(); public VendorOrderSubmissionRequest requiredServiceInfo(Map<String, String> requiredServiceInfo) { this.requiredServiceInfo = requiredServiceInfo; return this; } public VendorOrderSubmissionRequest putRequiredServiceInfoItem(String key, String requiredServiceInfoItem) { if (this.requiredServiceInfo == null) { this.requiredServiceInfo = new HashMap<String, String>(); } this.requiredServiceInfo.put(key, requiredServiceInfoItem); return this; } /** * A map of additional data required by the requested service. This includes things like Volume and Concentration. * @return requiredServiceInfo **/ @ApiModelProperty(example = "{\"extractDNA\":true,\"genus\":\"Zea\",\"species\":\"mays\",\"volumePerWell\":\"2.3 ml\"}", value = "A map of additional data required by the requested service. This includes things like Volume and Concentration.") public Map<String, String> getRequiredServiceInfo() { return requiredServiceInfo; } public void setRequiredServiceInfo(Map<String, String> requiredServiceInfo) { this.requiredServiceInfo = requiredServiceInfo; } public VendorOrderSubmissionRequest serviceIds(List<String> serviceIds) { this.serviceIds = serviceIds; return this; } public VendorOrderSubmissionRequest addServiceIdsItem(String serviceIdsItem) { this.serviceIds.add(serviceIdsItem); return this; } /** * A list of unique, alpha-numeric ID which identify the requested services to be applied to this order. A Vendor Service defines what platform, technology, and markers will be used. A list of available service IDs can be retrieved from the Vendor Specs. * @return serviceIds **/ @ApiModelProperty(example = "[\"e8f60f64\",\"05bd925a\",\"b698fb5e\"]", required = true, value = "A list of unique, alpha-numeric ID which identify the requested services to be applied to this order. A Vendor Service defines what platform, technology, and markers will be used. A list of available service IDs can be retrieved from the Vendor Specs.") public List<String> getServiceIds() { return serviceIds; } public void setServiceIds(List<String> serviceIds) { this.serviceIds = serviceIds; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } VendorOrderSubmissionRequest vendorOrderSubmissionRequest = (VendorOrderSubmissionRequest) o; return Objects.equals(this.requiredServiceInfo, vendorOrderSubmissionRequest.requiredServiceInfo) && Objects.equals(this.serviceIds, vendorOrderSubmissionRequest.serviceIds) && super.equals(o); } @Override public int hashCode() { return Objects.hash(requiredServiceInfo, serviceIds, super.hashCode()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class VendorOrderSubmissionRequest {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" requiredServiceInfo: ").append(toIndentedString(requiredServiceInfo)).append("\n"); sb.append(" serviceIds: ").append(toIndentedString(serviceIds)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
function isIP(str) { const ip = str.split('.'); if(ip.length === 4 && ip.every(v => !isNaN(v) && v >= 0 && v < 256)) { return true } return false; }
import '../modules/metrics-analysis-sk'; import '../modules/ct-scaffold-sk';
<gh_stars>1-10 from tortoise import fields from tortoise.models import Model __all__ = ['Link'] class Link(Model): id = fields.IntField(pk=True) url = fields.CharField(128) description = fields.TextField(null=True)
import { Injectable } from '@angular/core'; import Task from '../dto/Task'; import { BehaviorSubject } from 'rxjs'; import { DexieService } from '../db/dexie.service'; import { PersistedFileService } from '../db/persisted-file.service'; import { FileType } from '../dto/FileType'; import { FileId } from '../dto/FileId'; import { RepositoryService } from './repository.service'; import TaskList from '../dto/TaskList'; import { filterTasks } from '../task-filter/task-filter/TaskFilter'; import * as moment from 'moment'; @Injectable({ providedIn: 'root' }) export class TaskService { public tasks = new BehaviorSubject<Map<FileId, Task>>(new Map<FileId, Task>()); private _tasks = new Map<FileId, Task>(); private _allStates = []; private _allDelegations = []; constructor(private dexie: DexieService, private persistedFile: PersistedFileService, private repositoryService: RepositoryService) { } loadAllTasksOnce(): Promise<Task[]> { if (this._tasks.size == 0) { return this.loadAllTasks(); } else { let tasks1: Task[] = Array.from(this._tasks.values()); return new Promise<Task[]>(r => r(tasks1)); } } async loadAllTasks(): Promise<Task[]> { await this.repositoryService.waitLoadAllRepositoriesOnce(); let openRepositories = this.repositoryService.openRepositories; let tasks: Task[] = []; for (let repo of openRepositories) { let persisted = await this.dexie.getAllNonDeleted(repo.id, FileType.Task); tasks = tasks.concat(await Promise.all(persisted.filter(p => p.type === FileType.Task).map(p => this.persistedFile.toTask(p, repo)))); } tasks.forEach(t => this._tasks.set(t.id, t)); tasks.filter(t => t.parent).forEach(t => this._tasks.get(t.parent).addChild(t)); this.notifyChanges(); return tasks; } async loadAllTaskStates() { this._allStates.splice(0); await this.repositoryService.waitLoadAllRepositoriesOnce(); this.repositoryService.openRepositories.map(r => r.getTaskStateIndex.getAllValues()).forEach(given => { for (let tag of Array.from(given)) { if (tag) { if (this._allStates.findIndex(t => t.toLocaleLowerCase() === tag.toLocaleLowerCase()) == -1) { this._allStates.push(tag); } } } }); } async loadAllTaskDelegations() { this._allDelegations.splice(0); await this.repositoryService.waitLoadAllRepositoriesOnce(); this.repositoryService.openRepositories.map(r => r.getDelegationIndex.getAllValues()).forEach(given => { for (let delegation of Array.from(given)) { if (delegation) { if (this._allDelegations.findIndex(t => t.toLocaleLowerCase() === delegation.toLocaleLowerCase()) == -1) { this._allDelegations.push(delegation); } } } }); } notifyChanges() { let map = new Map(this._tasks.entries()); this.tasks.next(map); } async store(task: Task): Promise<string> { let repository = this.repositoryService.getRepository(task.repository); let id = await this.dexie.store(task, repository); if (!this._tasks.has(task.id)) { this._tasks.set(task.id, task); this.notifyChanges(); } return id; } async delete(task: Task): Promise<string> { task.deleted = new Date(); const id = await this.store(task); this.removeFromListAndNotify(task); return id; } async deleteAll(tasks: Task[]): Promise<string[]> { tasks.forEach(t => t.deleted = new Date()); let stored = await Promise.all(tasks.map(t => this.store(t))); tasks.forEach(t => this.removeFromList(t)); this.notifyChanges(); return stored; } async finishAll(tasks: Task[]): Promise<string[]> { tasks.forEach(t => t.details.finished = new Date()); let stored = await Promise.all(tasks.map(t => this.store(t))); this.notifyChanges(); return stored; } async getTask(id: string): Promise<Task | undefined> { await this.repositoryService.waitLoadAllRepositoriesOnce(); if (this._tasks.has(id)) { return this._tasks.get(id); } let file = await this.dexie.getById(id); if (file) { let repository = this.repositoryService.getRepository(file.repositoryId); let task = await this.persistedFile.toTask(file, repository); this._tasks.set(task.id, task); return task; } return undefined; } removeFromListAndNotify(file: Task) { this.removeFromList(file); this.notifyChanges(); } private removeFromList(file: Task) { Array.from(this._tasks.values()).forEach(t => { if (t.children) { let index = t.children.indexOf(t); if (index >= 0) { t.children.splice(index, 1); } } }); this._tasks.delete(file.id); } async finishTask(task: Task): Promise<string> { task.details.finished = new Date(); task.stopWork(); await this.store(task); this.notifyChanges(); return task.id; } get states(): string[] { return this._allStates.slice(); } get delegations(): string[] { return this._allDelegations.slice(); } async stopWork(task: Task): Promise<string> { task.stopWork(); await this.store(task); this.notifyChanges(); return task.id; } async startWork(task: Task): Promise<string> { task.startWork(); await this.store(task); this.notifyChanges(); return task.id; } async getTasksForList(list: TaskList): Promise<Task[]> { await this.loadAllTasksOnce(); let filter = list.details.filter; if (filter) { return filterTasks(filter, this._tasks, false); } else { return list.content.map(id => this._tasks.get(id)); } } async getScheduledTasks(start: moment.Moment, end: moment.Moment): Promise<Task[]> { await this.loadAllTasksOnce(); let retval = Array.from(this._tasks.values()) .filter(t => { return !!t.details.schedule; }) .filter(t => { return t.details.schedule.isScheduled(); }) .filter(t => { let startDate = moment(t.details.schedule.getStartDate()); let endDate = moment(t.details.schedule.getEndDate(t.details.estimatedTime)); let startIsIn = startDate.isBetween(start, end); let endIsIn = endDate.isBetween(start, end); let isInRange = startIsIn || endIsIn; let spansOverRange = startDate.isSameOrBefore(start) && endDate.isSameOrAfter(end); return isInRange || spansOverRange; }); return retval; } }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ import React from 'react'; import { render } from 'enzyme'; import { requiredProps } from '../../../test/required_props'; import { EuiCollapsibleNavGroup, BACKGROUNDS } from './collapsible_nav_group'; describe('EuiCollapsibleNavGroup', () => { test('is rendered', () => { const component = render( <EuiCollapsibleNavGroup id="id" {...requiredProps} /> ); expect(component).toMatchSnapshot(); }); describe('props', () => { test('title is rendered', () => { const component = render( <EuiCollapsibleNavGroup title="Title" id="id" /> ); expect(component).toMatchSnapshot(); }); test('iconType is rendered', () => { const component = render( <EuiCollapsibleNavGroup title="Title" iconType="bolt" id="id" /> ); expect(component).toMatchSnapshot(); }); test('iconSize is rendered', () => { const component = render( <EuiCollapsibleNavGroup title="Title" iconSize="s" iconType="bolt" id="id" /> ); expect(component).toMatchSnapshot(); }); test('iconProps renders data-test-subj', () => { const component = render( <EuiCollapsibleNavGroup title="Title" iconProps={{ 'data-test-subj': 'DTS', }} iconType="bolt" id="id" /> ); expect(component).toMatchSnapshot(); }); describe('background', () => { BACKGROUNDS.forEach((color) => { test(`${color} is rendered`, () => { const component = render( <EuiCollapsibleNavGroup id="id" background={color} /> ); expect(component).toMatchSnapshot(); }); }); }); test('titleElement can change the rendered element to h2', () => { const component = render( <EuiCollapsibleNavGroup title="Title" titleElement="h2" id="id" /> ); expect(component).toMatchSnapshot(); }); test('titleSize can be larger', () => { const component = render( <EuiCollapsibleNavGroup id="id" titleSize="s" /> ); expect(component).toMatchSnapshot(); }); }); describe('when isCollapsible is true', () => { test('will render an accordion', () => { const component = render( <EuiCollapsibleNavGroup isCollapsible={true} initialIsOpen={false} title="Title" id="id" /> ); expect(component).toMatchSnapshot(); }); test('accepts accordion props', () => { const component = render( <EuiCollapsibleNavGroup isCollapsible={true} initialIsOpen={false} title="Title" id="id" {...requiredProps} buttonProps={requiredProps} /> ); expect(component).toMatchSnapshot(); }); }); describe('throws a warning', () => { const oldConsoleError = console.warn; let consoleStub: jest.Mock; beforeEach(() => { // We don't use jest.spyOn() here, because EUI's tests apply a global // console.error() override that throws an exception. For these // tests, we just want to know if console.error() was called. console.warn = consoleStub = jest.fn(); }); afterEach(() => { console.warn = oldConsoleError; }); test('if iconType is passed without a title', () => { const component = render( <EuiCollapsibleNavGroup iconType="bolt" id="id" /> ); expect(consoleStub).toBeCalled(); expect(consoleStub.mock.calls[0][0]).toMatch( 'not render an icon without `title`' ); expect(component).toMatchSnapshot(); }); }); });
#!/bin/bash # ----------------------------------------- Setting parameters: HOSTNAME=$(hostname -i) SMTP_URL="XXXX" SMTP_MAIL="XXXX@XXXX" # Tableau data device location MOUNT_POINT=/tableau # Setup Tableau Server Version for install TABLEAU_SERVER_VER='2021-4-2' TS_VER_DIR="${TABLEAU_SERVER_VER//-/.}" TS_VER_RMP="tableau-server-${TABLEAU_SERVER_VER}.x86_64.rpm" TS_VER_RMP_LINK="https://downloads.tableau.com/esdalt/${TS_VER_DIR}/${TS_VER_RMP}" PSGSQL_JAR='postgresql-42.2.22.jar' PSGSQL_DIR='/opt/tableau/tableau_driver/jdbc' CHD_HIVE_RPM='ClouderaHiveODBC-2.6.11.1011-1.x86_64.rpm' CHD_IMPALA_RPM='ClouderaImpalaODBC-2.6.14.1016-1.x86_64.rpm' BLACK="\033[30m" RED="\033[31m" GREEN="\033[32m" YELLOW="\033[33m" BLUE="\033[34m" PINK="\033[35m" CYAN="\033[36m" WHITE="\033[37m" NORMAL="\033[0;39m" genpass() { openssl rand -hex 10 } # TABLEAU application admin user ADMIN_USER='admin' ADMIN_PWD=genpass # TABLEAU Server managmanet admin user ADMIN_SERVER_USER='tableau' ADMIN_SERVER_PWD=genpass # === Starting envirounment installation === # -------------------------------------------- echo -e $YELLOW "=== Starting envirounment installation ===" $NORMAL sudo yum -y update sudo yum -y upgrade sudo yum -y install htop # The best way is to run that script after resource "aws_volume_attachment" created sleep 60 # === Set local envirounment parameters === # ------------------------------------------ # [optional] - Backup /etc/environment sudo cp /etc/environment /etc/environment.orid # Edit /etc/environment - Adding these lines into sudo bash -c 'echo -e "LANG=en_US.utf-8" >> /etc/environment' sudo bash -c 'echo -e "LC_ALL=en_US.utf-8" >> /etc/environment' # === Automount EBS Volume on Reboot === # -------------------------------------- echo -e $CYAN "=== Data mount point Configuration ===" $NORMAL DEVICE=/dev/$(lsblk --noheadings --raw --sort SIZE | tail -1 | cut -d ' ' -f 1) sudo mkdir -p $MOUNT_POINT # Command to create a file system on the volume (Format) sudo mkfs -t xfs -f $DEVICE # Mount device with path sudo mount $DEVICE $MOUNT_POINT # Automatically mount an attached volume after reboot / For the current task it's not obligatory # Create a backup of your /etc/fstab sudo cp /etc/fstab /etc/fstab.orig UUID=$(sudo blkid | grep $DEVICE | awk -F '\"' '{print $2}') # Add entries into /etc/fstab to mount the device at the specified mount point sudo bash -c 'echo -e "# Mount device at /tableau_data" >> /etc/fstab' echo -e "UUID=$(echo $UUID) $MOUNT_POINT xfs defaults,nofail 0 1" | sudo tee -a /etc/fstab sudo umount $MOUNT_POINT # Mount all (remount to validate device attachment) sudo mount -a # --------------------------------------------------------------------------------------------------------------------- # Install ODBC driver manager echo -e $YELLOW "=== Install ODBC driver manager ===" $NORMAL sudo yum -y install libiodbc # Install the unixODBC manager sudo yum -y install unixODBC* unixODBC-devel* # Install libsasl libraries echo -e $YELLOW "=== Install libsasl libraries ===" $NORMAL sudo yum -y groupinstall "Development Tools" sudo yum -y install cyrus-sasl-gssapi sudo yum -y install cyrus-sasl-plain # Install Cyrus SASL From Source cd ~ wget https://github.com/cyrusimap/cyrus-sasl/releases/download/cyrus-sasl-2.1.27/cyrus-sasl-2.1.27.tar.gz tar xvfz cyrus-sasl-2.1.27.tar.gz cd cyrus-sasl-2.1.27 sudo mkdir -p /usr/local/cyrus_sasl/2_1_27 sudo chown -R ec2-user:ec2-user /usr/local/cyrus_sasl sudo mkdir -p /usr/local/lib/pkgconfig sudo chown -R ec2-user:ec2-user /usr/local/lib/pkgconfig ./configure --prefix=/usr/local/cyrus_sasl/2_1_27 make make install # link /usr/local/include sudo ln -s /usr/local/cyrus_sasl/2_1_27/lib/libsasl2.la /usr/local/lib/ sudo ln -s /usr/local/cyrus_sasl/2_1_27/lib/libsasl2.so /usr/local/lib/ sudo ln -s /usr/local/cyrus_sasl/2_1_27/lib/libsasl2.so.3 /usr/local/lib/ sudo ln -s /usr/local/cyrus_sasl/2_1_27/lib/libsasl2.so.3.0.0 /usr/local/lib/ sudo ln -s /usr/local/cyrus_sasl/2_1_27/lib/sasl2 /usr/local/lib/ # link /usr/local/lib/pkgconfig #sudo mkdir -p /usr/local/lib/pkgconfig sudo ln -s /usr/local/cyrus_sasl/2_1_27/lib/pkgconfig/libsasl2.pc /usr/local/lib/pkgconfig/ # link /usr/local/sbin sudo ln -s /usr/local/cyrus_sasl/2_1_27/sbin/pluginviewer /usr/local/sbin/ sudo ln -s /usr/local/cyrus_sasl/2_1_27/sbin/saslauthd /usr/local/sbin/ sudo ln -s /usr/local/cyrus_sasl/2_1_27/sbin/sasldblistusers2 /usr/local/sbin/ sudo ln -s /usr/local/cyrus_sasl/2_1_27/sbin/saslpasswd2 /usr/local/sbin/ sudo ln -s /usr/local/cyrus_sasl/2_1_27/sbin/testsaslauthd /usr/local/sbin/ # === Install Cloudera HIVE ODBC Driver === # ------------------------------------------ echo -e $CYAN "=== Install Cloudera HIVE ODBC Driver ===" $NORMAL cd ~ wget https://downloads.cloudera.com/connectors/Cloudera_Hive_ODBC_2.6.11/Linux/$CHD_HIVE_RPM # Hive ODBC RPM installation sudo yum -y --nogpgcheck localinstall $CHD_HIVE_RPM sudo yum list | grep ClouderaHiveODBC # Append the following lines to the /etc/odbcinst.ini file: echo -e '\n[Cloudera ODBC Driver for Apache Hive 64-bit]' | sudo tee -a /etc/odbcinst.ini echo -e 'Description=Cloudera ODBC Driver for Apache Hive (64-bit)' | sudo tee -a /etc/odbcinst.ini echo -e 'Driver=/opt/cloudera/hiveodbc/lib/64/libclouderahiveodbc64.so' | sudo tee -a /etc/odbcinst.ini # Update the driver configuration file /opt/cloudera/hiveodbc/lib/64/cloudera.hiveodbc.ini echo -e 'DriverManagerEncoding=UTF-16' | sudo tee -a /opt/cloudera/hiveodbc/lib/64/cloudera.hiveodbc.ini # === Install Cloudera Impala ODBC Driver === # ------------------------------------------ echo -e $CYAN "=== Install Cloudera Impala ODBC Driver ===" $NORMAL wget https://downloads.cloudera.com/connectors/impala_odbc_2.6.14.1016/Linux/$CHD_IMPALA_RPM # Impala ODBC RPM installation sudo yum -y --nogpgcheck localinstall $CHD_IMPALA_RPM # Append the following lines to the /etc/odbcinst.ini file echo -e '\n[Cloudera ODBC Driver for Impala 64-bit]' | sudo tee -a /etc/odbcinst.ini echo -e 'Description=Cloudera ODBC Driver for Impala (64-bit)' | sudo tee -a /etc/odbcinst.ini echo -e 'Driver=/opt/cloudera/impalaodbc/lib/64/libclouderaimpalaodbc64.so' | sudo tee -a /etc/odbcinst.ini echo -e 'FileUsage = 1' | sudo tee -a /etc/odbcinst.ini # Update the driver configuration file /opt/cloudera/impalaodbc/lib/64/cloudera.impalaodbc.ini echo -e 'DriverManagerEncoding=UTF-16' | sudo tee -a /opt/cloudera/impalaodbc/lib/64/cloudera.impalaodbc.ini # === Install Snowflake ODBC Driver === # ------------------------------------------ echo -e $CYAN "=== Install Snowflake ODBC Driver ===" $NORMAL # Create Snowflake odbc repo sudo touch /etc/yum.repos.d/snowflake-odbc.repo echo -e '[snowflake-odbc]' | sudo tee -a /etc/yum.repos.d/snowflake-odbc.repo echo -e 'name=snowflake-odbc' | sudo tee -a /etc/yum.repos.d/snowflake-odbc.repo echo -e 'baseurl=https://sfc-repo.snowflakecomputing.com/odbc/linux/2.24.2/' | sudo tee -a /etc/yum.repos.d/snowflake-odbc.repo echo -e 'gpgkey=https://sfc-repo.snowflakecomputing.com/odbc/Snowkey-37C7086698CB005C-gpg' | sudo tee -a /etc/yum.repos.d/snowflake-odbc.repo # Install Snowflake sudo yum -y install snowflake-odbc # === Install MySQL ODBC Driver === # ------------------------------------------ echo -e $CYAN "=== Install MySQL ODBC Driver ===" $NORMAL sudo yum -y install mysql-connector-odbc echo -e '\n[MySQL ODBC 8.0 Unicode Driver]' | sudo tee -a /etc/odbcinst.ini echo -e 'Driver=/usr/lib64/libmyodbc5w.so' | sudo tee -a /etc/odbcinst.ini echo -e 'UsageCount=1' | sudo tee -a /etc/odbcinst.ini echo -e '\n[MySQL ODBC 8.0 ANSI Driver]' | sudo tee -a /etc/odbcinst.ini echo -e 'Driver=/usr/lib64/libmyodbc5a.so' | sudo tee -a /etc/odbcinst.ini echo -e 'UsageCount=1' | sudo tee -a /etc/odbcinst.ini # === Installing Tableau Server === # --------------------------------- echo -e $YELLOW "=== Installing Tableau Server === " $NORMAL # Save ADMIN_PWD sudo mkdir -p $MOUNT_POINT/ssh echo -e "ADMIN_USER=${ADMIN_USER}" | sudo tee $MOUNT_POINT/ssh/keys $ADMIN_PWD | sudo tee $MOUNT_POINT/ssh/pwd echo -e "ADMIN_PWD=$(cat $MOUNT_POINT/ssh/pwd)" | sudo tee -a $MOUNT_POINT/ssh/keys ADMIN_PWD=$(cat $MOUNT_POINT/ssh/keys | grep ADMIN_PWD | cut -d '=' -f 2) # Save ADMIN_SERVER_PWD echo -e "ADMIN_SERVER_USER=${ADMIN_SERVER_USER}" | sudo tee -a $MOUNT_POINT/ssh/keys $ADMIN_SERVER_PWD | sudo tee $MOUNT_POINT/ssh/pwd echo -e "ADMIN_SERVER_PWD=$(cat $MOUNT_POINT/ssh/pwd)" | sudo tee -a $MOUNT_POINT/ssh/keys ADMIN_SERVER_PWD=$(cat $MOUNT_POINT/ssh/keys | grep ADMIN_SERVER_PWD | cut -d '=' -f 2) # Change dir to user path home cd ~ wget $TS_VER_RMP_LINK # Change previliges sudo chmod 755 $TS_VER_RMP # Insatlling tableau-server rpm pckg sudo yum -y install $TS_VER_RMP # === Install PsgSQL JAVA Driver === echo -e $YELLOW "=== Install PsgSQL JAVA Driver === " $NORMAL # PsgSQL .jar folder&file configuration wget "https://downloads.tableau.com/drivers/linux/postgresql/${PSGSQL_JAR}" sudo mkdir -p $PSGSQL_DIR sudo mv ~/$PSGSQL_JAR $PSGSQL_DIR # === Configure Local Firewall and Port configuration === # ------------------------------------------------------- echo -e $PINK "=== Configure Local Firewall and Port configuration ===" $NORMAL # Install Firewalld [provides a way to configure dynamic firewall rules in Linux] sudo yum -y install firewalld # Check dynamic port range. typical range is 8000 to 9000. #tsm configuration get -k ports.range.min #tsm configuration get -k ports.range.max # Start firewalld: sudo systemctl start firewalld # Set default zone to 'public' sudo firewall-cmd --set-default-zone=public -q # Verify that the default zone is a high-security zone, such as public. sudo firewall-cmd --get-default-zone # Add ports for the gateway, tabadmincontroller port and port range (27000-27010) # for licensing communication between nodes sudo firewall-cmd --permanent --add-port=80/tcp sudo firewall-cmd --permanent --add-port=8850/tcp sudo firewall-cmd --permanent --add-port=27000-27010/tcp sudo firewall-cmd --permanent --add-port=443/tcp # Configure the firewall to allow all traffic from the other nodes in the cluster. sudo firewall-cmd --permanent --add-rich-rule="rule family=ipv4 source address=$HOSTNAME/32 port port=8000-9000 protocol=tcp accept" sudo firewall-cmd --permanent --add-rich-rule="rule family=ipv4 source address=$HOSTNAME/32 port port=27000-27010 protocol=tcp accept" #Reload the firewall and verify the settings. sudo firewall-cmd --reload # [optional] List Firewall status sudo firewall-cmd --list-all # ---------------------------------------------------------------------------------------- # initialize TSM echo -e $YELLOW "Tableau Server - initializing tsm" $NORMAL cd /opt/tableau/tableau_server/packages/scripts.* sudo ./initialize-tsm --accepteula source /etc/profile.d/tableau_server.sh echo -e $CYAN "Tableau Server - Creating server administrator user" $NORMAL sudo usermod -a -G tsmadmin $ADMIN_SERVER_USER --password $ADMIN_SERVER_PWD echo $ADMIN_SERVER_PWD | sudo passwd --stdin $ADMIN_SERVER_USER # Check tms installed version echo -e $CYAN "Tableau Server - tsm version:" $NORMAL tsm version # Activate Trail version echo -e $PINK "Tableau Server - Activate Trail version:" $NORMAL tsm licenses activate -t # Change owner for mount point to 'tableau' sudo chown -R $ADMIN_SERVER_USER:$ADMIN_SERVER_USER $MOUNT_POINT # JSON Templeate creation for registry cd ~ REG='{ "zip" : "XXXX", "country" : "XXXX", "city" : "XXXX", "last_name" : "XXXX", "industry" : "XXXX", "eula" : "yes", "title" : "XXXX", "phone" : "XXXX", "company" : "XXXX", "state" : "XXXX", "department" : "XXXX", "first_name" : "Tableau", "email" : "{$SMTP_MAIL}" }' echo $REG | sudo tee $MOUNT_POINT/registration.json > /dev/null # Registration with JSON file echo -e $CYAN "Tableau Server - Registration and configuration:" $NORMAL tsm register --file $MOUNT_POINT/registration.json # Configure sample workbook installation [False or True] tsm configuration set -k install.component.samples -v false # Import Configuration File AUTH_CONFIG='{ "configEntities": { "gatewaySettings": { "_type": "gatewaySettingsType", "port": 80, "firewallOpeningEnabled": true, "sslRedirectEnabled": true, "publicHost": "localhost", "publicPort": 80 }, "identityStore": { "_type": "identityStoreType", "type": "local", "domain": "XXXX", "nickname": "XXXX" } }, "configKeys": { "gateway.timeout": "900" } }' echo $AUTH_CONFIG | sudo tee $MOUNT_POINT/auth_config.json > /dev/null tsm settings import -f $MOUNT_POINT/auth_config.json # TSM Apply Changes tsm pending-changes apply # Initialize and start Tableau Server echo -e $YELLOW "Tableau Server - Finishing initializing and starting server:" $NORMAL tsm initialize --start-server --request-timeout 1800 # Enable external file store tsm stop tsm topology external-services storage enable -network-share $MOUNT_POINT # Create an Tableau application admin user echo -e $CYAN "Tableau Server - Create an Tableau application admin user" $NORMAL tabcmd initialuser --username $ADMIN_USER --password $ADMIN_PWD --server http://localhost # Configure SMTP Setup SMTP='{ "configKeys": { "svcmonitor.notification.smtp.server": "'$SMTP_URL'", "svcmonitor.notification.smtp.send_account": "''", "svcmonitor.notification.smtp.port": 443, "svcmonitor.notification.smtp.password": "''", "svcmonitor.notification.smtp.ssl_enabled": true, "svcmonitor.notification.smtp.from_address": "'$SMTP_MAIL'", "svcmonitor.notification.smtp.target_addresses": "'$SMTP_MAIL'", "svcmonitor.notification.smtp.canonical_url": "'$SMTP_URL'" } }' echo $SMTP | sudo tee $MOUNT_POINT/smtp.json > /dev/null echo -e $CYAN "Tableau Server - Setting SMTP details" $NORMAL tsm settings import -f $MOUNT_POINT/smtp.json # === Configure NODE TSM Services: === # ------------------------------------ # Increase the value for the backgrounder.querylimit parameter. (20 Hours) tsm configuration set -k backgrounder.querylimit -v 60000 # Increase the application server Java Virtual machine heap space (Default=1024 MB) #tsm configuration set -k vizportal.vmopts -v "-XX:+UseConcMarkSweepGC -Xmx2048m -Xms256m -XX:+CrashOnOutOfMemoryError -XX:-CreateMinidumpOnCrash" # Set 'Backgrounder' to 3 services (defualt=2) tsm topology set-process -n node1 -pr backgrounder -c 2 # Set 'Cache Server' to 3 services (default=2) tsm topology set-process -n node1 -pr CacheServer -c 3 # Apply TSM pending-changes on NODE (Force restart) -------------------------------- echo -e $YELLOW "Tableau Server - Applying changes on server..." $NORMAL tsm pending-changes apply --ignore-prompt echo -e $GREEN "\n === Tableau Server installation completed! Version: ${TABLEAU_SERVER_VER} ===\n" $NORMAL echo -e $YELLOW "If you want to change your users admin passwords please run 'sudo passwd [username]'\n" $NORMAL echo -e "- Follow this link for Tableau Server Web UI: ${PINK} http://${HOSTNAME}"${NORMAL} echo -e "- Follow this link for Tableau Server Adminstration Managment Web UI: ${CYAN} https://${HOSTNAME}:8850\n"${NORMAL}
<gh_stars>1-10 package app.habitzl.elasticsearch.status.monitor.tool.client.data.connection; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; class ConnectionStatusTest { @ParameterizedTest @MethodSource(value = "httpStatusToConnectionStatus") void fromHttpCode_httpStatusCode_returnConnectionStatus(final int httpStatusCode, final ConnectionStatus expected) { // When ConnectionStatus result = ConnectionStatus.fromHttpCode(httpStatusCode); // Then assertThat(result, equalTo(expected)); } private static Stream<Arguments> httpStatusToConnectionStatus() { return Stream.of( Arguments.of(-1, ConnectionStatus.UNKNOWN), Arguments.of(0, ConnectionStatus.UNKNOWN), Arguments.of(200, ConnectionStatus.SUCCESS), Arguments.of(401, ConnectionStatus.UNAUTHORIZED), Arguments.of(404, ConnectionStatus.NOT_FOUND), Arguments.of(503, ConnectionStatus.SERVICE_UNAVAILABLE), Arguments.of(999, ConnectionStatus.UNKNOWN) ); } }
module.exports = ({ chainWebpack }, vendor) => { chainWebpack((config) => { if (!vendor) { config.optimization.splitChunks({ cacheGroups: {} }); } else { config.optimization.splitChunks({ cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, name: 'vendor', chunks: 'initial', minChunks: 2, }, } }); } }); };
function toLowerCase(str) { return str.toLowerCase(); }
/** */ package PhotosMetaModel.impl; import PhotosMetaModel.EnableGlobalMethodSecurity; import PhotosMetaModel.PhotosMetaModelPackage; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Enable Global Method Security</b></em>'. * <!-- end-user-doc --> * * @generated */ public class EnableGlobalMethodSecurityImpl extends MinimalEObjectImpl.Container implements EnableGlobalMethodSecurity { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EnableGlobalMethodSecurityImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return PhotosMetaModelPackage.Literals.ENABLE_GLOBAL_METHOD_SECURITY; } } //EnableGlobalMethodSecurityImpl
geometric-optimize --engine psi4 --nt 6 --coordsys dlc --enforce 0.1 input.dat constraints.txt | tee optimize.out
package com.dam.user.rest.message; import org.springframework.http.HttpStatus; import com.dam.user.model.entity.UserMessageContainer; public class UpdateResponse extends RestResponse{ private UserMessageContainer user; public UpdateResponse (UserMessageContainer user) { super(HttpStatus.OK, "OK", "User updated"); setUser(user); } private void setUser(UserMessageContainer user) { this.user = user; } public UserMessageContainer getUser() { return user; } }
function customize_subfooter_branding_bg_type($wp_customize) { // Add setting for subfooter branding background type $wp_customize->add_setting('subfooter_branding_bg_type', array('default' => 'default')); // Add control for subfooter branding background type $wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'subfooter_branding_bg_type_control', array( 'label' => __('Subfooter Branding Background Type'), 'section' => 'your_section_id', // Replace with the actual section ID 'settings' => 'subfooter_branding_bg_type', 'type' => 'select', 'choices' => array( 'show' => __('Display'), 'hide' => __('Hide') ), 'priority' => 4 ) ) ); } add_action('customize_register', 'customize_subfooter_branding_bg_type');
# Autocompletion for homebrew-cask. # # This script intercepts calls to the brew plugin and adds autocompletion # for the cask subcommand. # # Author: https://github.com/pstadler compdef _brew-cask brew _brew-cask() { local curcontext="$curcontext" state line typeset -A opt_args _arguments -C \ ':command:->command' \ ':subcmd:->subcmd' \ '*::options:->options' case $state in (command) __call_original_brew cask_commands=( 'cask:manage casks' ) _describe -t commands 'brew cask command' cask_commands ;; (subcmd) case "$line[1]" in cask) if (( CURRENT == 3 )); then local -a subcommands subcommands=( "alfred:used to modify Alfred's scope to include the Caskroom" 'audit:verifies installability of casks' 'checklinks:checks for bad cask links' 'cleanup:cleans up cached downloads' 'create:creates a cask of the given name and opens it in an editor' 'doctor:checks for configuration issues' 'edit:edits the cask of the given name' 'fetch:downloads Cask resources to local cache' 'home:opens the homepage of the cask of the given name' 'info:displays information about the cask of the given name' 'install:installs the cask of the given name' 'list:with no args, lists installed casks; given installed casks, lists installed files' 'search:searches all known casks' 'uninstall:uninstalls the cask of the given name' "update:a synonym for 'brew update'" ) _describe -t commands "brew cask subcommand" subcommands fi ;; *) __call_original_brew ;; esac ;; (options) local -a casks installed_casks local expl case "$line[2]" in list|uninstall) __brew_installed_casks _wanted installed_casks expl 'installed casks' compadd -a installed_casks ;; audit|edit|home|info|install) __brew_all_casks _wanted casks expl 'all casks' compadd -a casks ;; esac ;; esac } __brew_all_casks() { casks=(`brew cask search`) } __brew_installed_casks() { installed_casks=(`brew cask list`) } __call_original_brew() { local ret=1 _call_function ret _brew compdef _brew-cask brew }
#ifndef _VIDEO_PREPROCESSING_PLUGIN_H_ #define _VIDEO_PREPROCESSING_PLUGIN_H_ #include "../SDK/include/IAgoraRtcEngine.h" int load_preprocessing_plugin(agora::rtc::IRtcEngine* engine); int unload_preprocessing_plugin(agora::rtc::IRtcEngine* engine); #endif //_VIDEO_PREPROCESSING_PLUGIN_H_
#include <mutex> #include <condition_variable> #include <iostream> #include <thread> #include <vector> class FenceManager { public: void CreateFence(int fenceValue) { std::unique_lock<std::mutex> lock(_mutex); _fenceValues.push_back(fenceValue); _fences.push_back(false); } void SignalFence(int fenceValue) { std::unique_lock<std::mutex> lock(_mutex); auto it = std::find(_fenceValues.begin(), _fenceValues.end(), fenceValue); if (it != _fenceValues.end()) { size_t index = std::distance(_fenceValues.begin(), it); _fences[index] = true; _cv.notify_all(); } } void WaitForFence(int fenceValue) { std::unique_lock<std::mutex> lock(_mutex); auto it = std::find(_fenceValues.begin(), _fenceValues.end(), fenceValue); if (it != _fenceValues.end()) { size_t index = std::distance(_fenceValues.begin(), it); _cv.wait(lock, [this, index] { return _fences[index]; }); } } private: std::vector<int> _fenceValues; std::vector<bool> _fences; std::mutex _mutex; std::condition_variable _cv; }; int main() { FenceManager fenceManager; // Create fences fenceManager.CreateFence(1); fenceManager.CreateFence(2); fenceManager.CreateFence(3); // Signal fences from different threads std::thread t1([&fenceManager] { fenceManager.SignalFence(1); }); std::thread t2([&fenceManager] { fenceManager.SignalFence(2); }); std::thread t3([&fenceManager] { fenceManager.SignalFence(3); }); t1.join(); t2.join(); t3.join(); // Wait for fences to be signaled fenceManager.WaitForFence(1); fenceManager.WaitForFence(2); fenceManager.WaitForFence(3); std::cout << "All fences signaled." << std::endl; return 0; }
<gh_stars>1-10 package heap; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; /** * * @author exponential-e * 백준 11292번: 키 큰 사람 * * @see https://www.acmicpc.net/problem/11292 * */ public class Boj11292 { private static String SPACE = " "; private static String NEW_LINE = "\n"; private static class Student { private String name; private double height; private int index; public Student(String name, double height, int index) { this.name = name; this.height = height; this.index = index; } public double getHeight() { return -this.height; } public int getIndex() { return this.index; } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); while(true) { int N = Integer.parseInt(br.readLine()); if(N == 0) break; Queue<Student> pq = new PriorityQueue<>( Comparator.comparingDouble(Student::getHeight) .thenComparingInt(Student::getIndex) ); for(int i = 0; i < N; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); pq.offer(new Student(st.nextToken(), Double.parseDouble(st.nextToken()), i)); } List<String> students = getCandidate(pq); while(!students.isEmpty()) { sb.append(students.remove(0)).append(SPACE); } sb.append(NEW_LINE); } System.out.println(sb.toString()); } private static List<String> getCandidate(Queue<Student> pq) { List<String> result = new LinkedList<>(); Student top = pq.poll(); result.add(top.name); while(!pq.isEmpty()) { Student next = pq.poll(); if(next.height != top.height) break; result.add(next.name); } return result; } }
# Create train data: python3 generate_tfrecord.py \ --csv_input=data/data_train.csv \ --img_folder=images \ --output_file=train.record # Create validation data: python3 generate_tfrecord.py \ --csv_input=data/data_validation.csv \ --img_folder=images \ --output_file=validation.record # Create test data: python3 generate_tfrecord.py \ --csv_input=data/data_test.csv \ --img_folder=images \ --output_file=test.record
#!/bin/bash python scripts/train.py -k 10 -d yakindu-github -pd data/yakindu-github/ -s models/yakindu-github-finalModel-cuda.m -td models/yakindu-github-finalModel-cuda.details -e 50 -es trainloss -emf python -hi 64 -b 128 -dev cuda python scripts/train.py -k 10 -d ecore-github -pd data/ecore-github/ -s models/ecore-github-finalModel-cuda.m -td models/ecore-github-finalModel-cuda.details -e 75 -es trainloss -emf java -hi 64 -b 128 -dev cuda python scripts/train.py -k 10 -d yakindu-exercise -pd data/yakindu-exercise/ -s models/yakindu-exercise-finalModel-cuda.m -td models/yakindu-exercise-finalModel-cuda.details -e 25 -es trainloss -emf python -hi 64 -b 128 -dev cuda python scripts/train.py -k 10 -d rds-genmymodel -pd data/rds-genmymodel/ -s models/rds-genmymodel-finalModel-cuda.m -td models/rds-genmymodel-finalModel-cuda.details -e 75 -es trainloss -emf python -hi 64 -b 128 -dev cuda
<filename>packages/react-core/src/components/Divider/examples/DividerVerticalFlexInsetMedium.tsx<gh_stars>0 import React from 'react'; import { Divider, Flex, FlexItem } from '@patternfly/react-core'; export const DividerVerticalFlexInsetMedium: React.FunctionComponent = () => ( <Flex> <FlexItem>first item</FlexItem> <Divider orientation={{ default: 'vertical' }} inset={{ default: 'insetMd' }} /> <FlexItem>second item</FlexItem> </Flex> );
/* Node.js script to compile kit into single page on-device (local) HTML file with no external dependencies, suitable for offline mobile use. */ const fs = require('fs'); const path = require('path'); const parse5 = require('parse5'); function findAttribute(attribute, node=null) { if (node == null) { return (null); } if (node.attrs == undefined) { return (null); } for (var count=0; count < node.attrs.length; count++) { var currentAttr = node.attrs[count]; if (currentAttr.name == attribute) { return (currentAttr.value); } } return (null); } function deleteAttribute(attribute, node=null) { if (node == null) { return (false); } if (node.attrs == undefined) { return (false); } for (var count=0; count < node.attrs.length; count++) { var currentAttr = node.attrs[count]; if (currentAttr.name == attribute) { node.attrs.splice(count, 1); return (true); } } return (false); } function findNodes(name, doc) { for (var count=0; count < doc.childNodes.length; count++) { var childNode = doc.childNodes[count]; if (childNode.nodeName == name) { return (childNode); } } return (null); } function replaceScriptNode(node) { var replaceFilePath = findAttribute("src", node); deleteAttribute("src", node); var insertFile = fs.readFileSync(replaceFilePath); console.log ("Inserting script contents: "+replaceFilePath); var textNode = new Object(); textNode.nodeName = "#text"; textNode.value = String.fromCharCode(13) + insertFile.toString() + String.fromCharCode(13); textNode.parentNode = node; node.childNodes = [textNode]; } function replaceStyleNode(nodes, index) { var replaceFilePath = findAttribute("href", nodes[index]); var insertFile = fs.readFileSync(replaceFilePath); console.log ("Inserting style contents: "+replaceFilePath); var styleNode = new Object(); styleNode.nodeName = "style"; styleNode.tagName = "style"; styleNode.attrs = []; styleNode.namespaceURI = "http://www.w3.org/1999/xhtml"; styleNode.parentNode = nodes[index]; var textNode = new Object(); textNode.nodeName = "#text"; textNode.value = String.fromCharCode(13) + insertFile.toString() + String.fromCharCode(13); textNode.parentNode = styleNode; styleNode.childNodes = [textNode]; nodes[index] = styleNode; } function replaceNodes(doc) { for (var count=0; count < doc.childNodes.length; count++) { var childNode = doc.childNodes[count]; if (childNode.nodeName == "script") { replaceScriptNode(childNode); } if (childNode.nodeName == "link") { replaceStyleNode(doc.childNodes, count); } if (childNode.childNodes != undefined) { replaceNodes(childNode); } } } console.log("Compiling main page (index.html) to integrated single page (index-device.html)..."); var indexHTML = fs.readFileSync("index.html"); var document = parse5.parse(indexHTML.toString()); replaceNodes(document); fs.writeFileSync("index-device.html", parse5.serialize(document)); console.log ("Done.");
#!/usr/bin/env bash # This is a script that will train all of the models for scene graph classification and then evaluate them. #export CUDA_VISIBLE_DEVICES=$1 echo "EVALUATING MOTIFNET" # python -m models.eval_rels -m sgcls -model motifnet -order leftright -nl_obj 2 -nl_edge 4 -b 1 -clip 5 \ # -p 100 -hidden_dim 512 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -test -ckpt /scratch/cluster/ankgarg/gqa/temp_abhinav/checkpoints/motifnet_sgcls/vgrel-0.tar -nepoch 50 -use_bias -cache motifnet_sgcls # python -m models.eval_rels -m predcls -model motifnet -order leftright -nl_obj 2 -nl_edge 4 -b 1 -clip 5 \ # -p 100 -hidden_dim 512 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -test -ckpt /scratch/cluster/ankgarg/gqa/temp_abhinav/checkpoints/motifnet_sgcls/vgrel-0.tar -nepoch 50 -use_bias -cache motifnet_predcls # python -m models._visualize -m predcls -model motifnet -order leftright -nl_obj 2 -nl_edge 4 -b 1 -clip 5 \ # -p 100 -hidden_dim 512 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -test -ckpt /scratch/cluster/ankgarg/gqa/temp_abhinav/checkpoints/motifnet_sgcls/vgrel-0.tar -nepoch 50 -use_bias -cache motifnet_visualize # test, val, train python -m models.generate_scenegraph -m predcls -model motifnet -order leftright -nl_obj 2 -nl_edge 4 -b 1 -clip 5 \ -p 100 -hidden_dim 512 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -test -ckpt /scratch/cluster/ankgarg/gqa/temp_abhinav/checkpoints/motifnet_sgcls/vgrel-0.tar -nepoch 50 -use_bias -cache motifnet_generate_scenegraph python -m models.generate_scenegraph -m predcls -model motifnet -order leftright -nl_obj 2 -nl_edge 4 -b 1 -clip 5 \ -p 100 -hidden_dim 512 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -val -ckpt /scratch/cluster/ankgarg/gqa/temp_abhinav/checkpoints/motifnet_sgcls/vgrel-0.tar -nepoch 50 -use_bias -cache motifnet_generate_scenegraph python -m models.generate_scenegraph -m predcls -model motifnet -order leftright -nl_obj 2 -nl_edge 4 -b 1 -clip 5 \ -p 100 -hidden_dim 512 -pooling_dim 4096 -lr 1e-3 -ngpu 1 -ckpt /scratch/cluster/ankgarg/gqa/temp_abhinav/checkpoints/motifnet_sgcls/vgrel-0.tar -nepoch 50 -use_bias -cache motifnet_generate_scenegraph
<gh_stars>1-10 /* * Copyright 2016 <NAME>, <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 org.noorganization.instalist.view.modelwrappers; import android.os.Parcelable; /** * The Interface for accessing Items for the Item overview. * Created by TS on 25.05.2015. */ public interface IBaseListEntry extends Parcelable { enum eItemType{ PRODUCT_LIST_ENTRY, RECIPE_LIST_ENTRY, ALL, NAME_SEARCH, // no good style } /** * Get the assigned name of the item. * @return the name of the item. */ String getName(); /** * Sets the name of the item. * @param _Name the name of the item. */ void setName(String _Name); /** * Get the type of this item. * @return */ eItemType getType(); /** * Check if item is checked. * @return true if checked, false if not. */ boolean isChecked(); /** * Sets the checked field. * @param _Checked true if should be checked, false not to be checked. */ void setChecked(boolean _Checked); /** * Get the item inside. * @return the according item. */ Object getItem(); /** * Get the Id of this item. * @return the item of this item. */ String getId(); /** * * @param o * @return */ boolean equals(Object o); /** * * @return */ int hashCode(); }
import styled from 'react-emotion' export default styled.div` ${props => props.theme.mq({ maxWidth: [960, 960, 1152, 1344] })}; margin: 0 auto; padding: 0 1rem; `
import React from 'react' import { CircularProgress } from '@material-ui/core' export default function LoadingIcon() { return ( <div className="loading-icon-container"> <CircularProgress/> </div> ) }
package <%= projectNameSnakeCase %> import ( "fmt" "path" "github.com/hallucino5105/glog" "github.com/hallucino5105/<%= projectNameSnakeCase %>/cmd/garg" "github.com/hallucino5105/<%= projectNameSnakeCase %>/pkg/appconf" "github.com/hallucino5105/<%= projectNameSnakeCase %>/pkg/<%= projectNameSnakeCase %>/handler" "github.com/labstack/echo" "github.com/labstack/echo/middleware" "github.com/pkg/errors" ) func Entry() error { glog.SetupLogger(glog.WithVerbose(garg.GlobalOptions.Verbose)) conf, err := appconf.LoadAppConfig() if err != nil { return errors.WithStack(err) } startServer(conf) return nil } func startServer(conf *appconf.AppConfig) { e := echo.New() e.Use(middleware.Logger()) e.Use(middleware.Recover()) e.Use(middleware.CORS()) e.GET(path.Join(conf.Serve.PublicPath, "/api/sample.json"), handler.HandlerSample()) addr := fmt.Sprintf("%s:%s", conf.Serve.Host, conf.Serve.Port) glog.Debugf("serve address \"%s\"", addr) e.Logger.Fatal(e.Start(addr)) }
#!/bin/sh ./tictactoe -n -l tictactoe.net
SELECT Name FROM Employee WHERE Salary = (SELECT MAX(Salary) FROM Employee WHERE City = Employee.City)
<gh_stars>1-10 "use strict"; exports.__esModule = true; var toString_1 = require("../lang/toString"); var trim_1 = require("./trim"); /** * Limit number of chars. */ function truncate(str, maxChars, append, onlyFullWords) { str = toString_1["default"](str); append = append || '...'; maxChars = onlyFullWords ? maxChars + 1 : maxChars; str = trim_1["default"](str); if (str.length <= maxChars) { return str; } str = str.substr(0, maxChars - append.length); // crop at last space or remove trailing whitespace str = onlyFullWords ? str.substr(0, str.lastIndexOf(' ')) : trim_1["default"](str); return str + append; } exports["default"] = truncate;
mkdir "Binaries" # # # dir=$(pwd)/$(dirname $0) # echo ${dir} # # # gccflags="-std=c++14 -Wall -Wno-unused-function -O2 -lpthread" # includepath="${dir}/../Source" # # SOURCES= # SOURCES+=" ../Source/PublicLibs/SMC_PublicLibs.cpp" # SOURCES+=" ../Source/DigitViewer2/SMC_DigitViewer2.cpp" # SOURCES+=" ../Source/DigitViewer2/Main.cpp" # # echo "Compiling 05-A64 (x64 SSE3)..." # g++ $SOURCES -I "${includepath}" ${gccflags} -D X64_04_SSE3 -msse3 -o "Binaries/Digit Viewer - 05-A64" # # echo "Compiling 07-PNR (x64 SSE4.1)..." # g++ $SOURCES -I "${includepath}" ${gccflags} -D X64_07_Penryn -march=core2 -msse4.1 -o "Binaries/Digit Viewer - 07-PNR" # # echo "Compiling 13-HSW (x64 AVX2)..." # g++ $SOURCES -I "${includepath}" ${gccflags} -D X64_13_Haswell -march=haswell -o "Binaries/Digit Viewer - 13-HSW" # # echo "Compiling 17-SKX (x64 AVX512BW)..." # g++ $SOURCES -I "${includepath}" ${gccflags} -D X64_17_Skylake -march=skylake-avx512 -o "Binaries/Digit Viewer - 17-SKX" # #
workspace_path="../prostate_3D/workspace_prostate" dataset_path="../data_preparation/dataset" datalist_path="../data_preparation/datalist" echo "Centralized" python3 prostate_3d_test_only.py --model_path "${workspace_path}/server/${job_id_cen}/app_server/best_FL_global_model.pt" --dataset_base_dir ${dataset_path} --datalist_json_path "${datalist_path}/client_All.json" echo "FedAvg" python3 prostate_3d_test_only.py --model_path "${workspace_path}/server/${job_id_avg}/app_server/best_FL_global_model.pt" --dataset_base_dir ${dataset_path} --datalist_json_path "${datalist_path}/client_All.json" echo "FedProx" python3 prostate_3d_test_only.py --model_path "${workspace_path}/server/${job_id_prox}/app_server/best_FL_global_model.pt" --dataset_base_dir ${dataset_path} --datalist_json_path "${datalist_path}/client_All.json" echo "Ditto" site_IDs="I2CVB MSD NCI_ISBI_3T NCI_ISBI_Dx" for site in ${site_IDs}; do python3 prostate_3d_test_only.py --model_path "${workspace_path}/client_${site}/${job_id_dit}/app_client_${site}/best_personalized_model.pt" --dataset_base_dir ${dataset_path} --datalist_json_path "${datalist_path}/client_${site}.json" done
require("dotenv").config({path: `${__dirname}/.env`}); const express = require("express"), databaseConfig = require("./config/databaseConfig"), mongoose = require("mongoose"), {Client} = require("pg"); require("./models/index")(); const CoalitionsController = require("./controllers/Coalitions.controller"); const UsersController = require("./controllers/Users.controller"); const logger = require("./helpers/logger.helper"), app = express(), server = require("http").Server(app), Storage = require("storage"), globalStorage = new Storage(), queue = new (require("./helpers/Queue.helper"))(globalStorage), Oauth = require("./helpers/OAuth.helper"), oauth = new Oauth(globalStorage, queue), psqlClient = new Client(), coalitionsController = new CoalitionsController(globalStorage, queue, oauth, psqlClient), usersController = new UsersController(globalStorage, queue, oauth, psqlClient), io = require("./websockets/io")(server, globalStorage, queue, oauth, coalitionsController, usersController), bodyParser = require("body-parser"), cors = require("cors"), morgan = require("morgan"), tokenHelper = require("./helpers/tokenCache.helper"), stdinHelper = require("./helpers/stdin.helper"); const {clientPath, serverPort} = require("./config/globalConfig"); coalitionsController.updateScores(); app.use(cors()); app.use(morgan("dev")); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.use(express.static(__dirname + clientPath)); app.use((req, res, next) => { var err = new Error("Not Found"); err.status = 404; next(err); }); mongoose.connect(databaseConfig.db).then(() => {}, (err) => { logger.add_log({ type: "Error", description: "DB error", additionnal_infos: { Error :err } }); }); globalStorage.set({psqlStatus: false}); const db = mongoose.connection; const promise = psqlClient.connect() .then(() => { globalStorage.psqlStatus = true; logger.add_log({ type: "General", description: "Connected to PSQL database" }); }) .catch(() => logger.add_log({ type: "warning", description: "Couldn't connect to PSQL database" })); db.on("error", (err) => { logger.add_log({ type: "Error", description: "DB error", additionnal_infos: { Error :err } }); }); db.once("open", () => { logger.add_log({ type: "General", description: "Succesfully Connected to database" }); promise .then(() => { globalStorage.userInfos = {}; server.listen(serverPort, () => { logger.add_log({ type: "General", description: "Succesfully launched server", additionnal_infos: { Port: serverPort } }); }); }) .catch(error => logger.add_log({ type: "error", description: "Server couldn't be launched", additionnal_infos: {error} })); }); process.on("SIGINT", () => tokenHelper.saveTokens(globalStorage)); process.on("SIGHUP", () => tokenHelper.saveTokens(globalStorage)); process.on("SIGTERM", () => tokenHelper.saveTokens(globalStorage)); process.stdin.setEncoding("utf8"); process.stdin.on("data", text => stdinHelper.treateCommand(text, io.sockets));
<filename>cgfy-tkmybatis/src/main/java/com/cgfy/mybatis/bussApi/service/TestGenService.java package com.cgfy.mybatis.bussApi.service; import com.cgfy.mybatis.base.service.BaseService; import com.cgfy.mybatis.base.bean.CgfyListResponse; import com.cgfy.mybatis.base.bean.CgfySelectInputBean; import com.cgfy.mybatis.bussApi.bean.TestGenOutputBean; import com.cgfy.mybatis.bussApi.bean.TestGenInputBean; /** * 「cgfy」基础Service * * @author cgfy_web */ public interface TestGenService extends BaseService{ /** * 检索 * @param cgfyInput 输入参数 * @return 输出对象 */ public CgfyListResponse<TestGenOutputBean> select(CgfySelectInputBean CgfyInput); /** * 保存 * @param input 输入参数 * @param id 主键id * @return 输出对象 */ public TestGenOutputBean save(TestGenInputBean input,String id); /** * 获取详情 * @param id 主键id * @return 输出对象 */ public TestGenOutputBean getDetail(String id); /** * 物理删除 * @param id 主键id * @return 输出对象 */ public void deleteForce(String id); }
#!/bin/bash #SBATCH -J Act_maxsig_1 #SBATCH --mail-user=eger@ukp.informatik.tu-darmstadt.de #SBATCH --mail-type=FAIL #SBATCH -e /work/scratch/se55gyhe/log/output.err.%j #SBATCH -o /work/scratch/se55gyhe/log/output.out.%j #SBATCH -n 1 # Number of cores #SBATCH --mem-per-cpu=6000 #SBATCH -t 23:59:00 # Hours, minutes and seconds, or '#SBATCH -t 10' -only mins #module load intel python/3.5 python3 /home/se55gyhe/Act_func/sequence_tagging/arg_min/PE-my.py maxsig 143 Adamax 3 0.657308980115609 0.0021407175196852006 id 0.05
package com.dayofpi.super_block_world.world.feature.utility.feature_config; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import com.mojang.serialization.DynamicOps; import com.mojang.serialization.codecs.RecordCodecBuilder.Instance; import net.minecraft.util.dynamic.Codecs; public class CustomFeatureConfig { public static final Codec<CustomFeatureConfig> CODEC = RecordCodecBuilder.create((instance) -> instance.group( Codec.INT.fieldOf("rarity").forGetter(CustomFeatureConfig::getRarity), Codec.BOOL.fieldOf("enabled").forGetter(CustomFeatureConfig::isEnabled), Codec.STRING.fieldOf("identifier").forGetter(CustomFeatureConfig::getIdentifier) ).apply(instance, CustomFeatureConfig::new) ); private final int rarity; private final boolean enabled; private final String identifier; public CustomFeatureConfig(int rarity, boolean enabled, String identifier) { this.rarity = rarity; this.enabled = enabled; this.identifier = identifier; } public int getRarity() { return rarity; } public boolean isEnabled() { return enabled; } public String getIdentifier() { return identifier; } public <T> DynamicOps<T> serialize(DynamicOps<T> ops) { return CODEC.encodeStart(ops, this).result().orElse(ops.empty()); } public static <T> CustomFeatureConfig deserialize(DynamicOps<T> ops, T input) { return CODEC.parse(ops, input).resultOrPartial(ops, CustomFeatureConfig::new).orElse(null); } }
<reponame>tuckerbeauchamp/whatToWatch import React from 'react'; function DetailsCard(props) { return( <> <div className="details-container"> <div className="card"> <img src={props.image} alt={props.title} /> </div> <div className="desc"> <p>{props.overview}</p> <p>{props.release}</p> </div> </div> <div className="flexspace"> <button className="is-primary" onClick={props.addFavorite}>Save</button> <div className="rating"> {props.rating} </div> </div> </> ) } export default DetailsCard;
cortex testtypes.cx test1.cx > test1.log cortex testtypes.cx test2.cx > test2.log
package com.cbsb.backup.exporter; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.util.Vector; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import android.text.TextUtils; import com.cbsb.backup.BackupTask; import com.cbsb.backup.R; import com.cbsb.backup.Strings; public abstract class SimpleExporter extends Exporter { protected static final String EQUALS = "=\""; protected Context context; private String tag; private String[] fields; private Uri contentUri; private boolean checkFields; private String selection; private String filename; private String sortOrder; private String[] optionalFields; public SimpleExporter(String tag, String[] fields, Uri contentUri, boolean checkFields, String selection, String sortOrder, ExportTask exportTask, String[] optionalFields) { super(exportTask); this.context = exportTask.getContext(); this.tag = tag; this.fields = fields; this.contentUri = contentUri; this.selection = selection; this.checkFields = checkFields; this.sortOrder = sortOrder; this.optionalFields = optionalFields; } public SimpleExporter(String tag, String[] fields, Uri contentUri, boolean checkFields, String selection, ExportTask exportTask) { this(tag, fields, contentUri, checkFields, selection, null, exportTask, null); } public SimpleExporter(String tag, String[] fields, Uri contentUri, boolean checkFields, ExportTask exportTask) { this(tag, fields, contentUri, checkFields, null, exportTask); } public SimpleExporter(String tag, Uri contentUri, String selection, ExportTask exportTask) { this(tag, null, contentUri, false, selection, exportTask); } public SimpleExporter(String tag, Uri contentUri, ExportTask exportTask) { this(tag, contentUri, null, exportTask); } public final int export(String filename) throws Exception { this.filename = filename; Cursor cursor = context.getContentResolver().query(contentUri, null, selection, null, sortOrder); if (checkFields && fields != null) { if (cursor == null || !checkFieldNames(cursor.getColumnNames(), fields)) { throw new Exception(context.getString(R.string.error_unsupporteddatabasestructure)); } if (optionalFields != null && optionalFields.length > 0) { fields = determineFields(cursor.getColumnNames(), fields, optionalFields); } } else if (fields == null) { if (cursor == null) { this.filename = null; return 0; } else { fields = cursor.getColumnNames(); } } int count = cursor.getCount(); if (count == 0) { this.filename = null; return 0; } exportTask.progress(BackupTask.MESSAGE_COUNT, count); exportTask.progress(BackupTask.MESSAGE_PROGRESS, 0); int length = fields.length; int[] positions = new int[length]; for (int n = 0; n < length; n++) { positions[n] = cursor.getColumnIndex(fields[n]); } BufferedWriter writer = new BufferedWriter(new PrintWriter(filename, Strings.UTF8)); writeXmlStart(writer, tag, count); int position = 0; while (!canceled && cursor.moveToNext()) { writer.write('<'); writer.write(tag); for (int n = 0; n < length; n++) { try { String string = cursor.getString(positions[n]); if (string != null && !BaseColumns._ID.equals(fields[n])) { writer.write(' '); writer.write(fields[n]); writer.write(EQUALS); writer.write(TextUtils.htmlEncode(string)); writer.write('"'); } } catch (Exception e) { // if there is blob data } } writer.write('>'); addText(cursor, writer); writer.write(ENDTAG_START); writer.write(tag); writer.write(TAG_END); exportTask.progress(BackupTask.MESSAGE_PROGRESS, ++position); } cursor.close(); writeXmlEnd(writer, tag); writer.close(); if (!canceled) { return count; } else { new File(filename).delete(); this.filename = null; return -1; } } private String[] determineFields(String[] columnNames, String[] fields, String[] optionalFields) { Vector<String> result = new Vector<String>(); for (String field : fields) { result.add(field); } for (String field : optionalFields) { if (Strings.indexOf(columnNames, field) > -1) { result.add(field); } } return result.toArray(new String[0]); } protected boolean checkFieldNames(String[] availableFieldNames, String[] neededFieldNames) { for (int n = 0, i = neededFieldNames != null ? neededFieldNames.length : 0; n < i; n++) { if (Strings.indexOf(availableFieldNames, neededFieldNames[n]) == -1) { return false; } } return true; } /* * Override to use */ public void addText(Cursor cursor, Writer writer) throws IOException { } @Override public String[] getExportedFilenames() { return new String[] {filename}; } public String getFilename() { return filename; } }
<reponame>tailhook/jarred<gh_stars>1-10 function Hotkeys() { var self = this; var bindings = {}; var state = null; this.allow_input = false; // public methods this.bind_to = function (el) { jQuery(el).keydown(handler); } this.unbind_from = function (el) { jQuery(el).unbind('keydown', handler); } this.add_key = function(key, fun) { jQuery.each(key.split(' '), function(i, val) { add_key(val, fun); }); } this.handle = function(key, owner) { this.reset(); var lst = key.match(/<[^>]+>|./g); jQuery.each(lst, function(i, val) { handle(val, owner); }); this.reset(); } this.reset = function() { state = null; } function add_key(key, fun) { var lst = key.match(/<[^>]+>|./g); if(lst.length < 1) return; var tmp = bindings; while(lst.length > 1) { var single = lst.shift(); if(!(single in tmp)) { tmp = tmp[single] = {}; } else { tmp = tmp[single]; } if(typeof tmp == 'function') throw Error("Conflicting binding \"" + key + "\""); } tmp[lst[0]] = fun; } function handle(key, owner) { var nstate = state; if(!nstate) nstate = bindings; nstate = nstate[key]; if(!nstate) { if(self.modifiers[key]) { return false; } state = null; return true; } if(typeof nstate == 'function') { state = null; nstate(owner); return false; } state = nstate; return false; } // private methods function handler(ev) { if ((/textarea|select/i.test(ev.target.nodeName) || ev.target.type === "text") && !self.allow_input) { return; } var special = ev.type !== "keypress" && self.specialKeys[ ev.which ]; var key = String.fromCharCode( ev.which ).toLowerCase(); if(special) { key = special; } if ( ev.ctrlKey && special !== "ctrl" ) { key = "C-" + key; } if ( ev.shiftKey && special !== "shift" ) { if(special) { key = 'S-' + key; } else { key = key.toUpperCase(); } } if(key.length > 1) { key = '<'+key+'>'; } return handle(key, ev.target); } return this; } Hotkeys.prototype.specialKeys = { 8: "backspace", 9: "tab", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause", 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 191: "/", 91: "win", 189: "-", 187: "=", 219: "[", 221: "]", 224: "meta" }; Hotkeys.prototype.shiftNums = { "`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": "\"", ",": "<", ".": ">", "/": "?", "\\": "|" }; Hotkeys.prototype.modifiers = { '<shift>': 1, '<alt>': 1, '<ctrl>': 1, '<win>': 1 };
/** A typical comparator for sorting object keys */ type KeyComparator = (a: string, b: string) => number /** An indexable object */ type IndexedObject = { [key: string]: any } /** * Returns a copy of the passed array, with all nested objects within it sorted deeply by their keys, without mangling any nested arrays. * @param subject The unsorted array. * @param comparator An optional comparator for sorting keys of objects. * @returns The new sorted array. */ export function sortArray<T extends any[]>( subject: T, comparator?: KeyComparator ): T { const result = [] for (let value of subject) { // Recurse if object or array if (value != null) { if (Array.isArray(value)) { value = sortArray(value, comparator) } else if (typeof value === 'object') { /* eslint no-use-before-define:0 */ value = sortObject(value, comparator) } } // Push result.push(value) } return result as T } /** * Returns a copy of the passed object, with all nested objects within it sorted deeply by their keys, without mangling any nested arrays inside of it. * @param subject The unsorted object. * @param comparator An optional comparator for sorting keys of objects. * @returns The new sorted object. */ export default function sortObject<T extends IndexedObject>( subject: T, comparator?: KeyComparator ): T { const result: IndexedObject = {} as T const sortedKeys = Object.keys(subject).sort(comparator) for (let i = 0; i < sortedKeys.length; ++i) { // Fetch const key = sortedKeys[i] let value = subject[key] // Recurse if object or array if (value != null) { if (Array.isArray(value)) { value = sortArray(value, comparator) } else if (typeof value === 'object') { value = sortObject(value, comparator) } } // Push result[key] = value } return result as T }
<reponame>Rca96/controle-estoque  //Variaveis usadas dentro do código //valor do raio var raio; //variavel para criar circulo a partir de um centro var myCity, myCityDesenho, isvisible = false; //mapa var map; //usado para montar os marcadores var marker2; //marcadores em volta do ponto escolhido var markers = new Array(); //ip que esta acessando var ipusu; //organizção(provedor) responsavel pelo ip var org; //dados vindo do banco, com a localização var locations2 = ""; //dados para montar tabela var dadosf2 = ""; //id da cidade var idc; //latitude e longitude da cidade var latlngLate; //usado para marcar a cidade escolhida com um marcador diferente var customerMarker; // grupo de markers var markerCluster = new MarkerClusterer(); //array para mapa de calor var heatmapData = new Array(); //usado para instanciar mapa de calor var heatmap; //filtrar por secretaria var secretaria = null; $(document).ready(function(){ $('#raio_acao').click(function(){ var raio= $('#raio').val(); if($.isNumeric(raio)) $("#raio_atual").html(raio); else alert("Digite apenas números!"); }); MontaMapa(-22.3519957, -47.3520484); // simula click no mapa para carregar pontos google.maps.event.trigger(map, 'click', { stop: null, latLng: new google.maps.LatLng(-22.3519957, -47.3520484) }); $("body").on('click', '.secretaria', function(){ secretaria = $(this).attr('data-val'); if($(this).attr('style') == 'color:blue;font-weight:bold') secretaria = null; getData(); }); $("body").on('click', '.total_secs', function(){ secretaria = null; $('.secretaria').attr('style', ''); getData(); }); }); function success(position) { var s = document.querySelector('#status'); if (s.className == 'success') { return; } s.innerHTML = ""; s.className = 'success'; var lati = position.coords.latitude; var longi = position.coords.longitude; MontaMapa(lati, longi); } //Monta o mapa function MontaMapa(latitude, longitude){ var latlng = new google.maps.LatLng(latitude, longitude); latlngLate = latlng; var myOptions = { zoom: 13.6, center: latlng, mapTypeControl: true, mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.SMALL, position: google.maps.ControlPosition.TOP_RIGHT }, mapTypeIds: [ google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE ], streetViewControl: false, }; map = new google.maps.Map(document.getElementById("mapa"), myOptions); google.maps.event.addListener(map, 'click', function(event) { placeCustomerMarker(event.latLng); }); var marker; myCity = new google.maps.Circle({ center: latlngLate, radius: 30000, strokeColor: "#0000FF", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#0000FF", fillOpacity: 0.4 }); myCity.setMap(map); myCity.setVisible(false); //getLocations(latitude,longitude); //PONTOS & CALOR var centerControlDiv = document.createElement('div'); var centerControl = new CenterControl(centerControlDiv, map); centerControlDiv.index = 1; map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(centerControlDiv); //EXIBIR RAIO var topRightControlDiv2 = document.createElement('div'); var centerControl = new TopRightControl2(topRightControlDiv2, map); topRightControlDiv2.index = 2; map.controls[google.maps.ControlPosition.TOP_RIGHT].push(topRightControlDiv2); } function CenterControl(controlDiv, map) { // Set CSS for the control border. var controlUI = document.createElement('div'); controlUI.style.backgroundColor = '#1a1a1a'; controlUI.style.border = '2px solid #1a1a1a'; controlUI.style.borderRadius = '10px 0px 0px 10px'; controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)'; controlUI.style.cursor = 'pointer'; controlUI.style.marginBottom = '22px'; controlUI.style.textAlign = 'left'; controlUI.title = 'Escolha o tipo de mapa'; controlDiv.appendChild(controlUI); // Set CSS for the control interior. var controlText = document.createElement('div'); controlText.style.color = 'rgb(255, 255, 255)'; controlText.style.fontFamily = 'Roboto,Arial,sans-serif'; controlText.style.fontSize = '16px'; controlText.style.lineHeight = '38px'; controlText.style.paddingLeft = '5px'; controlText.style.paddingRight = '5px'; controlText.innerHTML = '<div class="demo-radio-button">'+ '<input name="rd_auto" id="chk_auto" class="filled-in" checked="checked" type="checkbox"><label style="min-width: 100px;font-size:12px" for="chk_auto">Automático</label><br>' + '<input name="rd_tipo_mapa" id="rd_pontos" class="with-gap radio-col-red" checked="checked" type="radio"><label style="min-width: 100px;" for="rd_pontos">PONTOS</label><br>' + '<input name="rd_tipo_mapa" id="rd_calor" class="with-gap radio-col-blue" type="radio"><label style="min-width: 100px;" for="rd_calor">CALOR</label>' + '</div>'; controlUI.appendChild(controlText); // Setup the click event listeners controlUI.addEventListener('click', function() { getData(); }); // altera entre pontos e calor automático setInterval(function(){ if($('#chk_auto').is(':checked')) { if($('#rd_pontos').is(':checked')) { $('#rd_pontos').prop('checked', false); $('#rd_calor').prop('checked', true); } else { $('#rd_calor').prop('checked', false); $('#rd_pontos').prop('checked', true); } getData(); } }, 30000); } function CenterLeftControl(controlDiv, data, secretaria) { var controlUI = document.createElement('div'); controlUI.style.backgroundColor = '#fff'; controlUI.style.border = '2px solid #fff'; controlUI.style.borderRadius = '10px 0px 0px 10px'; controlUI.style.boxShadow = '-1px 2px 4px rgba(0, 0, 0, 0.2)'; controlUI.style.cursor = 'pointer'; controlUI.style.margin = '0px'; controlUI.style.textAlign = 'left'; controlUI.title = 'Estatísticas'; controlDiv.appendChild(controlUI); // Set CSS for the control interior. var controlText = document.createElement('div'); controlText.style.color = 'rgb(0, 0, 0)'; controlText.style.fontFamily = 'Roboto,Arial, sans-serif'; controlText.style.fontSize = '12px'; // controlText.style.fontWeight = '500'; controlText.style.padding = '10px'; controlText.innerHTML = '<p style="font-weight:bold;font-size:12px">Números por Secretaria:</p>'; var total = 0; var style = ""; $.each(data, function(i, val) { total += parseInt(val.qtd); style = (secretaria == val.id) ? "color:blue;font-weight:bold" : ""; controlText.innerHTML += '<p><a style="'+style+'" class="secretaria" data-val="' + val.id + '">' + val.nome + ' (' + val.qtd + ')' + '</a></p>'; }); controlText.innerHTML += '<p style="margin-top:15px"><a class="total_secs">TOTAL: ' + total + '</a></p>'; controlUI.appendChild(controlText); } function TopRightControl2(controlDiv, map) { // Set CSS for the control border. var controlUI = document.createElement('div'); controlUI.style.backgroundColor = '#fff'; controlUI.style.border = '2px solid #fff'; controlUI.style.borderRadius = '3px'; controlUI.style.boxShadow = '-1px 2px 4px rgba(0, 0, 0, 0.2)'; controlUI.style.cursor = 'pointer'; controlUI.style.margin = '10px'; controlUI.style.textAlign = 'center'; controlUI.title = 'Exibir Raio'; controlDiv.appendChild(controlUI); // Set CSS for the control interior. var controlText = document.createElement('div'); controlText.style.color = 'rgb(0, 0, 0)'; controlText.style.fontFamily = 'Roboto,Arial,sans-serif'; controlText.style.fontSize = '11px'; controlText.style.fontWeight = '500'; controlText.style.padding = '6px'; controlText.innerHTML = 'Exibir raio'; controlUI.appendChild(controlText); // Setup the click event listeners controlUI.addEventListener('click', function() { if(!isvisible) isvisible = true; else isvisible = false; myCityDesenho.setVisible(isvisible); }); } function getData(){ var data = { 'status[]' : [], 'data_ini': $("#data_ini").val(), 'data_fim': $("#data_fim").val(), 'hora_inicial': $("#hora_inicial").val(), 'hora_final': $("#hora_final").val(), 'agrupamento': 'secretaria', 'secretaria': secretaria }; $(".chk_status").each(function() { if($(this).is(":checked")) data['status[]'].push($(this).val()); }); $.ajax({ type: "POST", data: data, url: '../index.php/mapa/getMarkers', dataType: "JSON", beforeSend: function(){ $("#page-content-wrapper").attr("class", "loading-overlay"); }, success: function(res){ // console.log(res); //limpa marcadores e calor clearHeatmap(); clearMarcadores(); //clearEstatisticas(); if($('#rd_calor').is(':checked')) montaCalor(res.ocorrencias); else montaPontos(res.ocorrencias); montaEstatistica(data); $("#page-content-wrapper").attr("class", ""); }, error: function(error){ $("#page-content-wrapper").attr("class", ""); console.log(error); } }); } function montaPontos(data){ myCity.setVisible(false); myCityDesenho.setVisible(false); var infowindow = new google.maps.InfoWindow(); var latLngBounds = myCity.getBounds(); //array para gerar pdf's dos pontos montados var pontos_no_raio= new Array(); for (var i = 0; i < data.length; i++){ raio = new google.maps.LatLng(data[i].latitude, data[i].longitude); if (latLngBounds.contains(raio)) { //console.log(data[i]); //adicionando markers marker2 = new google.maps.Marker({ position: new google.maps.LatLng(data[i].latitude, data[i].longitude), map: map, icon: "../images/pins/"+data[i].pin, id: data[i].id, title: data[i].problema, desc: data[i].descricao, foto: data[i].foto, data_ocorrencia: data[i].data_ocorrencia, hora_ocorrencia: data[i].hora_ocorrencia, protocolo: data[i].protocolo }); markers.push(marker2); google.maps.event.addListener(marker2, 'click', (function(marker2, i){ return function(){ //Coloca nome da cidade no conteudo da InfoWindow var hora_ocorrencia = ""; if(data[i].hora_ocorrencia != "" && data[i].hora_ocorrencia != null) hora_ocorrencia = " às " + data[i].hora_ocorrencia; // var anexo = ""; // if(data[i].anexo != "" && data[i].anexo != null) // anexo = data[i].anexo; var contentString = '<a href="../ocorrencia/ver/'+data[i].id+'" target="_blank" style="outline:none;">'+ '<div id="gmap-content">'+ '<div id="gmap-siteNotice">'+ '</div>'+ '<h3 id="gmap-firstHeading" class="gmap-firstHeading" style="margin-top:10px">'+data[i].problema+'</h3>'+ '<div id="gmap-bodyContent">'+ '<div class="col-sm-3 text-center" style="padding:0px 10px 0px 0px;">'+ '<img src="'+data[i].foto+'" style="max-width:100%;max-height:65px">'+ '</div>'+ '<div class="col-sm-9" style="padding:0px">'+ '<b>Endereço: </b>' + data[i].endereco+'<br>'+ '<b>Protocolo: </b> '+data[i].protocolo+'<br>'+ '<b>Observação: </b> '+data[i].descricao+'<br>'+ '<b>Ocorrido em: </b>'+ data[i].data_ocorrencia + hora_ocorrencia +'<br>'+ '</div>'+ '</div>'+ '</div>' '</a>'; infowindow.setContent(contentString); //seta o marcador certo a ser exibido infowindow.open(map, marker2); } })(marker2, i)); pontos_no_raio.push(data[i]); } } // style marker cluster var mcOptions = { gridSize: 1, maxZoom: 200, zoomOnClick: false, imagePath: '../images/m' }; //instance makerClusterer markerCluster = new MarkerClusterer(map, markers, mcOptions); google.maps.event.addListener(markerCluster, "clusterclick", function (cluster){ var contentString2 = '<div id="gmap-content">'+ '<div id="gmap-siteNotice">'+ '</div>'+ '<span style="font-size:13px;font-weight: 300;font-family: Roboto,Arial,sans-serif;">Ocorrências: </span>'+ '<div id="gmap-bodyContent">'+ '<p>'+ '<b>Quantidade de Ocorrências: </b> '+cluster.getSize()+'<br>'+ '<a data-toggle="modal" data-target="#modal_ocorr" style="font-size:12px;cursor:pointer;">Visualizar ocorrências</a><br>'+ '</p>'+ '</div>'+ '</div>'; // $('.modal-title').html(cluster.getMarkers()[0].getTitle()); $('.modal-title').html("Ocorrências neste ponto"); var qtd= cluster.getSize(); $('#table-ocorrencias').html(""); $('#table-ocorrencias').append('<tr style="font-weight:bold;">'+ '<th>Foto</th>'+ '<th>Problema</th>'+ '<th>Protocolo</th>'+ '<th>Observação</th>'+ '<th>Ocorrido em</th>'+ '</tr>'); for (var i = 0; i < qtd; i++){ $('#table-ocorrencias').append('<tr>'+ '<td><img src="'+cluster.getMarkers()[i].foto+'" style="max-width:100%;max-height:60px"></td>'+ '<td>'+ '<a href="../ocorrencia/ver/'+cluster.getMarkers()[i].id+'" target="_blank" style="color: #337ab7;">'+cluster.getMarkers()[i].title+'</a>'+ '</td>'+ '<td>'+cluster.getMarkers()[i].protocolo+'</td>'+ '<td>'+cluster.getMarkers()[i].desc+'</td>'+ '<td>'+cluster.getMarkers()[i].data_ocorrencia + " " + cluster.getMarkers()[i].hora_ocorrencia + '</td>'+ '</tr>' ); } infowindow.setContent(contentString2); infowindow.setPosition(cluster.getCenter()); infowindow.open(map); }); var pontos= JSON.stringify( pontos_no_raio ); // gerar o PDF // $("#table").html("<form method='POST' action='gerapdf.php'>"+ // "<input type='hidden' name='dados' value='"+pontos+"' />"+ // "<input type='hidden' name='raio_acao' value='"+$('#raio_atual').html()+"' />"+ // "<input type='hidden' name='ano' value='"+$('#ano').val()+"' />"+ // "<input type='submit' style='margin-bottom:20px;' class='btn btn-warning' id='raio_acao' value='Gerar PDF' />"+ // "</form>"); if(pontos_no_raio=="") $("#table").html(""); montaImagem(pontos); } function montaCalor(data){ myCity.setVisible(false); var latLngBounds = myCity.getBounds(); for (var i = 0; i < data.length; i++){ raio = new google.maps.LatLng(data[i].latitude, data[i].longitude); if (latLngBounds.contains(raio)) { heatmapData[i] = new google.maps.LatLng(data[i].latitude, data[i].longitude); } } heatmap = new google.maps.visualization.HeatmapLayer({ data: heatmapData, radius: 50 }); heatmap.setMap(map); } function montaEstatistica(data){ $.ajax({ type: "POST", data: data, url: '../index.php/mapa/getQtdByAgrupamento', dataType: "JSON", beforeSend: function(){ //$("#page-content-wrapper").attr("class", "loading-overlay"); }, success: function(res){ if(map.controls[google.maps.ControlPosition.RIGHT_CENTER].length >= 2) map.controls[google.maps.ControlPosition.RIGHT_CENTER].pop(); //ESTATISTICAS var centerLeftControlDiv = document.createElement('div'); var centerLeftControl = new CenterLeftControl(centerLeftControlDiv, res, data.secretaria); centerLeftControlDiv.index = 2; map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(centerLeftControlDiv); //$("#page-content-wrapper").attr("class", ""); }, error: function(error){ //$("#page-content-wrapper").attr("class", ""); console.log(error); } }); // var total = 0; // $.each(data, function(i, val) { // $("#table_ocorrencias_est").DataTable().row.add({ // "0" : "<img src='images/icones/" + val.icone + "'> " + val.nome + "</td>", // "1" : val.total // }).draw(); // total += val.total; // }); // //Fill modal informations // $(".span_total").html(total); // $(".span_raio").html(($("#raio").val()/1000) + " km"); // $(".span_de").html($("#data_ini").val()); // $(".span_ate").html($("#data_fim").val()); // $(".span_instituicao").html($("#instituicao option:selected").text()); } function error(msg) { var s = document.querySelector('#status'); s.innerHTML = typeof msg == 'string' ? msg : "falhou"; s.className = 'fail'; } function VerificaLoc(){ if (navigator.geolocation){ navigator.geolocation.getCurrentPosition(success, error); } else { error('Seu navegador não suporta <b style="color:black;background-color:#ffff66">Geolocalização</b>!'); } } //Tabela para mostrar os dados da cidade que foi clicada function GenerateTable(){ //adiciona os dados a um array para que seja colocado na tabela var dadosf = new Array(); dadosf.push(["Empresa", "Faixa", "Tecnologia", "Conexoes"]); var dadosbd = dadosf2.split("_"); var cont = 0; for (cont = 0; cont < dadosbd.length; cont++) { dadosf.push(dadosbd[cont].split(",")); } //cria a tabela var table = document.createElement("TABLE"); //recebe o botao para o pdf var botao = document.getElementById("btnpdf"); table.border = "1"; var columnCount = dadosf[0].length; var row = table.insertRow(-1); for (var i = 0; i < columnCount; i++) { var headerCell = document.createElement("TH"); headerCell.innerHTML = dadosf[0][i]; row.appendChild(headerCell); } //adiciona os dados as linhas for (var i = 1; i < dadosf.length - 1; i++) { row = table.insertRow(-1); for (var j = 0; j < columnCount; j++) { var cell = row.insertCell(-1); cell.innerHTML = dadosf[i][j]; } } var dvTable = document.getElementById("dvTable"); dvTable.innerHTML = ""; botao.style.visibility="visible"; //document.getElementById("btnpdf").style.visibility = "hidden"; dvTable.appendChild(table); var posiTable = $("#btnpdf"); var offset = posiTable.offset(); $(window).scrollTop(offset.top, offset.left); } //Marker diferente para diferenciar a onde pessoa esta/ou clicou function placeCustomerMarker(location){ //chama a fução para limpar o mapa e deixar sem marcadores clearMarcadores(); clearHeatmap(); if (customerMarker != null) { customerMarker.setPosition(location); }else{ //cor do marcador var pinColor = "008CD5"; //usando imagem de um icone //var image = 'images/marcador.png'; //busca o marcador ja pronto com a cor escolhida e setando seu tamanho var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor, new google.maps.Size( 21, 34)); customerMarker = new google.maps.Marker({ title: "Você está aqui!", position : location, map : map }); } latlngLate = location; //getLocationsLate(latlngLate.A,latlngLate.F); //Limpa o circulo para ser adicionado o novo raio $('#raio_atual').html($('#raio').val()); if($('#raio').val()==""){ $('#raio').val('10000'); $('#raio_atual').html('10000'); } myCity.setMap(null); myCity = new google.maps.Circle({ center: latlngLate, radius: parseInt($('#raio').val()), strokeColor: "#0000FF", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#0000FF", fillOpacity: 0.1, map: map }); myCity.setVisible(false); //MONTA PONTOS PARA DESENHO if(myCityDesenho) myCityDesenho.setMap(null); myCityDesenho = new google.maps.Circle({ center: myCity.getCenter(), radius: parseInt($('#raio').val()) + (parseInt($('#raio').val())/100)*25, strokeColor: "#0000FF", strokeOpacity: 0.8, strokeWeight: 2, fillColor: "#0000FF", fillOpacity: 0.1, map: map }); //chama função para montar os pontos ou mapa de calor de acordo com o local escolhido getData(); //montaPontos(); } function montaImagem(pontos){ var latlng; var markers=""; var tipo; $.each(JSON.parse(pontos), function(i, data){ //console.log(data); icon_tipo= "http://172.16.31.10:3470/guardapma/images/"+data.imagem; markers = markers.concat("markers=icon:"+icon_tipo+"|"+data.latitude+","+data.longitude+"&"); }); $(".gerar-imagem").attr("href", "https://maps.googleapis.com/maps/api/staticmap?"+ "center="+latlngLate+"&"+ "zoom=14&"+ "size=640x400&"+ "scale=1&"+ "maptype=roadmap&"+markers ); } //limpa os marcadores function clearMarcadores() { for (var i = 0; i < markers.length; i++ ) { markers[i].setMap(null); } markers.length = 0; markerCluster.clearMarkers(); } //limpa as variacoes de calor function clearHeatmap() { heatmapData = []; if(heatmap) heatmap.setMap(null); } function clearEstatisticas(){ $("#table_ocorrencias_est").DataTable().clear().draw(); } function gerapdf(){ window.open("gerapdf.php?id=" + $("#idpdf").val()); }
#!/usr/bin/env bash # shellcheck disable=SC2034 : F_BOLD="\033[1m" F_DIM="\033[2m" F_UNDERLINED="\033[4m" F_INVERTED="\033[7m" F_HIDDEN="\033[8m" F_RESET="\033[0m" C_DEFAULT="\033[39m" C_BLACK="\033[30m" C_RED="\033[31m" C_GREEN="\033[32m" C_YELLOW="\033[33m" C_BLUE="\033[34m" C_MAGENTA="\033[35m" C_CYAN="\033[36m" C_LIGHT_GRAY="\033[37m" C_DARK_GRAY="\033[90m" C_LIGHT_RED="\033[91m" C_LIGHT_GREEN="\033[92m" C_LIGHT_YELLOW="\033[93m" C_LIGHT_BLUE="\033[94m" C_LIGHT_MAGENTA="\033[95m" C_LIGHT_CYAN="\033[96m" C_WHITE="\033[97m" C_BG_DEFAULT="\033[49m" C_BG_BLACK="\033[40m" C_BG_RED="\033[41m" C_BG_GREEN="\033[42m" C_BG_YELLOW="\033[43m" C_BG_BLUE="\033[44m" C_BG_MAGENTA="\033[45m" C_BG_CYAN="\033[46m" C_BG_LIGHT_GRAY="\033[47m" C_BG_DARK_GRAY="\033[100m" C_BG_LIGHT_RED="\033[101m" C_BG_LIGHT_GREEN="\033[102m" C_BG_LIGHT_YELLOW="\033[103m" C_BG_LIGHT_BLUE="\033[104m" C_BG_LIGHT_MAGENTA="\033[105m" C_BG_LIGHT_CYAN="\033[106m" C_BG_WHITE="\033[107m"
<gh_stars>0 import * as React from 'react'; import Link from 'next/link'; import dynamic from 'next/dynamic'; import { format } from 'date-fns'; import styled from 'styled-components'; import _ from 'lodash/fp'; import Section from '../Section'; import Markdown from '../Markdown'; import { getConfig } from '../../utils'; const Comment = dynamic(() => import('../Comment')); interface IAboutProps { data: IGithubIssue; } const { theme } = getConfig(); const Title = styled.h2` display: inline-block; margin-top: 0; margin-bottom: 15px; color: ${theme.color}; `; const About: React.SFC<IAboutProps> = (props) => { const { data } = props; const { number: issueNumber, title, body } = data; return ( <Section> <header> <Title>{title}</Title> </header> <Markdown source={body} /> <footer> <Comment issueNumber={issueNumber} /> </footer> </Section> ); }; export default About;
<gh_stars>1-10 <?hh // strict namespace Waffle\Container\Exception; use type Waffle\Contract\Container\NotFoundExceptionInterface; use type InvalidArgumentException; class NotFoundException extends InvalidArgumentException implements NotFoundExceptionInterface { }
import {MigrationInterface, QueryRunner} from "typeorm"; export class init1610641043084 implements MigrationInterface { name = 'init1610641043084' public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`CREATE TABLE "Tarjeta" ("Id" SERIAL NOT NULL, "Numero" character varying NOT NULL, "Pin" character varying NOT NULL, "Bloqueado" boolean NOT NULL DEFAULT false, "Intentos" integer NOT NULL DEFAULT '0', CONSTRAINT "PK_10002a11dbe3025766b18ee5739" PRIMARY KEY ("Id"))`); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`DROP TABLE "Tarjeta"`); } }
# generic math routines for graphics LDLIBS="-lm" define_header() { local name_=$1 local source_="\$(SOURCE)/$MODULE_DIR/$2" shift 2 new_target "\$(TARGET)/src/$MODULE/$name_" "$source_" CC -E -C "$@" "$source_" '>$@' } define_generic() { local name_=$1 local source_=$2 shift 2 define_object $name_.o gen/$source_.g.c "$@" $GENERIC_FLAGS define_header $name_.h gen/$source_.g.h "$@" $GENERIC_FLAGS } joined_header() { name_=$1 HEADERS="$HEADERS gm/$name_.h" shift 1 pathed_sources=$(printf " \$(TARGET)/src/$MODULE/%s" "$@") suffixed_sources=$( IFS=: for S in $TYPE_SUFFIXES; do unset IFS printf " %s$S.h" $pathed_sources done ) new_target "\$(TARGET)/include/gm/$name_.h" $suffixed_sources SH \ "sed -n '/begin gm header/,/end gm header/p' $suffixed_sources | " \ "sed '/gm header/d' | " \ "cat \$(SOURCE)/src/$MODULE/${name_}_prefix.h" \ " - \$(SOURCE)/src/$MODULE/${name_}_suffix.h | " \ "uniq " \ '>$@' } # Specialize math functions for the following types # ctype:suffix:literal:macro symbol:printf format:scanf format exec 3<<'TYPES' float:f:f:FLT:: double:::DBL::\"l\" long double:l:l:LDBL:\"L\":\"L\" TYPES while IFS=: read -r CTYPE S LITERAL MACRO PRINTF_FORMAT SCANF_FORMAT <&3 do GENERIC_FLAGS="\ -D T=\"$CTYPE\" \ -D S=\"$S\" \ -D F=\"$LITERAL\" \ -D FPFX=\"$MACRO\" \ -D PRINTF_FORMAT=\"$PRINTF_FORMAT\" \ -D SCANF_FORMAT=\"$SCANF_FORMAT\" \ " TYPE_SUFFIXES="$TYPE_SUFFIXES${TYPE_SUFFIXES:+:}$S" define_generic vector2$S vector -DL=2 define_generic vector3$S vector -DL=3 define_generic vector3x$S vector3x -DL=3 define_generic quaternion$S vector -DL=4 -D VECTOR_TAG=q define_generic quaternionx$S quaternionx -DL=4 -D VECTOR_TAG=q define_generic matrix22$S matrix -D'M=2' -D'N=2' define_generic matrix22x$S matrix22x -D'M=2' -D'N=2' define_generic matrix33$S matrix -D'M=3' -D'N=3' define_generic matrix33x$S matrix33x -D'M=3' -D'N=3' define_generic matrix44$S matrix -D'M=4' -D'N=4' define_generic matrix44x$S matrix44x -D'M=4' -D'N=4' define_generic misc$S misc define_generic array$S array define_generic plane$S plane define_ok_test matrix22$S test-gen/matrix.g.c -D'M=2' -D'N=2' $GENERIC_FLAGS define_ok_test matrix22x$S test-gen/matrix22x.g.c -D'M=2' -D'N=2' $GENERIC_FLAGS define_ok_test matrix44$S test-gen/matrix.g.c -D'M=4' -D'N=4' $GENERIC_FLAGS define_ok_test matrix44x$S test-gen/matrix44x.g.c -D'M=4' -D'N=4' $GENERIC_FLAGS done joined_header matrix matrix22 matrix22x matrix33 matrix33x matrix44 matrix44x joined_header vector vector2 vector3 vector3x joined_header quaternion quaternion quaternionx joined_header misc misc joined_header array array joined_header plane plane
import abc from typing import Optional import attr import six from ddtrace import Span from ddtrace.internal.logger import get_logger log = get_logger(__name__) @attr.s class SpanProcessor(six.with_metaclass(abc.ABCMeta)): """A Processor is used to process spans as they are created and finished by a tracer.""" def __attrs_post_init__(self): # type: () -> None """Default post initializer which logs the representation of the Processor at the ``logging.DEBUG`` level. The representation can be modified with the ``repr`` argument to the attrs attribute:: @attr.s class MyProcessor(Processor): field_to_include = attr.ib(repr=True) field_to_exclude = attr.ib(repr=False) """ log.debug("initialized processor %r", self) @abc.abstractmethod def on_span_start(self, span): # type: (Span) -> None """Called when a span is started. This method is useful for making upfront decisions on spans. For example, a sampling decision can be made when the span is created based on its resource name. """ pass @abc.abstractmethod def on_span_finish(self, span): # type: (Span) -> None """Called with the result of any previous processors or initially with the finishing span when a span finishes. It can return any data which will be passed to any processors that are applied afterwards. """ pass def shutdown(self, timeout): # type: (Optional[float]) -> None """Called when the processor is done being used. Any clean-up or flushing should be performed with this method. """ pass
package ch7_11.ex2; public class ex7112 { // TODO }
#!/bin/bash bin=`dirname "$0"` bin=`cd "$bin"; pwd` DIR=`cd $bin/../; pwd` . "${DIR}/../bin/config.sh" . "${DIR}/bin/config.sh" echo "========== running ${APP} bench ==========" # pre-running SIZE=`${DU} -s ${INPUT_HDFS} | awk '{ print $1 }'` JAR="${DIR}/target/PCAApp-1.0.jar" CLASS="PCA.src.main.scala.PCAApp" OPTION=" ${INOUT_SCHEME}${INPUT_HDFS} ${DIMENSIONS}" setup for((i=0;i<${NUM_TRIALS};i++)); do purge_data "${MC_LIST}" START_TS=`get_start_ts`; START_TIME=`timestamp` echo "${SPARK_HOME}/bin/spark-submit --class $CLASS --master ${APP_MASTER} ${YARN_OPT} ${SPARK_OPT} ${SPARK_RUN_OPT} $JAR ${OPTION} 2>&1|tee ${BENCH_NUM}/${APP}_run_${START_TS}.dat" exec ${SPARK_HOME}/bin/spark-submit --class $CLASS --master ${APP_MASTER} ${YARN_OPT} ${SPARK_OPT} ${SPARK_RUN_OPT} $JAR ${OPTION} 2>&1|tee ${BENCH_NUM}/${APP}_run_${START_TS}.dat res=$?; END_TIME=`timestamp` get_config_fields >> ${BENCH_REPORT} print_config ${APP} ${START_TIME} ${END_TIME} ${SIZE} ${START_TS} ${res}>> ${BENCH_REPORT}; done teardown exit 0
<filename>spec/spec_helper.rb # frozen_string_literal: true require "rspec" require "capybara/rspec" require "middleman-core" require "middleman-core/rack" require "middleman-autoprefixer" require "middleman-livereload" require "middleman-inliner" require "middleman-deploy" middleman_app = ::Middleman::Application.new { set :root, File.expand_path(File.join(File.dirname(__FILE__), "..")) set :environment, :development set :show_exceptions, false } Capybara.app = ::Middleman::Rack.new(middleman_app).to_app
<reponame>timloh-professional/polkabridge-launchpad export default { chainId: 1, chainIdTestnet: 42, bscChain: 56, bscChainTestent: 97, bscRpcTestnet: 'https://data-seed-prebsc-1-s1.binance.org:8545/', bscRpcMainnet: 'https://bsc-dataseed.binance.org/', hmy_rpc_mainnet: 'https://api.harmony.one', hmy_rpc_testnet: 'https://api.s0.b.hmny.io', hmyChainTestnet: 1666700000, hmyChainMainnet: 1666600000, polygon_rpc_mainnet: 'https://polygon-mainnet.infura.io/v3/${process.env.REACT_APP_INFURA_KEY}', // matic mainnet rpc infura polygon_rpc_testnet: 'https://mumbai-explorer.matic.today', // matic testnet rpc polygon_chain_mainnet: 137, polygon_chain_testnet: 80001, // bscChain: 97, api: 'http://localhost:8020', coingecko: 'https://api.coingecko.com/api', moonriverChain: 1285, moonriverRpc: 'https://rpc.api.moonriver.moonbeam.network', moonriverChainTestent: 1287, moonriverRpcTestnet: 'https://rpc.api.moonbase.moonbeam.network', ankrEthereumRpc: 'https://rpc.ankr.com/eth', ankrBscRpc: 'https://rpc.ankr.com/bsc', ankrPolygonRpc: 'https://rpc.ankr.com/polygon', ankrHmyRpc: '', ankrMoonriverRpc: '', }
import com.cootf.wechat.bean.BaseResult; import com.cootf.wechat.bean.scan.crud.ProductCreate; public class ProductGetResult extends BaseResult { private ProductCreate productCreate; // Constructor to initialize ProductGetResult with productCreate object public ProductGetResult(ProductCreate productCreate) { this.productCreate = productCreate; } // Method to display product details public void displayProductDetails() { System.out.println("Product Details:"); System.out.println("Product ID: " + productCreate.getProductId()); System.out.println("Product Name: " + productCreate.getProductName()); System.out.println("Price: " + productCreate.getPrice()); } }
#!/usr/bin/env bash # Copyright Materialize, Inc. All rights reserved. # # Use of this software is governed by the Business Source License # included in the LICENSE file at the root of this repository. # # As of the Change Date specified in that file, in accordance with # the Business Source License, use of this software will be governed # by the Apache License, Version 2.0. # # doc — renders API documentation. set -euo pipefail crate=$(basename $(pwd)) # Create a nice homepage for the docs. It's awful that we have to copy the # HTML template like this, but the upstream issue [0] that would resolve this is # now five years old and doesn't look close to resolution. # [0]: https://github.com/rust-lang/cargo/issues/739 cat > target/doc/index.html <<EOF <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>$crate</title> <link rel="stylesheet" type="text/css" href="normalize.css"> <link rel="stylesheet" type="text/css" href="rustdoc.css" id="mainThemeStyle"> <link rel="stylesheet" type="text/css" href="dark.css"> <link rel="stylesheet" type="text/css" href="light.css" id="themeStyle"> <script src="storage.js"></script> <noscript> <link rel="stylesheet" href="noscript.css"> </noscript> <link rel="shortcut icon" href="favicon.ico"> <style type="text/css"> #crate-search { background-image: url("down-arrow.svg"); } </style> </head> <body class="rustdoc mod"> <!--[if lte IE 8]><div class="warning">This old browser is unsupported and will most likely display funky things.</div><![endif]--> <nav class="sidebar"> <div class="sidebar-menu">&#9776;</div> <a href='index.html'><div class='logo-container'><img src='rust-logo.png' alt='logo'></div></a> <p class='location'>Home</p> <div class="sidebar-elems"> </div> </nav> <div class="theme-picker"> <button id="theme-picker" aria-label="Pick another theme!"><img src="brush.svg" width="18" alt="Pick another theme!"></button> <div id="theme-choices"></div> </div> <script src="theme.js"></script> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <div> <select id="crate-search"> <option value="All crates">All crates</option> </select> <input class="search-input" name="search" autocomplete="off" spellcheck="false" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> <a id="settings-menu" href="settings.html"><img src="wheel.svg" width="18" alt="Change settings"></a> </div> </form> </nav> <section id="main" class="content"> <h1 class='fqn'> <span class='in-band'>$crate documentation</span> </h1> <p>This is the home of $crate's internal API documentation.</p> </section> <section id="search" class="content hidden"></section> <section class="footer"></section> <script> window.rootPath = "./"; window.currentCrate = "$crate"; </script> <script src="aliases.js"></script> <script src="main.js"></script> <script defer src="search-index.js"></script> </body> </html> EOF # Make the logo link to the nice homepage we just created. Otherwise it just # links to the root of whatever crate you happen to be looking at. cat >> target/doc/main.js <<EOF ; var el = document.querySelector("img[alt=logo]").closest("a"); if (el.href != "index.html") { el.href = "../index.html"; } EOF
<filename>indexes/dba_missingIndexStoredProc_sp.sql Use dbaTools; Go /* Create a stored procedure skeleton */ If ObjectProperty(Object_ID('dbo.dba_missingIndexStoredProc_sp'), N'IsProcedure') Is Null Begin Execute ('Create Procedure dbo.dba_missingIndexStoredProc_sp As Print ''Hello World!''') RaisError('Procedure dba_missingIndexStoredProc_sp created.', 10, 1); End; Go /* Drop our table if it already exists */ If Exists(Select Object_ID From sys.tables Where [name] = N'dba_missingIndexStoredProc') Begin Drop Table dbo.dba_missingIndexStoredProc Print 'dba_missingIndexStoredProc table dropped!'; End /* Create our table */ Create Table dbo.dba_missingIndexStoredProc ( missingIndexSP_id int Identity(1,1) Not Null , databaseName varchar(128) Not Null , databaseID int Not Null , objectName varchar(128) Not Null , objectID int Not Null , query_plan xml Not Null , executionDate smalldatetime Not Null , statementExecutions int Not Null Constraint PK_missingIndexStoredProc Primary Key Clustered(missingIndexSP_id) ); Print 'dba_missingIndexStoredProc Table Created'; /* Configure our settings */ Set ANSI_Nulls On; Set Quoted_Identifier On; Go Alter Procedure dbo.dba_missingIndexStoredProc_sp /* Declare Parameters */ @lastExecuted_inDays int = 7 , @minExecutionCount int = 1 , @logResults bit = 1 , @displayResults bit = 0 As /********************************************************************************************************** NAME: dba_missingIndexStoredProc_sp SYNOPSIS: Retrieves stored procedures with missing indexes in their cached query plans. @lastExecuted_inDays = number of days old the cached query plan can be to still appear in the results; the HIGHER the number, the longer the execution time. @minExecutionCount = minimum number of executions the cached query plan can have to still appear in the results; the LOWER the number, the longer the execution time. @logResults = store results in dba_missingIndexStoredProc @displayResults = return results to the caller DEPENDENCIES: The following dependencies are required to execute this script: - SQL Server 2005 or newer NOTES: This is not 100% guaranteed to catch all missing indexes in a stored procedure. It will only catch it if the stored proc's query plan is still in cache. Run regularly to help minimize the chance of missing a proc. AUTHOR: <NAME>, http://sqlfool.com CREATED: 2009-09-03 VERSION: 1.0 LICENSE: Apache License v2 USAGE: Exec dbo.dba_missingIndexStoredProc_sp @lastExecuted_inDays = 30 , @minExecutionCount = 5 , @logResults = 1 , @displayResults = 1; ---------------------------------------------------------------------------- DISCLAIMER: This code and information are provided "AS IS" without warranty of any kind, either expressed or implied, including but not limited to the implied warranties or merchantability and/or fitness for a particular purpose. ---------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------- -- DATE VERSION AUTHOR DESCRIPTION -- --------------------------------------------------------------------------------------------------------- 20150619 1.0 Michelle Ufford Open Sourced on GitHub **********************************************************************************************************/ Set NoCount On; Set XACT_Abort On; Set Ansi_Padding On; Set Ansi_Warnings On; Set ArithAbort On; Set Concat_Null_Yields_Null On; Set Numeric_RoundAbort Off; Begin /* Declare Variables */ Declare @currentDateTime smalldatetime; Set @currentDateTime = GetDate(); Declare @plan_handles Table ( plan_handle varbinary(64) Not Null , statementExecutions int Not Null ); Create Table #missingIndexes ( databaseID int Not Null , objectID int Not Null , query_plan xml Not Null , statementExecutions int Not Null ); Create Clustered Index CIX_temp_missingIndexes On #missingIndexes(databaseID, objectID); Begin Try /* Perform some data validation */ If @logResults = 0 And @displayResults = 0 Begin /* Log the fact that there were open transactions */ Execute dbo.dba_logError_sp @errorType = 'app' , @app_errorProcedure = 'dba_missingIndexStoredProc_sp' , @app_errorMessage = '@logResults = 0 and @displayResults = 0; no action taken, exiting stored proc.' , @forceExit = 1 , @returnError = 1; End; Begin Transaction; /* Retrieve distinct plan handles to minimize dm_exec_query_plan lookups */ Insert Into @plan_handles Select plan_handle, Sum(execution_count) As 'executions' From sys.dm_exec_query_stats Where last_execution_time > DateAdd(day, -@lastExecuted_inDays, @currentDateTime) Group By plan_handle Having Sum(execution_count) > @minExecutionCount; With xmlNameSpaces ( Default 'http://schemas.microsoft.com/sqlserver/2004/07/showplan' ) /* Retrieve our query plan's XML if there's a missing index */ Insert Into #missingIndexes Select deqp.[dbid] , deqp.objectid , deqp.query_plan , ph.statementExecutions From @plan_handles As ph Cross Apply sys.dm_exec_query_plan(ph.plan_handle) As deqp Where deqp.query_plan.exist('//MissingIndex/@Database') = 1 And deqp.objectid Is Not Null; /* Do we want to store the results of our process? */ If @logResults = 1 Begin Insert Into dbo.dba_missingIndexStoredProc Execute sp_msForEachDB 'Use ?; Select ''?'' , mi.databaseID , Object_Name(o.object_id) , o.object_id , mi.query_plan , GetDate() , mi.statementExecutions From sys.objects As o Join #missingIndexes As mi On o.object_id = mi.objectID Where databaseID = DB_ID();'; End /* We're not logging it, so let's display it */ Else Begin Execute sp_msForEachDB 'Use ?; Select ''?'' , mi.databaseID , Object_Name(o.object_id) , o.object_id , mi.query_plan , GetDate() , mi.statementExecutions From sys.objects As o Join #missingIndexes As mi On o.object_id = mi.objectID Where databaseID = DB_ID();'; End; /* See above; this part will only work if we've logged our data. */ If @displayResults = 1 And @logResults = 1 Begin Select * From dbo.dba_missingIndexStoredProc Where executionDate >= @currentDateTime; End; /* If you have an open transaction, commit it */ If @@TranCount > 0 Commit Transaction; End Try Begin Catch /* Whoops, there was an error... rollback! */ If @@TranCount > 0 Rollback Transaction; /* Return an error message and log it */ Execute dbo.dba_logError_sp; End Catch; /* Clean-Up! */ Drop Table #missingIndexes; Set NoCount Off; Return 0; End Go Set Quoted_Identifier Off; Go
<reponame>smagill/opensphere-desktop package io.opensphere.mantle.mp.impl; import java.awt.Color; import java.awt.Font; import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; import io.opensphere.core.model.time.TimeSpan; import io.opensphere.core.util.Colors; import io.opensphere.mantle.mp.MapAnnotationPoint; import io.opensphere.mantle.mp.MapAnnotationPointChangeEvent; import io.opensphere.mantle.mp.MutableMapAnnotationPoint; import io.opensphere.mantle.mp.MutableMapAnnotationPointGroup; import io.opensphere.mantle.mp.MutableMapAnnotationPointSettings; import io.opensphere.mantle.mp.event.impl.MapAnnotationPointMemberChangedEvent; /** * The Class DefaultMapAnnotationPoint. */ @SuppressWarnings("PMD.GodClass") public class DefaultMapAnnotationPoint implements MutableMapAnnotationPoint { /** The default color. */ public static final Color DEFAULT_COLOR = new Color(Colors.LF_PRIMARY2.getRed(), Colors.LF_PRIMARY2.getGreen(), Colors.LF_PRIMARY2.getBlue(), 190); /** The our id counter. */ private static AtomicLong ourIdCounter = new AtomicLong(1000); /** The altitude of the point. */ private double myAltitude; /** The annotation settings. */ private final DefaultMapAnnotationPointSettings myAnnoSettings; /** The Associated view name. */ private String myAssociatedViewName; /** The background color. */ private Color myBackgroundColor = DEFAULT_COLOR; /** The color. */ private Color myColor = DEFAULT_COLOR; /** The description. */ private String myDescription = ""; /** Whether the bubble is filled. */ private boolean myFilled = true; /** The font color. */ private Font myFont; /** The font color. */ private Color myFontColor = Color.white; /** The font position. */ private String myFontSize = ""; /** The group. */ private MutableMapAnnotationPointGroup myGroup; /** * True if this point has altitude, false if it should be clamped to ground. */ private boolean myHasAltitude; /** The Id. */ private final long myId; /** The latitude. */ private double myLat; /** The longitude. */ private double myLon; /** The MGRS coords. */ private String myMGRS = ""; /** * The time of the point or null if no time. */ private TimeSpan myTime; /** * True if this point has a time component, false if it is timeless. */ private boolean myTimeEnabled; /** The title. */ private String myTitle = ""; /** The visible. */ private boolean myVisible; /** * The x coordinate offset of the call out for the map point with respect to * the anchor position. */ private int myXOffset; /** * The y coordinate offset of the call out for the map point with respect to * the anchor position. */ private int myYOffset; /** * Gets the next my places ID. * * @return the next ID */ public static final long getNextId() { return ourIdCounter.incrementAndGet(); } /** * Constructor. */ public DefaultMapAnnotationPoint() { myId = getNextId(); myAnnoSettings = new DefaultMapAnnotationPointSettings(); myAnnoSettings.setMapAnnotationPoint(this); } /** * COPY CTOR. * * @param other the other to copy. */ public DefaultMapAnnotationPoint(MapAnnotationPoint other) { myId = getNextId(); myAnnoSettings = new DefaultMapAnnotationPointSettings(other.getAnnoSettings()); myAnnoSettings.setMapAnnotationPoint(this); myColor = other.getColor(); myFilled = other.isFilled(); myFont = other.getFont(); myFontColor = other.getFontColor(); myDescription = other.getDescription(); myFontSize = other.getFontSize(); myBackgroundColor = other.getBackgroundColor(); myLat = other.getLat(); myLon = other.getLon(); myAltitude = other.getAltitude(); myMGRS = other.getMGRS(); myTitle = other.getTitle() == null ? "" : other.getTitle(); myAssociatedViewName = other.getAssociatedViewName() == null ? "" : other.getAssociatedViewName(); myVisible = other.isVisible(); myXOffset = other.getxOffset(); myYOffset = other.getyOffset(); } @Override public void fireChangeEvent(MapAnnotationPointChangeEvent e) { if (myGroup != null) { myGroup.fireGroupInfoChangeEvent(new MapAnnotationPointMemberChangedEvent(myGroup, this, e, e.getSource())); } } /** * {@inheritDoc} * * @see io.opensphere.mantle.mp.MapAnnotationPoint#getAltitude() */ @Override public double getAltitude() { return myAltitude; } @Override public MutableMapAnnotationPointSettings getAnnoSettings() { return myAnnoSettings; } @Override public String getAssociatedViewName() { return myAssociatedViewName; } @Override public Color getBackgroundColor() { return myBackgroundColor; } @Override public Color getColor() { return myColor; } @Override public String getDescription() { return myDescription; } @Override public Font getFont() { if (myFont == null) { try { float size = Float.parseFloat(myFontSize); myFont = DEFAULT_FONT.deriveFont(size); } catch (NumberFormatException e) { myFont = DEFAULT_FONT; } } return myFont; } @Override public Color getFontColor() { return myFontColor; } @Override public String getFontSize() { return myFontSize; } @Override public MutableMapAnnotationPointGroup getGroup() { return myGroup; } @Override public long getId() { return myId; } @Override public double getLat() { return myLat; } @Override public double getLon() { return myLon; } @Override public String getMGRS() { return myMGRS; } @Override public TimeSpan getTime() { return myTime; } @Override public String getTitle() { return myTitle; } @Override public int getxOffset() { return myXOffset; } @Override public int getyOffset() { return myYOffset; } @Override public boolean hasAltitude() { return myHasAltitude; } @Override public boolean isFilled() { return myFilled; } @Override public boolean isVisible() { return myVisible; } @Override public boolean isTimeEnabled() { return myTimeEnabled; } /** * {@inheritDoc} * * @see io.opensphere.mantle.mp.MutableMapAnnotationPoint#setAltitude(double, * java.lang.Object) */ @Override public void setAltitude(double pAltitude, Object pEventSource) { if (myAltitude != pAltitude) { myHasAltitude = true; myAltitude = pAltitude; fireChangeEvent(new MapAnnotationPointChangeEvent(this, Double.valueOf(myAltitude), pEventSource)); } } @Override public void setAssociatedViewName(String pName, Object source) { String name = pName == null ? "" : pName; if (!Objects.equals(myAssociatedViewName, name)) { myAssociatedViewName = name; fireChangeEvent(new MapAnnotationPointChangeEvent(this, myAssociatedViewName, source)); } } @Override public void setBackgroundColor(Color color, Object source) { if (!Objects.equals(myBackgroundColor, color)) { myBackgroundColor = color; fireChangeEvent(new MapAnnotationPointChangeEvent(this, myBackgroundColor, source)); } } @Override public void setColor(Color shapeColor, Object source) { if (!Objects.equals(myColor, shapeColor)) { myColor = shapeColor; fireChangeEvent(new MapAnnotationPointChangeEvent(this, shapeColor, source)); } } @Override public void setDescription(String desc, Object source) { if (!Objects.equals(myDescription, desc)) { myDescription = desc; fireChangeEvent(new MapAnnotationPointChangeEvent(this, myDescription, source)); } } @Override public void setEqualTo(MapAnnotationPoint other, Object source) { if (!equals(other)) { myAnnoSettings.setEqualTo(other.getAnnoSettings(), source, false); myAnnoSettings.setMapAnnotationPoint(this); myColor = other.getColor(); myFilled = other.isFilled(); myFont = other.getFont(); myFontColor = other.getFontColor(); myDescription = other.getDescription(); myFontSize = other.getFontSize(); myBackgroundColor = other.getBackgroundColor(); myLat = other.getLat(); myLon = other.getLon(); myAltitude = other.getAltitude(); myMGRS = other.getMGRS(); myTitle = other.getTitle() == null ? "" : other.getTitle(); myAssociatedViewName = other.getAssociatedViewName() == null ? "" : other.getAssociatedViewName(); myVisible = other.isVisible(); myXOffset = other.getxOffset(); myYOffset = other.getyOffset(); fireChangeEvent(new MapAnnotationPointChangeEvent(this, this, source)); } } @Override public void setFilled(boolean filled, Object source) { if (myFilled != filled) { myFilled = filled; fireChangeEvent(new MapAnnotationPointChangeEvent(this, Boolean.valueOf(myFilled), source)); } } @Override public void setFont(Font font, Object source) { if (!Objects.equals(myFont, font)) { myFont = font; fireChangeEvent(new MapAnnotationPointChangeEvent(this, font, source)); } } @Override public void setFontColor(Color color, Object source) { if (!Objects.equals(myFontColor, color)) { myFontColor = color; fireChangeEvent(new MapAnnotationPointChangeEvent(this, myFontColor, source)); } } @Override public void setFontSize(String fontSize, Object source) { if (!Objects.equals(myFontSize, fontSize)) { myFontSize = fontSize; fireChangeEvent(new MapAnnotationPointChangeEvent(this, fontSize, source)); } } @Override public void setGroup(MutableMapAnnotationPointGroup group) { myGroup = group; } @Override public void setLat(double lat, Object source) { if (myLat != lat) { myLat = lat; fireChangeEvent(new MapAnnotationPointChangeEvent(this, Double.valueOf(myLat), source)); } } /** * {@inheritDoc} * * @see io.opensphere.mantle.mp.MutableMapAnnotationPoint#setLon(double, * java.lang.Object) */ @Override public void setLon(double lon, Object source) { if (myLon != lon) { myLon = lon; fireChangeEvent(new MapAnnotationPointChangeEvent(this, Double.valueOf(myLon), source)); } } @Override public void setMGRS(String mgrs, Object source) { if (!Objects.equals(myMGRS, mgrs)) { myMGRS = mgrs; fireChangeEvent(new MapAnnotationPointChangeEvent(this, myMGRS, source)); } } /** * Sets the time for the point. * * @param time The time for the point or null if there isn't one. */ public void setTime(TimeSpan time) { myTime = time; } /** * {@inheritDoc} * * @see io.opensphere.mantle.mp.MutableMapAnnotationPoint#setTimeEnabled(boolean, * Object) */ @Override public void setTimeEnabled(boolean timeEnabled, Object source) { if (timeEnabled != myTimeEnabled) { myTimeEnabled = timeEnabled; fireChangeEvent(new MapAnnotationPointChangeEvent(this, Boolean.valueOf(myTimeEnabled), source)); } } @Override public void setTitle(String pTitle, Object source) { String title = pTitle == null ? "" : pTitle; if (!Objects.equals(myTitle, title)) { myTitle = title; fireChangeEvent(new MapAnnotationPointChangeEvent(this, myTitle, source)); } } @Override public void setVisible(boolean visible, Object source) { if (myVisible != visible) { myVisible = visible; fireChangeEvent(new MapAnnotationPointChangeEvent(this, Boolean.valueOf(myVisible), source)); } } @Override public void setxOffset(int xOffset, Object source) { if (myXOffset != xOffset) { myXOffset = xOffset; fireChangeEvent(new MapAnnotationPointChangeEvent(this, Integer.valueOf(xOffset), source)); } } @Override public void setXYOffset(int xOffset, int yOffset, Object source) { boolean changed = false; if (myXOffset != xOffset) { myXOffset = xOffset; changed = true; } if (myYOffset != yOffset) { myYOffset = yOffset; changed = true; } if (changed) { fireChangeEvent(new MapAnnotationPointChangeEvent(this, Integer.valueOf(xOffset), source)); } } @Override public void setyOffset(int yOffset, Object source) { if (myYOffset != yOffset) { myYOffset = yOffset; fireChangeEvent(new MapAnnotationPointChangeEvent(this, Integer.valueOf(myYOffset), source)); } } @Override public String toString() { StringBuilder sb = new StringBuilder(64); sb.append("MAPPOINT{TITLE[").append(getTitle()).append("], DESC["); sb.append(getDescription()).append("], LAT["); sb.append(getLat()).append("], LON["); sb.append(getLon()).append("]}"); return sb.toString(); } }
<reponame>h920526/jaBenDon package test.base; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.ContextConfiguration; import org.springframework.web.client.RestTemplate; @ContextConfiguration("/spring-test.xml") public abstract class BaseRestService { @Autowired public RestTemplate restTemplate; @Value("${rest.baseurl}") public String baseUrl; }
#!/bin/bash /wait/wait-for-it.sh database:3306 catalina.sh run
def is_collinear(point1, point2, point3): # calculate slopes slope_1 = (point2[1] - point1[1])/(point2[0] - point1[0]) slope_2 = (point3[1] - point2[1])/(point3[0] - point2[0]) # compare slopes if slope_1 == slope_2: return True else: return False
export default { DEFINE_IMAGE_SIZE_PRESETS: 'DEFINE_IMAGE_SIZE_PRESETS', INIT_FORM_SCHEMA_STACK: 'INIT_FORM_SCHEMA_STACK', POP_FORM_SCHEMA: 'POP_FORM_SCHEMA', PUSH_FORM_SCHEMA: 'PUSH_FORM_SCHEMA', RESET: 'RESET', RESET_FORM_STACK: 'RESET_FORM_STACK' };
#!/bin/bash -e #bdereims@vmware.com backup_file() { cp ${1} ${1}-bkp } # Backup files backup_file /etc/dnsmasq.conf backup_file /etc/nginx/html/index.html # Upgrade tdnf -y update # Delete tricky file rm /etc/systemd/network/99-dhcp-en.network
<gh_stars>0 package com.coltsoftware.liquidsledgehammer.json.streamsource; import org.junit.Test; import com.coltsoftware.liquidsledgehammer.json.JsonException; import com.coltsoftware.liquidsledgehammer.json.JsonStreamTransactionSource; import com.coltsoftware.liquidsledgehammer.model.NullFinancialTransactionSourceInformation; public final class RequiresDateTests extends StreamSourceTestBase { @Override protected String getAssetName() { return "datelessStatement.json"; } @Test(expected = JsonException.class) public void must_have_dates() { JsonStreamTransactionSource.fromStream(stream, NullFinancialTransactionSourceInformation.INSTANCE); } }
#include "LSM303.h" void check_overflow(int * buffer, char * byte_arr) { buffer[0] = ((byte_arr[1] << 8) | byte_arr[0]); if(buffer[0] > 32767) buffer[0] -= 65536; buffer[1] = ((byte_arr[3] << 8) | byte_arr[2]); if(buffer[1] > 32767) buffer[1] -= 65536; buffer[2] = ((byte_arr[5] << 8) | byte_arr[4]); if(buffer[2] > 32767) buffer[2] -= 65536; buffer[0] = buffer[0] >> 4; buffer[1] = buffer[1] >> 4; buffer[2] = buffer[2] >> 4; } LSM303::LSM303(int i2c_fd) { this->I2C_LSM_FILE = i2c_fd; std::cout << "LSM: " << this->I2C_LSM_FILE << std::endl; } LSM303::~LSM303() {} char LSM303::ReadRegister(char reg) { unsigned char data[1] = {0}; char r[1] = {reg}; write(this->I2C_LSM_FILE, r, 1); if(read(this->I2C_LSM_FILE, data, 1) != 1) std::cout << "Failed to read from register " << r[0] << std::endl; return data[0]; } void LSM303::GetMagData(LsmData * data) { int buffer[3] = {0, 0, 0}; char mag_bytes[6] = { this->ReadRegister(this->I2C_MAG_X_LSB_REG), this->ReadRegister(this->I2C_MAG_X_MSB_REG), this->ReadRegister(this->I2C_MAG_Y_LSB_REG), this->ReadRegister(this->I2C_MAG_Y_MSB_REG), this->ReadRegister(this->I2C_MAG_Z_LSB_REG), this->ReadRegister(this->I2C_MAG_Z_MSB_REG) }; check_overflow(buffer, mag_bytes); data->X_Mag = buffer[0] / (100000.0 / 1100.0); data->Y_Mag = buffer[1] / (100000.0/ 1100.0); data->Z_Mag = buffer[2] / (100000.0/ 980.0); data->Heading = ((atan2((float)data->Y_Mag, (float)data->X_Mag) * 180.0 ) / 3.14159); data->Heading = data->Heading < 0 ? data->Heading += 360 : data->Heading; } void LSM303::GetAccelData(LsmData * data) { int buffer[3] = {0, 0, 0}; char accel_bytes[6] = { this->ReadRegister(this->I2C_ACCEL_X_LSB_REG), this->ReadRegister(this->I2C_ACCEL_X_MSB_REG), this->ReadRegister(this->I2C_ACCEL_Y_LSB_REG), this->ReadRegister(this->I2C_ACCEL_Y_MSB_REG), this->ReadRegister(this->I2C_ACCEL_Z_LSB_REG), this->ReadRegister(this->I2C_ACCEL_Z_MSB_REG) }; check_overflow(buffer, accel_bytes); data->X_Accel = buffer[0]; data->Y_Accel = buffer[1]; data->Z_Accel = buffer[2]; data->Roll = (180.0/3.14159) * atan2((double)(data->Y_Accel), (double)(data->Z_Accel)); data->Pitch = (180.0/3.14159) * atan((double)(-data->X_Accel) / ((double)(data->Y_Accel) * sin(data->Roll) + (double)(data->Z_Accel) * cos(data->Roll))); data->Yaw = (180.0/3.14159) * atan((double)data->Y_Accel/(sqrt((double)data->X_Accel * (double)data->Y_Accel + (double)data->Z_Accel * (double)data->Z_Accel))); } LsmData LSM303::GetReadings() { LsmData data; // Configure & grab I2C accelerometer device via its register ioctl(this->I2C_LSM_FILE, I2C_SLAVE, this->I2C_ACCEL_ADDR); char cfg[2] = { this->I2C_ACCEL_CONF_REG, this->I2C_ACCEL_XYZ_CLK_REG }; write(this->I2C_LSM_FILE, cfg, 2); cfg[0] = this->I2C_CTRL_REG_4; cfg[1] = this->I2C_REG_4_CFG; write(this->I2C_LSM_FILE, cfg, 2); //usleep(10000); this->GetAccelData(&data); // Now, time for the magnometer ioctl(this->I2C_LSM_FILE, I2C_SLAVE, this->I2C_MAG_ADDR); cfg[0] = this->I2C_MR_REG; cfg[1] = this->I2C_MAG_CONT; write(this->I2C_LSM_FILE, cfg, 2); cfg[0] = this->I2C_CRA_REG; cfg[1] = this->I2C_MAG_OUT_RATE; write(this->I2C_LSM_FILE, cfg, 2); cfg[0] = this->I2C_CRB_REG; cfg[1] = this->I2C_MAG_GAIN; write(this->I2C_LSM_FILE, cfg, 2); //usleep(5000); this->GetMagData(&data); return data; }
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/1024+0+512-FW/7-model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/1024+0+512-FW/7-1024+0+512-STWS-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function shuffle_trigrams_within_sentences_first_two_thirds_sixth --eval_function last_sixth_eval
#!/bin/bash # Step 1: Retrieve the name of the parent branch with its remote tracking branch parent_branch_with_remote=$(git rev-parse --abbrev-ref --symbolic-full-name @{u}) parent_branch="${parent_branch_with_remote##*/}" # Step 2: Extract the username of the Git user configured on the local system github_username=$(git config user.name) # Step 3: Obtain the remote URL of the Git repository remote_url=$(git ls-remote --get-url) # Step 4: Derive the base URL and repository name from the remote URL base_url=$(dirname "$remote_url") repo_name=$(basename -s .git "$remote_url") # Step 5: Construct a full URL for the repository full_url="$base_url/$repo_name" # Step 6: Generate a pull request URL by combining the full URL, parent branch, Git username, and current branch current_branch=$(git rev-parse --abbrev-ref HEAD) zprURL="$full_url/compare/$parent_branch...$github_username:$current_branch?expand=1" # Output the pull request URL echo "Pull Request URL: $zprURL"
package weixin.popular.bean.live; public class LiveGoodsResetauditInfo { private Integer goodsId; private Long auditId; public Integer getGoodsId() { return goodsId; } public LiveGoodsResetauditInfo setGoodsId(Integer goodsId) { this.goodsId = goodsId; return this; } public Long getAuditId() { return auditId; } public LiveGoodsResetauditInfo setAuditId(Long auditId) { this.auditId = auditId; return this; } }
import * as V11 from 'shared/types/models/widgets/versioned/v11'; import * as V10 from 'shared/types/models/widgets/versioned/v10'; import { IMigrator } from 'shared/types/app'; function migrate(config: V10.IUserConfig): V11.IUserConfig { return { ...config, shouldOpenMarketOrderWarningModal: true, version: 11, }; } export const v11Migrator: IMigrator<11> = { migrate, version: 11 };
function generateRandomString(size: number): string { const allowed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; let text = ''; for (let j = 0; j <= size; j += 1) { text += allowed.charAt(Math.floor(Math.random() * allowed.length)); } return text; } export function* generateComponentKey() { while (true) { yield generateRandomString(10); } }
#!/bin/bash NS=openmcp controller_name="openmcp-apiserver" NAME=$(kubectl get pod -n $NS | grep -E $controller_name | awk '{print $1}') echo "Exec Into '"$NAME"'" #kubectl exec -it $NAME -n $NS /bin/sh for ((;;)) do kubectl logs -n $NS $NAME --follow done
<gh_stars>1-10 import { Component, OnInit } from '@angular/core'; import { UserFormQuestions } from '../models/user-form-questions'; import { FormDataService } from '../services/form-data.service'; @Component({ selector: 'app-form-step-seven', templateUrl: './form-step-seven.component.html', styleUrls: ['./form-step-seven.component.scss'], }) export class FormStepSevenComponent implements OnInit { formQuestions: UserFormQuestions; constructor(public formDataService: FormDataService) { this.formQuestions = formDataService.formQuestions; } ngOnInit(): void {} log() { console.log('20. -', this.formQuestions.questionTwenty); console.log('21. -', this.formQuestions.questionTwentyOne); console.log('22. -', this.formQuestions.questionTwentyTwo); } submitForm() { console.log('Form been submitted'); this.formDataService.sendFormQuestions(); } }
<gh_stars>1000+ const { ipcRenderer, webFrame } = require('electron') class EmailWinInjector { constructor () { this.init() } // 初始化 init () { ipcRenderer.on('dom-ready', () => { this.injectJs() }) } // 注入JS injectJs () { this.setZoomLevel() } setZoomLevel () { // 设置缩放限制 webFrame.setZoomFactor(100) webFrame.setZoomLevel(0) webFrame.setVisualZoomLevelLimits(1, 1) } } /* eslint-disable no-new */ new EmailWinInjector()
import random def generate_random_number(): random_number = random.randint(1, 10) return random_number if __name__ == '__main__': print(generate_random_number()) # Output 2
'use strict'; const home = require('os').homedir() exports.readCredentials = function() { const env = { apiKey: process.env.DEVO_KEY, apiSecret: process.env.DEVO_SECRET, apiToken: process.env.DEVO_TOKEN, url: process.env.DEVO_URL, } try { const read = require(home + '/.devo.json') Object.keys(env).forEach(key => { if (env[key]) read[key] = env[key] }) return read } catch(exception) { return env } }
<gh_stars>0 /* * Add class(es) to element * ------------------------ * * @param item [HTMLElement] * @param classes [string] of classes separated by space */ export const addClass = ( item, classes ) => { if( !item || !classes ) return; let currentClasses = item.className; if( currentClasses ) { classes = classes.split( ' ' ); currentClasses = currentClasses.split( ' ' ); classes.forEach( ( c ) => { let classPos = currentClasses.indexOf( c ); // only add if doesn't exist if( classPos === -1 ) currentClasses.splice( classPos, 0, c ); } ); item.className = currentClasses.join( ' ' ); } else { item.setAttribute( 'class', classes ); } };
def config_job_postings(jobs): configs = {} for job in jobs: configs[job['name']] = job['config'] return configs
<gh_stars>10-100 import TokenInput from './tokenInput'; export default TokenInput;
// Create the Order model public class Order { // Order properties private int id; private String item; private int quantity; private double price; // Constructor public Order(String item, int quantity, double price) { this.item = item; this.quantity = quantity; this.price = price; } // Getters and Setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } // Create the OrderController class public class OrderController { // Method for creating a new order @PostMapping("/orders") public ResponseEntity<Order> createOrder(@RequestBody Order order) { // TODO: Implement order creation logic return ResponseEntity.ok(order); } // Method for updating an order @PutMapping("/orders/{id}") public ResponseEntity<Order> updateOrder(@PathVariable int id, @RequestBody Order order) { // TODO: Implement order update logic return ResponseEntity.ok(order); } // Method for deleting an order @DeleteMapping("/orders/{id}") public ResponseEntity<?> deleteOrder(@PathVariable int id) { // TODO: Implement order delete logic return ResponseEntity.ok().build(); } // Method for retrieving an order @GetMapping("/orders/{id}") public ResponseEntity<Order> getOrder(@PathVariable int id) { // TODO: Implement order retrieval logic return ResponseEntity.ok(order); } }
using System; using System.Collections.Generic; public class EventDispatcher { private Dictionary<string, List<Delegate>> eventListeners; public EventDispatcher() { eventListeners = new Dictionary<string, List<Delegate>>(); } public void AddListener(string eventName, Delegate eventHandler) { if (!eventListeners.ContainsKey(eventName)) { eventListeners[eventName] = new List<Delegate>(); } eventListeners[eventName].Add(eventHandler); } public void RemoveListener(string eventName, Delegate eventHandler) { if (eventListeners.ContainsKey(eventName)) { eventListeners[eventName].Remove(eventHandler); } } public void Dispatch(string eventName) { if (eventListeners.ContainsKey(eventName)) { foreach (var handler in eventListeners[eventName]) { handler.DynamicInvoke(); } } } }
package chylex.hee.entity.mob.teleport; import java.util.ArrayList; import java.util.List; import java.util.Random; import net.minecraft.entity.Entity; import chylex.hee.entity.mob.teleport.TeleportLocation.ITeleportXZ; import chylex.hee.entity.mob.teleport.TeleportLocation.ITeleportY; import chylex.hee.system.abstractions.Vec; public class MobTeleporter<T extends Entity>{ private int attempts; private ITeleportLocation<T> locationSelector; private List<ITeleportPredicate<T>> locationPredicates = new ArrayList<>(2); private List<ITeleportListener<T>> onTeleport = new ArrayList<>(2); public void setAttempts(int attempts){ this.attempts = attempts; } public void setLocationSelector(ITeleportLocation<T> locationSelector){ this.locationSelector = locationSelector; } public void setLocationSelector(ITeleportXZ<T> xzSelector, ITeleportY<T> ySelector){ this.locationSelector = new TeleportLocation<>(xzSelector, ySelector); } public void addLocationPredicate(ITeleportPredicate<T> locationPredicate){ this.locationPredicates.add(locationPredicate); } public void onTeleport(ITeleportListener<T> listener){ this.onTeleport.add(listener); } public boolean teleport(T entity, Random rand){ if (entity.worldObj.isRemote)return false; Vec oldPos = Vec.pos(entity), oldPosCopy = oldPos.copy(); for(int attempt = 0; attempt < attempts; attempt++){ Vec newPos = locationSelector.findPosition(entity, oldPosCopy, rand); entity.setPosition(newPos.x, newPos.y, newPos.z); if (locationPredicates.stream().allMatch(predicate -> predicate.isValid(entity, oldPos, rand))){ if (entity.ridingEntity != null){ entity.mountEntity(null); entity.setPosition(newPos.x, newPos.y, newPos.z); } for(ITeleportListener<T> listener:onTeleport)listener.onTeleport(entity, oldPos, rand); return true; } } entity.setPosition(oldPos.x, oldPos.y, oldPos.z); return false; } }