repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
ndretn/RSBASPM
src/main/java/ca/pfv/spmf/algorithms/sequenceprediction/ipredict/database/Item.java
package ca.pfv.spmf.algorithms.sequenceprediction.ipredict.database; /* * This file is copyright (c) <NAME> * <<EMAIL>> * * This file is part of the IPredict project * (https://github.com/tedgueniche/IPredict). * * IPredict is distributed under The MIT License (MIT). * You may obtain a copy of the License at * https://opensource.org/licenses/MIT */ public class Item implements Comparable<Item> { public Integer val; public Item(Integer value) { val = value; } @Override public Item clone() { return new Item(val); } public Item() { val = -1; } public String toString() { return val.toString(); } public int hashCode() { return val.hashCode(); } public boolean equals(Item b) { return val.equals(b.val); } @Override public boolean equals(Object obj) { Item b = (Item) obj; return val.equals(b.val); }; @Override public int compareTo(Item o) { return this.val.compareTo(o.val); } }
ivan2hdez/icons-pack
packages/react-simple-icons/src/Beats.js
<reponame>ivan2hdez/icons-pack import React from 'react'; import PropTypes from 'prop-types'; const Beats = props => { const { color, size, ...others } = props; return ( <svg width={size} height={size} fill={color} viewBox="0 0 24 24" {...others}> <path d="M21.55 16.77a7.14 7.14 0 0 1-7.16 7.16H2.45v-7.16h8.36a9.61 9.61 0 0 0 8.5-5.19 7.09 7.09 0 0 1 2.24 5.2zm-4.24-6.53a7.29 7.29 0 0 0 .66-3.01A7.14 7.14 0 0 0 10.8.07H2.46v14.32h8.35c2.9 0 5.37-1.7 6.5-4.15z" /> </svg> ); }; Beats.propTypes = { /** * Hex color or color name */ color: PropTypes.string, /** * The size of the Icon. */ size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; Beats.defaultProps = { color: 'currentColor', size: '24', }; export default Beats;
composition-project/data-processing-agent
AgentAPIs/src/main/java/eu/linksmart/api/event/types/JsonSerializable.java
<filename>AgentAPIs/src/main/java/eu/linksmart/api/event/types/JsonSerializable.java package eu.linksmart.api.event.types; import eu.linksmart.api.event.exceptions.TraceableException; import eu.linksmart.api.event.exceptions.UntraceableException; import java.io.Serializable; /** * Copyright [2013] [Fraunhofer-Gesellschaft] * * 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. * * */ /** * This interface indicates that the class that implements it can be serialized/deserialized in a JSON document. * * * @author <NAME> * @since 1.0.0 * */ public interface JsonSerializable extends Serializable{ /** * when this is generated out of an JSON document, this function must be call if additionally object construction process must be started. * @return a reference of this * @exception eu.linksmart.api.event.exceptions.StatementException if the given JSON document that generated the object, it does not reached the needed attributes to be build. * @exception eu.linksmart.api.event.exceptions.InternalException if while the postprocessing some known logic failed. * @exception eu.linksmart.api.event.exceptions.UnknownException if while the postprocessing some unknown logic failed. * @exception eu.linksmart.api.event.exceptions.UntraceableException if while the postprocessing some known logic failed and the JSON document or structure of the object do not possess any referenceable id. * @exception eu.linksmart.api.event.exceptions.UnknownUntraceableException if while the postprocessing some unknown logic failed and the JSON document or structure of the object do not possess any referenceable id. * */ JsonSerializable build() throws TraceableException, UntraceableException; // void rebuild(T me) throws Exception; /** * If the parsed object needs to released some resources generated in the build process. * * @exception java.lang.Exception if some resource cannot released. * */ void destroy()throws Exception; }
masud-technope/ACER-Replication-Package-ASE2017
corpus/class/ecf/1924.java
<reponame>masud-technope/ACER-Replication-Package-ASE2017 /******************************************************************************* * Copyright (c) 2005, 2007 <NAME> * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * <NAME> <<EMAIL>> - initial API and implementation ******************************************************************************/ package org.eclipse.ecf.protocol.msn.internal.encode; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public final class Challenge { //$NON-NLS-1$ public static final String PRODUCT_ID = "PROD0090YUAUV{2B"; //$NON-NLS-1$ private static final String PRODUCT_KEY = "<KEY>"; private static MessageDigest instance; static { try { //$NON-NLS-1$ instance = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("No MD5 digest found"); } } public static String createQuery(String challenge) { String[] s = computeMD5DigestAsStringArray((challenge + PRODUCT_KEY).getBytes()); String md5Hash = computeMD5Digest((challenge + PRODUCT_KEY).getBytes()); int[] md5 = new int[4]; for (int i = 0; i < 4; i++) { md5[i] = Integer.parseInt(s[i], 16); } String chl = challenge + PRODUCT_ID; while (chl.length() % 8 != 0) { chl += '0'; } char[] array = chl.toCharArray(); String[] values = new String[chl.length() / 4]; for (int i = 0; i < array.length; i += 4) { int j = array[i + 3]; String value = Integer.toHexString(j); j = array[i + 2]; value += Integer.toHexString(j); j = array[i + 1]; value += Integer.toHexString(j); j = array[i]; value += Integer.toHexString(j); values[i / 4] = value; } int[] ints = new int[values.length]; for (int i = 0; i < values.length; i++) { ints[i] = Integer.parseInt(values[i], 16); } long high = 0; long low = 0; for (int i = 0; i < ints.length; i += 2) { long temp = ints[i]; temp = (temp * 0xe79a9c1L) % 0x7fffffff; temp += high; temp = md5[0] * temp + md5[1]; temp = temp % 0x7fffffff; high = ints[i + 1]; high = (high + temp) % 0x7fffffff; high = md5[2] * high + md5[3]; high = high % 0x7fffffff; low = low + high + temp; } high = (high + md5[1]) % 0x7fffffff; low = (low + md5[3]) % 0x7fffffff; String highString = Long.toHexString(high); String lowString = Long.toHexString(low); while (highString.length() < 8) { highString = '0' + highString; } while (lowString.length() < 8) { lowString = '0' + lowString; } highString = highString.substring(6, 8) + highString.substring(4, 6) + highString.substring(2, 4) + highString.substring(0, 2); lowString = lowString.substring(6, 8) + lowString.substring(4, 6) + lowString.substring(2, 4) + lowString.substring(0, 2); high = Long.parseLong(highString, 16); low = Long.parseLong(lowString, 16); String first = Long.toHexString((Long.parseLong(md5Hash.substring(0, 8), 16) ^ high)); String second = Long.toHexString((Long.parseLong(md5Hash.substring(8, 16), 16) ^ low)); String third = Long.toHexString((Long.parseLong(md5Hash.substring(16, 24), 16) ^ high)); String fourth = Long.toHexString((Long.parseLong(md5Hash.substring(24, 32), 16) ^ low)); while (first.length() < 8) { first = '0' + first; } while (second.length() < 8) { second = '0' + second; } while (third.length() < 8) { third = '0' + third; } while (fourth.length() < 8) { fourth = '0' + fourth; } return first + second + third + fourth; } /** * Computes the MD5 digest of a string given its bytes. * * @param bytes * the bytes of the string to be digested * @return the MD5 digest of the original string */ private static final String computeMD5Digest(byte[] bytes) { byte[] hash = instance.digest(bytes); StringBuffer buffer = new StringBuffer(); synchronized (buffer) { for (int i = 0; i < hash.length; i++) { int value = 0xff & hash[i]; if (value < 16) { buffer.append('0').append(Integer.toHexString(value)); } else { buffer.append(Integer.toHexString(value)); } } return buffer.toString(); } } private static final String[] computeMD5DigestAsStringArray(byte[] bytes) { byte[] hash = instance.digest(bytes); StringBuffer buffer = new StringBuffer(); synchronized (buffer) { for (int i = 0; i < hash.length; i++) { int value = 0xff & hash[i]; if (value < 16) { buffer.append('0').append(Integer.toHexString(value)); } else { buffer.append(Integer.toHexString(value)); } } } String result = buffer.toString(); String[] results = new String[4]; results[0] = result.substring(0, 8); results[1] = result.substring(8, 16); results[2] = result.substring(16, 24); results[3] = result.substring(24, 32); for (int i = 0; i < 4; i++) { char[] array = results[i].toCharArray(); char[] swapped = new char[8]; for (int j = 0; j < 8; j += 2) { swapped[7 - j] = array[j + 1]; swapped[6 - j] = array[j]; } results[i] = new String(swapped); } for (int i = 0; i < 4; i++) { long l = Long.parseLong(results[i], 16); l = l & 0x7fffffff; if (l < 0x10000000) { results[i] = '0' + Long.toHexString(l); } else { results[i] = Long.toHexString(l); } } return results; } }
Heikkips/oxCore
persistence-core/src/main/java/org/gluu/persist/service/BaseFactoryService.java
<reponame>Heikkips/oxCore<filename>persistence-core/src/main/java/org/gluu/persist/service/BaseFactoryService.java package org.gluu.persist.service; import org.gluu.persist.PersistenceEntryManagerFactory; import org.gluu.persist.model.PersistenceConfiguration; import org.slf4j.Logger; public interface BaseFactoryService { PersistenceConfiguration loadPersistenceConfiguration(); PersistenceConfiguration loadPersistenceConfiguration(String applicationPropertiesFile); PersistenceEntryManagerFactory getPersistenceEntryManagerFactory(PersistenceConfiguration persistenceConfiguration); PersistenceEntryManagerFactory getPersistenceEntryManagerFactory( Class<? extends PersistenceEntryManagerFactory> persistenceEntryManagerFactoryClass); PersistenceEntryManagerFactory getPersistenceEntryManagerFactory(String persistenceType); Logger getLog(); }
saksham-jain01/data-structures-algorithms
recursion-and-algos/factorial.cpp
<reponame>saksham-jain01/data-structures-algorithms<filename>recursion-and-algos/factorial.cpp #include<iostream> using namespace std; int fact(int n){ if(n==0){ return 1; } int ans = n*fact(n-1); return ans; } int fib(int n){ if(n==0||n==1){ return n; } int f1 = fib(n-1); int f2 = fib(n-2); return f1 + f2; } int main(){ //cout<<fact(5); cout<<fib(6)<<endl; return 0; }
manuelsousa7/po-labs
aula9/exemplo/Dates.java
<gh_stars>0 package exemplo; import java.io.*; public class Dates { /** * Computes the number of number of days of the given month. Does not take into account leap years. * * @param month the concerned month. This parameter is between 1 and 12, inclusive. * * @returns the number of days in the given month. **/ public int daysInMonth(int month) { // September, April, June and November have 30 days if ((month == 9) || (month == 4) || (month == 6) || (month == 11)) { return 30; } else if (month == 2) // All the rest have 31, except for February .... return 28; else return 31; } /** * This entry point method should be invoked with four arguements: first day, first month, last day and last month * and it should print the difference of days between the first date (first day and month) and the second date (last day and month). **/ public static void main (String[] args) { int someMonth, someDay; int laterMonth, laterDay; int aMonth; someMonth = Integer.parseInt(args[0]); someDay = Integer.parseInt(args[1]); laterMonth = Integer.parseInt(args[2]); laterDay = Integer.parseInt(args[3]); /* Used to record what day in the year the first day */ /* of someMonth and laterMonth are. */ int someDayInYear = 0; int laterDayInYear = 0; Dates dates = new Dates(); for (aMonth = 0; aMonth < someMonth; aMonth = aMonth + 1) { someDayInYear = someDayInYear + dates.daysInMonth(aMonth); } for (aMonth = 1; aMonth < laterMonth; aMonth = aMonth + 1) { laterDayInYear = laterDayInYear + dates.daysInMonth(aMonth); } /* The answer */ int daysBetween = 0; System.out.println("The difference in days between " + someMonth + "/" + someDay + " and " + laterMonth + "/" + laterDay + " is: "); daysBetween = laterDayInYear - someDayInYear; daysBetween = daysBetween + laterDay - someDay; System.out.println(daysBetween); } }
yidao2000/crm
src/main/java/com/yunchuang/crm/console/user/domain/User.java
<gh_stars>1-10 package com.yunchuang.crm.console.user.domain; import java.io.Serializable; /** * Created by 尹冬飞 on 2017/12/27 16:46 */ public class User implements Serializable { private static final long serialVersionUID = 3580277389227482834L; /** * 1.主键 */ private int id; /** * 2.用户名 */ private String name; /** * 3.密码 */ private String password; /** * 4.昵称 */ private String nickname; /** * 5.状态:锁定是1,否则是0. */ private int status; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname == null ? null : nickname.trim(); } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", password=" + password + ", nickname=" + nickname + ", status=" + status + "]"; } }
IntRepair/IntRepair
smtcodan/src/smtcodan/tests/CWE190_Integer_Overflow__int64_t_max_square_45_int64_t_rand_multiply_53d.java
package smtcodan.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.Map; import org.eclipse.cdt.codan.core.CodanRuntime; import org.eclipse.cdt.codan.core.model.CheckerLaunchMode; import org.eclipse.cdt.codan.core.model.IProblemReporter; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.junit.Ignore; import org.junit.Test; public class CWE190_Integer_Overflow__int64_t_max_square_45_int64_t_rand_multiply_53d{ protected IMarker[] markers; @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_45() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_45"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 33); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_45.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_51b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_51b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 28); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_51b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_52c() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_52c"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 28); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_52c.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_53d() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_53d"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 28); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_53d.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_54e() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_54e"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 28); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_54e.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_61a() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_61a"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 34); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_61a.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_62a() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_62a"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 37); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_62a.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_63b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_63b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 29); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_63b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_64b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_64b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 32); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_64b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_65b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_65b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 28); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_65b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_66b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_66b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 30); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_66b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_67b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_67b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 34); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_67b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_68b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_68b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 33); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_68b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_72b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_72b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 36); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_72b.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_73b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_73b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 36); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_73b.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_74b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_74b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 36); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_74b.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_81_bad() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_81_bad"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 31); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_81_bad.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_82_bad() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_82_bad"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 31); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_82_bad.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_83_bad() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_83_bad"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 37); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_83_bad.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_max_square_84_bad() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_max_square_84_bad"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 37); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_max_square_84_bad.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_01() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_01"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 30); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_01.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_02() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_02"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 35); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_02.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_03() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_03"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 35); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_03.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_04() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_04"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 41); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_04.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_05() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_05"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 41); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_05.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_06() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_06"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 40); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_06.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_07() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_07"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 40); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_07.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_08() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_08"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 48); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_08.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_09() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_09"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 35); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_09.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_10() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_10"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 35); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_10.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_11() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_11"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 35); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_11.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_12() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_12"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 40); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_12.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_13() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_13"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 35); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_13.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_14() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_14"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 35); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_14.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_15() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_15"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 42); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_15.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_16() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_16"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 36); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_16.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_17() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_17"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 36); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_17.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_18() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_18"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 34); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_18.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_21() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_21"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 31); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_21.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_22b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_22b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 31); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_22b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_31() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_31"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 33); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_31.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_32() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_32"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 38); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_32.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_33() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_33"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 36); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_33.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_34() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_34"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 40); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_34.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_41() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_41"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 26); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_41.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_42() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_42"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 36); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_42.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_43() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_43"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 38); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_43.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_44() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_44"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 26); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_44.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_45() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_45"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 31); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_45.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_51b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_51b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 26); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_51b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_52c() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_52c"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 26); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_52c.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_53d() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_53d"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 26); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_53d.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_54e() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_54e"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 26); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_54e.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_61a() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_61a"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 32); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_61a.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_62a() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_62a"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 35); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_62a.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_63b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_63b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 27); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_63b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_64b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_64b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 30); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_64b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_65b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_65b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 26); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_65b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_66b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_66b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 28); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_66b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_67b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_67b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 32); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_67b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_68b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_68b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 31); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_68b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_72b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_72b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 34); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_72b.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_73b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_73b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 34); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_73b.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_74b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_74b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 34); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_74b.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_81_bad() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_81_bad"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 29); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_81_bad.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_82_bad() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_82_bad"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 29); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_82_bad.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_83_bad() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_83_bad"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 35); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_83_bad.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_add_84_bad() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_add_84_bad"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 35); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_add_84_bad.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_01() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_01"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 31); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_01.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_02() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_02"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 36); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_02.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_03() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_03"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 36); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_03.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_04() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_04"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 42); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_04.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_05() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_05"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 42); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_05.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_06() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_06"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 41); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_06.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_07() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_07"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 41); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_07.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_08() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_08"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 49); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_08.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_09() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_09"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 36); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_09.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_10() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_10"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 36); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_10.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_11() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_11"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 36); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_11.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_12() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_12"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 41); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_12.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_13() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_13"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 36); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_13.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_14() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_14"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 36); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_14.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_15() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_15"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 43); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_15.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_16() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_16"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 37); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_16.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_17() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_17"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 37); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_17.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_18() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_18"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 35); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_18.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_21() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_21"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 32); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_21.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_22b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_22b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 32); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_22b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_31() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_31"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 34); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_31.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_32() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_32"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 39); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_32.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_33() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_33"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 37); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_33.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_34() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_34"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 41); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_34.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_41() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_41"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 27); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_41.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_42() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_42"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 37); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_42.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_43() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_43"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 39); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_43.cpp"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_44() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_44"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 27); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_44.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_45() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_45"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 32); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_45.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_51b() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_51b"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 27); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_51b.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_52c() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_52c"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 27); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_52c.c"); } catch (CoreException e) { fail(e.getMessage()); } } @Test public void test_CWE190_Integer_Overflow__int64_t_rand_multiply_53d() { IWorkspaceRoot wsr = ResourcesPlugin.getWorkspace().getRoot(); IProject proj = wsr.getProject("CWE190_Integer_Overflow__int64_t_rand_multiply_53d"); CodanRuntime.getInstance().getBuilder().processResource(proj, new NullProgressMonitor(), CheckerLaunchMode.RUN_ON_DEMAND); try { markers = proj.findMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); int number = markers.length; Map<String, Object> map = markers[0].getAttributes(); String type = markers[0].getType(); String resourceName = markers[0].getResource().getName(); proj.deleteMarkers(IProblemReporter.GENERIC_CODE_ANALYSIS_MARKER_TYPE, true, IResource.DEPTH_INFINITE); assertEquals(number,1); assertEquals(map.get("message"), "Upper array bound violation"); assertEquals(map.get("lineNumber"), 27); assertEquals(type, "org.eclipse.cdt.codan.core.codanProblem"); assertEquals(resourceName, "CWE190_Integer_Overflow__int64_t_rand_multiply_53d.c"); } catch (CoreException e) { fail(e.getMessage()); } } }
rnetuka/fabric8-1
runtime/container/karaf/managed/src/main/java/io/fabric8/runtime/container/karaf/KarafManagedContainer.java
<reponame>rnetuka/fabric8-1<filename>runtime/container/karaf/managed/src/main/java/io/fabric8/runtime/container/karaf/KarafManagedContainer.java /** * Copyright 2005-2016 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.fabric8.runtime.container.karaf; import io.fabric8.runtime.container.spi.AbstractManagedContainer; import java.io.File; import java.util.Map; /** * The managed root container * * @since 26-Feb-2014 */ public final class KarafManagedContainer extends AbstractManagedContainer<KarafContainerConfiguration> { @Override protected void doConfigure(KarafContainerConfiguration config) { File karaf = new File(getContainerHome(), "bin/karaf"); if (!karaf.isFile()) throw new IllegalStateException("Not a valid karaf executable: " + karaf); if (!karaf.canExecute()) karaf.setExecutable(true); } @Override protected void doStart(KarafContainerConfiguration config) throws Exception { File containerHome = getContainerHome(); if (!containerHome.isDirectory()) throw new IllegalStateException("Not a valid Karaf home dir: " + containerHome); String javaArgs = config.getJavaVmArguments() != null ? config.getJavaVmArguments() : ""; if (!javaArgs.contains("-Xmx")) { javaArgs = KarafContainerConfiguration.DEFAULT_JAVAVM_ARGUMENTS + javaArgs; } ProcessBuilder processBuilder = new ProcessBuilder("bin/karaf"); Map<String, String> env = processBuilder.environment(); env.put("JAVA_OPTS", javaArgs); processBuilder.directory(containerHome); processBuilder.redirectErrorStream(true); startProcess(processBuilder, config); } @Override protected void doStop(KarafContainerConfiguration config) throws Exception { destroyProcess(); } }
Git-liuxiaoyu/cloud-hospital-parent
cloud-hospital-parent/cloud-hospital-nacos-parent/drug-service/src/main/java/com/example/drugservice/util/DistributedLock.java
<gh_stars>0 package com.example.drugservice.util; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.util.StringUtils; import java.util.concurrent.TimeUnit; /** * 如何向非 Spring 托管对象中【注入】托管对象。 */ @Slf4j @Data public class DistributedLock { private final static long default_max_waiting_millis = 2 * 1000L; // 默认尝试 2s 后超时 private final static long default_try_interval_millis = 100L; // 默认 100ms 尝试一次获得锁 private final static long default_lock_expire_millis = 3 * 1000L; // 单个业务持有锁的时间3秒 private String name; private String value; private long lockExpireTime; private TimeUnit timeUnit; private StringRedisTemplate redisTemplate; public DistributedLock(String name) { this(name, name, default_lock_expire_millis, TimeUnit.MILLISECONDS); } public DistributedLock(String name, String value) { this(name, value, default_lock_expire_millis, TimeUnit.MILLISECONDS); } public DistributedLock(String name, String value, long lockExpireTime, TimeUnit timeUnit) { this.name = name; this.value = value; this.lockExpireTime = lockExpireTime; this.timeUnit = timeUnit; this.redisTemplate = ApplicationContextHolder.getApplicationContext() .getBean(StringRedisTemplate.class); } public boolean lock() { return lock(default_max_waiting_millis, default_try_interval_millis); } public boolean lock(long maxWaitingMillis, long tryIntervalMillis) { try { // step 1: 参数校验,要求 setnx 命令要执行条件的 <键值对> 必须要有值。 if (StringUtils.isEmpty(name) || StringUtils.isEmpty(value)) { throw new IllegalArgumentException("锁的 name 和 value 不能为空"); } // step 2: 记录当前时间,在未来,用于判断【截止目前为止】有没有超出 maxWaitingMillis 这么久? long startTimeMillis = System.currentTimeMillis(); // redisTemplate.opsForValue().setIfAbsent() 方法背后就是 Redis 的 setnx 命令。 // 你调用这个方法,就是在执行 setnx 命令。 ValueOperations<String, String> ops = redisTemplate.opsForValue(); // 3, s ==> 3 秒; 3, m ==> 3 分钟; 3, h ==> 3 小时 // set <lock.getName()> <lock.getValue> EX <lockExpireTime+timeUnit> NX while (!Boolean.TRUE.equals(ops.setIfAbsent(name, value, lockExpireTime, timeUnit))) { // 存在锁。setnx 失败就“进来”,执行下面代码 log.debug("锁已存在!等待他人释放..."); // 判断有没有到【放弃】的时间:maxWaitingMillis if (System.currentTimeMillis() - startTimeMillis > maxWaitingMillis) { // 尝试 log.debug("等待超时。无法获得分布式锁"); return false; } // 睡 tryIntervalMillis :实现【每隔 tryIntervalMillis 起来试一次】的逻辑。 log.debug("需要等待 {} 毫秒", tryIntervalMillis); Thread.sleep(tryIntervalMillis); } log.debug("成功获得分布式锁"); return true; } catch (InterruptedException e) { log.error(e.getMessage()); return false; } } public void unlock() { if (!StringUtils.isEmpty(name)) { redisTemplate.delete(name); } } }
egranata/puppy
newlib/include/sys/dlfcn.h
<filename>newlib/include/sys/dlfcn.h // Copyright 2018 Google LLC // // 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. #ifndef NEWLIB_DLFCN #define NEWLIB_DLFCN #include <newlib/stdint.h> #ifdef __cplusplus extern "C" { #endif #define RTLD_DEFAULT ((void*)0x1) // search across all loaded dylibs #define RTLD_LAZY 0 #define RTLD_NOW 0 void *dlopen(const char *filename, int); void *dlsym(void *handle, const char *symbol); int dlclose(void *handle); char* dlerror(void); #ifdef __cplusplus } #endif #endif
openlastchaos/lastchaos-source-client
EntitiesMP/FogMarker.cpp
<reponame>openlastchaos/lastchaos-source-client<filename>EntitiesMP/FogMarker.cpp /* * This file is generated by Entity Class Compiler, (c) CroTeam 1997-98 */ #line 2 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" #include "StdH.h" ENGINE_API extern FLOAT ter_fLODMul; #include <FogMarker.h> #include <FogMarker_tables.h> void CFogMarker::SetDefaultProperties(void) { m_fDepth = 10.0f; m_fAbove = 20.0f; m_fBelow = 20.0f; m_fFar = 100.0f; m_faType = FA_EXP ; m_fDensity = 0.1f; m_fgType = FG_CONSTANT ; m_fGraduation = 0.1f; m_bDensityDirect = TRUE ; m_fDensityPercentage = 0.95f; m_fDensityDistance = 10.0f; m_bGraduationDirect = TRUE ; m_fGraduationPercentage = 0.95f; m_fGraduationDistance = 10.0f; m_iSizeL = 32; m_iSizeH = 16; m_colColor = (C_WHITE | CT_OPAQUE ); CMarker::SetDefaultProperties(); } #line 57 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" const CTString & CFogMarker::GetFogName(void) #line 58 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" { #line 59 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" return m_strName ; #line 60 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" } #line 62 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" void CFogMarker::GetFog(class CFogParameters & fpFog) #line 63 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" { #line 64 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" const FLOATmatrix3D & m = GetRotationMatrix (); #line 65 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" fpFog . fp_vFogDir (1) = m (1 , 2); #line 66 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" fpFog . fp_vFogDir (2) = m (2 , 2); #line 67 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" fpFog . fp_vFogDir (3) = m (3 , 2); #line 68 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" FLOAT fPos = fpFog . fp_vFogDir % GetPlacement () . pl_PositionVector ; #line 69 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" fpFog . fp_colColor = m_colColor ; #line 70 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" fpFog . fp_atType = (AttenuationType ) m_faType ; #line 71 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" fpFog . fp_fDensity = m_fDensity ; #line 72 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" fpFog . fp_fgtType = (FogGraduationType ) m_fgType ; #line 73 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" fpFog . fp_fGraduation = m_fGraduation ; #line 74 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" fpFog . fp_fH0 = fPos - m_fDepth - m_fBelow ; #line 75 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" fpFog . fp_fH1 = fPos - m_fDepth ; #line 76 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" fpFog . fp_fH2 = fPos ; #line 77 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" fpFog . fp_fH3 = fPos + m_fAbove ; #line 78 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" fpFog . fp_fFar = m_fFar * ter_fLODMul ; #line 79 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" fpFog . fp_iSizeH = m_iSizeH ; #line 80 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" fpFog . fp_iSizeL = m_iSizeL ; #line 81 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" } BOOL CFogMarker:: #line 83 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" Main(const CEntityEvent &__eeInput) { #undef STATE_CURRENT #define STATE_CURRENT STATE_CFogMarker_Main ASSERTMSG(__eeInput.ee_slEvent==EVENTCODE_EVoid, "CFogMarker::Main expects 'EVoid' as input!"); const EVoid &e = (const EVoid &)__eeInput; #line 85 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" InitAsEditorModel (); #line 86 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" SetPhysicsFlags (EPF_MODEL_IMMATERIAL ); #line 87 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" SetCollisionFlags (ECF_IMMATERIAL ); #line 90 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" SetModel (MODEL_MARKER ); #line 91 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" SetModelMainTexture (TEXTURE_MARKER ); #line 94 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" if(m_strName == "Marker"){ #line 95 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" m_strName = "Fog marker"; #line 96 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" } #line 99 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" if(! m_bDensityDirect ){ #line 101 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" switch(m_faType ){ #line 102 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" case FA_LINEAR : #line 103 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" m_fDensity = m_fDensityPercentage / m_fDensityDistance ; #line 104 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" break ; #line 105 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" case FA_EXP : #line 106 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" m_fDensity = - log (1 - m_fDensityPercentage ) / m_fDensityDistance ; #line 107 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" break ; #line 108 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" case FA_EXP2 : #line 109 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" m_fDensity = Sqrt (- log (1 - m_fDensityPercentage )) / m_fDensityDistance ; #line 110 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" break ; #line 111 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" } #line 112 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" } #line 115 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" if(! m_bGraduationDirect ){ #line 117 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" switch(m_fgType ){ #line 118 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" case FG_LINEAR : #line 119 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" m_fGraduation = m_fGraduationPercentage / m_fGraduationDistance ; #line 120 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" break ; #line 121 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" case FG_EXP : #line 122 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" m_fGraduation = - log (1 - m_fGraduationPercentage ) / m_fGraduationDistance ; #line 123 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" break ; #line 124 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" } #line 125 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" } #line 129 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" m_fDensity = ClampDn (m_fDensity , 1E-6f); #line 131 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" m_fDepth = ClampDn (m_fDepth , 0.001f); #line 132 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" m_fAbove = ClampDn (m_fAbove , 0.001f); #line 133 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" m_fBelow = ClampDn (m_fBelow , 0.001f); #line 134 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" m_fFar = ClampDn (m_fFar , 0.001f); #line 136 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" m_iSizeL = 1 << INDEX (Log2 (m_iSizeL )); #line 137 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" m_iSizeH = 1 << INDEX (Log2 (m_iSizeH )); #line 138 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" m_iSizeL = Clamp (m_iSizeL , INDEX (2) , INDEX (256)); #line 139 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" m_iSizeH = Clamp (m_iSizeH , INDEX (2) , INDEX (256)); #line 141 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" Return(STATE_CURRENT,EVoid()); #line 141 "C:/Users/pwesty/Desktop/SD-Source/nov-source/Reco_Csrc/EntitiesMP/FogMarker.es" return TRUE; ASSERT(FALSE); return TRUE;};
jpanikulam/experiments
geometry/types/unit_vector.hh
#pragma once #include "logging/assert.hh" #include "eigen.hh" #include "sophus.hh" namespace geometry { template <int N> class UnitVector { public: using Vec = VecNd<N>; // We are using dependent types *partly* to be performant // So this is default uninitialized UnitVector() = default; explicit UnitVector(const Vec& v) { v_ = v.normalized(); } explicit UnitVector(double x, double y, double z) { static_assert(N == 3, "Cannot use this constructor with anything but 3 arguments."); v_ = jcc::Vec3(x, y, z).normalized(); } static UnitVector<2> from_angle(const double theta) { static_assert(N == 2); return UnitVector<2>::bless(VecNd<2>(std::cos(theta), std::sin(theta))); } // For now, the below "sinful" operations shall remain in cold storage /* UnitVector(const UnitVector&) = default; UnitVector& operator=(const Vec& v) { *this = normalize(v); return *this; } explicit operator Vec() const { return v_; } */ // TODO deprecate const Vec& vector() const { return v_; } const Vec& vec() const { return v_; } const Vec project(const Vec& v) const { return v_ * v_.dot(v); } double dot(const Vec& v) const { return v_.dot(v); } UnitVector unit_cross(const UnitVector& v) const { static_assert(N == 3, "Must have dimension 3"); return UnitVector(Vec(v_.cross(v.vec()))); } static UnitVector normalize(const Vec& v) { return bless(v.normalized()); } static UnitVector check(const Vec& v) { constexpr double F_EPS = 1e-6; JASSERT_LT(std::abs(v.squaredNorm() - 1.0), F_EPS, "v must be of unit norm"); return UnitVector(v); } static UnitVector bless(const Vec& v) { UnitVector vv; vv.v_ = v; return vv; } static UnitVector UnitX() { return UnitVector(Vec::UnitX()); } static UnitVector UnitY() { return UnitVector(Vec::UnitY()); } static UnitVector UnitZ() { return UnitVector(Vec::UnitZ()); } private: Vec v_; }; using UnitVector3 = UnitVector<3>; inline UnitVector3 operator*(const SE3& destination_from_source, const UnitVector3& source) { return UnitVector3::bless(destination_from_source.so3() * source.vec()); } using UnitVector3 = UnitVector<3>; inline UnitVector3 operator*(const SO3& destination_from_source, const UnitVector3& source) { return UnitVector3::bless(destination_from_source * source.vec()); } using Unit3 = UnitVector3; using UnitVector2 = UnitVector<2>; } // namespace geometry
sthagen/Nuitka-Nuitka
tests/basics/ListContractions.py
<filename>tests/basics/ListContractions.py # Copyright 2022, <NAME>, mailto:<EMAIL> # # Python tests originally created or extracted from other peoples work. The # parts were too small to be protected. # # 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. # """ Cover list contractions and a few special things in them. """ from __future__ import print_function # Tests do bad things, pylint: disable=possibly-unused-variable,redefined-outer-name def displayDict(d): result = "{" first = True for key, value in sorted(d.items()): if not first: result += "," result += "%s: %s" % (repr(key), repr(value)) first = False result += "}" return result print("List contraction on the module level:") x = [(u if u % 2 == 0 else 0) for u in range(10)] print(x) print("List contraction on the function level:") def someFunction(): x = [(u if u % 2 == 0 else 0) for u in range(10)] print(x) someFunction() print("List contractions with no, 1 one 2 conditions:") def otherFunction(): print([x for x in range(8)]) print([x for x in range(8) if x % 2 == 1]) print([x for x in range(8) if x % 2 == 1 if x > 4]) otherFunction() print("Complex list contractions with more than one for:") def complexContractions(): print([(x, y) for x in range(3) for y in range(5)]) seq = range(3) res = [(i, j, k) for i in iter(seq) for j in iter(seq) for k in iter(seq)] print(res) complexContractions() print("Contraction for 2 for statements and one final if referring to first for:") def trickyContraction(): class Range: def __init__(self, value): self.value = value def __iter__(self): print("Giving range iter to", self.value) return iter(range(self.value)) def Cond(y): print("Checking against", y) return y == 1 r = [(x, z, y) for x in Range(3) for z in Range(2) for y in Range(4) if Cond(y)] print("result is", r) trickyContraction() def lambdaWithcontraction(x): l = lambda x: [z for z in range(x)] r = l(x) print("Lambda contraction locals:", displayDict(locals())) lambdaWithcontraction(3) print("Contraction that gets a 'del' on the iterator variable:", end=" ") def allowedDelOnIteratorVariable(z): x = 2 del x return [x * z for x in range(z)] print(allowedDelOnIteratorVariable(3))
hovedstyret/indok-web
backend/apps/organizations/schema.py
<gh_stars>1-10 import graphene from .mutations import ( AssignMembership, CreateOrganization, DeleteOrganization, UpdateOrganization, ) from .resolvers import MembershipResolvers, OrganizationResolvers from .types import MembershipType, OrganizationType class OrganizationMutations(graphene.ObjectType): create_organization = CreateOrganization.Field() update_organization = UpdateOrganization.Field() delete_organization = DeleteOrganization.Field() assign_membership = AssignMembership.Field() class OrganizationQueries(graphene.ObjectType, OrganizationResolvers, MembershipResolvers): all_organizations = graphene.List(OrganizationType, search=graphene.String()) organization = graphene.Field( OrganizationType, id=graphene.ID(required=False), slug=graphene.String(required=False), ) event_filtered_organizations = graphene.List(OrganizationType) memberships = graphene.List(MembershipType, organization_id=graphene.ID())
yearliny/yogo
src/main/java/ga/yuan/yogo/repository/UserRepository.java
<filename>src/main/java/ga/yuan/yogo/repository/UserRepository.java package ga.yuan.yogo.repository; import ga.yuan.yogo.model.entity.UserDO; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<UserDO, Long> { /** * 通过 Email 地址查询用户 * @param email Email 地址 * @return UserDO */ UserDO findByEmail(String email); /** * 通过 username 查询用户 * @param name 用户名 * @return UserDO */ UserDO findByName(String name); }
opengauss-mirror/openGauss-graph
src/include/securectype.h
<reponame>opengauss-mirror/openGauss-graph<filename>src/include/securectype.h /* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * --------------------------------------------------------------------------------------- * * securectype.h * define internal used macro and data type. The marco of SECUREC_ON_64BITS * will be determined in this header file, which is a switch for part * of code. Some macro are used to supress warning by MS compiler. * * * * IDENTIFICATION * src/include/securectype.h * * Note: * user can change the value of SECUREC_STRING_MAX_LEN and SECUREC_MEM_MAX_LEN * macro to meet their special need ,but The maximum value should not exceed 2G . * * --------------------------------------------------------------------------------------- */ /* * [Standardize-exceptions]: Performance-sensitive * [reason]: Strict parameter verification has been done before use */ #ifndef SECURECTYPE_H_A7BBB686_AADA_451B_B9F9_44DACDAE18A7 #define SECURECTYPE_H_A7BBB686_AADA_451B_B9F9_44DACDAE18A7 #ifndef SECUREC_USING_STD_SECURE_LIB #if defined(_MSC_VER) && _MSC_VER >= 1400 #if defined(__STDC_WANT_SECURE_LIB__) && (!__STDC_WANT_SECURE_LIB__) /* Security functions have been provided since vs2005, default use of system library functions */ #define SECUREC_USING_STD_SECURE_LIB 0 #else #define SECUREC_USING_STD_SECURE_LIB 1 #endif #else #define SECUREC_USING_STD_SECURE_LIB 0 #endif #endif /* Compatibility with older Secure C versions, shielding VC symbol redefinition warning */ #if defined(_MSC_VER) && (_MSC_VER >= 1400) && (!SECUREC_USING_STD_SECURE_LIB) #ifndef SECUREC_DISABLE_CRT_FUNC #define SECUREC_DISABLE_CRT_FUNC 1 #endif #ifndef SECUREC_DISABLE_CRT_IMP #define SECUREC_DISABLE_CRT_IMP 1 #endif #else /* MSC VER */ #ifndef SECUREC_DISABLE_CRT_FUNC #define SECUREC_DISABLE_CRT_FUNC 0 #endif #ifndef SECUREC_DISABLE_CRT_IMP #define SECUREC_DISABLE_CRT_IMP 0 #endif #endif #if SECUREC_DISABLE_CRT_FUNC #ifdef __STDC_WANT_SECURE_LIB__ #undef __STDC_WANT_SECURE_LIB__ #endif #define __STDC_WANT_SECURE_LIB__ 0 #endif #if SECUREC_DISABLE_CRT_IMP #ifdef _CRTIMP_ALTERNATIVE #undef _CRTIMP_ALTERNATIVE #endif #define _CRTIMP_ALTERNATIVE /* Comment microsoft *_s function */ #endif /* Compile in kernel under macro control */ #ifndef SECUREC_IN_KERNEL #ifdef __KERNEL__ #define SECUREC_IN_KERNEL 1 #else #define SECUREC_IN_KERNEL 0 #endif #endif #if SECUREC_IN_KERNEL #ifndef SECUREC_ENABLE_SCANF_FILE #define SECUREC_ENABLE_SCANF_FILE 0 #endif #ifndef SECUREC_ENABLE_WCHAR_FUNC #define SECUREC_ENABLE_WCHAR_FUNC 0 #endif #else /* SECUREC_IN_KERNEL */ #ifndef SECUREC_ENABLE_SCANF_FILE #define SECUREC_ENABLE_SCANF_FILE 1 #endif #ifndef SECUREC_ENABLE_WCHAR_FUNC #define SECUREC_ENABLE_WCHAR_FUNC 1 #endif #endif /* Default secure function declaration, default declarations for non-standard functions */ #ifndef SECUREC_SNPRINTF_TRUNCATED #define SECUREC_SNPRINTF_TRUNCATED 1 #endif #if SECUREC_USING_STD_SECURE_LIB #if defined(_MSC_VER) && _MSC_VER >= 1400 /* Declare secure functions that are not available in the VS compiler */ #ifndef SECUREC_ENABLE_MEMSET #define SECUREC_ENABLE_MEMSET 1 #endif /* VS 2005 have vsnprintf_s function */ #ifndef SECUREC_ENABLE_VSNPRINTF #define SECUREC_ENABLE_VSNPRINTF 0 #endif #ifndef SECUREC_ENABLE_SNPRINTF /* VS 2005 have vsnprintf_s function Adapt the snprintf_s of the security function */ #define snprintf_s _snprintf_s #define SECUREC_ENABLE_SNPRINTF 0 #endif /* Before VS 2010 do not have v functions */ #if _MSC_VER <= 1600 || defined(SECUREC_FOR_V_SCANFS) #ifndef SECUREC_ENABLE_VFSCANF #define SECUREC_ENABLE_VFSCANF 1 #endif #ifndef SECUREC_ENABLE_VSCANF #define SECUREC_ENABLE_VSCANF 1 #endif #ifndef SECUREC_ENABLE_VSSCANF #define SECUREC_ENABLE_VSSCANF 1 #endif #endif #else /* MSC VER */ #ifndef SECUREC_ENABLE_MEMSET #define SECUREC_ENABLE_MEMSET 0 #endif #ifndef SECUREC_ENABLE_SNPRINTF #define SECUREC_ENABLE_SNPRINTF 0 #endif #ifndef SECUREC_ENABLE_VSNPRINTF #define SECUREC_ENABLE_VSNPRINTF 0 #endif #endif #ifndef SECUREC_ENABLE_MEMMOVE #define SECUREC_ENABLE_MEMMOVE 0 #endif #ifndef SECUREC_ENABLE_MEMCPY #define SECUREC_ENABLE_MEMCPY 0 #endif #ifndef SECUREC_ENABLE_STRCPY #define SECUREC_ENABLE_STRCPY 0 #endif #ifndef SECUREC_ENABLE_STRNCPY #define SECUREC_ENABLE_STRNCPY 0 #endif #ifndef SECUREC_ENABLE_STRCAT #define SECUREC_ENABLE_STRCAT 0 #endif #ifndef SECUREC_ENABLE_STRNCAT #define SECUREC_ENABLE_STRNCAT 0 #endif #ifndef SECUREC_ENABLE_SPRINTF #define SECUREC_ENABLE_SPRINTF 0 #endif #ifndef SECUREC_ENABLE_VSPRINTF #define SECUREC_ENABLE_VSPRINTF 0 #endif #ifndef SECUREC_ENABLE_SSCANF #define SECUREC_ENABLE_SSCANF 0 #endif #ifndef SECUREC_ENABLE_VSSCANF #define SECUREC_ENABLE_VSSCANF 0 #endif #ifndef SECUREC_ENABLE_SCANF #define SECUREC_ENABLE_SCANF 0 #endif #ifndef SECUREC_ENABLE_VSCANF #define SECUREC_ENABLE_VSCANF 0 #endif #ifndef SECUREC_ENABLE_FSCANF #define SECUREC_ENABLE_FSCANF 0 #endif #ifndef SECUREC_ENABLE_VFSCANF #define SECUREC_ENABLE_VFSCANF 0 #endif #ifndef SECUREC_ENABLE_STRTOK #define SECUREC_ENABLE_STRTOK 0 #endif #ifndef SECUREC_ENABLE_GETS #define SECUREC_ENABLE_GETS 0 #endif #else /* SECUREC USE STD SECURE LIB */ #ifndef SECUREC_ENABLE_MEMSET #define SECUREC_ENABLE_MEMSET 1 #endif #ifndef SECUREC_ENABLE_MEMMOVE #define SECUREC_ENABLE_MEMMOVE 1 #endif #ifndef SECUREC_ENABLE_MEMCPY #define SECUREC_ENABLE_MEMCPY 1 #endif #ifndef SECUREC_ENABLE_STRCPY #define SECUREC_ENABLE_STRCPY 1 #endif #ifndef SECUREC_ENABLE_STRNCPY #define SECUREC_ENABLE_STRNCPY 1 #endif #ifndef SECUREC_ENABLE_STRCAT #define SECUREC_ENABLE_STRCAT 1 #endif #ifndef SECUREC_ENABLE_STRNCAT #define SECUREC_ENABLE_STRNCAT 1 #endif #ifndef SECUREC_ENABLE_SPRINTF #define SECUREC_ENABLE_SPRINTF 1 #endif #ifndef SECUREC_ENABLE_VSPRINTF #define SECUREC_ENABLE_VSPRINTF 1 #endif #ifndef SECUREC_ENABLE_SNPRINTF #define SECUREC_ENABLE_SNPRINTF 1 #endif #ifndef SECUREC_ENABLE_VSNPRINTF #define SECUREC_ENABLE_VSNPRINTF 1 #endif #ifndef SECUREC_ENABLE_SSCANF #define SECUREC_ENABLE_SSCANF 1 #endif #ifndef SECUREC_ENABLE_VSSCANF #define SECUREC_ENABLE_VSSCANF 1 #endif #ifndef SECUREC_ENABLE_SCANF #if SECUREC_ENABLE_SCANF_FILE #define SECUREC_ENABLE_SCANF 1 #else #define SECUREC_ENABLE_SCANF 0 #endif #endif #ifndef SECUREC_ENABLE_VSCANF #if SECUREC_ENABLE_SCANF_FILE #define SECUREC_ENABLE_VSCANF 1 #else #define SECUREC_ENABLE_VSCANF 0 #endif #endif #ifndef SECUREC_ENABLE_FSCANF #if SECUREC_ENABLE_SCANF_FILE #define SECUREC_ENABLE_FSCANF 1 #else #define SECUREC_ENABLE_FSCANF 0 #endif #endif #ifndef SECUREC_ENABLE_VFSCANF #if SECUREC_ENABLE_SCANF_FILE #define SECUREC_ENABLE_VFSCANF 1 #else #define SECUREC_ENABLE_VFSCANF 0 #endif #endif #ifndef SECUREC_ENABLE_STRTOK #define SECUREC_ENABLE_STRTOK 1 #endif #ifndef SECUREC_ENABLE_GETS #define SECUREC_ENABLE_GETS 1 #endif #endif /* SECUREC_USE_STD_SECURE_LIB */ #if !SECUREC_ENABLE_SCANF_FILE #if SECUREC_ENABLE_FSCANF #undef SECUREC_ENABLE_FSCANF #define SECUREC_ENABLE_FSCANF 0 #endif #if SECUREC_ENABLE_VFSCANF #undef SECUREC_ENABLE_VFSCANF #define SECUREC_ENABLE_VFSCANF 0 #endif #if SECUREC_ENABLE_SCANF #undef SECUREC_ENABLE_SCANF #define SECUREC_ENABLE_SCANF 0 #endif #if SECUREC_ENABLE_FSCANF #undef SECUREC_ENABLE_FSCANF #define SECUREC_ENABLE_FSCANF 0 #endif #endif #if SECUREC_IN_KERNEL #include <linux/kernel.h> #include <linux/module.h> #else #ifndef SECUREC_HAVE_STDIO_H #define SECUREC_HAVE_STDIO_H 1 #endif #ifndef SECUREC_HAVE_STRING_H #define SECUREC_HAVE_STRING_H 1 #endif #ifndef SECUREC_HAVE_STDLIB_H #define SECUREC_HAVE_STDLIB_H 1 #endif #if SECUREC_HAVE_STDIO_H #include <stdio.h> #endif #if SECUREC_HAVE_STRING_H #include <string.h> #endif #if SECUREC_HAVE_STDLIB_H #include <stdlib.h> #endif #endif /* * If you need high performance, enable the SECUREC_WITH_PERFORMANCE_ADDONS macro, default is enable. * The macro is automatically closed on the windows platform and linux kernel */ #ifndef SECUREC_WITH_PERFORMANCE_ADDONS #if SECUREC_IN_KERNEL #define SECUREC_WITH_PERFORMANCE_ADDONS 0 #else #define SECUREC_WITH_PERFORMANCE_ADDONS 1 #endif #endif /* If enable SECUREC_COMPATIBLE_WIN_FORMAT, the output format will be compatible to Windows. */ #if (defined(_WIN32) || defined(_WIN64) || defined(_MSC_VER)) && !defined(SECUREC_COMPATIBLE_LINUX_FORMAT) #ifndef SECUREC_COMPATIBLE_WIN_FORMAT #define SECUREC_COMPATIBLE_WIN_FORMAT #endif #endif #if defined(SECUREC_COMPATIBLE_WIN_FORMAT) /* On windows platform, can't use optimized function for there is no __builtin_constant_p like function */ /* If need optimized macro, can define this: define __builtin_constant_p(x) 0 */ #ifdef SECUREC_WITH_PERFORMANCE_ADDONS #undef SECUREC_WITH_PERFORMANCE_ADDONS #define SECUREC_WITH_PERFORMANCE_ADDONS 0 #endif #endif #if defined(__VXWORKS__) || defined(__vxworks) || defined(__VXWORKS) || defined(_VXWORKS_PLATFORM_) || \ defined(SECUREC_VXWORKS_VERSION_5_4) #ifndef SECUREC_VXWORKS_PLATFORM #define SECUREC_VXWORKS_PLATFORM #endif #endif /* If enable SECUREC_COMPATIBLE_LINUX_FORMAT, the output format will be compatible to Linux. */ #if !defined(SECUREC_COMPATIBLE_WIN_FORMAT) && !defined(SECUREC_VXWORKS_PLATFORM) #ifndef SECUREC_COMPATIBLE_LINUX_FORMAT #define SECUREC_COMPATIBLE_LINUX_FORMAT #endif #endif #ifdef SECUREC_COMPATIBLE_LINUX_FORMAT #ifndef SECUREC_HAVE_STDDEF_H #define SECUREC_HAVE_STDDEF_H 1 #endif /* Some system may no stddef.h */ #if SECUREC_HAVE_STDDEF_H #if !SECUREC_IN_KERNEL #include <stddef.h> #endif #endif #endif /* * Add the -DSECUREC_SUPPORT_FORMAT_WARNING=1 compiler option to supoort -Wformat=2. * Default does not check the format is that the same data type in the actual code. * In the product is different in the original data type definition of VxWorks and Linux. */ #ifndef SECUREC_SUPPORT_FORMAT_WARNING #define SECUREC_SUPPORT_FORMAT_WARNING 0 #endif #if SECUREC_SUPPORT_FORMAT_WARNING #define SECUREC_ATTRIBUTE(x, y) __attribute__((format(printf, (x), (y)))) #else #define SECUREC_ATTRIBUTE(x, y) #endif /* * Add the -DSECUREC_SUPPORT_BUILTIN_EXPECT=0 compiler option, if complier can not support __builtin_expect. */ #ifndef SECUREC_SUPPORT_BUILTIN_EXPECT #define SECUREC_SUPPORT_BUILTIN_EXPECT 1 #endif #if SECUREC_SUPPORT_BUILTIN_EXPECT && defined(__GNUC__) && ((__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 3))) /* * This is a built-in function that can be used without a declaration, if warning for declaration not found occurred, * you can add -DSECUREC_NEED_BUILTIN_EXPECT_DECLARE to complier options */ #ifdef SECUREC_NEED_BUILTIN_EXPECT_DECLARE long __builtin_expect(long exp, long c); #endif #define SECUREC_LIKELY(x) __builtin_expect(!!(x), 1) #define SECUREC_UNLIKELY(x) __builtin_expect(!!(x), 0) #else #define SECUREC_LIKELY(x) (x) #define SECUREC_UNLIKELY(x) (x) #endif /* Define the max length of the string */ #ifndef SECUREC_STRING_MAX_LEN #define SECUREC_STRING_MAX_LEN 0x7fffffffUL #endif #define SECUREC_WCHAR_STRING_MAX_LEN (SECUREC_STRING_MAX_LEN / sizeof(wchar_t)) /* Add SECUREC_MEM_MAX_LEN for memcpy and memmove */ #ifndef SECUREC_MEM_MAX_LEN #define SECUREC_MEM_MAX_LEN 0x7fffffffUL #endif #define SECUREC_WCHAR_MEM_MAX_LEN (SECUREC_MEM_MAX_LEN / sizeof(wchar_t)) #if SECUREC_STRING_MAX_LEN > 0x7fffffffUL #error "max string is 2G" #endif #if (defined(__GNUC__) && defined(__SIZEOF_POINTER__)) #if (__SIZEOF_POINTER__ != 4) && (__SIZEOF_POINTER__ != 8) #error "unsupported system" #endif #endif #if defined(_WIN64) || defined(WIN64) || defined(__LP64__) || defined(_LP64) #define SECUREC_ON_64BITS #endif #if (!defined(SECUREC_ON_64BITS) && defined(__GNUC__) && defined(__SIZEOF_POINTER__)) #if __SIZEOF_POINTER__ == 8 #define SECUREC_ON_64BITS #endif #endif #if defined(__SVR4) || defined(__svr4__) #define SECUREC_ON_SOLARIS #endif #if (defined(__hpux) || defined(_AIX) || defined(SECUREC_ON_SOLARIS)) #define SECUREC_ON_UNIX #endif /* * Codes should run under the macro SECUREC_COMPATIBLE_LINUX_FORMAT in unknow system on default, * and strtold. * The function strtold is referenced first at ISO9899:1999(C99), and some old compilers can * not support these functions. Here provides a macro to open these functions: * SECUREC_SUPPORT_STRTOLD -- If defined, strtold will be used */ #ifndef SECUREC_SUPPORT_STRTOLD #define SECUREC_SUPPORT_STRTOLD 0 #if (defined(SECUREC_COMPATIBLE_LINUX_FORMAT)) #if defined(__USE_ISOC99) || \ (defined(_AIX) && defined(_ISOC99_SOURCE)) || \ (defined(__hpux) && defined(__ia64)) || \ (defined(SECUREC_ON_SOLARIS) && (!defined(_STRICT_STDC) && !defined(__XOPEN_OR_POSIX)) || \ defined(_STDC_C99) || defined(__EXTENSIONS__)) #undef SECUREC_SUPPORT_STRTOLD #define SECUREC_SUPPORT_STRTOLD 1 #endif #endif #if ((defined(SECUREC_WRLINUX_BELOW4) || defined(_WRLINUX_BELOW4_))) #undef SECUREC_SUPPORT_STRTOLD #define SECUREC_SUPPORT_STRTOLD 0 #endif #endif #if SECUREC_WITH_PERFORMANCE_ADDONS #ifndef SECUREC_TWO_MIN #define SECUREC_TWO_MIN(a, b) ((a) < (b) ? (a) : (b)) #endif /* For strncpy_s performance optimization */ #define SECUREC_STRNCPY_SM(dest, destMax, src, count) \ (((void *)(dest) != NULL && (void *)(src) != NULL && (size_t)(destMax) > 0 && \ (((unsigned long long)(destMax) & (unsigned long long)(-2)) < SECUREC_STRING_MAX_LEN) && \ (SECUREC_TWO_MIN((size_t)(count), strlen(src)) + 1) <= (size_t)(destMax)) ? \ (((size_t)(count) < strlen(src)) ? (memcpy((dest), (src), (count)), *((char *)(dest) + (count)) = '\0', EOK) : \ (memcpy((dest), (src), strlen(src) + 1), EOK)) : (strncpy_error((dest), (destMax), (src), (count)))) #define SECUREC_STRCPY_SM(dest, destMax, src) \ (((void *)(dest) != NULL && (void *)(src) != NULL && (size_t)(destMax) > 0 && \ (((unsigned long long)(destMax) & (unsigned long long)(-2)) < SECUREC_STRING_MAX_LEN) && \ (strlen(src) + 1) <= (size_t)(destMax)) ? (memcpy((dest), (src), strlen(src) + 1), EOK) : \ (strcpy_error((dest), (destMax), (src)))) /* For strcat_s performance optimization */ #if defined(__GNUC__) #define SECUREC_STRCAT_SM(dest, destMax, src) ({ \ int catRet_ = EOK; \ if ((void *)(dest) != NULL && (void *)(src) != NULL && (size_t)(destMax) > 0 && \ (((unsigned long long)(destMax) & (unsigned long long)(-2)) < SECUREC_STRING_MAX_LEN)) { \ char *catTmpDst_ = (char *)(dest); \ size_t catRestSize_ = (destMax); \ while (catRestSize_ > 0 && *catTmpDst_ != '\0') { \ ++catTmpDst_; \ --catRestSize_; \ } \ if (catRestSize_ == 0) { \ catRet_ = EINVAL; \ } else if ((strlen(src) + 1) <= catRestSize_) { \ memcpy(catTmpDst_, (src), strlen(src) + 1); \ catRet_ = EOK; \ } else { \ catRet_ = ERANGE; \ } \ if (catRet_ != EOK) { \ catRet_ = strcat_s((dest), (destMax), (src)); \ } \ } else { \ catRet_ = strcat_s((dest), (destMax), (src)); \ } \ catRet_; \ }) #else #define SECUREC_STRCAT_SM(dest, destMax, src) strcat_s((dest), (destMax), (src)) #endif /* For strncat_s performance optimization */ #if defined(__GNUC__) #define SECUREC_STRNCAT_SM(dest, destMax, src, count) ({ \ int ncatRet_ = EOK; \ if ((void *)(dest) != NULL && (void *)(src) != NULL && (size_t)(destMax) > 0 && \ (((unsigned long long)(destMax) & (unsigned long long)(-2)) < SECUREC_STRING_MAX_LEN) && \ (((unsigned long long)(count) & (unsigned long long)(-2)) < SECUREC_STRING_MAX_LEN)) { \ char *ncatTmpDest_ = (char *)(dest); \ size_t ncatRestSize_ = (size_t)(destMax); \ while (ncatRestSize_ > 0 && *ncatTmpDest_ != '\0') { \ ++ncatTmpDest_; \ --ncatRestSize_; \ } \ if (ncatRestSize_ == 0) { \ ncatRet_ = EINVAL; \ } else if ((SECUREC_TWO_MIN((count), strlen(src)) + 1) <= ncatRestSize_) { \ if ((size_t)(count) < strlen(src)) { \ memcpy(ncatTmpDest_, (src), (count)); \ *(ncatTmpDest_ + (count)) = '\0'; \ } else { \ memcpy(ncatTmpDest_, (src), strlen(src) + 1); \ } \ } else { \ ncatRet_ = ERANGE; \ } \ if (ncatRet_ != EOK) { \ ncatRet_ = strncat_s((dest), (destMax), (src), (count)); \ } \ } else { \ ncatRet_ = strncat_s((dest), (destMax), (src), (count)); \ } \ ncatRet_; \ }) #else #define SECUREC_STRNCAT_SM(dest, destMax, src, count) strncat_s((dest), (destMax), (src), (count)) #endif /* This macro do not check buffer overlap by default */ #define SECUREC_MEMCPY_SM(dest, destMax, src, count) \ (!(((size_t)(destMax) == 0) || \ (((unsigned long long)(destMax) & (unsigned long long)(-2)) > SECUREC_MEM_MAX_LEN) || \ ((size_t)(count) > (size_t)(destMax)) || ((void *)(dest)) == NULL || ((void *)(src) == NULL)) ? \ (memcpy((dest), (src), (count)), EOK) : \ (memcpy_s((dest), (destMax), (src), (count)))) #define SECUREC_MEMSET_SM(dest, destMax, c, count) \ (!((((unsigned long long)(destMax) & (unsigned long long)(-2)) > SECUREC_MEM_MAX_LEN) || \ ((void *)(dest) == NULL) || ((size_t)(count) > (size_t)(destMax))) ? \ (memset((dest), (c), (count)), EOK) : \ (memset_s((dest), (destMax), (c), (count)))) #endif #endif
hawesy/qlcplus
plugins/hid/win32/hidwindowsjoystick.h
<filename>plugins/hid/win32/hidwindowsjoystick.h /* Q Light Controller Plus hidwindowsjoystick.h Copyright (c) <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.txt 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. */ #ifndef HIDWINDOWSJOYSTICK_H #define HIDWINDOWSJOYSTICK_H #include <windows.h> #include <mmsystem.h> #include "hidjsdevice.h" class HIDWindowsJoystick: public HIDJsDevice { Q_OBJECT public: HIDWindowsJoystick(HIDPlugin *parent, quint32 line, hid_device_info *info); static bool isJoystick(unsigned short vid, unsigned short pid); /** @reimp */ void init(); /** @reimp */ bool readEvent(); protected: JOYCAPS m_caps; JOYINFOEX m_info; UINT m_windId; DWORD m_buttonsMask; QByteArray m_axesValues; }; #endif // HIDWINDOWSJOYSTICK_H
daredevil999/Whiz
src/main/java/seedu/task/logic/parser/SaveParser.java
<filename>src/main/java/seedu/task/logic/parser/SaveParser.java package seedu.task.logic.parser; import static seedu.task.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import java.util.regex.Matcher; import java.util.regex.Pattern; import seedu.task.logic.commands.Command; import seedu.task.logic.commands.IncorrectCommand; import seedu.task.logic.commands.SaveCommand; //@@author A0125534L /** * Parses arguments in the context of the save command. * * @param args * full command args string * @return the prepared command * * */ public class SaveParser implements Parser { private static final Pattern SAVE_ARGS_FORMAT = Pattern.compile("(?<arguments>.*)"); public SaveParser() {} public Command prepare(String args) { final Matcher matcher = SAVE_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveCommand.MESSAGE_USAGE)); } return new SaveCommand(args); } }
gaomengzhou/enforcement
src/pages/Intelligentize/Timing/List.js
/* eslint-disable no-shadow */ /* eslint-disable react/jsx-no-bind */ /* eslint-disable consistent-return */ /* eslint-disable react/no-unused-state */ /* eslint-disable no-undef */ /* eslint-disable eqeqeq */ /* eslint-disable no-param-reassign */ /* eslint-disable radix */ /* eslint-disable no-plusplus */ /* eslint-disable react/sort-comp */ /* eslint-disable no-unused-vars */ /* eslint-disable import/no-extraneous-dependencies */ import React, { PureComponent } from 'react'; import moment from 'moment'; import { connect } from 'dva'; import Link from 'umi/link'; import { Row, Col, Form, Input, Select, Button, DatePicker, Table, Radio, Modal, Breadcrumb } from 'antd'; import residue from "../../../utils/time"; const FormItem = Form.Item; const { RangePicker } = DatePicker; const RadioGroup = Radio.Group; @connect(({ timing, select, complain, inspectors, comprehensive }) => ({ timing, select, complain, inspectors, comprehensive })) @Form.create() class Workplace extends PureComponent { state = { formValues: {}, page: 1, pageSize: 10, selectedRowKeys: [], value: 3, selectedGroupKeysId: [], // 当前获取组键id complainArr: [], // 投诉工单 complainArrNo: [], // 不是投诉工单 城管工单 综合执法 comprehensiveArr: [], // 综合执法工单 comprehensiveArrNo: [], // 不是综合执法工单 是投诉工单 是城管工单 inspectorArr: [], // 城管工单 inspectorArrNo: [], // 不是城管工单 是综合执法工单 是投诉工单 complainDispatchIds: [], // 投诉工单 派遣 状态为2 complainDispatchNoIds: [], // 投诉工单 派遣 状态不为2 comprehensiveDispatchIds: [], // 综合执法 派遣 状态为2,3 comprehensiveDispatchNoIds: [], // 综合执法 派遣 状态不为2,3 visibleDispatch: false, CloseCaseIds: [], // 投诉工单 城管工单 综合执法 结案 状态为9 CloseCaseNoIds: [], // 投诉工单 城管工单 综合执法 结案 状态不为9 visibleCloseCase: false, }; start = () => { this.setState({ selectedRowKeys: [], }) }; onSelectChange = (selectedRowKeys) => { this.setState({ selectedRowKeys }); const selectedGroupKeysId = [];// 当前选中的数组id const complainArr = [];// 投诉工单 const complainArrNo = [];// 不是投诉工单 是城管工单 是综合执法 const comprehensiveArr = [];// 综合执法工单 const comprehensiveArrNo = [];// 不是综合执法工单 是投诉工单 是城管工单 const inspectorArr = [];// 城管工单 const inspectorArrNo = [];// 不是城管工单 是综合执法工单 是投诉工单 const complainDispatchIds = [];// 投诉工单 派遣 状态为2 const complainDispatchNoIds = [];// 投诉工单 派遣 状态不为2 const comprehensiveDispatchIds = [];// 综合执法 派遣 状态为2,3 const comprehensiveDispatchNoIds = [];// 综合执法 派遣 状态不为2,3 const CloseCaseIds = [];// 投诉工单 城管工单 综合执法 结案 状态为9 const CloseCaseNoIds = [];// 投诉工单 城管工单 综合执法 结案 状态不为9 for (let i = 0; i < selectedRowKeys.length; i++) { // 组键id const id = selectedRowKeys[i].split('/')[0].substring(0); // 工单类型 const workOrderSourceId = selectedRowKeys[i].workTypeDesc; // 工单编号 const workorderid = selectedRowKeys[i].split('/')[2].substring(0); // 当前状态 const workorderstatus = selectedRowKeys[i].status; selectedGroupKeysId.push(parseInt(id)); if (workOrderSourceId === '投诉工单') { complainArr.push(workOrderSourceId); } else { complainArrNo.push(workOrderSourceId); } if (workOrderSourceId === '街道自处置工单' || workOrderSourceId === '街城管工单') { inspectorArr.push(workOrderSourceId); } else { inspectorArrNo.push(workOrderSourceId); } if (workOrderSourceId === '街道综合执法工单' || workOrderSourceId === '区综合执法工单') { comprehensiveArr.push(workOrderSourceId); } else { comprehensiveArrNo.push(workOrderSourceId); } if (parseInt(workorderstatus) === 2) { complainDispatchIds.push(parseInt(workorderstatus)); } if (parseInt(workorderstatus) !== 2) { complainDispatchNoIds.push(parseInt(workorderstatus)); } if (parseInt(workorderstatus) === 2 || parseInt(workorderstatus) === 3) { comprehensiveDispatchIds.push(parseInt(workorderstatus)); } if (parseInt(workorderstatus) !== 2 && parseInt(workorderstatus) !== 3) { comprehensiveDispatchNoIds.push(parseInt(workorderstatus)); } if (parseInt(workorderstatus) === 9) { CloseCaseIds.push(parseInt(workorderstatus)); } if (parseInt(workorderstatus) !== 9) { CloseCaseNoIds.push(parseInt(workorderstatus)); } } this.setState({ selectedGroupKeysId, complainArr, complainArrNo, inspectorArr, inspectorArrNo, comprehensiveArr, comprehensiveArrNo, complainDispatchIds, complainDispatchNoIds, comprehensiveDispatchIds, comprehensiveDispatchNoIds, CloseCaseIds, CloseCaseNoIds, }); }; // 派遣 listDispatchCase = () => { this.setState({ visibleDispatch: true, }); }; handleOkDispatch = () => { // 投诉举报工单类型 if (this.state.complainArr.length > 0 && this.state.inspectorArr.length === 0 && this.state.comprehensiveArr.length === 0) { this.props.dispatch({ type: 'complain/dispatchFetch', payload: { goverIds: this.state.selectedGroupKeysId, int: 1, } }); } // 城管工单类型 if (this.state.inspectorArr.length > 0 && this.state.complainArr.length === 0 && this.state.comprehensiveArr.length === 0) { this.props.dispatch({ type: 'inspectors/dispatchFetch', payload: { flag: 2, orderIds: this.state.selectedGroupKeysId, int: 1, } }); } // 综合执法工单类型 if (this.state.comprehensiveArr.length > 0 && this.state.inspectorArr.length === 0 && this.state.complainArr.length === 0) { this.props.dispatch({ type: 'comprehensive/comprehensiveDispatchFetch', payload: { enforceIds: this.state.selectedGroupKeysId,// 数组 int: 1, }, }); } this.setState({ visibleDispatch: false, selectedGroupKeysId: [], complainArr: [], complainArrNo: [], inspectorArr: [], inspectorArrNo: [], comprehensiveArr: [], comprehensiveArrNo: [], complainDispatchIds: [], complainDispatchNoIds: [], comprehensiveDispatchIds: [], comprehensiveDispatchNoIds: [], CloseCaseIds: [], CloseCaseNoIds: [], selectedRowKeys: [], }); }; handleCancelDispatch = () => { this.setState({ visibleDispatch: false, selectedGroupKeysId: [], complainArr: [], complainArrNo: [], inspectorArr: [], inspectorArrNo: [], comprehensiveArr: [], comprehensiveArrNo: [], complainDispatchIds: [], complainDispatchNoIds: [], comprehensiveDispatchIds: [], comprehensiveDispatchNoIds: [], CloseCaseIds: [], CloseCaseNoIds: [], selectedRowKeys: [], }); }; // 结案 listCloseCase = () => { this.setState({ visibleCloseCase: true, }); }; handleOkCloseCase = () => { // 投诉举报工单类型 if (this.state.complainArr.length > 0 && this.state.inspectorArr.length === 0 && this.state.comprehensiveArr.length === 0) { this.props.dispatch({ type: 'complain/complainCloseCaseFetch', payload: { goverIds: this.state.selectedGroupKeysId, } }); } // 城管工单类型 if (this.state.inspectorArr.length > 0 && this.state.complainArr.length === 0 && this.state.comprehensiveArr.length === 0) { this.props.dispatch({ type: 'inspectors/intCloseCaseFetch', payload: { orderIds: this.state.selectedGroupKeysId, } }); } // 综合执法工单类型 if (this.state.comprehensiveArr.length > 0 && this.state.inspectorArr.length === 0 && this.state.complainArr.length === 0) { this.props.dispatch({ type: 'comprehensive/comprehensiveCloseCaseFetch', payload: { enforceIds: this.state.selectedGroupKeysId,// 数组 }, }); } this.setState({ visibleCloseCase: false, selectedGroupKeysId: [], complainArr: [], complainArrNo: [], inspectorArr: [], inspectorArrNo: [], comprehensiveArr: [], comprehensiveArrNo: [], complainDispatchIds: [], complainDispatchNoIds: [], comprehensiveDispatchIds: [], comprehensiveDispatchNoIds: [], CloseCaseIds: [], CloseCaseNoIds: [], selectedRowKeys: [], }); }; handleCancelCloseCase = () => { this.setState({ visibleCloseCase: false, selectedGroupKeysId: [], complainArr: [], complainArrNo: [], inspectorArr: [], inspectorArrNo: [], comprehensiveArr: [], comprehensiveArrNo: [], complainDispatchIds: [], complainDispatchNoIds: [], comprehensiveDispatchIds: [], comprehensiveDispatchNoIds: [], CloseCaseIds: [], CloseCaseNoIds: [], selectedRowKeys: [], }); }; componentDidMount() { // 列表 this.props.dispatch({ type: 'timing/timinglistFetch', payload: { page: 1, pageSize: 10, userRole: window.sessionStorage.userRole, type: 1 } }); // 社区 this.props.dispatch({ type: 'select/community', }); // 部门 department getdepartment this.props.dispatch({ type: 'select/getdepartment', }); // 状态 this.props.dispatch({ type: 'select/status', }); } ; // 分页 handleTableChange = (page, size) => { this.setState({ page, pageSize: size, }); this.props.dispatch({ type: 'timing/timinglistFetch', payload: Object.assign({ page, pageSize: size, userRole: window.sessionStorage.userRole, type: 1 }, this.state.formValues) }) }; // 查询 handleSearch = (e) => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (values.createdate) { values.createdate = moment(values.createdate).format('YYYY-MM-DD ') }; if (values.reporttime) { values.reporttime = moment(values.reporttime).format('YYYY-MM-DD ') } this.props.dispatch({ type: 'timing/timinglistFetchForCheck', payload: { page: 1, pageSize: 10, userRole: window.sessionStorage.userRole, type: 1, obj: { assistDepartment_S_EQ: values.sponsordepartment, createDate_D_GE: `${values.createdate}00:00:00`, createDate_D_LE: `${values.createdate}23:59:59`, incidentDate_D_GE: `${values.reporttime}00:00:00`, incidentDate_D_LE: `${values.reporttime}23:59:59`, ownCommunity_S_EQ: values.complainaddresscommunity, status_S_EQ: values.workOrderStatusId, workOrderId_S_EQ: values.workorderid } } }); this.setState({ page: 1, pageSize: 10, formValues: values, }) }); }; // 分页 类型 // onChangeRadio = (e) => { // this.props.dispatch({ // type: 'timing/timinglistFetch', // payload: { // page: 1, // pageSize: 10, // status: e.target.value, // userRole: window.sessionStorage.userRole, // type: 1 // } // }); // this.setState({ // page: 1, // pageSize: 10, // value: e.target.value, // }); // }; // onChangeRadio = e => { const { dispatch } = this.props; const { page, pageSize } = this.state; // 待处理 if (e.target.value == '1') { this.setState({ page: 1, pageSize: 10, value: e.target.value, }) if (window.sessionStorage.userRole == '1') { const obj = {}; obj.statusDesc_S_EQ = "待审核"; dispatch({ type: 'timing/timinglistFetch', payload: { page: 1, pageSize: 10, userRole: window.sessionStorage.userRole, type: 1, obj }, }); // this.setState({ // page: 1, // pageSize: 10, // value: e.target.value, // callback: res => { // if (res) { // if (res.retCode == 1) { // let w = res.list.filter(item => item.isExamine == '1').filter(item => item.status == '2'); // this.setState({ // dataSource: w, // totalNumber: w.length, // value: e.target.value, // }); // } // } // }, // }); } if (window.sessionStorage.userRole == '2') { const obj = {}; obj.status_S_NE = "1"; obj.statusDesc_S_IN = ['待派遣', '处置反馈完毕二级']; dispatch({ type: 'timing/timinglistFetch', payload: { page: 1, pageSize: 10, userRole: window.sessionStorage.userRole, type: 1, obj }, // callback: res => { // if (res) { // if (res.retCode == 1) { // let w = res.list.filter(item => item.status == '2' || item.status == '3' || item.status == '9' || (item.status == '5' && item.isReview == "1")); // this.setState({ // dataSource: w, // totalNumber: w.length, // value: e.target.value, // }); // } // } // }, }); } if (window.sessionStorage.userRole == '3') { const obj = {}; obj.statusDesc_S_IN = ['待派遣', '处置反馈完毕二级']; dispatch({ type: 'timing/timinglistFetch', payload: { page: 1, pageSize: 10, userRole: window.sessionStorage.userRole, type: 1, obj }, // callback: res => { // if (res) { // if (res.retCode == 1) { // let w = res.list.filter(item => item.isArrangeDesc == "需安排" || item.isAuditDesc == "需审核"); // this.setState({ // dataSource: w, // totalNumber: w.length, // value: e.target.value, // }); // } // } // }, }); } if (window.sessionStorage.userRole == '4') { const obj = {}; obj.status_S_IN = ['待上报', '待处置']; dispatch({ type: 'timing/timinglistFetch', payload: { page: 1, pageSize: 10, userRole: window.sessionStorage.userRole, type: 1, obj }, // callback: res => { // if (res) { // if (res.retCode == 1) { // let w = res.list.filter(item => item.status == '1' || (item.status == '5' && item.isReview != "1")); // this.setState({ // dataSource: w, // totalNumber: w.length, // value: e.target.value, // }); // } // } // }, }); } } // 已处理 if (e.target.value == '2') { if (window.sessionStorage.userRole == '1') { const obj = {}; obj.statusDesc_S_IN = ['待派遣', '已结案', '废案', '删除'] dispatch({ type: 'timing/timinglistFetch', payload: { page: 1, pageSize: 10, userRole: window.sessionStorage.userRole, type: 1, obj }, }); this.setState({ page: 1, pageSize: 10, value: e.target.value, }); } if (window.sessionStorage.userRole == '2') { const obj = {}; obj.statusDesc_S_IN = ['处置反馈完毕', '已结案', '废案']; dispatch({ type: 'timing/timinglistFetch', payload: { page: 1, pageSize: 10, userRole: window.sessionStorage.userRole, type: 1, obj }, }); this.setState({ page: 1, pageSize: 10, value: e.target.value, }); } if (window.sessionStorage.userRole == '3') { const obj = {}; dispatch({ type: 'timing/timinglistFetch', payload: { page: 1, pageSize, id: userRole, obj, }, callback: res => { if (res) { if (res.retCode == 1) { const w = res.list.filter(item => item.isArrangeDesc != "需安排" && item.isAuditDesc != "需审核"); this.setState({ dataSource: w, totalNumber: w.length, value: e.target.value, }); } } }, }); } if (window.sessionStorage.userRole == '4') { const obj = {}; obj.statusDesc_S_S_NE = "待上报"; dispatch({ type: 'timing/timinglistFetch', payload: { page: 1, pageSize: 10, userRole: window.sessionStorage.userRole, type: 1, obj }, // callback: res => { // if (res) { // if (res.retCode == 1) { // let w = res.list.filter(item => item.status != '1' && (item.status == '5' && item.isReview == "1")) // this.setState({ // dataSource: w, // totalNumber: w.length, // value: e.target.value, // }); // } // } // }, }); } } // 全部 if (e.target.value == '3') { this.props.dispatch({ type: 'timing/timinglistFetch', payload: { page: 1, pageSize: 10, userRole: window.sessionStorage.userRole, type: 1 } }); this.setState({ page: 1, pageSize: 10, value: e.target.value, }); } }; // 重置 handleFormReset = () => { const { form, dispatch } = this.props; form.resetFields(); dispatch({ type: 'timing/timinglistFetch', payload: { page: 1, pageSize: 10, userRole: window.sessionStorage.userRole, type: 1, } }); this.setState({ page: 1, pageSize: 10, formValues: {}, value: 3 }) }; // 定时设置 timingSetting = () => { this.props.history.push('/workOrder/intelligentize/timing/statistics'); }; render() { const { getFieldDecorator } = this.props.form; const { selectedRowKeys, page, pageSize, complainArr, complainArrNo, complainDispatchIds, complainDispatchNoIds, inspectorArr, inspectorArrNo, comprehensiveArr, comprehensiveArrNo, comprehensiveDispatchIds, comprehensiveDispatchNoIds, CloseCaseIds, CloseCaseNoIds } = this.state; const { timing, select, complain, inspectors, comprehensive } = this.props; const { timingList } = timing; const { communityList, departmentList, statusList } = select; const disableDispatch = !((complainArr.length > 0 && complainArrNo.length === 0 && complainDispatchIds.length > 0 && complainDispatchNoIds.length === 0) || (inspectorArr.length > 0 && inspectorArrNo.length === 0 && complainDispatchIds.length > 0 && complainDispatchNoIds.length === 0) || (comprehensiveArr.length > 0 && comprehensiveArrNo.length === 0 && comprehensiveDispatchIds.length > 0 && comprehensiveDispatchNoIds.length === 0)) const disableCloseCase = !((complainArr.length > 0 && complainArrNo.length === 0 && CloseCaseIds.length > 0 && CloseCaseNoIds.length === 0) || (inspectorArr.length > 0 && inspectorArrNo.length === 0 && CloseCaseIds.length > 0 && CloseCaseNoIds.length === 0) || (comprehensiveArr.length > 0 && comprehensiveArrNo.length === 0 && CloseCaseIds.length > 0 && CloseCaseNoIds.length === 0)) const that = this; const url = '/workOrder/intelligentize/timing/detail'; const rowSelection = { selectedRowKeys, onChange: this.onSelectChange, }; const columns = [ { title: '工单类型', dataIndex: 'workTypeDesc', }, // { // title: '剩余时间', // dataIndex: 'age', // render: (text, record) => ( // <span>{residue(record.deadline)}</span> // ) // }, { title: '工单编号', dataIndex: 'workOrderId', render: (text, record) => { if (record.workType == '1') { // 城管工单 return ( <Link to={`/workOrder/department/inspectors/detail/${record.workOrderId}/${sessionStorage.getItem('userRole')}/0`}>{text}</Link> ) } if (record.workType == '2') { // 综合执法工单 return ( <Link to={`/workOrder/department/comprehensive/detail/${record.workOrderId}/${sessionStorage.getItem('userRole')}/0`}>{text}</Link> ) } if (record.workType == '3') { // 投诉工单 return ( <Link to={`/workOrder/department/complain/detail/${record.workOrderId}/${sessionStorage.getItem('userRole')}/0`}>{text}</Link> ) } }, }, { title: '当前状态', dataIndex: 'statusDesc', }, { title: '事发时间', dataIndex: 'incidentDate', }, { title: '所属社区', dataIndex: 'ownCommunityDesc', }, { title: '创建时间', dataIndex: 'createDate', }, { title: '主办部门', dataIndex: 'assistDepartmentDesc', }, ]; return ( <div id="listTitleContent"> <Breadcrumb separator=">"> <span id="breadcrumbIcon" /> <Breadcrumb.Item>首页</Breadcrumb.Item> <Breadcrumb.Item href="">智能生成</Breadcrumb.Item> <Breadcrumb.Item href="">定时生成</Breadcrumb.Item> </Breadcrumb> <div id="tableForm"> <h3 id="listTitle">定时生成</h3> <Form onSubmit={this.handleSearch} layout="inline"> <Row gutter={{ md: 8, lg: 24, xl: 48 }}> <Col md={6} sm={8}> <FormItem label="工单编号"> {getFieldDecorator('workorderid')( <Input placeholder="请输入" /> )} </FormItem> </Col> <Col md={6} sm={8}> <FormItem label="状态"> {getFieldDecorator('workOrderStatusId')( <Select placeholder="请选择" allowClear> {statusList.map((val) => { return ( <Select.Option key={val.id} value={val.parentId}>{val.desp}</Select.Option> ) })} </Select> )} </FormItem> </Col> <Col md={6} sm={8}> <FormItem label="所属社区"> {getFieldDecorator('complainaddresscommunity')( <Select placeholder="请选择" allowClear> {communityList.map((val) => { return ( <Select.Option key={val.id} value={val.code}>{val.desp}</Select.Option> ) })} </Select> )} </FormItem> </Col> <Col md={6} sm={8}> <FormItem label="创建时间"> {getFieldDecorator('createdate')( <DatePicker placeholder="请输入" style={{ width: '100%' }} /> )} </FormItem> </Col> <Col md={6} sm={8}> <FormItem label="主办部门"> {getFieldDecorator('sponsordepartment')( <Select placeholder="请选择" allowClear> {departmentList.map((val) => { return ( <Select.Option key={val.id} value={val.orgCode}>{val.orgName}</Select.Option> ) })} </Select> )} </FormItem> </Col> <Col md={6} sm={8}> <FormItem label="事发时间"> {getFieldDecorator('reporttime')( <DatePicker placeholder="请选择时间" format="YYYY-MM-DD" style={{ width: '100%' }} /> )} </FormItem> </Col> <Col md={12} sm={16} style={{ textAlign: 'right' }}> <Button type="primary" htmlType="submit"> 查询 </Button> <Button id="buttonReset" style={{ marginRight: 0, marginLeft: 16 }} onClick={this.handleFormReset}> 重置 </Button> </Col> </Row> </Form> <div id="listOperator"> <Button type="primary" disabled={disableCloseCase} onClick={this.listCloseCase}>结案</Button> <Button type="primary" disabled={disableDispatch} onClick={this.listDispatchCase}>派遣</Button> <Button type="primary" onClick={this.timingSetting.bind(this)}>定时设置</Button> </div> </div> <div id="listTable"> <Table rowSelection={rowSelection} columns={columns} dataSource={timingList.list} // rowKey='ids' // return `${record.workOrderId}/${record.workOrderId}2/${record.workOrderId}3/${record.workOrderId}4`}} pagination={{ current: page, pageSize, onShowSizeChange(current, pageSize) { that.handleTableChange(current, pageSize); }, onChange(current, pageSize) { that.handleTableChange(current, pageSize); }, total: timingList.total, showTotal: total => `共 ${total} 条数据`, size: 'small', showSizeChanger: true, showQuickJumper: true, pageSizeOptions: ['10', '15', '20'] }} /> </div> <div style={{ width: 400, position: 'relative', top: '-80px', left: '50px', display: 'none' }}> <RadioGroup onChange={this.onChangeRadio} value={this.state.value}> <Radio value={1}>待处理</Radio> <Radio value={2}>已处理</Radio> <Radio value={3}>全部</Radio> </RadioGroup> </div> <Modal title="派遣" visible={this.state.visibleDispatch} onOk={this.handleOkDispatch} onCancel={this.handleCancelDispatch} > <p>请确定是否派遣</p> </Modal> <Modal title="结案" visible={this.state.visibleCloseCase} onOk={this.handleOkCloseCase} onCancel={this.handleCancelCloseCase} > <p>请确定是否派遣</p> </Modal> </div> ); } } export default Workplace;
JuntingLiu/karang
src/components/Icon/icons/status/cancelled.js
import React from 'react'; import createSVGIcon from '../utils/createSVGIcon'; const cancelled = createSVGIcon( <g> <rect fill="none" width="217" height="217" /> <g> <path fill="none" d="M150.3,162.62l-.5-.42A5,5,0,0,0,150.3,162.62Z" /> <path d="M150.35,162.67l0,0,0,0Z" /> <path d="M155.84,155.52,133.33,133l22.83-22.84a4.5,4.5,0,1,0-6.36-6.37h0L127,126.65l-22.8-22.8v0a4.51,4.51,0,0,0-6.36,0,4.42,4.42,0,0,0-.08,6.29L120.64,133,97.8,155.83a4.5,4.5,0,0,0,6.36,6.37L127,139.35l23.33,23.29a4.5,4.5,0,0,0,5.83-6.81Z" /> <polygon points="97.78 155.86 97.8 155.83 97.8 155.83 97.78 155.86" /> <polygon points="104.16 162.2 104.16 162.2 104.12 162.24 104.16 162.2" /> </g> <path d="M195.9,53.74c0-.07-.05-.13-.07-.21a4.64,4.64,0,0,0-.23-.64l-.16-.27a4.58,4.58,0,0,0-.31-.46l-.21-.25a4.11,4.11,0,0,0-.52-.45l-.16-.14a4.08,4.08,0,0,0-.77-.4L109.55,18.54a6.82,6.82,0,0,0-2.21-.54,1.94,1.94,0,0,0-.66.11L24,49.57,24,50l-1.12.44a1.93,1.93,0,0,0-.28.22l-.07.18-.31.22a1.87,1.87,0,0,1-.38.35,6.2,6.2,0,0,0-.5.47l-.19.24a6.15,6.15,0,0,0-.38.57c0,.06-.07.12-.1.19a4.55,4.55,0,0,0-.25.67c0,.07,0,.14-.06.22s-.09.35-.15.53-.05.22-.07.25c0,.25-.11.54-.11.82V161.65a4.07,4.07,0,0,0,2.65,3.71l83.9,32.36.13,0,.34.08.31.09a4.11,4.11,0,0,0,.77.08,4.87,4.87,0,0,0,.75-.07l.33-.1.36-.1,83.91-32.37a3.94,3.94,0,0,0,2.53-3.71V54.57A3.77,3.77,0,0,0,195.9,53.74Zm-14.9.89L108.12,82.74,77.2,70.81,150.08,42.7ZM108.12,26.51,139,38.44,66.16,66.55,35.24,54.63ZM187,156.92l-74,29.33-9,0L29,156.93V62.45L62,75.53v46.05c0,2,2.15,4,4.5,4s4.5-2,4.5-4V78.63l33,13.08,9,0L187,62.4Z" /> </g>, 'Cancelled' ); export default cancelled;
kikislater/micmac
src/uti_image/Digeo/Times.inline.h
// this file should be included by Times.h solely //---------------------------------------------------------------------- // methods of class Times //---------------------------------------------------------------------- inline Times::~Times(){} //---------------------------------------------------------------------- // methods of class NoTimes //---------------------------------------------------------------------- inline double NoTimes::stop( const char *i_name ){ return 0.; } inline void NoTimes::start(){} inline void NoTimes::clear(){} //---------------------------------------------------------------------- // methods of class MapTimes::Record //---------------------------------------------------------------------- inline MapTimes::Record::Record(){} //---------------------------------------------------------------------- // methods of class MapTimes //---------------------------------------------------------------------- inline void MapTimes::clear() { mRecords.clear(); } inline double MapTimes::totalTime() const { return mRecords.begin()->totalTime(); } #ifndef ELISE_unix inline Timer::Timer():mRecordedTime(getTime()){} inline void Timer::reinit(){ mRecordedTime = getTime(); } inline double Timer::uval(){ return getTime()-mRecordedTime; } #endif
ezLeaks/backdoored
com/fasterxml/jackson/core/JsonPointer.java
package com.fasterxml.jackson.core; import com.fasterxml.jackson.core.io.*; public class JsonPointer { public static final char SEPARATOR = '/'; protected static final JsonPointer EMPTY; protected final JsonPointer _nextSegment; protected volatile JsonPointer _head; protected final String _asString; protected final String _matchingPropertyName; protected final int _matchingElementIndex; protected JsonPointer() { super(); this._nextSegment = null; this._matchingPropertyName = ""; this._matchingElementIndex = -1; this._asString = ""; } protected JsonPointer(final String a1, final String a2, final JsonPointer a3) { super(); this._asString = a1; this._nextSegment = a3; this._matchingPropertyName = a2; this._matchingElementIndex = _parseIndex(a2); } protected JsonPointer(final String a1, final String a2, final int a3, final JsonPointer a4) { super(); this._asString = a1; this._nextSegment = a4; this._matchingPropertyName = a2; this._matchingElementIndex = a3; } public static JsonPointer compile(final String a1) throws IllegalArgumentException { if (a1 == null || a1.length() == 0) { return JsonPointer.EMPTY; } if (a1.charAt(0) != '/') { throw new IllegalArgumentException("Invalid input: JSON Pointer expression must start with '/': \"" + a1 + "\""); } return _parseTail(a1); } public static JsonPointer valueOf(final String a1) { return compile(a1); } public static JsonPointer forPath(JsonStreamContext v-3, final boolean v-2) { if (v-3 == null) { return JsonPointer.EMPTY; } if (!v-3.hasPathSegment() && (!v-2 || !v-3.inRoot() || !v-3.hasCurrentIndex())) { v-3 = v-3.getParent(); } JsonPointer jsonPointer = null; while (v-3 != null) { if (v-3.inObject()) { String a1 = v-3.getCurrentName(); if (a1 == null) { a1 = ""; } jsonPointer = new JsonPointer(_fullPath(jsonPointer, a1), a1, jsonPointer); } else if (v-3.inArray() || v-2) { final int a2 = v-3.getCurrentIndex(); final String v1 = String.valueOf(a2); jsonPointer = new JsonPointer(_fullPath(jsonPointer, v1), v1, a2, jsonPointer); } v-3 = v-3.getParent(); } if (jsonPointer == null) { return JsonPointer.EMPTY; } return jsonPointer; } private static String _fullPath(final JsonPointer a2, final String v1) { if (a2 == null) { final StringBuilder a3 = new StringBuilder(v1.length() + 1); a3.append('/'); _appendEscaped(a3, v1); return a3.toString(); } final String v2 = a2._asString; final StringBuilder v3 = new StringBuilder(v1.length() + 1 + v2.length()); v3.append('/'); _appendEscaped(v3, v1); v3.append(v2); return v3.toString(); } private static void _appendEscaped(final StringBuilder v-2, final String v-1) { for (int a2 = 0, v1 = v-1.length(); a2 < v1; ++a2) { final char a3 = v-1.charAt(a2); if (a3 == '/') { v-2.append("~1"); } else if (a3 == '~') { v-2.append("~0"); } else { v-2.append(a3); } } } public boolean matches() { return this._nextSegment == null; } public String getMatchingProperty() { return this._matchingPropertyName; } public int getMatchingIndex() { return this._matchingElementIndex; } public boolean mayMatchProperty() { return this._matchingPropertyName != null; } public boolean mayMatchElement() { return this._matchingElementIndex >= 0; } public JsonPointer last() { JsonPointer v1 = this; if (v1 == JsonPointer.EMPTY) { return null; } JsonPointer v2; while ((v2 = v1._nextSegment) != JsonPointer.EMPTY) { v1 = v2; } return v1; } public JsonPointer append(final JsonPointer a1) { if (this == JsonPointer.EMPTY) { return a1; } if (a1 == JsonPointer.EMPTY) { return this; } String v1 = this._asString; if (v1.endsWith("/")) { v1 = v1.substring(0, v1.length() - 1); } return compile(v1 + a1._asString); } public boolean matchesProperty(final String a1) { return this._nextSegment != null && this._matchingPropertyName.equals(a1); } public JsonPointer matchProperty(final String a1) { if (this._nextSegment != null && this._matchingPropertyName.equals(a1)) { return this._nextSegment; } return null; } public boolean matchesElement(final int a1) { return a1 == this._matchingElementIndex && a1 >= 0; } public JsonPointer matchElement(final int a1) { if (a1 != this._matchingElementIndex || a1 < 0) { return null; } return this._nextSegment; } public JsonPointer tail() { return this._nextSegment; } public JsonPointer head() { JsonPointer v1 = this._head; if (v1 == null) { if (this != JsonPointer.EMPTY) { v1 = this._constructHead(); } this._head = v1; } return v1; } @Override public String toString() { return this._asString; } @Override public int hashCode() { return this._asString.hashCode(); } @Override public boolean equals(final Object a1) { return a1 == this || (a1 != null && a1 instanceof JsonPointer && this._asString.equals(((JsonPointer)a1)._asString)); } private static final int _parseIndex(final String v-2) { final int length = v-2.length(); if (length == 0 || length > 10) { return -1; } char v0 = v-2.charAt(0); if (v0 <= '0') { return (length == 1 && v0 == '0') ? 0 : -1; } if (v0 > '9') { return -1; } for (int a1 = 1; a1 < length; ++a1) { v0 = v-2.charAt(a1); if (v0 > '9' || v0 < '0') { return -1; } } if (length == 10) { final long v2 = NumberInput.parseLong(v-2); if (v2 > 0L) { return -1; } } return NumberInput.parseInt(v-2); } protected static JsonPointer _parseTail(final String v-1) { final int v0 = v-1.length(); int v2 = 1; while (v2 < v0) { final char a1 = v-1.charAt(v2); if (a1 == '/') { return new JsonPointer(v-1, v-1.substring(1, v2), _parseTail(v-1.substring(v2))); } ++v2; if (a1 == '~' && v2 < v0) { return _parseQuotedTail(v-1, v2); } } return new JsonPointer(v-1, v-1.substring(1), JsonPointer.EMPTY); } protected static JsonPointer _parseQuotedTail(final String a2, int v1) { final int v2 = a2.length(); final StringBuilder v3 = new StringBuilder(Math.max(16, v2)); if (v1 > 2) { v3.append(a2, 1, v1 - 1); } _appendEscape(v3, a2.charAt(v1++)); while (v1 < v2) { final char a3 = a2.charAt(v1); if (a3 == '/') { return new JsonPointer(a2, v3.toString(), _parseTail(a2.substring(v1))); } ++v1; if (a3 == '~' && v1 < v2) { _appendEscape(v3, a2.charAt(v1++)); } else { v3.append(a3); } } return new JsonPointer(a2, v3.toString(), JsonPointer.EMPTY); } protected JsonPointer _constructHead() { final JsonPointer v1 = this.last(); if (v1 == this) { return JsonPointer.EMPTY; } final int v2 = v1._asString.length(); final JsonPointer v3 = this._nextSegment; return new JsonPointer(this._asString.substring(0, this._asString.length() - v2), this._matchingPropertyName, this._matchingElementIndex, v3._constructHead(v2, v1)); } protected JsonPointer _constructHead(final int a1, final JsonPointer a2) { if (this == a2) { return JsonPointer.EMPTY; } final JsonPointer v1 = this._nextSegment; final String v2 = this._asString; return new JsonPointer(v2.substring(0, v2.length() - a1), this._matchingPropertyName, this._matchingElementIndex, v1._constructHead(a1, a2)); } private static void _appendEscape(final StringBuilder a1, char a2) { if (a2 == '0') { a2 = '~'; } else if (a2 == '1') { a2 = '/'; } else { a1.append('~'); } a1.append(a2); } static { EMPTY = new JsonPointer(); } }
EveningMoon/Balance
app/src/main/java/com/emoon/balance/Fragment/BaseFragment.java
package com.emoon.balance.Fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * Base fragment created to be extended by every fragment that uses Realm in this application. * This class handles the closing and starting of realms. * * @author <NAME> */ public abstract class BaseFragment extends Fragment { private static String TAG = "BaseFragment"; protected View view; protected Fragment instance; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(TAG, "onCreateView"); view = inflater.inflate(getFragmentLayout(), container, false); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.d(TAG, "onActivityCreated"); init(); instance = this; } /** * Every fragment has to inflate a layout in the onCreateView method. Added this method to * avoid duplicate all the inflate code in every fragment. You only have to return the layout to * inflate in this method when extends BaseFragment. */ protected abstract int getFragmentLayout(); /** * Every fragment should override this function as it should be where other initialization * occurs once only in the lifecycle. * Note: I would put init in the onStart function but it will call multiple times when the user * comes back into the fragment which is unnecessary. */ protected abstract void init(); }
kcwiakala/algo
src/graphs/Johnson.cpp
<reponame>kcwiakala/algo #include <list> #include <gtest/gtest.h> #include <gmock/gmock.h> #include <Graph.hpp> #include <Matrix.hpp> namespace algo { namespace johnson { constexpr int MAX_INT = std::numeric_limits<int>::max(); struct Graph: public GenericGraph<WeightedEdge> { Graph(size_t s): GenericGraph(s) {} VerticeList bellmanFord(int s, const Graph& g) { VerticeList distance(g.size, MAX_INT); distance[s] = 0; for(int i=0; i<g.size-1; ++i) { for(int u=0; u<g.size; ++u) { if(distance[u] == MAX_INT) { continue; } for(const auto& e: g.adjacency[u]) { int v = e.to; distance[v] = std::min(distance[v], distance[u] + e.weight); } } } // skip cycle check return distance; } auto dijkstra(int s, const Graph& g) { Flags onHeap(g.size, false); Flags visited(g.size, false); VerticeList distance(g.size, MAX_INT); VerticeList parent(g.size, -1); distance[s] = 0; auto comp = [&distance](int v1, int v2) { return distance[v1] > distance[v2]; }; std::vector<int> heap; heap.push_back(s); onHeap[s] = true; while(!heap.empty()) { int u = heap.front(); std::pop_heap(heap.begin(), heap.end()); heap.pop_back(); onHeap[u] = false; visited[u] = true; bool rebuildHeap = false; for(const auto& e: g.adjacency[u]) { const int v = e.to; if(!visited[v]) { int aux = distance[u] + e.weight; if(aux < distance[v]) { parent[v] = u; distance[v] = aux; if(onHeap[v]) { rebuildHeap = true; } else { heap.push_back(v); std::push_heap(heap.begin(), heap.end()); onHeap[v] = true; } } } } if(rebuildHeap) { std::make_heap(heap.begin(), heap.end()); } } return std::make_pair(distance, parent); } auto johnson() { Graph g(size+1); std::copy(adjacency.begin(), adjacency.end(), g.adjacency.begin()); int s = size; for(int i=0; i<size; ++i) { g.connect(s, i, 0); } VerticeList d = bellmanFord(s, g); // re-weight for(int u=0; u<size; ++u) { for(auto& e: g.adjacency[u]) { const int v = e.to; e.weight = e.weight + d[u] - d[v]; } } Matrix<int> D(size, size, MAX_INT); Matrix<int> P(size, size, -1); for(int u=0; u<size; ++u) { auto dp = dijkstra(u, g); for(int v=0; v<size; ++v) { D(u,v) = dp.first[v] + d[v] - d[u]; P(u,v) = dp.second[v]; } } return std::make_pair(D,P); } }; auto path(int i, int j, const Matrix<int>& parent) { std::list<int> result; result.push_front(j); int p = j; while(p != i) { p = parent(i,p); result.push_front(p); } return result; } TEST(FloydWarshall, test1) { Graph g(5); g.connect(0,1,3); g.connect(0,2,8); g.connect(0,4,-4); g.connect(1,3,1); g.connect(1,4,7); g.connect(2,1,4); g.connect(3,0,2); g.connect(3,2,-5); g.connect(4,3,6); auto result = g.johnson(); const auto& dist = result.first; const auto& parent = result.second; for(int i=0; i<dist.width(); ++i) { EXPECT_EQ(dist(i,i), 0); } for(int i=0; i<parent.width(); ++i) { EXPECT_EQ(parent(i,i), -1); } // Path 4-1: 4 -> 3 -> 2 -> 1 EXPECT_EQ(dist(4,1), 5); auto p = path(4,1, parent); EXPECT_THAT(p.size(), testing::Eq(4)); EXPECT_THAT(p, testing::ElementsAre(4,3,2,1)); } } // namespace johnson } // namespace algo
pulsar-chem/BPModule
lib/systems/alpha-d-talopyranose.py
import pulsar as psr def load_ref_system(): """ Returns alpha-d-talopyranose as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" C 1.4128 0.6971 0.9470 C 1.7413 0.1005 -0.4384 O 2.0101 -1.2922 -0.3022 C 0.5697 0.2774 -1.4272 O 0.7796 -0.5454 -2.5759 C -0.7693 -0.1819 -0.7974 O -0.7332 -1.6153 -0.6448 C -0.9954 0.4230 0.6002 C -2.0977 -0.2940 1.4034 O -3.3557 0.3104 1.0978 O 0.1586 0.2842 1.4664 O 1.3861 2.1047 0.7536 H -1.2119 1.5138 0.5051 H 2.1198 0.3978 1.7515 H 2.6938 0.5205 -0.8405 H 0.5048 1.3177 -1.8186 H -1.6209 0.0665 -1.4717 H 1.0754 2.5663 1.5633 H 1.1967 -1.7541 0.0754 H -2.1160 -1.3810 1.2067 H -1.9685 -0.1109 2.4899 H -0.6218 -2.0228 -1.5420 H 1.4115 -1.2846 -2.3547 H -3.7166 -0.0524 0.2632 """)
ahenaobuild/redluv
utils/metric/metric.go
// (c) 2021, <NAME>, Inc. All rights reserved. // See the file LICENSE for licensing terms. package metric import ( "fmt" "github.com/prometheus/client_golang/prometheus" ) func NewNanosecondsLatencyMetric(namespace, name string) prometheus.Histogram { return prometheus.NewHistogram(prometheus.HistogramOpts{ Namespace: namespace, Name: name, Help: fmt.Sprintf("Latency of a %s call in nanoseconds", name), Buckets: NanosecondsBuckets, }) }
preranaandure/wildlifecompliance
wildlifecompliance/migrations/0188_auto_20190508_0853.py
<filename>wildlifecompliance/migrations/0188_auto_20190508_0853.py # -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-05-08 00:53 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wildlifecompliance', '0187_callemail_number'), ] operations = [ migrations.RemoveField( model_name='callemail', name='schema', ), migrations.AlterField( model_name='callemail', name='report_type', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='call_schema', to='wildlifecompliance.ReportType'), ), ]
hextor/astrofox
src/view/components/controls/PixelateControl.js
import React from 'react'; import { Control, Option } from 'components/editing'; import useEntity from 'components/hooks/useEntity'; const renderOptions = ['Square', 'Hexagon']; const minPixelSize = 2; const maxPixelSize = 240; export default function PixelateControl({ display, active }) { const { type, size } = display.properties; const onChange = useEntity(display); return ( <Control label="Pixelate" active={active} display={display} onChange={onChange}> <Option label="Type" type="select" name="type" items={renderOptions} value={type} /> <Option label="Size" type="number" name="size" value={size} min={minPixelSize} max={maxPixelSize} withRange withReactor /> </Control> ); }
GenSolutionRep/Note
src/main/java/com/gensolution/activity/vo/ActivityEvnMobileVo.java
<filename>src/main/java/com/gensolution/activity/vo/ActivityEvnMobileVo.java package com.gensolution.activity.vo; import java.util.List; import java.util.Map; public class ActivityEvnMobileVo { private String main_innb; private String updt_de; private List<Map<String, Object>> evn_list; public String getUpdt_de() { return updt_de; } public void setUpdt_de(String updt_de) { this.updt_de = updt_de; } public String getMain_innb() { return main_innb; } public void setMain_innb(String main_innb) { this.main_innb = main_innb; } public List<Map<String, Object>> getEvn_list() { return evn_list; } public void setEvn_list(List<Map<String, Object>> evn_list) { this.evn_list = evn_list; } }
BURAI-team/burai
src/burai/atoms/design/AtomsStyle.java
/* * Copyright (C) 2018 <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 burai.atoms.design; public enum AtomsStyle { BALL_STICK(0, "Ball & Stick"), BALL(1, "Ball"), STICK(2, "Stick"); private int id; private String label; private AtomsStyle(int id, String label) { this.id = id; this.label = label; } public int getId() { return this.id; } public static AtomsStyle getInstance(int id) { AtomsStyle[] atomsStyles = values(); if (atomsStyles == null || atomsStyles.length < 1) { return null; } for (AtomsStyle atomsStyle : atomsStyles) { if (atomsStyle != null && id == atomsStyle.getId()) { return atomsStyle; } } return null; } @Override public String toString() { return this.label; } }
jkuharev/ISOQuant
src/isoquant/kernel/plugin/gui/PluginList.java
<reponame>jkuharev/ISOQuant<gh_stars>0 package isoquant.kernel.plugin.gui; import isoquant.kernel.plugin.Plugin; import java.util.List; import javax.swing.JList; public class PluginList extends JList { private static final long serialVersionUID = 20110220L; public PluginList() { setCellRenderer(new PluginListCellRenderer()); } public PluginList(Plugin[] plugins) { this(); setListData( plugins ); } public PluginList(List<Plugin> plugins) { this(); setListData( plugins.toArray() ); } }
polar/busme-iphone-rubylib
lib/busme/api/marker_info.rb
module Api class MarkerInfo < MessageSpec attr_accessor :point attr_accessor :radius # feet attr_accessor :title attr_accessor :description attr_accessor :goUrl attr_accessor :goLabel attr_accessor :content attr_accessor :iconUrl attr_accessor :loaded attr_accessor :priority attr_accessor :seen attr_accessor :lastSeen attr_accessor :displayed attr_accessor :remindable attr_accessor :remindPeriod attr_accessor :remindTime def propList (super.propList) + %w( @point @radius @title @description @goUrl @goLabel @content @iconUrl @loaded @priority @seen @lastSeen @displayed @remindable @remindPeriod @remindTime ) end def initWithCoder1(decoder) super(decoder) self.point = decoder[:point] self.radius = decoder[:radius] self.title = decoder[:title] self.description = decoder[:description] self.goUrl = decoder[:goUrl] self.goLabel = decoder[:goLabel] self.content = decoder[:content] self.iconUrl = decoder[:iconUrl] self.loaded = decoder[:loaded] self.priority = decoder[:priority] self.seen = decoder[:seen] self.lastSeen = decoder[:lastSeen] self.displayed = decoder[:displayed] self.remindable = decoder[:remindable] self.remindPeriod = decoder[:remindPeriod] self.remindTime = decoder[:remindTime] self rescue Exception => boom puts "#{boom}" p boom.backtrace end def encodeWithCoder1(encoder) super(encoder) encoder[:point] = point encoder[:radius] = radius encoder[:title] = title encoder[:description] = description encoder[:goUrl] = goUrl encoder[:goLabel] = goLabel encoder[:content] = content encoder[:iconUrl] = iconUrl encoder[:loaded] = loaded encoder[:priority] = priority encoder[:seen] = seen encoder[:lastSeen] = lastSeen encoder[:displayed] = displayed encoder[:remindable] = remindable encoder[:remindPeriod] = remindPeriod encoder[:remindTime] = remindTime rescue Exception => boom puts "#{boom}" p boom.backtrace end def initialize super(nil,nil,nil) end def shouldBeSeen?(time) # markers don't have expiry times. #time < expiryTime && (!seen || (remindable && (remindTime ? remindTime < time : false))) # We are not seen implies it goes up. If it's been seen and it's no longer displayed, # then we should be displayed only if the remindTime has past. (!expiryTime || time < expiryTime) && (!seen || (displayed || remindable && (remindTime ? remindTime < time : false))) end # This is used for sorting. Basically if it is not seen or expired the time is # is basically high, so that it will come up at the end of the list and be # disposed of by the controller. If it has a later remindTime that will be sorted # appropriately. def nextTime(time = nil) time = Utils::Time.current if time.nil? if true # time < expiryTime if remindable && remindTime remindTime else time + 10 * 365 * 24 * 60 * 60 end else time + 10 * 365 * 24 * 60 * 60 end end def reset(time = nil) time = Utils::Time.current if time.nil? self.seen = false self.lastSeen = nil self.displayed = false self.remindTime = nil end def onDisplay(time) self.seen = true self.lastSeen = time self.displayed = true end def onDismiss(remind, time) self.displayed = false self.lastSeen = time if remind && remindable && remindPeriod self.remindTime = time + remindPeriod end end def loadParsedXML(tag) self.id = tag.attributes["id"] self.goUrl = tag.attributes["go_url"] self.iconUrl = tag.attributes["icon_url"] self.remindable = "true" == tag.attributes["remindable"] for m in tag.childNodes case m.name when "Title" self.title = m.text when "Content" self.content = m.text when "GoLabel" self.goLabel = m.text end end self.expiryTime = Time.at(tag.attributes["expiryTime"].to_i) if tag.attributes["expiryTime"] self.priority = tag.attributes["priority"].to_f self.remindPeriod = tag.attributes["remindPeriod"].to_i self.version = tag.attributes["version"].to_i lon = tag.attributes["lon"].to_f lat = tag.attributes["lat"].to_f self.point = Integration::GeoPoint.new(lat * 1E6, lon * 1E6) self.radius = tag.attributes["radius"].to_i self.loaded = true end end end
jiangzy1992/task
task11_bus-css/js/app.js
function lineHeight() { var height; var num; $('.con-nav ul li').each(function (index, value) { num = $(this).text().length; height = 160/num + "px"; $(this).css("line-height",height); }); } lineHeight();
552301/wotrd-cloud
wotrd-dynamic-datasource/src/main/java/com/wotrd/dydatasource/four/mapper/TUserMapper.java
<gh_stars>100-1000 package com.wotrd.dydatasource.four.mapper; import com.wotrd.dydatasource.four.domain.TUser; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; @Mapper @Repository public interface TUserMapper { /** * 根据组织ID和用户名字查询 * * @param orgId * @param userName * @return */ TUser selectByOrgIdAndUserName(@Param("orgId") String orgId, @Param("userName") String userName); int insert(TUser record); int insertSelective(TUser record); }
ToQuery/clever-framework
clever-framework-system/src/main/java/io/github/toquery/framework/system/service/ISysDictItemService.java
package io.github.toquery.framework.system.service; import io.github.toquery.framework.crud.service.AppBaseService; import io.github.toquery.framework.system.entity.SysDict; import io.github.toquery.framework.system.entity.SysDictItem; import java.util.List; /** * @author toquery * @version 1 */ public interface ISysDictItemService extends AppBaseService<SysDictItem> { List<SysDictItem> findByDictId(Long dictId); }
sparkoss/ccm
src/runtime/rpc/dbus/threadpoolexecutor.cpp
//========================================================================= // Copyright (C) 2018 The C++ Component Model(CCM) Open Source Project // // 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. //========================================================================= //========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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. //========================================================================= #include "threadpoolexecutor.h" #include "util/ccmlogger.h" #include <assert.h> #include <errno.h> #include <pthread.h> #include <signal.h> namespace ccm { //------------------------------------------------------------------------- ThreadPoolExecutor::Worker::Worker( /* [in] */ Runnable* task, /* [in] */ ThreadPoolExecutor* owner) : mThread(0) , mTask(task) , mOwner(owner) {} ECode ThreadPoolExecutor::Worker::Run() { return mTask->Run(); } //------------------------------------------------------------------------- AutoPtr<ThreadPoolExecutor> ThreadPoolExecutor::sInstance; Mutex ThreadPoolExecutor::sInstanceLock; AutoPtr<ThreadPoolExecutor> ThreadPoolExecutor::GetInstance() { { Mutex::AutoLock lock(sInstanceLock); if (sInstance == nullptr) { sInstance = new ThreadPoolExecutor(); } } return sInstance; } ECode ThreadPoolExecutor::RunTask( /* [in] */ Runnable* task) { AutoPtr<Worker> w = new Worker(task, this); { Mutex::AutoLock lock(w->mLock); pthread_attr_t threadAddr; pthread_attr_init(&threadAddr); pthread_attr_setdetachstate(&threadAddr, PTHREAD_CREATE_DETACHED); pthread_t thread; int ret = pthread_create(&thread, &threadAddr, ThreadPoolExecutor::ThreadEntry, (void*)w); if (ret != 0) { return E_RUNTIME_EXCEPTION; } w->mThread = thread; { Mutex::AutoLock lock(mMainLock); mWorkers.Add(w); } } return NOERROR; } ECode ThreadPoolExecutor::StopTask( /* [in] */ Runnable* task) { Mutex::AutoLock _l(mMainLock); for (Long i = 0; i < mWorkers.GetSize(); i++) { Worker* w = mWorkers.Get(i); if (w->mTask == task) { if (pthread_kill(w->mThread, SIGUSR2) == ESRCH) { Logger::E("ThreadPoolExecutor", "pthread_kill failed"); } mWorkers.Remove(i); break; } } return NOERROR; } void* ThreadPoolExecutor::ThreadEntry(void* arg) { AutoPtr<Worker> w = (Worker*)arg; { Mutex::AutoLock lock(w->mLock); assert(w->mThread != 0); } ECode ec = w->Run(); { ThreadPoolExecutor* executor = w->mOwner; Mutex::AutoLock lock(executor->mMainLock); for (Long i = 0; i < executor->mWorkers.GetSize(); ++i) { if (executor->mWorkers.Get(i) == w) { executor->mWorkers.Remove(i); break; } } } return reinterpret_cast<void*>(ec); } }
josephhyatt/learn_co
rails-amusement-park-v-000/app/controllers/application_controller.rb
<filename>rails-amusement-park-v-000/app/controllers/application_controller.rb class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception helper_method :current_user before_action :require_login, except: [:home, :new, :create] private def require_login unless logged_in? flash[:error] = "You must be logged in to do that" redirect_to root_path end end def logged_in? !!current_user end def current_user @user ||= User.find_by(id: session[:user_id]) if session[:user_id] end end
damongreen123/fpl-ccd-configuration
service/src/main/java/uk/gov/hmcts/reform/fpl/model/docmosis/DocmosisChild.java
package uk.gov.hmcts.reform.fpl.model.docmosis; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Builder; import lombok.Data; @Data @Builder @JsonInclude(JsonInclude.Include.NON_NULL) public class DocmosisChild { private final String name; private final String age; private final String gender; private final String dateOfBirth; private final String address; private final String livingSituation; private final String keyDates; private final String careAndContactPlan; private final String adoption; private final String placementOrderApplication; private final String placementCourt; private final String mothersName; private final String fathersName; private final String fathersResponsibility; private final String socialWorkerName; private final String socialWorkerTelephoneNumber; private final String additionalNeeds; private final String litigationIssues; private final String detailsHiddenReason; private final DocmosisBirthCertificate birthCertificate; }
Huawei-Ascend/modelzoo
built-in/TensorFlow/Official/nlp/Transformer_for_TensorFlow/noahnmt/utils/fp16_utils.py
# coding=utf-8 # Copyright <NAME>'s Ark Lab. import tensorflow as tf class DynamicLossScaler: def __init__(self, init_scale=2.**15, scale_factor=2., scale_window=2000): self.loss_scale = tf.get_variable( initializer=tf.constant_initializer(init_scale), trainable=False, shape=(), dtype=tf.float32, name="dls_loss_scale") self.scale_factor = tf.constant(scale_factor, dtype=tf.float32) self.scale_window = tf.constant(scale_window, dtype=tf.int64) self._iter = tf.get_variable( initializer=tf.constant_initializer(0), trainable=False, shape=(), dtype=tf.int64, name="dls_iter") self._last_overflow_iter = tf.get_variable( initializer=tf.constant_initializer(-1), trainable=False, shape=(), dtype=tf.int64, name="dls_last_overflow_iter") def update_scale(self, overflow): def _overflow_ops(): return tf.group(*[ tf.assign(self.loss_scale, self.loss_scale / self.scale_factor).op, tf.assign(self._last_overflow_iter, self._iter).op]) def _normal_ops(): def _update(): return tf.assign(self.loss_scale, self.loss_scale * self.scale_factor).op return tf.cond( tf.equal(tf.mod(self._iter - self._last_overflow_iter, self.scale_window), 0), _update, tf.no_op) op_ = tf.cond(overflow, _overflow_ops, _normal_ops) with tf.control_dependencies([op_]): return tf.assign_add(self._iter, 1).op @staticmethod def has_overflow(grad_norm): # detect inf and nan return tf.logical_or( tf.is_nan(grad_norm), tf.not_equal(grad_norm, grad_norm)) # if grad_norm == float('inf') or grad_norm != grad_norm: # return True # return False class FP16Helper(): """ TODO """ def __init__(self): # dynamically scale loss to reduce overflow self.scaler = DynamicLossScaler(init_scale=2.**7) self._fp32_params = [] self._fp16_params = [] self._init_op = None self._update_op = None def fp16_loss(self, loss): # dynamically rescale loss to stay in FP16 range return tf.cast(loss * self.scaler.loss_scale, dtype=tf.float16) def fp32_variables(self): return self._fp32_params # def create_init_op(self): # init_ops = [] # for _, var in gradvars: # fp32_v = tf.get_variable( # initializer=init_ops.zeros_initializer(var.dtype), # shape=var.get_shape(), # trainable=False, # dtype=tf.float32, # name="fp32/%s" %var.name) # self._fp32_params.append(fp32_v) # init_ops.append(tf.assign(fp32_v, tf.cast(var, dtype=tf.float32)).op) # return tf.group(*init_ops) def create_update_op(self): def _update_op(): init_ops = [] for v16, v32 in zip(self._fp16_params, self._fp32_params): with tf.device(v16.device): init_ops.append(tf.assign(v16, tf.cast(v32, dtype=tf.float16)).op) return tf.group(*init_ops) # if overflow, don't assign return tf.cond(self._overflow, tf.no_op, _update_op) def fp32_gradvars(self, gradvars, max_norm=None): gradients = [] for grad, var in gradvars: gradients.append(grad) with tf.device(var.device): # create fp32 variables fp32_v = tf.get_variable( initializer = tf.cast(var.initialized_value(), dtype=tf.float32), trainable=False, dtype=tf.float32, name="fp32_helper/%s" % var.op.name) self._fp32_params.append(fp32_v) self._fp16_params.append(var) # conver gradient to fp32 grads_fp32 = [] for grad in gradients: if isinstance(grad, tf.Tensor): grad = tf.cast(grad, dtype=tf.float32) elif isinstance(grad, tf.IndexedSlices): grad = tf.IndexedSlices( values=tf.cast(grad.values, dtype=tf.float32), indices=grad.indices, dense_shape=grad.dense_shape) else: raise ValueError("unknow gradient type") # undo effect of dynamic loss scaling on gradients # rescale grad = grad / self.scaler.loss_scale grads_fp32.append(grad) gradients = grads_fp32 # undo effect of dynamic loss scaling on gradients # rescale # gradients = [grad / self.scaler.loss_scale for grad in gradients] if max_norm: gradients, grad_norm = tf.clip_by_global_norm(gradients, max_norm) else: grad_norm = tf.global_norm(gradients) # detect overflow and adjust loss scale overflow = DynamicLossScaler.has_overflow(grad_norm) self._overflow = overflow update_scale_op = self.scaler.update_scale(overflow) with tf.control_dependencies([update_scale_op]): # if overflow, zero grads mask = 1. - tf.cast(overflow, dtype=tf.float32) gradients = [g * mask for g in gradients] return zip(gradients, self._fp32_params)
Koheron/koheron-sdk
server/templates/drivers_table.hpp
<reponame>Koheron/koheron-sdk<filename>server/templates/drivers_table.hpp<gh_stars>10-100 /// Autogenerated DO NOT EDIT /// /// (c) Koheron #ifndef __DRIVERS_TABLE_HPP__ #define __DRIVERS_TABLE_HPP__ #include <array> #include <tuple> #include <memory> #include <string_utils.hpp> #include <meta_utils.hpp> using driver_id = std::size_t; class NoDriver; class Server; {% for driver in drivers %} class {{ driver.objects[0]["type"] }}; {% endfor -%} constexpr driver_id device_num = {{ drivers|length + 2 }}; constexpr auto drivers_names = koheron::make_array( koheron::str_const("NoDriver"), koheron::str_const("Server"), {%- for driver in drivers -%} {% if not loop.last %} koheron::str_const("{{ driver.objects[0]['type'] }}"), {%- else %} koheron::str_const("{{ driver.objects[0]['type'] }}") {%- endif %} {%- endfor %} ); static_assert(std::tuple_size<decltype(drivers_names)>::value == device_num, ""); // Drivers are stored as unique_ptr ensuring single // instantiation of each driver. using drivers_tuple_t = std::tuple< {%- for driver in drivers -%} {% if not loop.last -%} std::unique_ptr<{{ driver.objects[0]['type'] }}>, {%- else -%} std::unique_ptr<{{ driver.objects[0]['type'] }}> {%- endif -%} {%- endfor -%} >; static_assert(std::tuple_size<drivers_tuple_t>::value == device_num - 2, ""); // Driver id from driver type template<class Driver> constexpr driver_id driver_id_of = Index_v<std::unique_ptr<Driver>, drivers_tuple_t> + 2; template<> constexpr driver_id driver_id_of<NoDriver> = 0; template<> constexpr driver_id driver_id_of<Server> = 1; // Driver type from driver id template<driver_id driver> using device_t = std::remove_reference_t<decltype(*std::get<driver - 2>(std::declval<drivers_tuple_t>()))>; #endif // __DRIVERS_TABLE_HPP__
arbarlow/account_service
account_service.pb.go
// Code generated by protoc-gen-go. // source: account_service.proto // DO NOT EDIT! /* Package account_service is a generated protocol buffer package. It is generated from these files: account_service.proto It has these top-level messages: Account ListAccountsRequest ListAccountsResponse GetByIdRequest GetByEmailRequest AuthenticateByEmailRequest GeneratePasswordTokenRequest GeneratePasswordTokenResponse ResetPasswordRequest ConfirmAccountRequest CreateAccountRequest UpdateAccountRequest DeleteAccountRequest */ package account_service import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import google_protobuf "github.com/golang/protobuf/ptypes/empty" import image_service "github.com/lileio/image_service" import ( context "golang.org/x/net/context" grpc "google.golang.org/grpc" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type Account struct { Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` Name string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` Email string `protobuf:"bytes,3,opt,name=email" json:"email,omitempty"` Images map[string]*image_service.Image `protobuf:"bytes,4,rep,name=images" json:"images,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` ConfirmToken string `protobuf:"bytes,5,opt,name=confirm_token,json=confirmToken" json:"confirm_token,omitempty"` PasswordResetToken string `protobuf:"bytes,6,opt,name=password_reset_token,json=passwordResetToken" json:"password_reset_token,omitempty"` Metadata map[string]string `protobuf:"bytes,7,rep,name=metadata" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` } func (m *Account) Reset() { *m = Account{} } func (m *Account) String() string { return proto.CompactTextString(m) } func (*Account) ProtoMessage() {} func (*Account) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *Account) GetId() string { if m != nil { return m.Id } return "" } func (m *Account) GetName() string { if m != nil { return m.Name } return "" } func (m *Account) GetEmail() string { if m != nil { return m.Email } return "" } func (m *Account) GetImages() map[string]*image_service.Image { if m != nil { return m.Images } return nil } func (m *Account) GetConfirmToken() string { if m != nil { return m.ConfirmToken } return "" } func (m *Account) GetPasswordResetToken() string { if m != nil { return m.PasswordResetToken } return "" } func (m *Account) GetMetadata() map[string]string { if m != nil { return m.Metadata } return nil } type ListAccountsRequest struct { PageSize int32 `protobuf:"varint,1,opt,name=page_size,json=pageSize" json:"page_size,omitempty"` PageToken string `protobuf:"bytes,2,opt,name=page_token,json=pageToken" json:"page_token,omitempty"` } func (m *ListAccountsRequest) Reset() { *m = ListAccountsRequest{} } func (m *ListAccountsRequest) String() string { return proto.CompactTextString(m) } func (*ListAccountsRequest) ProtoMessage() {} func (*ListAccountsRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *ListAccountsRequest) GetPageSize() int32 { if m != nil { return m.PageSize } return 0 } func (m *ListAccountsRequest) GetPageToken() string { if m != nil { return m.PageToken } return "" } type ListAccountsResponse struct { Accounts []*Account `protobuf:"bytes,1,rep,name=accounts" json:"accounts,omitempty"` NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken" json:"next_page_token,omitempty"` } func (m *ListAccountsResponse) Reset() { *m = ListAccountsResponse{} } func (m *ListAccountsResponse) String() string { return proto.CompactTextString(m) } func (*ListAccountsResponse) ProtoMessage() {} func (*ListAccountsResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *ListAccountsResponse) GetAccounts() []*Account { if m != nil { return m.Accounts } return nil } func (m *ListAccountsResponse) GetNextPageToken() string { if m != nil { return m.NextPageToken } return "" } type GetByIdRequest struct { Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` } func (m *GetByIdRequest) Reset() { *m = GetByIdRequest{} } func (m *GetByIdRequest) String() string { return proto.CompactTextString(m) } func (*GetByIdRequest) ProtoMessage() {} func (*GetByIdRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (m *GetByIdRequest) GetId() string { if m != nil { return m.Id } return "" } type GetByEmailRequest struct { Email string `protobuf:"bytes,1,opt,name=email" json:"email,omitempty"` } func (m *GetByEmailRequest) Reset() { *m = GetByEmailRequest{} } func (m *GetByEmailRequest) String() string { return proto.CompactTextString(m) } func (*GetByEmailRequest) ProtoMessage() {} func (*GetByEmailRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } func (m *GetByEmailRequest) GetEmail() string { if m != nil { return m.Email } return "" } type AuthenticateByEmailRequest struct { Email string `protobuf:"bytes,1,opt,name=email" json:"email,omitempty"` Password string `protobuf:"bytes,2,opt,name=password" json:"password,omitempty"` } func (m *AuthenticateByEmailRequest) Reset() { *m = AuthenticateByEmailRequest{} } func (m *AuthenticateByEmailRequest) String() string { return proto.CompactTextString(m) } func (*AuthenticateByEmailRequest) ProtoMessage() {} func (*AuthenticateByEmailRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } func (m *AuthenticateByEmailRequest) GetEmail() string { if m != nil { return m.Email } return "" } func (m *AuthenticateByEmailRequest) GetPassword() string { if m != nil { return m.Password } return "" } type GeneratePasswordTokenRequest struct { Email string `protobuf:"bytes,1,opt,name=email" json:"email,omitempty"` } func (m *GeneratePasswordTokenRequest) Reset() { *m = GeneratePasswordTokenRequest{} } func (m *GeneratePasswordTokenRequest) String() string { return proto.CompactTextString(m) } func (*GeneratePasswordTokenRequest) ProtoMessage() {} func (*GeneratePasswordTokenRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } func (m *GeneratePasswordTokenRequest) GetEmail() string { if m != nil { return m.Email } return "" } type GeneratePasswordTokenResponse struct { Token string `protobuf:"bytes,1,opt,name=token" json:"token,omitempty"` } func (m *GeneratePasswordTokenResponse) Reset() { *m = GeneratePasswordTokenResponse{} } func (m *GeneratePasswordTokenResponse) String() string { return proto.CompactTextString(m) } func (*GeneratePasswordTokenResponse) ProtoMessage() {} func (*GeneratePasswordTokenResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } func (m *GeneratePasswordTokenResponse) GetToken() string { if m != nil { return m.Token } return "" } type ResetPasswordRequest struct { Token string `protobuf:"bytes,1,opt,name=token" json:"token,omitempty"` Password string `protobuf:"bytes,2,opt,name=password" json:"password,omitempty"` } func (m *ResetPasswordRequest) Reset() { *m = ResetPasswordRequest{} } func (m *ResetPasswordRequest) String() string { return proto.CompactTextString(m) } func (*ResetPasswordRequest) ProtoMessage() {} func (*ResetPasswordRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} } func (m *ResetPasswordRequest) GetToken() string { if m != nil { return m.Token } return "" } func (m *ResetPasswordRequest) GetPassword() string { if m != nil { return m.Password } return "" } type ConfirmAccountRequest struct { Token string `protobuf:"bytes,1,opt,name=token" json:"token,omitempty"` } func (m *ConfirmAccountRequest) Reset() { *m = ConfirmAccountRequest{} } func (m *ConfirmAccountRequest) String() string { return proto.CompactTextString(m) } func (*ConfirmAccountRequest) ProtoMessage() {} func (*ConfirmAccountRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} } func (m *ConfirmAccountRequest) GetToken() string { if m != nil { return m.Token } return "" } type CreateAccountRequest struct { Account *Account `protobuf:"bytes,1,opt,name=account" json:"account,omitempty"` Password string `protobuf:"bytes,2,opt,name=password" json:"password,omitempty"` Image *image_service.ImageStoreRequest `protobuf:"bytes,3,opt,name=image" json:"image,omitempty"` } func (m *CreateAccountRequest) Reset() { *m = CreateAccountRequest{} } func (m *CreateAccountRequest) String() string { return proto.CompactTextString(m) } func (*CreateAccountRequest) ProtoMessage() {} func (*CreateAccountRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} } func (m *CreateAccountRequest) GetAccount() *Account { if m != nil { return m.Account } return nil } func (m *CreateAccountRequest) GetPassword() string { if m != nil { return m.Password } return "" } func (m *CreateAccountRequest) GetImage() *image_service.ImageStoreRequest { if m != nil { return m.Image } return nil } type UpdateAccountRequest struct { Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` Password string `protobuf:"bytes,2,opt,name=password" json:"password,omitempty"` Image *image_service.ImageStoreRequest `protobuf:"bytes,3,opt,name=image" json:"image,omitempty"` Account *Account `protobuf:"bytes,4,opt,name=account" json:"account,omitempty"` } func (m *UpdateAccountRequest) Reset() { *m = UpdateAccountRequest{} } func (m *UpdateAccountRequest) String() string { return proto.CompactTextString(m) } func (*UpdateAccountRequest) ProtoMessage() {} func (*UpdateAccountRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11} } func (m *UpdateAccountRequest) GetId() string { if m != nil { return m.Id } return "" } func (m *UpdateAccountRequest) GetPassword() string { if m != nil { return m.Password } return "" } func (m *UpdateAccountRequest) GetImage() *image_service.ImageStoreRequest { if m != nil { return m.Image } return nil } func (m *UpdateAccountRequest) GetAccount() *Account { if m != nil { return m.Account } return nil } type DeleteAccountRequest struct { Id string `protobuf:"bytes,1,opt,name=id" json:"id,omitempty"` } func (m *DeleteAccountRequest) Reset() { *m = DeleteAccountRequest{} } func (m *DeleteAccountRequest) String() string { return proto.CompactTextString(m) } func (*DeleteAccountRequest) ProtoMessage() {} func (*DeleteAccountRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{12} } func (m *DeleteAccountRequest) GetId() string { if m != nil { return m.Id } return "" } func init() { proto.RegisterType((*Account)(nil), "account_service.Account") proto.RegisterType((*ListAccountsRequest)(nil), "account_service.ListAccountsRequest") proto.RegisterType((*ListAccountsResponse)(nil), "account_service.ListAccountsResponse") proto.RegisterType((*GetByIdRequest)(nil), "account_service.GetByIdRequest") proto.RegisterType((*GetByEmailRequest)(nil), "account_service.GetByEmailRequest") proto.RegisterType((*AuthenticateByEmailRequest)(nil), "account_service.AuthenticateByEmailRequest") proto.RegisterType((*GeneratePasswordTokenRequest)(nil), "account_service.GeneratePasswordTokenRequest") proto.RegisterType((*GeneratePasswordTokenResponse)(nil), "account_service.GeneratePasswordTokenResponse") proto.RegisterType((*ResetPasswordRequest)(nil), "account_service.ResetPasswordRequest") proto.RegisterType((*ConfirmAccountRequest)(nil), "account_service.ConfirmAccountRequest") proto.RegisterType((*CreateAccountRequest)(nil), "account_service.CreateAccountRequest") proto.RegisterType((*UpdateAccountRequest)(nil), "account_service.UpdateAccountRequest") proto.RegisterType((*DeleteAccountRequest)(nil), "account_service.DeleteAccountRequest") } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // Client API for AccountService service type AccountServiceClient interface { List(ctx context.Context, in *ListAccountsRequest, opts ...grpc.CallOption) (*ListAccountsResponse, error) GetById(ctx context.Context, in *GetByIdRequest, opts ...grpc.CallOption) (*Account, error) GetByEmail(ctx context.Context, in *GetByEmailRequest, opts ...grpc.CallOption) (*Account, error) AuthenticateByEmail(ctx context.Context, in *AuthenticateByEmailRequest, opts ...grpc.CallOption) (*Account, error) GeneratePasswordToken(ctx context.Context, in *GeneratePasswordTokenRequest, opts ...grpc.CallOption) (*GeneratePasswordTokenResponse, error) ResetPassword(ctx context.Context, in *ResetPasswordRequest, opts ...grpc.CallOption) (*Account, error) ConfirmAccount(ctx context.Context, in *ConfirmAccountRequest, opts ...grpc.CallOption) (*Account, error) Create(ctx context.Context, in *CreateAccountRequest, opts ...grpc.CallOption) (*Account, error) Update(ctx context.Context, in *UpdateAccountRequest, opts ...grpc.CallOption) (*Account, error) Delete(ctx context.Context, in *DeleteAccountRequest, opts ...grpc.CallOption) (*google_protobuf.Empty, error) } type accountServiceClient struct { cc *grpc.ClientConn } func NewAccountServiceClient(cc *grpc.ClientConn) AccountServiceClient { return &accountServiceClient{cc} } func (c *accountServiceClient) List(ctx context.Context, in *ListAccountsRequest, opts ...grpc.CallOption) (*ListAccountsResponse, error) { out := new(ListAccountsResponse) err := grpc.Invoke(ctx, "/account_service.AccountService/List", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *accountServiceClient) GetById(ctx context.Context, in *GetByIdRequest, opts ...grpc.CallOption) (*Account, error) { out := new(Account) err := grpc.Invoke(ctx, "/account_service.AccountService/GetById", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *accountServiceClient) GetByEmail(ctx context.Context, in *GetByEmailRequest, opts ...grpc.CallOption) (*Account, error) { out := new(Account) err := grpc.Invoke(ctx, "/account_service.AccountService/GetByEmail", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *accountServiceClient) AuthenticateByEmail(ctx context.Context, in *AuthenticateByEmailRequest, opts ...grpc.CallOption) (*Account, error) { out := new(Account) err := grpc.Invoke(ctx, "/account_service.AccountService/AuthenticateByEmail", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *accountServiceClient) GeneratePasswordToken(ctx context.Context, in *GeneratePasswordTokenRequest, opts ...grpc.CallOption) (*GeneratePasswordTokenResponse, error) { out := new(GeneratePasswordTokenResponse) err := grpc.Invoke(ctx, "/account_service.AccountService/GeneratePasswordToken", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *accountServiceClient) ResetPassword(ctx context.Context, in *ResetPasswordRequest, opts ...grpc.CallOption) (*Account, error) { out := new(Account) err := grpc.Invoke(ctx, "/account_service.AccountService/ResetPassword", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *accountServiceClient) ConfirmAccount(ctx context.Context, in *ConfirmAccountRequest, opts ...grpc.CallOption) (*Account, error) { out := new(Account) err := grpc.Invoke(ctx, "/account_service.AccountService/ConfirmAccount", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *accountServiceClient) Create(ctx context.Context, in *CreateAccountRequest, opts ...grpc.CallOption) (*Account, error) { out := new(Account) err := grpc.Invoke(ctx, "/account_service.AccountService/Create", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *accountServiceClient) Update(ctx context.Context, in *UpdateAccountRequest, opts ...grpc.CallOption) (*Account, error) { out := new(Account) err := grpc.Invoke(ctx, "/account_service.AccountService/Update", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } func (c *accountServiceClient) Delete(ctx context.Context, in *DeleteAccountRequest, opts ...grpc.CallOption) (*google_protobuf.Empty, error) { out := new(google_protobuf.Empty) err := grpc.Invoke(ctx, "/account_service.AccountService/Delete", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } // Server API for AccountService service type AccountServiceServer interface { List(context.Context, *ListAccountsRequest) (*ListAccountsResponse, error) GetById(context.Context, *GetByIdRequest) (*Account, error) GetByEmail(context.Context, *GetByEmailRequest) (*Account, error) AuthenticateByEmail(context.Context, *AuthenticateByEmailRequest) (*Account, error) GeneratePasswordToken(context.Context, *GeneratePasswordTokenRequest) (*GeneratePasswordTokenResponse, error) ResetPassword(context.Context, *ResetPasswordRequest) (*Account, error) ConfirmAccount(context.Context, *ConfirmAccountRequest) (*Account, error) Create(context.Context, *CreateAccountRequest) (*Account, error) Update(context.Context, *UpdateAccountRequest) (*Account, error) Delete(context.Context, *DeleteAccountRequest) (*google_protobuf.Empty, error) } func RegisterAccountServiceServer(s *grpc.Server, srv AccountServiceServer) { s.RegisterService(&_AccountService_serviceDesc, srv) } func _AccountService_List_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ListAccountsRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(AccountServiceServer).List(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/account_service.AccountService/List", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(AccountServiceServer).List(ctx, req.(*ListAccountsRequest)) } return interceptor(ctx, in, info, handler) } func _AccountService_GetById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetByIdRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(AccountServiceServer).GetById(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/account_service.AccountService/GetById", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(AccountServiceServer).GetById(ctx, req.(*GetByIdRequest)) } return interceptor(ctx, in, info, handler) } func _AccountService_GetByEmail_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetByEmailRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(AccountServiceServer).GetByEmail(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/account_service.AccountService/GetByEmail", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(AccountServiceServer).GetByEmail(ctx, req.(*GetByEmailRequest)) } return interceptor(ctx, in, info, handler) } func _AccountService_AuthenticateByEmail_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AuthenticateByEmailRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(AccountServiceServer).AuthenticateByEmail(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/account_service.AccountService/AuthenticateByEmail", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(AccountServiceServer).AuthenticateByEmail(ctx, req.(*AuthenticateByEmailRequest)) } return interceptor(ctx, in, info, handler) } func _AccountService_GeneratePasswordToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GeneratePasswordTokenRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(AccountServiceServer).GeneratePasswordToken(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/account_service.AccountService/GeneratePasswordToken", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(AccountServiceServer).GeneratePasswordToken(ctx, req.(*GeneratePasswordTokenRequest)) } return interceptor(ctx, in, info, handler) } func _AccountService_ResetPassword_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ResetPasswordRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(AccountServiceServer).ResetPassword(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/account_service.AccountService/ResetPassword", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(AccountServiceServer).ResetPassword(ctx, req.(*ResetPasswordRequest)) } return interceptor(ctx, in, info, handler) } func _AccountService_ConfirmAccount_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ConfirmAccountRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(AccountServiceServer).ConfirmAccount(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/account_service.AccountService/ConfirmAccount", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(AccountServiceServer).ConfirmAccount(ctx, req.(*ConfirmAccountRequest)) } return interceptor(ctx, in, info, handler) } func _AccountService_Create_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CreateAccountRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(AccountServiceServer).Create(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/account_service.AccountService/Create", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(AccountServiceServer).Create(ctx, req.(*CreateAccountRequest)) } return interceptor(ctx, in, info, handler) } func _AccountService_Update_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(UpdateAccountRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(AccountServiceServer).Update(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/account_service.AccountService/Update", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(AccountServiceServer).Update(ctx, req.(*UpdateAccountRequest)) } return interceptor(ctx, in, info, handler) } func _AccountService_Delete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeleteAccountRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(AccountServiceServer).Delete(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/account_service.AccountService/Delete", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(AccountServiceServer).Delete(ctx, req.(*DeleteAccountRequest)) } return interceptor(ctx, in, info, handler) } var _AccountService_serviceDesc = grpc.ServiceDesc{ ServiceName: "account_service.AccountService", HandlerType: (*AccountServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "List", Handler: _AccountService_List_Handler, }, { MethodName: "GetById", Handler: _AccountService_GetById_Handler, }, { MethodName: "GetByEmail", Handler: _AccountService_GetByEmail_Handler, }, { MethodName: "AuthenticateByEmail", Handler: _AccountService_AuthenticateByEmail_Handler, }, { MethodName: "GeneratePasswordToken", Handler: _AccountService_GeneratePasswordToken_Handler, }, { MethodName: "ResetPassword", Handler: _AccountService_ResetPassword_Handler, }, { MethodName: "ConfirmAccount", Handler: _AccountService_ConfirmAccount_Handler, }, { MethodName: "Create", Handler: _AccountService_Create_Handler, }, { MethodName: "Update", Handler: _AccountService_Update_Handler, }, { MethodName: "Delete", Handler: _AccountService_Delete_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "account_service.proto", } func init() { proto.RegisterFile("account_service.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 767 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xb4, 0x56, 0xdd, 0x52, 0xd3, 0x40, 0x14, 0xa6, 0xff, 0xe5, 0xd4, 0x16, 0x5d, 0x82, 0x93, 0x09, 0x32, 0xd6, 0xa0, 0x0c, 0xea, 0x90, 0x3a, 0x05, 0x1d, 0x47, 0xbd, 0x01, 0x44, 0x64, 0x44, 0xc5, 0x00, 0x37, 0x5e, 0xd8, 0x09, 0xed, 0xa1, 0x64, 0x68, 0x93, 0x9a, 0x6c, 0x91, 0xf2, 0x30, 0x3e, 0x80, 0x17, 0x3e, 0x96, 0xcf, 0xe1, 0x64, 0x77, 0x13, 0x9b, 0x66, 0x1b, 0xb8, 0xf1, 0xae, 0x39, 0xfb, 0x9d, 0xef, 0x7c, 0x7b, 0xf6, 0x7c, 0xdb, 0x85, 0x05, 0xab, 0xdd, 0x76, 0x87, 0x0e, 0x6d, 0xf9, 0xe8, 0x5d, 0xd8, 0x6d, 0x34, 0x06, 0x9e, 0x4b, 0x5d, 0x32, 0x37, 0x11, 0xd6, 0x16, 0xbb, 0xae, 0xdb, 0xed, 0x61, 0x83, 0x2d, 0x9f, 0x0c, 0x4f, 0x1b, 0xd8, 0x1f, 0xd0, 0x11, 0x47, 0x6b, 0xeb, 0x5d, 0x9b, 0x9e, 0x0d, 0x4f, 0x8c, 0xb6, 0xdb, 0x6f, 0xf4, 0xec, 0x1e, 0xda, 0x6e, 0xc3, 0xee, 0x5b, 0x5d, 0x0c, 0xb3, 0xe3, 0x5f, 0x3c, 0x49, 0xff, 0x95, 0x83, 0xd2, 0x26, 0xaf, 0x42, 0x6a, 0x90, 0xb5, 0x3b, 0x6a, 0xa6, 0x9e, 0x59, 0x9d, 0x35, 0xb3, 0x76, 0x87, 0x10, 0xc8, 0x3b, 0x56, 0x1f, 0xd5, 0x2c, 0x8b, 0xb0, 0xdf, 0x44, 0x81, 0x02, 0xf6, 0x2d, 0xbb, 0xa7, 0xe6, 0x58, 0x90, 0x7f, 0x90, 0x37, 0x50, 0x64, 0xe4, 0xbe, 0x9a, 0xaf, 0xe7, 0x56, 0x2b, 0xcd, 0x87, 0xc6, 0xe4, 0x86, 0x44, 0x0d, 0x63, 0x8f, 0xc1, 0x76, 0x1c, 0xea, 0x8d, 0x4c, 0x91, 0x43, 0x96, 0xa1, 0xda, 0x76, 0x9d, 0x53, 0xdb, 0xeb, 0xb7, 0xa8, 0x7b, 0x8e, 0x8e, 0x5a, 0x60, 0xdc, 0xb7, 0x44, 0xf0, 0x28, 0x88, 0x91, 0x67, 0xa0, 0x0c, 0x2c, 0xdf, 0xff, 0xe1, 0x7a, 0x9d, 0x96, 0x87, 0x3e, 0x52, 0x81, 0x2d, 0x32, 0x2c, 0x09, 0xd7, 0xcc, 0x60, 0x89, 0x67, 0x6c, 0x41, 0xb9, 0x8f, 0xd4, 0xea, 0x58, 0xd4, 0x52, 0x4b, 0x4c, 0xd6, 0xca, 0x54, 0x59, 0x1f, 0x05, 0x90, 0x0b, 0x8b, 0xf2, 0xb4, 0xcf, 0x50, 0x19, 0x53, 0x4c, 0x6e, 0x43, 0xee, 0x1c, 0x47, 0xa2, 0x45, 0xc1, 0x4f, 0xf2, 0x04, 0x0a, 0x17, 0x56, 0x6f, 0xc8, 0x9b, 0x54, 0x69, 0x2a, 0x46, 0xbc, 0xc9, 0x2c, 0xd9, 0xe4, 0x90, 0x57, 0xd9, 0x97, 0x19, 0xed, 0x35, 0x54, 0x63, 0xb5, 0x24, 0x94, 0xca, 0x38, 0xe5, 0xec, 0x58, 0xb2, 0xfe, 0x05, 0xe6, 0xf7, 0x6d, 0x9f, 0x0a, 0xd1, 0xbe, 0x89, 0xdf, 0x87, 0xe8, 0x53, 0xb2, 0x08, 0xb3, 0x03, 0x56, 0xd4, 0xbe, 0x42, 0x46, 0x54, 0x30, 0xcb, 0x41, 0xe0, 0xd0, 0xbe, 0x42, 0xb2, 0x04, 0xc0, 0x16, 0x79, 0xb7, 0x38, 0x25, 0x83, 0xb3, 0x26, 0xe9, 0x14, 0x94, 0x38, 0xa5, 0x3f, 0x70, 0x1d, 0x1f, 0xc9, 0x06, 0x94, 0x45, 0xaf, 0x7c, 0x35, 0xc3, 0x9a, 0xa7, 0x4e, 0x6b, 0x9e, 0x19, 0x21, 0xc9, 0x0a, 0xcc, 0x39, 0x78, 0x49, 0x5b, 0x89, 0x8a, 0xd5, 0x20, 0x7c, 0x10, 0x55, 0xad, 0x43, 0x6d, 0x17, 0xe9, 0xd6, 0x68, 0xaf, 0x13, 0xee, 0x61, 0x62, 0xf6, 0xf4, 0xc7, 0x70, 0x87, 0x21, 0x76, 0x82, 0xf9, 0x0a, 0x41, 0xd1, 0xf0, 0x65, 0xc6, 0x86, 0x4f, 0xff, 0x04, 0xda, 0xe6, 0x90, 0x9e, 0xa1, 0x43, 0xed, 0xb6, 0x45, 0xf1, 0x26, 0x39, 0x44, 0x83, 0x72, 0x38, 0x31, 0x42, 0x61, 0xf4, 0xad, 0x6f, 0xc0, 0xbd, 0x5d, 0x74, 0xd0, 0xb3, 0x28, 0x1e, 0x88, 0x18, 0x53, 0x9d, 0xae, 0xe2, 0x39, 0x2c, 0x4d, 0xc9, 0x12, 0x1d, 0x55, 0xa0, 0xc0, 0x3b, 0x22, 0xd2, 0xd8, 0x87, 0xfe, 0x1e, 0x14, 0x36, 0xb2, 0x07, 0xd1, 0xfc, 0x46, 0x45, 0x92, 0xe8, 0x54, 0xd9, 0x6b, 0xb0, 0xb0, 0xcd, 0x0d, 0x13, 0x9e, 0x4b, 0x1a, 0x95, 0xfe, 0x33, 0x03, 0xca, 0xb6, 0x87, 0x16, 0xc5, 0x09, 0x78, 0x13, 0x4a, 0xe2, 0x3c, 0x59, 0x42, 0xda, 0xc1, 0x87, 0xc0, 0x34, 0x5d, 0xe4, 0x05, 0x14, 0x98, 0x27, 0xd8, 0x8d, 0x51, 0x69, 0xd6, 0x65, 0x0e, 0x39, 0xa4, 0xae, 0x87, 0x42, 0x80, 0xc9, 0xe1, 0xfa, 0xef, 0x0c, 0x28, 0xc7, 0x83, 0x4e, 0x52, 0xe0, 0xe4, 0x35, 0xf5, 0x1f, 0x8a, 0x8f, 0x37, 0x21, 0x7f, 0xc3, 0x26, 0xe8, 0x2b, 0xa0, 0xbc, 0xc5, 0x1e, 0x5e, 0xa7, 0xb7, 0xf9, 0xa7, 0x08, 0x35, 0x01, 0x39, 0xe4, 0x5c, 0xe4, 0x18, 0xf2, 0x81, 0x0b, 0x49, 0xf2, 0xde, 0x94, 0xf8, 0x5d, 0x7b, 0x74, 0x0d, 0x8a, 0x0f, 0x9c, 0x3e, 0x43, 0xde, 0x41, 0x49, 0xd8, 0x8c, 0xdc, 0x4f, 0xe4, 0xc4, 0x0d, 0xa8, 0x4d, 0xdd, 0xa0, 0x3e, 0x43, 0xf6, 0x01, 0xfe, 0x99, 0x91, 0xe8, 0x72, 0xaa, 0x71, 0xd7, 0xa5, 0xb2, 0x7d, 0x83, 0x79, 0x89, 0x5f, 0xc9, 0xd3, 0x64, 0xca, 0x54, 0x57, 0xa7, 0xf2, 0x5f, 0xc2, 0x82, 0xd4, 0x89, 0x64, 0x4d, 0x22, 0x7c, 0xba, 0xcf, 0x35, 0xe3, 0xa6, 0xf0, 0xa8, 0xdf, 0x26, 0x54, 0x63, 0x66, 0x26, 0xc9, 0x93, 0x92, 0x99, 0x3d, 0x75, 0x37, 0x47, 0x50, 0x8b, 0xdb, 0x9a, 0x24, 0xff, 0xc5, 0xa4, 0xbe, 0x4f, 0x65, 0xfd, 0x00, 0x45, 0x6e, 0x7e, 0x89, 0x44, 0xd9, 0xad, 0x70, 0x1d, 0x19, 0x37, 0xaa, 0x84, 0x4c, 0xe6, 0xe0, 0x54, 0xb2, 0x3d, 0x28, 0x72, 0x17, 0x49, 0xc8, 0x64, 0xf6, 0xd2, 0xee, 0x1a, 0xfc, 0x51, 0x64, 0x84, 0x8f, 0x22, 0x63, 0x27, 0x78, 0x14, 0xe9, 0x33, 0x5b, 0xcb, 0x5f, 0x1f, 0x24, 0x9f, 0x44, 0x13, 0x9c, 0x27, 0x45, 0x96, 0xb6, 0xfe, 0x37, 0x00, 0x00, 0xff, 0xff, 0x2c, 0x08, 0x71, 0x24, 0x83, 0x09, 0x00, 0x00, }
laurentd75/CLK
Storage/Disk/DiskImage/Formats/FAT12.hpp
// // FAT12.hpp // Clock Signal // // Created by <NAME> on 07/01/2018. // Copyright 2018 <NAME>. All rights reserved. // #ifndef MSXDSK_hpp #define MSXDSK_hpp #include "MFMSectorDump.hpp" #include <string> namespace Storage { namespace Disk { /*! Provides a @c DiskImage holding an MSDOS-style FAT12 disk image: a sector dump of appropriate proportions. */ class FAT12: public MFMSectorDump { public: FAT12(const std::string &file_name); HeadPosition get_maximum_head_position() final; int get_head_count() final; private: long get_file_offset_for_position(Track::Address address) final; int head_count_; int track_count_; int sector_count_; int sector_size_; }; } } #endif /* MSXDSK_hpp */
daughtryz/JavaScriptSoftwareUniversity
JS Advanced/ObjectsAndClasses-Exer/tickets.js
function solve(tickets,criteria) { class Ticket { constructor(descriptor) { const [destination,price,status] = descriptor.split('|'); this.destination = destination; this.price = Number(price); this.status = status; } } const comparator = { destination: (a,b) => a.destination.localeCompare(b.destination), price: (a,b) => a.price - b.price, status: (a,b) => a.status.localeCompare(b.status), } return tickets.map(t => new Ticket(t)).sort(comparator[criteria]); } console.log(solve(['Philadelphia|94.20|available', 'New York City|95.99|available', 'New York City|95.99|sold', 'Boston|126.20|departed'], 'destination'));
activequant/aq2o
model/src/main/java/com/activequant/interfaces/archive/IArchiveReader.java
<filename>model/src/main/java/com/activequant/interfaces/archive/IArchiveReader.java package com.activequant.interfaces.archive; import java.io.IOException; import com.activequant.archive.MultiValueTimeSeriesIterator; import com.activequant.archive.TSContainer; import com.activequant.archive.TimeSeriesIterator; import com.activequant.domainmodel.TimeStamp; /** * * @author GhostRider * */ public interface IArchiveReader { public TSContainer getTimeSeries(String streamId, String key, TimeStamp startTimeStamp) throws Exception; public TSContainer getTimeSeries(String streamId, String key, TimeStamp startTimeStamp, TimeStamp stopTimeStamp) throws Exception; public TimeSeriesIterator getTimeSeriesStream(String streamId, String key, TimeStamp startTimeStamp, TimeStamp stopTimeStamp) throws Exception; public MultiValueTimeSeriesIterator getMultiValueStream(String streamId, TimeStamp startTimeStamp, TimeStamp stopTimeStamp) throws Exception; public void close() throws IOException; }
cogitoergoread/muszi-macrohard.hu
examples/leduc_holdem_nfsp_pytorch_load_model.py
<gh_stars>1-10 ''' An example of loading pre-trained NFSP model on Leduc Holdem ''' import os import torch import rlcard3 from rlcard3.agents.nfsp_agent_pytorch import NFSPAgent from rlcard3.agents.random_agent import RandomAgent from rlcard3.utils.utils import set_global_seed, tournament # Make environment env = rlcard3.make('leduc-holdem') # Set a global seed set_global_seed(0) # Load pretrained model nfsp_agents = [] for i in range(env.player_num): agent = NFSPAgent(scope='nfsp' + str(i), action_num=env.action_num, state_shape=env.state_shape, hidden_layers_sizes=[128,128], q_mlp_layers=[128,128], device=torch.device('cpu')) nfsp_agents.append(agent) # We have a pretrained model here. Change the path for your model. check_point_path = os.path.join(rlcard3.__path__[0], 'models/pretrained/leduc_holdem_nfsp_pytorch/model.pth') checkpoint = torch.load(check_point_path) for agent in nfsp_agents: agent.load(checkpoint) # Evaluate the performance. Play with random agents. evaluate_num = 10000 random_agent = RandomAgent(env.action_num) env.set_agents([nfsp_agents[0], random_agent]) reward = tournament(env, evaluate_num)[0] print('Average reward against random agent: ', reward)
pbohman/istio
mixer/pkg/lang/externs_test.go
<reponame>pbohman/istio // Copyright 2017 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package lang import ( "bytes" "net" "testing" "time" "istio.io/pkg/attribute" ) func TestExternIp(t *testing.T) { b, err := ExternIP("1.2.3.4") if err != nil { t.Fatalf("Unexpected error: %v", err) } if !bytes.Equal(b, net.ParseIP("1.2.3.4")) { t.Fatalf("Unexpected output: %v", b) } } func TestExternIp_Error(t *testing.T) { _, err := ExternIP("A.A.A.A") if err == nil { t.Fatalf("Expected error not found.") } } func TestExternIpEqual_True(t *testing.T) { b := ExternIPEqual(net.ParseIP("1.2.3.4"), net.ParseIP("1.2.3.4")) if !b { t.Fatal() } } func TestExternIpEqual_False(t *testing.T) { b := ExternIPEqual(net.ParseIP("1.2.3.4"), net.ParseIP("1.2.3.5")) if b { t.Fatal() } } func TestExternTimestamp(t *testing.T) { ti, err := externTimestamp("2015-01-02T15:04:35Z") if err != nil { t.Fatalf("Unexpected error: %v", err) } if ti.Year() != 2015 || ti.Month() != time.January || ti.Day() != 2 || ti.Hour() != 15 || ti.Minute() != 4 { t.Fatalf("Unexpected time: %v", ti) } } func TestExternTimestamp_Error(t *testing.T) { _, err := externTimestamp("AAA") if err == nil { t.Fatalf("Expected error not found.") } } func TestExternTimestampEqual_True(t *testing.T) { t1, _ := externTimestamp("2015-01-02T15:04:35Z") t2, _ := externTimestamp("2015-01-02T15:04:35Z") b := externTimestampEqual(t1, t2) if !b { t.Fatal() } } func TestExternTimestampEqual_False(t *testing.T) { t1, _ := externTimestamp("2015-01-02T15:04:35Z") t2, _ := externTimestamp("2018-11-11T15:04:35Z") b := externTimestampEqual(t1, t2) if b { t.Fatal() } } func TestExternDnsName_Positive(t *testing.T) { positive := []string{ "foo", "foo.", "fOO", "Foo", "f00", "f00.", "a-b.c-d", } for _, v := range positive { o, err := ExternDNSName(v) if err != nil { t.Fatalf("Error: %v for %s", err, v) } if o != v { t.Fatalf("%v != %v", o, v) } } } func TestExternDnsName_Negative(t *testing.T) { negative := []string{ "", ".", "b..a", "b..a.", "-a", "b.-a.c", "f-", "f-.", "f-.boo", "f--.boo", } for _, v := range negative { _, err := ExternDNSName(v) if err == nil { t.Fatalf("Expected error not found for: %v", v) } } } func TestExternDnsNameEqual_Positive(t *testing.T) { positive := map[string]string{ "foo": "foo", "FOO": "foo", "foo.": "foo", "boo": "boo.", "zoo.": "zoo.", "foo.bar": "foo.bar", } for k, v := range positive { eq, err := ExternDNSNameEqual(k, v) if err != nil { t.Fatalf("Error: %v for %s", err, v) } if !eq { t.Fatalf("Expected to be equal: %s != %s", k, v) } } } func TestExternDnsNameEqual_Negative(t *testing.T) { negative := map[string]string{ "foo.bar-a.": "foo.bar", } for k, v := range negative { eq, err := ExternDNSNameEqual(k, v) if err != nil { t.Fatalf("Error: %v for %s", err, v) } if eq { t.Fatalf("Expected to be not equal: %s != %s", k, v) } } } func TestExternDnsNameEqual_Error(t *testing.T) { erroneous := map[string]string{ "a-": "a", "b": "b-", } for k, v := range erroneous { _, err := ExternDNSNameEqual(k, v) if err == nil { t.Fatalf("Expected error not found for: %v == %v", k, v) } } } func TestExternEmail_Positive(t *testing.T) { positive := []string{ "foo<EMAIL>", "<EMAIL>", "<EMAIL>", `"john..doe"@<EMAIL>`, } for _, v := range positive { o, err := ExternEmail(v) if err != nil { t.Fatalf("Error: %v for %s", err, v) } if o != v { t.Fatalf("%v != %v", o, v) } } } func TestExternEmail_Negative(t *testing.T) { negative := []string{ "foo", "foo.", "foo@", "@foo", "foo+a@bar-.com", `aaaa <<EMAIL>>`, } for _, v := range negative { _, err := ExternEmail(v) if err == nil { t.Fatalf("Expected error not found for: %v", v) } } } func TestExternEmailEqual_Positive(t *testing.T) { positive := map[string]string{ "<EMAIL>": "<EMAIL>", "<EMAIL>": "<EMAIL>", `"foo"@<EMAIL>`: "<EMAIL>", } for k, v := range positive { eq, err := ExternEmailEqual(k, v) if err != nil { t.Fatalf("Error: %v for %s", err, v) } if !eq { t.Fatalf("Expected to be equal: %s != %s", k, v) } } } func TestExternEmailEqual_Error(t *testing.T) { erroneous := map[string]string{ "<EMAIL>": "<EMAIL>", "<EMAIL>": "<EMAIL>", "foo": "<EMAIL>", "<EMAIL>": "foo", } for k, v := range erroneous { _, err := ExternEmailEqual(k, v) if err == nil { t.Fatalf("Expected error not found for: %v == %v", k, v) } } } func TestExternEmailEqual_Negative(t *testing.T) { negative := map[string]string{ "<EMAIL>": "<EMAIL>", "<EMAIL>": "<EMAIL>", "<EMAIL>": "<EMAIL>", } for k, v := range negative { eq, err := ExternEmailEqual(k, v) if err != nil { t.Fatalf("Error: %v for %s", err, v) } if eq { t.Fatalf("Expected to be not equal: %s != %s", k, v) } } } func TestGetEmailParts(t *testing.T) { cases := [][]string{ {"", "", ""}, {"@", "", ""}, {"foo", "foo", ""}, {"foo@", "foo", ""}, {"@foo", "", "foo"}, {"foo@bar", "foo", "bar"}, {"foo@bar@baz", "foo", "bar@baz"}, } for _, c := range cases { p1, p2 := getEmailParts(c[0]) if p1 != c[1] || p2 != c[2] { t.Fatalf("Failed for '%s' got: '%s','%s' wanted: '%s','%s'.", c[0], p1, p2, c[1], c[2]) } } } func TestExternUri_Positive(t *testing.T) { positive := []string{ "urn:foo", "urn:foo/bar", "urn:foo/bar?q=5", "urn:foo/bar?q=5#frr", "http://foo", "http://foo/", "http://foo/bar", "http://foo/bar/", "http://foo/bar/?q=4", "http://foo/bar/?q=4#fr", "https://foo/bar/?q=4#fr", "ftp://foo/bar/?q=4#fr", "fs:foo", "fs:/foo", "foo", "http://[fe80::1%25en0]", } for _, v := range positive { o, err := ExternURI(v) if err != nil { t.Fatalf("Error: %v for %s", err, v) } if o != v { t.Fatalf("%v != %v", o, v) } } } func TestExternUri_Negative(t *testing.T) { negative := []string{ "", ":/", ":a", `http://[fe80::1%25en0`, } for _, v := range negative { _, err := ExternURI(v) if err == nil { t.Fatalf("Expected error not found for: '%v'", v) } } } func TestExternUriEqual_Positive(t *testing.T) { positive := map[string]string{ "foo": "foo", "scheme:bar": "scheme:bar", "urn:bar": "URN:bar", "http://host": "http://host", "http://HOST": "http://host", "http://HOST.com": "http://host.COM", "http://HOST.com:80": "http://host.COM:80", "http://HOST.COM:": "http://host.COM", "HTTP://host.com:": "http://host.com", } for k, v := range positive { eq, err := ExternURIEqual(k, v) if err != nil { t.Fatalf("Error: %v for %s", err, v) } if !eq { t.Fatalf("Expected to be equal: %s != %s", k, v) } } } func TestExternUriEqual_Negative(t *testing.T) { negative := map[string]string{ "urn:foo": "urn:bar", "urn:BAR": "urn:bar", "http://host": "http://host/", "http://bar": "http://host", "http://host:80": "http://host:81", "http://host.com": "https://host.com", } for k, v := range negative { eq, err := ExternURIEqual(k, v) if err != nil { t.Fatalf("Error: %v for %s", err, v) } if eq { t.Fatalf("Expected to be not equal: %s != %s", k, v) } } } func TestExternUriEqual_Error(t *testing.T) { erroneous := map[string]string{ ":/": "a", "a": ":/", } for k, v := range erroneous { _, err := ExternURIEqual(k, v) if err == nil { t.Fatalf("Expected error not found for: %v == %v", k, v) } } } func TestExternMatch(t *testing.T) { var cases = []struct { s string p string e bool }{ {"ns1.svc.local", "ns1.*", true}, {"ns1.svc.local", "ns2.*", false}, {"svc1.ns1.cluster", "*.ns1.cluster", true}, {"svc1.ns1.cluster", "*.ns1.cluster1", false}, {"svc1.ns1.cluster", "svc1.ns1.cluster", true}, {"svc1.ns1.cluster", "svc2.ns1.cluster", false}, } for _, c := range cases { if ExternMatch(c.s, c.p) != c.e { t.Fatalf("externMatch failure: %+v", c) } } } func TestExternMatches(t *testing.T) { var cases = []struct { p string s string e bool }{ {"ns1\\.svc\\.local", "ns1.svc.local", true}, {"ns1.*", "ns1.svc.local", true}, {"ns2.*", "ns1.svc.local", false}, } for _, c := range cases { if m, err := externMatches(c.p, c.s); err != nil { t.Errorf("Unexpected error: %+v, %v", c, err) } else if m != c.e { t.Errorf("matches failure: %+v", c) } } } func TestExternStartsWith(t *testing.T) { var cases = []struct { s string p string e bool }{ {"abc", "a", true}, {"abc", "", true}, {"abc", "abc", true}, {"abc", "abcd", false}, {"cba", "a", false}, } for _, c := range cases { m := ExternStartsWith(c.s, c.p) if m != c.e { t.Fatalf("startsWith failure: %+v", c) } } } func TestExternEndsWith(t *testing.T) { var cases = []struct { s string u string e bool }{ {"abc", "c", true}, {"abc", "", true}, {"abc", "abc", true}, {"abc", "dabc", false}, {"cba", "c", false}, } for _, c := range cases { m := ExternEndsWith(c.s, c.u) if m != c.e { t.Fatalf("endsWith failure: %+v", c) } } } func TestExternEmptyStringMap(t *testing.T) { m := externEmptyStringMap() if !attribute.Equal(m, attribute.WrapStringMap(nil)) { t.Errorf("emptyStringMap() returned non-empty map: %#v", m) } } func TestExternConditionalString(t *testing.T) { got := externConditionalString(true, "yes", "no") if got != "yes" { t.Errorf("externIfElse(true, \"yes\", \"no\") => %s, wanted: yes", got) } }
okanon/tbd.linux
include/arch_info.h
<filename>include/arch_info.h // // include/arch_info.h // tbd // // Created by inoahdev on 11/19/18. // Copyright © 2018 - 2019 inoahdev. All rights reserved. // #ifndef ARCH_INFO_H #define ARCH_INFO_H #include "mach-o/loader.h" #include "notnull.h" struct arch_info { cpu_type_t cputype; cpu_subtype_t cpusubtype; const char *name; uint64_t name_length; }; const struct arch_info *__notnull arch_info_get_list(void); uint64_t arch_info_list_get_size(void); const struct arch_info * arch_info_for_cputype(cpu_type_t cputype, cpu_subtype_t cpusubtype); const struct arch_info *arch_info_for_name(const char *__notnull name); #endif /* ARCH_INFO_H */
JCCDex/jccWalletExtension
app/scripts/constants/walletType-constants.js
<gh_stars>1-10 export const NETWORK_TYPE_RPC = 'rpc'; export const SWTC = 'swt' //井通链 export const RIPPLE = 'ripple' //瑞波链 export const CALL = 'call' //CALL 链 export const STM = 'stm' //stm 链 export const JINGTUM = 'jingtum' export const MOAC = 'moac' export const ETH = 'eth' export const WALLET_TYPES = [SWTC, RIPPLE, CALL, STM, JINGTUM, MOAC, ETH];
rochaporto/gophernotes
vendor/github.com/cosmos72/gomacro/jit/_arith_arm64.go
<reponame>rochaporto/gophernotes<filename>vendor/github.com/cosmos72/gomacro/jit/_arith_arm64.go // +build arm64 /* * gomacro - A Go interpreter with Lisp-like macros * * Copyright (C) 2018-2019 <NAME> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * * arith_arm64.go * * Created on May 20, 2018 * Author <NAME> */ package jit // xz += a func (asm *Asm) Add(z Reg, a Arg) *Asm { if a.Const() { val := a.(*Const).val if asm.add_const(z, val) || asm.sub_const(z, -val) { return asm } } tmp, alloc := asm.hwAlloc(a) asm.Uint32(0x8b<<24 | tmp.lo()<<16 | asm.lo(z)*0x21) // add xz, xz, xtmp asm.hwFree(tmp, alloc) return asm } // xz -= a func (asm *Asm) Sub(z Reg, a Arg) *Asm { if a.Const() { val := a.(*Const).val if asm.sub_const(z, val) || asm.add_const(z, -val) { return asm } } tmp, alloc := asm.hwAlloc(a) asm.Uint32(0xcb<<24 | tmp.lo()<<16 | asm.lo(z)*0x21) // sub xz, xz, xtmp asm.hwFree(tmp, alloc) return asm } func (asm *Asm) add_const(z Reg, val int64) bool { if val == 0 { return true } else if uint64(val) < 4096 { asm.Uint32(0x91<<24 | uint32(val)<<10 | asm.lo(z)*0x21) // add xz, xz, $val return true } return false } func (asm *Asm) sub_const(z Reg, val int64) bool { if val == 0 { return true } else if uint64(val) < 4096 { asm.Uint32(0xd1<<24 | uint32(val)<<10 | asm.lo(z)*0x21) // sub xz, xz, $val return true } return false } // xz *= a func (asm *Asm) Mul(z Reg, a Arg) *Asm { if a.Const() { val := a.(*Const).val if val == 0 { return asm.LoadConst(z, 0) } else if val == 1 { return asm } else if val == 2 { return asm.Add(z, z) } } tmp, alloc := asm.hwAlloc(a) asm.Uint32(0x9b007c00 | tmp.lo()<<16 | asm.lo(z)*0x21) // mul xz, xz, xtmp asm.hwFree(tmp, alloc) return asm } // xz /= a signed division func (asm *Asm) SDiv(z Reg, a Arg) *Asm { return asm.div(z, a, signed) } // xz /= a unsigned division func (asm *Asm) UDiv(z Reg, a Arg) *Asm { return asm.div(z, a, unsigned) } // xz %= a signed remainder func (asm *Asm) SRem(z Reg, a Arg) *Asm { return asm.rem(z, a, signed) } // xz %= a unsigned remainder func (asm *Asm) URem(z Reg, a Arg) *Asm { return asm.rem(z, a, unsigned) } func (asm *Asm) div(z Reg, a Arg, k divkind) *Asm { if a.Const() { val := a.(*Const).val if val == 0 { // cause a runtime fault by clearing x29 then dereferencing it return asm.loadConst(x29, 0).storeReg(&Var{}, x29) } else if val == 1 { return asm } } tmp, alloc := asm.hwAlloc(a) var flag uint32 if k&unsigned == 0 { flag = 0x400 } asm.Uint32(0x9ac00800 | flag | tmp.lo()<<16 | asm.lo(z)*0x21) // {s,u}div xz, xz, xtmp asm.hwFree(tmp, alloc) return asm } func (asm *Asm) rem(z Reg, a Arg, k divkind) *Asm { if a.Const() { c := a.(*Const) val := c.val if val == 0 { // cause a runtime fault by clearing x29 then dereferencing it return asm.loadConst(x29, 0).storeReg(&Var{}, x29) } else if val&(val-1) == 0 { // transform xz %= power-of-two // into zx &= power-of-two - 1 return asm.And(z, &Const{c.kind, val - 1}) } } den, alloc := asm.hwAlloc(a) // // den = a quo := asm.hwRegs.Alloc() var flag uint32 if k&unsigned == 0 { flag = 0x400 } asm.Uint32(0x9ac08000 | flag | den.lo()<<16 | asm.lo(z)<<5 | quo.lo()) // {s,u}div quo, xz, den // quo = xz / den asm.Uint32(0x9b008000 | den.lo()<<16 | quo.lo()<<5 | asm.lo(z)*0x401) // msub xz, quo, den, xz // xz = xz - quo * den asm.hwFree(quo, true) asm.hwFree(den, alloc) return asm } // xz = - xz func (asm *Asm) Neg(z Reg) *Asm { return asm.Uint32(0xcb0003e0 | asm.lo(z)*0x10001) // neg xz, xz }
Amuxix/ItemFilter
src/main/scala/me/amuxix/FilterLevel.scala
<gh_stars>0 package me.amuxix sealed abstract case class FilterLevel(suffix: String, cutoffRarity: FilterRarity, id: String) object Racing extends FilterLevel(" Leveling", Leveling, ItemFilter.settings.ggg.racingId) object Normal extends FilterLevel("", Common, ItemFilter.settings.ggg.normalId) object Diminished extends FilterLevel(" Diminished", Uncommon, ItemFilter.settings.ggg.diminishedId) object Reduced extends FilterLevel(" Reduced", Rare, ItemFilter.settings.ggg.reducedId)
eugene-matvejev/battleship-game-gui-react-js
src/to-be-reviewed/service/generator/battlefield_generator.test.js
import { generateBattlefield } from './battlefield_generator'; describe(`generator:: Battlefield`, () => { [1, 2, 3, 10, 15].forEach((size) => { const expected = size ** 2; it(`expected ${expected} cells in generated battlefield with size: ${size}`, () => { const battlefield = generateBattlefield(size); expect(Object.keys(battlefield.getCellsIndexedByCoordinate()).length).toBe(expected); }); }); });
eddieyang97/VoogaSalad_RTS
src/server/LobbyManager.java
package server; /** * This entity stores all GameLobbies currently active. * @author andrew */ import java.io.Serializable; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public class LobbyManager implements Serializable{ private static final long serialVersionUID = 1L; private Map<Integer,GameLobby> lobbies; private int nextID; public LobbyManager() { lobbies = new HashMap<>(); nextID = 0; } /** * Adds the GameLobby to the manager and assigns it an ID * @param element gameLobby to add */ public void addElementToManager(GameLobby element) { nextID++; element.setID(nextID); lobbies.put(nextID, element); } /** * Removes the given GameLobby from this object * @param element GameLobby to remove */ public void removeElement(GameLobby element) { lobbies.remove(element.getID()); } /** * returns an unmodifiable list of all GameLobbies * @return */ public List<GameLobby> getElements() { List<GameLobby> gameLobbies = new ArrayList<>(); for(GameLobby g: lobbies.values()) { gameLobbies.add(g); } return Collections.unmodifiableList(gameLobbies); } public GameLobby get(int ID) { return lobbies.get(ID); } /** * Finds the GameLobby * @param player the player to find * @return the GameLobby containing the player, null if no active lobbies contain the player */ public GameLobby find(Socket player) { for(GameLobby g: lobbies.values()) { if (g.contains(player)) return g; } return null; } }
antholuo/Blob_Traffic
Blob_Lib/glfw-3.3.7/glfw/tests/msaa.c
<reponame>antholuo/Blob_Traffic version https://git-lfs.github.com/spec/v1 oid sha256:c9082c6059173c6a33ca4689fc3adef095c2920cd00a1bd62b3c8a0a98ae6389 size 6134
vizicist/palette
ffgl/source/lib/ffglex/FFGLFBO.cpp
<reponame>vizicist/palette<gh_stars>1-10 #include "FFGLFBO.h" #include "FFGLScopedFBOBinding.h" #include "FFGLScopedRenderBufferBinding.h" #include "FFGLScopedTextureBinding.h" namespace ffglex { FFGLFBO::FFGLFBO() : width( 0 ), height( 0 ), internalColorFormat( 0 ), fboID( 0 ), depthBufferID( 0 ), colorTextureID( 0 ) { } bool FFGLFBO::Initialise( GLsizei width, GLsizei height, GLint internalColorFormat ) { //Cannot initialize if we're already initialized, please Release us first. if( fboID != 0 ) return false; this->width = width; this->height = height; this->internalColorFormat = internalColorFormat; //If any of the generation functions fail we'll release the resources that did successfully initialize so that //we wont end up in a partially initialized state. if( !GenerateFBO() || !GenerateDepthBuffer() || !GenerateColorTexture() ) { Release(); return false; } //If we got to this point generating the depth buffer and color textures has succeeded so we can now attach them to the fbo. //We use a reverting binding behaviour so that the bound fboIDs may be reverted back to the host's fbo. ScopedFBOBinding scopedFBO( fboID, ScopedFBOBinding::RB_REVERT ); glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBufferID ); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTextureID, 0 ); //If the framebuffer status is not complete for some reason we'll release all the resources we've initialized so that //they dont keep dangling around. The caller should not have to call Release if Initialise failed. if( glCheckFramebufferStatus( GL_FRAMEBUFFER ) != GL_FRAMEBUFFER_COMPLETE ) { Release(); return false; } return true; } void FFGLFBO::Release() { width = 0; height = 0; if( fboID != 0 ) { glDeleteFramebuffers( 1, &fboID ); fboID = 0; } if( depthBufferID != 0 ) { glDeleteRenderbuffers( 1, &depthBufferID ); depthBufferID = 0; } if( depthBufferID != 0 ) { glDeleteTextures( 1, &depthBufferID ); depthBufferID = 0; } } void FFGLFBO::ResizeViewPort() { glViewport( 0, 0, width, height ); } GLuint FFGLFBO::GetWidth() const { return width; } GLuint FFGLFBO::GetHeight() const { return height; } GLuint FFGLFBO::GetGLID() const { return fboID; } FFGLTextureStruct FFGLFBO::GetTextureInfo() const { FFGLTextureStruct t; t.Width = t.HardwareWidth = width; t.Height = t.HardwareHeight = height; t.Handle = colorTextureID; return t; } bool FFGLFBO::GenerateFBO() { glGenFramebuffers( 1, &fboID ); return fboID != 0; } bool FFGLFBO::GenerateDepthBuffer() { glGenRenderbuffers( 1, &depthBufferID ); if( depthBufferID == 0 ) return false; ScopedRenderBufferBinding scopedBinding( depthBufferID ); glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height ); return true; } bool FFGLFBO::GenerateColorTexture() { glGenTextures( 1, &colorTextureID ); if( colorTextureID == 0 ) return false; //Temporarily bind the texture so that we may initialize it's size. Scoped2DTextureBinding textureBinding( colorTextureID ); //Create the texture with no mipmap levels and no borders. The data format and data type dont really matter as we're not uploading any data. glTexImage2D( GL_TEXTURE_2D, 0, internalColorFormat, width, height, 0, GL_RGBA, internalColorFormat == GL_RGBA8 ? GL_UNSIGNED_BYTE : GL_FLOAT, NULL ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); return true; } }//End namespace ffglex
brianneisler/moltres-template
src/app/components/HeaderTopRightNav/HeaderTopRightNav.js
<gh_stars>1-10 import React from 'react' import { StyleSheet } from 'react-native' import { AuthState } from '../../../constants' import { compose } from '../../../utils/lang' import { connect, defaultProps, setDisplayName, setPropTypes, styleShape, withPropsOnChange } from '../../../utils/react' import { buildLocation } from '../../../utils/url' import { selectAuthState, selectCurrentUser } from '../../modules/auth' import { selectRouterLocationPathname } from '../../modules/router' import { Colors, Styles } from '../../styles' import Icon from '../Icon' import Link from '../Link' import Text from '../Text' import TouchableOpacity from '../TouchableOpacity' const USER_PATH = /^\/user\/([a-zA-Z0-9]*)\/?.*/ const enhance = compose( setDisplayName('HeaderTopRightNav'), setPropTypes({ style: styleShape }), defaultProps({ styles: { ...Styles, ...StyleSheet.create({ menuIcon: { color: Colors.whitePrimary, fontSize: 24, lineHeight: 30 } }) } }), connect((state) => ({ authState: selectAuthState(state), currentUser: selectCurrentUser(state), pathname: selectRouterLocationPathname(state) })), withPropsOnChange( ['currentUser', 'pathname'], ({ currentUser, pathname }) => { const match = pathname.match(USER_PATH) const isPathCurrentUserProfile = currentUser && match ? currentUser.id === match[1] : false return { isPathCurrentUserProfile } } ) ) const HeaderTopRightNav = enhance( ({ authState, isPathCurrentUserProfile, pathname, style, styles }) => { if (authState !== AuthState.LOGGED_IN) { if (pathname !== '/login' && pathname !== '/login/code') { return ( <Link style={StyleSheet.flatten([styles.link, styles.whiteButton, style])} to="/login" > <Text style={styles.whiteButtonText}>Login</Text> </Link> ) } } else if (isPathCurrentUserProfile) { return ( <Link to={buildLocation({ pathname: '/menu', state: { back: true } })} > <TouchableOpacity style={[styles.inline, style]}> <Text style={styles.menuIcon}> <Icon icon="bars" /> </Text> </TouchableOpacity> </Link> ) } return null } ) export default HeaderTopRightNav
mickael-menu/client
src/sidebar/components/Tutorial.js
<reponame>mickael-menu/client<gh_stars>0 import { SvgIcon } from '@hypothesis/frontend-shared'; import { isThirdPartyService } from '../helpers/is-third-party-service'; import { withServices } from '../service-context'; /** * Subcomponent: an "instruction" within the tutorial step that includes an * icon and a "command" associated with that icon. Encapsulating these together * allows for styling to keep them from having a line break between them. * * @param {object} props * @param {string} props.commandName - Name of the "command" the instruction represents * @param {string} props.iconName - Name of the icon to display */ function TutorialInstruction({ commandName, iconName }) { return ( <span className="Tutorial__instruction"> <SvgIcon name={iconName} inline={true} className="Tutorial__icon" /> <em>{commandName}</em> </span> ); } /** * Tutorial for using the sidebar app */ function Tutorial({ settings }) { const canCreatePrivateGroups = !isThirdPartyService(settings); return ( <ol className="Tutorial__list"> <li className="Tutorial__item"> To create an annotation, select text and then select the{' '} <TutorialInstruction iconName="annotate" commandName="Annotate" />{' '} button. </li> <li className="Tutorial__item"> To create a highlight ( <a href="https://web.hypothes.is/help/why-are-highlights-private-by-default/" target="_blank" rel="noopener noreferrer" > visible only to you </a> ), select text and then select the{' '} <TutorialInstruction iconName="highlight" commandName="Highlight" />{' '} button. </li> {canCreatePrivateGroups && ( <li className="Tutorial__item"> To annotate in a private group, select the group from the groups dropdown. Don&apos;t see your group? Ask the group creator to send a{' '} <a href="https://web.hypothes.is/help/how-to-join-a-private-group/" target="_blank" rel="noopener noreferrer" > join link </a> ). </li> )} <li className="Tutorial__item"> To reply to an annotation, select the{' '} <TutorialInstruction iconName="reply" commandName="Reply" /> button. </li> </ol> ); } export default withServices(Tutorial, ['settings']);
nao2b/jiji2
src/jiji/model/trading/back_test_repository.rb
# frozen_string_literal: true require 'encase' require 'thread/pool' module Jiji::Model::Trading class BackTestRepository include Encase include Jiji::Errors needs :backtest_thread_pool attr_accessor :container def initialize @backtests = {} end def all @backtests.values end def runnings @backtests.values.select do |b| b.retrieve_process_status == :running end end def collect_backtests_by_id(ids) tests = ids.map do |id| begin get(id) rescue Jiji::Errors::NotFoundException # ignore nil end end tests.reject { |test| test.nil? } end def register(config) config = config.with_indifferent_access backtest = BackTest.create_from_hash(config) setup_backtest(backtest) backtest.save backtest.create_agent_instances(extract_agent_setting(config), true) @backtests[backtest.id] = backtest backtest.start backtest end def get(id) @backtests[id] || not_found(id) end def restart(id) backtest = get(id) unless backtest.status != :running || backtest.trading_context.finished? illegal_state end config = extract_backtest_config(id) new_test = register(config) delete(id) new_test end def delete(id) backtest = get(id) backtest.pause backtest.destroy @backtests.delete(id) end def stop rest = all.reject do |t| if t.retrieve_process_status == :wait_for_start t.pause true else false end end rest.each { |t| t.pause } backtest_thread_pool.shutdown end def load @backtests = BackTest .order_by(:created_at.asc) .all.each_with_object(@backtests) do |t, r| setup_backtest(t) t.start if t.start_on_startup? r[t.id] = t r end end private def extract_agent_setting(config) setting = config[:agent_setting] || {} illegal_argument if setting.empty? setting end def extract_backtest_config(id) backtest = get(id) backtest.to_h.merge({ agent_setting: backtest.agent_settings.map do |s| hash = s.to_h hash.delete :id hash[:agent_name] = hash[:name] hash end }) end def setup_backtest(backtest) container.inject(backtest) backtest.setup backtest end end end
NIRALUser/AtlasWerks
Utilities/planio/read_objects.cxx
<reponame>NIRALUser/AtlasWerks #include <stdio.h> #include <stdlib.h> #include "plan_file_io.h" #include "plan_xdr.h" #include "gen.h" #include "brachy.h" #include "libplanio.h" int XDR_ReadObjects(int fdes, BRACHY_OBJECTS *o); /* --------------------------------------------------------------------------- NAME read_objects(fdes, objects_desc) SYNOPSIS read_objects(fdes, objects_desc) int fdes; BRACHY_OBJECTS *objects_desc; DESCRIPTION read a BRACHY_OBJECTS structure from a file RETURN VALUE 0 -> ok -1 -> error SEE ALSO plan_xdr_defs.c AUTHOR <NAME> Radiation Oncology North Carolina Memorial Hospital University of North Carolina 27 September 1988 --------------------------------------------------------------------------- */ int read_objects(int fdes, BRACHY_OBJECTS *objects_desc) { return(XDR_ReadObjects(fdes, objects_desc)); } int XDR_ReadObjects(int fdes, BRACHY_OBJECTS *o) { int status = XDR_NO_ERROR; XDR_fdes *xdr_fdes; unsigned int size; register int i; xdr_fdes = xdr_ll_open_stream(fdes, XDR_READ_MODE); if (xdr_fdes == NULL) { XDR_ReportError("Cannot open xdr_fdes"); return(XDR_ERROR); } if (! xdr_int(xdr_fdes->xdrs, &o->count)) { XDR_ReportError("Cannot read brachy objects"); status = XDR_ERROR; goto cleanup; } size = o->count * sizeof(BRACHY_OBJECT); o->objects = (BRACHY_OBJECT *) malloc(size); if (o->objects == NULL) { XDR_ReportError("Cannot malloc brachy objects object list"); status = XDR_ERROR; goto cleanup; } for (i=0; i<o->count; i++) if (xdr_ll_brachy_object(xdr_fdes, &(o->objects[i]), TRUE) ==XDR_ERROR) { XDR_ReportError("Cannot read brachy object"); status = XDR_ERROR; } cleanup: xdr_ll_close_stream(xdr_fdes); return(status); }
alexsoft037/springboot
src/main/java/xin/xiaoer/common/utils/Const.java
package xin.xiaoer.common.utils; import java.util.HashMap; import java.util.Map; import org.springframework.context.ApplicationContext; /** * 项目名称: * * @author:fh qq313596790[青苔] * 修改日期:2015/11/2 */ public class Const { public static final String APPLICATION_BASE_PATH = "basepath"; public static final String SQ_NAME = "sqname"; public static final String STREET_NAME="street_name"; public static final Map<String, String> MENUS = new HashMap<String,String>(); public static final Map<String, String> SQNAMES = new HashMap<String,String>(); public static final String SQ_BINGDING_ID = "sqBingdingId"; public static final Integer PAGE_SIZE = 10; public static final String WEIXIN_USER = "weixin_user"; public static final String SESSION_USERROLEMENU = "sessionUserRoleMenu"; public static final String SESSION_USERROLEFUNCS = "sessionUserRoleFuncs"; public static final String CURRENT_MENUID = "currentMenuId"; public static final String WEIXIN_BINDING="weixin_binding"; public static final String SESSION_SECURITY_CODE = "sessionSecCode";//验证码 public static final String SESSION_USER = "sessionUser"; //session用的用户 public static final String SESSION_ROLE_RIGHTS = "sessionRoleRights"; public static final String sSESSION_ROLE_RIGHTS = "sessionRoleRights"; public static final String SESSION_menuList = "menuList"; //当前菜单 public static final String SESSION_allmenuList = "allmenuList"; //全部菜单 public static final String SESSION_rightMenuList = "rightMenuList"; public static final String SESSION_QX = "QX"; public static final String SESSION_userpds = "userpds"; public static final String SESSION_USERROL = "USERROL"; //用户对象 public static final String SESSION_USERNAME = "USERNAME"; //用户名 public static final String SESSION_KEY_SYS_MSG = "SysMsg"; // public static final String SYS_MSG_ITEM_TPL = "<div class='alert alert-%s'>%s</div>"; public static final String TRUE = "T"; public static final String FALSE = "F"; public static final String LOGIN = "/login_form.do"; //登录地址 public static final String SYSNAME = "admin/config/SYSNAME.txt"; //系统名称路径 public static final String PAGE = "admin/config/PAGE.txt"; //分页条数配置路径 public static final String EMAIL = "admin/config/EMAIL.txt"; //邮箱服务器配置路径 public static final String SMS1 = "admin/config/SMS1.txt"; //短信账户配置路径1 public static final String SMS2 = "admin/config/SMS2.txt"; //短信账户配置路径2 public static final String FWATERM = "admin/config/FWATERM.txt"; //文字水印配置路径 public static final String IWATERM = "admin/config/IWATERM.txt"; //图片水印配置路径 public static final String WEIXIN = "admin/config/WEIXIN.txt"; //微信配置路径 public static final String WEBSOCKET = "admin/config/WEBSOCKET.txt";//WEBSOCKET配置路径 public static final String FILEPATH_STATIC = "static/"; public static final String FILEPATH_UPLOAD = "upload/"; //图片上传路径 public static final String FILEPATH_UPLOAD_THUMBNAIL = FILEPATH_UPLOAD + "thumbnail/"; //文件上传路径 public static final String FILEPATHTWODIMENSIONCODE = "resource/twoDimensionCode/"; //二维码存放路径 public static final String NO_INTERCEPTOR_PATH = ".*/((login)|(logout)|(code)|(app)|(weixin)|(static)|(main)|(websocket)).*"; //不对匹配该值的访问路径拦截(正则) public static final Long ACCESS_TOCKEN_CACHE_SECONDS = 7000L; public static final String SERVLET_CONTEXT = "servletContext"; public static final String WX_COUNTINFO_ASY_JD = "weixin_countinfo_asy_jd"; public static ApplicationContext WEB_APP_CONTEXT = null; //该值会在web容器启动时由WebAppContextListener初始化 public static String DOMAIN = null; //该值会在web容器启动时由WebAppContextListener初始化 public static final String CLIENT_TOCKEN="tocken4weixin"; public static final String TEMP_CLIENT_TOCKEN = "temp_tocken4session"; public static final String SESSION_MSG = "sessionMsg"; /** * APP Constants */ //app注册接口_请求协议参数) public static final String[] APP_REGISTERED_PARAM_ARRAY = new String[]{"countries", "uname", "passwd", "title", "full_name", "company_name", "countries_code", "area_code", "telephone", "mobile"}; public static final String[] APP_REGISTERED_VALUE_ARRAY = new String[]{"国籍", "邮箱帐号", "密码", "称谓", "名称", "公司名称", "国家编号", "区号", "电话", "手机号"}; //app根据用户名获取会员信息接口_请求协议中的参数 public static final String[] APP_GETAPPUSER_PARAM_ARRAY = new String[]{"USERNAME"}; public static final String[] APP_GETAPPUSER_VALUE_ARRAY = new String[]{"用户名"}; }
a506131222/ILIFE
llifeRobot/Setting/Controller/ZJMAddReserVC.h
// // ZJMTimedReserVC.h // llifeRobot // // Created by 张佳满 on 2017/10/9. // Copyright © 2017年 ZJM. All rights reserved. // #import "ZJMBaseVC.h" @interface ZJMAddReserVC : ZJMBaseVC @property (strong,nonatomic)NSMutableArray *saveTimeList; @property (copy,nonatomic)NSString *subDomain; @end
rit-bikeshare/mobile-app
src/js/lock/actions/connectToSocket.js
<reponame>rit-bikeshare/mobile-app import { createAction } from 'redux-actions'; import { bikeUnlocked } from './unlockBike'; import { bikeLocked } from './lockBike'; import { CONNECTED_TO_SOCKET, BIKE_LOCK_LOCKING, BIKE_LOCK_UNLOCKING, } from '../constants/LockActionTypes'; const socketConnected = createAction(CONNECTED_TO_SOCKET); const bikeLockLocking = createAction(BIKE_LOCK_LOCKING); const bikeLockUnlocking = createAction(BIKE_LOCK_UNLOCKING); export default function connectToSocket(rentalId) { return dispatch => { const webSocket = new WebSocket( `wss://bikesharedev.rit.edu/api/ws/lock-state/${rentalId}` ); webSocket.addEventListener('message', message => { const data = JSON.parse(message.data); switch (data.state) { case 'locking': dispatch(bikeLockLocking()); break; case 'unlocking': dispatch(bikeLockUnlocking()); break; case 'locked': dispatch(bikeLocked()); break; case 'unlocked': dispatch(bikeUnlocked()); break; default: break; } }); dispatch(socketConnected(webSocket)); }; }
keera-studios/hsQt
Qtc/include/gui/qtc_hs_QProgressBar_h.h
///////////////////////////////////////////////////////////////////////////// // // File : qtc_hs_QProgressBar_h.h // Copyright : (c) <NAME> 2010 // Project : qtHaskell // Version : 1.1.4 // Modified : 2010-09-02 17:02:41 // // Warning : this file is machine generated - do not modify. // ///////////////////////////////////////////////////////////////////////////// int qtc_QProgressBar_unSetHandler(void*,void*); int qtc_QProgressBar_event_h(void*,void*); int qtc_QProgressBar_setHandler1(void*,void*,void*,void*,void*); void* qtc_QProgressBar_minimumSizeHint_h(void*); int qtc_QProgressBar_setHandler2(void*,void*,void*,void*,void*); void* qtc_QProgressBar_minimumSizeHint_qth_h(void*,int*,int*); void qtc_QProgressBar_paintEvent_h(void*,void*); int qtc_QProgressBar_setHandler3(void*,void*,void*,void*,void*); void* qtc_QProgressBar_sizeHint_h(void*); void* qtc_QProgressBar_sizeHint_qth_h(void*,int*,int*); void* qtc_QProgressBar_text_h(void*); int qtc_QProgressBar_setHandler4(void*,void*,void*,void*,void*); void qtc_QProgressBar_actionEvent_h(void*,void*); void qtc_QProgressBar_changeEvent_h(void*,void*); void qtc_QProgressBar_closeEvent_h(void*,void*); void qtc_QProgressBar_contextMenuEvent_h(void*,void*); int qtc_QProgressBar_devType_h(void*); int qtc_QProgressBar_setHandler5(void*,void*,void*,void*,void*); void qtc_QProgressBar_dragEnterEvent_h(void*,void*); void qtc_QProgressBar_dragLeaveEvent_h(void*,void*); void qtc_QProgressBar_dragMoveEvent_h(void*,void*); void qtc_QProgressBar_dropEvent_h(void*,void*); void qtc_QProgressBar_enterEvent_h(void*,void*); void qtc_QProgressBar_focusInEvent_h(void*,void*); void qtc_QProgressBar_focusOutEvent_h(void*,void*); int qtc_QProgressBar_heightForWidth_h(void*,int); int qtc_QProgressBar_setHandler6(void*,void*,void*,void*,void*); void qtc_QProgressBar_hideEvent_h(void*,void*); void* qtc_QProgressBar_inputMethodQuery_h(void*,long); int qtc_QProgressBar_setHandler7(void*,void*,void*,void*,void*); void qtc_QProgressBar_keyPressEvent_h(void*,void*); void qtc_QProgressBar_keyReleaseEvent_h(void*,void*); void qtc_QProgressBar_leaveEvent_h(void*,void*); void qtc_QProgressBar_mouseDoubleClickEvent_h(void*,void*); void qtc_QProgressBar_mouseMoveEvent_h(void*,void*); void qtc_QProgressBar_mousePressEvent_h(void*,void*); void qtc_QProgressBar_mouseReleaseEvent_h(void*,void*); void qtc_QProgressBar_moveEvent_h(void*,void*); void* qtc_QProgressBar_paintEngine_h(void*); int qtc_QProgressBar_setHandler8(void*,void*,void*,void*,void*); void qtc_QProgressBar_resizeEvent_h(void*,void*); void qtc_QProgressBar_setVisible_h(void*,int); int qtc_QProgressBar_setHandler9(void*,void*,void*,void*,void*); void qtc_QProgressBar_showEvent_h(void*,void*); void qtc_QProgressBar_tabletEvent_h(void*,void*); void qtc_QProgressBar_wheelEvent_h(void*,void*); int qtc_QProgressBar_eventFilter_h(void*,void*,void*); int qtc_QProgressBar_setHandler10(void*,void*,void*,void*,void*);
akuhnregnier/empirical-fire-modelling
analysis/calculate_loco_values.py
<filename>analysis/calculate_loco_values.py<gh_stars>0 # -*- coding: utf-8 -*- """LOCO value calculation.""" import logging import sys import warnings from pathlib import Path from pprint import pprint import matplotlib as mpl import pandas as pd from loguru import logger as loguru_logger from wildfires.dask_cx1 import DaskRandomForestRegressor from wildfires.qstat import get_ncpus from empirical_fire_modelling.analysis.loco import calculate_loco from empirical_fire_modelling.cache import IN_STORE from empirical_fire_modelling.configuration import ( Experiment, param_dict, selected_features, ) from empirical_fire_modelling.cx1 import run from empirical_fire_modelling.data import get_experiment_split_data from empirical_fire_modelling.logging_config import enable_logging from empirical_fire_modelling.utils import optional_client_call mpl.rc_file(Path(__file__).resolve().parent / "matplotlibrc") loguru_logger.enable("alepython") loguru_logger.remove() loguru_logger.add(sys.stderr, level="WARNING") logger = logging.getLogger(__name__) enable_logging(level="WARNING") warnings.filterwarnings("ignore", ".*Collapsing a non-contiguous coordinate.*") warnings.filterwarnings("ignore", ".*DEFAULT_SPHERICAL_EARTH_RADIUS.*") warnings.filterwarnings("ignore", ".*guessing contiguous bounds.*") warnings.filterwarnings( "ignore", 'Setting feature_perturbation = "tree_path_dependent".*' ) def loco_calc(experiment, cache_check=False, **kwargs): """Calculate LOCO values. Args: experiment (str): Experiment (e.g. 'ALL'). cache_check (bool): Whether to check for cached data exclusively. """ # Operate on cached data only. get_experiment_split_data.check_in_store(experiment) X_train, X_test, y_train, y_test = get_experiment_split_data(experiment) loco_results = optional_client_call( calculate_loco, dict( rf=DaskRandomForestRegressor(**param_dict), X_train=X_train, y_train=y_train, X_test=X_test, y_test=y_test, leave_out=("", *selected_features[experiment]), local_n_jobs=(1 if (get_ncpus() < 4) else (get_ncpus() - 2)), ), cache_check=cache_check, add_client=True, )[0] if cache_check: return IN_STORE return loco_results if __name__ == "__main__": args_loco_results = run( loco_calc, list(Experiment), cx1_kwargs=False, return_local_args=True ) if args_loco_results is None: sys.exit(0) args, kwargs, loco_results = args_loco_results vis_data = {} for experiment, exp_results in zip(args[0], loco_results): for leave_out, results in exp_results.items(): vis_data[(experiment, leave_out)] = results combined_df = pd.DataFrame(vis_data).T combined_df.index.names = ["experiment", "feature"] combined_df.rename( { "score": "train score", "mse": "train mse", "test_score": "test score", "test_mse": "test mse", }, inplace=True, axis="columns", ) loco_importances = {} for experiment, df in combined_df.groupby("experiment"): df.index = df.index.droplevel("experiment") reference_scores = df.loc[""] df = df.drop("", axis="index") df = reference_scores - df df["train mse"] = -df["train mse"] df["test mse"] = -df["test mse"] df.rename( {"train mse": "train -mse", "test mse": "test -mse"}, inplace=True, axis="columns", ) loco_importances[experiment] = df.sort_values(by="test score", ascending=False) pprint(loco_importances)
akrherz/pyIEM
src/pyiem/plot/geoplot.py
<reponame>akrherz/pyIEM # -*- coding: utf-8 -*- # pylint: disable=import-outside-toplevel,too-many-lines """Plotting utility for generating maps, windroses and everything else under the sun. This module provides a wrapper around `Basemap` and `windrose` packages. It tries to be general so to work for others, but may contain some unfortunate hard coded values. Bad daryl! Example: Here is a basic example of usage. >>> from pyiem.plot.geoplot import MapPlot >>> m = MapPlot(sector='conus', title='My Fancy Title') >>> m.postprocess(filename='myplot.png') >>> m.close() """ # stdlib from io import BytesIO import tempfile import os import sys import subprocess import shutil import datetime import warnings # third party import rasterio from rasterio.warp import reproject, Resampling import requests from metpy.calc import wind_components from metpy.units import units import numpy as np import geopandas as gpd from shapely.geometry import shape from scipy.signal import convolve2d from scipy.interpolate import NearestNDInterpolator from PIL import Image import matplotlib.colors as mpcolors from matplotlib.patches import Wedge import matplotlib.colorbar as mpcolorbar import matplotlib.patheffects as PathEffects import cartopy import cartopy.crs as ccrs import cartopy.feature as cfeature # local from pyiem.plot.use_agg import plt from pyiem.plot.util import ( sector_setter, mask_outside_polygon, polygon_fill, mask_outside_geom, draw_logo, fitbox, ramp2df, ) from pyiem.reference import ( # noqa: F401 # pylint: disable=unused-import LATLON, Z_CF, Z_FILL, Z_FILL_LABEL, Z_CLIP, Z_CLIP2, Z_POLITICAL, Z_OVERLAY, Z_OVERLAY2, Z_FRAME, TWITTER_RESOLUTION_INCH, ) from pyiem.util import ssw, LOG, utc, exponential_backoff, load_geodf from pyiem.plot.colormaps import stretch_cmap # geopandas currently emits this as parquet is unstable. warnings.filterwarnings("ignore", message=".*implementation of Parquet.*") # Set a saner default for apache et al cartopy.config["data_dir"] = "/tmp/" DATADIR = os.sep.join([os.path.dirname(__file__), "..", "data"]) MAIN_AX_BOUNDS = [0.01, 0.05, 0.898, 0.85] CAX_BOUNDS = [0.917, 0.1, 0.02, 0.8] def load_bounds(filebase): """Load bounds file Args: filebase (str): the basename of the file containing the data Returns: numpy 2d array of the data """ fn = os.path.join(DATADIR, f"{filebase}.npy") if not os.path.isfile(fn): LOG.info("load_bounds(%s) is missing!", fn) return None return np.load(fn) class MapPlot: """An object representing a cartopy plot. An object that allows one to quickly and easily generate map plots of data with some customization possible. This is what drives most of the plots you see on the IEM website. Example: Here is an example of usage:: mplot = MapPlot(sector='midwest', title='My Plot Title') mplot.plot_values([-99,-95], [44,45], ['hi','there']) mplot.postprocess(filename='test.png') mplot.close() Attributes: fig (matplotlib.Figure): figure object ax (matplotlib.Axes): main figure plot axes """ def __init__(self, sector="iowa", figsize=(10.24, 7.68), **kwargs): """Construct a MapPlot Args: sector (str): plot domain, set 'custom' to bring your own projection kwargs: projection (cartopy.crs,optional): bring your own projection north (float,optional): Plot top bounds (degN Lat) south (float,optional): Plot bottom bounds (degN Lat) east (float,optional): Plot right bounds (degE Lon) west (float,optional): Plot left bounds (degE Lon) titlefontsize (int): fontsize to use for the plot title subtitlefontsize (int): fontsize to use for the plot subtitle continentalcolor (color): color to use for continental coloring debug (bool): enable debugging aspect (str): plot aspect, defaults to equal fig (matplotlib.pyplot.figure,optional): provide a figure instance for more advanced plot control. logo (str,optional): logo name to slap on the plot. twitter (bool): Set an image resolution that is favorable to posting to Twitter. Default: False. """ self.debug = kwargs.get("debug", False) self.fig = kwargs.get("fig") if kwargs.get("twitter", False) is True: figsize = TWITTER_RESOLUTION_INCH if self.fig is None: self.fig = plt.figure( num=None, figsize=figsize, dpi=kwargs.get("dpi", 100) ) # Storage of axes within this plot self.state = None self.cwa = None self.textmask = None # For our plot_values magic, to prevent overlap self.sector = sector self.cax = plt.axes(CAX_BOUNDS, frameon=False, yticks=[], xticks=[]) self.axes = [] self.ax = None self.pr_ax = None self.hi_ax = None self.ak_ax = None # hack around sector=iowa if self.sector == "iowa": self.sector = "state" self.state = "IA" sector_setter(self, MAIN_AX_BOUNDS, **kwargs) for _a in self.axes: if _a is None: continue # legacy usage of axisbg here _c = kwargs.get( "axisbg", kwargs.get("continentalcolor", "#EEEEEE") ) _a.add_feature(cfeature.LAND, facecolor=_c, zorder=Z_CF) _a.add_feature(cfeature.COASTLINE, lw=1.0, zorder=Z_POLITICAL) _a.add_feature(cfeature.BORDERS, lw=1.0, zorder=Z_POLITICAL) _a.add_feature( cfeature.LAKES, facecolor=(0.4471, 0.6235, 0.8117), zorder=Z_CF ) if "nostates" not in kwargs: states = load_geodf("us_states") _a.add_geometries( states["geom"].values, crs=LATLON, lw=1.0, edgecolor=kwargs.get("statebordercolor", "k"), facecolor="None", zorder=Z_POLITICAL, ) if not kwargs.get("nologo", False): draw_logo(self.fig, kwargs.get("logo", "iem")) if "title" in kwargs: fitbox( self.fig, kwargs.get("title"), 0.09 if not kwargs.get("nologo") else 0.02, 0.99, 0.94, 0.99, textsize=kwargs.get("titlefontsize", 18), ) if "subtitle" in kwargs: fitbox( self.fig, kwargs.get("subtitle"), 0.09 if not kwargs.get("nologo") else 0.02, 0.99, 0.91, 0.94, textsize=kwargs.get("subtitlefontsize", 12), ) if "nocaption" not in kwargs: self.fig.text( 0.01, 0.03, f"{kwargs.get('caption', 'Iowa Environmental Mesonet')} :: " f"generated {datetime.datetime.now():%d %B %Y %I:%M %p %Z}", ) def close(self): """Close the figure in the case of batch processing""" plt.close() def draw_usdm(self, valid=None, filled=True, hatched=False): """Overlay the US Drought Monitor This utilizes a GeoJSON web service provided by the IEM. The provided date to this method is passed to the web service which rectifies the date to provide the USDM analysis valid for that date. If no date is specified, the current analysis is plotted. Args: valid (str or datetime.date): The valid time to plot this USDM filled (boolean): Should we draw lines or filled polygons hatched (boolean): Should we use hatch filling Return: date that the USDM is valid for """ colors = ["#ffff00", "#fcd37f", "#ffaa00", "#e60000", "#730000"] hatches = ["+", "/", "\\", "-", "x"] if valid is None: valid = "" elif isinstance(valid, datetime.date): valid = valid.strftime("%Y-%m-%d") elif isinstance(valid, datetime.datetime): valid = valid.strftime("%Y-%m-%d") url = f"http://mesonet.agron.iastate.edu/geojson/usdm.py?date={valid}" try: req = requests.get(url, timeout=30) except requests.ConnectionError as exp: warnings.warn(f"draw_usdm IEM USDM Webservice failed: {exp}") return None df = gpd.GeoDataFrame().from_features(req.json()) lw = 1 if filled else 4.0 usdm_valid = None for _, row in df.iterrows(): color = colors[row["dm"]] geom = shape(row["geometry"]) usdm_valid = row["date"] fc = color if filled else "None" ec = color if not filled else "k" self.ax.add_geometries( [geom], LATLON, facecolor="None", edgecolor=ec, linewidth=lw, zorder=Z_OVERLAY2, ) if filled: self.ax.add_geometries( [geom], LATLON, facecolor=fc, alpha=0.5, edgecolor="None", zorder=Z_OVERLAY, ) elif hatched: self.ax.add_geometries( [geom], LATLON, facecolor="None", hatch=hatches[row["dm"]], edgecolor=color, zorder=Z_OVERLAY2 + 2, ) if usdm_valid is not None: self.ax.text( 0.99, 0.99, "D4", color="k", transform=self.ax.transAxes, va="top", ha="right", bbox=dict(color=colors[4]), zorder=Z_OVERLAY2 + 3, ) self.ax.text( 0.955, 0.99, "D3", color="k", transform=self.ax.transAxes, va="top", ha="right", bbox=dict(color=colors[3]), zorder=Z_OVERLAY2 + 3, ) self.ax.text( 0.92, 0.99, "D2", color="k", transform=self.ax.transAxes, va="top", ha="right", bbox=dict(color=colors[2]), zorder=Z_OVERLAY2 + 3, ) self.ax.text( 0.885, 0.99, "D1", color="k", transform=self.ax.transAxes, va="top", ha="right", bbox=dict(color=colors[1]), zorder=Z_OVERLAY2 + 3, ) self.ax.text( 0.85, 0.99, "D0", color="k", transform=self.ax.transAxes, va="top", ha="right", bbox=dict(color=colors[0]), zorder=Z_OVERLAY2 + 3, ) self.ax.text( 0.815, 0.99, f"USDM {usdm_valid}", color="w", transform=self.ax.transAxes, va="top", ha="right", bbox=dict(color="k"), zorder=Z_OVERLAY2 + 3, ) return datetime.datetime.strptime(usdm_valid, "%Y-%m-%d") return None def draw_colorbar(self, clevs, cmap, norm, **kwargs): """Draw the colorbar on the structed plot using `self.cax`. Args: clevs (list): The levels used in the classification cmap (matplotlib.colormap): The colormap norm (normalize): The value normalizer title (str,optional): Place a label on the side, adjusts the plot accordingly to allow this text to fit, no multiline please! spacing (str,optional): should the colorbar be `uniform` or `proportional`, defaults to `uniform` """ if self.cax is None: return self.cax.set_frame_on(True) extend = kwargs.get("extend", "both") # Do we need to muck with the cmap # pylint: disable=W0212 if (extend in ["max", "both"] and cmap._rgba_over is None) or ( extend in ["min", "both"] and cmap._rgba_under is None ): cmap = stretch_cmap(cmap, clevs, extend=extend) norm = mpcolors.BoundaryNorm(clevs, cmap.N) clevlabels = kwargs.get("clevlabels", clevs) under = clevs[0] - (clevs[1] - clevs[0]) over = clevs[-1] + (clevs[-1] - clevs[-2]) # create some faked levels in case we want an extended colorbar if extend == "min": blevels = np.concatenate([[under], clevs]) elif extend == "max": blevels = np.concatenate([clevs, [over]]) elif extend == "both": blevels = np.concatenate([[under], clevs, [over]]) else: blevels = clevs stride = slice(None, None, int(kwargs.get("clevstride", 1))) cb2 = mpcolorbar.ColorbarBase( self.cax, cmap=cmap, norm=norm, boundaries=blevels, extend=extend, ticks=clevs[stride], spacing=kwargs.get("spacing", "uniform"), orientation="vertical", ) def _myrepr(val): """avoid list conversion in matplotlib that fowls numpy floats.""" try: return "%g" % (val,) except TypeError: return f"{val}" cb2.ax.set_yticklabels(list(map(_myrepr, clevlabels[stride]))) # Attempt to quell offset that sometimes appears with large numbers cb2.ax.get_yaxis().get_major_formatter().set_offset_string("") for label in cb2.ax.get_yticklabels(): sz = len(label.get_text()) if sz > 4: label.set_fontsize(12) else: label.set_fontsize(16) if sz > 6: label.set_rotation(45) if "units" in kwargs: self.fig.text( 0.99, 0.03, f"data units :: {kwargs['units']}", ha="right" ) title = kwargs.get("title") if title: self.ax.set_position( [ MAIN_AX_BOUNDS[0], MAIN_AX_BOUNDS[1], MAIN_AX_BOUNDS[2] - 0.03, MAIN_AX_BOUNDS[3], ] ) cb2.ax.text( -0.05, 0.5, title, rotation=90, fontsize=16, transform=cb2.ax.transAxes, ha="right", va="center", ) def plot_station(self, data, **kwargs): """Plot values on a map in a station plot like manner. Args: data (list): list of dicts with station data to plot fontsize (int): font size to use for plotted text """ (x0, x1) = self.ax.set_xlim() # size to use for circles circlesz = (x1 - x0) / 180.0 # (y0, y1) = self.ax.set_ylim() offsets = { 1: [-4, 4, "right", "bottom"], 2: [0, 4, "center", "bottom"], 3: [4, 4, "left", "bottom"], 4: [-4, 0, "right", "center"], 5: [0, 0, "center", "center"], 6: [4, 0, "left", "center"], 7: [-4, -4, "right", "top"], 8: [0, -4, "center", "top"], 9: [4, -4, "left", "top"], } mask = np.zeros(self.fig.canvas.get_width_height(), bool) for stdata in data: (x, y) = self.ax.projection.transform_point( stdata["lon"], stdata["lat"], ccrs.Geodetic() ) (imgx, imgy) = self.ax.transData.transform([x, y]) imgx = int(imgx) imgy = int(imgy) # Check to see if this overlaps _cnt = np.sum( np.where( mask[imgx - 15 : imgx + 15, imgy - 15 : imgy + 15], 1, 0 ) ) if _cnt > 5: continue mask[imgx - 15 : imgx + 15, imgy - 15 : imgy + 15] = True # Plot bars if stdata.get("sknt") is not None and stdata["sknt"] > 1: (u, v) = wind_components( units("knot") * stdata["sknt"], units("degree") * stdata["drct"], ) if u is not None and v is not None: self.ax.barbs(x, y, u.m, v.m, zorder=Z_OVERLAY) # Sky Coverage skycoverage = stdata.get("coverage") if ( skycoverage is not None and skycoverage >= 0 and skycoverage <= 100 ): w = Wedge( (x, y), circlesz, 0, 360, ec="k", fc="white", zorder=2 ) self.ax.add_artist(w) w = Wedge( (x, y), circlesz, 0, 360.0 * skycoverage / 100.0, ec="k", fc="k", zorder=3, ) self.ax.add_artist(w) # Temperature val = stdata.get("tmpf") if val is not None: (offx, offy, ha, va) = offsets[1] self.ax.annotate( stdata.get("tmpf_format", "%.0f") % (val,), xy=(x, y), ha=ha, va=va, xytext=(offx, offy), color=stdata.get("tmpf_color", "r"), textcoords="offset points", zorder=Z_OVERLAY + 2, clip_on=True, fontsize=kwargs.get("fontsize", 8), ) # Dew Point val = stdata.get("dwpf") if val is not None: (offx, offy, ha, va) = offsets[7] self.ax.annotate( stdata.get("dwpf_format", "%.0f") % (val,), xy=(x, y), ha=ha, va=va, xytext=(offx, offy), color=stdata.get("dwpf_color", "b"), textcoords="offset points", zorder=Z_OVERLAY + 2, clip_on=True, fontsize=kwargs.get("fontsize", 8), ) # Plot identifier val = stdata.get("id") if val is not None: (offx, offy, ha, va) = ( offsets[6] if skycoverage is not None else offsets[5] ) self.ax.annotate( f"{val}", xy=(x, y), ha=ha, va=va, xytext=(offx, offy), color=stdata.get("id_color", "tan"), textcoords="offset points", zorder=Z_OVERLAY + 2, clip_on=True, fontsize=kwargs.get("fontsize", 8), ) def plot_values( self, lons, lats, vals, fmt="%s", valmask=None, color="#000000", textsize=14, labels=None, labeltextsize=10, labelcolor="#000000", showmarker=False, labelbuffer=25, outlinecolor="#FFFFFF", zorder=None, **kwargs, ): """Plot values onto the map Args: lons (list): longitude values to use for placing `vals` lats (list): latitude values to use for placing `vals` vals (list): actual values to place on the map fmt (str, optional): Format specification to use for representing the values. For example, the default is '%s'. valmask (list, optional): Boolean list to use as masking of the `vals` while adding to the map. color (str, list, optional): Color to use while plotting the `vals`. This can be a list to specify each color to use with each value. textsize (str, optional): Font size to draw text. labels (list, optional): Optional list of labels to place below the plotting of `vals` labeltextsize (int, optional): Size of the label text labelcolor (str, optional): Color to use for drawing labels showmarker (bool, optional): Place a marker on the map for the label labelbuffer (int): pixel buffer around labels, a value of `0` disables the label culling logic. outlinecolor (color): color to use for text outlines zorder (int or list, optional): zorder to use for plotting. textoutlinewidth (int): width of the font outline, default 3. """ if valmask is None: valmask = [True] * len(lons) if labels is None: labels = [""] * len(lons) if zorder is None: zorder = [Z_OVERLAY + 2] * len(lons) if isinstance(color, str): color = [color] * len(lons) bbox = self.fig.get_window_extent().transformed( self.fig.dpi_scale_trans.inverted() ) axbbox = self.ax.get_window_extent().transformed( self.fig.dpi_scale_trans.inverted() ) axx0 = axbbox.x0 * self.fig.dpi axx1 = (axbbox.x0 + axbbox.width) * self.fig.dpi axy0 = axbbox.y0 * self.fig.dpi axy1 = (axbbox.y0 + axbbox.height) * self.fig.dpi figwidth = bbox.width * self.fig.dpi figheight = bbox.height * self.fig.dpi if self.textmask is None: # zorder is used to track plotting priorities self.textmask = np.zeros((int(figwidth), int(figheight)), np.int8) # Create a fake label, to test out our scaling t0 = self.fig.text( 0.5, 0.5, "ABCDEFGHIJ", transform=self.ax.transAxes, color="None", size=textsize, ) bbox = t0.get_window_extent(self.fig.canvas.get_renderer()) xpixels_per_char = bbox.width / 10.0 ypixels = bbox.height def _find_ax(lon, lat): """Figure out whom this point belongs.""" for ax in self.axes: (x0, x1, y0, y1) = ax.get_extent() (x, y) = ax.projection.transform_point( lon, lat, ccrs.Geodetic() ) if (x0 <= x <= x1) and (y0 <= y <= y1): return ax for o, a, v, m, c, label, z in zip( lons, lats, vals, valmask, color, labels, zorder ): if not m: continue ha = "center" mystr = fmt % (v,) max_mystr_len = max([len(s) for s in mystr.split("\n")]) mystr_lines = len(mystr.split("\n")) # compute the pixel coordinate of this data point ax = _find_ax(o, a) if ax is None: continue (x, y) = ax.projection.transform_point(o, a, ccrs.Geodetic()) (imgx, imgy) = ax.transData.transform([x, y]) imgx0 = int(imgx - (max_mystr_len * xpixels_per_char / 2.0)) if imgx0 < axx0: ha = "left" imgx0 = imgx imgx1 = imgx0 + max_mystr_len * xpixels_per_char if imgx1 > axx1: imgx1 = imgx imgx0 = imgx1 - max_mystr_len * xpixels_per_char ha = "right" # Now we buffer imgx0 = max([0, imgx0 - labelbuffer]) imgx1 = min( [ figwidth, ( imgx0 + 2 * labelbuffer + max_mystr_len * xpixels_per_char ), ] ) imgy0 = max([0, int(imgy) - labelbuffer * 0.75]) imgy1 = min( [ figheight, (imgy0 + mystr_lines * ypixels + 2 * labelbuffer * 0.75), ] ) overlap = ( self.textmask[int(imgx0) : int(imgx1), int(imgy0) : int(imgy1)] >= z ) _cnt = np.sum(overlap) # If we have more than 15 pixels of overlap, don't plot this! if _cnt > 15 and labelbuffer > 0: if self.debug: LOG.info( "culling |%s| due to overlap, %s", repr(mystr), _cnt ) continue if self.debug: rec = plt.Rectangle( [imgx0, imgy0], (imgx1 - imgx0), (imgy1 - imgy0), facecolor="None", edgecolor="r", ) self.fig.patches.append(rec) # Useful for debugging this algo if self.debug: LOG.info( ( "label: %s imgx: %s/%s-%s imgy: %s/%s-%s " "x:%s-%s y:%s-%s _cnt:%s" ), repr(mystr), imgx, axx0, axx1, imgy, axy0, axy1, imgx0, imgx1, imgy0, imgy1, _cnt, ) self.textmask[ int(imgx0) : int(imgx1), int(imgy0) : int(imgy1) ] = np.where( self.textmask[int(imgx0) : int(imgx1), int(imgy0) : int(imgy1)] < z, z, self.textmask[ int(imgx0) : int(imgx1), int(imgy0) : int(imgy1) ], ) t0 = ax.text( o, a, mystr, color=c, size=textsize, zorder=z, va="center" if not showmarker else "bottom", ha=ha, transform=LATLON, ) bbox = t0.get_window_extent(self.fig.canvas.get_renderer()) if self.debug: rec = plt.Rectangle( [bbox.x0, bbox.y0], bbox.width, bbox.height, facecolor="None", edgecolor="k", ) self.fig.patches.append(rec) if showmarker: ax.scatter( o, a, marker="+", zorder=z, color="k", transform=LATLON, ) t0.set_clip_on(True) t0.set_path_effects( [ PathEffects.Stroke( linewidth=kwargs.get("textoutlinewidth", 3), foreground=outlinecolor, ), PathEffects.Normal(), ] ) if label and label != "": ax.annotate( f"{label}", xy=(x, y), ha="center", va="top", xytext=(0, 0 - textsize / 2), color=labelcolor, textcoords="offset points", zorder=z - 1, clip_on=True, fontsize=labeltextsize, ) def scatter(self, lons, lats, vals, clevs, **kwargs): """Draw points on the map Args: lons (list): longitude values lats (list): latitude values vals (list): Data values for the points to use for colormapping clevs (list): Levels to use for ramp **kwargs: additional options """ cmap = stretch_cmap( kwargs.get("cmap"), clevs, extend=kwargs.get("extend") ) norm = mpcolors.BoundaryNorm(clevs, cmap.N) colors = cmap(norm(vals)) self.ax.scatter( lons, lats, c=colors, edgecolors=colors, transform=LATLON, zorder=Z_OVERLAY, ) kwargs.pop("cmap", None) self.draw_colorbar(clevs, cmap, norm, **kwargs) def hexbin(self, lons, lats, vals, clevs, **kwargs): """hexbin wrapper""" cmap = stretch_cmap( kwargs.get("cmap"), clevs, extend=kwargs.get("extend") ) norm = mpcolors.BoundaryNorm(clevs, cmap.N) points = self.ax.projection.transform_points(LATLON, lons, lats) _hex = self.ax.hexbin( points[:, 0], points[:, 1], C=vals, norm=norm, cmap=cmap, zorder=Z_FILL, ) kwargs.pop("cmap", None) self.draw_colorbar(clevs, cmap, norm, **kwargs) return _hex def pcolormesh(self, lons, lats, vals, clevs, **kwargs): """Opinionated mpl.pcolormesh wrapper. If you supply a lons in the same shape of the vals, this method will tack on an extra row and column to make matplotlib happy. If you do not want this, then pass your own lons + lats that is 1 column and 1 row greater than vals. """ cmap = stretch_cmap( kwargs.get("cmap"), clevs, extend=kwargs.get("extend") ) norm = mpcolors.BoundaryNorm(clevs, cmap.N) if lons.shape == vals.shape: # Tack on some extra new = lons[-1, :] * 2 - lons[-2, :] lons = np.r_[lons, [new]] new = lats[-1, :] * 2 - lats[-2, :] lats = np.r_[lats, [new]] new = lons[:, -1] * 2 - lons[:, -2] lons = np.c_[lons, new] new = lats[:, -1] * 2 - lats[:, -2] lats = np.c_[lats, new] res = self.ax.pcolormesh( lons, lats, vals, norm=norm, cmap=cmap, zorder=Z_FILL, transform=LATLON, ) if kwargs.get("clip_on", True): self.draw_mask() kwargs.pop("cmap", None) self.draw_colorbar(clevs, cmap, norm, **kwargs) return res def draw_mask(self, sector=None): """Draw a mask on the main axes. If `sector` is not provided, this attempts to intelligently to the masking the user wants. Args: sector (str,optional): Hard code what type of sector masking should happen. """ sector = self.sector if sector is None else sector # can't mask what we don't have a polygon bounds for. if sector not in ( "iailin", "midwest", "conus", "state", "iowawfo", "cwa", ): return # in lon,lat if sector == "state": s = load_geodf("us_states") mask_outside_geom(self.ax, s.at[self.state, "geom"]) return if sector == "cwa": s = load_geodf("cwa") mask_outside_geom(self.ax, s.at[self.cwa, "geom"]) return if sector == "conus": s = load_geodf("conus") mask_outside_geom(self.ax, s.iloc[0]["geom"]) return if sector == "iowawfo": s = load_geodf("iowawfo") geo = s["geom"].values[0] ccw = np.asarray(geo.exterior.coords)[::-1] else: ccw = load_bounds(f"{sector}_ccw") # in map coords points = self.ax.projection.transform_points( ccrs.Geodetic(), ccw[:, 0], ccw[:, 1] ) mask_outside_polygon(points[:, :2], ax=self.ax) def contourf(self, lons, lats, vals, clevs, **kwargs): """Contourf Args: ilabel (boolean,optional): Should we label contours iline (boolean,optional): should we draw contour lines Returns: vals (np.array): The values used for plotting, maybe after gridding """ if isinstance(lons, list): lons = np.array(lons) lats = np.array(lats) vals = np.array(vals) if np.array(vals).ndim == 1: # We need to grid, get current plot bounds in display proj # Careful here as a rotated projection may have maxes not in ul xbnds = self.ax.get_xlim() ybnds = self.ax.get_ylim() ll = ccrs.Geodetic().transform_point( xbnds[0], ybnds[0], self.ax.projection ) cl = ccrs.Geodetic().transform_point( xbnds[0], sum(ybnds) / 2, self.ax.projection ) ul = ccrs.Geodetic().transform_point( xbnds[0], ybnds[1], self.ax.projection ) uc = ccrs.Geodetic().transform_point( sum(xbnds) / 2, ybnds[1], self.ax.projection ) ur = ccrs.Geodetic().transform_point( xbnds[1], ybnds[1], self.ax.projection ) cr = ccrs.Geodetic().transform_point( xbnds[1], sum(ybnds) / 2, self.ax.projection ) lr = ccrs.Geodetic().transform_point( xbnds[1], ybnds[0], self.ax.projection ) lc = ccrs.Geodetic().transform_point( sum(xbnds) / 2, ybnds[0], self.ax.projection ) xi = np.linspace( min(ll[0], cl[0], ul[0]), max(lr[0], cr[0], ur[0]), 100, ) yi = np.linspace( min(ll[1], lc[1], lr[1]), max(ul[1], uc[1], ur[1]), 100, ) xi, yi = np.meshgrid(xi, yi) nn = NearestNDInterpolator((lons, lats), vals) vals = nn(xi, yi) lons = xi lats = yi window = np.ones((6, 6)) vals = convolve2d( vals, window / window.sum(), mode="same", boundary="symm" ) if lons.ndim == 1: lons, lats = np.meshgrid(lons, lats) cmap = stretch_cmap( kwargs.get("cmap"), clevs, extend=kwargs.get("extend") ) norm = mpcolors.BoundaryNorm(clevs, cmap.N) # vals = maskoceans(lons, lats, vals, resolution='h') self.ax.contourf( lons, lats, vals, clevs, cmap=cmap, norm=norm, zorder=Z_FILL, extend="both", transform=LATLON, ) if kwargs.get("iline", True): csl = self.ax.contour( lons, lats, vals, clevs, colors="w", zorder=Z_FILL_LABEL, transform=LATLON, ) if kwargs.get("ilabel", False): self.ax.clabel( csl, fmt=kwargs.get("labelfmt", "%.0f"), colors="k", fontsize=14, ) if kwargs.get("clip_on", True): self.draw_mask() kwargs.pop("cmap", None) self.draw_colorbar(clevs, cmap, norm, **kwargs) return vals def fill_climdiv(self, data, **kwargs): """Fill climate divisions using provided data dictionary Args: data (dict): A dictionary of climate division IDs and values """ geodf = load_geodf("climdiv") polygon_fill(self, geodf, data, **kwargs) def fill_ugcs(self, data, **kwargs): """Overlay filled UGC geometries Note the importance of the `is_firewx` flag. This determines which UGC database to look at in the face of ambiquity. Args: data(dict): A dictionary of 6 char UGC code keys and values bins(list, optional): Bins to use for cloropleth, default 0:101:10 color(dict, optional): Hard code what each UGC should display as for color. is_firewx(bool, optional): Are we plotting fire weather zones? nocbar (bool, optional): Should a color bar be generated, default is `True`. plotmissing(bool, optional): Should missing UGC data be plotted? labels(dict, optional): UGC indexed dictionary to use for labeling. missingval(str, optional): value to use when labelling UGCs with missing values, defaults to '-'. """ # Figure out if we have zones or counties/parishes counties = True for key in data: if key[2] == "Z": counties = False break zonesfn = "firewx" if kwargs.get("is_firewx", False) else "zone" geodf = load_geodf("ugcs_county" if counties else f"ugcs_{zonesfn}") if self.sector == "state": geodf = geodf[geodf.index.str.slice(0, 2) == self.state] elif self.sector == "cwa": geodf = geodf[geodf["cwa"] == self.cwa] polygon_fill(self, geodf, data, **kwargs) def fill_states(self, data, **kwargs): """Add overlay of filled state polygons""" geodf = load_geodf("us_states") polygon_fill(self, geodf, data, **kwargs) def draw_cwas(self, color="k", **kwargs): """Overlay CWA Borders Draw the CWA border lines on the map. Args: color(str): The color to draw the CWA borders with kwargs(dict, optional): Parameters passed to matplotlib for plotting """ kwargs["edgecolor"] = color cwas = load_geodf("cwa") for _a in self.axes: _a.add_geometries( cwas["geom"].values, crs=LATLON, zorder=Z_POLITICAL, facecolor="None", **kwargs, ) def fill_cwas(self, data, **kwargs): """Add overlay of filled polygons for NWS Forecast Offices. Method adds a colorized overlay of NWS Forecast Offices based on a data dictionary of values provided. This method also places a color bar on the image. Args: data (dict): Dictionary of values with keys representing the 3 char or 4 char idenitifer for the WFO. This assumes the 3 char sites are the K ones. """ geodf = load_geodf("cwa") # Painfull. San Juan's WFO identifier is SJU, but VTEC uses JSJ, our # plotting here uses SJU if "JSJ" in data: data["SJU"] = data["JSJ"] polygon_fill(self, geodf, data, **kwargs) def drawcities(self, **kwargs): """Overlay some cities Args: minpop (int,optional): Minimum population to consider for plotting. labelbuffer (int): approximate number of pixels to compute overlap textsize (int): size of the text color (str): color to plot the text with outlinecolor (str): color to outline the text with """ gdf = load_geodf("cities") (west, east, south, north) = self.ax.get_extent(crs=LATLON) minpop = kwargs.get( "minpop", 50000.0 if self.sector in ["nws", "conus"] else 5000.0 ) df2 = gdf[ ( (gdf["geom"].y > south) & (gdf["geom"].y < north) & (gdf["geom"].x > west) & (gdf["geom"].x < east) & (gdf["pop_2010"] > minpop) ) ] # debug option to test an individual point on the plot # df2 = df[(df['name'] == 'Sioux City')] # hack around a API break tsz = kwargs.pop("textsize", 16) self.plot_values( df2["geom"].x, df2["geom"].y, df2["name"].values, showmarker=True, textsize=tsz, **kwargs, ) def drawcounties(self, color="k"): """Draw counties onto the map Args: color (color,optional): line color to use """ geodf = load_geodf("ugcs_county") self.ax.add_geometries( geodf["geom"].values, crs=LATLON, facecolor="None", edgecolor=color, lw=0.4, zorder=Z_POLITICAL, ) def postprocess(self, **kwargs): """Postprocessing. Args: filename (str): file to save output to. web (bool): Write result to sys.stdout, default False. memcache (obj): write image to memcache memcachekey (str): key to use when writing to memcache. memcacheexpire (int): how long should we persist in memcache, default is 300. pqstr (str): Do pqinsert with the following LDM product name. """ ram = BytesIO() self.fig.savefig(ram, format="png") ram.seek(0) im = Image.open(ram) im2 = im.convert("RGB").convert("P", palette=Image.ADAPTIVE) if kwargs.get("memcache") and kwargs.get("memcachekey"): ram = BytesIO() im2.save(ram, format="png") ram.seek(0) r = ram.read() kwargs["memcache"].set( kwargs["memcachekey"], r, time=kwargs.get("memcacheexpire", 300), ) if kwargs.get("web", False): ssw("Content-Type: image/png\n\n") im2.save(getattr(sys.stdout, "buffer", sys.stdout), format="png") return tmpfd = tempfile.NamedTemporaryFile(delete=False) im2.save(tmpfd, format="PNG") tmpfd.close() if kwargs.get("pqstr") is not None: subprocess.call( f"pqinsert -p '{kwargs.get('pqstr')}' {tmpfd.name}", shell=True, ) if kwargs.get("filename") is not None: shutil.copyfile(tmpfd.name, kwargs.get("filename")) os.unlink(tmpfd.name) def overlay_roadcond(self, valid=None): """Overlay Iowa Winter Road Conditions. Args: valid (datetime.datetime): Valid time for NEXRAD overlay. """ if valid is None: valid = utc() if hasattr(valid, "tzinfo"): valid = valid.astimezone(datetime.timezone.utc) url = ( "https://mesonet.agron.iastate.edu/" "api/1/iowa_winter_roadcond.geojson" ) tstamp = valid.strftime("%Y-%m-%d %H:%M") try: req = requests.get(url, params={"valid": tstamp}, timeout=30) except requests.ConnectionError as exp: warnings.warn(f"overlay_roadcond failed: {exp}") return None df = gpd.GeoDataFrame().from_features(req.json()) labels = [] for _, row in df.iterrows(): for geo in row["geometry"].geoms: self.ax.plot( *geo.xy, transform=LATLON, color=row["color"], linewidth=2 if row["rtype"] > 1 else 4, zorder=Z_OVERLAY2, label=None if row["label"] in labels else row["label"], ) if row["label"] not in labels: labels.append(row["label"]) self.ax.legend( loc=3, ncol=6, fontsize=10, facecolor="white", framealpha=1, ).set_zorder(Z_OVERLAY2 + 5) def overlay_nexrad(self, valid=None, product="N0Q", caxpos=None): """Overlay an IEM NEXRAD Composite Image. Args: valid (datetime.datetime): Valid time for NEXRAD overlay. product (str): either N0Q or N0R for the mosaic type. caxpos (array-like): `matplotlib.axes.set_position` value for the colorbar. Defaults to something in the upper-right. Returns: valid time of the NEXRAD, or None if not found. """ if valid is None: valid = utc() if hasattr(valid, "tzinfo"): valid = valid.astimezone(datetime.timezone.utc) if product not in ["N0R", "N0Q"]: raise ValueError("nexrad `product` not in {N0R,N0Q}") # Rectify to modulus 5 minutes valid -= datetime.timedelta(minutes=(valid.minute % 5)) compsector = "us" if self.sector == "state" and self.state in ["AK", "HI", "PR"]: compsector = self.state.lower() elif self.sector == "cwa" and self.cwa in ["AFG", "AJK", "AFC"]: compsector = "ak" elif self.sector == "cwa" and self.cwa in [ "HFO", ]: compsector = "hi" elif self.sector == "cwa" and self.cwa in [ "SJU", ]: compsector = "pr" baseurl = valid.strftime( "https://mesonet.agron.iastate.edu/archive/data/%Y/%m/%d/" f"GIS/{compsector}comp/{product.lower()}_%Y%m%d%H%M." ) req_png = exponential_backoff( requests.get, baseurl + "png", timeout=10 ) req_wld = exponential_backoff( requests.get, baseurl + "wld", timeout=10 ) if req_png is None or req_png.status_code != 200: LOG.debug("Failed to fetch %spng", baseurl) return None if req_wld is None or req_wld.status_code != 200: LOG.debug("Failed to fetch %swld", baseurl) return None (dx, _, _, dy, west, north) = [ float(x) for x in req_wld.content.decode("ascii").split("\n") ] bio = BytesIO(req_png.content) bio.seek(0) im = np.asarray(Image.open(bio)) # Use rasterio to reproject this grid into the projection of axes with rasterio.Env(): src_aff = rasterio.Affine(dx, 0, west, 0, dy, north) src_crs = {"init": "EPSG:4326"} (px0, px1, py0, py1) = self.ax.get_extent() pbbox = self.ax.get_window_extent() pdx = (px1 - px0) / pbbox.width pdy = (py1 - py0) / pbbox.height dest_aff = rasterio.Affine(pdx, 0, px0, 0, pdy, py0) res = np.zeros( (int(pbbox.height), int(pbbox.width)), dtype=im.dtype ) reproject( im, res, src_transform=src_aff, src_crs=src_crs, src_nodata=0, dst_transform=dest_aff, dst_crs=self.ax.projection.proj4_params, resampling=Resampling.nearest, ) ramp = ramp2df(f"composite_{product.lower()}") cmap = mpcolors.ListedColormap(ramp[["r", "g", "b"]].to_numpy() / 256) cmap.set_under((0, 0, 0, 0)) norm = mpcolors.BoundaryNorm(ramp["coloridx"].values, cmap.N) self.ax.imshow( res, interpolation="nearest", # prevents artifacts extent=(px0, px1, py0, py1), cmap=cmap, norm=norm, zorder=Z_FILL, origin="lower", ).set_rasterized(True) pos = self.ax.get_position() cax = self.fig.add_axes( caxpos or [pos.x1 - 0.35, pos.y1 - 0.01, 0.35, 0.015] ) cb = mpcolorbar.ColorbarBase( cax, cmap=cmap, norm=norm, ticks=ramp.loc[ramp["value"] % 20 == 0]["coloridx"].values, extend="neither", orientation="horizontal", drawedges=False, ticklocation="top", ) cb.set_ticklabels( [ "%.0d" % (d,) for d in ramp.loc[ramp["value"] % 20 == 0]["value"].values ] ) if caxpos is not None: pos = cb.ax.get_position() self.fig.text(pos.x1, pos.y1 + 0.005, "dBZ", ha="left") return valid
goodmind/FlowDefinitelyTyped
flow-types/types/gulp-size_vx.x.x/flow_v0.25.x-/gulp-size.js
<gh_stars>10-100 declare module "gulp-size" { declare interface size$Options { showFiles?: boolean; gzip?: boolean; title?: string; pretty?: boolean; showTotal?: boolean; } declare type size$SizeStream = { size: number, prettySize: string } & NodeJS.ReadWriteStream; declare function size(options?: size$size$Options): size$size$SizeStream; declare module.exports: typeof size; }
Berstanio/moe-core
moe.apple/moe.platform.ios/src/main/java/apple/photosui/PHPickerConfiguration.java
package apple.photosui; import apple.NSObject; import apple.foundation.NSArray; import apple.foundation.NSMethodSignature; import apple.foundation.NSSet; import apple.foundation.protocol.NSCopying; import apple.photos.PHPhotoLibrary; import org.moe.natj.c.ann.FunctionPtr; import org.moe.natj.general.NatJ; import org.moe.natj.general.Pointer; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.Mapped; import org.moe.natj.general.ann.MappedReturn; import org.moe.natj.general.ann.NInt; import org.moe.natj.general.ann.NUInt; import org.moe.natj.general.ann.Owned; import org.moe.natj.general.ann.Runtime; import org.moe.natj.general.ptr.VoidPtr; import org.moe.natj.objc.Class; import org.moe.natj.objc.ObjCRuntime; import org.moe.natj.objc.SEL; import org.moe.natj.objc.ann.ObjCClassBinding; import org.moe.natj.objc.ann.Selector; import org.moe.natj.objc.map.ObjCObjectMapper; /** * A configuration for \c PHPickerViewController. */ @Generated @Library("PhotosUI") @Runtime(ObjCRuntime.class) @ObjCClassBinding public class PHPickerConfiguration extends NSObject implements NSCopying { static { NatJ.register(); } @Generated protected PHPickerConfiguration(Pointer peer) { super(peer); } @Generated @Selector("accessInstanceVariablesDirectly") public static native boolean accessInstanceVariablesDirectly(); @Generated @Owned @Selector("alloc") public static native PHPickerConfiguration alloc(); @Generated @Selector("allocWithZone:") @MappedReturn(ObjCObjectMapper.class) public static native Object allocWithZone(VoidPtr zone); @Generated @Selector("automaticallyNotifiesObserversForKey:") public static native boolean automaticallyNotifiesObserversForKey(String key); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:") public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:") public static native void cancelPreviousPerformRequestsWithTargetSelectorObject( @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector, @Mapped(ObjCObjectMapper.class) Object anArgument); @Generated @Selector("classFallbacksForKeyedArchiver") public static native NSArray<String> classFallbacksForKeyedArchiver(); @Generated @Selector("classForKeyedUnarchiver") public static native Class classForKeyedUnarchiver(); @Generated @Owned @Selector("copyWithZone:") @MappedReturn(ObjCObjectMapper.class) public native Object copyWithZone(VoidPtr zone); @Generated @Selector("debugDescription") public static native String debugDescription_static(); @Generated @Selector("description") public static native String description_static(); /** * Applying a filter to restrict the types that can be displayed. Default is \c nil. * * Setting \c filter to \c nil means all asset types can be displayed. */ @Generated @Selector("filter") public native PHPickerFilter filter(); @Generated @Selector("hash") @NUInt public static native long hash_static(); /** * Initializes new configuration with the system photo library. This configuration never returns asset identifiers. */ @Generated @Selector("init") public native PHPickerConfiguration init(); /** * Initializes new configuration with the \c photoLibrary the picker should use. */ @Generated @Selector("initWithPhotoLibrary:") public native PHPickerConfiguration initWithPhotoLibrary(PHPhotoLibrary photoLibrary); @Generated @Selector("instanceMethodForSelector:") @FunctionPtr(name = "call_instanceMethodForSelector_ret") public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector); @Generated @Selector("instanceMethodSignatureForSelector:") public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector); @Generated @Selector("instancesRespondToSelector:") public static native boolean instancesRespondToSelector(SEL aSelector); @Generated @Selector("isSubclassOfClass:") public static native boolean isSubclassOfClass(Class aClass); @Generated @Selector("keyPathsForValuesAffectingValueForKey:") public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key); @Generated @Owned @Selector("new") @MappedReturn(ObjCObjectMapper.class) public static native Object new_objc(); /** * Preferred representation mode of selected assets. Default is \c PHPickerConfigurationAssetRepresentationModeAutomatic. * * Setting \c preferredAssetRepresentationMode to \c PHPickerConfigurationAssetRepresentationModeAutomatic means the best representation determined by the system will be used. */ @Generated @Selector("preferredAssetRepresentationMode") @NInt public native long preferredAssetRepresentationMode(); @Generated @Selector("resolveClassMethod:") public static native boolean resolveClassMethod(SEL sel); @Generated @Selector("resolveInstanceMethod:") public static native boolean resolveInstanceMethod(SEL sel); /** * Maximum number of assets that can be selected. Default is 1. * * Setting \c selectionLimit to 0 means maximum supported by the system. */ @Generated @Selector("selectionLimit") @NInt public native long selectionLimit(); /** * Applying a filter to restrict the types that can be displayed. Default is \c nil. * * Setting \c filter to \c nil means all asset types can be displayed. */ @Generated @Selector("setFilter:") public native void setFilter(PHPickerFilter value); /** * Preferred representation mode of selected assets. Default is \c PHPickerConfigurationAssetRepresentationModeAutomatic. * * Setting \c preferredAssetRepresentationMode to \c PHPickerConfigurationAssetRepresentationModeAutomatic means the best representation determined by the system will be used. */ @Generated @Selector("setPreferredAssetRepresentationMode:") public native void setPreferredAssetRepresentationMode(@NInt long value); /** * Maximum number of assets that can be selected. Default is 1. * * Setting \c selectionLimit to 0 means maximum supported by the system. */ @Generated @Selector("setSelectionLimit:") public native void setSelectionLimit(@NInt long value); @Generated @Selector("setVersion:") public static native void setVersion_static(@NInt long aVersion); @Generated @Selector("superclass") public static native Class superclass_static(); @Generated @Selector("version") @NInt public static native long version_static(); }
code-signal/code-signal-arcade-bloomtech
S1M2_Task_13/solution.js
<filename>S1M2_Task_13/solution.js function solution(n) { if ( n === 0 ) return "none"; if ( n === 1 ) return "one"; if ( n === 2 ) return "two"; return "some"; }
kenshirokk/springboot_demo
concurrent/src/main/java/com/kenshiro/concurrent/test/Test8.java
package com.kenshiro.concurrent.test; import java.util.concurrent.locks.ReentrantLock; public class Test8 { private static ReentrantLock lock = new ReentrantLock(); public static void main(String[] args) { lock.lock(); try { System.out.println("main"); m1(); } finally { lock.unlock(); } } public static void m1() { lock.lock(); try { System.out.println("m1"); m2(); }finally { lock.unlock(); } } public static void m2() { lock.lock(); try { System.out.println("m2"); }finally { lock.unlock(); } } }
China2B2T/FrostCord
api/src/main/java/net/md_5/bungee/api/Title.java
package net.md_5.bungee.api; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.connection.ProxiedPlayer; /** * Represents a configuration of a title. A title in Minecraft consists of a * main title and a sub title. It will {@link #fadeIn(int)}, {@link #stay(int)}, * and {@link #fadeOut(int)} for a specified amount of time. In most cases you * will want to {@link #reset()} the current title first so your title won't be * affected by a previous one. * <p> * You can create a new configuration by calling * {@link ProxyServer#createTitle()}. */ public interface Title { /** * Set the title to send to the player. * * @param text The text to use as the title. * @return This title configuration. */ public Title title(BaseComponent text); /** * Set the title to send to the player. * * @param text The text to use as the title. * @return This title configuration. */ public Title title(BaseComponent... text); /** * Set the subtitle to send to the player. * * @param text The text to use as the subtitle. * @return This title configuration. */ public Title subTitle(BaseComponent text); /** * Set the subtitle to send to the player. * * @param text The text to use as the subtitle. * @return This title configuration. */ public Title subTitle(BaseComponent... text); /** * Set the duration in ticks of the fade in effect of the title. Once this * period of time is over the title will stay for the amount of time * specified in {@link #stay(int)}. The default value for the official * Minecraft version is 20 (1 second). * * @param ticks The amount of ticks (1/20 second) for the fade in effect. * @return This title configuration. */ public Title fadeIn(int ticks); /** * Set the duration in ticks how long the title should stay on the screen. * Once this period of time is over the title will fade out using the * duration specified in {@link #fadeOut(int)}. The default value for the * official Minecraft version is 60 (3 seconds). * * @param ticks The amount of ticks (1/20 second) for the stay effect. * @return This title configuration. */ public Title stay(int ticks); /** * Set the duration in ticks of the fade out effect of the title. The * default value for the official Minecraft version is 20 (1 second). * * @param ticks The amount of ticks (1/20 second) for the fade out effect. * @return This title configuration. */ public Title fadeOut(int ticks); /** * Remove the currently displayed title from the player's screen. This will * keep the currently used display times and will only remove the title. * * @return This title configuration. */ public Title clear(); /** * Remove the currently displayed title from the player's screen and set the * configuration back to the default values. * * @return This title configuration. */ public Title reset(); /** * Send this title configuration to the specified player. This is the same * as calling {@link ProxiedPlayer#sendTitle(Title)}. * * @param player The player to send the title to. * @return This title configuration. */ public Title send(ProxiedPlayer player); }
frantchico/igrp-catalogo
IGRP-Template/src/main/webapp/images/IGRP/IGRP2.3/core/fileeditor/classes/templates.clss.js
(function(){ var templates = { newItem : function(type){ return '<li class="'+type+' brand-new"><span><input class="adder-input" type="text"/></span></li>'; }, folderOptions : function(){ var r = $('.add-new-options').html(); return r; }, folderFiles : function(files, ulID){ var r = ''; files.forEach(function(f){ var id = f.id || Math.random().toString(36).substr(2, 9), fileName = f.fileName || ''; r+='<li id="'+id+'" class="file" file-name="'+fileName+'" file-path="'+f.path+'" item-name="'+f.name.toLowerCase()+'" title="'+f.name+'">'+ '<span class="txt-ellipsis">'+f.name+'</span>'+ '</li>'; }); return r; }, treeItem : function(i){ var clss = i.dir_files && i.dir_files[0] ? 'folder' : 'file', uniq = Math.random().toString(36).substr(2, 9), id = 'folder'+'_'+uniq, toggleAttr = 'data-toggle="collapse" data-target="#'+id+'"', dirs = i.dir && i.dir[0] ? templates.tree( i.dir, '', '', false) : '', files = i.dir_files && i.dir_files[0] ? templates.folderFiles( i.dir_files, id ) : '', item = '<li id="'+uniq+'" class="folder" dir-path="'+i.dir_path+'" item-name="'+i.dir_name.toLowerCase()+'">'+ '<span class="" '+toggleAttr+'>'+i.dir_name+templates.folderOptions()+'</span>'+ '<div id="'+id+'" class="collapse"><ul>'+ dirs+files+ '</ul></div>'+ '</li>'; return item; }, search : function(){ var html = '<div class="fileeditor-search-wrapper input-group"><input class="form-control fileeditor-searcher" /><span class="input-group-addon s-clear" style="display:none"><i class="fa fa-times"></i></span><span class="input-group-addon"><i class="fa fa-search"></i></span></div>'; return html; }, tree : function(data, id, clss, ul){ id = id || ''; clss = clss || ''; var tree = ul != false ? '<ul id="'+id+'" class="'+clss+'">' : ''; try{ if($.isArray(data)){ data.forEach(function(d){ tree += templates.treeItem(d); }); }else{ tree += templates.treeItem(data); } }catch(err){ console.log(err) } tree+= ul != false ? '</ul>' : ''; return tree; } }; $.IGRP.components.fileeditor.classes.set('templates', templates ); })();
serulian/compiler
generator/es5/tests/serialization/tagged.js
$module('tagged', function () { var $static = this; this.$struct('bad44f92', 'SomeStruct', false, '', function () { var $static = this; var $instance = this.prototype; $static.new = function (SomeField) { var instance = new $static(); instance[BOXED_DATA_PROPERTY] = { somefield: SomeField, }; instance.$markruntimecreated(); return instance; }; $static.$fields = []; $t.defineStructField($static, 'SomeField', 'somefield', function () { return $g.________testlib.basictypes.Integer; }, function () { return $g.________testlib.basictypes.Integer; }, false); this.$typesig = function () { if (this.$cachedtypesig) { return this.$cachedtypesig; } var computed = { "Parse|1|cf412abd<bad44f92>": true, "equals|4|cf412abd<aa28dc2d>": true, "Stringify|2|cf412abd<cb470bcc>": true, "Mapping|2|cf412abd<899aec48<any>>": true, "Clone|2|cf412abd<bad44f92>": true, "String|2|cf412abd<cb470bcc>": true, }; return this.$cachedtypesig = computed; }; }); $static.TEST = $t.markpromising(function () { var $result; var jsonString; var s; var $current = 0; var $continue = function ($resolve, $reject) { localasyncloop: while (true) { switch ($current) { case 0: s = $g.tagged.SomeStruct.new($t.fastbox(2, $g.________testlib.basictypes.Integer)); jsonString = $t.fastbox('{"somefield":2}', $g.________testlib.basictypes.String); $promise.maybe(s.Stringify($g.________testlib.basictypes.JSON)()).then(function ($result0) { $result = $g.________testlib.basictypes.String.$equals($result0, jsonString); $current = 1; $continue($resolve, $reject); return; }).catch(function (err) { $reject(err); return; }); return; case 1: $resolve($result); return; default: $resolve(); return; } } }; return $promise.new($continue); }); });
Marxlp/RLFrame
core/model/nets/mlp_critic.py
import torch.nn as nn from core.model.nets.nn_base import NN import numpy as np class ValueNet(NN): def __init__(self, input_shape, output_shape=(1,), hidden_size=(256, 256), activation='tanh'): super(ValueNet, self).__init__(input_shape, output_shape) hl = [] last_dim = int(np.prod(self.input_shape)) for nh in hidden_size: hl.append(nn.Linear(last_dim, nh)) if activation == 'tanh': hl.append(nn.Tanh()) elif activation == 'relu': hl.append(nn.ReLU()) elif activation == 'sigmoid': hl.append(nn.Sigmoid()) last_dim = nh self.hidden_layers = nn.Sequential(*hl) self.value_head = nn.Linear(last_dim, int(np.prod(self.output_shape))) self.value_head.weight.data *= 0.1 self.value_head.bias.data.zero_() def forward(self, x): x = self.hidden_layers(x.view(x.size(0), -1)) value = self.value_head(x) return self._reshape_output(value)
xXJLMXx/3dmap
untitled folder/src/webgl.js
<filename>untitled folder/src/webgl.js /** * Copyright 2020 (c) <NAME> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ import gl from '/gl'; import utils from '/glUtils'; import track from '/track'; var extensions = ( gl !== null ) ? gl.getSupportedExtensions() : []; // Find missing extensions var needed = [ 'ANGLE_instanced_arrays', 'OES_standard_derivatives' ]; var optional = [ 'WEBGL_depth_texture' ]; var missing = needed.filter( function ( ext ) { return extensions.indexOf( ext ) === -1; } ); var missingOptional = optional.filter( function ( ext ) { return extensions.indexOf( ext ) === -1; } ); // Test for ability to render to textures with different formats // For discussion, see: http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture var testFramebuffer = function ( ext, format ) { var tex, fb; var ok = false; try { // Optionally check for extension if ( ext ) { var hasExt = gl.getExtension( ext ); if ( !hasExt ) { return false; } } tex = gl.createTexture(); gl.bindTexture( gl.TEXTURE_2D, tex ); // Note using RGB for 565 gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 1, 1, 0, gl.RGB, format, null ); gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); fb = gl.createFramebuffer(); gl.bindFramebuffer( gl.FRAMEBUFFER, fb ); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0 ); var status = gl.checkFramebufferStatus( gl.FRAMEBUFFER ); ok = ( status === gl.FRAMEBUFFER_COMPLETE ); } catch ( e ) { ok = false; } finally { if ( tex ) { gl.deleteTexture( tex ) } if ( fb ) { gl.deleteFramebuffer( fb ) } } return ok; }; // The webgl module typically loads before we are ready, so track stats once loaded track.onload = function () { track.event( 'webgl', 'supported', webgl.supported ? 'yes' : 'no' ); track.event( 'webgl', 'render_565', webgl.render565 ? 'yes' : 'no' ); if ( webgl.missing.length > 0 ) { for ( var i = 0; i < webgl.missing.length; i++ ) { track.event( 'webgl', 'missing_extension', webgl.missing[ i ] ); } } if ( webgl.missingOptional.length > 0 ) { for ( var i = 0; i < webgl.missingOptional.length; i++ ) { track.event( 'webgl', 'missing_optional_extension', webgl.missingOptional[ i ] ); } } }; var webgl = { supported: ( gl !== null ), supports: function ( extension ) { return extensions.indexOf( extension ) !== -1; }, extensions: extensions, render565: false, s3tc: false, pvrtc: false, missing: missing, missingOptional: missingOptional, workers: !!window.Worker }; if ( webgl.supported ) { var program = utils.createProgram( 'void main() { gl_Position = vec4( 1.0, 1.0, 1.0, 1.0); }', 'precision mediump float; uniform sampler2D uiiii_tex; void main() { gl_FragColor = texture2D( uiiii_tex, vec2( 0.5, 0.5 ) ); }' ); // Check for ability to render to a 565 texture. If we can do this // we can reduce our memory footprint webgl.render565 = testFramebuffer( null, gl.UNSIGNED_SHORT_5_6_5 ); gl.deleteProgram( program ); program = undefined; // Check texture compression support var s3tc = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' ); var pvrtc = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' ); webgl.s3tc = ( s3tc !== null ); webgl.pvrtc = ( pvrtc !== null ); // Check for depth texture webgl.depthTexture = webgl.supports( 'WEBGL_depth_texture' ); } export default webgl;
CanadaHealthInfoway/message-builder
message-builder-mif-comparer/src/test/java/ca/infoway/messagebuilder/mifcomparer/XmlResequenceFilterTest.java
/** * Copyright 2013 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy$ * Last modified: $LastChangedDate$ * Revision: $LastChangedRevision$ */ package ca.infoway.messagebuilder.mifcomparer; import static ca.infoway.messagebuilder.mifcomparer.Message.MessageType.FILTER; import static ca.infoway.messagebuilder.mifcomparer.Message.Severity.WARNING; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.NamespaceContext; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.custommonkey.xmlunit.XMLUnit; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class XmlResequenceFilterTest extends XmlFilterTest { @Rule public ExpectedException exception = ExpectedException.none(); @Test public void test_that_if_xpath_doesnt_match_then_filter_does_nothing() throws SAXException, IOException { String xml = "<outer><inner seq='2' value='a'/><inner seq='4' value='c'/><inner seq='3' value='b'/></outer>"; performFilterTest( new XmlResequenceFilter(null, "sortKey", "/outer/nonexistent-node"), xml, xml, new Message[]{}); } @Test public void test_that_matching_element_is_resequenced() throws SAXException, IOException { performFilterTest( new XmlResequenceFilter(null, "sortKey", "/outer/inner"), "<outer>" + " <inner sortKey='2' value='a'/>" + " <inner sortKey='9' value='c'/>" + " <inner sortKey='5' value='b'/>" + "</outer>", // N.B.: The sortKey's should get resequenced, and the nodes should also be physically reordered // to match the sequence. "<outer>" + " <inner sortKey='1' value='a'/>" + " <inner sortKey='2' value='b'/>" + " <inner sortKey='3' value='c'/>" + "</outer>", new Message[]{}); } @Test public void test_that_elements_with_nonnumeric_keys_are_reordered_but_key_values_are_preserved() throws SAXException, IOException { performFilterTest( new XmlResequenceFilter(null, "sortKey", "/outer/inner"), "<outer>" + " <inner sortKey='QQ' value='a'/>" + " <inner sortKey='SS' value='c'/>" + " <inner sortKey='RR' value='b'/>" + "</outer>", // N.B.: The sortKey's should get resequenced, and the nodes should also be physically reordered // to match the sequence. "<outer>" + " <inner sortKey='QQ' value='a'/>" + " <inner sortKey='RR' value='b'/>" + " <inner sortKey='SS' value='c'/>" + "</outer>", new Message[]{}); } @Test public void test_that_resequenced_nodes_are_inserted_in_the_proper_place() throws SAXException, IOException { XMLUnit.setCompareUnmatched(true); XMLUnit.setIgnoreWhitespace(true); performFilterTest( new XmlResequenceFilter(null, "sortKey", "/outer/inner"), "<outer>" + " <predecessor/>" + " <inner sortKey='2' value='a'/>" + " <inner sortKey='9' value='c'/>" + " <inner sortKey='5' value='b'/>" + " <follower/>" + "</outer>", // N.B.: The sortKey's should get resequenced, and the nodes should also be physically reordered // to match the sequence. "<outer>" + " <predecessor/>" + " <inner sortKey='1' value='a'/>" + " <inner sortKey='2' value='b'/>" + " <inner sortKey='3' value='c'/>" + " <follower/>" + "</outer>", new Message[]{}); } @Test public void test_that_two_groups_of_nodes_are_resequenced_independently() throws SAXException, IOException { XMLUnit.setCompareUnmatched(true); XMLUnit.setIgnoreWhitespace(true); performFilterTest( new XmlResequenceFilter(null, "sortKey", "/outer/mid/inner"), "<outer>" + " <mid index='1'>" + " <predecessor/>" + " <inner sortKey='2' value='a'/>" + " <inner sortKey='9' value='c'/>" + " <inner sortKey='5' value='b'/>" + " <follower/>" + " </mid>" + " <mid index='2'>" + " <predecessor/>" + " <inner sortKey='7' value='e'/>" + " <inner sortKey='3' value='d'/>" + " <follower/>" + " </mid>" + "</outer>", // N.B.: The sortKey's should get resequenced, and the nodes should also be physically reordered // to match the sequence. "<outer>" + " <mid index='1'>" + " <predecessor/>" + " <inner sortKey='1' value='a'/>" + " <inner sortKey='2' value='b'/>" + " <inner sortKey='3' value='c'/>" + " <follower/>" + " </mid>" + " <mid index='2'>" + " <predecessor/>" + " <inner sortKey='1' value='d'/>" + " <inner sortKey='2' value='e'/>" + " <follower/>" + " </mid>" + "</outer>", new Message[]{}); } @Test public void test_that_missing_sort_key_attr_doesnt_prevent_sorting_other_groups() throws SAXException, IOException { XMLUnit.setCompareUnmatched(true); XMLUnit.setIgnoreWhitespace(true); performFilterTest( new XmlResequenceFilter(null, "sortKey", "/outer/mid/inner"), "<outer>" + " <mid index='1'>" + " <predecessor/>" + " <inner sortKey='2' value='a'/>" + " <inner sortKey='9' value='c'/>" + " <inner sortKey='5' value='b'/>" + " <follower/>" + " </mid>" + " <mid index='2'>" + " <predecessor/>" + " <inner sortKey='6' value='e'/>" + " <inner value='d'/>" + " <follower/>" + " </mid>" + " <mid index='3'>" + " <predecessor/>" + " <inner sortKey='7' value='g'/>" + " <inner sortKey='3' value='f'/>" + " <follower/>" + " </mid>" + "</outer>", // N.B.: The sortKey's should get resequenced, and the nodes should also be physically reordered // to match the sequence. "<outer>" + " <mid index='1'>" + " <predecessor/>" + " <inner sortKey='1' value='a'/>" + " <inner sortKey='2' value='b'/>" + " <inner sortKey='3' value='c'/>" + " <follower/>" + " </mid>" + " <mid index='2'>" + " <predecessor/>" + " <inner sortKey='6' value='e'/>" + " <inner value='d'/>" + " <follower/>" + " </mid>" + " <mid index='3'>" + " <predecessor/>" + " <inner sortKey='1' value='f'/>" + " <inner sortKey='2' value='g'/>" + " <follower/>" + " </mid>" + "</outer>", new Message[]{ new Message(WARNING, FILTER, "Can't sort \"/outer/mid/inner\" elements due to missing \"sortKey\" attribute; expect spurious differences", new File("the-file"), null), }); } @Test public void test_that_matching_element_is_resequenced_with_namespaces() throws SAXException, IOException { performFilterTest( new XmlResequenceFilter(testNsContext, "sortKey", "/x:outer/y:inner"), "<x:outer xmlns:x='http://www.example.com/ns/x' xmlns:y='http://www.example.com/ns/y'>" + " <y:inner sortKey='2' value='a'/>" + " <y:inner sortKey='9' value='c'/>" + " <y:inner sortKey='5' value='b'/>" + "</x:outer>", // N.B.: The sortKey's should get resequenced, and the nodes should also be physically reordered // to match the sequence. "<x:outer xmlns:x='http://www.example.com/ns/x' xmlns:y='http://www.example.com/ns/y'>" + " <y:inner sortKey='1' value='a'/>" + " <y:inner sortKey='2' value='b'/>" + " <y:inner sortKey='3' value='c'/>" + "</x:outer>", new Message[]{}); } @Test public void test_that_missing_sortKeyAttr_causes_the_correct_message() throws SAXException, IOException { performFilterTest( new XmlResequenceFilter(null, "sortKey", "/outer/inner"), "<outer><inner a=\"1\"/></outer>", "<outer><inner a=\"1\"/></outer>", new Message[]{ new Message(WARNING, FILTER, "Can't sort \"/outer/inner\" elements due to missing \"sortKey\" attribute; expect spurious differences", new File("the-file"), null), }); } @Test public void test_that_unparseable_sortKeyAttr_causes_the_correct_message() throws SAXException, IOException { performFilterTest( new XmlResequenceFilter(null, "sortKey", "/outer/inner"), "<outer><inner sortKey=\"not-an-int\"/></outer>", "<outer><inner sortKey=\"not-an-int\"/></outer>", new Message[]{}); } @Test public void test_that_bogus_xpath_expr_causes_the_correct_message() throws SAXException, IOException { String returnMessages = performFilterTestAndReturnMessages( new XmlResequenceFilter(null, "sortKey", "/outer("), // Intentional XPath error: unmatched paren "<outer><inner a=\"b\"/><inner a=\"d\"/></outer>", "<outer><inner a=\"b\"/><inner a=\"d\"/></outer>"); // It's not clear to me why we double the quotes when formatting the message string, but it's clearly deliberate, so we'd better roll with it assertTrue(returnMessages.contains("Error evaluating XPath expr \"\"/outer(\"\":")); assertTrue(returnMessages.contains("Unknown nodetype: outer")); } // Utility methods private List<? extends Node> doXPathQuery(NamespaceContext nsContext, String xpathExpr, Document dom) throws XPathExpressionException { XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); if (nsContext != null) xpath.setNamespaceContext(nsContext); NodeList nodes = (NodeList)xpath.evaluate(xpathExpr, dom, XPathConstants.NODESET); List<Node> list = new ArrayList<Node>(nodes.getLength()); for (int i=0; i<nodes.getLength(); ++i) { list.add(nodes.item(i)); } return list; } }
haiyiyun/plugins
urlmanager/service/serve/urlmanager.go
package serve import ( "net/http" "regexp" "strconv" "strings" "sync" "github.com/haiyiyun/log" ) func parse(r string) (string, string, []flag) { var expr, replace string var flags []flag r = regexp.MustCompile(`[[:blank:]]+`).ReplaceAllString(r, "`") rs := strings.Split(r, "`") lrs := len(rs) if lrs >= 2 { expr = rs[0] replace = rs[1] if lrs >= 3 { flagss := strings.Split(strings.Trim(rs[2], `[]`), ",") for _, f := range flagss { if f == "NC" { expr = `(?i)` + expr continue } var fl flag fs := strings.Split(f, "=") fl = flag{ name: fs[0], } if len(fs) > 1 { fl.param = fs[1] } flags = append(flags, fl) } } } return expr, replace, flags } /* NC - Nocase:URL地址匹配对大小写敏感 S - Skip:忽略之后的规则 R - Redirect:发出一个HTTP重定向 N - Next:再次从第一个规则开始处理,但是使用当前重写后的URL地址 L - Last:停止处理接下来的规则 QSA - Qsappend:在新的URL地址后附加查询字符串部分,而不是替代 */ type flag struct { name string param string } type rule struct { regexp *regexp.Regexp replace string flags []flag } type UrlManager struct { manage bool mustMatch bool rules []rule mutex sync.RWMutex urlCache map[string]string } func New() *UrlManager { return &UrlManager{} } func (u *UrlManager) Cache() bool { return u.mustMatch } func (u *UrlManager) SetCache(cache bool) { u.mutex.Lock() u.mustMatch = !cache u.mutex.Unlock() } func (u *UrlManager) RefreshCache() { u.mutex.Lock() u.urlCache = map[string]string{} u.mutex.Unlock() } func (u *UrlManager) Manage() bool { return u.manage } func (u *UrlManager) Start() { u.mutex.Lock() u.manage = true u.mutex.Unlock() } func (u *UrlManager) Stop() { u.mutex.Lock() u.manage = false u.mutex.Unlock() } func (u *UrlManager) addRule(expr, replace string, flags ...flag) { if expr == "" || replace == "" { log.Warn("expr and reolace is empty") return } r, err := regexp.Compile(expr) if err != nil { log.Warn("regexp compile failed - ", err) return } rl := rule{ regexp: r, replace: replace, flags: flags, } u.mutex.Lock() u.rules = append(u.rules, rl) u.mutex.Unlock() } func (u *UrlManager) doRule(rw http.ResponseWriter, req *http.Request) string { var match bool var out string reqUrl := req.URL in := reqUrl.Path u.mutex.RLock() lrs := len(u.rules) u.mutex.RUnlock() RESTART: for i := 0; i < lrs; i++ { u.mutex.RLock() ur := u.rules[i] u.mutex.RUnlock() if !ur.regexp.MatchString(in) { continue } var skip bool var restart bool var last bool var redirect bool var redirectCode int var queryStringAppend bool if len(ur.flags) > 0 { for _, f := range ur.flags { switch f.name { case "R": redirect = true redirectCode, _ = strconv.Atoi(f.param) if redirectCode == 0 { redirectCode = http.StatusFound } case "S": skip = true skipNum, _ := strconv.Atoi(f.param) //循环后会自动加1,所以这里减1 skipNum = skipNum - 1 if skipNum > 0 { i = i + skipNum } case "N": restart = true case "L": last = true case "QSA": queryStringAppend = true } } } out = ur.regexp.ReplaceAllString(in, ur.replace) if out != in { match = true } if queryStringAppend { if strings.Contains(out, "?") { out += "&" + reqUrl.RawQuery } else { if rawQuery := reqUrl.RawQuery; rawQuery != "" { out += "?" + reqUrl.RawQuery } } } if redirect { http.Redirect(rw, req, out, redirectCode) return `redirect` } if skip { continue } if restart { in = out goto RESTART } if last { break } } if !match { return reqUrl.String() } else { if !u.mustMatch { u.mutex.Lock() u.urlCache[reqUrl.String()] = out u.mutex.Unlock() } } return out } func (u *UrlManager) clearRule() { u.mutex.Lock() defer u.mutex.Unlock() u.rules = make([]rule, 0) } func (u *UrlManager) loadRule(rules string) { for _, r := range strings.Split(rules, "\n") { u.AddRule(r) } } func (u *UrlManager) AddRule(r string) { expr, replace, flags := parse(r) u.addRule(expr, replace, flags...) } func (u *UrlManager) ReWrite(rw http.ResponseWriter, req *http.Request) string { u.mutex.RLock() manage := u.manage cache := !u.mustMatch u.mutex.RUnlock() if !manage { return req.URL.String() } if cache { if u.urlCache == nil { u.urlCache = map[string]string{} } if to, ok := u.urlCache[req.URL.String()]; ok { return to } } return u.doRule(rw, req) } func (u *UrlManager) LoadRule(rules string, reload bool) { if reload { u.clearRule() } u.loadRule(strings.TrimSpace(rules)) }
wavemotion-dave/StellaDS
arm9/source/instructions.cpp
#include <nds.h> #include <stdio.h> #include <fat.h> #include <dirent.h> #include <unistd.h> #include "ds_tools.h" #include "highscore.h" #include "Console.hxx" #include "Cart.hxx" #include "bgInstructions.h" #include "bgBottom.h" extern int bg0, bg0b,bg1b; struct instructions_t { string gameID; const char *text; }; const struct instructions_t instructions[] = { {"ADVENT", "ADVENTURE (C)1980 ATARI\n" "BY <NAME>\n" " \n" "GAME 1: EASY - FIXED LAYOUT\n" "GAME 2: MEDIUM - FIXED LAYOUT\n" "GAME 3: HARD - RANDOM LAYOUT\n" "L-DIFF: A=DRAGON BITES FASTER\n" " \n" "THE EVIL MAGICIAN HAS STOLEN\n" "THE GOLDEN CHALICE. IT'S HIDDEN\n" "SOMEWHERE IN THE REALM AND YOU\n" "MUST FIND IT AND RETURN IT TO\n" "THE YELLOW CASTLE. BEWARE THE\n" "DRAGONS AND BAT WHO LOOK TO\n" "SPOIL YOUR ADVENTURE!\n" }, {"ADTRON", "ADVENTURES OF TRON (C)1982" " \n" "L-DIFF: A=FASTER GAMEPLAY\n" " \n" "TRON! MUST CROSS THE I/O BEAM\n" "TO ALLOW ELEVATORS TO LIFT.\n" "INTERCEPT BITS ON 4 FLOORS.\n" " \n" "BIT ON 1ST FLOOR 100\n" "BIT ON 2ND FLOOR 200\n" "BIT ON 3RD FLOOR 400\n" "BIT ON TOP FLOOR 800\n" "BONUS LEVEL CLEAR 2,000\n" " \n" "PRESS UP/DN TO RIDE ELEVATORS.\n" "WHEN ALL BITS ARE INTERCEPTED\n" "RIDE THE I/O BEAM TO NEXT LEVEL\n" " \n" }, {"ASTERD", "ASTEROIDS (C)1981 ATARI\n" "GAME 1: SLOW, EXTRA LIFE AT 5K\n" "GAME 2: FAST, EXTRA LIFE AT 5K\n" "GAME 3: SLOW, EXTRA LIFE AT 10K\n" "GAME 4: FAST, EXTRA LIFE AT 10K\n" "GAME 6: FAST, EXTRA LIFE AT 20K\n" "GAME 9: SLOW, SHIELDS, LIFE 5K\n" "GAME 10:FAST, SHIELDS, LIFE 5K\n" "GAME 12:FAST, SHIELDS, LIFE 10K\n" "GAME 14:FAST, SHIELDS, LIFE 20K\n" "GAME 16:FAST, SHIELDS, LIFE ---\n" "L-DIFF: A=UFOS + SATELLITES\n" " \n" "SMALL ASTEROIDS 100 PTS\n" "MEDIUM ASTEROIDS 50 PTS\n" "LARGE ASTEROIDS 20 PTS\n" "SATELLITES 200 PTS\n" "UFOS 1000 PTS\n" }, {"ATLANT", "ATLANTIS (C)1982 IMAGIC" " \n" "DEFEND ATLANTIS! BLAST GORGONS\n" "BEFORE THEY DEMOLISH ATLANTIS!\n" " \n" "GAME 1: NORMAL GAME\n" "GAME 2: NO COMMAND POST!\n" "GAME 4: EASY GAME\n" " \n" "SCORING:\n" "LARGE GORGON 100/200 PTS\n" "SMALL GORGON 1000/2000 PTS\n" "BONUS 500 PTS FOR EACH AREA\n" "THAT SURVIVIES GORGON ASSAULT\n" "EXTRA LIFE EVERY 10,000 PTS\n" " \n" }, {"BARNST", "BARNSTORMING\n" "(C)1982 BY ACTIVISION\n" " \n" "BARNSTORM YOUR WAY THROUGH\n" "THE BARNS IN SHORTEST TIME!\n" "\n" "L-DIFF: A=LOW BARNS\n" "R-DIFF: A=MORE GEESE\n" " \n" "GAME 1: 10 BARNS FIXED COURSE\n" "GAME 2: 15 BARNS FIXED COURSE\n" "GAME 3: 15 BARNS FIXED COURSE\n" "GAME 4: 25 BARNS RANDOM COURSE\n" }, {"BAZONE", "BATTLEZONE (C)1983 ATARI\n" " \n" "GAME 1: NOVICE\n" "GAME 2: INTERMEDIATE\n" "GAME 3: ADVANCED\n" "SCORING\n" "TANK 1,000 PTS\n" "FIGHTER 2,000 PTS\n" "SUPERTANK 3,000 PTS\n" "SAUCER 5,000 PTS\n" "BONUS TANK 50K AND 100K\n" }, {"BEAMRI", "BEAMRIDER (C)1984 ACTIVISION\n" " \n" "L-DIFF: A=ADVANCED GAME\n" " \n" "WELCOME TO THE BEAM! THERE ARE\n" "99 SECTORS - A NEW ENEMY SHOWS\n" "UP FOR THE FIRST 16 SECTORS.\n" "15 SAUCERS MUST BE DESTROYED\n" "IN EACH SECTOR THEN THE SECTOR\n" "SENTINEL SHIP APPEARS. ONLY\n" "A TORPEDO WILL TAKE IT OUT.\n" "YELLOW REJUVENATORS=EXTRA LIFE\n" "WHITE AND YELLOW SHIPS ARE\n" "VUNERABLE TO NORMAL FIRE.\n" "PRESS UP TO FIRE TORPEDO (3X)\n" "PRESS UP TO START NEW SECTOR\n" }, {"DODGEM", "DODGE-EM (C)1980 ATARI\n" " \n" "L-DIFF: A=COMPUTER 2X SPEED\n" "R-DIFF: A=COMPUTER RAND START\n" " \n" "EACH DOT REMOVED IS 1 POINT.\n" "BONUS OF 8 PTS PER DOT IF\n" "YOU CLEAR THE ENTIRE SCREEN.\n" }, {"DEFEND", "DEFENDER (C)1982 ATARI\n" " \n" "GM 1: NORMAL SPEED\n" "GM 2: FASTER SPEED\n" "GM 4: SAME AS GM 1 - WAVE 3\n" "GM 7: SAME AS GM 1 - WAVE 5\n" " \n" "L-DIFF: A=SLOWER DEFENDER\n" "POD 1000 PTS\n" "SWARMER 500 PTS\n" "BOMBER 250 PTS\n" "BAITER 200 PTS\n" "LANDER 150 PTS\n" "MUTANT 150 PTS\n" "SAVE HUMAN: 250/500/1000 PTS\n" "BONUS DEFENDER EVERY 10K PTS\n" }, {"DRFIRE", "DRAGONFIRE (C)1982 IMAGIC\n" "CROSS THE BRIDGE TO ENTER THE\n" "TREASURE ROOM AND COLLECT ALL!\n" "GAME 1: START DRAGON 1\n" "GAME 2: START DRAGON 3\n" "GAME 3: START DRAGON 5\n" "GAME 4: START DRAGON 7\n" "JUG 10 PTS\n" "LAMP 10 PTS\n" "GOBLET 10 PTS\n" "HELMET 60 PTS\n" "CANDELABRA 60 PTS\n" "CHEST 200 PTS\n" "HARP 200 PTS\n" "DIAMOND 400 PTS\n" "CROWN 400 PTS\n" }, {"ENDURO", "ENDURO (C)1983 ACTIVISION\n" " \n" "PASS THE REQUIRED NUMBER OF\n" "CARS EACH DAY TO ENDURE!\n" " \n" "PRESS BUTTON TO ACCELERATE\n" "PULL BACK ON JOY TO BRAKE\n" " \n" "MUST PASS 200 CARDS ON FIRST\n" "DAY AND 300 ON SUBSEQUENT DAYS\n" " \n" "YOUR ODOMETER IS YOUR SCORE\n" }, {"COSCOM", "COSMIC COMMUTER\n" "(C)1984 BY ACTIVISION\n" " \n" "LAND YOUR ROCKET MODULE\n" "GET COMMUTERS AT BUS STOPS\n" "BLAST OBSTACLES IN YOUR WAY\n" "RETURN TO ROCKET MODULE\n" " \n" "GAME 1: NORMAL\n" "GAME 2: HARDER\n" " \n" "BONUS BUS EVERY 10000 PTS\n" }, {"MISCOM", "MISSILE COMMAND (C)1981 ATARI\n" " \n" "SAVE ZARDON CITIES FROM ATTACK\n" "GM 1: SLOW TARGET,DUMB CRUISE\n" "GM 2: FAST TARGET,DUMB CRUISE\n" "GM 3: SLOW TARGET,SMART CRUISE\n" "GM 4: FAST TARGET,SMART CRUISE\n" "GM 5: SAME AS 1 - START WAVE 7\n" "GM 9: SAME AS 1 - START WAVE 11\n" " \n" "L-DIFF: A=SLOWER ABMS\n" "IBMS 25 PTS\n" "CRUISE MISSILE 125 PTS\n" "UNUSED ABMS 5 PTS\n" "SAVED CITIES 100 PTS\n" "EVERY ODD WAVE ALL SCORING\n" "MULTIPLIES (2X,3X,4X,5X,ETC)\n" "BONUS CITY EVERY 10,000 PTS\n" }, {"SPAINV", "SPACE INVADERS (C)1980 ATARI\n" " \n" "GAME 1: NORMAL GAME\n" "GAME 2: MOVING SHIELDS\n" "GAME 3: ZIGZAG BOMBS\n" "GAME 4: MOVING SHIELDS+ZIGZAG\n" "GAME 5: FAST BOMBS\n" "GAME 6: MOVING SHIELDS+FAST\n" "GAME 7: ZIGZAG + FAST BOMBS\n" "GAME 8: MOVING+ZIGZAG+FAST\n" "GAME 9: INVISIBLE INVADERS!\n" " \n" "L-DIFF: A=FAT MISSILE BASE\n" " \n" "THE SPACE INVADERS ARE WORTH\n" "5, 10, 15, 20, 25, 30 POINTS IN\n" "THE FIRST THROUGH SIXTH ROWS.\n" "ALIEN MOTHERSHIP IS WORTH 200\n" }, {"SPACAV", "SPACE CAVERN (C)1981 APOLLO\n" " \n" "USE YOUR PHOTON RAY TO DESTROY\n" "SKY ALIENS WHILE USING UP+DN\n" "TO HIT SHAGGY GROUND TARGETS\n" " \n" "GAME 01: LV1 NORMAL\n" "GAME 03: LV1 MORE ALIENS\n" "GAME 07: LV1 RANDOM BLASTS\n" "GAME 17: LV2 NORMAL\n" "GAME 19: LV2 MORE ALIENS\n" "GAME 33: LV3 NORMAL\n" "GAME 35: LV3 MORE ALIENS\n" "L-DIFF: A=FRENZIED MODE\n" "LG ELECTROSAURUS 115 PTS\n" "SM ELECTROSAURUS 165 PTS\n" "SHAGGY MARSUPODS 200 PTS\n" "EXTRA LIFE EVERY 20,000 PTS\n" }, {"SPACET", "SPACE TREAT DELUXE\n" " \n" "GUIDE YOUR SHIP TO COLLECT\n" "FOOD AND BRING BACK TO SAFETY.\n" " \n" "EACH SHIP REMAINING 100 PTS\n" "EACH FUEL REMAINING 10 PTS\n" "NO LIFE LOST ON LEVEL 1000 PTS\n" " \n" "ADDITIONAL BONUS FROM 10-1000\n" "POINTS DEPEND ON LEVEL CLEARED\n" " \n" "THERE ARE 99 LEVELS IN ALL!\n" }, {"STAMPE", "STAMPEED (C)1981 ACTIVISION\n" " \n" "GAME 1: SIDEKICK\n" "GAME 2: PILGRIM\n" "GAME 3: COWPOKE\n" "GAME 4: WRANGLER\n" "GAME 5: TOP HAND\n" "GAME 6: TRAIL BOSS\n" "GAME 7: RANCHER\n" "GAME 8: CATTLE BARON\n" "L-DIFF: A=SHORTER ROPE\n" " \n" "BLACK ANGUS 100 PTS\n" "LIGHT BROWN JERSEYS 25 PTS\n" "MEDIUM BROWN GUERNSEYS 15 PTS\n" "DARK RED HEREFORDS 3 PTS\n" }, {"YARSRE", "YARS' REVENGE (C)1982 ATARI\n" " \n" "GAME 0: EASY - SLOW DESTROYER\n" "GAME 2: NORMAL GAME\n" "GAME 4: HARD - CANNON BOUNCE\n" "GAME 6: ULTIMATE YARS!\n" " \n" "L-DIFF: A=FASTER SWIRLS\n" " \n" "SCORING:\n" "CELL HIT BY MISSILE 69\n" "CELL DEVOURED BY YAR 69\n" "QOTILE DESTROYED 1000\n" "SWIRL DESTROYED IN PLACE 2000\n" "SWIRL DESTROYED IN MID-AIR 6000\n" " \n" "AT 70,000 SWIRL TRIPLES IN FREQ\n" "AT 150,000 SWIRL HEAT SEAKING\n" }, {"FROGGR", "FROGGER (C)1982 PARKER BROS\n" " \n" "GET FROGGIE TO THE OTHER SIDE\n" "BEFORE TIME RUNS OUT!\n" " \n" "GAME 1: NORMAL GAME\n" "GAME 3: FASTER GAME\n" "GAME 5: FASTEST GAME\n" "L-DIFF: A=SIDE SCREEN DEATH\n" " \n" "FROGGER FORWARD 1 PTS\n" "FROGGER HOME 5 PTS\n" "JUMPING 5 FROGS HOME 100 PTS\n" "TAKING LADY FROG HOME 20 PTS\n" "EATING A FLY 20 PTS\n" "BONUS FOR SECONDS LEFT 2 PTS\n" "EXTRA LIFE EVERY 1000 POINTS\n" }, {"OFFROG", "OFFICIAL FROGGER\n" "(C) 1983 ARCADIA\n" " \n" "GET FROGGIE TO THE OTHER SIDE\n" "BEFORE TIME RUNS OUT!\n" " \n" "L-DIFF: A=SIDE SCREEN DEATH\n" " \n" "FROGGER FORWARD 10 PTS\n" "FROGGER HOME 50 PTS\n" "JUMPING 5 FROGS HOME 1000 PTS\n" "TAKING LADY FROG HOME 200 PTS\n" "EATING A FLY 200 PTS\n" "BONUS FOR SECONDS LEFT 10 PTS\n" "EXTRA LIFE EVERY 20000 POINTS\n" }, {"LADBUG", "LADY BUG (C)2006 CHAMP GAMES\n" " \n" "NOVICE: 5 LADY BUGS\n" "STANDARD: 4 LADY BUGS\n" "ADVANCED: 3 LADY BUGS\n" "L-DIFF: A=SLOWER LADY BUG\n" " \n" "BLUE HEART: 2X, 3X, 5X\n" "YELLOW EXTRA: EXTRA LIFE\n" "RED SPECIAL: BOUNTY HARVEST\n" " \n" "EAT FLOWER: 10 PTS\n" "GET BLUE ITEM: 100 PTS\n" "GET YELLOW ITEM: 300 PTS\n" "GET RED ITEM: 800 PTS\n" "VEGGIES ARE 500 PER LEVEL\n" }, {"OYSTRO", "OYSTRON (C)1997 <NAME>\n" " \n" "THREE LEVELS OF DIFFICULTY:\n" "BEGINNER, INTERMEDIATE, ADV\n" "L-DIFF: A=EASIER SHIP BOUNCE\n" " \n" "SHOOT ENEMIES AND TURN THEM\n" "INTO PEARLS. COLLECT PEARLS \n" "DROP THEM IN PEARL ZONE. \n" "8 PEARLS IN ROW = BOMB\n" " \n" "SPACE OYSTER (EACH HIT): 10 PTS\n" "FORMATION DESTROYED: 30 PTS\n" "OYSTRON (WITH A BOMB): 1530 PTS\n" " + (BOMBS LEFT)X100 POINTS\n" " \n" "EXTRA SHIP EVERY 4,000 POINTS\n" }, {"PHASER", "PHASER PATROL (C)1982 STARPATH\n" " \n" "L-DIFF: A=SECTOR MAP, B=COMBAT\n" "R-DIFF: A=HARDER GAME\n" "COLOR: SHIELDS ON/OFF\n" " \n" "DESTROY THE DRACON ARMADA!\n" "USE SECTOR MAP TO FIND ENEMY.\n" "FIND STARBASE FOR REPAIR\n" " \n" "DAMAGE COLOR PER SYSTEM:\n" "GREEN: FULLY OPERATIONAL\n" "YELLOW: SYSTEM DAMAGED\n" "RED: SYSTEM DESTROYED\n" " \n" "RANKS: HERO,ACE,PILOT,GREENHORN\n" }, {"PITFAL", "PITFALL! (C)1982 ACTIVISION\n" " \n" "YOU START WITH 2000 POINTS AND\n" "LOSE POINTS AS MISHAPS OCCUR.\n" "YOU HAVE 20 MINUTES TO COLLECT\n" "ALL 32 TREASURES TO FINISH.\n" " \n" "DIAMOND RING 5000 PTS\n" "GOLD BAR 4000 PTS\n" "SILVER BAR 3000 PTS\n" "MONEY BAG 2000 PTS\n" " \n" "A PERFECT SCORE IS 114,000 PTS\n" }, {"PITFA2", "PITFALL 2 (C)1983 ACTIVISION\n" " \n" "FIND RHONDA, QUICKCLAW, RAT,\n" "DIAMOND AND ALL 28 GOLD BARS.\n" " \n" "START WITH 4000 POINTS.\n" " 5,000 PTS GOLD BAR\n" "15,000 PTS CAVE RAT\n" "20,000 PTS RAJ DIAMOND\n" "10,000 PTS RHONDA RETURN\n" "10,000 PTS QUICKCLAW RETURN\n" " \n" "LOSE PTS FOR FALLS/HAZARDS\n" " \n" "PERFECT SCORE IS 199,000 POINTS.\n" }, {"BERZRK", "BERZERK (C)1982 ATARI\n" " \n" "GAME SELECT:\n" "GAME 1: EXTRA LIFE 1K. NO OTTO\n" "GAME 2: EXTRA LIFE 1K. NOR OTTO\n" "GAME 3: EXTRA LIFE 1K. INV OTTO\n" "GAME 4: EXTRA LIFE 2K. NO OTTO\n" "GAME 5: EXTRA LIFE 2K. NOR OTTO\n" "GAME 6: EXTRA LIFE 2K. INV OTTO\n" " \n" "SCORING:\n" "EACH ROBOT 50 PTS EACH\n" "ALL ROBOT BONUS 10 PTS EACH\n" }, {"CENTIP", "CENTIPEDE (C)1982 ATARI\n" " \n" "GAME SELECT:\n" "GAME 1: EASY PLAY\n" "GAME 2: STANDARD PLAY\n" " \n" "SCORING:\n" "CENTIPEDE BODY 10 PTS\n" "CENTIPEDE HEAD 100 PTS\n" "SPIDER (DISTANT) 300 PTS\n" "SPIDER (MEDIUM) 600 PTS\n" "SPIDER (CLOSE!) 900 PTS\n" "FLEA 200 PTS\n" "SCORPION 1000 PTS\n" "MUSHROOM (DEST) 1 PTS\n" "MUSHROOM (WOUND) 5 PTS\n" "BONUS WAND EVERY 10,000 PTS\n" }, {"COMMIE", "COMMUNIST MUTANTS FROM SPACE\n" "(C)1982 STARPATH CORP \n" " \n" "OPTIONS:\n" "PL 1 NUMBER OF PLAYERS\n" "DIF 1 DIFFICULTY LVL (9=HARD)\n" "SH NO SHIELDS (PRESS DOWN)\n" "TW NO TIME WARP (PRESS UP)\n" "PF NO PENETRATING FIRE\n" "GF NO GUIDED FIRE\n" " \n" "SCORING:\n" "MOTHER CREATURE 500\n" "DIVING MUTANT ATTK 60\n" "MUTANT EGGS 10\n" "CLEARING THE SCREEN 100 \n" "BONUS LIFE AFTER ODD WAVES\n" }, {"DEMONA", "DEMON ATTACK (C)1981 IMAGIC\n" " \n" "GAME SELECT:\n" "1 DEMON ATTACK\n" "3 TRACER SHOT DEMON ATTACK\n" "5 ADVANCED DEMON ATTACK\n" "7 ADVANCED TRACER DEMON ATTACK\n" "L-DIFF: FASTER DEMON ATTACK\n" " \n" "SCORING:\n" "WAVE DEMONS SPLIT DIVE\n" "1-2 10 -- --\n" "3-4 15 -- --\n" "5-6 20 40 80\n" "7-8 25 50 100\n" "9-10 30 60 120\n" "11+ 35 70 140\n" }, {"COSARK", "COSMIC ARK (C)1981 IMAGIC\n" " \n" "SURVIVE THE METEOR SHOWER\n" "AND THEN RESCUE BOTH OF THE\n" "BEASTIES ON THE PLANET!\n" " \n" "GAME SELECT:\n" "GAME 1: REGULAR MISSION\n" "GAME 2: METEOR SHOWER\n" "GAME 4: ADVANCED MISSION\n" "GAME 5: ADVANCED METEOR SHOWER\n" "L-DIFF: A=ARK SIZE WIDER\n" "SCORING:\n" "METEOR 10 PTS\n" "WAVE METEOR 30 PTS\n" "RESCUE BEASTIES: 1000 PTS\n" }, {"CHOPER", "CHOPPER COMMAND\n" "(C)1981 BY ACTIVISION\n" " \n" "KNOCK OUT ENEMY AIRCRAFT\n" "WHILE PROTECTING TRUCKS.\n" " \n" "GAME SELECT:\n" "GAME 1: CADET LEVEL\n" "GAME 3: COMMANDER LEVEL\n" "L-DIFF: A=SLOWER CHOPPER FIRE\n" " \n" "SCORING:\n" "ENEMY COPTER 100 PTS\n" "ENEMY JET 200 PTS\n" "WAVE BONUS/TRUCK: 100 PTS\n" "BONUS SHIP EVERY 10000 PTS\n" }, {"CROSSF", "CROSS FORCE 1982 SPECTRAVISION\n" " \n" "CATCH THE ENEMY IN A CROSSFIRE\n" "GAME 1: DIAGNONAL LASER\n" "GAME 2: PARALELL LASER\n" "L-DIFF: A=SLOW SPECTRON\n" " \n" "WAVE NUMBER SHIP MORPUL\n" "WAVE ONE 10 -- PTS\n" "WAVE TWO 20 20 PTS\n" "WAVE THREE 30 30 PTS\n" "WAVE FOUR+ +10 +10 PTS\n" " \n" "1K - 10K PURPLE HEART\n" "10K - 30K CERT OF HONOR\n" "30K - 50K MEDAL OF VALOR\n" "50K - 70K SPECTRA MEDALLION\n" "70K - 100K MEDAL OF KLIG\n" }, {"ELAVAT", "ELEVATORS AMISS\n" "(C)2007 BY BMONTGOMERY\n" " \n" "GUIDE MAID MARIA TO THE TOP\n" "FLOOR WHILE AVOIDING ELEVATORS\n" " \n" "GAME ELEV BONUS\n" "NORMAL: 7 40 PTS\n" "EXPERT: 7 60 PTS\n" "CHILD: 2 0 PTS\n" "NOVICE: 4 20 PTS\n" " \n" "SCORING:\n" "GET ACROSS FLOOR: TIMER PTS\n" "GET TO TOP FLOOR: BONUS PTS\n" " \n" "PRESS JOY BUTTON FOR SPEED!\n" }, {"RABTRA", "RABBIT TRANSIT (C)1983 ARCADIA\n" " \n" "GUIDE YOUR BUNNY TO THE\n" "BUNNY BUSHES!\n" " \n" "L-DIFF: A=TURTLE SUBMERGES\n" " \n" "SCORING:\n" "EACH HOP SCORES POINTS\n" "BONUS POINTS FOR TIME REMAIN\n" " \n" "EXTRA BUNNY AT 10,000 PTS\n" " \n" }, {"SEAQST", "SEA QUEST (C)1983 ACTIVISION\n" " \n" "RESCUE DIVERS FROM SUBS AND\n" "SHARKS IN THE DEEP OCEAN.\n" "DON'T RUN OUT OF OXYGEN!\n" " \n" "L-DIFF: A=SLOWER FIRE\n" " \n" "SCORING:\n" "SUBS/SHARKS 10 PTS\n" "RESCUED DIVERS 50 PTS\n" "POINTS INCREASE WHEN YOU\n" "BRING 6 DIVERS TO SURFACE\n" "BONUS POINTS FOR OXYGEN REMAIN\n" }, {"RVRAID", "<NAME> (C)1982 ACTIVISION\n" " \n" "DESTROY ENEMIES AS YOU SEEK\n" "BRIDGE AT END OF EVERY SECTION\n" "WATCH YOUR FUEL CONSUMPTION!\n" " \n" "L-DIFF: A=UNGUIDED SHOTS\n" " \n" "SCORING:\n" "TANKER 30 PTS\n" "HELICOPTER 60 PTS\n" "FUEL DEPOT 80 PTS\n" "JET 100 PTS\n" "BRIDGE 500 PTS\n" " \n" "BONUS JET EVERY 10,000 PTS\n" }, {"CIRCUS", "<NAME> (C)1980 ATARI\n" " \n" "POP BALLOONS TO SCORE!\n" " \n" "L-DIFF: A=FASTER CLOWN BOUNCE\n" " \n" "GAME 1: NORMAL BOUNCE\n" "GAME 2: EXTRA WALL\n" "GAME 3: BREAKTHRU (EASIER)\n" "GAME 4: BREAKTHRU + WALL\n" "GAME 5: MUST POP ALL BALOONS\n" "SCORING:\n" "TRAMPOLINE BOUNCE: 1 PTS\n" "RED BALOON POP: 10 PTS\n" "BLUE BALOON POP: 5 PTS\n" "WHITE BALOON POP: 2 PTS\n" "CLEAR ROW BONUS 100/50/20 PTS\n" " \n" }, {"BRKOUT", "BREAKOUT (C)1978 ATARI\n" " \n" "L-DIFF: A=SMALLER PADDLE\n" " \n" "GAME 1: NORMAL BREAKOUT\n" "GAME 2: STEERABLE BALL\n" "GAME 3: CATCHABLE BALL\n" "GAME 4: INSIVISBLE WALL\n" "GAME 5-8: TIMED BREAKOUT\n" "GAME 9-12: BREAKTHRU\n" " \n" "SCORING:\n" "BLUE+AQUA BRICKS 1 PTS\n" "YELLOW+GREEN BRICKS 4 PTS\n" "RED+ORANGE BRICKS 7 PTS\n" " \n" }, {"SUPBRK", "SUPER BREAKOUT (C)1982 ATARI\n" " \n" "L-DIFF: A=SMALLER PADDLE\n" " \n" "GAME 1: NORMAL BREAKOUT\n" "GAME 3: DOUBLE BREAKOUT\n" "GAME 5: CAVITY BREAKOUT\n" "GAME 7: PROGRESSIVE BREAKOUT\n" "GAME 8: CHILDREN'S VERSION\n" " \n" "SCORING:\n" "BLUE+AQUA BRICKS 1 PTS\n" "YELLOW+GREEN BRICKS 4 PTS\n" "RED+ORANGE BRICKS 7 PTS\n" " \n" }, {"BOWLNG", "BOWLING (C)1980 ATARI\n" " \n" "TEN FRAMES TO BOWL.\n" "MAX SCORE IS 300 PTS!\n" " \n" "L-DIFF: A=HARDER TO STRIKE\n" " \n" "SELECT:\n" "GAME 1: CURVE BALL\n" "GAME 3: STEER BALL\n" "GAME 5: STRAIGHT BALL\n" " \n" }, {"MOONPA", "MOON PATROL (C)1983 ATARI\n" " \n" "L-DIFF: A=MUSIC OFF\n" "R-DIFF: A=TWO BUGGY SPEEDS\n" "CHOOSE EASY, MED, HARD GAME\n" " \n" " JUMPING OBSTACLE SHOOTING\n" " 100 PTS SM CRATER --- PTS\n" " 200 PTS LG CRATER --- PTS\n" " 50 PTS LAND MINE --- PTS\n" " 80 PTS ROCK 100 PTS\n" " 100 PTS TANK 200 PTS\n" " --- PTS REGULAR UFO 100 PTS\n" " --- PTS CRATER UFO 200 PTS\n" " --- PTS ENEMY CAR 500/800/1K\n" " \n" "BONUS PTS FOR COMPLETE COURSE\n" "BONUS BUGGY AT 10K,30K,50K\n" }, {"VANGRD", "VANGUARD (C)1982 ATARI\n" " \n" "REACH THE CITY OF MYSTERY AT\n" "TUNNEL END AND DESTROY GOND!\n" " \n" "DIFF A,A: BUTTON+DIR = FIRE\n" "DIFF A,B: AUTO FORWARD FIRE\n" "DIFF B,A: BUTTON STOPS FIRE\n" "DIFF B,B: AUTO FORWARD FIRE\n" " BUTTON STOPS FIRE\n" "HARLEY 50 PTS\n" "MIST 70 PTS\n" "HELM,AMMO 80 PTS\n" "ROMEDA 100 PTS\n" "BARRIER 800 PTS\n" "GARIME,BASE 100-400 PTS\n" "DESTROY GOND 1000-8000 PTS\n" "BONUS LIFE 10K + 50K\n" }, {"KABOOM", "KABOOM! (C)1981 ACTIVISION\n" " \n" "THE MAD BOMBER IS UP TO NO\n" "GOOD. STOP FALLING BOMGS IN\n" "WATER BUCKET USING PADDLES\n" " \n" "L-DIFF A: SMALLER BUCKETS\n" "SCORING:\n" "GROUP #BOMBS EACH TOTALPTS\n" " 1 10 1 10 PTS\n" " 2 20 2 40 PTS\n" " 3 30 3 90 PTS\n" " 4 40 4 160 PTS\n" " 5 50 5 250 PTS\n" " 6 75 6 450 PTS\n" " 7 100 7 700 PTS\n" " 8 150 8 1200 PTS\n" "EXTRA BUCKET EVERY 10K PTS\n" }, {"SPIDFI", "SPIDER FIGHTER\n" "(C)1981 ACTIVISION\n" "PROTECT YOUR FRUIT ORCHARD \n" "FROM INSECT FRUIT ATTACKERS!\n" " \n" "L-DIFF A=EXPERT, B=REGULAR\n" "R-DIFF A=STRAIGHT, B=GUIDED\n" "SCORING:\n" "MASTER NEST 100 PTS\n" "STINGER 50 PTS\n" "SPY POD 50 PTS\n" "GREEN WIDOW 30 PTS\n" "SAVE ALL 3 FRUIT AND GAIN\n" "EXTRA LIFE UP TO FOUR (ELSE\n" "YOU GAIN 500 BONUS PTS)\n" "EXPERT PTS X2 (GRAPE LV),\n" "X4 (STRAW LV),X8 (BANANAS)" }, {"MEGAMA", "MEGAMANIA (C)1981 ACTIVISION\n" "A SPACE NIGHTMARE - BLAST\n" "CRAZY OBJECTS FROM THE SKY!\n" " \n" "GAME 1: GUIDED MISSILES\n" "GAME 3: STRAIGHT MISSILES\n" "L-DIFF A=SLOW MISSILES\n" "HAMBURGERS 20 PTS\n" "COOKIES 30 PTS\n" "BUGS 40 PTS\n" "RADIAL TIRES 50 PTS\n" "DIAMONDS 60 PTS\n" "STEAM IRONS 70 PTS\n" "BOW TIES 80 PTS\n" "SPACE DICE 90 PTS\n" "AFTER 1ST WAVE: 90 PTS\n" "EXTRA LIFE EVERY 10000 PTS\n" }, {"MASH00", "M.A.S.H. (C)1983 20TH CENTURY\n" " \n" "GUIDE YOUR CHOPPER TO RESCUE\n" "WOUNDED ON THE BATTLEFIELD\n" "AND RETURN THEM TO MASH UNIT\n" " \n" "GAME 1: WELCOME TO KOREA\n" "GAME 3: COLONEL POTTER (HARD)\n" "GAME 5: CEASE FIRE\n" "GAME 7: OPERATING ROOM\n" "L-DIFF: START PTS (A=0,B=99)\n" "R-DIFF: START PTS (A=0,B=99)\n" " \n" "FIRST PLAYER TO 999 WINS!\n" }, {"MOONSW", "MOONSWEEPER (C)1983 IMAGIC\n" "RESCUE MINERS STRANDED ON \n" "MOONS IN STAR QUADRANT JUPITER\n" " \n" "GAME 1 BLUE, GREEN MOON (EASY)\n" "GAME 2 BLUE, GREEN AND YELLOW\n" "GAME 3 BLUE, GREEN AND YELLOW\n" "GAME 4 BLUE, GREEN, YEL, RED\n" " \n" "FORCE FIELD: BUTTON + JOY BACK\n" "PICKUP SIX MINERS TO END MOON\n" "PHASE AND ESCAPE GRAVITY VIA\n" "VIA THE ACCELERATION RINGS\n" " \n" "EXTRA MOONSWEEPER EVERY 10K PTS\n" }, {"LASERG", "LASER GATES (C)1983 IMAGIC\n" " \n" "DESTROY 4 FAILSAFE DETONATORS\n" "INSIDE THE COMPUTER BEFORE \n" "THEY SELF-DESTRUCT!\n" " \n" "SHIELDS PROTECT THE DANTE DART\n" "GAIN 6 SHIELD UNITS PER 10K PTS\n" " \n" "PASS FORCEFIELD 400 PTS\n" "DESTROY RADAR MORTAR 115 PTS\n" "DESTROY ROCK MUNCHER 325 PTS\n" "DESTROY BAT 330 PTS\n" "DESTROY HOMING MISSILE 525 PTS\n" "DESTROY DETONATOR 6507 PTS\n" }, {"THUNGR", "THUNDERGROUND (C)1983 SEGA\n" " \n" "DESTROY SIX ATOMIC REACTORS\n" "WHILE AVOIDING TANK FIRE!\n" " \n" "12 LEVELS OF DIFFICULTY WITH\n" "4 ROUNDS PER LEVEL\n" " \n" "ENEMY TANKS: 50 PTS\n" "SHOVEL TOKEN: <PASSWORD>" "WALKIE TOKEN 2<PASSWORD> PTS\n" "KEY TOKEN 3000 PTS\n" "FLAG TOKEN 4000 PTS\n" "40 POINTS PER TIME TICK\n" "\n" "BASES DESTROYED ARE BETWEEN\n" "50 AND 7550 PTS DEPENDING ON\n" "LEVEL AND IF YOU HAVE TOKEN\n" }, {"VENREL", "VENTURE RELOADED (C)2020\n" " \n" "GUIDE WINKY THROUGH 9 LEVELS\n" "AND CAPTURE 36 TREASURES\n" " \n" "DIFF B,B: LEVEL 1\n" "DIFF B,A: LEVEL 2\n" "DIFF A,B: LEVEL 3\n" "DIFF A,A: LEVEL 4\n" " \n" "ENEMIES: 200 PTS\n" "TREASURES: 400 PTS\n" "LEVEL BONUS X LEVEL POINTS\n" " \n" "EXTRA LIFE EVERY 30K PTS\n" "ONLY IF LESS THAN 3 LIVES\n" }, {"KAPERS", "KEYSTONE KAPERS\n" "(C)1983 ACTIVISION\n" " \n" "<NAME> IS AT IT\n" "APREHEND HIM, RECOVERY ITEMS\n" "AND AVOID ALL OBSTACLES.\n" " \n" "SCORING: KROOKS 1-8 ARE\n" "WORTH 100X AMOUNT LEFT ON \n" "BONUS TIMER. KROOKS 9-16 ARE\n" "WORTH 200X BONUS TIMER.\n" "KROOKS 16+ WORTH 300X BONUS.\n" "EACH RECOVERED ITEM IS 50 PTS\n" " \n" "BONUS KOP EVERY 10,000 PTS\n" }, {"AARDVK", "AARDVARK (C)2019\n" " \n" "GUIDE OSCAR'S TONGUE DOWN\n" "THE ANTHILL TO EAT EGGS.\n" " \n" "MODES: NOVICE, EASY, NORMAL,\n" "HARD, EXPERT, WILD1-2-3\n" " \n" "EGG 10 PTS\n" "ANT 100 PTS\n" "RED ANT 150 PTS\n" "CATERPILLAR 150 PTS\n" "WORM 200 PTS\n" "QUEEN 1000 PTS\n" "SPIDER 200 PTS\n" "BONUS = WORMS X ANTS\n" "EXTRA OSCAR BASED ON MODE\n" }, {"TURMOI", "TURMOIL (C)1982 20TH CENTURY\n" " \n" "ZIP UP AND DOWN TO WIPE OUT\n" "ALIENS AND COLLECT PRIZES.\n" " \n" "GAME SELECT IS USED TO \n" "CHOOSE STARTING LEVEL 1-9\n" " \n" "THE FASTER THE ALIENS MOVE,\n" "THE MORE POINTS THEY ARE WORTH\n" " \n" "EXTRA SHIP FOR LEVEL CLEAR\n" }, {"CRAPOT", "CRACKPOTS (C)1983 ACTIVISION\n" " \n" "HELP POTSY DROP POTTED PETUNIAS\n" "ON THE BUG INFESTATION!\n" " \n" "SCORING: BUG COLOR\n" "LV BLACK BLUE RED GREEN\n" " 1 10 20 30 40\n" " 2 20 40 60 80\n" " 3 30 60 90 120\n" " 4 40 80 120 160\n" " 5 50 100 150 200\n" " 6 60 120 180 240\n" " 7 70 140 210 280\n" " 8 80 160 240 320\n" " \n" "200 POINTS ARE AWARDED FOR EACH\n" "BUG REMAINING AT END OF WAVE\n" }, {"ASTROB", "ASTROBLAST (C)1982 MATEL\n" " \n" "DESTROY FALLING ROCKS\n" "L-DIFF: A=AUTO FIRE\n" "R-DIFF: A=FASTER PACE\n" "SCORE+ BG SM SP PUL UFO\n" "0 - 1K 10 20 40 80 ---\n" "1K - 5K 20 40 80 160 ---\n" "5K - 20K 30 60 120 240 ---\n" "20K- 50K 40 80 160 320 400\n" "50,000+ 50 100 200 400 500\n" "SCORE- BG SM SP HIT\n" "0 - 1K 5 10 100 100\n" "1K - 5K 10 20 200 200\n" "5K - 20K 15 30 300 300\n" "20K- 50K 20 40 400 400\n" "50,000+ 25 50 500 500\n" "EXTRA LIFE EVERY 1000 PTS\n" }, {"BUCKRO", "BUCK ROGERS (C)1983 SEGA\n" " \n" "ROUND 1: ELECTRON POSTS\n" "ROUND 2: POSTS + ALIEN SAUCERS\n" "ROUND 3: POSTS + SPACE HOPPERS\n" "ROUND 4: THE MOTHER SHIP!\n" "LEVEL ONE 20 POSTS\n" "LEVEL TWO 23 POSTS\n" "LEVEL THREE 28 POSTS\n" "LEVEL FOUR 33 POSTS\n" "LEVEL FIVE 28 POSTS\n" "LEVEL SIX+ 31+3 POSTS\n" " \n" "SAUCER/HOPPER 300 PTS\n" "ELECTRON POST 500 PTS\n" "MOTHER SHIP 20K PTS\n" "EXTRA SHIP EVERY 50K PTS\n" }, {"CLIMB5", "CLIMBER 5 (C)2004 D.DEBRO\n" " \n" "FETCH YOUR WAYWARD BASEBALL\n" "ON THE TOP LEFT GIRDER.\n" " \n" "GAME TYEPS: NOVICE, INTERMEDIATE\n" "AND ADVANCED\n" "L-DIFF: A=GIRDERS WARNING OFF\n" " \n" "CATCH THESE IN ORDER:\n" "CUP 100 PTS\n" "TEDDY BEAR 300 PTS\n" "BUTTERFLY 500 PTS\n" "AA LOGO 700 PTS\n" "HAMMER, BOX, BRICK 0 PTS\n" "RETRIEVING BALL: BONUS VALUE\n" "EXTRA LIVE AT 10,000 PTS\n" }, {"COMRAI", "COMMANDO RAID (C)1982 US GAMES\n" " \n" "THERE ARE EIGHT LEVELS OF PLAY\n" "EACH LEVEL HAS A DIFFERENT\n" "COLORED PARATROOPER SQUAD.\n" " \n" "B/W SWITCH FOR AUTO FIRE\n" "L-DIFF: A=STRAIGHT BULLETS\n" "R-DIFF: A=NO BOMBER\n" " \n" "HELICOPTER/BOMBER 200 PTS\n" "COMMANDO PARATROOPER 115 PTS\n" "EXTRA BUILDING EVERY 10K PTS\n" }, {"CONMAR", "CONQUEST OF MARS (C)2006 CHAMP\n" " \n" "THERE ARE SIX DEEP CAVERNS TO\n" "NAVIGATE AND ACTIVATE THE BOMB!\n" " \n" "UP/DN SELECT DIFFICULTY LEVEL\n" "B/W SWITCH TO PAUSE GAME\n" "L-DIFF: A=CANNONS WILL FIRE!\n" "TRAVEL ONE PARSEC 10 PTS\n" "FUEL BUNKER 150 PTS\n" "GENERATOR 200 PTS\n" "CANNON / ROCKET 250 PTS\n" "SPACE MINE 300 PTS\n" "2 STAGES CLEAR 2000 PTS\n" "3 STAGES CLEAR 4000 PTS\n" "4 STAGES CLEAR 8000 PTS\n" "5 STAGES CLEAR 15000 PTS\n" "ESCAPE TIME BONUS 500/SEC\n" }, {"CONDOR", "CONDOR ATTACK (C)1982 CHAMP\n" " \n" "A RIFT IN TIME HAS CAUSED\n" "PREHISTORIC CONDOR ATTACK!\n" " \n" "DIFF SWITCHES: A,A=FATTER BASE\n" " \n" "SMALL UPPER ATTACKER 3 PTS\n" "LV 1 LARGE ATTACKER 10 PTS\n" "LV 2 LARGE ATTACKER 20 PTS\n" "LV 3 LARGE ATTACKER 40 PTS\n" "LV 4 LARGE ATTACKER 50 PTS\n" "LV 5 LARGE ATTACKER 60 PTS\n" "LV 6 LARGE ATTACKER 70 PTS\n" "LV 7 LARGE ATTACKER 80 PTS\n" "LV 8 LARGE ATTACKER 90 PTS\n" "LV 9 LARGE ATTACKER 99 PTS\n" "EXTRA FIREBASES EVERY 1000 PTS\n" }, {"DSTOMP", "DRAGONSTOMPER (C)1982 ARCADIA\n" " \n" "PART ONE: ENCHANTED COUNTRYSIDE\n" "PART TWO: THE OPPRESSED VILLAGE\n" "PART THREE: THE DRAGON'S CAVE\n" " \n" "JOYSTICK TO MOVE, FIGHT OR USE\n" "AN ITEM OR MAGIC SPELL. CHECK\n" "STATUS OFTEN - IF STR DROPS TO\n" "BELOW 0 YOU DIE. TO RESSURECT\n" "IN FIRST PART, PRESS RESET BUT\n" "YOU LOSE ALL MAGIC OBJECTS.\n" }, {"FANVOY", "FANTASTIC VOYAGE (C)1982 20TH\n" "INJECTED INTO THE BLOODSTREAM\n" "YOU RACE TO SAVE THE PATIENT!\n" " \n" "GAME 1 = NORMAL GAME\n" "GAME 2 = EXTENDED GAME\n" "GAME 3 = DIFFICULT VERSION \n" "GAME 4 = EXTENDED DIFFICULT\n" "SIX PHASES:\n" "PH1: DEFENSE CELLS : SHOOT\n" "PH2: BLOOD CELLS : NO SHOOT\n" "PH3: BACTERIA : SHOOT\n" "PH4: MIX OF CELLS : NO/SHOOT\n" "PH5: NARROW ARTERY : NO/SHOOT\n" "PH6: BLOOD CLOT : SHOOT\n" "FIRST PATIENT: PH1,2,5,6\n" "SECOND PATIENT: PH1,2,3,5,6\n" "THIRD+ PATIENT: PH1,2,3,4,5,6\n" }, {"FATHOM", "FATHOM (C)1983 IMAGIC\n" " \n" "LOCATE THE 3 MISSING PIECES\n" "NEPTUNE'S TRIDENT AND FREE\n" "HIS DAUGHTER 7 TIMES.\n" "SWITCH FROM DOLPHIN TO GULL\n" "PRESSING BUTTON AT SURFACE\n" " \n" "SCORING:\n" "EACH TIME YOU FREE NEPTINA\n" "YOUR LEVEL POINTS ARE ADDED\n" "TO ALL PREVIOUS POINTS. HIGHER\n" "LEVELS MULTIPLY TO MORE POINTS\n" }, {"FREWAY", "FREEWAY (C)1981 ACTIVISION\n" " \n" "WHY DID THE CHICKEN CROSS\n" "THE ROAD?!\n" " \n" "L-DIFF: A=FULL CURB KNOCK BACK\n" "GM1: LAKE SHORE DRIVE, CHICAGO\n" "GM2: INTERSTATE 5, SEATTLE\n" "GM3: SANTA MONICA FREEWAY, LA\n" "GM4: BAYSHORE FREEWAY, SANFRAN\n" "GM5: JOHN LODGE EXWAY, DETROIT\n" "GM6: THE BELTWAY, WASHINGTON\n" "GM7: LBJ FREEWAY, DALLAS\n" "GM8: LONG ISLAND EXWAY, NYC\n" }, {"KILLER", "KILLER SATELLITES (C)1983 AR\n" " \n" "DESTROY ALL SKY OBJECTS TO\n" "SAVE GROUND OBJECTS.\n" " \n" "USE GAME SELECT TO PICK\n" "THE STARTING WAVE.\n" "L-DIFF: A=FASTER SHIP\n" "R-DIFF: A=SLOWER FIRE\n" " \n" "SKY OBJECTS WORTH 10-90PTS\n" "EACH GROUND OBJECT SAVED 50PTS\n" "EACH WAVE IS 100 PTS X WAVE\n" "BONUS FOR UNUSED FUEL.\n" "EXTRA LIFE EVERY 10,000 PTS\n" }, {"HAUNTH", "HAUNTED HOUSE (C)1982 ATARI\n" " \n" "FIND THE THREE PIECES OF THE\n" "MAGIC URN AND BRING BACK TO THE\n" "MAIN ENTRANCE OF THE MANSION.\n" "USE SCEPTER FOR PROTECTION.\n" "USE KEY TO OPEN LOCKED DOORS.\n" " \n" "L-DIFF: A=NO LIGHT FLASH\n" "GM1 - LIGHTED WALLS, NO DOORS\n" "GM2 - ALL DARK, UNLK DOORS\n" "GM3 - ALL DARK, LOCK DOORS\n" "GM4 - RANDOM MASTER KEY\n" "GM5 - EXTRA SPIDERS\n" "GM6 - CREATURS CROSS ROOMS\n" "GM7 - BAT CAUSES OBJ DROP\n" "GM8 - FASTER CREATURES\n" "GM9 - ULTIMATE CHALLENGE!\n" }, {"GALAXY", "GALAXIAN (C)1983 ATARI\n" " \n" "GAME SELECT = WAVE NUMBER\n" "L-DIFF: A=NO AUTO FIRE\n" " \n" "SCORE FORMATION IN-FLIGHT\n" "GREEN ROWS 30 PTS 60 PTS\n" "PURPLE ROWS 40 PTS 80 PTS\n" "RED ROW 50 PTS 100 PTS\n" "WHITE ROW 60 PTS 120 PTS\n" "FLAGSHIP 200/300/800 PTS\n" " \n" "EXTRA LIFE AT 7000 PTS\n" }, {"PACMAN", "PAC-MAN (C)1982 ATARI\n" " \n" "L-DIFF: A=ADVANCED GAME\n" "GM1: SLOW PAC, SLOW GHOSTS\n" "GM2: SLOW PAC, FAST GHOSTS\n" "GM3: FAST PAC, SLOW GHOSTS\n" "GM4: FAST PAC, FAST GHOSTS\n" "GM5: FAST PAC, FASTER GHOSTS\n" "GM6: FAST PAC, FASTEST GHOSTS\n" " \n" "VIDEO WAFER 1 PT\n" "POWER PILL 5 PTS\n" "VITAMINS 100 PTS\n" "FIRST GHOST 20 PTS\n" "SECOND GHOST 40 PTS\n" "THIRD GHOST 80 PTS\n" "FOURTH GHOST 160 PTS\n" "EXTRA LIFE EVERY BOARD CLEAR\n" }, {"PHOENX", "PHOENIX (C)1982 ATARI\n" " \n" "L-DIFF: A=BIRD SOUND OFF\n" "PRESS DOWN FOR SHIELD\n" " \n" "SCORING VARIES DEPENDING\n" "ON WAVE, SWOOPING BIRDS,\n" "PROXIMITY TO SHIP, ETC.\n" }, {"QUICKS", "QUICK STEP! (C)1983 IMAGIC\n" " \n" "CHANGE TRAMPOLINES COLOR AS\n" "YOU JUMP ON THEM. LAND ON THE\n" "PINK TRAMPOLINES TO SCORE." " \n" "BONUS OF 200 PTS FOR EACH\n" "LIFE LEFT WHEN OPP DIES.\n" "BONUS LIFE AT 2000 PTS\n" }, {"STAVOY", "STAR VOYAGER (C)1982 IMAGIC\n" " \n" "PENETRATE THE 7 STAR PORTALS\n" "AND SAVE CAPITAL STARPORT!\n" " \n" "L-DIFF: A=ACCELERATED ACTION\n" "R-DIFF: A=LASERS, B=PHOTONS\n" "SCORE: NUMBER OF ENEMIES * 5\n" " +10 PER STAR PORTAL\n" " 0-15 AWOL\n" " 16-47 (ONE CHEVRON)\n" " 48-79 (TWO CHEVRONS)\n" " 80-111 (THREE CHEVRONS)\n" "112-143 (FOUR CHEVRONS)\n" "144-175 LIEUTENANT\n" "176-207 CAPTAIN\n" "208- ADMIRAL\n" }, {"MSPACM", "MS PAC MAN (C)1982 ATARI\n" "GM CHERRIES - NORMAL GAME \n" "GM 1 BEAR - BEGINNER \n" "GM 2 BEARS - NOVICE \n" "GM 3 BEARS - INTERMEDIATE \n" " \n" "DOT 10 PTS\n" "ENERGY PILL 50 PTS\n" "CHERRY 100 PTS\n" "STRAWBERRY 200 PTS\n" "ORANGE 500 PTS\n" "PRETZEL 700 PTS\n" "APPLE 1000 PTS\n" "PEAR 2000 PTS\n" "BANANA 5000 PTS\n" "GHOSTS 200/400/800/1600 PTS\n" "EXTRA LIFE AT 10,000 PTS\n" }, {"SOLARI", "SOLARIS (C)1986 ATARI\n" " \n" "HYPERWARP ACROSS SECTORS OF\n" "THE GALAXY TO REACH SOLARIS!\n" " \n" "CORRIDOR NAVIGATE 8,000 PTS\n" "RESCUING ALL CADETS 8,000 PTS\n" "FLAGSHIP 500 PTS\n" "RAIDER 400 PTS\n" "KOGALON STAR PIRATE 320 PTS\n" "TARGETER 320 PTS\n" "GLIDER 320 PTS\n" "MECHNOID 300 PTS\n" "BLOCKADER 260 PTS\n" "COBRA SHIP 80 PTS\n" "GUARDIAN 60 PTS\n" "DISTRACTOR 20 PTS\n" "PRESS Y BUTTON FOR GALACTIC MAP\n" }, {"RAIDER", "RAIDERS OF THE LOST ARK (C)1986\n" " \n" "HELP INDY FIND THE LOST ARK!\n" "USE X,Y,A,B TO MANAGE INVENTORY\n" " \n" "FLUTE PROTECTS FROM SNAKES\n" "COINS ARE USED TO BUY ITEMS\n" "GRENADE TO BLAST BARRIERS\n" "KEY USED TO OPEN DOORS\n" "WHIP CLOSE COMBAT ATTACK\n" "PARACHUTE TO LAND SAFELY\n" "TIMEPIECE TELLS IN-GAME TIME\n" "REVOLVER LONG RANGE ATTACK\n" "BULLETS FOR THE REVOLVER\n" "ANKH TRANSPORT TO MESA FIELD\n" "CHAI TRANSPORT TO BLACK MARKET\n" "HOURGLASS OBTAIN GRAPLING HOOK\n" "SHOVEL IS USED FOR DIGGING\n" }, {"WIZWOR", "WIZARD OF WOR (C)1982\n" " \n" "OUTWITTING AND OUTBLAST THE\n" "SINISTER WIZARD OF WOR!\n" " \n" "L-DIFF: A=HARDER ENEMIES\n" " \n" "SCORING:\n" "BLUE BURWORS 100 PTS\n" "YELLOW GARWORS 200 PTS\n" "RED THORWORS 500 PTS\n" "WORLUK 1000 PTS\n" "WIZARD OF WOR 2500 PTS\n" "EXTRA LIFE AT 10,000 PTS\n" }, {"CARNIV", "CARNIVAL (C)1982 COLECO\n" " \n" "CLEAR THE RACK OF ALL TARGETS\n" "AND PIPES TO ADVANCE LEVEL.\n" " \n" "SCORING:\n" "TARGET LV1 LV2 LV3 LV4\n" "PIPE 200 200 200 200\n" "BOTTOM ROW 20 30 40 50\n" "MIDDLE ROW 40 50 60 70\n" "TOP ROW 60 70 80 90\n" "EXTRA BULLET 8 8 8 8\n" " \n" "TWO CONSECUTIVE PIPES OF SAME\n" "COLOR EARN BONUS OF 200/800 PTS\n" "GALLERY CLEAR BONUS 50 PTS/SHOT\n" }, {"Z-TACK", "Z-TACK (C)1983 BOMB\n" " \n" "GAME 1: BEGINNER\n" "GAME 3: ADVANCED\n" " \n" "THERE ARE 6 DISTINCT LEVELS\n" "IN ONE COMPLETE CYCLE AND THE\n" "GAME PATTERN WILL RECYCLE.\n" " \n" "MAXIMUM SCORE IS 999,999\n" }, {"WALDEF", "WALL DEFENDER (C)1983 BOMB\n" " \n" "THE OUTER WALL TAKE 10 HITS\n" "SUPER ALIEN TAKES OUT WALL\n" "WALL COLOR DEEPS WITH DAMAGE\n" "MOVE TO INNER WALL WHEN THE\n" "OUTER WALL IS ALMOST GONE.\n" " \n" "MAXIMUM SCORE IS 999,999\n" }, {"EARTHW", "EARTH WORLD (C)1982 ATARI\n" "TRAVERSE THE 12 ROOMS OF THE\n" "ZODIAC. A VARIETY OF MAGICAL\n" "OBJECTS ASSIST YOUR QUEST.\n" "BY LEAVING THE RIGHT OBJECTS\n" "IN THE RIGHT ROOMS, YOU GET\n" "CLUES TO PUZZLES. THIS GAME\n" "REQUIRES USE OF THE COMIC\n" "THAT CAME WITH IT.\n" " \n" "FINAL SEQUENCE TRIGGERS WHEN\n" "YOU HAVE PERFORMED 15 TRIALS\n" }, {"FIREWO", "FIRE WORLD (C)1982 ATARI\n" " \n" }, {"WATERW", "WATER WORLD (C)1983 ATARI\n" " \n" }, {"STARTR", "STAR TREK (C)1983 SEGA\n" " \n" "DESTROY NOMAD! SIX ROUNDS\n" "OF ADVENTURE AS FOLLOWS:\n" "1-2 : KLINGON ENCOUNTER\n" "3 : ASTEROIDS/METEORS\n" "4-5 : KLINGON ENCOUNTER\n" "6 : NOMAD!\n" " \n" "SHIELD CONDITIONS:\n" "YELLOW : 3+ STRENGTH\n" "ORANGE : 2 STRENGTH\n" "LIGHT RED : 1 STRENGTH\n" "DARK RED : DEFENSES DOWN!\n" "DOCK W STARBASE TO REFUEL\n" }, {"SPJOCK", "SPACE JOCKEY (C)1982 USGAMES\n" " \n" "L-DIFF: A=FASTER ENEMY SHOT\n" "R-DIFF: A=FREQUENT ENEMY SHOT\n" " \n" "GAME 1: NORMAL\n" "GAME 2: GUIDED SHOT\n" "GAME 3: RANDOM ENEMIES\n" "GAME 5: HORIZONTAL MOVE\n" "GAME 9: COLLISIONS ON\n" "GAME 16: THE KITCHEN SINK!\n" "SCORING:\n" "JET PLANE 100 PTS\n" "HELICOPTER 50 PTS\n" "PROP PLANE 100 PTS\n" "BALLOON 25 PTS\n" "TANK 100 PTS\n" "HOUSE/TREE 20 PTS\n" }, {"PLAQUE", "PLAQUE ATTACK (C)1983 ACTIVSN\n" " \n" "YOU HAVE 35 SECONDS TO WIPE\n" "OUT EACH WAVE OF FOOD!\n" "L-DIFF: A=SLOWER FIRE\n" "GAME 1: NORMAL\n" "GAME 3: BEGINNER GAME\n" "SCORING:\n" "WV FOOD HIT SECS TEETH\n" "1 HAMBURGERS 5 5 5\n" "2 HOT DOGS 10 10 20\n" "3 FRIES 15 15 45\n" "4 STRAWBERRIES 20 20 80\n" "5 GUM DROPS 25 25 125\n" "6 DONUTS 30 30 150\n" "7 CANDY CANES 35 35 175\n" "8 ICE CREAM 40 40 200\n" "BONUS TOOTH EVERY 2000 POINTS\n" }, {"BERMUD", "BERMUDA TRIANGLE (C)1982 DATA\n" " \n" "COLLECT SUNKEN TREASURES FROM\n" "THE OCEAN FLOOR AND DELIVER\n" "TO A RESEARCH SHIP ON SURFACE\n" "WATCH OUT FOR MINES AND ENEMY\n" "SHIPS THAT STEAL YOUR CARGO.\n" "L-DIFF: A=ADVANCED GAME\n" "GAME 1: LASERS AFTER 10,000\n" "GAME 3: LASERS AT START\n" " \n" "SCORING:\n" "KILLER SHARK 200 PTS\n" "GIANT SQUID 200 PTS\n" "AQUATIC DRONE 200 PTS\n" "ARTIFACT TO SURFACE 600 PTS\n" " \n" "EXTRA LIFE EVERY 10000 PTS\n" }, {"TACSCN", "TAC-SCAN (C)1982 BY SEGA\n" " \n" "WIPE OUT 10 ENEMY SHIPS ANDN" "BRING IN REINFORCEMENTS ON\n" "EACH OF 15 POSSIBLE LEVELS.\n" "\n" "SCORING:\n" "LEVEL 1HIT ROUND 3HIT 4HIT\n" "LV1 100 1000 10K 20K PTS\n" "LV2 200 2000 10K 20K PTS\n" "LV3 300 5000 10K 20K PTS\n" "LV4 400 20000 10K 20K PTS\n" "LV5+ ETC 20000 10K 20K PTS\n" " \n" "COLORED SHIP BONUS IS 500 PTS\n" "HIGHER SCORES FOR HITTING 3 OR\n" "4 ENEMIES WITH ONE SALVO.\n" }, {"SEAHWK", "SEA HAWK (C)1983 BY FROGGO\n" " \n" "DODGE ENEMY FIRE AND USE YOUR\n" "GUNS AND TORPEDOS TO SURVIVE.\n" " \n" "INTENSITY INCREASES AT 10K\n" "AND AGAIN AT 30K. PRESS BUTTON\n" "ALONG WITH LEFT/RIGHT TO FIRE.\n" " \n" "L-DIFF: A=FASTER GAME\n" "USE SELECT FOR TORPEDO SIZE\n" " \n" "POINTS SCALE UP AS YOU GO FROM\n" "LEVEL 1,2,3 - BE CAREFUL NOT TO\n" "SHOOT DOWN YOUR OWN SHIPS!\n" " \n" "BONUS LIFE EVERY 20 HELICOPTERS\n" }, {"SABOTR", "SABOTEUR (C)1983 BY ATARI\n" "COMPLETED PROTOTYPE GAME.\n" "RACE AGAINST TIME TO DISARM\n" "WARHEADS ACROSS THREE SCREENS.\n" "L-DIFF: A=29 SECS B=38 SECS\n" "GAME 1: NORMAL\n" "GAME 2: SHOTS REFLECT\n" "GAME 3: SIDE BULLETS APPEAR\n" "GAME 4: INSANE SPEED!\n" "QOTILE ROBOT: 23 PTS\n" "YAR FLY: 198 PTS\n" "MASTER ROBOT: 57 PTS\n" "SIDE BULLET: 33 PTS\n" "GORFON SAFE TRIP: 71 PTS\n" "ROCKET DISTANCE: 22 PTS\n" "WARHEAD PIECES: 33/495 PTS\n" "TIME LEFT: 99 PTS\n" "DESTROY WARHEAD: 600 PTS\n" }, {"POLEPO", "POLE POSITION (C)1983 ATARI\n" " \n" "QUALIFYING LAP AND GRAND PRIX\n" "YOU EARN 10,000 PTS FOR LAP\n" "AND 50 PTS FOR EACH CAR PASSED.\n" "QUALIFYING LAP IS 90 SECS BUT\n" "YOU MUST COMPLETE IN 73 SECS TO\n" "QUALIFY FOR A POLE POSITION!\n" " \n" "JOYSTICK UP FOR LOW GEAR\n" "JOYSTICK DN FOR HIGH GEAR\n" "USE BUTTON TO BRAKE CAR\n" " \n" }, {"MINDMA", "ESCAPE FROM THE MIND MASTER\n" "(C)1983 BY STARPATH \n" " \n" "CARRY AND FIT GEOMETRIC KEYS\n" "INTO MATCHING SLOTS ON WALLS\n" "TO UNLOCK DOOR TO NEXT LEVEL.\n" "WATCH OUT FOR THE MINDMASTERS\n" "TRICKY MINI-GAMES AND BEWARE\n" "THE LOST ALIEN ALSO TRAPPED\n" "IN THE MAZE. WHEN YOU FINALLY\n" "ARE DONE, THE MINDMASTER WILL\n" "EVALUATE YOUR ATTEMPT!\n" }, {"POLARI", "POLARIS (C)1982 TIGERVISION\n" " \n" "WATCH OUT FOR DANGER FROM\n" "ABOVE AND BELOW!\n" "BOMBER SQUADRON: 300/200/100\n" "ENEMY SUBMARINES: 100/200/300\n" "ENEMY DESTROYER: 800 PTS\n" "CHANNEL MINES: 300 PTS\n" "DIVE BOMBER: 1000 PTS\n" " \n" "LV PLANES BOMBS SUBS SPEED\n" " 1 2 1 1 SLOW\n" " 2 3 1 1 SLOW\n" " 3 4 1 2 SLOW\n" " 4 5 1 3 SLOW\n" "5-8 ETC ETC ETC MED \n" "9-12 ETC ETC ETC FAST\n" "13-16 ETC ETC ETC VFAST\n" }, {"LEAD01", "LEAD (C)2008 <NAME>\n" " \n" "SURVIVE WAVE AFTER WAVE OF\n" "ONCOMING ENENIES!\n" " \n" "1ST STAGE: FIRE STAGE\n" "2ND STAGE: DODGE STAGE\n" "3RD STAGE: SCRAMBLE STAGE\n" "4TH STAGE: CATCH STAGE\n" " \n" "L-DIFF: A=EXPERT GAME\n" "R-DIFF: A=SAFE SMART BOMB\n" " \n" "YOU GET 3 PTS FOR ENEMIES ON\n" "STAGES 1-3 AND 5 PTS ON STAGE\n" "4 PLUS A STAGE CLEAR BONUS.\n" "DOWN ACTIVATES SMART BOMB BUT\n" "CAUSES SCORE TO ROUND DOWN.\n" }, {"GOFISH", "GO FISH (C)2007 B.MONTGOMERY\n" "EAT OR BE EATEN!\n" "L-DIFF: A=START AS BIG FISH\n" " \n" "FISH POINTS AND ADVANCE SCORE:\n" "LV1: 1 PTS 5 PTS TINY WHITE\n" "LV2: 2 PTS 19 PTS TINY GREEN\n" "LV3: 4 PTS 55 PTS TINY YELLW\n" "LV4: 7 PTS 132 PTS TINY RED\n" "LV5: 10 PTS 262 PTS MED GREEN\n" "LV6: 15 PTS 487 PTS MED BLACK\n" "LV7: 20 PTS 827 PTS MED WHITE\n" "LV8: 25 PTS 1302 PTS MED BROWN\n" "LV9: 35 PTS 2037 PTS BIG PINK\n" "L10: 45 PTS 3071 PTS BIG GREEN\n" "L11: 55 PTS 4446 PTS BIG GREY\n" "L12: 65 PTS 6203 PTS BIG RED\n" "L13: 80 PTS ---- PTS HUGE RED\n" }, {"HELWAY", "HELLWAY (C)2021\n" "M0: CYCLE TRAFFIC\n" "M1: CONSTANT TRAFFIC\n" "M2: M0 + RANDOM TRAFFIC\n" "M3: M1 + RANDOM TRAFFIC\n" "M4: M0+BIGGER SPEED DIFFS\n" "M5: M1+BIGGER SPEED DIFFS\n" "M6: M2+BIGGER SPEED DIFFS\n" "M7: M3+BIGGER SPEED DIFFS\n" "M8: M0+RANDOM CHKPT INTENSITY\n" "M9: M1+RANDOM CHKPT INTENSITY\n" "MA: M2+RANDOM CHKPT INTENSITY\n" "MB: M3+RANDOM CHKPT INTENSITY\n" "MC: M4+RANDOM CHKPT INTENSITY\n" "MD: M5+RANDOM CHKPT INTENSITY\n" "ME: M6+RANDOM CHKPT INTENSITY\n" "MF: M7+RANDOM CHKPT INTENSITY\n" "DIF: BB 29S DIF BA 34S\n" "DIF: AB 39S DIF AA 44S\n" }, {"SPGAME", "SPACEGAME (C)2020 <NAME>\n" "DESTROY INVADING ENEMIES AND\n" "DONT LET SMART BOMB HIT GROUND\n" "L-DIFF: A=DOUBLE WIDE SHIP\n" "R-DIFF: A=ENEMIES SHOOT FAST\n" " \n" "POWER UPS: DOUBLE SHIP, WIDE\n" "SHIP, FAST SHIP, SLOW SHIP,\n" "BAD NAV, BLAST SHIELD, BAD\n" "GUNS, POWER DOWN, RANDOM ???\n" " \n" "SCORING:\n" "EACH ALIEN: 75 PTS\n" "GROUP ALIENS: 50 PTS\n" "BOSS KILL: 500 PTS\n" "NO COLLISIONS: 300 PTS\n" "EACH COLLISION: -50 PTS\n" "EXTRA LIFE AT 20K AND 100K\n" }, {"ALIEN0", "ALIEN (C)1982 20TH CENT FOX\n" "IN SPACE... NO ONE CAN HEAR\n" "YOU SCREAM! CLEAR EGGS.\n" "L-DIFF: A=RANDOM ALIEN MOVE\n" "R-DIFF: A=PULSAR HAS NO EFFECT\n" "GAME 1: NORMAL GAME\n" "GAME 2: ADVANCED GAME\n" "GAME 3: EXPERT GAME\n" "EGGS: 10 PTS\n" "PULSAR: 100 PTS\n" "1ST ALIEN: 500 PTS\n" "2ND ALIEN: 1000 PTS\n" "3RD ALIEN: 2000 PTS\n" "COMPLETE SCREEN: 1 PTS\n" "ROCKET: 500 PTS\n" "SATURN: 1000 PTS\n" "STARSHIP: 2000 PTS\n" "EXTRA LIFE AFTER 2ND SCREEN\n" }, {"BEANYB", "BEANY BOPPER (C)1982 20TH CENT\n" "CAPTURE BEANIES+FALLING OBJS\n" "OPTION 1: BEANIES BOUNCE\n" "OPTION 2: BEANIES DON'T BOUNCE\n" "ADVANCEMENT:\n" "LEVEL 0 = 0-999 PTS\n" "LEVEL 1 = 1,000 - 2,999 PTS\n" "LEVEL 2 = 3,000 - 4,999 PTS\n" "LEVEL 3 = 5,000 - 9,999 PTS\n" "LEVEL 4 = 10,000 - 19,999 PTS\n" "LEVEL 5 = 20,000 - 29,999 PTS\n" "LEVEL 6 = 30,000 - 49,999 PTS\n" "LEVEL 7 = 50,000+ PTS\n" "BEANY STUNNED/CAPTURED: 20/100+\n" "FALLING OBJ STUN/CAPT: 20/100+\n" "ORANGE EYE STUN/CAPT: 100/100+\n" "SURPRISE AT 100,000 POINTS!\n" "EXTRA BOPPER EVERY 4 BEANIES\n" }, {"DEMDIA", "DEMONS 2 DIAMONDS (C)1982 ATARI\n" " \n" "HIT DEMONS OF YOUR COLOR AND\n" "THEN HIT DIAMOND FOR BONUS PTS\n" " \n" "L-DIFF: A=FASTER DEMON FIRE\n" "GAME 1: NORMAL GAME\n" "GAME 4: EASY GAME\n" "DEMON OF YOUR COLOR: 1-8 PTS\n" "PULSATING DIAMONDS: 10-80 PTS\n" "HIGHER POINT VALUES FOR\n" "WHAT LEVEL THE OBJECT IS ON\n" }, {"FROSTB", "FROSTBITE (C)1982 ACTIVISION\n" " \n" "FROSTBITE BAILY BUILDS IGLOO\n" "GAME 1: REGULAR GAME (LV 1)\n" "GAME 3: ADVANCED GAME (LV 5)\n" "LEVEL PTS/BLOCK PTS/IGLOO\n" "LV1 10 PTS 160 PTS\n" "LV2 20 PTS 320 PTS\n" "LV3 30 PTS 480 PTS\n" "LV4 40 PTS 640 PTS\n" "LV5 50 PTS 800 PTS\n" "LV6 60 PTS 960 PTS\n" "LV7 70 PTS 1120 PTS\n" "LV8 80 PTS 1280 PTS\n" "LV9 90 PTS 1440 PTS\n" "FISH ARE WORTH 200 POINTS\n" "IGLOO BONUS: 10*DEGREES*LEVEL\n" "EXTRA LIFE EVERY 5000 POINTS\n" }, {"SOLSTM", "SOLAR STORM (C)1983 IMAGIC\n" " \n" "HIT SOLAR DEBRIS TO AVOID\n" "PLANETARY OVERHEATING.\n" "WAVE ENDS WHEN YOU SHOOT ALL\n" "OBJECTS OR THEY REACH PLANET.\n" " \n" "SCORING:\n" "SUN SPOT 5 PTS\n" "DELTOID/BLASTER/LANDER 10 PTS\n" "SOLAR FLARE 20 PTS\n" "SIZZLOID HIT 50 PTS\n" "FLEET SHIP 10 PTS\n" "AT END OF A WAVE WHEN SCORE IS\n" "500, 1000, 1500, ETC, ORBITAL\n" "PLATFORM APPEARS WHERE YOU CAN\n" "EARN BONUS POINTS + EXTRA LIFE\n" }, {"SPACX7", "SPACEMASTER X7 (C)1983 20TH CF\n" " \n" "DESTROY HYPERION MILITARY BASE\n" " \n" "SCORING:\n" "FIREBALL 25 PTS\n" "HEAT SEEKER 100 PTS\n" "BOUNCER 50 PTS\n" "WANDERER 200 PTS\n" "HOMER 400 PTS\n" "BASE PER HIT 25 PTS\n" "BASE DESTROYED IS 1000 PTS\n" "FOR FIRST FOUR BASES, THEN\n" "2000 PTS FOR NEXT FOUR, ETC\n" " \n" "EXTRA LIFE EVERY 10,000 PTS\n" }, {"STARMA", "STARMASTER (C)1982 ACTIVISION\n" "E: ENSIGN 9 ENEMIES NORMAL\n" "L: LEADER 17 ENEMIES FAST\n" "W: WING CDR 23 ENEMIES FASTER\n" "S: STARMASTR 31 ENEMIES FASTEST\n" " \n" "W: ENERGY NEEDED TO WARP.\n" "S: STARDATE (ELAPSED TIME).\n" "E: ENERGY REMAINING.\n" "D: DAMAGE CONTROL STATUS:\n" " L=LASR,S=SHD,W=WARP,R=RADAR\n" "GREEN: EMPTY SECTOR.\n" "RED: ENEMY SECTOR.\n" "BLUE: STARBASE SECTOR\n" "SCORE BASE(3100,4300,5700,6900)\n" "SCORE 100 PTS FOR EACH ENEMY\n" "MINUS 500 PTS STARBASE DESTROY\n" "MINUS 100 PTS DOCK / REPAIR\n" "MINUS 1 PTS PER STARDATE\n" }, {"STELTR", "STELLAR TRACK (c)1980 SEARS\n" " \n" "DESTROY ALL ALIENS IN GALAXY\n" "WITH PHASERS AND PHOTONS.\n" " \n" "GAME SELECT: RANDOM MISSION\n" "L-DIFF: A=PHASERS HALF STR\n" "R-DIFF: A=SHIELDS HALF STR\n" "GALAXY MAP SHOWS NUMBER OF \n" "ALIENS AND STARBASES as XY\n" " \n" "PHOTON / WARP DIRECTIONS:\n" " \n" " 1 \n" " 8 : 2 \n" " 7 -o- 3 \n" " 6 : 4 \n" " 5 \n" }, {"WORMW1", "WORM WAR I (C)1982 FOX\n" " \n" "BLAST WORMS AND BLOCKS\n" "AND KEEP AN EYE ON FUEL.\n" " \n" "OPT 1: OBSTACLE COURSE\n" "OPT 2: STRAIGHTAWAY COURSE\n" "OPT 3: INVISIBLE WORMS\n" "L-DIFF: A=RANDOM WORM MOVE\n" "R-DIFF: A=SLOWER BRAKES\n" " \n" "WORMS ATTACK IN GROUPS AND\n" "BLOCKS ARE WORTH 5 PTS\n" }, {"SOLARF", "SOLAR FOX (C)1982 CBS\n" " \n" "L-DIFF: A=FAST CRUISE\n" " \n" "EVERY 5 RACKS YOU GET\n" "A CHALLENGE RACK.\n" " \n" "SCORING\n" "RACKS 1 TO 5 100 PTS\n" "RACKS 6 TO 10 200 PTS\n" "RACKS 11 TO 15 300 PTS\n" "RACKS 16 TO 20 400 PTS\n" " \n" "CHALLENGE RACK: NUMBER OF CELLS\n" " IN RACK * CELL POINT VALUE.\n" }, {"SKIING", "SKIING (C)1982 ACTIVISION\n" " \n" "SLALOM RUNS\n" "GM1: 20 GATES, NOVICE RUN\n" "GM2: 40 GATES, INTERMEDIATE\n" "GM3: 30 GATES, EXPERT RUN\n" "GM4: 50 GATES, OLYMPIC RUN\n" "GM5: 30 GATES, RANDOM COURSE\n" " \n" "DOWNHILL RUNS\n" "GM6: 200 METERS, NOVICE HILL\n" "GM7: 300 METERS, INTERMEDIATE\n" "GM8: 500 METERS, EXPERT HILL\n" "GM9: 900 METERS, OLYMPIC HILL\n" "GM10: 900 METERS, RANDOM COURSE\n" " \n" }, {"ROTANK", "ROBOT TANK (C)1982 ACTIVISION\n" " \n" "DESTROY ENEMY TANKS AND AVOID\n" "THEIR FIRE.\n" " \n" "A SMALL TANK APPEARS AT THE TOP\n" "OF YOUR SCREEN FOR EACH ENEMY\n" "ROBOT TANK YOU DESTROY. A SQUARE\n" "WITH THE NUMBER 12 APPEARS AT\n" "THE TOP OF YOUR SCREEN EACH TIME\n" "A SQUADRON OF TWELVE ARE KILLED.\n" " \n" "R = RADAR DAMAGE\n" "T = TRED DAMAGE\n" "V = VIDEO DAMAGE\n" "C = CANNONS DAMAGE\n" }, {"PLAPAT", "PLANET PATROL (C)1982 SPECTRAV\n" " \n" "PATROL PLANET DAY AND NIGHT.\n" "REFUEL AS NEEDED TO SURVIVE.\n" " \n" "DESTROY 3 DEPOTS TO ADVANCE\n" "TO DODGE AND AVOID ENEMIES.\n" " \n" "GAME 1: SLOW GAME\n" "GAME 3: FAST GAME\n" }, {"UCHAOS", "UNIVERSAL CHAOS (C)1989 TELEGMS\n" " \n" "PILOT YOUR BATTLE COUP THROUGH\n" "THE STREETS OF PHENIX. USE THE\n" "JOYSTICK TO CONTROL SPEED AND\n" "THE FIRE BUTTON TO ELIMINATE\n" "INVADING MORTII SPACECRAFT.\n" " \n" "BONUS AFTER EVERY CLEARED WAVE.\n" }, {"MI3000", "MISSION 3000AD (C)1983 BIT-CORP\n" " \n" "COLOR SHOWER:\n" "GREEN: NORMAL\n" "BLUE: FAST\n" "RED: FASTEST\n" " \n" "STARBASE COLORS:\n" "GREY: 1+4 ARRANGEMENT\n" "YELLOW: 2+5 ARRANGEMENT\n" "ORANGE: 3+6 ARRANGEMENT\n" " \n" "DEFEAT STARFIGHTER: 100PTS\n" "DESTROY STARBASE: 500PTS\n" " \n" "EXTRA LIFE AFTER 6 STARBASES\n" }, {"OINK!!", "OINK! (C)1982 ACTIVISION\n" " \n" "HELP PIGS PATCH THEIR HOUSE.\n" "L-DIFF: A=PIG DROPS AT WALL\n" " \n" "SCORE 4 POINTS FOR DROPPING\n" "BRICK INTO FIRST WALL, 8 PTS\n" "FOR DROPPING INTO SECOND WALL,\n" "ETC. EACH ROW IS WORTH MORE.\n" }, {"FROSTY", "STAY FROSTY (C)2008 SPICEWARE\n" " \n" "PUT OUT ALL THE FIRES ON EACH\n" "LEVEL AND TAKE CARE THAT YOU\n" "DONT MELT DUE TO FIRE OR SUN!\n" "STAY FROSTY...!\n" " \n" "SCORING:\n" "SHRINK FIRE: 50 PTS\n" "EXTINGUISH FIRE: 100 PTS\n" "ICE: 4-10 PTS DEPEND ON SIZE\n" "LEVEL BONUS 1000 FOR SOLID\n" "SNOWMAN, 500-100 FOR VARIOUS\n" "MELTED STAGES.\n" }, {"M.A.D.", "M.A.D. (c)1982 US GAMES\n" " \n" "Photon Cannon has 7 shot angles\n" " \n" "Computer will lock onto missile.\n" "It turns white before falling.\n" " \n" "Scoring:\n" "Each missile shot down by your\n" "Cannon in waves 1-6 = 100 PTS\n" " After wave 6 = 200 PTS\n" }, {"LOCKNC", "LOCK N CHASE (c)1982 M-NETWORK\n" " \n" "You have five thieves who enter\n" "vault one at a time to loot!\n" " \n" "Press button to slam doors.\n" " \n" "L-DIFF: A = FAST GAME\n" " \n" "SCORING:\n" "Gold Bars 20 PTS\n" "Upper Trs 500,1000,2000,4000\n" "Lower Trs 250,500,1000, etc\n" "Trap a Cop 2000 points each\n" }, {"CNEXAR", "CHALLENGE OF NEXAR 1982 SPECVSN\n" " \n" "AT each of 99 levels, DESTROY\n" "3 BEACONS and avoid collisions.\n" " \n" "L-DIFF: B=5, A=3 SHIELDS\n" "R-DIFF: A=LOSE SHIELD ON TIME\n" "GAME 1: PRACTICE\n" "GAME 2: ADVANCE PRACTICE\n" "GAME 3: THE CHALLENGE OF NEXAR\n" "SPD: 1 2 3 4 5 6 7 \n" "PTS: 25 50 100 200 400 800 1200\n" "BONUS SHIELD EVERY 10K PTS\n" "RATING:\n" " 0K - 30K CADET\n" " 30K - 100K ADVANCED CADET\n" "100K - 300K STAR WARRIOR\n" "300K - 700K SPECTRA WARRIOR\n" "700K - 999K LEGION OF CHOSEN\n" }, {"DOKONG", "<NAME> 1982 NINTENDO\n" " \n" "ONLY 2 STAGES - SAVE PRINCESS\n" "AND REMOVE ALL RIVETS.\n" " \n" "Each screen has a score/bonus\n" "counter at the top when you\n" "clear a level.\n" " \n" "SCORING:\n" "Jumping a barrel 100 PTS\n" "Removing a rivet 100 PTS\n" "Smashing barrel 800 PTS\n" }, {"STRAID", "STAR RAIDERS (c)1981 ATARI\n" " \n" "Destroy all Krylon Warships\n" "and save the starbase.\n" "Use the Keypad Overlay for\n" "this game.\n" " \n" "DIFF A/A will allow control of\n" "Comp and Shields via Keypad.\n" " \n" "P=PHOTONS, E=ENGINES, S=SHIELDS\n" "C=COMP. YLW=DAMAGED, RED=DEST\n" "T10 = 10 Targets, T20,T30,T40\n" " \n" "Control Panel Color:\n" "RED Enemy is right behind you\n" "GREEN In front and out of range\n" "BLUE Visible and within range\n" }, {"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", (char*)0}, }; char inst_text[1024]; void dsShowScreenInstructions(void) { short int idx=0; char bFound=0; decompress(bgInstructionsTiles, bgGetGfxPtr(bg0b), LZ77Vram); decompress(bgInstructionsMap, (void*) bgGetMapPtr(bg0b), LZ77Vram); dmaCopy((void *) bgInstructionsPal,(u16*) BG_PALETTE_SUB,256*2); unsigned short dmaVal = *(bgGetMapPtr(bg1b) +31*32); dmaFillWords(dmaVal | (dmaVal<<16),(void*) bgGetMapPtr(bg1b),32*24*2); swiWaitForVBlank(); while (instructions[idx].text != (char*)0) { if (instructions[idx].gameID == myCartInfo.gameID) { bFound = 1; strcpy(inst_text, instructions[idx].text); break; } idx++; } if (bFound) { short line=3; char *token = NULL; token = strtok(inst_text, "\n"); while( token != NULL ) { dsPrintValue(1,line++,0, token); token = strtok(NULL, "\n"); } } else { dsPrintValue(1,4,0, (char *)"Game Manual Not Found"); dsPrintValue(1,5,0, (char *)"Many more comming soon!"); } }
huidong-chen/directx-sdk-samples
InstallHelpers/GameuxInstallHelper/GameuxInstallHelper.cpp
//-------------------------------------------------------------------------------------- // File: GameuxInstallHelper.cpp // // Copyright (c) Microsoft Corporation. // Licensed under the MIT License (MIT). //-------------------------------------------------------------------------------------- #define _WIN32_DCOM #ifndef SAFE_DELETE_ARRAY #define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } #endif #ifndef SAFE_RELEASE #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } #endif #include <windows.h> #include <shlobj.h> #include <rpcsal.h> #include <gameux.h> #include <crtdbg.h> // The Microsoft Platform SDK or Microsoft Windows SDK is required to compile this sample #include <msi.h> #include <msiquery.h> #include <stdio.h> #include <assert.h> #include <wbemidl.h> #include <objbase.h> #include <shellapi.h> #include <WtsApi32.h> #define NO_SHLWAPI_STRFCNS #include <shlwapi.h> #include "GameuxInstallHelper.h" #include "GDFParse.h" // Uncomment to get a debug messagebox // #define SHOW_S1_DEBUG_MSGBOXES // #define SHOW_S2_DEBUG_MSGBOXES // more detail //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- LPWSTR GetPropertyFromMSI(MSIHANDLE hMSI, LPCWSTR szPropName); HRESULT GenerateGUID(GUID* pInstanceGUID); HRESULT ConvertStringToGUID(const WCHAR* strSrc, GUID* pGuidDest); HRESULT ConvertGUIDToStringCch(const GUID* pGuidSrc, WCHAR* strDest, int cchDestChar); HRESULT CreateShortcut(WCHAR* strLaunchPath, WCHAR* strCommandLineArgs, WCHAR* strShortcutFilePath); HRESULT GetAccountName(WCHAR* strUser, DWORD cchUser, WCHAR* strDomain, DWORD cchDomain); HRESULT RetrieveGUIDForApplication(WCHAR* szPathToGDFdll, GUID* pGUID); HRESULT GameExplorerInstallToRegistry(WCHAR* strGDFBinPath, WCHAR* strGameInstallPath, GAME_INSTALL_SCOPE InstallScope); HRESULT GameExplorerUninstallFromRegistry(WCHAR* strGDFBinPath); HRESULT RemoveTasks(WCHAR* strGDFBinPath); HRESULT CreateTasks(WCHAR* strGDFBinPath, WCHAR* strGameInstallPath, GAME_INSTALL_SCOPE InstallScope); HRESULT IsV2GDF ( __in WCHAR* strGDFBinPath, __out BOOL* pfV2GDF ); HRESULT GameExplorerInstallUsingIGameExplorer(IGameExplorer* pFwGameExplorer, WCHAR* strGDFBinPath, WCHAR* strGameInstallPath, GAME_INSTALL_SCOPE InstallScope); HRESULT GameExplorerUninstallUsingIGameExplorer(IGameExplorer* pFwGameExplorer, WCHAR* strGDFBinPath); HRESULT GameExplorerInstallUsingIGameExplorer2(IGameExplorer2* pFwGameExplorer2, WCHAR* strGDFBinPath, WCHAR* strGameInstallPath, GAME_INSTALL_SCOPE InstallScope); HRESULT GameExplorerUninstallUsingIGameExplorer2(IGameExplorer2* pFwGameExplorer2, WCHAR* strGDFBinPath); STDAPI GameExplorerUninstallW(WCHAR* strGDFBinPath); STDAPI GameExplorerInstallW(WCHAR* strGDFBinPath, WCHAR* strGameInstallPath, GAME_INSTALL_SCOPE InstallScope); HRESULT GameExplorerUpdateUsingIGameExplorer(IGameExplorer* pFwGameExplorer, WCHAR* strGDFBinPath); STDAPI GameExplorerUpdateW( WCHAR* strGDFBinPath ); STDAPI GameExplorerUpdateA( CHAR* strGDFBinPath ); //-------------------------------------------------------------------------------------- // This stores the install location // sets up the CustomActionData properties for the deferred custom actions //-------------------------------------------------------------------------------------- UINT __stdcall GameExplorerSetMSIProperties(MSIHANDLE hModule) { WCHAR* szInstallDir = NULL; WCHAR* szProductCode = GetPropertyFromMSI(hModule, L"ProductCode"); if (szProductCode != NULL) { DWORD dwBufferSize = 1024; szInstallDir = new WCHAR[dwBufferSize]; if (szInstallDir != NULL) { if (ERROR_SUCCESS != MsiGetProductInfo(szProductCode, INSTALLPROPERTY_INSTALLLOCATION, szInstallDir, &dwBufferSize)) { SAFE_DELETE_ARRAY(szInstallDir); szInstallDir = GetPropertyFromMSI(hModule, L"TARGETDIR"); } } SAFE_DELETE_ARRAY(szProductCode); } else { szInstallDir = GetPropertyFromMSI(hModule, L"TARGETDIR"); } // See if the install location property is set. If it is, use that. // Otherwise, get the property from TARGETDIR if (szInstallDir != NULL) { // Set the ARPINSTALLLOCATION property to the install dir so that // the uninstall custom action can have it when getting the INSTALLPROPERTY_INSTALLLOCATION MsiSetPropertyW(hModule, L"ARPINSTALLLOCATION", szInstallDir); WCHAR szCustomActionData[1024] = {0}; WCHAR* szRelativePathToGDF = GetPropertyFromMSI(hModule, L"RelativePathToGDF"); if (szRelativePathToGDF != NULL ) { wcscpy_s(szCustomActionData, 1024, szInstallDir); wcscat_s(szCustomActionData, 1024, szRelativePathToGDF); wcscat_s(szCustomActionData, 1024, L"|"); wcscat_s(szCustomActionData, 1024, szInstallDir); wcscat_s(szCustomActionData, 1024, L"|"); WCHAR* szALLUSERS = GetPropertyFromMSI(hModule, L"ALLUSERS"); if (szALLUSERS && (szALLUSERS[0] == '1' || szALLUSERS[0] == '2')) { wcscat_s(szCustomActionData, 1024, L"3"); } else { wcscat_s(szCustomActionData, 1024, L"2"); } // Set the CustomActionData property for the deferred custom actions MsiSetProperty(hModule, L"GameUXAddAsAdmin", szCustomActionData); MsiSetProperty(hModule, L"GameUXAddAsCurUser", szCustomActionData); MsiSetProperty(hModule, L"GameUXRollBackRemoveAsAdmin", szCustomActionData); MsiSetProperty(hModule, L"GameUXRollBackRemoveAsCurUser", szCustomActionData); WCHAR szFullPathToGDF[MAX_PATH] = {0}; wcscpy_s(szFullPathToGDF, MAX_PATH, szInstallDir); wcscat_s(szFullPathToGDF, MAX_PATH, szRelativePathToGDF); // Set the CustomActionData property for the deferred custom actions MsiSetProperty(hModule, L"GameUXRemoveAsAdmin", szFullPathToGDF); MsiSetProperty(hModule, L"GameUXRemoveAsCurUser", szFullPathToGDF); MsiSetProperty(hModule, L"GameUXRollBackAddAsAdmin", szFullPathToGDF); MsiSetProperty(hModule, L"GameUXRollBackAddAsCurUser", szFullPathToGDF); if (szALLUSERS != NULL) { SAFE_DELETE_ARRAY(szALLUSERS); } SAFE_DELETE_ARRAY(szRelativePathToGDF); } SAFE_DELETE_ARRAY(szInstallDir); } return ERROR_SUCCESS; } //-------------------------------------------------------------------------------------- // The CustomActionData property must be formated like so: // "<path to GDF binary>|<game install path>|<install scope>" // for example: // "C:\MyGame\GameGDF.dll|C:\MyGame|2|" //-------------------------------------------------------------------------------------- UINT __stdcall GameExplorerInstallUsingMSI(MSIHANDLE hModule) { WCHAR* szCustomActionData = GetPropertyFromMSI(hModule, L"CustomActionData"); if (szCustomActionData != NULL) { WCHAR szGDFBinPath[MAX_PATH] = {0}; WCHAR szGameInstallPath[MAX_PATH] = {0}; GAME_INSTALL_SCOPE InstallScope = GIS_ALL_USERS; WCHAR* pFirstDelim = wcschr(szCustomActionData, '|'); if (pFirstDelim) { *pFirstDelim = 0; WCHAR* pSecondDelim = wcschr(pFirstDelim + 1, '|'); if (pSecondDelim) { *pSecondDelim = 0; InstallScope = (GAME_INSTALL_SCOPE)_wtoi(pSecondDelim + 1); } wcscpy_s(szGameInstallPath, MAX_PATH, pFirstDelim + 1); } wcscpy_s(szGDFBinPath, MAX_PATH, szCustomActionData); #ifdef SHOW_S1_DEBUG_MSGBOXES HRESULT hr = GameExplorerInstallW(szGDFBinPath, szGameInstallPath, InstallScope); WCHAR sz[1024]; WCHAR szGUID[64] = {0}; swprintf_s(sz, 1024, L"szGDFBinPath='%s'\nszGameInstallPath='%s'\nInstallScope='%s'\nszGUID='%s'\nhr=0x%0.8x\n", szGDFBinPath, szGameInstallPath, (InstallScope == GIS_ALL_USERS) ? L"GIS_ALL_USERS" : L"GIS_CURRENT_USER", szGUID, hr); MessageBox(NULL, sz, L"GameExplorerInstallUsingMSI", MB_OK); #else GameExplorerInstallW(szGDFBinPath, szGameInstallPath, InstallScope); #endif SAFE_DELETE_ARRAY(szCustomActionData); } else { #ifdef SHOW_S1_DEBUG_MSGBOXES WCHAR sz[1024]; swprintf_s(sz, 1024, L"CustomActionData property not found\n"); MessageBox(NULL, sz, L"GameExplorerInstallUsingMSI", MB_OK); #endif } // Ignore success/failure and continue on with install return ERROR_SUCCESS; } //-------------------------------------------------------------------------------------- // The CustomActionData property must be formated like so: // "<path to GDF binary>" // for example: // "C:\MyGame\GameGDF.dll" //-------------------------------------------------------------------------------------- UINT __stdcall GameExplorerUninstallUsingMSI(MSIHANDLE hModule) { WCHAR* szCustomActionData = GetPropertyFromMSI(hModule, L"CustomActionData"); if (szCustomActionData) { WCHAR szGDFBinPath[MAX_PATH] = {0}; wcscpy_s(szGDFBinPath, MAX_PATH, szCustomActionData); SAFE_DELETE_ARRAY(szCustomActionData); #ifdef SHOW_S2_DEBUG_MSGBOXES HRESULT hr = GameExplorerUninstallW(szGDFBinPath); WCHAR sz[1024]; swprintf_s(sz, 1024, L"szGDFBinPath='%s'\nhr=0x%0.8x", szGDFBinPath, hr); MessageBox(NULL, sz, L"GameExplorerUninstallUsingMSI", MB_OK); #else GameExplorerUninstallW(szGDFBinPath); #endif } // Ignore success/failure and continue on with uninstall return ERROR_SUCCESS; } //-------------------------------------------------------------------------------------- // Install a game to the Game Explorer (UNICODE) //-------------------------------------------------------------------------------------- STDAPI GameExplorerInstallW(WCHAR* strGDFBinPath, WCHAR* strGameInstallPath, GAME_INSTALL_SCOPE InstallScope) { assert(strGDFBinPath); assert(strGameInstallPath); if (strGDFBinPath == NULL || strGameInstallPath == NULL) { return E_INVALIDARG; } HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (SUCCEEDED(hr)) { BOOL fIsV2GDF = FALSE; hr = IsV2GDF(strGDFBinPath, &fIsV2GDF); if (SUCCEEDED(hr)) { if (fIsV2GDF) { IGameExplorer2* pFwGameExplorer2 = NULL; // Create an instance of the IGameExplorer2 Interface hr = CoCreateInstance(__uuidof(GameExplorer), NULL, CLSCTX_INPROC_SERVER, __uuidof(IGameExplorer2), (void**)&pFwGameExplorer2); if (SUCCEEDED(hr) && (pFwGameExplorer2 != NULL)) { // Windows 7 hr = GameExplorerInstallUsingIGameExplorer2(pFwGameExplorer2, strGDFBinPath, strGameInstallPath, InstallScope); pFwGameExplorer2->Release(); } else { IGameExplorer* pFwGameExplorer = NULL; // Create an instance of the IGameExplorer Interface hr = CoCreateInstance(__uuidof(GameExplorer), NULL, CLSCTX_INPROC_SERVER, __uuidof(IGameExplorer), (void**)&pFwGameExplorer); if (SUCCEEDED(hr) && (pFwGameExplorer != NULL)) { // Windows Vista hr = GameExplorerInstallUsingIGameExplorer(pFwGameExplorer, strGDFBinPath, strGameInstallPath, InstallScope); pFwGameExplorer->Release(); } else { // Windows XP hr = GameExplorerInstallToRegistry(strGDFBinPath, strGameInstallPath, InstallScope); } } } else { IGameExplorer* pFwGameExplorer = NULL; // Create an instance of the IGameExplorer Interface hr = CoCreateInstance(__uuidof(GameExplorer), NULL, CLSCTX_INPROC_SERVER, __uuidof(IGameExplorer), (void**)&pFwGameExplorer); if (SUCCEEDED(hr) && (pFwGameExplorer != NULL)) { // Windows Vista or Windows 7 hr = GameExplorerInstallUsingIGameExplorer(pFwGameExplorer, strGDFBinPath, strGameInstallPath, InstallScope); pFwGameExplorer->Release(); } else { // Windows XP hr = GameExplorerInstallToRegistry(strGDFBinPath, strGameInstallPath, InstallScope); } } } CoUninitialize(); } return hr; } //-------------------------------------------------------------------------------------- // Install game to the Game Explorer (ASCII) //-------------------------------------------------------------------------------------- STDAPI GameExplorerInstallA(CHAR* strGDFBinPath, CHAR* strGameInstallPath, GAME_INSTALL_SCOPE InstallScope) { assert(strGDFBinPath); assert(strGameInstallPath); if (strGDFBinPath == NULL || strGameInstallPath == NULL) { return E_INVALIDARG; } WCHAR wstrBinPath[MAX_PATH] = {0}; WCHAR wstrInstallPath[MAX_PATH] = {0}; MultiByteToWideChar(CP_ACP, 0, strGDFBinPath, MAX_PATH, wstrBinPath, MAX_PATH); MultiByteToWideChar(CP_ACP, 0, strGameInstallPath, MAX_PATH, wstrInstallPath, MAX_PATH); return GameExplorerInstallW(wstrBinPath, wstrInstallPath, InstallScope); } //-------------------------------------------------------------------------------------- // Uninstall a game to the Game Explorer (UNICODE) //-------------------------------------------------------------------------------------- STDAPI GameExplorerUninstallW(WCHAR* strGDFBinPath) { assert(strGDFBinPath); if (strGDFBinPath == NULL) { return E_INVALIDARG; } HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (SUCCEEDED(hr)) { BOOL fIsV2GDF = FALSE; hr = IsV2GDF(strGDFBinPath, &fIsV2GDF); if (SUCCEEDED(hr)) { if (fIsV2GDF) { IGameExplorer2* pFwGameExplorer2 = NULL; // Create an instance of the IGameExplorer2 Interface hr = CoCreateInstance(__uuidof(GameExplorer), NULL, CLSCTX_INPROC_SERVER, __uuidof(IGameExplorer2), (void**)&pFwGameExplorer2); if (SUCCEEDED(hr) && (pFwGameExplorer2 != NULL)) { // Windows 7 hr = GameExplorerUninstallUsingIGameExplorer2(pFwGameExplorer2, strGDFBinPath); pFwGameExplorer2->Release(); } else { IGameExplorer* pFwGameExplorer = NULL; // Create an instance of the IGameExplorer Interface hr = CoCreateInstance(__uuidof(GameExplorer), NULL, CLSCTX_INPROC_SERVER, __uuidof(IGameExplorer), (void**)&pFwGameExplorer); if (SUCCEEDED(hr) && (pFwGameExplorer != NULL)) { // Windows Vista hr = GameExplorerUninstallUsingIGameExplorer(pFwGameExplorer, strGDFBinPath); pFwGameExplorer->Release(); } else { // Windows XP hr = GameExplorerUninstallFromRegistry(strGDFBinPath); } } } else { IGameExplorer* pFwGameExplorer = NULL; // Create an instance of the IGameExplorer Interface hr = CoCreateInstance(__uuidof(GameExplorer), NULL, CLSCTX_INPROC_SERVER, __uuidof(IGameExplorer), (void**)&pFwGameExplorer); if (SUCCEEDED(hr) && (pFwGameExplorer != NULL)) { // Windows Vista hr = GameExplorerUninstallUsingIGameExplorer(pFwGameExplorer, strGDFBinPath); pFwGameExplorer->Release(); } else { // Windows XP hr = GameExplorerUninstallFromRegistry(strGDFBinPath); } } } CoUninitialize(); } return hr; } //-------------------------------------------------------------------------------------- // Uninstall a game to the Game Explorer (ASCII) //-------------------------------------------------------------------------------------- STDAPI GameExplorerUninstallA(CHAR* strGDFBinPath) { assert(strGDFBinPath); if (strGDFBinPath == NULL) { return E_INVALIDARG; } WCHAR wstrBinPath[MAX_PATH] = {0}; MultiByteToWideChar(CP_ACP, 0, strGDFBinPath, MAX_PATH, wstrBinPath, MAX_PATH); return GameExplorerUninstallW(wstrBinPath); } //-------------------------------------------------------------------------------------- // Update a game with the Game Explorer (UNICODE) //-------------------------------------------------------------------------------------- STDAPI GameExplorerUpdateW(WCHAR* strGDFBinPath) { assert(strGDFBinPath); if (strGDFBinPath == NULL) { return E_INVALIDARG; } HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (SUCCEEDED(hr)) { IGameExplorer* pFwGameExplorer = NULL; // Create an instance of the IGameExplorer Interface hr = CoCreateInstance(__uuidof(GameExplorer), NULL, CLSCTX_INPROC_SERVER, __uuidof(IGameExplorer), (void**)&pFwGameExplorer); if (SUCCEEDED(hr) && (pFwGameExplorer != NULL)) { hr = GameExplorerUpdateUsingIGameExplorer(pFwGameExplorer, strGDFBinPath); pFwGameExplorer->Release(); } CoUninitialize(); } return hr; } //-------------------------------------------------------------------------------------- // Update a game with the Game Explorer (ASCII) //-------------------------------------------------------------------------------------- STDAPI GameExplorerUpdateA(CHAR* strGDFBinPath) { assert(strGDFBinPath); if (strGDFBinPath == NULL) { return E_INVALIDARG; } WCHAR wstrBinPath[MAX_PATH] = {0}; MultiByteToWideChar(CP_ACP, 0, strGDFBinPath, MAX_PATH, wstrBinPath, MAX_PATH); return GameExplorerUpdateW(wstrBinPath); } //-------------------------------------------------------------------------------------- // Adds a game to the Game Explorer for XP //-------------------------------------------------------------------------------------- HRESULT GameExplorerInstallToRegistry(WCHAR* strGDFBinPath, WCHAR* strGameInstallPath, GAME_INSTALL_SCOPE InstallScope) { assert(strGDFBinPath); assert(strGameInstallPath); if (strGDFBinPath == NULL || strGameInstallPath == NULL) { return E_INVALIDARG; } HRESULT hr = E_FAIL; BSTR bstrGDFBinPath = NULL; BSTR bstrGameInstallPath = NULL; bstrGDFBinPath = SysAllocString(strGDFBinPath); bstrGameInstallPath = SysAllocString(strGameInstallPath); if (bstrGDFBinPath != NULL && bstrGameInstallPath != NULL) { // On Windows XP or eariler, write registry keys to known location // so that if the machine is upgraded to Windows Vista or later, these games will // be automatically found. // // Depending on GAME_INSTALL_SCOPE, write to: // HKLM\Software\Microsoft\Windows\CurrentVersion\GameUX\GamesToFindOnWindowsUpgrade\{GUID}\ // or // HKCU\Software\Classes\Software\Microsoft\Windows\CurrentVersion\GameUX\GamesToFindOnWindowsUpgrade\{GUID}\ // and write there these 2 string values: GDFBinaryPath and GameInstallPath // HKEY hKeyGamesToFind = NULL, hKeyGame = NULL; LONG lResult; DWORD dwDisposition; if (InstallScope == GIS_CURRENT_USER) { lResult = RegCreateKeyEx(HKEY_CURRENT_USER, L"Software\\Classes\\Software\\Microsoft\\Windows\\CurrentVersion\\GameUX\\GamesToFindOnWindowsUpgrade", 0, NULL, 0, KEY_WRITE, NULL, &hKeyGamesToFind, &dwDisposition); } else { lResult = RegCreateKeyEx(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\GameUX\\GamesToFindOnWindowsUpgrade", 0, NULL, 0, KEY_WRITE, NULL, &hKeyGamesToFind, &dwDisposition); } #ifdef SHOW_S1_DEBUG_MSGBOXES WCHAR sz[1024]; swprintf_s(sz, 1024, L"RegCreateKeyEx lResult=%d", lResult); MessageBox(NULL, sz, L"GameExplorerInstallForXP", MB_OK); #endif hr = HRESULT_FROM_WIN32(lResult); if (SUCCEEDED(hr)) { GUID InstanceGUID = GUID_NULL; RetrieveGUIDForApplication(strGDFBinPath, &InstanceGUID); if (InstanceGUID == GUID_NULL) { GenerateGUID(&InstanceGUID); } WCHAR strGameInstanceGUID[128] = {0}; if (StringFromGUID2(InstanceGUID, strGameInstanceGUID, ARRAYSIZE(strGameInstanceGUID)) != 0) { lResult = RegCreateKeyEx(hKeyGamesToFind, strGameInstanceGUID, 0, NULL, 0, KEY_WRITE, NULL, &hKeyGame, &dwDisposition); hr = HRESULT_FROM_WIN32(lResult); if (SUCCEEDED(hr)) { size_t nGDFBinPath = 0, nGameInstallPath = 0; nGDFBinPath = wcsnlen(strGDFBinPath, MAX_PATH); nGameInstallPath = wcsnlen(strGameInstallPath, MAX_PATH); RegSetValueEx(hKeyGame, L"GDFBinaryPath", 0, REG_SZ, (BYTE*)strGDFBinPath, (DWORD) ((nGDFBinPath + 1) * sizeof(WCHAR))); RegSetValueEx(hKeyGame, L"GameInstallPath", 0, REG_SZ, (BYTE*)strGameInstallPath, (DWORD) ((nGameInstallPath + 1) * sizeof(WCHAR))); RegCloseKey(hKeyGame); } } RegCloseKey(hKeyGamesToFind); } SysFreeString(bstrGDFBinPath); SysFreeString(bstrGameInstallPath); } // create short cut, play tasks, and support tasks if (SUCCEEDED(hr)) { hr = CreateTasks(strGDFBinPath, strGameInstallPath, InstallScope); } return hr; } //-------------------------------------------------------------------------------------- // Adds a game to the Game Explorer for Windows Vista //-------------------------------------------------------------------------------------- HRESULT GameExplorerInstallUsingIGameExplorer(IGameExplorer* pFwGameExplorer, WCHAR* strGDFBinPath, WCHAR* strGameInstallPath, GAME_INSTALL_SCOPE InstallScope) { assert(strGDFBinPath); assert(strGameInstallPath); assert(pFwGameExplorer); if (strGDFBinPath == NULL || strGameInstallPath == NULL || pFwGameExplorer == NULL) { return E_INVALIDARG; } HRESULT hr = E_FAIL; BSTR bstrGDFBinPath = NULL; BSTR bstrGameInstallPath = NULL; bstrGDFBinPath = SysAllocString(strGDFBinPath); bstrGameInstallPath = SysAllocString(strGameInstallPath); if ((bstrGDFBinPath != NULL) && (bstrGameInstallPath != NULL)) { GUID InstanceGUID = GUID_NULL; BOOL bHasAccess = FALSE; hr = pFwGameExplorer->VerifyAccess(bstrGDFBinPath, &bHasAccess); if (SUCCEEDED(hr) && bHasAccess) { hr = pFwGameExplorer->AddGame(bstrGDFBinPath, bstrGameInstallPath, InstallScope, &InstanceGUID); } #ifdef SHOW_S1_DEBUG_MSGBOXES WCHAR strUser[256] = {0}; WCHAR strDomain[256] = {0}; GetAccountName(strUser, 256, strDomain, 256); BOOL bAdmin = IsUserAnAdmin(); WCHAR sz[1024] = {0}; WCHAR strGameInstanceGUID[128] = {0}; StringFromGUID2(InstanceGUID, strGameInstanceGUID, ARRAYSIZE(strGameInstanceGUID)); swprintf_s(sz, 1024, L"szGDFBinPath='%s'\nszGameInstallPath='%s'\nInstallScope='%s'\nszGUID='%s'\nAccount=%s\\%s\nAdmin=%d\nhr=0x%0.8x", bstrGDFBinPath, bstrGameInstallPath, (InstallScope == GIS_ALL_USERS) ? L"GIS_ALL_USERS" : L"GIS_CURRENT_USER", strGameInstanceGUID, strDomain, strUser, bAdmin, hr); MessageBox(NULL, sz, L"GameExplorerInstallUsingIGameExplorer", MB_OK); #endif SysFreeString(bstrGDFBinPath); SysFreeString(bstrGameInstallPath); } // create short cut, play tasks, and support tasks if (SUCCEEDED(hr)) { hr = CreateTasks(strGDFBinPath, strGameInstallPath, InstallScope); } return hr; } //-------------------------------------------------------------------------------------- // Adds a game to the Game Explorer //-------------------------------------------------------------------------------------- HRESULT GameExplorerInstallUsingIGameExplorer2(IGameExplorer2* pFwGameExplorer2, WCHAR* strGDFBinPath, WCHAR* strGameInstallPath, GAME_INSTALL_SCOPE InstallScope) { assert(strGDFBinPath); assert(strGameInstallPath); assert(pFwGameExplorer2); if (strGDFBinPath == NULL || strGameInstallPath == NULL || pFwGameExplorer2 == NULL) { return E_INVALIDARG; } HRESULT hr = E_FAIL; BSTR bstrGDFBinPath = NULL; BSTR bstrGameInstallPath = NULL; bstrGDFBinPath = SysAllocString(strGDFBinPath); bstrGameInstallPath = SysAllocString(strGameInstallPath); if (bstrGDFBinPath != NULL && bstrGameInstallPath != NULL) { hr = pFwGameExplorer2->InstallGame(bstrGDFBinPath, bstrGameInstallPath, InstallScope); #ifdef SHOW_S1_DEBUG_MSGBOXES WCHAR strUser[256] = {0}; WCHAR strDomain[256] = {0}; GetAccountName(strUser, 256, strDomain, 256); BOOL bAdmin = IsUserAnAdmin(); WCHAR sz[1024] = {0}; WCHAR strGameInstanceGUID[128] = {0}; GUID InstanceGUID = GUID_NULL; RetrieveGUIDForApplication(strGDFBinPath, &InstanceGUID); StringFromGUID2(InstanceGUID, strGameInstanceGUID, ARRAYSIZE(strGameInstanceGUID)); swprintf_s(sz, 1024, L"szGDFBinPath='%s'\nszGameInstallPath='%s'\nInstallScope='%s'\nszGUID='%s'\nAccount=%s\\%s\nAdmin=%d\nhr=0x%0.8x", bstrGDFBinPath, bstrGameInstallPath, (InstallScope == GIS_ALL_USERS) ? L"GIS_ALL_USERS" : L"GIS_CURRENT_USER", strGameInstanceGUID, strDomain, strUser, bAdmin, hr); MessageBox(NULL, sz, L"GameExplorerInstallUsingIGameExplorer2", MB_OK); #endif SysFreeString(bstrGDFBinPath); SysFreeString(bstrGameInstallPath); } return hr; } //-------------------------------------------------------------------------------------- // Removes a game from the Game Explorer - On Windows XP remove reg keys //-------------------------------------------------------------------------------------- HRESULT GameExplorerUninstallFromRegistry(WCHAR* strGDFBinPath) { assert(strGDFBinPath); if (strGDFBinPath == NULL) { return E_INVALIDARG; } GUID InstanceGUID = GUID_NULL; HRESULT hr = RemoveTasks(strGDFBinPath); if (SUCCEEDED(hr)) { hr = RetrieveGUIDForApplication(strGDFBinPath, &InstanceGUID); if (SUCCEEDED(hr)) { WCHAR strGameInstanceGUID[128] = {0}; if (StringFromGUID2(InstanceGUID, strGameInstanceGUID, ARRAYSIZE(strGameInstanceGUID)) != 0) { WCHAR szKeyPath[1024]; if (SUCCEEDED(swprintf_s(szKeyPath, 1024, L"Software\\Classes\\Software\\Microsoft\\Windows\\CurrentVersion\\GameUX\\GamesToFindOnWindowsUpgrade\\%s", strGameInstanceGUID))) { SHDeleteKey(HKEY_CURRENT_USER, szKeyPath); } if (SUCCEEDED(swprintf_s(szKeyPath, 1024, L"Software\\Microsoft\\Windows\\CurrentVersion\\GameUX\\GamesToFindOnWindowsUpgrade\\%s", strGameInstanceGUID))) { SHDeleteKey(HKEY_LOCAL_MACHINE, szKeyPath); } } } } #ifdef SHOW_S1_DEBUG_MSGBOXES WCHAR sz[1024]; WCHAR strGameInstanceGUID[128] = {0}; StringFromGUID2(InstanceGUID, strGameInstanceGUID, ARRAYSIZE(strGameInstanceGUID)); swprintf_s(sz, 1024, L"bVistaPath=%d\npInstanceGUID='%s'\nhr=0x%0.8x", false, strGameInstanceGUID, hr); MessageBox(NULL, sz, L"GameExplorerUninstallForXP", MB_OK); #endif return hr; } //-------------------------------------------------------------------------------------- // Removes a game from the Game Explorer for Windows Vista //-------------------------------------------------------------------------------------- HRESULT GameExplorerUninstallUsingIGameExplorer(IGameExplorer* pFwGameExplorer, WCHAR* strGDFBinPath) { assert(pFwGameExplorer); assert(strGDFBinPath); if (strGDFBinPath == NULL || pFwGameExplorer == NULL) { return E_INVALIDARG; } GUID InstanceGUID = GUID_NULL; HRESULT hr = RemoveTasks(strGDFBinPath); if (SUCCEEDED(hr)) { hr = RetrieveGUIDForApplication(strGDFBinPath, &InstanceGUID); if (SUCCEEDED(hr)) { // Remove the game from the Game Explorer hr = pFwGameExplorer->RemoveGame(InstanceGUID); } } #ifdef SHOW_S1_DEBUG_MSGBOXES WCHAR sz[1024]; WCHAR strGameInstanceGUID[128] = {0}; StringFromGUID2(InstanceGUID, strGameInstanceGUID, ARRAYSIZE(strGameInstanceGUID)); swprintf_s(sz, 1024, L"\npInstanceGUID='%s'\nhr=0x%0.8x", strGameInstanceGUID, hr); MessageBox(NULL, sz, L"GameExplorerUninstallUsingIGameExplorer", MB_OK); #endif return hr; } //-------------------------------------------------------------------------------------- // Removes a game from the Game Explorer for Windows 7 //-------------------------------------------------------------------------------------- HRESULT GameExplorerUninstallUsingIGameExplorer2(IGameExplorer2* pFwGameExplorer2, WCHAR* strGDFBinPath) { assert(pFwGameExplorer2); assert(strGDFBinPath); if (strGDFBinPath == NULL || pFwGameExplorer2 == NULL) { return E_INVALIDARG; } #ifdef SHOW_S1_DEBUG_MSGBOXES WCHAR strGameInstanceGUID[128] = {0}; GUID InstanceGUID = GUID_NULL; RetrieveGUIDForApplication(strGDFBinPath, &InstanceGUID); StringFromGUID2(InstanceGUID, strGameInstanceGUID, ARRAYSIZE(strGameInstanceGUID)); #endif // Remove the game from the Game Explorer HRESULT hr = pFwGameExplorer2->UninstallGame(strGDFBinPath); #ifdef SHOW_S1_DEBUG_MSGBOXES WCHAR sz[1024]; swprintf_s(sz, 1024, L"\npInstanceGUID='%s'\nhr=0x%0.8x", strGameInstanceGUID, hr); MessageBox(NULL, sz, L"GameExplorerUninstallUsingIGameExplorer2", MB_OK); #endif return hr; } //-------------------------------------------------------------------------------------- // Updates a game with Game Explorer //-------------------------------------------------------------------------------------- HRESULT GameExplorerUpdateUsingIGameExplorer(IGameExplorer* pFwGameExplorer, WCHAR* strGDFBinPath) { assert(pFwGameExplorer); assert(strGDFBinPath); if (strGDFBinPath == NULL || pFwGameExplorer == NULL) { return E_INVALIDARG; } GUID InstanceGUID = GUID_NULL; HRESULT hr = RetrieveGUIDForApplication(strGDFBinPath, &InstanceGUID); if (SUCCEEDED(hr)) { // Update game using Game Explorer hr = pFwGameExplorer->UpdateGame(InstanceGUID); } #ifdef SHOW_S1_DEBUG_MSGBOXES WCHAR sz[1024]; WCHAR strGameInstanceGUID[128] = {0}; StringFromGUID2(InstanceGUID, strGameInstanceGUID, ARRAYSIZE(strGameInstanceGUID)); swprintf_s(sz, 1024, L"\npInstanceGUID='%s'\nhr=0x%0.8x", strGameInstanceGUID, hr); MessageBox(NULL, sz, L"GameExplorerUpdateUsingIGameExplorer", MB_OK); #endif return hr; } //-------------------------------------------------------------------------------------- // Generates a random GUID //-------------------------------------------------------------------------------------- HRESULT GenerateGUID(GUID* pInstanceGUID) { assert(pInstanceGUID); if (pInstanceGUID == NULL) { return E_INVALIDARG; } return CoCreateGuid(pInstanceGUID); } //-------------------------------------------------------------------------------------- // Gets a property from MSI. Deferred custom action can only access the property called // "CustomActionData" //-------------------------------------------------------------------------------------- LPWSTR GetPropertyFromMSI(MSIHANDLE hMSI, LPCWSTR szPropName) { DWORD dwSize = 0, dwBufferLen = 0; LPWSTR szValue = NULL; WCHAR empty[] = L""; UINT uErr = MsiGetProperty(hMSI, szPropName, empty, &dwSize); if ((ERROR_SUCCESS == uErr) || (ERROR_MORE_DATA == uErr)) { dwSize++; // Add NULL term dwBufferLen = dwSize; szValue = new WCHAR[ dwBufferLen ]; if (szValue) { uErr = MsiGetProperty(hMSI, szPropName, szValue, &dwSize); if ((ERROR_SUCCESS != uErr)) { // Cleanup on failure SAFE_DELETE_ARRAY(szValue); } else { // Make sure buffer is null-terminated szValue[ dwBufferLen - 1 ] = '\0'; } } } return szValue; } //----------------------------------------------------------------------------- // Converts a string to a GUID //----------------------------------------------------------------------------- HRESULT ConvertStringToGUID(const WCHAR* strSrc, GUID* pGuidDest) { assert(strSrc); assert(pGuidDest); if (strSrc == NULL || pGuidDest == NULL) { return E_INVALIDARG; } UINT aiTmp[10]; if (swscanf_s(strSrc, L"{%8X-%4X-%4X-%2X%2X-%2X%2X%2X%2X%2X%2X}", &pGuidDest->Data1, &aiTmp[0], &aiTmp[1], &aiTmp[2], &aiTmp[3], &aiTmp[4], &aiTmp[5], &aiTmp[6], &aiTmp[7], &aiTmp[8], &aiTmp[9]) != 11) { ZeroMemory(pGuidDest, sizeof(GUID)); return E_FAIL; } else { pGuidDest->Data2 = (USHORT)aiTmp[0]; pGuidDest->Data3 = (USHORT)aiTmp[1]; pGuidDest->Data4[0] = (BYTE)aiTmp[2]; pGuidDest->Data4[1] = (BYTE)aiTmp[3]; pGuidDest->Data4[2] = (BYTE)aiTmp[4]; pGuidDest->Data4[3] = (BYTE)aiTmp[5]; pGuidDest->Data4[4] = (BYTE)aiTmp[6]; pGuidDest->Data4[5] = (BYTE)aiTmp[7]; pGuidDest->Data4[6] = (BYTE)aiTmp[8]; pGuidDest->Data4[7] = (BYTE)aiTmp[9]; return S_OK; } } //----------------------------------------------------------------------------- HRESULT ConvertGUIDToStringCch(const GUID* pGuidSrc, WCHAR* strDest, int cchDestChar) { assert(pGuidSrc); assert(strDest); if (pGuidSrc == NULL || strDest == NULL) { return E_INVALIDARG; } return swprintf_s(strDest, cchDestChar, L"{%0.8X-%0.4X-%0.4X-%0.2X%0.2X-%0.2X%0.2X%0.2X%0.2X%0.2X%0.2X}", pGuidSrc->Data1, pGuidSrc->Data2, pGuidSrc->Data3, pGuidSrc->Data4[0], pGuidSrc->Data4[1], pGuidSrc->Data4[2], pGuidSrc->Data4[3], pGuidSrc->Data4[4], pGuidSrc->Data4[5], pGuidSrc->Data4[6], pGuidSrc->Data4[7]); } //----------------------------------------------------------------------------- // Enums WinXP registry for GDF upgrade keys, and returns the GUID // based on the GDF binary path //----------------------------------------------------------------------------- bool RetrieveGUIDForApplicationOnWinXP(HKEY hKeyRoot, WCHAR* szPathToGDFdll, GUID* pGUID) { assert(szPathToGDFdll); assert(pGUID); DWORD iKey = 0; WCHAR strRegKeyName[256]; WCHAR strGDFBinPath[MAX_PATH]; HKEY hKey = NULL; LONG lResult; DWORD dwDisposition, dwType, dwSize; bool bFound = false; for(; ;) { lResult = RegEnumKey(hKeyRoot, iKey, strRegKeyName, 256); if (lResult != ERROR_SUCCESS) { break; } lResult = RegCreateKeyEx(hKeyRoot, strRegKeyName, 0, NULL, 0, KEY_READ, NULL, &hKey, &dwDisposition); if (lResult == ERROR_SUCCESS) { dwSize = MAX_PATH * sizeof(WCHAR); lResult = RegQueryValueEx(hKey, L"GDFBinaryPath", 0, &dwType, (BYTE*)strGDFBinPath, &dwSize); if (lResult == ERROR_SUCCESS) { if (wcscmp(strGDFBinPath, szPathToGDFdll) == 0) { bFound = true; ConvertStringToGUID(strRegKeyName, pGUID); } } RegCloseKey(hKey); } if (bFound) { break; } iKey++; } return bFound; } //----------------------------------------------------------------------------- HRESULT RetrieveGUIDForApplication(WCHAR* szPathToGDFdll, GUID* pGUID) { assert(szPathToGDFdll); assert(pGUID); if (szPathToGDFdll == NULL || pGUID == NULL) { return E_INVALIDARG; } bool bFound = false; HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (SUCCEEDED(hr)) { IWbemLocator* pIWbemLocator = NULL; hr = CoCreateInstance(__uuidof(WbemLocator), NULL, CLSCTX_INPROC_SERVER, __uuidof(IWbemLocator), (LPVOID*)&pIWbemLocator); if (SUCCEEDED(hr) && pIWbemLocator) { // Using the locator, connect to WMI in the given namespace. BSTR pNamespace = SysAllocString(L"\\\\.\\root\\cimv2\\Applications\\Games"); IWbemServices* pIWbemServices = NULL; hr = pIWbemLocator->ConnectServer(pNamespace, NULL, NULL, 0L, 0L, NULL, NULL, &pIWbemServices); if (SUCCEEDED(hr) && (pIWbemServices != NULL)) { // Switch security level to IMPERSONATE. CoSetProxyBlanket(pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0); BSTR bstrQueryType = SysAllocString(L"WQL"); // Double up the '\' marks for the WQL query WCHAR szDoubleSlash[2048]; int iDest = 0, iSource = 0; for(; ;) { if (szPathToGDFdll[iSource] == 0 || iDest > 2000) { break; } szDoubleSlash[iDest] = szPathToGDFdll[iSource]; if (szPathToGDFdll[iSource] == L'\\') { iDest++; szDoubleSlash[iDest] = L'\\'; } iDest++; iSource++; } szDoubleSlash[iDest] = 0; WCHAR szQuery[1024]; swprintf_s(szQuery, 1024, L"SELECT * FROM GAME WHERE GDFBinaryPath = \"%s\"", szDoubleSlash); BSTR bstrQuery = SysAllocString(szQuery); IEnumWbemClassObject* pEnum = NULL; hr = pIWbemServices->ExecQuery(bstrQueryType, bstrQuery, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnum); if (SUCCEEDED(hr)) { IWbemClassObject* pGameClass = NULL; DWORD uReturned = 0; BSTR pPropName = NULL; // Get the first one in the list hr = pEnum->Next(5000, 1, &pGameClass, &uReturned); if (SUCCEEDED(hr) && (uReturned != 0) && (pGameClass != NULL)) { VARIANT var; // Get the InstanceID string pPropName = SysAllocString(L"InstanceID"); hr = pGameClass->Get(pPropName, 0L, &var, NULL, NULL); if (SUCCEEDED(hr) && (var.vt == VT_BSTR)) { bFound = true; if (pGUID) { ConvertStringToGUID(var.bstrVal, pGUID); } } if (pPropName) { SysFreeString(pPropName); } } SAFE_RELEASE(pGameClass); } SAFE_RELEASE(pEnum); } if (pNamespace) { SysFreeString(pNamespace); } SAFE_RELEASE(pIWbemServices); } SAFE_RELEASE(pIWbemLocator); CoUninitialize(); } #ifdef SHOW_S2_DEBUG_MSGBOXES WCHAR sz[1024]; swprintf_s(sz, 1024, L"szPathToGDFdll=%s \nbFound=%d", szPathToGDFdll, bFound); MessageBox(NULL, sz, L"RetrieveGUIDForApplication", MB_OK); #endif if (!bFound) { // Look in WinXP regkey paths HKEY hKeyRoot; LONG lResult; DWORD dwDisposition; lResult = RegCreateKeyEx(HKEY_CURRENT_USER, L"Software\\Classes\\Software\\Microsoft\\Windows\\CurrentVersion\\GameUX\\GamesToFindOnWindowsUpgrade", 0, NULL, 0, KEY_READ, NULL, &hKeyRoot, &dwDisposition); if (ERROR_SUCCESS == lResult) { bFound = RetrieveGUIDForApplicationOnWinXP(hKeyRoot, szPathToGDFdll, pGUID); RegCloseKey(hKeyRoot); } if (!bFound) { lResult = RegCreateKeyEx(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\GameUX\\GamesToFindOnWindowsUpgrade", 0, NULL, 0, KEY_READ, NULL, &hKeyRoot, &dwDisposition); if (ERROR_SUCCESS == lResult) { bFound = RetrieveGUIDForApplicationOnWinXP(hKeyRoot, szPathToGDFdll, pGUID); RegCloseKey(hKeyRoot); } } } return (bFound) ? S_OK : E_FAIL; } //----------------------------------------------------------------------------- // Debug function to return account name of calling process //----------------------------------------------------------------------------- HRESULT GetAccountName(WCHAR* strUser, DWORD cchUser, WCHAR* strDomain, DWORD cchDomain) { assert(strUser); assert(strDomain); if (strUser == NULL || strDomain == NULL ) { return E_INVALIDARG; } HRESULT hr = E_FAIL; WCHAR strMachine[256] = {0}; DWORD cchMachine = 256; GetComputerName(strMachine, &cchMachine); WTS_PROCESS_INFOW* pProcessInfo = NULL; HANDLE hServer = WTSOpenServer(strMachine); DWORD dwCount = 0; DWORD dwCurrentProcessId = GetCurrentProcessId(); if (WTSEnumerateProcesses(hServer, 0, 1, &pProcessInfo, &dwCount)) { for(DWORD n = 0; n < dwCount; n++) { if (pProcessInfo[n].ProcessId == dwCurrentProcessId) { SID_NAME_USE eUse; BOOL bSuccess = LookupAccountSid(NULL, pProcessInfo[n].pUserSid, strUser, &cchUser, strDomain, &cchDomain, &eUse); if (bSuccess) { hr = S_OK; } break; } } } WTSFreeMemory(pProcessInfo); WTSCloseServer(hServer); return hr; } //-------------------------------------------------------------------------------------- HRESULT GetXMLAttribute(IXMLDOMNode* pNode, WCHAR* strAttribName, WCHAR* strValue, int cchValue) { assert(pNode); assert(strAttribName); assert(strValue); if (pNode == NULL || strAttribName == NULL || strValue == NULL) { return E_INVALIDARG; } bool bFound = false; IXMLDOMNamedNodeMap* pIXMLDOMNamedNodeMap = NULL; BSTR bstrAttributeName = ::SysAllocString( strAttribName ); IXMLDOMNode* pIXMLDOMNode = NULL; HRESULT hr; VARIANT v; hr = pNode->get_attributes( &pIXMLDOMNamedNodeMap ); if( SUCCEEDED( hr ) && pIXMLDOMNamedNodeMap ) { hr = pIXMLDOMNamedNodeMap->getNamedItem( bstrAttributeName, &pIXMLDOMNode ); if( SUCCEEDED( hr ) && pIXMLDOMNode ) { pIXMLDOMNode->get_nodeValue( &v ); if( SUCCEEDED( hr ) && v.vt == VT_BSTR ) { wcscpy_s( strValue, cchValue, v.bstrVal ); bFound = true; } VariantClear( &v ); SAFE_RELEASE( pIXMLDOMNode ); } SAFE_RELEASE( pIXMLDOMNamedNodeMap ); } ::SysFreeString( bstrAttributeName ); bstrAttributeName = NULL; if( !bFound ) { return S_FALSE; } else { return S_OK; } } //----------------------------------------------------------------------------- HRESULT GetBaseKnownFolderCsidl(WCHAR* strBaseKnownFolder, int* pCsidl) { assert(strBaseKnownFolder); assert(pCsidl); if (strBaseKnownFolder == NULL || pCsidl == NULL ) { return E_INVALIDARG; } HRESULT hr = S_OK; if (wcscmp(strBaseKnownFolder, L"{905e63b6-c1bf-494e-b29c-65b732d3d21a}") == 0) { *pCsidl = CSIDL_PROGRAM_FILES; } else if (wcscmp(strBaseKnownFolder, L"{F7F1ED05-9F6D-47A2-AAAE-29D317C6F066}") == 0) { *pCsidl = CSIDL_PROGRAM_FILES_COMMON; } else if (wcscmp(strBaseKnownFolder, L"{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}") == 0) { *pCsidl = CSIDL_DESKTOP; } else if (wcscmp(strBaseKnownFolder, L"{FDD39AD0-238F-46AF-ADB4-6C85480369C7}") == 0) { *pCsidl = CSIDL_MYDOCUMENTS; } else if (wcscmp(strBaseKnownFolder, L"{C4AA340D-F20F-4863-AFEF-F87EF2E6BA25}") == 0) { *pCsidl = CSIDL_COMMON_DESKTOPDIRECTORY; } else if (wcscmp(strBaseKnownFolder, L"{ED4824AF-DCE4-45A8-81E2-FC7965083634}") == 0) { *pCsidl = CSIDL_COMMON_DOCUMENTS; } else if (wcscmp(strBaseKnownFolder, L"{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}") == 0) { *pCsidl = CSIDL_SYSTEM; } else if (wcscmp(strBaseKnownFolder, L"{F38BF404-1D43-42F2-9305-67DE0B28FC23}") == 0) { *pCsidl = CSIDL_WINDOWS; } else { hr = S_FALSE; } return hr; } //----------------------------------------------------------------------------- HRESULT CreateShortcut(WCHAR* strLaunchPath, WCHAR* strCommandLineArgs, // strCommandLineArgs can be NULL WCHAR* strShortcutFilePath, BOOL bFileTask) { assert(strLaunchPath); assert(strShortcutFilePath); if (strLaunchPath == NULL || strShortcutFilePath == NULL ) { return E_INVALIDARG; } HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (SUCCEEDED(hr)) { IShellLink* psl; hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl); if (SUCCEEDED(hr)) { // Setup shortcut psl->SetPath(strLaunchPath); if (strCommandLineArgs) { psl->SetArguments(strCommandLineArgs); } // These shortcut settings aren't needed for tasks // if (strIconPath) psl->SetIconLocation(strIconPath, nIcon); // if (wHotkey) psl->SetHotkey(wHotkey); // if (nShowCmd) psl->SetShowCmd(nShowCmd); // if (strDescription) psl->SetDescription(strDescription); if (bFileTask) { // Set working dir to path of launch exe WCHAR strFullPath[512]; WCHAR* strExePart; GetFullPathName(strLaunchPath, 512, strFullPath, &strExePart); if (strExePart) { *strExePart = 0; } psl->SetWorkingDirectory(strFullPath); } // Save shortcut to file IPersistFile* ppf; hr = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf); if (SUCCEEDED(hr)) { hr = ppf->Save(strShortcutFilePath, TRUE); ppf->Release(); } psl->Release(); } CoUninitialize(); } return hr; } //----------------------------------------------------------------------------- HRESULT SubCreateSingleTask(GAME_INSTALL_SCOPE InstallScope, // Either GIS_CURRENT_USER or GIS_ALL_USERS WCHAR* strGDFBinPath, // valid GameInstance GUID that was passed to AddGame() WCHAR* strTaskName, // Name of task. Ex "Play" WCHAR* strLaunchPath, // Path to exe. Example: "C:\Program Files\Microsoft\MyGame.exe" WCHAR* strCommandLineArgs, // Can be NULL. Example: "-windowed" int nTaskID, // ID of task BOOL bSupportTask, // if TRUE, this is a support task otherwise it is a play task BOOL bFileTask) // if TRUE, this is a file task otherwise it is a URL task { assert(strGDFBinPath); assert(strTaskName); assert(strLaunchPath); if (strGDFBinPath == NULL || strTaskName == NULL || strLaunchPath == NULL) { return E_INVALIDARG; } HRESULT hr; WCHAR strPath[512]; WCHAR strGUID[256]; WCHAR strCommonFolder[MAX_PATH]; WCHAR strShortcutFilePath[512]; // Get base path based on install scope if (InstallScope == GIS_CURRENT_USER) { SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, strCommonFolder); } else { SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, strCommonFolder); } GUID InstanceGUID = GUID_NULL; if (FAILED(hr = RetrieveGUIDForApplication(strGDFBinPath, &InstanceGUID))) { return hr; } // Convert GUID to string if (StringFromGUID2(InstanceGUID, strGUID, ARRAYSIZE(strGUID)) == 0) { return E_FAIL; } // Create dir path for shortcut swprintf_s(strPath, 512, L"%s\\Microsoft\\Windows\\GameExplorer\\%s\\%s\\%d", strCommonFolder, strGUID, (bSupportTask) ? L"SupportTasks" : L"PlayTasks", nTaskID); // Create the directory and all intermediate directories SHCreateDirectoryEx(NULL, strPath, NULL); // Create full file path to shortcut swprintf_s(strShortcutFilePath, 512, L"%s\\%s.lnk", strPath, strTaskName); #ifdef SHOW_S2_DEBUG_MSGBOXES WCHAR sz[1024]; swprintf_s(sz, 1024, L"strShortcutFilePath='%s' strTaskName='%s'", strShortcutFilePath, strTaskName); MessageBox(NULL, sz, L"CreateTask", MB_OK); #endif // Create shortcut hr = CreateShortcut(strLaunchPath, strCommandLineArgs, strShortcutFilePath, bFileTask); return hr; } //----------------------------------------------------------------------------- HRESULT RemoveTasks(WCHAR* strGDFBinPath) // valid GameInstance GUID that was passed to AddGame() { assert(strGDFBinPath); if (strGDFBinPath == NULL) { return E_INVALIDARG; } HRESULT hr; WCHAR strPath[512] = {0}; WCHAR strGUID[256]; WCHAR strLocalAppData[MAX_PATH]; WCHAR strCommonAppData[MAX_PATH]; // Get base path based on install scope if (FAILED(hr = SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, strLocalAppData))) { return hr; } if (FAILED(hr = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, strCommonAppData))) { return hr; } GUID InstanceGUID = GUID_NULL; if (FAILED(hr = RetrieveGUIDForApplication(strGDFBinPath, &InstanceGUID))) { return hr; } // Convert GUID to string if (StringFromGUID2(InstanceGUID, strGUID, ARRAYSIZE(strGUID)) == 0) return E_FAIL; if (FAILED(hr = swprintf_s(strPath, 512, L"%s\\Microsoft\\Windows\\GameExplorer\\%s", strLocalAppData, strGUID))) { return hr; } SHFILEOPSTRUCT fileOp = {}; fileOp.wFunc = FO_DELETE; fileOp.pFrom = strPath; fileOp.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT; SHFileOperation(&fileOp); if (FAILED(hr = swprintf_s(strPath, 512, L"%s\\Microsoft\\Windows\\GameExplorer\\%s", strCommonAppData, strGUID))) { return hr; } ZeroMemory(&fileOp, sizeof(SHFILEOPSTRUCT)); fileOp.wFunc = FO_DELETE; fileOp.pFrom = strPath; fileOp.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT; SHFileOperation(&fileOp); return S_OK; } //----------------------------------------------------------------------------- HRESULT CreateSingleTask(IXMLDOMNode* pTaskNode, WCHAR* strGDFBinPath, WCHAR* strGameInstallPath, GAME_INSTALL_SCOPE InstallScope, BOOL bPrimaryTask, BOOL bSupportTask) { assert(pTaskNode); assert(strGDFBinPath); assert(strGameInstallPath); if (pTaskNode == NULL || strGDFBinPath == NULL || strGameInstallPath == NULL) { return E_INVALIDARG; } HRESULT hr = S_OK; WCHAR strTaskName[256] = {0}; if (bPrimaryTask) { wcscpy_s( strTaskName, 256, L"Play"); } else { hr = GetXMLAttribute(pTaskNode, L"name", strTaskName, 256); } if (SUCCEEDED(hr)) { WCHAR strTaskID[256] = {0}; if (bPrimaryTask) { wcscpy_s( strTaskID, 256, L"0"); } else { hr = GetXMLAttribute(pTaskNode, L"index", strTaskID, 256); } if (SUCCEEDED(hr)) { int nTaskID = _wtoi(strTaskID); IXMLDOMNode* pFileTaskNode = NULL; pTaskNode->selectSingleNode(L"FileTask", &pFileTaskNode); if (pFileTaskNode != NULL) { WCHAR strPath[256] = {0}; hr = GetXMLAttribute(pFileTaskNode, L"path", strPath, 256); if (SUCCEEDED(hr)) { WCHAR strCommandLineArgs[256] = {0}; hr = GetXMLAttribute(pFileTaskNode, L"arguments", strCommandLineArgs, 256); if (SUCCEEDED(hr)) { WCHAR strBaseKnownFolderID[256] = {0}; hr = GetXMLAttribute(pFileTaskNode, L"baseKnownFolderID", strBaseKnownFolderID, 256); if (hr == S_OK) { int nCsidl; hr = GetBaseKnownFolderCsidl(strBaseKnownFolderID, &nCsidl); if (hr == S_OK) { WCHAR strFolderPath[MAX_PATH]; hr = SHGetFolderPath(NULL, nCsidl, NULL, SHGFP_TYPE_CURRENT, strFolderPath); if (SUCCEEDED(hr)) { WCHAR strLaunchPath[MAX_PATH] = {0}; swprintf_s( strLaunchPath, MAX_PATH, L"%s\\%s", strFolderPath, strPath); hr = SubCreateSingleTask(InstallScope, strGDFBinPath, strTaskName, strLaunchPath, strCommandLineArgs, nTaskID, bSupportTask, true); } } } else if(hr == S_FALSE) { WCHAR strLaunchPath[MAX_PATH]; swprintf_s( strLaunchPath, MAX_PATH, L"%s%s", strGameInstallPath, strPath); hr = SubCreateSingleTask(InstallScope, strGDFBinPath, strTaskName, strLaunchPath, strCommandLineArgs, nTaskID, bSupportTask, true); } } } } else { IXMLDOMNode* pURLTaskNode = NULL; pTaskNode->selectSingleNode(L"URLTask", &pURLTaskNode); if (pURLTaskNode != NULL) { WCHAR strURLPath[256] = {0}; hr = GetXMLAttribute(pURLTaskNode, L"Link", strURLPath, 256); if (SUCCEEDED(hr)) { hr = SubCreateSingleTask(InstallScope, strGDFBinPath, strTaskName, strURLPath, NULL, nTaskID, bSupportTask, false); } } } } } return hr; } //----------------------------------------------------------------------------- HRESULT CreateTasks(WCHAR* strGDFBinPath, WCHAR* strGameInstallPath, GAME_INSTALL_SCOPE InstallScope) { assert(strGDFBinPath); assert(strGameInstallPath); if (strGDFBinPath == NULL || strGameInstallPath == NULL) { return E_INVALIDARG; } CGDFParse gdfParse; HRESULT hr = gdfParse.ExtractXML( strGDFBinPath ); if( SUCCEEDED( hr ) ) { IXMLDOMNode* pRootNode = NULL; gdfParse.GetXMLRootNode(&pRootNode); if (pRootNode != NULL) { IXMLDOMNode* pPlayTasksNode = NULL; pRootNode->selectSingleNode(L"//GameDefinitionFile/GameDefinition/ExtendedProperties/GameTasks/Play", &pPlayTasksNode); if (pPlayTasksNode != NULL) { IXMLDOMNode* pPrimaryPlayTaskNode = NULL; pPlayTasksNode->selectSingleNode(L"Primary", &pPrimaryPlayTaskNode); if (pPrimaryPlayTaskNode != NULL) { hr = CreateSingleTask(pPrimaryPlayTaskNode, strGDFBinPath, strGameInstallPath, InstallScope, true, false); if( SUCCEEDED( hr ) ) { // Secondary play tasks IXMLDOMNode* pSecondaryPlayTaskNode; pPrimaryPlayTaskNode->get_nextSibling(&pSecondaryPlayTaskNode); while (pSecondaryPlayTaskNode != NULL) { hr = CreateSingleTask(pSecondaryPlayTaskNode, strGDFBinPath, strGameInstallPath, InstallScope, false, false); pSecondaryPlayTaskNode->get_nextSibling(&pSecondaryPlayTaskNode); } } } // support tasks if (SUCCEEDED(hr)) { IXMLDOMNode* pSupportTasksNode = NULL; pRootNode->selectSingleNode(L"//GameDefinitionFile/GameDefinition/ExtendedProperties/GameTasks/Support", &pSupportTasksNode); if (pSupportTasksNode != NULL) { IXMLDOMNode* pTaskNode = NULL; pSupportTasksNode->selectSingleNode(L"Task", &pTaskNode); while (pTaskNode != NULL) { hr = CreateSingleTask(pTaskNode, strGDFBinPath, strGameInstallPath, InstallScope, false, true); pTaskNode->get_nextSibling(&pTaskNode); } } } } else { #ifdef SHOW_S1_DEBUG_MSGBOXES WCHAR sz[1024]; swprintf_s(sz, 1024, L"The game task information is missing! Please check your GDF file and reinstall the game again!"); MessageBox(NULL, sz, L"GameExplorerInstall", MB_OK); #endif hr = S_FALSE; } } } return hr; } /****************************************************************** IsV2GDF - test the GDF version ********************************************************************/ HRESULT IsV2GDF ( __in WCHAR* strGDFBinPath, __out BOOL* pfV2GDF ) { assert(strGDFBinPath); assert(pfV2GDF); #ifdef SHOW_S1_DEBUG_MSGBOXES WCHAR sz[1024]; swprintf_s(sz, 1024, L"IsV2GDF\n"); MessageBox(NULL, sz, L"IsV2GDF", MB_OK); #endif if (strGDFBinPath == NULL || pfV2GDF == NULL) { return E_INVALIDARG; } *pfV2GDF = FALSE; CGDFParse gdfParse; HRESULT hr = gdfParse.ExtractXML( strGDFBinPath ); if( SUCCEEDED( hr ) ) { IXMLDOMNode* pRootNode = NULL; gdfParse.GetXMLRootNode(&pRootNode); if (pRootNode != NULL) { IXMLDOMNode* pPrimaryPlayTasksNode = NULL; hr = pRootNode->selectSingleNode(L"//GameDefinitionFile/GameDefinition/ExtendedProperties/GameTasks/Play/Primary", &pPrimaryPlayTasksNode); if (S_OK == hr) { *pfV2GDF = TRUE; } else if (S_FALSE == hr) { *pfV2GDF = FALSE; } else { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); } } } return hr; }
nonkr/cat
ipc/semaphore/c/system_v_sem.c
<gh_stars>0 /* * Copy from Linux高性能服务器编程 * Datetime: 2018/2/2 10:18 * */ #include <sys/sem.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> union semun { int val; struct semid_ds *buf; unsigned short int *array; struct seminfo *__buf; }; void pv(int sem_id, int op) { struct sembuf sem_b; sem_b.sem_num = 0; sem_b.sem_op = op; sem_b.sem_flg = SEM_UNDO; semop(sem_id, &sem_b, 1); } int main(int argc, char *argv[]) { int sem_id = semget(IPC_PRIVATE, 1, 0666); union semun sem_un; sem_un.val = 1; semctl(sem_id, 0, SETVAL, sem_un); pid_t id = fork(); if (id < 0) { return 1; } else if (id == 0) { printf("child try to get binary sem\n"); pv(sem_id, -1); printf("child get the sem and would release it after 5 seconds\n"); sleep(5); pv(sem_id, 1); exit(0); } else { printf("parent try to get binary sem\n"); pv(sem_id, -1); printf("parent get the sem and would release it after 5 seconds\n"); sleep(5); pv(sem_id, 1); } waitpid(id, NULL, 0); semctl(sem_id, 0, IPC_RMID, sem_un); return 0; }
maxtomCMU/hfnet
hfnet/models/netvlad_original.py
""" Based on the TensorFlow re-implementation of NetVLAD by <NAME>. Paper: https://arxiv.org/abs/1511.07247 TensorFlow: github.com/uzh-rpg/netvlad_tf_open Matlab: github.com/Relja/netvlad """ import tensorflow as tf import numpy as np from .base_model import BaseModel def vlad_legacy(inputs, num_clusters, assign_weight_initializer=None, cluster_initializer=None, skip_postnorm=False): K = num_clusters D = inputs.get_shape()[-1] # soft-assignment. s = tf.layers.conv2d(inputs, K, 1, use_bias=False, kernel_initializer=assign_weight_initializer, name='assignment') a = tf.nn.softmax(s) # Dims used hereafter: batch, H, W, desc_coeff, cluster # Move cluster assignment to corresponding dimension. a = tf.expand_dims(a, -2) # VLAD core. C = tf.get_variable('cluster_centers', [1, 1, 1, D, K], initializer=cluster_initializer, dtype=inputs.dtype) v = tf.expand_dims(inputs, -1) + C v = a * v v = tf.reduce_sum(v, axis=[1, 2]) v = tf.transpose(v, perm=[0, 2, 1]) if not skip_postnorm: # Result seems to be very sensitive to the normalization method # details, so sticking to matconvnet-style normalization here. v = matconvnetNormalize(v, 1e-12) v = tf.transpose(v, perm=[0, 2, 1]) v = matconvnetNormalize(tf.layers.flatten(v), 1e-12) return v def matconvnetNormalize(inputs, epsilon): return inputs / tf.sqrt(tf.reduce_sum(inputs ** 2, axis=-1, keep_dims=True) + epsilon) class NetvladOriginal(BaseModel): input_spec = { 'image': {'shape': [None, None, None, 3], 'type': tf.float32}, } required_config_keys = [] default_config = { 'num_clusters': 64, 'pca_dimension': 4096, 'local_descriptor_layer': None, } def _model(self, inputs, mode, **config): image_batch = inputs['image'] with tf.variable_scope('vgg16_netvlad_pca'): # Gray to color if necessary. if image_batch.shape[3] == 1: x = tf.nn.conv2d(image_batch, np.ones((1, 1, 1, 3)), np.ones(4).tolist(), 'VALID') else: assert image_batch.shape[3] == 3 x = image_batch # Subtract trained average image. average_rgb = tf.get_variable( 'average_rgb', 3, dtype=image_batch.dtype) x = x - average_rgb endpoints = {} # VGG16 def vggConv(inputs, numbers, out_dim, with_relu): activation = tf.nn.relu if with_relu else None return tf.layers.conv2d( inputs, out_dim, [3, 3], 1, padding='same', activation=activation, name='conv%s' % numbers) def vggPool(inputs): return tf.layers.max_pooling2d(inputs, 2, 2) x = vggConv(x, '1_1', 64, True) x = vggConv(x, '1_2', 64, False) endpoints['conv1_2'] = x x = vggPool(x) x = tf.nn.relu(x) x = vggConv(x, '2_1', 128, True) x = vggConv(x, '2_2', 128, False) endpoints['conv2_2'] = x x = vggPool(x) x = tf.nn.relu(x) x = vggConv(x, '3_1', 256, True) x = vggConv(x, '3_2', 256, True) x = vggConv(x, '3_3', 256, False) endpoints['conv3_3'] = x x = vggPool(x) x = tf.nn.relu(x) x = vggConv(x, '4_1', 512, True) x = vggConv(x, '4_2', 512, True) x = vggConv(x, '4_3', 512, False) endpoints['conv4_3'] = x x = vggPool(x) x = tf.nn.relu(x) x = vggConv(x, '5_1', 512, True) x = vggConv(x, '5_2', 512, True) x = vggConv(x, '5_3', 512, False) endpoints['conv5_3'] = x # NetVLAD x = tf.nn.l2_normalize(x, dim=-1) x = vlad_legacy(x, config['num_clusters']) # PCA x = tf.layers.conv2d(tf.expand_dims(tf.expand_dims(x, 1), 1), config['pca_dimension'], 1, 1, name='WPCA') x = tf.nn.l2_normalize(tf.layers.flatten(x), dim=-1) ret = {'global_descriptor': x} if config['local_descriptor_layer']: desc = tf.nn.l2_normalize( endpoints[config['local_descriptor_layer']], axis=-1) ret['local_descriptor_map'] = desc return ret def _loss(self, outputs, inputs, **config): raise NotImplementedError def _metrics(self, outputs, inputs, **config): raise NotImplementedError
iconben/gitlabhq
app/services/jira_import/users_importer.rb
# frozen_string_literal: true module JiraImport class UsersImporter def initialize(user, project, start_at) @project = project @start_at = start_at @user = user end def execute Gitlab::JiraImport.validate_project_settings!(project, user: user) ServiceResponse.success(payload: mapped_users) rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, Errno::ECONNREFUSED, URI::InvalidURIError, JIRA::HTTPError, OpenSSL::SSL::SSLError => error Gitlab::ErrorTracking.log_exception(error, project_id: project.id) ServiceResponse.error(message: "There was an error when communicating to Jira") rescue Projects::ImportService::Error => error ServiceResponse.error(message: error.message) end private attr_reader :user, :project, :start_at def mapped_users users_mapper_service.execute end def users_mapper_service @users_mapper_service ||= user_mapper_service_factory end def user_mapper_service_factory if project.jira_service.data_fields.deployment_server? ServerUsersMapperService.new(user, project, start_at) elsif project.jira_service.data_fields.deployment_cloud? CloudUsersMapperService.new(user, project, start_at) else raise ArgumentError end end end end
ranguli/canonical-ubuntu-18.04-lts-stig-baseline
controls/V-219158.rb
# encoding: UTF-8 control 'V-219158' do title "The Ubuntu operating system must not have the rsh-server package installed." desc "It is detrimental for Ubuntu operating systems to provide, or install by default, functionality exceeding requirements or mission objectives. These unnecessary capabilities or services are often overlooked and therefore may remain unsecured. They increase the risk to the platform by providing additional attack vectors. Ubuntu operating systems are capable of providing a wide variety of functions and services. Some of the functions and services, provided by default, may not be necessary to support essential organizational operations (e.g., key missions, functions). The rsh-server service provides an unencrypted remote access service that does not provide for the confidentiality and integrity of user passwords or the remote session and has very weak authentication. If a privileged user were to log on using this service, the privileged user password could be compromised. " desc 'rationale', '' desc 'check', " Check to see if the rsh-server package is installed with the following command: # dpkg -l | grep rsh-server If the rsh-server package is installed, this is a finding. " desc 'fix', " Configure the Ubuntu operating system to disable non-essential capabilities by removing the rsh-server package from the system with the following command: # sudo apt-get remove rsh-server " impact 0.7 tag severity: 'high' tag gtitle: 'SRG-OS-000095-GPOS-00049' tag gid: 'V-219158' tag rid: 'SV-219158r508662_rule' tag stig_id: 'UBTU-18-010019' tag fix_id: 'F-20882r304803_fix' tag cci: ['SV-109645', 'V-100541', 'CCI-000381'] tag nist: ['CM-7 a'] end
saai/LeetcodePythonSolutions
restoreIpAddresses.py
class Solution: # @param {string} s # @return {string[]} def restoreIpAddresses(self, s): res =[] def addPoint(frontStr,restStr,pointNum): if pointNum==0: if self.isValidSection(restStr): r = frontStr[1::] + restStr res.append(r) return l = len(restStr) fp_len = 1 rp_len = l - fp_len while(fp_len <=3 and rp_len>=pointNum and rp_len<=(pointNum+1)*3): curSection = restStr[0:fp_len] if self.isValidSection(curSection): newFrontStr = frontStr + curSection+'.' addPoint(newFrontStr,restStr[fp_len:l],pointNum-1) fp_len += 1 rp_len = l-fp_len addPoint('.',s,3) return res def isValidSection(self, s): if len(s)==0 or len(s)>3 or (s[0] == '0' and len(s)!=1)or int(s)>255: return False return True
kevin-DL/m3o-go
examples/user/readSession/readASessionByTheSessionId.go
<filename>examples/user/readSession/readASessionByTheSessionId.go package example import ( "fmt" "os" "go.m3o.com/user" ) // Read a session by the session id. In the event it has expired or is not found and error is returned. func ReadAsessionByTheSessionId() { userService := user.NewUserService(os.Getenv("M3O_API_TOKEN")) rsp, err := userService.ReadSession(&user.ReadSessionRequest{ SessionId: "sds34s34s34-s34s34-s43s43s34-s4s34s", }) fmt.Println(rsp, err) }
Zhongger/zmail
zmail-product/src/main/java/com/zhongger/zmail/product/dao/SpuInfoDao.java
package com.zhongger.zmail.product.dao; import com.zhongger.zmail.product.entity.SpuInfoEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; /** * spu信息 * * @author zhongmingyi * @email <EMAIL> * @date 2019-10-01 21:08:49 */ @Mapper public interface SpuInfoDao extends BaseMapper<SpuInfoEntity> { void updateSpuStatus(@Param("spuId") Long spuId, @Param("code") int code); }
factorion/graytracer
pkg/patterns/stripe.go
package patterns import ( "math" "github.com/factorion/graytracer/pkg/primitives" ) // Stripe Basic stripe pattern based on x-axis value type Stripe struct { PatternBase pattern1, pattern2 Pattern } // MakeStripe Make a stripe pattern from two patterns func MakeStripe(p1, p2 Pattern) *Stripe { return &Stripe{PatternBase:PatternBase{transform:primitives.MakeIdentityMatrix(4)}, pattern1:p1, pattern2:p2} } // ColorAt Calculate which stripe and return the color func (s Stripe) ColorAt(point primitives.PV) RGB { patternPoint := s.PatternPoint(point) if int(math.Floor(patternPoint.X)) % 2 == 0 { return s.pattern1.ColorAt(patternPoint) } return s.pattern2.ColorAt(patternPoint) }
myronZhouJ/AdxLibrary_iOS
ADXLibrary/Dependencies/FBAudienceNetwork.framework/Headers/FBRewardedVideoAd.h
version https://git-lfs.github.com/spec/v1 oid sha256:a86a86957d5e1f4452a88f14dbdfe36c9c482260c3fd53a0621cc8e535a78000 size 7307
xzxie/nuls
consensus-impl/poc/poc-consensus-protocol-impl/src/main/java/io/nuls/consensus/poc/block/validator/SmallBlockValidator.java
<filename>consensus-impl/poc/poc-consensus-protocol-impl/src/main/java/io/nuls/consensus/poc/block/validator/SmallBlockValidator.java package io.nuls.consensus.poc.block.validator; import io.nuls.core.constant.ErrorCode; import io.nuls.core.validate.NulsDataValidator; import io.nuls.core.validate.ValidateResult; import io.nuls.protocol.model.NulsDigestData; import io.nuls.protocol.model.SmallBlock; /** * @author: <NAME> * @date: 2018/4/19 */ public class SmallBlockValidator implements NulsDataValidator<SmallBlock> { /** * @param data * @return */ @Override public ValidateResult validate(SmallBlock data) { if (null == data || data.getHeader() == null || null == data.getTxHashList() || null == data.getSubTxList() || data.getTxHashList().isEmpty() || data.getSubTxList().isEmpty()) { return ValidateResult.getFailedResult(ErrorCode.DATA_ERROR, "the small block has null field"); } ValidateResult result = data.getHeader().verify(); if (result.isFailed()) { return result; } if (!data.getHeader().getMerkleHash().equals(NulsDigestData.calcMerkleDigestData(data.getTxHashList()))) { return ValidateResult.getFailedResult("the MerkleHash is wrong:" + data.getHeader().getHash()); } return ValidateResult.getSuccessResult(); } }
DragonStuff/actor-platform
actor-server/actor-peer-managers/src/main/scala/im/actor/server/peermanagers/GroupsImplicits.scala
package im.actor.server.peermanagers import im.actor.api.rpc.groups.Member import im.actor.server.models trait GroupsImplicits { implicit class ExtGroupUser(gu: models.GroupUser) { def toMember: Member = Member(gu.userId, gu.inviterUserId, gu.invitedAt.getMillis) } }
Keneral/asystem
update_engine/payload_generator/fake_filesystem.h
<reponame>Keneral/asystem // // Copyright (C) 2015 The Android Open Source Project // // 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. // #ifndef UPDATE_ENGINE_PAYLOAD_GENERATOR_FAKE_FILESYSTEM_H_ #define UPDATE_ENGINE_PAYLOAD_GENERATOR_FAKE_FILESYSTEM_H_ // A fake filesystem interface implementation allowing the user to add arbitrary // files/metadata. #include "update_engine/payload_generator/filesystem_interface.h" #include <string> #include <vector> #include "update_engine/update_metadata.pb.h" namespace chromeos_update_engine { class FakeFilesystem : public FilesystemInterface { public: FakeFilesystem(uint64_t block_size, uint64_t block_count); virtual ~FakeFilesystem() = default; // FilesystemInterface overrides. size_t GetBlockSize() const override; size_t GetBlockCount() const override; bool GetFiles(std::vector<File>* files) const override; bool LoadSettings(brillo::KeyValueStore* store) const override; // Fake methods. // Add a file to the list of fake files. void AddFile(const std::string& filename, const std::vector<Extent> extents); // Sets the PAYLOAD_MINOR_VERSION key stored by LoadSettings(). Use a negative // value to produce an error in LoadSettings(). void SetMinorVersion(int minor_version) { minor_version_ = minor_version; } private: FakeFilesystem() = default; uint64_t block_size_; uint64_t block_count_; int minor_version_{-1}; std::vector<File> files_; DISALLOW_COPY_AND_ASSIGN(FakeFilesystem); }; } // namespace chromeos_update_engine #endif // UPDATE_ENGINE_PAYLOAD_GENERATOR_FAKE_FILESYSTEM_H_
SAP-samples/sap-iot-hyperscaler-azure-integration-ref
integration-commons/src/main/java/com/sap/iot/azure/ref/integration/commons/cache/CacheKeyBuilder.java
package com.sap.iot.azure.ref.integration.commons.cache; import com.sap.iot.azure.ref.integration.commons.mapping.MappingServiceConstants; import java.nio.charset.StandardCharsets; public class CacheKeyBuilder { /** * Generate key for sensor info cache entry from sensor and capability id. * * @param sensorId used for constructing key * @param capabilityId used for constructing key * @return sensor info key as byte array */ public static byte[] constructSensorInfoKey(String sensorId, String capabilityId) { return (MappingServiceConstants.CACHE_KEY_CREATOR_PREFIX + MappingServiceConstants.CACHE_SENSOR_KEY_PREFIX + sensorId + MappingServiceConstants.CACHE_KEY_SEPARATOR + capabilityId).getBytes(StandardCharsets.UTF_8); } /** * Generate key for property mapping info cache entry from mapping, structure and virtual capability id. * * @param mappingId used for constructing key * @param structureId used for constructing key * @param virtualCapabilityId used for constructing key * @return property mapping info key as byte array */ public static byte[] constructPropertyMappingInfoKey(String mappingId, String structureId, String virtualCapabilityId) { String sep = MappingServiceConstants.CACHE_KEY_SEPARATOR; return (MappingServiceConstants.CACHE_KEY_CREATOR_PREFIX + MappingServiceConstants.CACHE_MAPPING_KEY_PREFIX + mappingId + sep + structureId + sep + virtualCapabilityId).getBytes(StandardCharsets.UTF_8); } /** * Generate key for sensor cache entry from sensor id. * * @param sensorId used for constructing key * @return sensor key as byte array */ public static byte[] constructSensorKey(String sensorId) { return (MappingServiceConstants.CACHE_KEY_CREATOR_PREFIX + MappingServiceConstants.CACHE_SENSOR_KEY_PREFIX + sensorId).getBytes(StandardCharsets.UTF_8); } /** * Generate key for schema info cache entry from structure id. * * @param structureId used for constructing key * @return schema info key as byte array */ public static byte[] constructSchemaInfoKey(String structureId) { return (MappingServiceConstants.CACHE_KEY_CREATOR_PREFIX + MappingServiceConstants.CACHE_STRUCTURE_KEY_PREFIX + structureId).getBytes(StandardCharsets.UTF_8); } /** * Returns a given cache key as byte array. * * @param key to be converted to byte array * @return provided key as byte array */ public static byte[] getKeyAsBytes(String key) { return key.getBytes(StandardCharsets.UTF_8); } }
mantanquzzmo/footballsimulator_rails_api
spec/factories/players.rb
<gh_stars>0 FactoryBot.define do factory :player do name { 'Marquinhos' } age { 21 } position { 'A' } skill { 5 } form { 11 } form_tendency { 4 } starting_11 { 0 } association :team end end
azeemba/everyoneisjohn
client/reducers/app.js
// @flow import {SOUND, ON} from '../constants/settings'; import {CONNECTING} from '../constants/connection-status'; import {get} from '../utils/local-storage'; import {AppStateType, ActionType} from './types'; export const defaultState = { error: null, sound: get(SOUND) === ON, connection: { status: CONNECTING } }; const AppReducer = (state: AppStateType = defaultState, action: ActionType): AppStateType => { const {type, payload} = action; switch (type) { case 'SET_ERROR': return { ...state, error: { error: payload.error, type: payload.type } }; case 'CLEAR_ERROR': return { ...state, error: null }; case 'SET_SOUND': return { ...state, sound: payload.sound }; case 'SET_CONNECTION_STATUS': return { ...state, connection: { status: payload.status } }; default: return state; } }; export default AppReducer;
rafi-kamal/Residential-Building-Management-System
app/models/ApartmentBuilding.java
<gh_stars>1-10 package models; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.validation.Valid; import play.data.validation.Constraints.Max; import play.data.validation.Constraints.Min; import play.data.validation.Constraints.Required; import play.db.ebean.Model; @Entity public class ApartmentBuilding extends Model { private static final long serialVersionUID = -888907934350076591L; @Id @GeneratedValue public long id; @Required public String name; @Required @Max(100) public String address; public ApartmentBuilding(String name, String address, RealEstateCompany realEstateCompany) { this.name = name; this.address = address; this.realEstateCompany = realEstateCompany; } @Valid @ManyToOne(fetch=FetchType.LAZY) public RealEstateCompany realEstateCompany; @Valid @OneToMany(fetch=FetchType.LAZY, mappedBy="apartmentBuilding", cascade=CascadeType.ALL) public List<Apartment> apartments; public static Finder<Long, ApartmentBuilding> find = new Finder<Long, ApartmentBuilding> (Long.class, ApartmentBuilding.class); }
adevress/gfal2
test/unit/transfer/tests_params.h
<reponame>adevress/gfal2<gh_stars>0 /* * Copyright @ Members of the EMI Collaboration, 2010. * See www.eu-emi.eu for details on the copyright holders. * * 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. */ #include <gtest/gtest.h> #ifndef TESTS_PARAMS_H #define TESTS_PARAMS_H void create_params(); void test_timeout(); void test_timeout_c(); void test_nbstreams(); void test_nbstreams_c(); void test_lock(); void test_local_transfers(); #endif /* TESTS_PARAMS_H */
Alexey-N-Chernyshov/cpp-libp2p
src/multi/multibase_codec/codecs/base32.cpp
<gh_stars>100-1000 /** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ /** * base32 (de)coder implementation as specified by RFC4648. * * Copyright (c) 2010 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. **/ #include <gsl/span> #include <libp2p/multi/multibase_codec/codecs/base32.hpp> #include <libp2p/multi/multibase_codec/codecs/base_error.hpp> namespace libp2p::multi::detail { const std::string kUpperBase32Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; const std::string kLowerBase32Alphabet = "abcdefghijklmnopqrstuvwxyz234567"; enum Base32Mode { LOWER, UPPER, }; int get_byte(int block) { return block * 5 / 8; } int get_bit(int block) { return 8 - 5 - block * 5 % 8; } char encode_char(unsigned char c, Base32Mode mode) { if (mode == Base32Mode::UPPER) { return kUpperBase32Alphabet[c & 0x1F]; // 0001 1111 } return kLowerBase32Alphabet[c & 0x1F]; } unsigned char shift_right(uint8_t byte, int8_t offset) { if (offset > 0) return byte >> offset; return byte << -offset; } unsigned char shift_left(uint8_t byte, int8_t offset) { return shift_right(byte, -offset); } int encode_sequence(gsl::span<const uint8_t> plain, gsl::span<char> coded, Base32Mode mode) { for (int block = 0; block < 8; block++) { int byte = get_byte(block); int bit = get_bit(block); if (byte >= plain.size()) { return block; } unsigned char c = shift_right(plain[byte], bit); if (bit < 0 && byte < plain.size() - 1) { c |= shift_right(plain[byte + 1], 8 + bit); } coded[block] = encode_char(c, mode); } return 8; } std::string encodeBase32(const common::ByteArray &bytes, Base32Mode mode) { std::string result; if (bytes.size() % 5 == 0) { result = std::string(bytes.size() / 5 * 8, ' '); } else { result = std::string((bytes.size() / 5 + 1) * 8, ' '); } for (size_t i = 0, j = 0; i < bytes.size(); i += 5, j += 8) { int n = encode_sequence( gsl::make_span(&bytes[i], std::min<size_t>(bytes.size() - i, 5)), gsl::make_span(&result[j], 8), mode); if (n < 8) { result.erase(result.end() - (8 - n), result.end()); } } return result; } std::string encodeBase32Upper(const common::ByteArray &bytes) { return encodeBase32(bytes, Base32Mode::UPPER); } std::string encodeBase32Lower(const common::ByteArray &bytes) { return encodeBase32(bytes, Base32Mode::LOWER); } int decode_char(unsigned char c, Base32Mode mode) { char decoded_ch = -1; if (mode == Base32Mode::UPPER) { if (c >= 'A' && c <= 'Z') decoded_ch = c - 'A'; // NOLINT } else { if (c >= 'a' && c <= 'z') decoded_ch = c - 'a'; // NOLINT } if (c >= '2' && c <= '7') decoded_ch = c - '2' + 26; // NOLINT return decoded_ch; } outcome::result<int> decode_sequence(gsl::span<const char> coded, gsl::span<uint8_t> plain, Base32Mode mode) { plain[0] = 0; for (int block = 0; block < 8; block++) { int bit = get_bit(block); int byte = get_byte(block); if (block >= coded.size()) { return byte; } int c = decode_char(coded[block], mode); if (c < 0) { return BaseError::INVALID_BASE32_INPUT; } plain[byte] |= shift_left(c, bit); if (bit < 0) { plain[byte + 1] = shift_left(c, 8 + bit); } } return 5; } outcome::result<common::ByteArray> decodeBase32(std::string_view string, Base32Mode mode) { common::ByteArray result; if (string.size() % 8 == 0) { result = common::ByteArray(string.size() / 8 * 5); } else { result = common::ByteArray((string.size() / 8 + 1) * 5); } for (size_t i = 0, j = 0; i < string.size(); i += 8, j += 5) { OUTCOME_TRY(n, decode_sequence( gsl::make_span(&string[i], std::min<size_t>(string.size() - i, 8)), gsl::make_span(&result[j], 5), mode)); if (n < 5) { result.erase(result.end() - (5 - n), result.end()); } } return result; } outcome::result<common::ByteArray> decodeBase32Upper( std::string_view string) { return decodeBase32(string, Base32Mode::UPPER); } outcome::result<common::ByteArray> decodeBase32Lower( std::string_view string) { return decodeBase32(string, Base32Mode::LOWER); } } // namespace libp2p::multi::detail
KirilChuchev/BgPropertiesSpa
BgPropertiesClient/bg-properties-client/src/components/BgProperties/BgProperty/BgProperty.js
<filename>BgPropertiesClient/bg-properties-client/src/components/BgProperties/BgProperty/BgProperty.js import { useContext, useEffect, useState } from "react"; import { useParams } from "react-router-dom"; import ThemeContext from "../../../contexts/ThemeContext"; import authService from "../../../services/authService"; import bgPropertyService from "../../../services/bgPropertyService"; import { parseTime } from "../../../utils/helpers"; import { themeStyleSelector } from "../../../utils/themeStyleSelector"; import styles from "./BgProperty.module.css"; const BgProperty = () => { const userClaims = authService.getLocalStorageUserClaims(); var token = userClaims.token; let { theme } = useContext(ThemeContext); let { bgPropertyId, searchSetId } = useParams(); const [bgPropertyModel, setBgPropertyModel] = useState({}); const [isLoading, setIsLoading] = useState(true); let bgProperty = bgPropertyModel?.bgProperty; useEffect(() => { bgPropertyService .fetchOne(token, bgPropertyId, searchSetId) .then((data) => { setBgPropertyModel(data); setIsLoading(false); }); }, [token, bgPropertyId, searchSetId, bgProperty?.isTracked]); async function trackBgProperty(token, bgPropertyId) { await bgPropertyService.trackOne(token, bgPropertyId); setBgPropertyModel({ ...bgPropertyModel, bgProperty: { ...bgProperty, isTracked: !bgProperty.isTracked }, }); } if (isLoading) { return "Loading..."; } return ( <section className={themeStyleSelector( theme, styles, styles.lightThemeBgPropertySectionWrapper )}> {bgPropertyModel && ( <article className={styles.bgPropertyWrapper} > <section className={ bgProperty.isTracked ? styles.bgPropertyDetailsInfoTracked : styles.bgPropertyDetailsInfo } onClick={() => trackBgProperty(token, bgPropertyId)} > {bgProperty.isTracked && ( <span className={styles.trackedSign}> TRACKED <span className={styles.trackedSignTooltip}> click to un-track </span> </span> )} {!bgProperty.isTracked && ( <span className={styles.notTrackedSign}> NOT-TRACKED <span className={styles.trackedSignTooltip}> click to track </span> </span> )} </section> <section className={styles.bgPropertyDetailsWrapper}> <section className={styles.bgPropertyDetails}> <span className={styles.bgPropertyDetailsLabel}>URL:</span> <span className={styles.bgPropertyDetailsValue}> {bgProperty.url && ( <a href={`${bgProperty.url}`} target="_blank" rel="noopener noreferrer" > {bgProperty.url} </a> )} {!bgProperty.url && "n/a"} </span> </section> <section className={styles.bgPropertyDetails}> <span className={styles.bgPropertyDetailsLabel}> Създадена на: </span> <span className={styles.bgPropertyDetailsValue}> {parseTime(bgProperty.createdOn) || "n/a"} </span> </section> <section className={styles.buildingInfo}> <section className={styles.bgPropertyDetails}> <span className={styles.bgPropertyDetailsLabel}> Вид на имота: </span> <span className={styles.bgPropertyDetailsValue}> {bgProperty.propertyType || "n/a"} </span> </section> <section className={styles.bgPropertyDetails}> <span className={styles.bgPropertyDetailsLabel}> Тип строителство: </span> <span className={styles.bgPropertyDetailsValue}> {bgProperty.buildingType || "n/a"} </span> </section> <section className={styles.bgPropertyDetails}> <span className={styles.bgPropertyDetailsLabel}> Година на строителство: </span> <span className={styles.bgPropertyDetailsValue}> {bgProperty.buildingYear || "n/a"} </span> </section> </section> <section className={styles.bgPropertyDetails}> <span className={styles.bgPropertyDetailsLabel}> Местоположение: </span> <span className={styles.bgPropertyDetailsValue}> {bgProperty.location || "n/a"} </span> </section> <section className={styles.placementInfo}> <section className={styles.bgPropertyDetails}> <span className={styles.bgPropertyDetailsLabel}>Площ:</span> <span className={styles.bgPropertyDetailsValue}> {bgProperty.area || "n/a"} {!!bgProperty.area && "м2"} </span> </section> <section className={styles.bgPropertyDetails}> <span className={styles.bgPropertyDetailsLabel}>Етаж:</span> <span className={styles.bgPropertyDetailsValue}> {bgProperty.floor || "n/a"} </span> </section> <section className={styles.bgPropertyDetails}> <span className={styles.bgPropertyDetailsLabel}> Общ брой етажи в сградата: </span> <span className={styles.bgPropertyDetailsValue}> {bgProperty.totalBuildingFloors || "n/a"} </span> </section> </section> <section className={styles.priceInfo}> <section className={styles.bgPropertyDetails}> <span className={styles.bgPropertyDetailsLabel}>Цена:</span> <span className={styles.bgPropertyDetailsValue}> {bgProperty.priceInEUR || "n/a"} {!!bgProperty.priceInEUR && " EUR"} </span> </section> <section className={styles.bgPropertyDetails}> <span className={styles.bgPropertyDetailsLabel}> Цена на кв.м. </span> <span className={styles.bgPropertyDetailsValue}> {bgProperty.pricePerSquareMeterInEUR || "n/a"} {!!bgProperty.pricePerSquareMeterInEUR && " EUR"} </span> </section> </section> <section className={styles.bgPropertyDetails}> <span className={styles.bgPropertyDetailsValue}> <span className={styles.bgPropertyDetailsLabel}>Описание:</span> {bgProperty.description || "n/a"} </span> </section> </section> </article> )} </section> ); }; export default BgProperty;
Kajabi/sage-lib
docs/lib/sage_rails/app/sage_components/sage_modal.rb
<filename>docs/lib/sage_rails/app/sage_components/sage_modal.rb class SageModal < SageComponent set_attribute_schema({ active: [:optional, TrueClass], disable_close: [:optional, TrueClass], id: [:optional, String], large: [:optional, TrueClass], remove_content_on_close: [:optional, TrueClass], disable_background_blur: [:optional, TrueClass], animate: [:optional, String, TrueClass, { direction: [:optional, String, Set.new(["bottom", "top", "left", "right"])] }], remote_url: [:optional, String] }) end
mingca/deep_unrest
lib/deep_unrest/paginators/basic.rb
module DeepUnrest module Paginators module Basic def self.get_page(item, results) page = [item[:query][:page] || 1].max page_size = item[:query][:pageSize] || DeepUnrest.page_size results.limit(page_size).offset(page - 1) end end end end