text
stringlengths
1
1.05M
<filename>snail/src/main/java/com/acgist/snail/net/torrent/dht/response/PingResponse.java package com.acgist.snail.net.torrent.dht.response; import com.acgist.snail.net.torrent.dht.DhtRequest; import com.acgist.snail.net.torrent.dht.DhtResponse; /** * <p>Ping</p> * * @author acgist */ public final class PingResponse extends DhtResponse { /** * @param t 节点ID */ private PingResponse(byte[] t) { super(t); } /** * @param response 响应 */ private PingResponse(DhtResponse response) { super(response.getT(), response.getY(), response.getR(), response.getE()); } /** * <p>创建响应</p> * * @param request 请求 * * @return 响应 */ public static final PingResponse newInstance(DhtRequest request) { return new PingResponse(request.getT()); } /** * <p>创建响应</p> * * @param response 响应 * * @return 响应 */ public static final PingResponse newInstance(DhtResponse response) { return new PingResponse(response); } }
import os from hypothesis import settings settings.register_profile("ci", deadline=None) settings.register_profile("dev", deadline=None, max_examples=10) settings.load_profile( os.getenv("HYPOTHESIS_PROFILE", "ci" if os.getenv("CI") else "default") )
# # Copyright 2019 Xilinx 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. # CXX=${CXX:-g++} $CXX -std=c++11 -O2 -I=/usr/include/drm/ -o seg_and_pose_detect_drm seg_and_pose_detect.cpp -lopencv_core -lopencv_video -lopencv_videoio -lopencv_imgproc -lopencv_imgcodecs -lopencv_highgui -lglog -lvitis_ai_library-multitask -lvitis_ai_library-posedetect -lvitis_ai_library-ssd -ldrm -lpthread -DUSE_DRM=1
package controllers import ( "go-auth-api-sample/database" "go-auth-api-sample/middlewares" "go-auth-api-sample/models" "strconv" "github.com/gofiber/fiber/v2" ) func AllUsers(ctx *fiber.Ctx) error { if err := middlewares.IsUserAuthorized(ctx, "users"); err != nil { return err } page, _ := strconv.Atoi(ctx.Query("page", "1")) return ctx.JSON( models.Paginate(database.DB, &models.User{}, page), ) } func GetUser(ctx *fiber.Ctx) error { if err := middlewares.IsUserAuthorized(ctx, "users"); err != nil { return err } userId, err := ctx.ParamsInt("id") if err != nil { return err } var user models.User err = database.DB.Preload("Role").First(&user, userId).Error if err != nil { return fiber.NewError(fiber.StatusNotFound) } return ctx.JSON(user) } func CreateUser(ctx *fiber.Ctx) error { if err := middlewares.IsUserAuthorized(ctx, "users"); err != nil { return err } var user models.User if err := ctx.BodyParser(&user); err != nil { return err } const DefaultPasswordForNewUsers = "<PASSWORD>" user.SetPassword(DefaultPasswordForNewUsers) result := database.DB.Create(&user) if result.Error != nil { return result.Error } return ctx.JSON(user) } func UpdateUser(ctx *fiber.Ctx) error { if err := middlewares.IsUserAuthorized(ctx, "users"); err != nil { return err } userId, err := ctx.ParamsInt("id") if err != nil { return err } var user models.User if err := ctx.BodyParser(&user); err != nil { return err } user.Id = uint(userId) result := database.DB.Model(&user).Updates(user) if result.Error != nil { return err } return ctx.JSON(user) } func DeleteUser(ctx *fiber.Ctx) error { if err := middlewares.IsUserAuthorized(ctx, "users"); err != nil { return err } userId, err := ctx.ParamsInt("id") if err != nil { return err } result := database.DB.Delete(&models.User{}, userId) if result.Error != nil { return err } if result.RowsAffected == 0 { return fiber.NewError(fiber.StatusNotFound) } ctx.Status(fiber.StatusNoContent) return nil }
<filename>Movie-App/node_modules/helmet-csp/dist/lib/check-options/check-directive/plugin-types.js "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; var config_1 = __importDefault(require("../../config")); var is_function_1 = __importDefault(require("../../is-function")); var notAllowed = ['self', "'self'"].concat(config_1.default.unsafes); module.exports = function pluginTypesCheck(key, value) { if (!Array.isArray(value)) { throw new Error("\"" + value + "\" is not a valid value for " + key + ". Use an array of strings."); } if (value.length === 0) { throw new Error(key + " must have at least one value. To block everything, set " + key + " to [\"'none'\"]."); } value.forEach(function (pluginType) { if (!pluginType) { throw new Error("\"" + pluginType + "\" is not a valid plugin type. Only non-empty strings are allowed."); } if (is_function_1.default(pluginType)) { return; } pluginType = pluginType.valueOf(); if (typeof pluginType !== 'string' || pluginType.length === 0) { throw new Error("\"" + pluginType + "\" is not a valid plugin type. Only non-empty strings are allowed."); } if (notAllowed.indexOf(pluginType) !== -1) { throw new Error("\"" + pluginType + "\" does not make sense in " + key + ". Remove it."); } if (config_1.default.mustQuote.indexOf(pluginType) !== -1) { throw new Error("\"" + pluginType + "\" must be quoted in " + key + ". Change it to \"'" + pluginType + "'\" in your source list. Force this by enabling loose mode."); } }); };
<gh_stars>1-10 #include "stdafx.h" #include "xrLC_GlobalData.h" #include "xrface.h" typedef poolSS<Vertex,8*1024> poolVertices; typedef poolSS<Face,8*1024> poolFaces; static poolVertices _VertexPool; static poolFaces _FacePool; Face* xrLC_GlobalData ::create_face () { return _FacePool.create(); } void xrLC_GlobalData ::destroy_face (Face* &f) { _FacePool.destroy( f ); } Vertex* xrLC_GlobalData ::create_vertex () { return _VertexPool.create(); } void xrLC_GlobalData ::destroy_vertex (Vertex* &f) { _VertexPool.destroy( f ); } void xrLC_GlobalData ::gl_mesh_clear () { _g_vertices.clear(); _g_faces.clear(); _VertexPool.clear(); _FacePool.clear(); }
package fwcd.fructose.ml.neural; public class NNParameters { private final double learningRate; public NNParameters( double learningRate ) { this.learningRate = learningRate; } public double getLearningRate() { return learningRate; } }
<gh_stars>0 import isObject from 'lodash/isObject.js'; import isPlainObject from 'lodash/isPlainObject.js'; import isString from 'lodash/isString.js'; import isArray from 'lodash/isArray.js'; import Logger from '../Logger'; /** * This class provides some static methods which might be helpful when working * with objects. * * @class ObjectUtil */ class ObjectUtil { /** * Returns the dot delimited path of a given object by the given * key-value pair. Example: * * ``` * const obj = { * level: 'first', * nested: { * level: 'second' * } * }; * const key = 'level'; * const value = 'second'; * * ObjectUtil.getPathByKeyValue(obj, key, value); // 'nested.level' * ``` * * Note: It will return the first available match! * * @param {Object} obj The object to obtain the path from. * @param {String} key The key to look for. * @param {String|Number|Boolean} value The value to look for. * @param {String} [currentPath=''] The currentPath (if called in a recursion) * or the custom root path (default is to ''). */ static getPathByKeyValue(obj, key, value, currentPath = '') { currentPath = currentPath ? `${currentPath}.` : currentPath; for (let k in obj) { if (k === key && obj[k] === value) { return `${currentPath}${k}`; } else if (isPlainObject(obj[k])) { const path = ObjectUtil.getPathByKeyValue(obj[k], key, value, `${currentPath}${k}`); if (path) { return path; } else { continue; } } } } /** * Method may be used to return a value of a given input object by a * provided query key. The query key can be used in two ways: * * Single-value: Find the first matching key in the provided object * (Use with caution as the object/array order may not be as * expected and/or deterministic!). * * Backslash ("/") separated value: Find the last (!) matching key * in the provided object. * * @param {String} queryKey The key to be searched. * @param {Object} queryObject The object to be searched on * * @return {*} The target value or `undefined` if the given couldn't be * found, or an object if a path was passed, from which we only could * find a part, but not the most specific one. * TODO Harmonize return values */ static getValue(queryKey, queryObject) { var queryMatch; if (!isString(queryKey)) { Logger.error('Missing input parameter queryKey <String>'); return undefined; } if (!isObject(queryObject)) { Logger.error('Missing input parameter queryObject <Object>'); return undefined; } // if the queryKey contains backslashes we understand this as the // path in the object-hierarchy and will return the last matching // value if (queryKey.split('/').length > 1) { queryKey.split('/').forEach(function(key) { if (queryObject[key]) { queryObject = queryObject[key]; } else { // if the last entry wasn't found return the last match return queryObject; } }); return queryObject; } // iterate over the input object and return the first matching // value for (var key in queryObject) { // get the current value var value = queryObject[key]; // if the given key is the queryKey, let's return the // corresponding value if (key === queryKey) { return value; } // TODO MJ: I do not like this too much, see the appropriate test. // I fear we can only reach this if the original key was not a path, // right? // // if the value is an array and the array contains an object as // well, let's call ourself recursively for this object if (isArray(value)) { for (var i = 0; i < value.length; i++) { var val = value[i]; if (isObject(val)) { queryMatch = this.getValue(queryKey, val); if (queryMatch) { return queryMatch; } } } } // if the value is an object, let's call ourself recursively if (isObject(value)) { queryMatch = this.getValue(queryKey, value); if (queryMatch) { return queryMatch; } } } // if we couldn't find any match, return undefined return undefined; } } export default ObjectUtil;
# Sum of vector sum_vec <- sum(vec) # Print the result print(sum_vec)
package cyclops.pure.arrow; import cyclops.function.higherkinded.Higher; import cyclops.function.enhanced.Function1; import cyclops.pure.typeclasses.functor.Functor; import cyclops.pure.typeclasses.monad.Monad; import java.util.function.Function; public interface FunctionsHK { static <W1, W2, T, R> Function1<Higher<W1, T>, Higher<W2, R>> liftNT(Function<? super T, ? extends R> fn, Function<? super Higher<W1, T>, ? extends Higher<W2, T>> hktTransform, Functor<W2> functor) { return (T1) -> functor.map(fn, hktTransform.apply(T1)); } static <T, CRE> Function1<? super T, ? extends Higher<CRE, T>> arrow(Monad<CRE> monad) { return t -> monad.unit(t); } }
<reponame>raframmed/raframmed_iaw package es.cj.ejercicios.datos; import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class Ejercicio3_beta { private static Scanner sc = new Scanner(System.in); private static int contPares = 0, contImpares = 0; private static int [] numeros; private static int [] pares; private static int [] impares; public static void main(String[] args) { int tamano; do { System.out.println("Introduzca la cantidad de numeros que desea que se muestren"); tamano = sc.nextInt(); }while(tamano <= 0); numeros = new int [tamano]; pares = new int [tamano]; impares = new int [tamano]; inicializarTablaNumeros(); dividirParesImpares(); mostrarResultado(); } private static void mostrarResultado() { String cadPares = "", cadImpares = ""; for (int i = 0; i < numeros.length; i++) { if(i < contPares) { } } for (int i = 0; i < contPares; i++) { System.out.print(pares[i] + " "); } for (int i = 0; i < contImpares; i++) { System.out.print(impares[i] + " "); } } private static void dividirParesImpares() { for (int i = 0; i < numeros.length; i++) { if(numeros[i] % 2 == 0) { pares[contPares] = numeros[i]; contPares++; } else { impares[contImpares] = numeros[i]; contImpares++; } } } private static void inicializarTablaNumeros() { for (int i = 0; i < numeros.length; i++) { numeros[i] = new Random().nextInt(50)+1; } } }
<gh_stars>10-100 import { SceneNavigator, SceneParams } from './SceneNavigator'; export abstract class Scene<T extends SceneParams = {}> { protected navigator: SceneNavigator; protected params: T; constructor(navigator: SceneNavigator, params: T) { this.navigator = navigator; this.params = params; } }
#!/usr/bin/env bash # shellcheck disable=SC2154 # these top lines are moved during build # check process(es) proccheck() { # check for RELRO support if ${readelf} -l "${1}/exe" 2> /dev/null | grep -q 'Program Headers'; then if ${readelf} -l "${1}/exe" 2> /dev/null | grep -q 'GNU_RELRO'; then if ${readelf} -d "${1}/exe" 2> /dev/null | grep -q 'BIND_NOW'; then echo_message '\033[32mFull RELRO \033[m ' 'Full RELRO,' ' relro="full"' '"relro":"full",' else echo_message '\033[33mPartial RELRO\033[m ' 'Partial RELRO,' ' relro="partial"' '"relro":"partial",' fi else echo_message '\033[31mNo RELRO \033[m ' 'No RELRO,' ' relro="no"' '"relro":"no",' fi else echo -n -e '\033[31mPermission denied (please run as root)\033[m\n' exit 1 fi # check for stack canary support if ${readelf} -s "${1}/exe" 2> /dev/null | grep -q 'Symbol table'; then if ${readelf} -s "${1}/exe" 2> /dev/null | grep -Eq '__stack_chk_fail|__stack_chk_guard|__intel_security_cookie'; then echo_message '\033[32mCanary found \033[m ' 'Canary found,' ' canary="yes"' '"canary":"yes",' else echo_message '\033[31mNo canary found \033[m ' 'No Canary found,' ' canary="no"' '"canary":"no",' fi else if [[ "${1}" == "1" ]]; then echo_message '\033[33mPermission denied \033[m ' 'Permission denied,' ' canary="Permission denied"' '"canary":"Permission denied",' else echo_message '\033[33mNo symbol table found \033[m ' 'No symbol table found,' ' canary="No symbol table found"' '"canary":"No symbol table found",' fi fi if ${extended_checks}; then # check if compiled with Clang CFI $debug && echo -e "\n***function proccheck->clangcfi" #if $readelf -s "$1" 2>/dev/null | grep -Eq '\.cfi'; then read -r -a cfifunc <<< "$($readelf -s "$1/exe" 2> /dev/null | grep .cfi | awk '{ print $8 }')" func=${cfifunc/.cfi/} # TODO: fix this check properly, need more clang CFI files to be able to test properly # shellcheck disable=SC2128 if [ -n "$cfifunc" ] && $readelf -s "$1/exe" 2> /dev/null | grep -q "$func$"; then echo_message '\033[32mClang CFI found \033[m ' 'with CFI,' ' clangcfi="yes"' '"clangcfi":"yes",' else echo_message '\033[31mNo Clang CFI found\033[m ' 'without CFI,' ' clangcfi="no"' '"clangcfi":"no",' fi # check if compiled with Clang SafeStack $debug && echo -e "\n***function proccheck->safestack" if $readelf -s "$1/exe" 2> /dev/null | grep -Eq '__safestack_init'; then echo_message '\033[32mSafeStack found \033[m ' 'with SafeStack,' ' safestack="yes"' '"safestack":"yes",' else echo_message '\033[31mNo SafeStack found\033[m ' 'without SafeStack,' ' safestack="no"' '"safestack":"no",' fi fi # check for Seccomp mode seccomp=$(grep 'Seccomp:' "${1}/status" 2> /dev/null | cut -b10) if [[ "${seccomp}" == "1" ]]; then echo_message '\033[32mSeccomp strict\033[m ' 'Seccomp strict,' ' seccomp="strict"' '"seccomp":"strict",' elif [[ "${seccomp}" == "2" ]]; then echo_message '\033[32mSeccomp-bpf \033[m ' 'Seccomp-bpf,' ' seccomp="bpf"' '"seccomp":"bpf",' else echo_message '\033[31mNo Seccomp \033[m ' 'No Seccomp,' ' seccomp="no"' '"seccomp":"no",' fi # first check for PaX support if grep -q 'PaX:' "${1}/status" 2> /dev/null; then pageexec=$(grep 'PaX:' "${1}/status" 2> /dev/null | cut -b6) segmexec=$(grep 'PaX:' "${1}/status" 2> /dev/null | cut -b10) mprotect=$(grep 'PaX:' "${1}/status" 2> /dev/null | cut -b8) randmmap=$(grep 'PaX:' "${1}/status" 2> /dev/null | cut -b9) if [[ "${pageexec}" = "P" || "${segmexec}" = "S" ]] && [[ "${mprotect}" = "M" && "${randmmap}" = "R" ]]; then echo_message '\033[32mPaX enabled\033[m ' 'Pax enabled,' ' pax="yes"' '"pax":"yes",' elif [[ "${pageexec}" = "p" && "${segmexec}" = "s" && "${randmmap}" = "R" ]]; then echo_message '\033[33mPaX ASLR only\033[m ' 'Pax ASLR only,' ' pax="aslr_only"' '"pax":"aslr_only",' elif [[ "${pageexec}" = "P" || "${segmexec}" = "S" ]] && [[ "${mprotect}" = "m" && "${randmmap}" = "R" ]]; then echo_message '\033[33mPaX mprot off \033[m' 'Pax mprot off,' ' pax="mprot_off"' '"pax":"mprot_off",' elif [[ "${pageexec}" = "P" || "${segmexec}" = "S" ]] && [[ "${mprotect}" = "M" && "${randmmap}" = "r" ]]; then echo_message '\033[33mPaX ASLR off\033[m ' 'Pax ASLR off,' ' pax="aslr_off"' '"pax":"aslr_off",' elif [[ "${pageexec}" = "P" || "${segmexec}" = "S" ]] && [[ "${mprotect}" = "m" && "${randmmap}" = "r" ]]; then echo_message '\033[33mPaX NX only\033[m ' 'Pax NX only,' ' pax="nx_only"' '"pax":"nx_only",' else echo_message '\033[31mPaX disabled\033[m ' 'Pax disabled,' ' pax="no"' '"pax":"no",' fi # fallback check for NX support elif ${readelf} -l "${1}/exe" 2> /dev/null | grep 'GNU_STACK' | grep -q 'RWE'; then echo_message '\033[31mNX disabled\033[m ' 'NX disabled,' ' nx="no"' '"nx":"no",' else echo_message '\033[32mNX enabled \033[m ' 'NX enabled,' ' pax="yes"' '"nx":"yes",' fi # check for PIE support if ${readelf} -h "${1}/exe" 2> /dev/null | grep -q 'Type:[[:space:]]*EXEC'; then echo_message '\033[31mNo PIE \033[m ' 'No PIE,' ' pie="no"' '"pie":"no",' elif ${readelf} -h "${1}/exe" 2> /dev/null | grep -q 'Type:[[:space:]]*DYN'; then if ${readelf} -d "${1}/exe" 2> /dev/null | grep -q 'DEBUG'; then echo_message '\033[32mPIE enabled \033[m ' 'PIE enabled,' ' pie="yes"' '"pie":"yes",' else echo_message '\033[33mDynamic Shared Object\033[m ' 'Dynamic Shared Object,' ' pie="dso"' '"pie":"dso",' fi else echo_message '\033[33mNot an ELF file \033[m ' 'Not an ELF file,' ' pie="not_elf"' '"pie":"not_elf",' fi if ${extended_checks}; then # check for selfrando support if ${readelf} -S "${1}/exe" 2> /dev/null | grep -c txtrp | grep -q '1'; then echo_message '\033[32mSelfrando enabled \033[m ' else echo_message '\033[31mNo Selfrando \033[m ' fi fi #check for forifty source support Proc_FS_functions="$(${readelf} -s "${1}/exe" 2> /dev/null | awk '{ print $8 }' | sed 's/_*//' | sed -e 's/@.*//')" if grep -q '_chk$' <<< "$Proc_FS_functions"; then echo_message '\033[32mYes\033[m' 'Yes' " fortify_source='yes'>" '"fortify_source":"yes" }' else echo_message "\033[31mNo\033[m" "No" " fortify_source='no'>" '"fortify_source":"no" }' fi }
<filename>webpack-configs/client/config.js /* eslint-disable import/no-extraneous-dependencies */ import UglifyJsPlugin from 'uglifyjs-webpack-plugin'; import VueLoaderPlugin from 'vue-loader/lib/plugin'; import MiniCssPlugin from 'mini-css-extract-plugin'; import autoprefixer from 'autoprefixer'; import VueSSRPlugin from 'vue-server-renderer/client-plugin'; import path from 'path'; import getGlobals from '../plugins/globals'; import getEnvs from '../utils/dotenv'; getEnvs(); const context = { DIR: path.resolve('./'), }; export default function configClientWebpack(props) { const { production = true } = props; const { DIR } = context; return { target: 'web', mode: production ? 'production' : 'development', devtool: production ? 'cheap-source-map' : 'source-map', context: DIR, entry: { client: [ '@babel/polyfill', path.join(DIR, 'client'), ], }, output: { filename: production ? '[name].[hash].js' : 'client.js', chunkFilename: production ? '[name].[hash].js' : '[name].js', path: path.join(DIR, 'build'), publicPath: process.env.PUBLIC_PATH, }, resolve: { alias: { vue$: production ? 'vue/dist/vue.min.js' : 'vue/dist/vue.js', api$: path.join(DIR, 'fetch', 'browser.js'), }, mainFiles: ['index.js'], extensions: ['.js', '.jsx', '.styl', '.vue'], modules: [DIR, 'node_modules'], }, module: { rules: [ { test: /\.vue$/, use: { loader: 'vue-loader', }, }, { test: /\.(png|jpe?g|woff|ttf)$/, use: { loader: 'file-loader', options: { name: '[name]@[hash:base64:5].[ext]', }, }, }, { test: /\.styl|(us)$/, use: [ production ? MiniCssPlugin.loader : 'vue-style-loader', { loader: 'css-loader', options: { modules: { mode: 'local', localIdentName: '[name]-[local]-[hash:base64:5]', }, }, }, { loader: 'postcss-loader', options: { sourceMap: false, plugins() { return [autoprefixer]; }, }, }, { loader: 'stylus-loader', options: { import: [path.join(DIR, 'client', 'styles', 'import.styl')], }, }, ], }, { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], plugins: [ '@babel/plugin-syntax-dynamic-import', ], }, }, }, ], }, plugins: [ getGlobals(), new VueLoaderPlugin(), production && new MiniCssPlugin({ filename: '[name]@[hash:12].css', }), new VueSSRPlugin(), ].filter(Boolean), optimization: production ? { minimizer: [new UglifyJsPlugin()] } : {}, }; };
<reponame>nkrios/lemongrenade package lemongrenade.core.util; /* This class assists with creating http(s) get/post requests. */ import lemongrenade.core.templates.LGAdapter; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.client.CookieStore; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.*; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.ssl.AllowAllHostnameVerifier; import org.apache.http.cookie.*; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.LaxRedirectStrategy; import org.apache.http.impl.cookie.DefaultCookieSpec; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONObject; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.KeyStore; import java.security.Principal; import java.security.cert.X509Certificate; import java.util.Enumeration; import java.util.Iterator; public class Requests { public static final int DEFAULT_TIMEOUT = 30000; public static Registry<CookieSpecProvider> r; public static CookieStore cookieStore; static { try { setCerts(); r = RegistryBuilder.<CookieSpecProvider>create() .register("easy", new EasySpecProvider()) .build(); cookieStore = new BasicCookieStore(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } // Put Requests public static RequestResult put(String url) throws Exception { return Requests.final_request(url, "", new JSONObject(), "PUT", DEFAULT_TIMEOUT, true); } public static RequestResult put(String url, JSONObject params) throws Exception { return Requests.final_request(url, params.toString(), new JSONObject(), "PUT", DEFAULT_TIMEOUT, true); } public static RequestResult put(String url, JSONObject params, JSONObject requestParameters) throws Exception { return Requests.final_request(url, params.toString(), requestParameters, "PUT", DEFAULT_TIMEOUT, true); } //Get Requests public static RequestResult get(String url) throws Exception { return Requests.final_request(url, "", new JSONObject(), "GET", DEFAULT_TIMEOUT, true); } public static RequestResult get(String url, JSONObject params) throws Exception { return Requests.final_request(url, urlEncode(params), new JSONObject(), "GET", DEFAULT_TIMEOUT, true); } public static RequestResult get(String url, JSONObject params, JSONObject requestParameters) throws Exception { return Requests.final_request(url, urlEncode(params), requestParameters, "GET", DEFAULT_TIMEOUT, true); } public static RequestResult get(String url, JSONObject params, JSONObject requestParameters, int timeout) throws Exception { return Requests.final_request(url, urlEncode(params), requestParameters, "GET", timeout, true); } //Post Requests public static RequestResult post(String url, JSONObject params) throws Exception { return Requests.final_request(url, params.toString(), new JSONObject(), "POST", DEFAULT_TIMEOUT, true); } public static RequestResult post(String url, JSONObject params, JSONObject requestParameters) throws Exception { return Requests.final_request(url, params.toString(), requestParameters, "POST", DEFAULT_TIMEOUT, true); } //JSONObject type data public static RequestResult post(String url, JSONObject params, JSONObject requestParameters, int timeout) throws Exception { return Requests.final_request(url, params.toString(), requestParameters, "POST", timeout, true); } public static RequestResult post(String url, JSONObject params, JSONObject requestParameters, Boolean urlEncode) throws Exception { if(urlEncode) return Requests.final_request(url, urlEncode(params), requestParameters, "POST", DEFAULT_TIMEOUT, true); else return Requests.final_request(url, params.toString(), requestParameters, "POST", DEFAULT_TIMEOUT, true); } public static RequestResult post(String url, JSONObject params, JSONObject requestParameters, Boolean urlEncode, int timeout) throws Exception { if(urlEncode) return Requests.final_request(url, urlEncode(params), requestParameters, "POST", timeout, true); else return Requests.final_request(url, params.toString(), requestParameters, "POST", timeout, true); } //String type data public static RequestResult post(String url, String data, JSONObject requestParameters) throws Exception { return Requests.final_request(url, data, requestParameters, "POST", DEFAULT_TIMEOUT, true); } public static RequestResult post(String url, String data, JSONObject requestParameters, Boolean urlEncode) throws Exception { if(urlEncode) return Requests.final_request(url, urlEncode(data), requestParameters, "POST", DEFAULT_TIMEOUT, true); else return Requests.final_request(url, data, requestParameters, "POST", DEFAULT_TIMEOUT, true); } public static RequestResult post(String url, String data, JSONObject requestParameters, Boolean urlEncode, int timeout) throws Exception { if(urlEncode) return Requests.final_request(url, urlEncode(data), requestParameters, "POST", timeout, true); else return Requests.final_request(url, data, requestParameters, "POST", timeout, true); } //JSONArray type data public static RequestResult post(String url, JSONArray data, JSONObject requestParameters) throws Exception { return Requests.final_request(url, data.toString(), requestParameters, "POST", DEFAULT_TIMEOUT, true); } public static RequestResult post(String url, JSONArray data, JSONObject requestParameters, Boolean urlEncode) throws Exception { if(urlEncode) return Requests.final_request(url, urlEncode(data.toString()), requestParameters, "POST", DEFAULT_TIMEOUT, true); else return Requests.final_request(url, data.toString(), requestParameters, "POST", DEFAULT_TIMEOUT, true); } public static RequestResult post(String url, JSONArray data, JSONObject requestParameters, Boolean urlEncode, int timeout) throws Exception { if(urlEncode) return Requests.final_request(url, urlEncode(data.toString()), requestParameters, "POST", timeout, true); else return Requests.final_request(url, data.toString(), requestParameters, "POST", timeout, true); } //sets the keystore and truststore to values set in the default config - run this when defaults aren't good public static void setCerts () { try { System.setProperty("javax.net.ssl.keyStore", LGAdapter.DEFAULT_CONFIG.get("cert_keystore").toString()); System.setProperty("javax.net.ssl.keyStoreType", LGAdapter.DEFAULT_CONFIG.get("cert_keystore_type").toString()); System.setProperty("javax.net.ssl.keyStorePassword", LGAdapter.DEFAULT_CONFIG.get("cert_keystore_pass").toString()); System.setProperty("javax.net.ssl.trustStore", LGAdapter.DEFAULT_CONFIG.get("cert_truststore").toString()); System.setProperty("javax.net.ssl.trustStoreType", LGAdapter.DEFAULT_CONFIG.get("cert_truststore_type").toString()); System.setProperty("javax.net.ssl.trustStorePassword", LGAdapter.DEFAULT_CONFIG.get("cert_truststore_pass").toString()); System.setProperty("jsse.enableSNIExtension", "false"); //Fixes unrecognized_name error on Adapters } catch(Exception e) { System.out.println("Error setting system properties for certificates. Ensure cert.json contains values for " + "'cert_keystore', 'cert_keystore_type', 'cert_keystore_pass', 'cert_truststore', 'cert_truststore_type', and 'cert_truststore_pass'."); throw e; } } public static void add_headers(JSONObject headers, HttpGet httpObject) { Iterator<String> keys = headers.keys(); String key; while(keys.hasNext()) { key = keys.next(); httpObject.addHeader(key, headers.getString(key)); } } public static void add_headers(JSONObject headers, HttpPost httpObject) { Iterator<String> keys = headers.keys(); String key; while(keys.hasNext()) { key = keys.next(); httpObject.addHeader(key, headers.getString(key)); } } private static void add_headers(JSONObject headers, HttpPut httpObject) { Iterator<String> keys = headers.keys(); String key; while(keys.hasNext()) { key = keys.next(); httpObject.addHeader(key, headers.getString(key)); } } public static HttpEntity getEntity(String params) throws UnsupportedEncodingException {//takes a string of params and creates an entity from them return new ByteArrayEntity(params.getBytes("UTF-8")); } static class EasyCookieSpec extends DefaultCookieSpec { @Override public void validate(Cookie arg0, CookieOrigin arg1) throws MalformedCookieException { //allow all cookies } } static class EasySpecProvider implements CookieSpecProvider { @Override public CookieSpec create(HttpContext context) { return new EasyCookieSpec(); } } public static RequestResult final_request(String targetURL, String params, JSONObject headers, String method, int timeout, boolean verifySSL) throws Exception { CloseableHttpResponse response = null; CloseableHttpClient httpclient = null; try { // Create the client and issue the request RequestConfig requestConfig = RequestConfig.custom() .setCookieSpec("easy") .setConnectTimeout(timeout) .setConnectionRequestTimeout(timeout) .setSocketTimeout(timeout) .build(); HttpClientBuilder builder = HttpClientBuilder.create() .setRedirectStrategy(new LaxRedirectStrategy()) //allow automatic redirects .useSystemProperties() .setDefaultRequestConfig(requestConfig) .setDefaultCookieStore(cookieStore) .setDefaultCookieSpecRegistry(r) .setDefaultRequestConfig(requestConfig) .disableAutomaticRetries(); if(verifySSL == false) { //Don't verify host names, WARNING, only use this for testing and with caution builder.setSSLHostnameVerifier(new AllowAllHostnameVerifier()); } httpclient = builder.build(); String url; method = method.toUpperCase(); url = targetURL; if(method.equals("GET")) { if(params.length() > 0) url = url + "?" + params; HttpGet httpGet = new HttpGet(url); add_headers(headers, httpGet); response = httpclient.execute(httpGet); } else if (method.equals("POST")) { //POST method HttpPost httpPost = new HttpPost(url); add_headers(headers, httpPost); HttpEntity entity = getEntity(params); httpPost.setEntity(entity); response = httpclient.execute(httpPost); } else if(method.equals("PUT")) { HttpPut httpPut = new HttpPut(url); add_headers(headers, httpPut); HttpEntity entity = getEntity(params); httpPut.setEntity(entity); response = httpclient.execute(httpPut); } else { throw new Exception("Unknown method:"+method); } RequestResult result; Header[] response_headers = response.getAllHeaders(); String response_msg = ""; int status = response.getStatusLine().getStatusCode(); if(status != 204) { HttpEntity entity = response.getEntity(); response_msg = EntityUtils.toString(entity); } result = new RequestResult(status, response_msg, response_headers); // Close your connections when you're finished response.close(); httpclient.close(); return result; } catch (Exception e) { if(response != null) { response.close(); } if(httpclient != null) { httpclient.close(); } e.printStackTrace(); throw e; } } //Converts a JSON key/value object into a url encoded string. public static String urlEncode(JSONObject input) throws Exception { String params = ""; Iterator<String> keys = input.keys(); String key; String value; if(keys.hasNext()) { key = keys.next(); value = input.get(key).toString(); params = key + "=" + URLEncoder.encode(value, "UTF-8"); } while(keys.hasNext()) { key = keys.next(); value = input.get(key).toString(); params += "&" + key + "=" + URLEncoder.encode(value, "UTF-8"); } return params; } public static String urlEncode(String input) throws Exception { return URLEncoder.encode(input, "UTF-8"); } /* Create a keystore from a .p12/.pfx keytool -v -importkeystore -srckeystore my_key.p12 -srcstoretype PKCS12 -destkeystore new_truststore.jks -deststoretype JKS IMPORTANT: The password on the new trust store must match the password for the .p12 key used */ //Change keystore password: keytool -storepasswd -keystore my.keystore //Change key password: keytool -keypasswd -alias <key_name> -keystore my.keystore //example from http://www.java2s.com/Tutorial/Java/0490__Security/GettingtheSubjectandIssuerDistinguishedNamesofanX509Certificate.htm public static JSONObject getDNs(String s_keystore, String pass, String type) { JSONObject DNs = new JSONObject(); try { FileInputStream is = new FileInputStream(s_keystore); DNs = getDNs(is, pass, type); } catch (Exception e) { e.printStackTrace(); } return DNs; } public static JSONObject getDNs() throws FileNotFoundException { String file = LGAdapter.DEFAULT_CONFIG.get("cert_keystore").toString(); String pass = LGAdapter.DEFAULT_CONFIG.get("cert_keystore_pass").toString(); String type = LGAdapter.DEFAULT_CONFIG.get("cert_keystore_type").toString(); InputStream is = new FileInputStream(file); return getDNs(is, pass, type); } public static JSONObject getDNs(InputStream is, String pass, String type) { JSONObject DNs = new JSONObject(); try { KeyStore keystore = KeyStore.getInstance(type); keystore.load(is, pass.toCharArray()); Enumeration e = keystore.aliases(); for(; e.hasMoreElements();) { String alias = (String) e.nextElement(); java.security.cert.Certificate cert = keystore.getCertificate(alias); if(cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; Principal principal = x509cert.getSubjectDN(); DNs.put("user_dn", principal.getName()); principal = x509cert.getIssuerDN(); DNs.put("issuer_dn", principal.getName()); break; } } } catch (Exception e) { e.printStackTrace(); } return DNs; } //Enables full debug output for requests public static void enableFullDebug() { System.out.println("'javax.net.debug' set to 'all'."); System.setProperty("javax.net.debug", "all"); } }
#!/bin/sh provider=$(var VPN_PROVIDER) COUNTRY=$1 TUN=$dev IP=$ifconfig_local log -v "on-up.sh country: $COUNTRY, tun: $TUN, ip: $IP" # # Do we have an IP? # if [ -z "$IP" ] then log -e "No IP. Forcing reconnect..." exit 1; else log -i "Connected. Assigned IP is: $IP." fi # # Remove killswitch (if any) # if [ "$(var VPN_KILLSWITCH)" = "true" ] then log -d "Removing killswitch config." iptables -P OUTPUT ACCEPT iptables -D OUTPUT -p udp -m udp --dport $(var VPN_PORT) -j ACCEPT iptables -D INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT iptables -D OUTPUT -o tun0 -j ACCEPT NS=$(cat /etc/resolv.conf | grep "nameserver" | sed 's/nameserver \(.*\)/\1/g') for s in $NS do iptables -D OUTPUT -d $s -j ACCEPT done fi host=$(/app/openvpn/provider/$provider.sh -e host -c $COUNTRY) log -i "Vpn ($COUNTRY) is up. Connected remote: $host." # # Find all on-openvpn-up.sh files # EVENTS=$(find /app/*/ -type f -name on-openvpn-up.sh) for filepath in $EVENTS do # # Ensure execution rights and execute file # log -v "Executing $filepath $COUNTRY $TUN $IP." chmod +x $filepath $filepath $COUNTRY $TUN $IP # # Check outcome # if [ $? -eq 1 ] then log -d "$filepath $COUNTRY $TUN $IP failed."; exit 1; fi done exit 0;
require('dotenv').config(); import * as express from 'express'; import * as mongoose from 'mongoose'; const app = express(); const { PORT: port = 3000, MONGO_URI: mongoURI } = process.env; mongoose.Promise = global.Promise; mongoose.connect(mongoURI).then(() => { console.log(mongoURI); console.log('connnected to mongodb'); }).catch((e: any) => { console.error(e); }); app.use(express.json()); app.use(express.static('public')); app.use('/api', require('./api')); app.get('/', (req: express.Request, res: express.Response) => { console.log("정상작동"); res.status(200).json({success:"success"}); }); app.listen(port, () => { console.log('listening on port ' + port); });
// // Created by ooooo on 2020/4/21. // #ifndef CPP_064__SOLUTION1_H_ #define CPP_064__SOLUTION1_H_ #include <iostream> using namespace std; class Solution { public: int sumNums(int n) { bool f = n > 1 && (n += sumNums(n - 1)); return n; } }; #endif //CPP_064__SOLUTION1_H_
#!/usr/bin/env sh set -e -v go mod download cat tools.go | grep _ | awk -F'"' '{print $2}' | xargs -t go install
package vectorwing.farmersdelight.common.tag; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.BlockTags; import net.minecraft.tags.ItemTags; import net.minecraft.tags.Tag; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; /** * References to tags under the Forge namespace. * These tags are generic concepts, meant to be shared with other mods for compatibility. */ public class ForgeTags { // Blocks that are efficiently mined with a Knife. public static final Tag.Named<Block> MINEABLE_WITH_KNIFE = forgeBlockTag("mineable/knife"); public static final Tag.Named<Item> BREAD = forgeItemTag("bread"); public static final Tag.Named<Item> BREAD_WHEAT = forgeItemTag("bread/wheat"); public static final Tag.Named<Item> COOKED_BACON = forgeItemTag("cooked_bacon"); public static final Tag.Named<Item> COOKED_BEEF = forgeItemTag("cooked_beef"); public static final Tag.Named<Item> COOKED_CHICKEN = forgeItemTag("cooked_chicken"); public static final Tag.Named<Item> COOKED_PORK = forgeItemTag("cooked_pork"); public static final Tag.Named<Item> COOKED_MUTTON = forgeItemTag("cooked_mutton"); public static final Tag.Named<Item> COOKED_EGGS = forgeItemTag("cooked_eggs"); public static final Tag.Named<Item> COOKED_FISHES = forgeItemTag("cooked_fishes"); public static final Tag.Named<Item> COOKED_FISHES_COD = forgeItemTag("cooked_fishes/cod"); public static final Tag.Named<Item> COOKED_FISHES_SALMON = forgeItemTag("cooked_fishes/salmon"); public static final Tag.Named<Item> CROPS = forgeItemTag("crops"); public static final Tag.Named<Item> CROPS_CABBAGE = forgeItemTag("crops/cabbage"); public static final Tag.Named<Item> CROPS_ONION = forgeItemTag("crops/onion"); public static final Tag.Named<Item> CROPS_RICE = forgeItemTag("crops/rice"); public static final Tag.Named<Item> CROPS_TOMATO = forgeItemTag("crops/tomato"); public static final Tag.Named<Item> EGGS = forgeItemTag("eggs"); public static final Tag.Named<Item> GRAIN = forgeItemTag("grain"); public static final Tag.Named<Item> GRAIN_WHEAT = forgeItemTag("grain/wheat"); public static final Tag.Named<Item> GRAIN_RICE = forgeItemTag("grain/rice"); public static final Tag.Named<Item> MILK = forgeItemTag("milk"); public static final Tag.Named<Item> MILK_BUCKET = forgeItemTag("milk/milk"); public static final Tag.Named<Item> MILK_BOTTLE = forgeItemTag("milk/milk_bottle"); public static final Tag.Named<Item> PASTA = forgeItemTag("pasta"); public static final Tag.Named<Item> PASTA_RAW_PASTA = forgeItemTag("pasta/raw_pasta"); public static final Tag.Named<Item> RAW_BACON = forgeItemTag("raw_bacon"); public static final Tag.Named<Item> RAW_BEEF = forgeItemTag("raw_beef"); public static final Tag.Named<Item> RAW_CHICKEN = forgeItemTag("raw_chicken"); public static final Tag.Named<Item> RAW_PORK = forgeItemTag("raw_pork"); public static final Tag.Named<Item> RAW_MUTTON = forgeItemTag("raw_mutton"); public static final Tag.Named<Item> RAW_FISHES = forgeItemTag("raw_fishes"); public static final Tag.Named<Item> RAW_FISHES_COD = forgeItemTag("raw_fishes/cod"); public static final Tag.Named<Item> RAW_FISHES_SALMON = forgeItemTag("raw_fishes/salmon"); public static final Tag.Named<Item> RAW_FISHES_TROPICAL = forgeItemTag("raw_fishes/tropical_fish"); public static final Tag.Named<Item> SALAD_INGREDIENTS = forgeItemTag("salad_ingredients"); public static final Tag.Named<Item> SALAD_INGREDIENTS_CABBAGE = forgeItemTag("salad_ingredients/cabbage"); public static final Tag.Named<Item> SEEDS = forgeItemTag("seeds"); public static final Tag.Named<Item> SEEDS_CABBAGE = forgeItemTag("seeds/cabbage"); public static final Tag.Named<Item> SEEDS_RICE = forgeItemTag("seeds/rice"); public static final Tag.Named<Item> SEEDS_TOMATO = forgeItemTag("seeds/tomato"); public static final Tag.Named<Item> VEGETABLES = forgeItemTag("vegetables"); public static final Tag.Named<Item> VEGETABLES_BEETROOT = forgeItemTag("vegetables/beetroot"); public static final Tag.Named<Item> VEGETABLES_CARROT = forgeItemTag("vegetables/carrot"); public static final Tag.Named<Item> VEGETABLES_ONION = forgeItemTag("vegetables/onion"); public static final Tag.Named<Item> VEGETABLES_POTATO = forgeItemTag("vegetables/potato"); public static final Tag.Named<Item> VEGETABLES_TOMATO = forgeItemTag("vegetables/tomato"); public static final Tag.Named<Item> TOOLS = forgeItemTag("tools"); public static final Tag.Named<Item> TOOLS_AXES = forgeItemTag("tools/axes"); public static final Tag.Named<Item> TOOLS_KNIVES = forgeItemTag("tools/knives"); public static final Tag.Named<Item> TOOLS_PICKAXES = forgeItemTag("tools/pickaxes"); public static final Tag.Named<Item> TOOLS_SHOVELS = forgeItemTag("tools/shovels"); private static Tag.Named<Block> forgeBlockTag(String path) { return BlockTags.bind(new ResourceLocation("forge", path).toString()); } private static Tag.Named<Item> forgeItemTag(String path) { return ItemTags.bind(new ResourceLocation("forge", path).toString()); } }
<reponame>tagnyngompe/taj-ginilogitpls # encoding: utf-8 #from __future__ import absolute_import, division, print_function import numpy as np from sklearn.cross_decomposition import PLSCanonical, PLSRegression from sklearn.metrics import matthews_corrcoef from sklearn.model_selection import RandomizedSearchCV, GridSearchCV from scipy.stats import randint as sp_randint import random from time import time from ginipls.data.data_utils import load_ytrue_ypred_file from ginipls.models.ginipls import PLS, PLS_VARIANT class PLSCanonical(PLSCanonical): def __init__(self, n_components=2, scale=True, algorithm="nipals", max_iter=500, tol=1e-06, copy=True): super(PLSCanonical, self).__init__(n_components=n_components, scale=scale, algorithm=algorithm, max_iter=max_iter, tol=tol, copy=copy) def fit(self, X, Y): self.__Y_train_mean = np.mean(Y) return super(PLSCanonical, self).fit(X, Y) return self def predict(self, X, copy=True): Ypred = super(PLSCanonical, self).predict(X, copy) #print('Ypred', Ypred) return [1 if y_pred > self.__Y_train_mean else 0 for y_pred in Ypred] class PLSRegression(PLSRegression): def __init__(self, n_components=2, scale=True, max_iter=500, tol=1e-06, copy=True): super(PLSRegression, self).__init__(n_components=n_components, scale=scale, max_iter=max_iter, tol=tol, copy=copy) def fit(self, X, Y): self.__Y_train_mean = np.mean(Y) return super(PLSRegression, self).fit(X, Y) return self def predict(self, X, copy=True): Ypred = super(PLSRegression, self).predict(X, copy) #print('Ypred', Ypred) return [1 if y_pred > self.__Y_train_mean else 0 for y_pred in Ypred] #/***********************************************************************/ #/* Dimension reduction */ #/***********************************************************************/ def lsa_learn_transformation(X_train, n_components=10, n_iter=10): from sklearn.decomposition import TruncatedSVD #training LSA #print('n_components', n_components) #print('X_train', X_train.shape) svd = TruncatedSVD(n_components=n_components, n_iter=n_iter, random_state=42) svd.fit(X_train) #print(svd.explained_variance_ratio_) # transforming train and test sets into the reduced space #X_train_lsa = svd.fit_transform(X_train) #X_test_lsa = svd.fit_transform(X_test) # X_test_lsa peut avoir moins de colonnes que X_train_lsa car les colonnes nulles ne sont pas conservées, ? comment trouver le bon nb de n_components? return svd def print_top_words(model, feature_names, n_top_words): for topic_idx, topic in enumerate(model.components_): message = "Topic #%d: " % topic_idx message += " # ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]]) print(message) print() def latentDA_learn_transformation(X_train, n_components=10, max_iter=100): """ http://scikit-learn.org/stable/auto_examples/applications/plot_topics_extraction_with_nmf_lda.html#sphx-glr-auto-examples-applications-plot-topics-extraction-with-nmf-lda-py """ from sklearn.decomposition import LatentDirichletAllocation lda = LatentDirichletAllocation(n_components=n_components, max_iter=max_iter, learning_method='online', learning_offset=50., random_state=0) t0 = time() print('latentDA_train_transform: learning topics ... ', end='', flush=True) lda.fit(X_train) print("\tdone in %0.3fs." % (time() - t0)) return lda def linearDA_train_transformation(X_train, y_train): return linearDA_train(X_train, y_train) def quadraticDA_train_transformation(X_train, y_train): return quadraticDA_train(X_train, y_train) def our_standard_pls_train_transformation(X_train, y_train): return our_standard_pls_train(X_train, y_train) def our_gini_pls_train_transformation(X_train, y_train): return our_gini_pls_train(X_train, y_train) def our_logit_pls_train_transformation(X_train, y_train): return our_logit_pls_train(X_train, y_train) def our_logit_gini_pls_train_transformation(X_train, y_train): return our_logit_gini_pls_train(X_train, y_train) def sklearn_pls_canonical_train_transformation(X_train, y_train): return sklearn_pls_canonical_train(X_train, y_train) def sklearn_pls_regression_train_transformation(X_train, y_train): return sklearn_pls_regression_train(X_train, y_train) #/***********************************************************************/ #/* Classifier */ #/***********************************************************************/ # Utility function to report best scores for Model Selection # http://chrisstrelioff.ws/sandbox/2015/06/25/decision_trees_in_python_again_cross_validation.html def reportBestMetaparameters(results, n_top=3): for i in range(1, n_top + 1): candidates = np.flatnonzero(results['rank_test_score'] == i) for candidate in candidates: print("Model with rank: {0}".format(i)) print("Mean validation score: {0:.3f} (std: {1:.3f})".format( results['mean_test_score'][candidate], results['std_test_score'][candidate])) print("Parameters: {0}".format(results['params'][candidate])) print("") def report_besthyperpara(results_search_hyperpara, param_min_to_select_name): best_candidates = np.flatnonzero(results_search_hyperpara['rank_test_score'] == 1) best_candidate = 0 if param_min_to_select_name != None: min_ = results_search_hyperpara['params'][0][param_min_to_select_name] for candidate in best_candidates: current_val = results_search_hyperpara['params'][candidate][param_min_to_select_name] if current_val < min_: min_ = current_val best_candidate = candidate best_metaparameters = results_search_hyperpara['params'][best_candidate] print("api.linearDA_train.best_metaparameters", best_metaparameters) return best_metaparameters def run_randomsearch(clf, param_dist, X_train, y_train, k_cv=3, param_min_to_select_name = None, n_iter_search=20): random_search = RandomizedSearchCV(clf, param_distributions=param_dist, n_iter=n_iter_search, cv=k_cv) random_search.fit(X_train, y_train) return report_besthyperpara(random_search.cv_results_, param_min_to_select_name) def run_gridsearch(clf, param_grid, X, y, k_cv=5, param_min_to_select_name = None): """Run a grid search for best Decision Tree parameters. Args ---- X -- features y -- targets (classes) clf -- scikit-learn Decision Tree param_grid -- [dict] parameter settings to test cv -- fold of cross-validation, default 5 Returns ------- top_params -- [dict] from report() """ grid_search = GridSearchCV(clf, param_grid=param_grid, cv=k_cv) start = time() grid_search.fit(X, y) return report_besthyperpara(grid_search.cv_results_, param_min_to_select_name) default_n_components = 2 default_nu = 2 use_VIP=False def our_standard_pls_train(X_train, y_train, n_components=default_n_components, nu=default_nu, centering_reduce=True): return __our_pls_train(X_train, y_train, PLS_VARIANT.STANDARD, n_components, nu, centering_reduce) def our_gini_pls_train(X_train, y_train, n_components=default_n_components, nu=default_nu, centering_reduce=True): return __our_pls_train(X_train, y_train, PLS_VARIANT.GINI, n_components, nu, centering_reduce) def our_logit_pls_train(X_train, y_train, n_components=default_n_components, nu=default_nu, centering_reduce=True): return __our_pls_train(X_train, y_train, PLS_VARIANT.LOGIT, n_components, nu, centering_reduce) def our_logit_gini_pls_train(X_train, y_train, n_components=default_n_components, nu=default_nu, centering_reduce=True): return __our_pls_train(X_train, y_train, PLS_VARIANT.LOGIT_GINI, n_components, nu, centering_reduce) def __our_pls_train(X_train, y_train, pls_type, n_components=default_n_components, nu=default_nu, centering_reduce=True, use_VIP=use_VIP): #import ginipls clf = PLS(pls_type, n_components, nu, centering_reduce,use_VIP=use_VIP) clf.fit(X_train, y_train) return clf def sklearn_pls_canonical_train(X_train, y_train, n_components=10): if n_components > np.asarray(X_train).shape[1]: n_components = np.asarray(X_train).shape[1]-1 clf = PLSCanonical(n_components=n_components) clf.fit(X_train, y_train) return clf def sklearn_pls_regression_train(X_train, y_train, n_components=10): if n_components > np.asarray(X_train).shape[1]: n_components = np.asarray(X_train).shape[1]-1 clf = PLSRegression(n_components=n_components) clf.fit(X_train, y_train) return clf def linearDA_train(X_train, y_train): """ http://www.science.smith.edu/~jcrouser/SDS293/labs/lab5-py.html """ from sklearn.discriminant_analysis import LinearDiscriminantAnalysis clf = LinearDiscriminantAnalysis() # MODEL SELECTION: specify meta-parameters and distributions to sample from n_features = np.asmatrix(X_train).shape[1] n_classes = len(set(y_train)) #print("api.linearDA_train.num_attributes", num_attributes) # param_dist = {"solver": ["svd", "lsqr"],#, "eigen"], # #"shrinkage": [None, "auto"], # "n_components": [min(10, n_features, n_classes-1)] # } # ## run randomized search # n_iter_search = 20 # random_search = RandomizedSearchCV(clf, param_distributions=param_dist, # n_iter=n_iter_search, cv=3) # random_search.fit(X_train, y_train) # #reportBestMetaparameters(random_search.cv_results_, 1) # results = random_search.cv_results_ # best_candidates = np.flatnonzero(results['rank_test_score'] == 1) # best_candidate = 0 # min_n_components = results['params'][0]["n_components"] # for candidate in best_candidates: # n_components = results['params'][candidate]["n_components"] # if n_components < min_n_components: # min_n_components = n_components # best_candidate = candidate # best_metaparameters = results['params'][best_candidate] # print("api.linearDA_train.best_metaparameters", best_metaparameters) # # init the model with the best metaparameters # clf = LinearDiscriminantAnalysis( # solver=best_metaparameters["solver"], # #shrinkage=best_metaparameters["shrinkage"], # n_components=best_metaparameters["n_components"]) clf = LinearDiscriminantAnalysis() clf.fit(X_train, y_train) return clf def quadraticDA_train(X_train, y_train): """ http://www.science.smith.edu/~jcrouser/SDS293/labs/lab5-py.html """ from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis # MODEL SELECTION: specify meta-parameters and distributions to sample from # clf = QuadraticDiscriminantAnalysis() # param_dist = {"reg_param": [random.uniform(0,1) for i in range(1000000)]} # best_metaparameters = run_randomsearch(clf, param_dist, X_train, y_train, k_cv=4) # print("api.quadraticDA_train.best_metaparameters", best_metaparameters) # init the model with the best metaparameters #clf = QuadraticDiscriminantAnalysis(reg_param=best_metaparameters["reg_param"]) clf = QuadraticDiscriminantAnalysis() clf.fit(X_train, y_train) return clf def naivebayes_train(X_train, y_train): from sklearn.naive_bayes import BernoulliNB clf = BernoulliNB() clf.fit(X_train, y_train) # y doit être un simple np.array pas une matrice return clf def knn_train(X_train, y_train, nb_neighbors=1): from sklearn import neighbors # MODEL SELECTION: # clf = neighbors.KNeighborsClassifier() # num_instances = np.asmatrix(X_train).shape[0] # param_dist = { # "n_neighbors": sp_randint(2, num_instances/2.0), # "weights": ['uniform', 'distance'], # "algorithm": ['auto', 'ball_tree', 'kd_tree', 'brute'], # "leaf_size": sp_randint(2, num_instances/2.0), # "metric": ['euclidean', 'manhattan', 'chebyshev'] # } # best_metaparameters = run_randomsearch(clf, param_dist, X_train, y_train, k_cv=4) # clf = neighbors.KNeighborsClassifier( # n_neighbors=best_metaparameters["n_neighbors"], # weights=best_metaparameters["weights"], # algorithm=best_metaparameters["algorithm"], # leaf_size=best_metaparameters["leaf_size"], # metric=best_metaparameters["metric"] # ) clf = neighbors.KNeighborsClassifier(n_neighbors=5) clf.fit(X_train, y_train) return clf def svm_train(X_train, y_train): from sklearn import svm # MODEL SELECTION: # clf = svm.SVC() # param_dist = { # "C": [random.uniform(0,100) for i in range(100000)] + [0.1, 0.5, 1], # "kernel": ['linear', 'poly', 'rbf', 'sigmoid'], # "degree": sp_randint(2, 5), # "gamma": [random.uniform(0,100) for i in range(100000)] + [0.1, 1, 'scale'] # } # best_metaparameters = run_randomsearch(clf, param_dist, X_train, y_train, k_cv=4) # clf = svm.SVC( # C = best_metaparameters['C'], # kernel = best_metaparameters['kernel'], # degree = best_metaparameters['degree'], # gamma = best_metaparameters['gamma'] # ) clf = svm.SVC() clf.fit(X_train, y_train) # simple np.array pas une matrice return clf def decision_tree_train(X_train, y_train): from sklearn.tree import DecisionTreeClassifier # MODEL SELECTION: # clf = DecisionTreeClassifier() # num_attributes = np.asmatrix(X_train).shape[1] # num_instances = np.asmatrix(X_train).shape[0] # param_dist = { # "criterion": ['gini', 'entropy'], # "splitter": ['best', 'random'], # "min_samples_split": [random.uniform(0,1) for i in range(10)], # "max_depth":[x for x in range (2, 10)] + [None], # "min_samples_leaf": [x for x in range (1, num_instances)], # "max_leaf_nodes": [x for x in range (2, num_instances)] + [None], # "max_features": [random.uniform(0,1) for i in range(10)] + ['auto', 'sqrt', 'log2', None], # "class_weight": ['balanced', None] # } # best_metaparameters = run_gridsearch(clf, param_dist, X_train, y_train, k_cv=4) # clf = DecisionTreeClassifier( # criterion=best_metaparameters['criterion'], # splitter=best_metaparameters['splitter'], # min_samples_split=best_metaparameters['min_samples_split'], # max_depth=best_metaparameters['max_depth'], # min_samples_leaf=best_metaparameters['min_samples_leaf'], # max_leaf_nodes=best_metaparameters['max_leaf_nodes'], # max_features=best_metaparameters['max_features'], # class_weight=best_metaparameters['class_weight'] # ) clf = DecisionTreeClassifier(criterion='gini') clf = clf.fit(X_train, y_train) # simple np.array pas une matrice return clf def random_forest_train(X_train, y_train): from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(n_estimators=10, max_depth=None, min_samples_split = 2, random_state = 0) clf = clf.fit(X_train, y_train) return clf def extra_trees_train(X_train, y_train): from sklearn.ensemble import ExtraTreesClassifier clf = ExtraTreesClassifier(n_estimators=10, max_depth=None, min_samples_split = 2, random_state = None) clf = clf.fit(X_train, y_train) return clf def balanced_accuracy_score(y_true, y_pred, normalize=True, sample_weight=None): # print("y_true", y_true) # print("y_pred", y_pred) classes = set(y_true) b_acc = 0 for c in classes: c = c nb_true_c = len([x for x in y_true if x == c]) # c expected #nb_pred_c = len([x for x in y_pred if x == c]) # c predicted nb_bien_pred_c = len([t for t,p in zip(y_true, y_pred) if t == c and t==p]) # c predicted b_acc += float(nb_bien_pred_c) / nb_true_c #print(c, nb_bien_pred_c, "/", nb_true_c) return b_acc/len(classes) def evaluation(y_true, y_pred): #from sklearn.metrics import confusion_matrix, classification_report, accuracy_score, cohen_kappa_score from sklearn.metrics import accuracy_score, recall_score, f1_score acc = accuracy_score(y_true=y_true, y_pred=y_pred) b_acc = balanced_accuracy_score(y_true, y_pred) errors = [1 - x for x in recall_score(y_true=y_true, y_pred=y_pred, average=None)] categories = list(set(y_true)) #print("api.evaluation.categories", categories) f1_scores = [x for x in f1_score(y_true=y_true, y_pred=y_pred, labels=categories, average=None)] f1_macro_avg = f1_score(y_true=y_true, y_pred=y_pred, labels=categories, average="macro") # if len(errors) == 1: # print("errors", errors) # if(y_true[0] < 1): # errors = errors + [0] # else : # errors = [0] + errors # print("errors", errors) mcc = matthews_corrcoef(y_true, y_pred) return [acc, b_acc]+errors+f1_scores+[f1_macro_avg, mcc] #print(cohen_kappa_score(y1=expected, y2=predicted)) #print(confusion_matrix(y_true=expected, y_pred=predicted)) #print(classification_report(y_true=expected, y_pred=predicted, digits=3)) def run_all_classifiers(X_train, y_train, X_test, y_test): # print('\tlinearDA:', evaluation(y_test, linearDA_train(X_train, y_train).predict(X_test))) # print('\tOurStandardPLS:', evaluation(y_test, our_standard_pls_train(X_train, y_train).predict(X_test))) # print('\tOurGiniPLS:', evaluation(y_test, our_gini_pls_train(X_train, y_train).predict(X_test))) # print('\tOurLogitPLS:', evaluation(y_test, our_logit_pls_train(X_train, y_train).predict(X_test))) # print('\tSklearnPLSCanonical:', evaluation(y_test, sklearn_pls_canonical_train(X_train, y_train).predict(X_test))) # print('\tSklearnPLSRegression:', evaluation(y_test, sklearn_pls_regression_train(X_train, y_train).predict(X_test))) # print('\tquadraticDA:', evaluation(y_test, quadraticDA_train(X_train, y_train).predict(X_test))) # print('\tGaussianNB:', evaluation(y_test, naivebayes_train(X_train, y_train).predict(X_test))) # import decimal # nb_voisins = int(str(round(decimal.Decimal((len(y_train)/4)+1)))) # print('nb_voisins', nb_voisins) # print('\tKNN:', evaluation(y_test, knn_train(X_train, y_train, nb_neighbors=nb_voisins).predict(X_test))) # print('\tSVM:', evaluation(y_test, svm_train(X_train, y_train).predict(X_test))) y_p = decision_tree_train(X_train, y_train).predict(X_test) print(y_p) print('\tDecisionTreeClassifier:', evaluation(y_test, y_p)) print('\tDecisionTreeClassifier:', evaluation(y_test, decision_tree_train(X_train, y_train).predict(X_test))) if __name__ == "__main__": _, ytrue, ypred = load_ytrue_ypred_file("C:\\Users\\gtngompe\\GitHub\\taj-ginipls\\reports\\cv-context\\predictions\\acpa_ATFCHI2_None_OurGiniPLS_0_wd-1_1-tsv.tsv") print("ytrue", ytrue) print("ypred", ypred) print("MCC", matthews_corrcoef(ytrue, ypred))
<gh_stars>0 package com.simplepathstudios.snowgloo.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.simplepathstudios.snowgloo.R; import com.simplepathstudios.snowgloo.adapter.CategoryAdapter; import com.simplepathstudios.snowgloo.api.model.CategoryList; import com.simplepathstudios.snowgloo.api.model.MusicCategory; import com.simplepathstudios.snowgloo.viewmodel.CategoryListViewModel; import java.util.ArrayList; public class CategoryListFragment extends Fragment { private final String TAG = "CategoryListFragment"; private RecyclerView listElement; private CategoryAdapter adapter; private LinearLayoutManager layoutManager; private CategoryListViewModel viewModel; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.category_list_fragment, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); listElement = view.findViewById(R.id.category_list); adapter = new CategoryAdapter(); listElement.setAdapter(adapter); layoutManager = new LinearLayoutManager(getActivity()); listElement.setLayoutManager(layoutManager); viewModel = new ViewModelProvider(this).get(CategoryListViewModel.class); viewModel.Data.observe(getViewLifecycleOwner(), new Observer<CategoryList>() { @Override public void onChanged(CategoryList categoryList) { ArrayList<MusicCategory> categories = new ArrayList<MusicCategory>(); for(String categoryName : categoryList.list){ categories.add(categoryList.lookup.get(categoryName)); } adapter.setData(categories); adapter.notifyDataSetChanged(); } }); viewModel.load(); } }
#!/bin/bash #************************************************************************************************** # Configure Defaults #************************************************************************************************** set -eu : ${WPT_BRANCH:='release'} # Prompt for the configuration options echo "WebPageTest automatic server install." # Pre-prompt for the sudo authorization so it doesn't prompt later sudo date cd ~ until sudo apt-get update do sleep 1 done until sudo DEBIAN_FRONTEND=noninteractive apt-get -yq -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" dist-upgrade do sleep 1 done until sudo apt-get install -y git screen nginx beanstalkd zip unzip curl \ php-fpm php-apcu php-sqlite3 php-curl php-gd php-zip php-mbstring php-xml php-redis \ imagemagick ffmpeg libjpeg-turbo-progs libimage-exiftool-perl \ software-properties-common psmisc do sleep 1 done sudo chown -R $USER:$USER /var/www cd /var/www until git clone --depth 1 --branch=$WPT_BRANCH https://github.com/WPO-Foundation/webpagetest.git do sleep 1 done until git clone https://github.com/WPO-Foundation/wptserver-install.git do sleep 1 done # Configure the OS and software cat wptserver-install/configs/sysctl.conf | sudo tee -a /etc/sysctl.conf sudo sysctl -p mkdir -p /var/www/webpagetest/www/tmp cat wptserver-install/configs/fstab | sudo tee -a /etc/fstab sudo mount -a cat wptserver-install/configs/security/limits.conf | sudo tee -a /etc/security/limits.conf cat wptserver-install/configs/default/beanstalkd | sudo tee /etc/default/beanstalkd sudo service beanstalkd restart #php PHPVER=$(find /etc/php/7.* -maxdepth 0 -type d -printf '%f') cat wptserver-install/configs/php/php.ini | sudo tee /etc/php/$PHPVER/fpm/php.ini cat wptserver-install/configs/php/pool.www.conf | sed "s/%USER%/$USER/" | sudo tee /etc/php/$PHPVER/fpm/pool.d/www.conf sudo service php$PHPVER-fpm restart #nginx cat wptserver-install/configs/nginx/fastcgi.conf | sudo tee /etc/nginx/fastcgi.conf cat wptserver-install/configs/nginx/fastcgi_params | sudo tee /etc/nginx/fastcgi_params cat wptserver-install/configs/nginx/nginx.conf | sed "s/%USER%/$USER/" | sudo tee /etc/nginx/nginx.conf cat wptserver-install/configs/nginx/sites.default | sudo tee /etc/nginx/sites-available/default sudo service nginx restart # WebPageTest Settings LOCATIONKEY=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1) SERVERKEY=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1) SERVERSECRET=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1) APIKEY=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1) cat wptserver-install/webpagetest/settings.ini | sed "s/%LOCATIONKEY%/$LOCATIONKEY/" | tee /var/www/webpagetest/www/settings/settings.ini cat wptserver-install/webpagetest/keys.ini | sed "s/%SERVERSECRET%/$SERVERSECRET/" | sed "s/%SERVERKEY%/$SERVERKEY/" | sed "s/%APIKEY%/$APIKEY/" | tee /var/www/webpagetest/www/settings/keys.ini cat wptserver-install/webpagetest/locations.ini | tee /var/www/webpagetest/www/settings/locations.ini cp /var/www/webpagetest/www/settings/connectivity.ini.sample /var/www/webpagetest/www/settings/connectivity.ini # Crontab to tickle the WebPageTest cron jobs every 5 minutes CRON_ENTRY="*/5 * * * * curl --silent http://127.0.0.1/work/getwork.php" ( crontab -l | grep -v -F "$CRON_ENTRY" ; echo "$CRON_ENTRY" ) | crontab - clear echo 'Setup is complete. System reboot is recommended.' echo 'The locations need to be configured manually in /var/www/webpagetest/www/settings/locations.ini' echo 'The settings can be tweaked in /var/www/webpagetest/www/settings/settings.ini' printf "\n" echo "The location key to use when configuring agents is: $LOCATIONKEY" echo "An API key to use for automated testing is: $APIKEY"
var GLOBAL = { DAY: 86400000, //one day in milliseconds WEEK: 604800000, //one week in milliseconds MINUTE: 60000, //one minute in milliseconds HOUR: 3600000 //one hour in milliseconds } var STATE = { CHECKPOINT: 0, LAST: 0, LOADED: false } var CONFIG = { SIMULATION_START: 0, SIMULATION_END: 0, REAL_START: 0, REAL_END: 0 } var realClock = document.getElementById('real-clock'); var simulationClock = document.getElementById('simulation-clock'); var countdownClock = document.getElementById('countdown-clock'); var checkpointLabel = document.getElementById('checkpoint-label'); var simulationCalendar = document.getElementById('simulation-calendar'); var calendarToolbar = document.getElementById('calendar-toolbar'); vex.defaultOptions.className = 'vex-theme-wireframe'; var PATH = "https://simulation-timer.firebaseio.com/"; function getConfiguration(key){ var firebase = new Firebase(PATH + key); firebase.once("value", function(snapshot){ var config = snapshot.val(); if(config !== null){ CONFIG = config; createCalendar(simulationCalendar, calendarToolbar, config); loadCalendar(simulationCalendar, config); setCheckPoint(config.SIMULATION_END); STATE.LAST = config.SIMULATION_START; STATE.LOADED = true; /*document.getElementById("menu").display = "none"; document.getElementById("main-timer").display = "block";*/ } else{ getUserKey(); } }); } function updatePastOpacities(simTimestamp){ var dateBoxes = document.getElementsByClassName("weekday"); $.each(dateBoxes, function(index, div){ if(div.id.length > 0){ var divDate = parseInt(div.id.split("-")[1], 10); //console.log(div.id) if(divDate < simTimestamp){ if(!div.classList.contains("weekday-label")){ div.classList.add("weekday-past"); } } } }); } function updateOpacity(now, config){ var simTime = getSimulationTime(now, config); var simDate = new Date(simTime); var findBox = new Date( simDate.getFullYear(), simDate.getMonth(), simDate.getDate() ); var dateBox = document.getElementById("weekday-" + findBox.getTime()); var opacity = ((1 - (simDate.getHours() / 24)) * 0.75) + 0.25; dateBox.style.opacity = opacity; if(counter < 1){ updatePastOpacities(findBox.getTime()); var index = getMonthInSimulation(simDate.getTime(), config); toggleMonthView(simulationCalendar, index); } } var counter = 0; window.setInterval(function(){ if(STATE.LOADED){ var realNow = new Date().getTime(); setClock(realNow, CONFIG); setCountdown(realNow, STATE.CHECKPOINT, CONFIG); //setMonthView(realNow, CONFIG); updateOpacity(realNow, CONFIG); counter++; } }, 25); getUserKey(); //getConfiguration("test"); function convertUTCToTimeZone(utcDate, timezone){ //if(timezone === "CS") } function getUserKey(){ vex.dialog.prompt({ message: "Enter the key given to you by your simulation organizer.", callback: function(key){ if(key){ getConfiguration(key); } } }); } /* * Returns scale between real time and simulation time * Multiply real time by this scalar to get simulation time */ function calculateTimeScale(config){ var simulationDuration = config.SIMULATION_END - config.SIMULATION_START; var realDuration = config.REAL_END - config.REAL_START; var scale = simulationDuration / realDuration; return scale; } function getSimulationTime(now, config){ var realElapsed = now - config.REAL_START; var scale = calculateTimeScale(config); var simTime = (realElapsed * scale) + config.SIMULATION_START; return simTime; } function convertToRealTime(simDuration, config){ var scale = calculateTimeScale(config); var realDuration = (simDuration / scale); return realDuration; } function minutesToSeconds(minutes){ var fraction = minutes - Math.floor(minutes); var seconds = fraction * 60; var displayMinutes = Math.floor(minutes); var displaySeconds = Math.floor(seconds).toString().length === 1 ? "0" + Math.floor(seconds) : Math.floor(seconds); var time = displayMinutes + " minutes, " + displaySeconds + " seconds"; return time; } //WARNING: ONLY WORKS FOR SIMULATIONS LESS THAN A YEAR LONG function getMonthInSimulation(timestamp, config){ var startMonth = new Date(config.SIMULATION_START).getMonth(); var currentMonth = new Date(timestamp).getMonth(); return (currentMonth - startMonth); } function getWeekInMonthInSimulation(timestamp, config){ //var startDay = time } function setClock(now, config){ var simTime = getSimulationTime(now, config); realClock.innerHTML = moment(now).format("M/D hh:mm:ss A"); simulationClock.innerHTML = moment(simTime).format("MMMM Do YYYY | hh:mm A"); } function showCurrentDate(now, simWeek, config){ var simTime = getSimulationTime(now, config); var simDate = new Date(simTime); var monthIndex = getMonthInSimulation(now, config); var monthDiv = getMonthDiv(calendarDiv, monthIndex); var dateBox = monthDiv.children[simWeek + 2].children[simDate.getDay()]; } //Returns real time remaining in minutes function showTimeUntil(timestamp, config){ var realNow = new Date().getTime(); var simNow = getSimulationTime(realNow, config); var simTimeRemaining = timestamp - simNow; var realTimeRemaining = convertToRealTime(simTimeRemaining, config); return (realTimeRemaining / GLOBAL.MINUTE); } function setCountdown(now, checkpoint, config){ var realTimeRemaining = showTimeUntil(checkpoint, config); countdownClock.innerHTML = minutesToSeconds(realTimeRemaining); } function setMonthView(now, config){ var simTime = getSimulationTime(now, config); var simDate = new Date(simTime); var lastDate = new Date(STATE.LAST); if(simDate.getMonth() !== lastDate.getMonth()){ var monthIndex = getMonthInSimulation(simTime, config); toggleMonthView(simulationCalendar, monthIndex); } } function setCheckPoint(timestamp){ STATE.CHECKPOINT = timestamp; var label = moment(timestamp).format("M/D"); checkpointLabel.innerHTML = label; } function toggleMonthView(calendarDiv, monthIndex){ var monthDiv = getMonthDiv(calendarDiv, monthIndex); var allMonths = calendarDiv.getElementsByClassName("month"); $.each(allMonths, function(index, div){ div.style.display = "none"; }); monthDiv.style.display = "block"; } var weekdayLabel = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; function createCalendar(calendarDiv, toolbarDiv, config){ var startMonth = new Date(config.SIMULATION_START).getMonth(); var endMonth = new Date(config.SIMULATION_END).getMonth(); var months = (endMonth - startMonth) + 1; var currentMonth = startMonth; var currentDate = new Date(config.SIMULATION_START); for(var m = 0; m < months; m++){ var labelDiv = document.createElement("h1"); labelDiv.classList.add("month-label"); labelDiv.innerHTML = moment(currentDate).format("MMMM YYYY"); var monthDiv = document.createElement("div"); monthDiv.classList.add("month"); monthDiv.appendChild(labelDiv); calendarDiv.appendChild(monthDiv); var toolbarMonth = document.createElement("button"); toolbarMonth.classList.add("month-button"); toolbarMonth.innerHTML = moment(currentDate).format("MMMM YYYY"); toolbarMonth.id = "month-button-" + m; toolbarDiv.appendChild(toolbarMonth); currentMonth++; currentDate.setMonth(currentDate.getMonth() + 1); } var monthDivs = calendarDiv.getElementsByClassName("month"); $.each(monthDivs, function(index, div){ var weekDiv = document.createElement("div"); weekDiv.classList.add("week"); weekDiv.classList.add("week-label"); div.appendChild(weekDiv); for(var w = 0; w < 5; w++){ var weekDiv = document.createElement("div"); weekDiv.classList.add("week"); div.appendChild(weekDiv); } }); var weekDivs = calendarDiv.getElementsByClassName("week"); $.each(weekDivs, function(index, div){ for(var d = 0; d < 7; d++){ var dayDiv = document.createElement("div"); dayDiv.classList.add("weekday"); dayDiv.classList.add("weekday-inactive"); dayDiv.innerHTML = "-"; if(div.classList.contains("week-label")){ dayDiv.classList.add("weekday-label"); dayDiv.innerHTML = weekdayLabel[d].substr(0, 2); } div.appendChild(dayDiv); } }); $(".month-button").click(function(event){ var monthIndex = parseInt(this.id.split("-")[2]); toggleMonthView(calendarDiv, monthIndex); }); $(".weekday").click(function(event){ var timestamp = parseInt(this.id.split("-")[1]); setCheckPoint(timestamp); }); } function getMonthDiv(calendarDiv, index){ var monthDivs = calendarDiv.children; return monthDivs[index]; } function loadCalendar(calendarDiv, config){ var simMonth = 0; var simWeek = 0; var simTime = config.SIMULATION_START; while(simTime <= config.SIMULATION_END){ var simDate = new Date(simTime); var monthDiv = getMonthDiv(calendarDiv, simMonth); var dateBox = monthDiv.children[simWeek + 2].children[simDate.getDay()]; dateBox.innerHTML = simDate.getDate(); dateBox.classList.remove("weekday-inactive"); dateBox.classList.add("weekday-active"); dateBox.id = "weekday-" + simTime; simTime += GLOBAL.DAY; if(simDate.getDay() === 6){ simWeek++; } if(simDate.getMonth() !== new Date(simTime).getMonth()){ simMonth++; simWeek = 0; } } }
def find_element(arr, predicate): """ Find an element in a given array that satisfies the given predicate. :param arr: list, the array to search :param predicate: function, a function to check for predicate satisfaction :returns element if found, otherwise None """ for element in arr: if predicate(element): return element return None
class Product: def __init__(self, product_rating_results): self._product_rating_results = product_rating_results self.openapi_types = { 'name': str, 'price': float, 'quantity': int } def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, attr_type in self.openapi_types.items(): if hasattr(self, attr): result[attr] = getattr(self, attr) return result
<template> <div> <p>Name: {{ input.firstName }} {{ input.lastName }}</p> <p>Email: {{ input.email }}</p> </div> </template> <script> export default { props: ["input"], }; </script>
#include "duckdb/planner/planner.hpp" #include "duckdb/common/serializer.hpp" #include "duckdb/main/client_context.hpp" #include "duckdb/main/database.hpp" #include "duckdb/parser/statement/pragma_statement.hpp" #include "duckdb/parser/statement/prepare_statement.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/planner/bound_sql_statement.hpp" #include "duckdb/planner/expression/bound_parameter_expression.hpp" #include "duckdb/planner/logical_plan_generator.hpp" #include "duckdb/planner/operator/logical_prepare.hpp" #include "duckdb/planner/statement/bound_execute_statement.hpp" #include "duckdb/planner/statement/bound_select_statement.hpp" #include "duckdb/planner/statement/bound_simple_statement.hpp" #include "duckdb/planner/query_node/bound_select_node.hpp" #include "duckdb/planner/query_node/bound_set_operation_node.hpp" #include "duckdb/planner/pragma_handler.hpp" #include "duckdb/parser/parsed_data/drop_info.hpp" using namespace duckdb; using namespace std; Planner::Planner(ClientContext &context) : binder(context), context(context) { } bool Planner::StatementRequiresValidTransaction(BoundSQLStatement &statement) { switch (statement.type) { case StatementType::DROP: { // dropping prepared statements also does not require a valid transaction auto &drop_info = (DropInfo &)(*((BoundSimpleStatement &)statement).info); return drop_info.type == CatalogType::PREPARED_STATEMENT; } case StatementType::PREPARE: case StatementType::TRANSACTION: // prepare and transaction statements can be executed without valid transaction return false; case StatementType::EXECUTE: // execute statement: look into the to-be-executed statement return ((BoundExecuteStatement &)statement).prepared->requires_valid_transaction; default: return true; } } void Planner::CreatePlan(SQLStatement &statement) { vector<BoundParameterExpression *> bound_parameters; // first bind the tables and columns to the catalog context.profiler.StartPhase("binder"); binder.parameters = &bound_parameters; auto bound_statement = binder.Bind(statement); context.profiler.EndPhase(); VerifyQuery(*bound_statement); this->read_only = binder.read_only; this->requires_valid_transaction = StatementRequiresValidTransaction(*bound_statement); this->names = bound_statement->GetNames(); this->sql_types = bound_statement->GetTypes(); // now create a logical query plan from the query context.profiler.StartPhase("logical_planner"); LogicalPlanGenerator logical_planner(binder, context); this->plan = logical_planner.CreatePlan(*bound_statement); context.profiler.EndPhase(); // set up a map of parameter number -> value entries for (auto &expr : bound_parameters) { // check if the type of the parameter could be resolved if (expr->return_type == TypeId::INVALID) { throw BinderException("Could not determine type of parameters: try adding explicit type casts"); } auto value = make_unique<Value>(expr->return_type); expr->value = value.get(); // check if the parameter number has been used before if (value_map.find(expr->parameter_nr) != value_map.end()) { throw BinderException("Duplicate parameter index. Use $1, $2 etc. to differentiate."); } PreparedValueEntry entry; entry.value = move(value); entry.target_type = expr->sql_type; value_map[expr->parameter_nr] = move(entry); } } void Planner::CreatePlan(unique_ptr<SQLStatement> statement) { assert(statement); switch (statement->type) { case StatementType::SELECT: case StatementType::INSERT: case StatementType::COPY: case StatementType::DELETE: case StatementType::UPDATE: case StatementType::CREATE: case StatementType::EXECUTE: case StatementType::DROP: case StatementType::ALTER: case StatementType::TRANSACTION: case StatementType::EXPLAIN: CreatePlan(*statement); break; case StatementType::PRAGMA: { auto &stmt = *reinterpret_cast<PragmaStatement *>(statement.get()); PragmaHandler handler(context); // some pragma statements have a "replacement" SQL statement that will be executed instead // use the PragmaHandler to get the (potential) replacement SQL statement auto new_stmt = handler.HandlePragma(*stmt.info); if (new_stmt) { CreatePlan(move(new_stmt)); } else { CreatePlan(stmt); } break; } case StatementType::PREPARE: { auto &stmt = *reinterpret_cast<PrepareStatement *>(statement.get()); auto statement_type = stmt.statement->type; // create a plan of the underlying statement CreatePlan(move(stmt.statement)); // now create the logical prepare auto prepared_data = make_unique<PreparedStatementData>(statement_type); prepared_data->names = names; prepared_data->sql_types = sql_types; prepared_data->value_map = move(value_map); prepared_data->read_only = this->read_only; prepared_data->requires_valid_transaction = this->requires_valid_transaction; this->read_only = true; this->requires_valid_transaction = false; auto prepare = make_unique<LogicalPrepare>(stmt.name, move(prepared_data), move(plan)); names = {"Success"}; sql_types = {SQLType(SQLTypeId::BOOLEAN)}; plan = move(prepare); break; } default: throw NotImplementedException("Cannot plan statement of type %s!", StatementTypeToString(statement->type).c_str()); } } void Planner::VerifyQuery(BoundSQLStatement &statement) { if (!context.query_verification_enabled) { return; } if (statement.type != StatementType::SELECT) { return; } auto &select = (BoundSelectStatement &)statement; VerifyNode(*select.node); } void Planner::VerifyNode(BoundQueryNode &node) { if (node.type == QueryNodeType::SELECT_NODE) { auto &select_node = (BoundSelectNode &)node; vector<unique_ptr<Expression>> copies; for (auto &expr : select_node.select_list) { VerifyExpression(*expr, copies); } if (select_node.where_clause) { VerifyExpression(*select_node.where_clause, copies); } for (auto &expr : select_node.groups) { VerifyExpression(*expr, copies); } if (select_node.having) { VerifyExpression(*select_node.having, copies); } for (auto &aggr : select_node.aggregates) { VerifyExpression(*aggr, copies); } for (auto &window : select_node.windows) { VerifyExpression(*window, copies); } // double loop to verify that (in)equality of hashes for (idx_t i = 0; i < copies.size(); i++) { auto outer_hash = copies[i]->Hash(); for (idx_t j = 0; j < copies.size(); j++) { auto inner_hash = copies[j]->Hash(); if (outer_hash != inner_hash) { // if hashes are not equivalent the expressions should not be equivalent assert(!Expression::Equals(copies[i].get(), copies[j].get())); } } } } else { assert(node.type == QueryNodeType::SET_OPERATION_NODE); auto &setop_node = (BoundSetOperationNode &)node; VerifyNode(*setop_node.left); VerifyNode(*setop_node.right); } } void Planner::VerifyExpression(Expression &expr, vector<unique_ptr<Expression>> &copies) { if (expr.HasSubquery()) { // can't copy subqueries return; } // verify that the copy of expressions works auto copy = expr.Copy(); // copy should have identical hash and identical equality function assert(copy->Hash() == expr.Hash()); assert(Expression::Equals(copy.get(), &expr)); copies.push_back(move(copy)); }
<filename>src/components/index.ts export default 'ddd'
from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB # Create a pipeline pipeline = Pipeline([ ('vect', TfidfVectorizer()), ('nb', MultinomialNB()) ]) # Train the model pipeline.fit(X_train, y_train) # Make predictions predictions = pipeline.predict(X_test) # Evaluate the model from sklearn.metrics import accuracy_score print("Accuracy:", accuracy_score(y_test, predictions))
#!/bin/bash # Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # simulate network latency on Mac OS X, see man ipfw(8) #set -x if [ $# -lt 1 ] ; then echo "usage: `basename $0` <delay-ms> [<port> ...]" echo " delay < 0 deletes the delay rule set" echo " = 0 disables the delay rule set" echo " > 0 enables the delay rule set" echo " port... adds the ports to the delay rule set" exit 1 fi delay=$1 shift ports=$* #echo "simulate a delay of ($delay + $delay) ms on ports $ports" echo "simulate a delay of $delay ms on destination ports $ports" pipe=4711 # 1..64k rset=21 # 0..30 if [ $delay -lt 0 ] ; then echo "removing rules (as admin)..." sudo ipfw delete set $rset sudo ipfw pipe delete $pipe > /dev/null 2>&1 elif [ $delay -eq 0 ] ; then echo "disabling rules (as admin)..." sudo ipfw set disable $rset else echo "adding rules (as admin)..." # not strictly necessary but better change atomically sudo ipfw set disable $rset sudo ipfw pipe $pipe config delay $delay sudo ipfw set enable $rset # rules not visible if set disabled for p in $ports ; do sudo ipfw list $p > /dev/null if [ $? -ne 0 ] ; then # not strictly necessary but better change atomically sudo ipfw set disable $rset # sudo ipfw add $p set $rset pipe $pipe src-port $p > /dev/null 2>&1 sudo ipfw add $p set $rset pipe $pipe dst-port $p > /dev/null 2>&1 sudo ipfw set enable $rset fi done fi echo "current rules:" sudo ipfw list | grep $pipe #sudo ipfw show echo "done." #set +x
#pragma once #include <unordered_map> #include "Utility.h" #include <filesystem> namespace tnah { /** * @struct File * * @brief Structure of a file, contains a name and a extension. * * @author <NAME> * @date 7/09/2021 */ struct File { std::string FileName; std::string Extension; std::string FullFile; /** * @fn File() = default; * * @brief Defaulted constructor * * @author <NAME> * @date 7/09/2021 */ File() = default; /** * @fn File(const std::string& name, const std::string& extension) * * @brief Constructor * * @author <NAME> * @date 7/09/2021 * * @param name The file name. * @param extension The file extension. */ File(const std::string& name, const std::string& extension) :FileName(name), Extension(extension) { FullFile = FileName + Extension; } /** * @fn operator std::string&() * * @brief Cast that converts the given to a string&amp; * * @author <NAME> * @date 7/09/2021 * * @returns The result of the operation. */ operator std::string&() { return FullFile; } }; /** * @typedef std::string Directory * * @brief Structure of a directory, contains a path. */ typedef std::string Directory; /** * @struct Folder * * @brief Structure of a Folder, contains a vector of files inside a root folder path * * @author <NAME> * @date 7/09/2021 */ struct Folder { /** @brief Pathname of the files in folder */ std::vector<File> FilesInFolder; /** @brief The folder root */ Directory FolderRoot; /** * @fn Folder() = default; * * @brief Defaulted constructor * * @author <NAME> * @date 7/09/2021 */ Folder() = default; }; /** * @struct Project * * @brief Structure of a Project, contains a root directory and vector of sub directories. * * @author <NAME> * @date 7/09/2021 */ struct Project { /** @brief The name */ std::string Name; /** @brief Pathname of the root directory */ Directory RootDirectory; /** @brief The sub directories */ std::vector<Directory> SubDirectories; /** @brief The project files */ std::unordered_map<Directory, Folder> ProjectFiles; /** * @fn Project(const Directory& root) * * @brief Constructor * * @author <NAME> * @date 7/09/2021 * * @param root The root. */ Project(const Directory& root) :RootDirectory(root) {} /** * @fn operator std::string&() * * @brief Cast that converts the given to a string&amp; * * @author <NAME> * @date 7/09/2021 * * @returns The result of the operation. */ operator std::string&() { return RootDirectory; } /** * @fn operator std::vector<Directory>&() * * @brief Cast that converts the given to a vector * * @author <NAME> * @date 7/09/2021 * * @returns The result of the operation. */ operator std::vector<Directory>&() { return SubDirectories; } /** * @fn operator std::unordered_map<Directory, Folder>&() * * @brief Gets the folder>&amp; * * @author <NAME> * @date 7/09/2021 * * @returns A std::unordered_map&lt;Directory. */ operator std::unordered_map<Directory, Folder>&() { return ProjectFiles; } }; /** * @enum RType * * @brief Values that represent types */ enum class RType { EMPTY, Unknown, Model, Image, Texture, Shader, Audio, Material, TNAH }; /** * @enum RSubType * * @brief Values that represent sub types */ enum class RSubType { EMPTY, ILLEGAL_SUBTYPE, PBR_Material, Heightmap, UI_Image, Texture_2D, Texture_3D, Vertex_Shader, Fragment_Shader, Audio_Clip, TNAH_Scene, TNAH_Project, TNAH_Resource, TNAH_Prefab }; /** * @struct ResourceType * * @brief A resource type. * * @author <NAME> * @date 7/09/2021 */ struct ResourceType { /** @brief The type */ RType Type = RType::EMPTY; /** @brief The sub type */ RSubType SubType = RSubType::EMPTY; /** * @fn ResourceType() = default; * * @brief Defaulted constructor * * @author <NAME> * @date 7/09/2021 */ ResourceType() = default; /** * @fn ResourceType(const RType& type, const RSubType& subType) * * @brief Constructor * * @author <NAME> * @date 7/09/2021 * * @param type The type. * @param subType The subtype. */ ResourceType(const RType& type, const RSubType& subType) :Type(type) { if(type != RType::EMPTY && subType != RSubType::EMPTY) { switch (type) { case RType::Model: // No Subtype for models yet break; case RType::Image: if(subType != RSubType::Heightmap && subType != RSubType::UI_Image) SubType = RSubType::ILLEGAL_SUBTYPE; else SubType = subType; break; case RType::Texture: if(subType != RSubType::Texture_2D && subType != RSubType::Texture_3D) SubType = RSubType::ILLEGAL_SUBTYPE; else SubType = subType; break; case RType::Shader: if(subType != RSubType::Vertex_Shader && subType != RSubType::Fragment_Shader) SubType = RSubType::ILLEGAL_SUBTYPE; else SubType = subType; break; case RType::Audio: if(subType != RSubType::Audio_Clip) SubType = RSubType::ILLEGAL_SUBTYPE; else SubType = subType; break; case RType::Material: if(subType != RSubType::PBR_Material) SubType = RSubType::ILLEGAL_SUBTYPE; else SubType = subType; break; case RType::TNAH: if(subType != RSubType::TNAH_Scene && subType != RSubType::TNAH_Prefab && subType != RSubType::TNAH_Project && subType != RSubType::TNAH_Resource) SubType = RSubType::ILLEGAL_SUBTYPE; else SubType = subType; break; default: SubType = RSubType::EMPTY; break; case RType::EMPTY: break; case RType::Unknown: break; } } } /** * @fn static RType GuessType(const std::string& fileExtension) * * @brief Guess type of the file from its extension * * @author <NAME> * @date 7/09/2021 * * @param fileExtension The file extension. * * @returns A RType. */ static RType GuessType(const std::string& fileExtension) { std::string modelGuess[] = { "fbx", "obj", "c4d", "3ds", "dae" }; std::string imageGuess[] = { "jpg", "png", "tga", "gif", "tiff", "raw", "bmp", "jpeg", "tif", "ktx", "ktx2" }; std::string audioGuess[] = { "mp3", "wav" }; std::string shaderGuess[] = { "glsl", "vert", "frag", "txt" }; std::string materialGuess[] = { "material", "mat", "pbr" }; std::string customGuess[] = { "tnah.scene", "tnahproj", "tnah.resource" , "tnah.meta", "tnah.prefab" }; for(auto s : modelGuess) { if(fileExtension.find(s) != std::string::npos) return RType::Model; } for(auto s : imageGuess) { if(fileExtension.find(s) != std::string::npos) return RType::Image; } for(auto s : audioGuess) { if(fileExtension.find(s) != std::string::npos) return RType::Audio; } for(auto s : shaderGuess) { if(fileExtension.find(s) != std::string::npos) return RType::Shader; } for(auto s : materialGuess) { if(fileExtension.find(s) != std::string::npos) return RType::Material; } for(auto s : customGuess) { if(fileExtension.find(s) != std::string::npos) return RType::TNAH; } return RType::Unknown; } }; /** * @struct Resource * * @brief A resource. * * @author <NAME> * @date 7/09/2021 */ struct Resource { /** @brief CustomName of the resource */ std::string CustomName = ""; /** @brief Pathname of the relative directory */ Directory RelativeDirectory = Directory(""); /** @brief Pathname of the root directory */ Directory RootDirectory = Directory(""); /** @brief Pathname of the absolute directory */ Directory AbsoluteDirectory = Directory(""); /** @brief Filename of the file */ File FileName = File("", ""); /** @brief The type */ ResourceType Type = ResourceType(RType::EMPTY, RSubType::EMPTY); /** * @fn Resource() = default; * * @brief Defaulted constructor * * @author <NAME> * @date 7/09/2021 */ Resource() = default; /** * @fn Resource(const Directory& fileDirectory, const File& fileName, const ResourceType& resourceType) * * @brief Constructor * * @author <NAME> * @date 7/09/2021 * * @param fileDirectory Pathname of the file directory. * @param fileName Filename of the file. * @param resourceType Type of the resource. */ Resource(const Directory& fileDirectory, const File& fileName, const ResourceType& resourceType) :RootDirectory(fileDirectory), FileName(fileName), Type(resourceType) { AbsoluteDirectory = RootDirectory + "/" + FileName.FullFile; } /** * @fn Resource(const std::string& fileDirectory, const std::string& fileName, const ResourceType& resourceType) * * @brief Constructor * * @author <NAME> * @date 7/09/2021 * * @param fileDirectory Pathname of the file directory. * @param fileName Filename of the file. * @param resourceType Type of the resource. */ Resource(const std::string& fileDirectory, const std::string& fileName, const ResourceType& resourceType) :RootDirectory(fileDirectory), Type(resourceType) { auto n = Utility::SplitFileNameAndExtension(fileName); FileName.FileName = n.first; FileName.Extension = n.second; FileName.FullFile = fileName; AbsoluteDirectory = RootDirectory + "/" + fileName; } /** * @fn Resource(const std::string& relativeFilePath) * * @brief Constructor * * @author <NAME> * @date 7/09/2021 * * @param relativeFilePath Full pathname of the relative file. */ Resource(const std::string& relativeFilePath) { if(relativeFilePath.find("\\/") != std::string::npos) { auto dirSplit = Utility::SplitDirectoryAndFilePath(relativeFilePath); RootDirectory = dirSplit.first; FileName.FullFile = dirSplit.second; auto nameSplit = Utility::SplitFileNameAndExtension(dirSplit.second); FileName.FileName = nameSplit.first; FileName.Extension = nameSplit.second; Type.Type = ResourceType::GuessType(FileName.Extension); AbsoluteDirectory = relativeFilePath; RelativeDirectory = Utility::RelativePathFromAbsolute(relativeFilePath); CustomName = nameSplit.first; } else { auto dirSplit = Utility::SplitDirectoryAndFilePath(relativeFilePath); RootDirectory = dirSplit.first; FileName.FullFile = dirSplit.second; auto nameSplit = Utility::SplitFileNameAndExtension(dirSplit.second); FileName.FileName = nameSplit.first; FileName.Extension = nameSplit.second; Type.Type = ResourceType::GuessType(FileName.Extension); AbsoluteDirectory = Utility::AbsolutePathFromRelative(relativeFilePath); RelativeDirectory = relativeFilePath; CustomName = nameSplit.first; } } }; }
#! /bin/bash -e source /etc/profile.d/gvm.sh source config/env-secret.sh HMACPROXY_SERVER_PORT=8083 HMACPROXY_PROXY_PORT=8084 HMACPROXY_SIGN_HEADER="Team-Api-Signature" HMACPROXY_HEADERS="Content-Type,Date" if [ "$1" = "run-server" ]; then exec hmacproxy -auth -port $HMACPROXY_SERVER_PORT -secret $HMACAUTH_SECRET \ -sign-header $HMACPROXY_SIGN_HEADER -headers $HMACPROXY_HEADERS fi if [ "$1" = "run-proxy" ]; then UPSTREAM="$2" if [ -z "$UPSTREAM" ]; then echo "No upstream server specified" exit 1 fi exec hmacproxy -port $HMACPROXY_PROXY_PORT -secret $HMACAUTH_SECRET \ -sign-header $HMACPROXY_SIGN_HEADER -headers $HMACPROXY_HEADERS \ -upstream $UPSTREAM fi exec "$@"
import re string = "This is a string with some numbers like 'ABC-123' and other numbers like '789XYZ'." result = re.search(r'\d+[a-zA-Z.]+\d+', string) if result: print(result.group())
import { UndoableEdit } from "./UndoableEdit"; /** * The UndoManager keeps track of all editables. */ export class UndoManager { private edits: UndoableEdit[] = []; private position = 0; private unmodifiedPosition = 0; private limit: number; private listener: null | (() => void) = null; /** * Create a new UndoManager * * @param limit The maximum amount of editables to remember */ public constructor(limit = 100) { this.limit = limit; } /** * The listener will be called when changes have been done (adding an edit, or undoing/redoing it) * * @param listener The new callback or null to remove the existing one. */ public setListener(listener: null | (() => void)) { this.listener = listener; } /** * Test if there is anything to be saved */ public isModified() { if (this.unmodifiedPosition === -1) return true; if (this.position === this.unmodifiedPosition) return false; if (this.edits.length <= this.unmodifiedPosition) return true; let from = this.testUndo(this.unmodifiedPosition); from = from === false ? this.unmodifiedPosition : from + 1; let to = this.testRedo(this.unmodifiedPosition); to = to === false ? this.unmodifiedPosition + 1 : to - 1; return this.position < from || this.position > to; } /** * Mark the point when the data has been saved. */ public setUnmodified() { this.unmodifiedPosition = this.position; } /** * Get the maximum amount of editables to remember */ public getLimit(): number { return this.limit; } /** * Set the maximum amount of editables to remember. * The new limit will be applied instantly. * * @param value The maximum amount of editables to remember */ public setLimit(value: number): void { this.applyLimit((this.limit = value)); } /** * Clear all edits */ public clear(): void { this.edits.length = 0; this.position = 0; this.unmodifiedPosition = 0; this.listener?.(); } private applyLimit(limit: number) { const diff = this.edits.length - limit; if (diff > 0) { this.position = Math.max(0, this.position - diff); if (this.unmodifiedPosition !== -1) this.unmodifiedPosition = Math.max(0, this.unmodifiedPosition - diff); this.edits.splice(0, diff); } } /** * Test to see the new position after an undo would happen. * * @param position The start position * @return False if no significant edit can be undone. * Otherwise the new position. */ private testUndo(position: number): number | false { for (let i = position - 1; i >= 0; i--) { if (this.edits[i].isSignificant()) return i; } return false; } /** * @returns true if there is anything to be undone (only significant edits count) */ public canUndo(): boolean { return this.testUndo(this.position) !== false; } /** * Undo the last significant edit. * This will undo all insignificant edits up to the edit to be undone. * * @throws Error if no edit can be undone. */ public undo(): void { const newPosition = this.testUndo(this.position); if (newPosition === false) throw new Error("Cannot undo"); while (this.position > newPosition) { const next = this.edits[--this.position]; next.undo(); } this.listener?.(); } /** * Test to see the new position after an redo would happen. * * @param position The start position * @return False if no significant edit can be redone. * Otherwise the new position. */ private testRedo(position: number): number | false { for (let i = position; i < this.edits.length; i++) { if (this.edits[i].isSignificant()) return i + 1; } return false; } /** * @returns true if there is anything to be redone (only significant edits count) */ public canRedo(): boolean { return this.testRedo(this.position) !== false; } /** * Redo the next significant edit. * This will redo all insignificant edits up to the edit to be redone. * * @throws Error if no edit can be redone. */ public redo(): void { const newPosition = this.testRedo(this.position); if (newPosition === false) throw new Error("Cannot redo"); while (this.position < newPosition) { const next = this.edits[this.position++]; next.redo(); } this.listener?.(); } /** * Add a new edit. Will try to merge or replace existing edits. * * @param edit The new edit to add. */ public add(edit: UndoableEdit) { if (this.edits.length > this.position) this.edits.length = this.position; if (this.edits.length === 0 || this.unmodifiedPosition === this.edits.length) this.edits.push(edit); else { const last = this.edits[this.edits.length - 1]; if (!last.merge(edit)) { if (edit.replace(last)) this.edits.pop(); this.edits.push(edit); } } this.applyLimit(this.limit); this.position = this.edits.length; if (this.unmodifiedPosition >= this.position) this.unmodifiedPosition = -1; this.listener?.(); } }
/** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */ package org.olat.course.nodes.card2brain; import java.util.Map; import org.olat.core.dispatcher.mapper.Mapper; import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.Component; import org.olat.core.gui.components.htmlheader.jscss.JSAndCSSComponent; import org.olat.core.gui.components.panel.Panel; import org.olat.core.gui.components.velocity.VelocityContainer; import org.olat.core.gui.control.Event; import org.olat.core.gui.control.WindowControl; import org.olat.core.gui.control.controller.BasicController; import org.olat.course.nodes.Card2BrainCourseNode; import org.olat.ims.lti.LTIContext; import org.olat.ims.lti.LTIManager; import org.olat.ims.lti.ui.PostDataMapper; import org.olat.modules.ModuleConfiguration; import org.olat.modules.card2brain.Card2BrainModule; import org.springframework.beans.factory.annotation.Autowired; /** * * Initial date: 11.04.2017<br> * * @author uhensler, <EMAIL>, http://www.frentix.com * */ public class Card2BrainRunController extends BasicController { private Panel main; private final ModuleConfiguration config; @Autowired private Card2BrainModule card2BrainModule; @Autowired private LTIManager ltiManager; public Card2BrainRunController(UserRequest ureq, WindowControl wControl, ModuleConfiguration config) { super(ureq, wControl); this.config = config; main = new Panel("card2brainPanel"); runCard2Brain(ureq); putInitialPanel(main); } private void runCard2Brain(UserRequest ureq) { VelocityContainer container = createVelocityContainer("run"); String url = String.format(card2BrainModule.getBaseUrl(), config.getStringValue(Card2BrainCourseNode.CONFIG_FLASHCARD_ALIAS)); String oauth_consumer_key; String oauth_secret; if (config.getBooleanSafe(Card2BrainCourseNode.CONFIG_ENABLE_PRIVATE_LOGIN)) { oauth_consumer_key = (String) config.get(Card2BrainCourseNode.CONFIG_PRIVATE_KEY); oauth_secret = (String) config.get(Card2BrainCourseNode.CONFIG_PRIVATE_SECRET); } else { oauth_consumer_key = card2BrainModule.getEnterpriseKey(); oauth_secret = card2BrainModule.getEnterpriseSecret(); } LTIContext context = new Card2BrainContext(); Map<String, String> unsignedProps = ltiManager.forgeLTIProperties(getIdentity(), getLocale(), context, true, true, false); Mapper contentMapper = new PostDataMapper(unsignedProps, url, oauth_consumer_key, oauth_secret, false); String mapperUri = registerMapper(ureq, contentMapper); container.contextPut("mapperUri", mapperUri + "/"); JSAndCSSComponent js = new JSAndCSSComponent("js", new String[] { "js/openolat/iFrameResizerHelper.js" }, null); container.put("js", js); main.setContent(container); } @Override protected void event(UserRequest ureq, Component source, Event event) { // } }
import styled from "styled-components"; export const Content = styled.div` display: flex; flex-direction: column; align-items: center; align-self: center; gap: 2rem; margin: 0 auto; padding: 1rem 2rem; border: 1px solid #542e91; border-radius: 0.5rem; background: #542e91; h2 { padding: 1rem 2rem; color: #fddc05; width: 100%; text-align: center; border-bottom: 1px solid #fddc05; } `;
#!/bin/bash GRAALVM_BUILD=${GRAALVM_BUILD:-"1.0.0-rc6"} docker build . --build-arg GRAALVM_BUILD=$GRAALVM_BUILD --tag graemerocher/graalvm-ce:$GRAALVM_BUILD --tag graemerocher/graalvm-ce:latest
class ApplicationController < ActionController::API include ActionController::Serialization include Response rescue_from ActiveRecord::RecordNotFound do |exception| json_response({ message: exception.message }, :not_found) end rescue_from ActiveRecord::RecordInvalid do |exception| json_response({ message: exception.message }, :unprocessable_entity) end end
echo ">> Generating data..." bash scripts/toy_gen_data.sh echo ">> Training..." bash scripts/toy_train.sh echo ">> Validating..." bash scripts/toy_test.sh echo ">> Solving..." bash scripts/toy_solve.sh
# A Dynamic Programming based # Python program for 0-1 Knapsack problem # Returns th maximum value that can # be put in a knapsack of capacity W def knapSack(W, wt, val, n): # Base Case if n == 0 or W == 0: return 0 # If weight of the nth item is more than Knapsack of capacity # W, then this item cannot be included in the optimal solution if wt[n-1] > W: return knapSack(W, wt, val, n-1) # return the maximum of two cases: # (1) nth item included # (2) not included else: return max(val[n-1] + knapSack(W-wt[n-1], wt, val, n-1), knapSack(W, wt, val, n-1)) # Driver program to test above function values = [20, 5, 10, 40, 15, 25] weights = [1, 2, 3, 8, 7, 4] capacity = 10 n = len(values) print(knapSack(capacity, weights, values, n))
import React from 'react'; import cn from 'classnames'; import Header from './components/Header'; import Messages from './components/Messages'; import Sender from './components/Sender'; import QuickButtons from './components/QuickButtons'; import { AnyFunction } from '../../../../utils/types'; import './style.scss'; type Props = { title: string; subtitle: string; senderPlaceHolder: string; showCloseButton: boolean; disabledInput: boolean; autofocus: boolean; className: string; sendMessage: AnyFunction; toggleChat: AnyFunction; profileAvatar?: string; titleAvatar?: string; onQuickButtonClicked?: AnyFunction; onTextInputChange: (event: any) => void; sendButtonAlt: string; showTimeStamp: boolean; showEmoji: boolean; input: string; setInput: AnyFunction; handleSelectEmoji: AnyFunction; handleRoomSelect: (any) => any; currentRoom: string; courseChatRooms: string[]; privateChatRooms: string[]; handleScrollToTop: any; loading: boolean; }; function Conversation({ title, subtitle, senderPlaceHolder, showCloseButton, disabledInput, autofocus, className, sendMessage, toggleChat, profileAvatar, titleAvatar, onQuickButtonClicked, onTextInputChange, sendButtonAlt, showTimeStamp, showEmoji, input, setInput, handleSelectEmoji, handleRoomSelect, currentRoom, courseChatRooms, privateChatRooms, handleScrollToTop, loading }: Props) { return ( <div className={cn('rcw-conversation-container', className)} aria-live="polite"> <Header title={title} subtitle={subtitle} toggleChat={toggleChat} showCloseButton={showCloseButton} titleAvatar={titleAvatar} handleRoomSelect={handleRoomSelect} currentRoom={currentRoom} courseChatRooms={courseChatRooms} privateChatRooms={privateChatRooms} /> <Messages profileAvatar={profileAvatar} showTimeStamp={showTimeStamp} handleScrollToTop={handleScrollToTop} loading={loading} /> <QuickButtons onQuickButtonClicked={onQuickButtonClicked} /> <Sender sendMessage={sendMessage} placeholder={senderPlaceHolder} disabledInput={disabledInput} autofocus={autofocus} onTextInputChange={onTextInputChange} buttonAlt={sendButtonAlt} showEmoji={showEmoji} input={input} setInput={setInput} handleSelectEmoji={handleSelectEmoji} /> </div> ); } export default Conversation;
<reponame>mission-apprentissage/prise-de-rdv<filename>ui/src/pages/admin/widgetParameters/components/EtablissementComponent.js import { createRef, useState, useEffect } from "react"; import * as PropTypes from "prop-types"; import "react-dates/initialize"; import { SingleDatePicker } from "react-dates"; import "react-dates/lib/css/_datepicker.css"; import * as moment from "moment"; import { Box, Text, Flex, EditablePreview, EditableInput, Editable, Button, Grid, Tag, Tooltip, useToast, } from "@chakra-ui/react"; import { Disquette } from "../../../../theme/components/icons"; import { _get, _put } from "../../../../common/httpClient"; import { dayjs } from "../../../../common/dayjs"; /** * @description Etablissement component. * @param {string} id * @returns {JSX.Element} */ const EtablissementComponent = ({ id }) => { const emailDecisionnaireFocusRef = createRef(); const emailDecisionnaireRef = createRef(); const [loading, setLoading] = useState(false); const [optModeLoading, setOptModeLoading] = useState(false); const [etablissement, setEtablissement] = useState(); const [optInActivatedAt, setOptInActivatedAt] = useState(); const [focused, setFocused] = useState(); const toast = useToast(); const optModes = { OPT_IN: "Opt-In", OPT_OUT: "Opt-Out", }; /** * @description Initial fetching. * @return {Promise<void>} */ const fetchData = async () => { try { setLoading(true); const response = await _get(`/api/etablissements/${id}`); setEtablissement(response); setOptInActivatedAt(moment(response.opt_in_activated_at)); } catch (error) { toast({ title: "Une erreur est survenue durant la récupération des informations.", status: "error", isClosable: true, position: "bottom-right", }); } finally { setLoading(false); } }; /** * @description Returns toast common error for etablissement updates. * @return {string | number} */ const putError = () => toast({ title: "Une erreur est survenue durant l'enregistrement.", status: "error", isClosable: true, position: "bottom-right", }); /** * @description Call succes Toast. * @return {string | number} */ const putSuccess = () => toast({ title: "Enregistrement effectué avec succès.", status: "success", isClosable: true, position: "bottom-right", }); useEffect(() => fetchData(), []); /** * @description Update "opt-in" activated. * @param {Date} date * @return {Promise<void>} */ const updateOptInActivedDate = async (date) => { try { setOptInActivatedAt(moment(date)); const response = await _put(`/api/etablissements/${etablissement._id}`, { opt_in_activated_at: dayjs(date).format("YYYY-MM-DD"), opt_mode: "OPT_IN", }); setEtablissement(response); putSuccess(); } catch (error) { putError(); } }; /** * @description Upserts "email_decisionnaire" * @param {string} email * @return {Promise<void>} */ const upsertEmailDecisionnaire = async (email) => { try { const response = await _put(`/api/etablissements/${etablissement._id}`, { email_decisionnaire: email }); setEtablissement(response); putSuccess(); } catch (error) { putError(); } }; /** * @description Enable Opt-in. * @returns {Promise<void>} */ const enableOptIn = async () => { try { setOptModeLoading(true); await _put(`/api/etablissements/${etablissement._id}`, { opt_mode: "OPT_IN" }); window.location.reload(false); } catch (error) { putError(); } finally { setOptModeLoading(false); } }; /** * @description Display a Toast on opt-out click. * @returns {string | number} */ const enableOptOut = () => toast({ title: "Cette fonctionnalité n'a pas été encore implémentée.", status: "info", isClosable: true, position: "bottom-right", }); return ( <Box bg="white" border="1px solid #E0E5ED" borderRadius="4px" mt={10} pb="5" loading={loading}> <Box borderBottom="1px solid #E0E5ED"> <Text fontSize="16px" p={5}> Etablissement </Text> </Box> <Grid templateColumns="repeat(3, 1fr)" gap={5} p="5"> <Box w="100%" h="10"> <Text textStyle="sm" fontWeight="600"> Raison sociale <br /> <br /> <Text as="span" fontWeight="400"> {etablissement?.raison_sociale} </Text> </Text> </Box> <Box w="100%" h="10"> <Text textStyle="sm" fontWeight="600"> SIRET Formateur <br /> <br /> <Text as="span" fontWeight="400"> {etablissement?.siret_formateur} </Text> </Text> </Box> <Box w="100%" h="10"> <Text textStyle="sm" fontWeight="600"> SIRET Gestionnaire <br /> <br /> <Text as="span" fontWeight="400"> {etablissement?.siret_gestionnaire} </Text> </Text> </Box> </Grid> <Grid templateColumns="repeat(3, 1fr)" gap={5} p="5" pt="10"> <Box w="100%" h="10"> <Text textStyle="sm" fontWeight="600"> Adresse <br /> <br /> <Text as="span" fontWeight="400"> {etablissement?.adresse} </Text> </Text> </Box> <Box w="100%" h="10"> <Text textStyle="sm" fontWeight="600"> Localité <br /> <br /> <Text as="span" fontWeight="400"> {etablissement?.localite} </Text> </Text> </Box> <Box w="100%" h="10"> <Text textStyle="sm" fontWeight="600"> Code postal <br /> <br /> <Text as="span" fontWeight="400"> {etablissement?.code_postal} </Text> </Text> </Box> </Grid> <Grid templateColumns="repeat(3, 1fr)" gap={5} p="5" pt="10"> <Box w="100%" h="10"> <Text textStyle="sm" fontWeight="600"> OPT Mode <br /> <br /> {etablissement?.opt_mode === null ? ( <> <Tooltip label="Activer toutes les formations qui ont un mail de contact catalogue." key="opt-in"> <Button variant="primary" fontSize="12px" size="sm" onClick={enableOptIn} isDisabled={optModeLoading}> Activer l'opt-in </Button> </Tooltip> <Tooltip label="Activer l'opt-out pour cet établissement. Un email décisionnaire doit être renseigné." key="opt-out" > <Button variant="primary" fontSize="12px" size="sm" ml="5" onClick={enableOptOut} isDisabled={!etablissement?.email_decisionnaire || optModeLoading} _hover={false} > Activer l'opt-out </Button> </Tooltip> </> ) : ( <Tag bg="#467FCF" size="md" color="white" key="activate"> {optModes[etablissement?.opt_mode]} </Tag> )} </Text> </Box> {etablissement?.opt_in_activated_at && ( <Box w="100%" h="10"> <Text textStyle="sm" fontWeight="600"> Opt-In activated date <br /> <br /> <SingleDatePicker isOutsideRange={() => false} date={optInActivatedAt} onDateChange={updateOptInActivedDate} focused={focused} onFocusChange={({ focused }) => setFocused(focused)} displayFormat={"DD/MM/YYYY"} numberOfMonths={1} /> </Text> </Box> )} {etablissement?.opt_out_invited_at && ( <Box w="100%" h="10"> <Text textStyle="sm" fontWeight="600"> Date d'invitation à l'opt-out <br /> <br /> <Tag bg="#467FCF" size="md" color="white"> {dayjs(etablissement?.opt_out_invited_at).format("DD/MM/YYYY")} </Tag> </Text> </Box> )} {etablissement?.opt_out_activated_at && ( <Box w="100%" h="10"> <Text textStyle="sm" fontWeight="600"> Date d'activation des formations <br /> <br /> <Tag bg="#467FCF" size="md" color="white"> {dayjs(etablissement?.opt_out_activated_at).format("DD/MM/YYYY")} </Tag> </Text> </Box> )} </Grid> <Grid templateColumns="repeat(3, 1fr)" gap={5} p="5" pt="10"> <Box onClick={() => emailDecisionnaireFocusRef.current.focus()}> <Text textStyle="sm" fontWeight="600"> Email décisionnaire <br /> <br /> </Text> <Flex> <Editable defaultValue={etablissement?.email_decisionnaire} style={{ border: "solid #dee2e6 1px", padding: 5, marginRight: 10, borderRadius: 4, minWidth: "70%", }} > <EditablePreview ref={emailDecisionnaireFocusRef} /> <EditableInput ref={emailDecisionnaireRef} type="email" _focus={{ border: "none" }} /> </Editable> <Button RootComponent="a" variant="primary" onClick={() => upsertEmailDecisionnaire(emailDecisionnaireRef.current.value.toLowerCase())} > <Disquette w="16px" h="16px" /> </Button> </Flex> </Box> </Grid> </Box> ); }; EtablissementComponent.propTypes = { id: PropTypes.string.isRequired, }; export default EtablissementComponent;
import sys sys.path.append('../') import json import arbitrage import time from observers import observer class TestObserver(observer.Observer): def opportunity(self, profit, volume, buyprice, kask, sellprice, kbid, perc, weighted_buyprice, weighted_sellprice): print("Time: %.3f" % profit) def main(): arbitrer = arbitrage.Arbitrer() depths = arbitrer.depths = json.load(open("speed-test.json")) start_time = time.time() testobs = TestObserver() arbitrer.observers = [testobs] arbitrer.arbitrage_opportunity("BitstampUSD", depths["BitstampUSD"]["asks"][0], "MtGoxEUR", depths["MtGoxEUR"]["asks"][0]) # FIXME: add asserts elapsed = time.time() - start_time print("Time: %.3f" % elapsed) if __name__ == '__main__': main()
/* * -* *- *- *- *- *- *- * * ** -* -* -* - *- *- *-* - ** - *- - * *- */ /* * _ _ +\ */ /* - | |_ ___ ___ ___ ___ ___ ___ ___ _| |___ ___ ___ ___ + */ /* + | _| _| .'| |_ -| _| -_| | . | -_| | _| -_| /* */ /* * |_| |_| |__,|_|_|___|___|___|_|_|___|___|_|_|___|___| + */ /* - ~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~--~ * */ /* * <NAME> | okruitho | Alpha_1337k *- */ /* -* <NAME> | rvan-hou | robijnvh -+ */ /* * / <NAME> | jbennink | JonasDBB /- */ /* / <NAME> | tvan-cit | Tjobo-Hero * */ /* + <NAME> | rbraaksm | rbraaksm - */ /* *. ._ */ /* *. settings.component.spec. | Created: 2021-09-30 22:01:53 ._ */ /* - Edited on 2021-09-30 22:01:53 by alpha .- */ /* -* *- *- * -* -* -* ** - *-* -* * / -* -*- * /- - -* --*-*++ * -* * */ import { ComponentFixture, TestBed } from '@angular/core/testing'; import { SettingsComponent } from './settings.component'; describe('SettingsComponent', () => { let component: SettingsComponent; let fixture: ComponentFixture<SettingsComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ SettingsComponent ] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(SettingsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
G.def('test/test', function() { return 'test/test.js'; });
#!/usr/bin/env bash # # 设置 Oracle 开机启动: # # vim /etc/oratab # # 修改最后一行: N -> Y # # orcl:/home/oracle/app/oracle/product/11.2.0/dbhome_1:N # orcl:/home/oracle/app/oracle/product/11.2.0/dbhome_1:Y #
#!/bin/sh set -e echo "Starting build-gcl-cltl1-acl2.sh" echo " -- Running in `pwd`" echo " -- Running on `hostname`" echo " -- PATH is $PATH" source $JENKINS_HOME/env.sh ACL2DIR=`pwd` LISP=`which gcl-cltl1` echo "Using LISP = $LISP" echo "Using STARTJOB = `which startjob`" echo "Making ACL2" startjob -c "make acl2 LISP=$LISP &> make.log" \ --name "J_GCL_CLTL1_ACL2" \ --limits "pmem=4gb,nodes=1:ppn=1,walltime=40:00" echo "Building the books." cd acl2-devel/books make ACL2=$ACL2DIR/acl2-devel/saved_acl2 all $MAKEOPTS echo "Build was successful." exit 0
// // ETRImagePickerController.h // // Created by <NAME> on 27/02/14. // Copyright (c) 2014 EastBanc Technologies Russia. All rights reserved. // @import UIKit; @interface ETRImagePickerController : UIImagePickerController + (void)presentImagePickerWithSourceType:(UIImagePickerControllerSourceType)sourceType sender:(UIView *)sender parent:(UIViewController *)viewController completion:(void (^)(UIImage *))completion; @end
<reponame>jsonshen/MyBatisX package org.shenjia.mybatis.paging; public class CUBRIDPagingDecorator extends LimitAndOffsetPagingDecorator { }
<filename>osquery/tables/system/darwin/process_open_files.cpp // Copyright 2004-present Facebook. All Rights Reserved. #include <set> // Keep sys/socket first. #include <sys/socket.h> #include <arpa/inet.h> #include <libproc.h> #include <netinet/in.h> #include <sys/sysctl.h> #include <sys/types.h> #include <unistd.h> #include <osquery/core.h> #include <osquery/filesystem.h> #include <osquery/logger.h> #include <osquery/tables.h> #define IPv6_2_IPv4(v6) (((uint8_t *)((struct in6_addr *)v6)->s6_addr) + 12) namespace osquery { namespace tables { // From processes.cpp std::set<int> getProcList(); struct OpenFile { std::string local_path; std::string file_type; std::string remote_host; std::string remote_port; std::string local_host; std::string local_port; }; std::vector<OpenFile> getOpenFiles(int pid) { std::vector<OpenFile> open_files; int sz; int bufsize = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, 0, 0); if (bufsize == -1) { LOG(ERROR) << "An error occurred retrieving the open files " << pid; return open_files; } proc_fdinfo fd_infos[bufsize / PROC_PIDLISTFD_SIZE]; int num_fds = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, fd_infos, sizeof(fd_infos)); struct vnode_fdinfowithpath vnode_info; struct socket_fdinfo socket_info; void *la = NULL, *fa = NULL; int lp, fp, v4mapped; char buf[1024]; for (int i = 0; i < num_fds; ++i) { OpenFile row; auto fd_info = fd_infos[i]; switch (fd_info.proc_fdtype) { case PROX_FDTYPE_VNODE: row.file_type = "file"; sz = proc_pidfdinfo(pid, fd_info.proc_fd, PROC_PIDFDVNODEPATHINFO, &vnode_info, PROC_PIDFDVNODEPATHINFO_SIZE); if (sz > 0) { row.local_path = std::string(vnode_info.pvip.vip_path); } break; case PROX_FDTYPE_SOCKET: // Its a socket sz = proc_pidfdinfo(pid, fd_info.proc_fd, PROC_PIDFDSOCKETINFO, &socket_info, PROC_PIDFDSOCKETINFO_SIZE); if (sz > 0) { switch (socket_info.psi.soi_family) { case AF_INET: if (socket_info.psi.soi_kind == SOCKINFO_TCP) { row.file_type = "TCP"; la = &socket_info.psi.soi_proto.pri_tcp.tcpsi_ini.insi_laddr.ina_46 .i46a_addr4; lp = ntohs(socket_info.psi.soi_proto.pri_tcp.tcpsi_ini.insi_lport); fa = &socket_info.psi.soi_proto.pri_tcp.tcpsi_ini.insi_faddr.ina_46 .i46a_addr4; fp = ntohs(socket_info.psi.soi_proto.pri_tcp.tcpsi_ini.insi_fport); } else { row.file_type = "UDP"; la = &socket_info.psi.soi_proto.pri_in.insi_laddr.ina_46.i46a_addr4; lp = ntohs(socket_info.psi.soi_proto.pri_in.insi_lport); fa = &socket_info.psi.soi_proto.pri_in.insi_faddr.ina_46.i46a_addr4; fp = ntohs(socket_info.psi.soi_proto.pri_in.insi_fport); } row.local_host = std::string(inet_ntop(AF_INET, &(((struct sockaddr_in *)la)->sin_addr), buf, sizeof(buf))); row.local_port = boost::lexical_cast<std::string>(lp); row.remote_host = std::string(inet_ntop(AF_INET, &(((struct sockaddr_in *)fa)->sin_addr), buf, sizeof(buf))); row.remote_port = boost::lexical_cast<std::string>(fp); break; case AF_INET6: if (socket_info.psi.soi_kind == SOCKINFO_TCP) { row.file_type = "TCP6"; la = &socket_info.psi.soi_proto.pri_tcp.tcpsi_ini.insi_laddr.ina_6; lp = ntohs(socket_info.psi.soi_proto.pri_tcp.tcpsi_ini.insi_lport); fa = &socket_info.psi.soi_proto.pri_tcp.tcpsi_ini.insi_faddr.ina_6; fp = ntohs(socket_info.psi.soi_proto.pri_tcp.tcpsi_ini.insi_fport); if ((socket_info.psi.soi_proto.pri_tcp.tcpsi_ini.insi_vflag & INI_IPV4) != 0) { v4mapped = 1; } } else { row.file_type = "UDP6"; la = &socket_info.psi.soi_proto.pri_in.insi_laddr.ina_6; lp = ntohs(socket_info.psi.soi_proto.pri_in.insi_lport); fa = &socket_info.psi.soi_proto.pri_in.insi_faddr.ina_6; fp = ntohs(socket_info.psi.soi_proto.pri_in.insi_fport); if ((socket_info.psi.soi_proto.pri_in.insi_vflag & INI_IPV4) != 0) { v4mapped = 1; } } if (v4mapped) { // Adjust IPv4 addresses mapped in IPv6 addresses. if (la) { la = (struct sockaddr *)IPv6_2_IPv4(la); } if (fa) { fa = (struct sockaddr *)IPv6_2_IPv4(fa); } } row.local_host = std::string(inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)la)->sin6_addr), buf, sizeof(buf))); row.local_port = boost::lexical_cast<std::string>(lp); row.remote_host = std::string(inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)fa)->sin6_addr), buf, sizeof(buf))); row.remote_port = boost::lexical_cast<std::string>(fp); break; default: break; } } break; default: break; } open_files.push_back(row); } return open_files; } QueryData genProcessOpenFiles(QueryContext &context) { QueryData results; auto pidlist = getProcList(); for (auto &pid : pidlist) { if (!context.constraints["pid"].matches<int>(pid)) { // Optimize by not searching when a pid is a constraint. continue; } auto open_files = getOpenFiles(pid); for (auto &open_file : open_files) { Row r; r["pid"] = INTEGER(pid); r["file_type"] = open_file.file_type; r["local_path"] = open_file.local_path; r["local_host"] = open_file.local_host; r["local_port"] = open_file.local_port; r["remote_host"] = open_file.remote_host; r["remote_port"] = open_file.remote_port; results.push_back(r); } } return results; } } }
<reponame>vadi2/codeql<filename>javascript/extractor/src/com/semmle/js/ast/Super.java package com.semmle.js.ast; /** * A <code>super</code> expression, appearing either as the callee of a super constructor call or as * the receiver of a super method call. */ public class Super extends Expression { public Super(SourceLocation loc) { super("Super", loc); } @Override public <Q, A> A accept(Visitor<Q, A> v, Q q) { return v.visit(this, q); } }
// flatten.rs pub fn flatten_list(input: &[Vec<i32>]) -> Vec<i32> { let mut result = Vec::new(); for item in input { for &val in item { result.push(val); } } result }
<reponame>vaniot-s/sentry export enum RuleType { PATTERN = 'pattern', CREDITCARD = 'creditcard', PASSWORD = 'password', IP = 'ip', IMEI = 'imei', EMAIL = 'email', UUID = 'uuid', PEMKEY = 'pemkey', URLAUTH = 'url_auth', USSSN = 'us_ssn', USER_PATH = 'userpath', MAC = 'mac', ANYTHING = 'anything', } export enum MethodType { MASK = 'mask', REMOVE = 'remove', HASH = 'hash', REPLACE = 'replace', } export enum EventIdStatus { LOADING = 'loading', INVALID = 'invalid', NOT_FOUND = 'not_found', LOADED = 'loaded', ERROR = 'error', } export enum SourceSuggestionType { VALUE = 'value', UNARY = 'unary', BINARY = 'binary', STRING = 'string', } export enum RequestError { Unknown = 'unknown', InvalidSelector = 'invalid-selector', RegexParse = 'regex-parse', } export type SourceSuggestion = { type: SourceSuggestionType; value: string; description?: string; examples?: Array<string>; }; type RuleBase = { id: number; source: string; }; export type RuleDefault = RuleBase & { type: | RuleType.CREDITCARD | RuleType.PASSWORD | RuleType.IP | RuleType.IMEI | RuleType.EMAIL | RuleType.UUID | RuleType.PEMKEY | RuleType.URLAUTH | RuleType.USSSN | RuleType.USER_PATH | RuleType.MAC | RuleType.ANYTHING; method: MethodType.MASK | MethodType.REMOVE | MethodType.HASH; }; export type RulePattern = RuleBase & { type: RuleType.PATTERN; pattern: string; } & Pick<RuleDefault, 'method'>; export type RuleReplace = RuleBase & { method: MethodType.REPLACE; placeholder?: string; } & Pick<RuleDefault, 'type'>; export type KeysOfUnion<T> = T extends any ? keyof T : never; export type RuleReplaceAndPattern = Omit<RulePattern, 'method'> & Omit<RuleReplace, 'type'>; export type Rule = RuleDefault | RuleReplace | RulePattern | RuleReplaceAndPattern; export type EventId = { value: string; status?: EventIdStatus; }; type PiiConfigDefault = { type: RuleDefault['type']; redaction: { method: RuleDefault['method']; }; }; type PiiConfigReplace = { type: RuleReplace['type']; redaction: { method: RuleReplace['method']; text?: string; }; }; type PiiConfigPattern = { type: RulePattern['type']; pattern: string; redaction: { method: RulePattern['method']; }; }; type PiiConfigRelaceAndPattern = Omit<PiiConfigPattern, 'redaction'> & Pick<PiiConfigReplace, 'redaction'>; export type PiiConfig = | PiiConfigDefault | PiiConfigPattern | PiiConfigReplace | PiiConfigRelaceAndPattern; export type Applications = Record<string, Array<string>>; export type Errors = Partial<Record<KeysOfUnion<Rule>, string>>;
import { PipeTransform, Injectable, ArgumentMetadata, NotFoundException } from '@nestjs/common'; @Injectable() export class ObjectIdPipe implements PipeTransform { transform(value: string, metadata: ArgumentMetadata) { if(!value.match(/^[0-9a-fA-F]{24}$/)){ throw new NotFoundException(`Movie with ID : ${value} not found.`) } return value; } }
#!/bin/bash set -e set -x mount_dir=$1
<filename>db/migrate/20150514163912_create_family_table.rb class CreateFamilyTable < ActiveRecord::Migration def change create_table :families do |t| t.integer :child_id t.integer :parent_id t.timestamps null:false end end end
<reponame>csyuser/wheelUI<filename>src/app.js import Vue from 'vue' import Button from './button.vue' import Icon from './icon' import ButtonGroup from './button-group' import Input from './input' import Row from './row' import Col from './col' import Layout from './layout' import Header from './header' import Footer from './footer' import Side from './side' import Content from './content' import Toast from './toast' import plugin from './plugin' import Tabs from './tabs' import TabsHead from './tabs-head' import TabsBody from './tabs-body' import TabsItem from './tabs-item' import TabsPane from './tabs-pane' import Popover from './popover' import Collapse from './collapse' import CollapseItem from './collapse-item' Vue.component('w-button', Button) Vue.component('w-icon', Icon) Vue.component('w-button-group', ButtonGroup) Vue.component('w-input', Input) Vue.component('w-row', Row) Vue.component('w-col', Col) Vue.component('w-layout', Layout) Vue.component('w-header', Header) Vue.component('w-footer', Footer) Vue.component('w-side', Side) Vue.component('w-content', Content) Vue.component('w-toast', Toast) Vue.component('w-tabs', Tabs) Vue.component('w-tabs-head', TabsHead) Vue.component('w-tabs-body', TabsBody) Vue.component('w-tabs-item', TabsItem) Vue.component('w-tabs-pane', TabsPane) Vue.component('w-popover', Popover) Vue.component('w-collapse', Collapse) Vue.component('w-collapse-item', CollapseItem) Vue.use(plugin) new Vue({ el: '#app', data: { loading1: false, selected:'sports', selectedTab:['1','3'] }, methods:{ inputChange(e){ // console.log(e) }, toastTop(){ this.$toast('我是toast信息 上',{closeButton:{text: 'ok啦',callback:this.log},position:'top'}) }, toastMiddle(){ this.$toast('我是toast信息 中',{closeButton:{text: 'ok',callback:this.log},position:'middle'}) }, toastBottom(){ this.$toast('我是toast信息 下',{closeButton:{text: 'ok啦',callback:this.log},position:'bottom'}) }, log(){ console.log('执行了关闭的callback') }, } })
CREATE PROCEDURE sp_department_report (in_dept_id INTEGER, OUT sales_total DECIMAL(8,2)) BEGIN SELECT employee_id, surname, firstname, address1, address2, salary FROM employees WHERE department_id = in_dept_id; SELECT customer_id, customer_name, address1, address2, zipcode FROM customers WHERE sales_rep_id IN (SELECT employee_id FROM employees WHERE department_id = in_dept_id); SELECT SUM(sale_value) INTO sales_total FROM sales WHERE customer_id IN (SELECT customer_id FROM customers WHERE sales_rep_id IN (SELECT employee_id FROM employees WHERE department_id = in_dept_id)); END
# Remove all entries for a given version number version=$1 dbname=${2:-spase-model} # Create SQL commands echo "delete from dictionary where Version = '$version';" > temp.sqlite echo "delete from list where Version = '$version';" >> temp.sqlite echo "delete from member where Version = '$version';" >> temp.sqlite echo "delete from type where Version = '$version';" >> temp.sqlite echo "delete from ontology where Version = '$version';" >> temp.sqlite # Run SQL commands cat temp.sqlite | sqlite3 $dbname".db" # Clean-up rm temp.sqlite
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by <NAME>, <EMAIL>, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Opus(AutotoolsPackage): """Opus is a totally open, royalty-free, highly versatile audio codec.""" homepage = "http://opus-codec.org/" url = "http://downloads.xiph.org/releases/opus/opus-1.1.4.tar.gz" version('1.1.4', 'a2c09d995d0885665ff83b5df2505a5f') version('1.1.3', '32bbb6b557fe1b6066adc0ae1f08b629') version('1.1.2', '1f08a661bc72930187893a07f3741a91') version('1.1.1', 'cfb354d4c65217ca32a762f8ab15f2ac') version('1.1', 'c5a8cf7c0b066759542bc4ca46817ac6') version('1.0.3', '86eedbd3c5a0171d2437850435e6edff') version('1.0.2', 'c503ad05a59ddb44deab96204401be03') version('1.0.1', 'bbac19996957b404a1139816e2f357f5') version('1.0.0', 'ec3ff0a16d9ad8c31a8856d13d97b155') version('0.9.14', 'c7161b247a8437ae6b0f11dd872e69e8') version('0.9.10', 'afbda2fd20dc08e6075db0f60297a137') version('0.9.9', '0c18f0aac37f1ed955f5d694ddd88000') version('0.9.8', '76c1876eae9169dee808ff4710d847cf') version('0.9.7', '49834324ab618105cf112e161770b422') version('0.9.6', '030556bcaebb241505f8577e92abe6d4') version('0.9.5', '6bec090fd28996da0336e165b153ebd8') version('0.9.3', '934226d4f572d01c5848bd70538248f5') version('0.9.2', '8b9047956c4a781e05d3ac8565cd28f5') version('0.9.1', 'f58214e530928aa3db1dec217d5dfcd4') version('0.9.0', '8a729db587430392e64280a499e9d061') depends_on('libvorbis')
#!/usr/bin/env bash mkdir -p /vagrant/logs/ /vagrant/build/ exec 2>/vagrant/logs/build.err # update or clone vyos-build if [ -d /home/vagrant/vyos-build ]; then pushd /home/vagrant/vyos-build git checkout . git pull origin current popd else git clone -b current https://github.com/vyos/vyos-build /home/vagrant/vyos-build fi pushd /home/vagrant/vyos-build ./configure --architecture amd64 --build-by "kikitux@gmail.com" KERNEL=`jq -r .kernel_version /home/vagrant/vyos-build/data/defaults.json` # clone linux if [ ! -d /home/vagrant/vyos-build/packages/linux-kernel/linux ]; then git clone https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git /home/vagrant/vyos-build/packages/linux-kernel/linux fi # check for kernel packages pushd /vagrant/build/ ls linux-headers-${KERNEL}-amd64-vyos_${KERNEL}-1_amd64.deb linux-image-${KERNEL}-amd64-vyos_${KERNEL}-1_amd64.deb linux-libc-dev_${KERNEL}-1_amd64.deb linux-tools-${KERNEL}-amd64-vyos_${KERNEL}-1_amd64.deb if [ $? -ne 0 ]; then # delete old kernel if present rm -f /home/vagrant/vyos-build/packages/linux-kernel/linux-* || true # we are building kernel, lets delete any leftover iso rm -f /home/vagrant/vyos-build/build/{live-image-amd64.*,*iso} || true rm -f /vagrant/build/vyos-*iso || true pushd /home/vagrant/vyos-build/packages/linux-kernel/linux # change to kernel version tag defined in defaults.json if [ "`git describe --exact-match --tags $(git log -n1 --pretty='%h')`" != "v${KERNEL}" ]; then git fetch origin "refs/tags/v${KERNEL}:refs/tags/v${KERNEL}" git checkout --force v${KERNEL} fi pushd /home/vagrant/vyos-build/packages/linux-kernel # add custom kernel configuration cp x86_64_vyos_defconfig .config ./linux/scripts/kconfig/merge_config.sh -m .config /vagrant/config_btrfs.fragment cp .config x86_64_vyos_defconfig bash -x ./build-kernel.sh cp linux-headers-${KERNEL}-amd64-vyos_${KERNEL}-1_amd64.deb linux-image-${KERNEL}-amd64-vyos_${KERNEL}-1_amd64.deb linux-libc-dev_${KERNEL}-1_amd64.deb linux-tools-${KERNEL}-amd64-vyos_${KERNEL}-1_amd64.deb /vagrant/build/ popd fi # check for iso if [ ! -f /vagrant/build/vyos-1.4-rolling-${KERNEL}-amd64.iso ] ; then pushd /home/vagrant/vyos-build # we building an iso, lets remove old images rm -f build/{live-image-amd64.*,*iso} || true sudo make iso cp -a /home/vagrant/vyos-build/build/live-image-amd64.hybrid.iso /vagrant/build/vyos-1.4-rolling-${KERNEL}-amd64.iso popd fi # kernel packages if [ ! -f /vagrant/build/linux-${KERNEL}-amd64-vyos_${KERNEL}.orig.tar.gz ]; then pushd /home/vagrant/vyos-build/packages/linux-kernel/linux/ source ../kernel-vars make deb-pkg BUILD_TOOLS=1 LOCALVERSION=${KERNEL_SUFFIX} KDEB_PKGVERSION=${KERNEL_VERSION}-1 -j $(getconf _NPROCESSORS_ONLN) cp /home/vagrant/vyos-build/packages/linux-kernel/linux-${KERNEL}-amd64-vyos_${KERNEL}.orig.tar.gz /vagrant/build/ fi pushd /vagrant/build shasum -a 256 linux-* vyos-*iso | tee SHA256SUMS
ROOT_DIR=run_median_results mkdir -p ${ROOT_DIR} NUM_EPOCHS=100 L=4 M=5 for N in 5 do for METHOD in deterministic_neuralsort do GRID_SEARCH_RESULTS_DIR="N_${N}_${METHOD}" mkdir ${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR} for LR in 0.001 do for TAU in 1024 do for REPETITION in 0 do OUTPUT_FILE="${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR}/N_${N}_${METHOD}_TAU_${TAU}_LR_${LR}_E_${NUM_EPOCHS}_REP_${REPETITION}.txt" python3 run_median.py --num_epochs ${NUM_EPOCHS} --l=${L} --lr=${LR} --M=${M} --n=${N} --tau=${TAU} --method=${METHOD} --repetition=${REPETITION} 2>&1 | tee ${OUTPUT_FILE} done done done done done NUM_EPOCHS=100 L=4 M=5 for N in 5 do for METHOD in stochastic_neuralsort do GRID_SEARCH_RESULTS_DIR="N_${N}_${METHOD}" mkdir ${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR} for LR in 0.001 do for TAU in 2048 do for REPETITION in 0 do OUTPUT_FILE="${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR}/N_${N}_${METHOD}_TAU_${TAU}_LR_${LR}_E_${NUM_EPOCHS}_REP_${REPETITION}.txt" python3 run_median.py --num_epochs ${NUM_EPOCHS} --l=${L} --lr=${LR} --M=${M} --n=${N} --tau=${TAU} --method=${METHOD} --repetition=${REPETITION} 2>&1 | tee ${OUTPUT_FILE} done done done done done NUM_EPOCHS=100 L=4 M=5 for N in 5 do for METHOD in deterministic_softsort do GRID_SEARCH_RESULTS_DIR="N_${N}_${METHOD}" mkdir ${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR} for LR in 0.001 do for TAU in 2048 do for REPETITION in 0 do OUTPUT_FILE="${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR}/N_${N}_${METHOD}_TAU_${TAU}_LR_${LR}_E_${NUM_EPOCHS}_REP_${REPETITION}.txt" python3 run_median.py --num_epochs ${NUM_EPOCHS} --l=${L} --lr=${LR} --M=${M} --n=${N} --tau=${TAU} --method=${METHOD} --repetition=${REPETITION} 2>&1 | tee ${OUTPUT_FILE} done done done done done NUM_EPOCHS=100 L=4 M=5 for N in 5 do for METHOD in stochastic_softsort do GRID_SEARCH_RESULTS_DIR="N_${N}_${METHOD}" mkdir ${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR} for LR in 0.001 do for TAU in 4096 do for REPETITION in 0 do OUTPUT_FILE="${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR}/N_${N}_${METHOD}_TAU_${TAU}_LR_${LR}_E_${NUM_EPOCHS}_REP_${REPETITION}.txt" python3 run_median.py --num_epochs ${NUM_EPOCHS} --l=${L} --lr=${LR} --M=${M} --n=${N} --tau=${TAU} --method=${METHOD} --repetition=${REPETITION} 2>&1 | tee ${OUTPUT_FILE} done done done done done NUM_EPOCHS=100 L=4 M=5 for N in 9 do for METHOD in deterministic_neuralsort do GRID_SEARCH_RESULTS_DIR="N_${N}_${METHOD}" mkdir ${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR} for LR in 0.001 do for TAU in 512 do for REPETITION in 0 do OUTPUT_FILE="${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR}/N_${N}_${METHOD}_TAU_${TAU}_LR_${LR}_E_${NUM_EPOCHS}_REP_${REPETITION}.txt" python3 run_median.py --num_epochs ${NUM_EPOCHS} --l=${L} --lr=${LR} --M=${M} --n=${N} --tau=${TAU} --method=${METHOD} --repetition=${REPETITION} 2>&1 | tee ${OUTPUT_FILE} done done done done done NUM_EPOCHS=100 L=4 M=5 for N in 9 do for METHOD in stochastic_neuralsort do GRID_SEARCH_RESULTS_DIR="N_${N}_${METHOD}" mkdir ${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR} for LR in 0.001 do for TAU in 512 do for REPETITION in 0 do OUTPUT_FILE="${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR}/N_${N}_${METHOD}_TAU_${TAU}_LR_${LR}_E_${NUM_EPOCHS}_REP_${REPETITION}.txt" python3 run_median.py --num_epochs ${NUM_EPOCHS} --l=${L} --lr=${LR} --M=${M} --n=${N} --tau=${TAU} --method=${METHOD} --repetition=${REPETITION} 2>&1 | tee ${OUTPUT_FILE} done done done done done NUM_EPOCHS=100 L=4 M=5 for N in 9 do for METHOD in deterministic_softsort do GRID_SEARCH_RESULTS_DIR="N_${N}_${METHOD}" mkdir ${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR} for LR in 0.001 do for TAU in 2048 do for REPETITION in 0 do OUTPUT_FILE="${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR}/N_${N}_${METHOD}_TAU_${TAU}_LR_${LR}_E_${NUM_EPOCHS}_REP_${REPETITION}.txt" python3 run_median.py --num_epochs ${NUM_EPOCHS} --l=${L} --lr=${LR} --M=${M} --n=${N} --tau=${TAU} --method=${METHOD} --repetition=${REPETITION} 2>&1 | tee ${OUTPUT_FILE} done done done done done NUM_EPOCHS=100 L=4 M=5 for N in 9 do for METHOD in stochastic_softsort do GRID_SEARCH_RESULTS_DIR="N_${N}_${METHOD}" mkdir ${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR} for LR in 0.001 do for TAU in 2048 do for REPETITION in 0 do OUTPUT_FILE="${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR}/N_${N}_${METHOD}_TAU_${TAU}_LR_${LR}_E_${NUM_EPOCHS}_REP_${REPETITION}.txt" python3 run_median.py --num_epochs ${NUM_EPOCHS} --l=${L} --lr=${LR} --M=${M} --n=${N} --tau=${TAU} --method=${METHOD} --repetition=${REPETITION} 2>&1 | tee ${OUTPUT_FILE} done done done done done NUM_EPOCHS=100 L=4 M=5 for N in 15 do for METHOD in deterministic_neuralsort do GRID_SEARCH_RESULTS_DIR="N_${N}_${METHOD}" mkdir ${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR} for LR in 0.001 do for TAU in 1024 do for REPETITION in 0 do OUTPUT_FILE="${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR}/N_${N}_${METHOD}_TAU_${TAU}_LR_${LR}_E_${NUM_EPOCHS}_REP_${REPETITION}.txt" python3 run_median.py --num_epochs ${NUM_EPOCHS} --l=${L} --lr=${LR} --M=${M} --n=${N} --tau=${TAU} --method=${METHOD} --repetition=${REPETITION} 2>&1 | tee ${OUTPUT_FILE} done done done done done NUM_EPOCHS=100 L=4 M=5 for N in 15 do for METHOD in stochastic_neuralsort do GRID_SEARCH_RESULTS_DIR="N_${N}_${METHOD}" mkdir ${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR} for LR in 0.001 do for TAU in 4096 do for REPETITION in 0 do OUTPUT_FILE="${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR}/N_${N}_${METHOD}_TAU_${TAU}_LR_${LR}_E_${NUM_EPOCHS}_REP_${REPETITION}.txt" python3 run_median.py --num_epochs ${NUM_EPOCHS} --l=${L} --lr=${LR} --M=${M} --n=${N} --tau=${TAU} --method=${METHOD} --repetition=${REPETITION} 2>&1 | tee ${OUTPUT_FILE} done done done done done NUM_EPOCHS=100 L=4 M=5 for N in 15 do for METHOD in deterministic_softsort do GRID_SEARCH_RESULTS_DIR="N_${N}_${METHOD}" mkdir ${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR} for LR in 0.001 do for TAU in 256 do for REPETITION in 0 do OUTPUT_FILE="${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR}/N_${N}_${METHOD}_TAU_${TAU}_LR_${LR}_E_${NUM_EPOCHS}_REP_${REPETITION}.txt" python3 run_median.py --num_epochs ${NUM_EPOCHS} --l=${L} --lr=${LR} --M=${M} --n=${N} --tau=${TAU} --method=${METHOD} --repetition=${REPETITION} 2>&1 | tee ${OUTPUT_FILE} done done done done done NUM_EPOCHS=100 L=4 M=5 for N in 15 do for METHOD in stochastic_softsort do GRID_SEARCH_RESULTS_DIR="N_${N}_${METHOD}" mkdir ${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR} for LR in 0.001 do for TAU in 2048 do for REPETITION in 0 do OUTPUT_FILE="${ROOT_DIR}/${GRID_SEARCH_RESULTS_DIR}/N_${N}_${METHOD}_TAU_${TAU}_LR_${LR}_E_${NUM_EPOCHS}_REP_${REPETITION}.txt" python3 run_median.py --num_epochs ${NUM_EPOCHS} --l=${L} --lr=${LR} --M=${M} --n=${N} --tau=${TAU} --method=${METHOD} --repetition=${REPETITION} 2>&1 | tee ${OUTPUT_FILE} done done done done done
require_relative '../diagram_converter' require 'delegate' require 'uri' module Asciidoctor module Diagram # @private class PlantUmlConverter include DiagramConverter CLASSPATH_ENV = 'DIAGRAM_PLANTUML_CLASSPATH' LIB_DIR = File.expand_path('../..', File.dirname(__FILE__)) PLANTUML_JARS = if ENV.has_key?(CLASSPATH_ENV) ENV[CLASSPATH_ENV].split(File::PATH_SEPARATOR) else begin require 'asciidoctor-diagram/plantuml/classpath' ::Asciidoctor::Diagram::PlantUmlClasspath::JAR_FILES rescue LoadError raise "Could not load PlantUML. Eiter require 'asciidoctor-diagram-plantuml' or specify the location of the PlantUML JAR(s) using the 'DIAGRAM_PLANTUML_CLASSPATH' environment variable." end end Java.classpath.concat Dir[File.join(File.dirname(__FILE__), '*.jar')].freeze Java.classpath.concat PLANTUML_JARS def wrap_source(source) PlantUMLPreprocessedSource.new(source, self.class.tag) end def supported_formats [:png, :svg, :txt, :atxt, :utxt] end def collect_options(source) { :size_limit => source.attr('size-limit', '4096') } end def convert(source, format, options) Java.load code = source.code case format when :png mime_type = 'image/png' when :svg mime_type = 'image/svg+xml' when :txt, :utxt mime_type = 'text/plain;charset=utf-8' when :atxt mime_type = 'text/plain' else raise "Unsupported format: #{format}" end headers = { 'Accept' => mime_type } size_limit = options[:size_limit] if size_limit headers['X-PlantUML-SizeLimit'] = size_limit end dot = source.find_command('dot', :alt_attrs => ['graphvizdot'], :raise_on_error => false) if dot headers['X-Graphviz'] = ::Asciidoctor::Diagram::Platform.host_os_path(dot) end response = Java.send_request( :url => '/plantuml', :body => code, :headers => headers ) unless response[:code] == 200 raise Java.create_error("PlantUML image generation failed", response) end response[:body] end end class UmlConverter < PlantUmlConverter def self.tag 'uml' end end class SaltConverter < PlantUmlConverter def self.tag 'salt' end end class PlantUMLPreprocessedSource < SimpleDelegator def initialize(source, tag) super(source) @tag = tag end def code @code ||= load_code end def load_code Java.load code = __getobj__.code code = "@start#{@tag}\n#{code}\n@end#{@tag}" unless code.index("@start") && code.index("@end") headers = {} config_file = attr('plantumlconfig', nil, true) || attr('config') if config_file headers['X-PlantUML-Config'] = File.expand_path(config_file, base_dir) end headers['X-PlantUML-Basedir'] = Platform.native_path(File.expand_path(base_dir)) include_dir = attr('plantuml-includedir', nil, true) || attr('includedir') if include_dir headers['X-PlantUML-IncludeDir'] = Platform.native_path(File.expand_path(include_dir, base_dir)) end response = Java.send_request( :url => '/plantumlpreprocessor', :body => code, :headers => headers ) unless response[:code] == 200 raise Java.create_error("PlantUML preprocessing failed", response) end code = response[:body] code.force_encoding(Encoding::UTF_8) code end end end end
#!/bin/bash DIRECTORY="./resource/Ensembl" FILENAME="mart_export.txt" if [ -f "${DIRECTORY}/${FILENAME}" ]; then # Control will enter here if that file exists. echo "[Ensembl] file '${DIRECTORY}/${FILENAME}' exists; skip downloading" else wget -O ${FILENAME} 'http://grch37.ensembl.org/biomart/martservice/results?query=<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE Query><Query virtualSchemaName="default" formatter="TSV" header="1" uniqueRows="0" count="" datasetConfigVersion="0.6"><Dataset name="hsapiens_gene_ensembl" interface="default"><Filter name="chromosome_name" value="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,X,Y"/><Attribute name="chromosome_name"/><Attribute name="transcript_start"/><Attribute name="transcript_end"/><Attribute name="transcription_start_site"/><Attribute name="strand"/><Attribute name="ensembl_gene_id"/><Attribute name="external_gene_name"/><Attribute name="start_position"/><Attribute name="end_position"/><Attribute name="ensembl_transcript_id"/><Attribute name="external_transcript_name"/></Dataset></Query>' mv ${FILENAME} ${DIRECTORY} fi Rscript vertex_ensembl.R echo "[Ensembl] done!"
#!/bin/bash val=$(cat /usr/local/hadoop/etc/hadoop/capacity-scheduler.xml | grep -oPm1 "(?<=<name>yarn.scheduler.capacity.maximum-am-resource-percent</name><value>)[^<]+") oldval=$val # "up", "down", or "set" policy=$1 interval=$2 date +%s | awk '{print "Time(s) " $1}' | tee -a /self-balancing/valueCapacitySchedulerLog echo $val | awk '{print "Value " $1}' | tee -a /self-balancing/valueCapacitySchedulerLog if [ "$policy" = "up" ] then val=$(echo "$val + $interval" | bc) else if [ "$policy" = "down" ] then val=$(echo "$val - $interval" | bc) else val=$interval fi fi if [ $(echo "$val >= 1" | bc) -eq 1 ] then val=1 fi if [ $(echo "$val <= 0.1" | bc) -eq 1 ] then val=.1 fi date +%s | awk '{print "Time(s) " $1}' | tee -a /self-balancing/valueCapacitySchedulerLog echo $val | awk '{print "Value " $1}' | tee -a /self-balancing/valueCapacitySchedulerLog echo " " | tee -a /self-balancing/valueCapacitySchedulerLog if [ "$oldval" != "$val" ] then sed -i "s|\(<name>yarn.scheduler.capacity.maximum-am-resource-percent</name><value>\)[^<>]*\(</value>\)|\1${val}\2|g" /usr/local/hadoop/etc/hadoop/capacity-scheduler.xml /usr/local/hadoop/bin/yarn rmadmin -refreshQueues fi
// Function to convert gyroscope readings from millidegrees per second (mdps) to degrees per second (dps) static double mdps_to_dps(double gyro_in_mdps) { return gyro_in_mdps / 1000.0; }
function generateRandomString(length) { let result = ''; let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let charactersLength = characters.length; for (let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } console.log(generateRandomString(10));
function LoadingPage() { this.dotAmount = 0; this.dotInterval = null; this.init = function init() { this.dotInterval = setInterval(function() { if(this.dotAmount < 3) { $("#loadingTitle").append("."); this.dotAmount++; } else { $("#loadingTitle").text("Loading"); this.dotAmount = 0; } }, 500); } this.hide = function hide() { clearInterval(this.dotInterval); //Wait for lag to stop and fade setTimeout(function() { $("#loadingPage").fadeOut(500); }, 800); } this.setText = function setText(text) { $("#loadingDesc").text(text); } } var LoadingPage = new LoadingPage();
def generate_dependency_report(dependencies): report = "Dependency Report:\n" for dep in dependencies: report += f"- Name: {dep['name']}\n" report += f" Artifact: {dep['artifact']}\n" report += f" Artifact SHA-256: {dep['artifact_sha256']}\n" report += f" Source JAR SHA-256: {dep['srcjar_sha256']}\n" report += f" Dependencies: {', '.join(dep['deps'])}\n" return report
public class Welcome { public static void main(String args[]) { String name = args[0]; System.out.println("Welcome " + name + "!"); } }
#!/bin/sh set -e if [ -z "$1" ]; then echo "No pull request ID was specified." exit 1 fi git fetch https://github.com/thelounge/lounge.git refs/pull/${1}/head git checkout FETCH_HEAD npm install npm run build npm test || true npm start
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_BASE_CERT_TEST_UTIL_H_ #define NET_BASE_CERT_TEST_UTIL_H_ #include <string> #include "base/memory/ref_counted.h" #include "net/base/x509_cert_types.h" #include "net/base/x509_certificate.h" class FilePath; namespace net { class EVRootCAMetadata; CertificateList CreateCertificateListFromFile(const FilePath& certs_dir, const std::string& cert_file, int format); // Imports a certificate file in the directory net::GetTestCertsDirectory() // returns. // |certs_dir| represents the test certificates directory. |cert_file| is the // name of the certificate file. If cert_file contains multiple certificates, // the first certificate found will be returned. scoped_refptr<X509Certificate> ImportCertFromFile(const FilePath& certs_dir, const std::string& cert_file); // ScopedTestEVPolicy causes certificates marked with |policy|, issued from a // root with the given fingerprint, to be treated as EV. |policy| is expressed // as a string of dotted numbers: i.e. "1.2.3.4". // This should only be used in unittests as adding a CA twice causes a CHECK // failure. class ScopedTestEVPolicy { public: ScopedTestEVPolicy(EVRootCAMetadata* ev_root_ca_metadata, const SHA1HashValue& fingerprint, const char* policy); ~ScopedTestEVPolicy(); private: SHA1HashValue fingerprint_; EVRootCAMetadata* const ev_root_ca_metadata_; }; } // namespace net #endif // NET_BASE_CERT_TEST_UTIL_H_
<gh_stars>0 import lowerCaseFirstChar from '../util/lowerCaseFirstChar'; export default function defineMessage( className, categoryName, baseMessageClass, initialize) { const typeName = lowerCaseFirstChar(className), constructor = function (...args) { let ret = this; if (this instanceof constructor) { throw new Error(`Message constructor '${className}' must be ` + "called without 'new' operator"); } if (!(this instanceof constructor)) { ret = Object.create(constructor.prototype); ret.type = typeName; if (categoryName) { ret.category = categoryName; } const initResult = initialize(...args); if (initResult === null) { // nothing to do } else if (typeof initResult ==='object') { Object.assign(ret, initResult); } else if (typeof initResult === 'function') { ret.apply = initResult; } else { throw new Error('The initialization function of message type ' + `'${className}' has returned an invalid value`); } } return ret; }; constructor.prototype = Object.create(baseMessageClass.prototype); constructor.prototype.toString = () => `#<Message instance of type '${className}'>`; constructor.toString = () => `#<Message class '${className}'>`; constructor[Symbol.toStringTag] = constructor.toString; constructor.parentConstructor = baseMessageClass; constructor.kind = className; constructor.type = typeName; constructor.category = categoryName; Object.freeze(constructor); return constructor; }
<!DOCTYPE html> <html> <head> <title> Background Color </title> </head> <body> <h1> Choose a Background Color </h1> <input type="color" id="bg-color-picker"> <button id="bg-color-button" type="button" onclick="changeBackgroundColour()"> Change Color </button> <script> function changeBackgroundColour() { let color = document.getElementById('bg-color-picker').value; document.body.style.backgroundColor = color; } </script> </body> </html>
<filename>src/distorb.c /** @file distorb.c @brief Subroutines that control the integration of the orbital model. @author <NAME> ([deitrr](https://github.com/deitrr/)) @date April 28 2015 */ #include <stdio.h> #include <math.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include "vplanet.h" #include "options.h" #include "output.h" void BodyCopyDistOrb(BODY *dest,BODY *src,int iTideModel,int iNumBodies,int iBody) { int iIndex,iPert; dest[iBody].dPinc = src[iBody].dPinc; dest[iBody].dQinc = src[iBody].dQinc; dest[iBody].iGravPerts = src[iBody].iGravPerts; // dest[iBody].iaGravPerts = malloc(dest[iBody].iGravPerts*sizeof(int)); for (iPert=0;iPert<src[iBody].iGravPerts;iPert++) dest[iBody].iaGravPerts[iPert] = src[iBody].iaGravPerts[iPert]; } void InitializeBodyDistOrb(BODY *body,CONTROL *control,UPDATE *update,int iBody,int iModule) { if (body[iBody].bDistOrb) { if (control->Evolve.iDistOrbModel == RD4) { body[iBody].iGravPerts = control->Evolve.iNumBodies - 2; body[iBody].iDistOrbModel = RD4; } else if (control->Evolve.iDistOrbModel == LL2) { /* "Perturbers" in LL2 correspond to eigenfrequencies, not planet pairs. Number of eigenfrequencies = number of planets. */ body[iBody].iGravPerts = control->Evolve.iNumBodies - 1; body[iBody].iDistOrbModel = LL2; } } body[iBody].iaGravPerts = malloc(body[iBody].iGravPerts*sizeof(int)); } void InitializeUpdateTmpBodyDistOrb(BODY *body,CONTROL *control,UPDATE *update,int iBody) { control->Evolve.tmpBody[iBody].iaGravPerts = malloc(body[iBody].iGravPerts*sizeof(int)); } /**************** DISTORB options ********************/ void ReadDfCrit(BODY *body,CONTROL *control,FILES *files,OPTIONS *options,SYSTEM *system,int iFile) { /* This parameter can exist in any file, but only once */ int lTmp=-1; double dTmp; AddOptionDouble(files->Infile[iFile].cIn,options->cName,&dTmp,&lTmp,control->Io.iVerbose); if (lTmp >= 0) { CheckDuplication(files,options,files->Infile[iFile].cIn,lTmp,control->Io.iVerbose); if (dTmp < 0) { if (control->Io.iVerbose >= VERBERR) fprintf(stderr,"ERROR: %s must be greater than or equal to 0.\n",options->cName); LineExit(files->Infile[iFile].cIn,lTmp); } system->dDfcrit = dTmp; if (system->dDfcrit > 1 && control->Io.iVerbose >= VERBALL) fprintf(stderr,"WARNING: %s > 1 is not advised (%s:%d).\n",options->cName,files->Infile[iFile].cIn,lTmp); UpdateFoundOption(&files->Infile[iFile],options,lTmp,iFile); } else AssignDefaultDouble(options,&system->dDfcrit,files->iNumInputs); } void ReadInvPlane(BODY *body,CONTROL *control,FILES *files,OPTIONS *options,SYSTEM *system,int iFile) { int lTmp=-1,bTmp; AddOptionBool(files->Infile[iFile].cIn,options->cName,&bTmp,&lTmp,control->Io.iVerbose); if (lTmp >= 0) { CheckDuplication(files,options,files->Infile[iFile].cIn,lTmp,control->Io.iVerbose); /* Option was found */ control->bInvPlane = bTmp; UpdateFoundOption(&files->Infile[iFile],options,lTmp,iFile); } else AssignDefaultInt(options,&control->bInvPlane,files->iNumInputs); } void ReadOutputLapl(BODY *body,CONTROL *control,FILES *files,OPTIONS *options,SYSTEM *system,int iFile) { int lTmp=-1,bTmp; AddOptionBool(files->Infile[iFile].cIn,options->cName,&bTmp,&lTmp,control->Io.iVerbose); if (lTmp >= 0) { CheckDuplication(files,options,files->Infile[iFile].cIn,lTmp,control->Io.iVerbose); /* Option was found */ control->bOutputLapl = bTmp; UpdateFoundOption(&files->Infile[iFile],options,lTmp,iFile); } else AssignDefaultInt(options,&control->bOutputLapl,files->iNumInputs); } void ReadOutputEigen(BODY *body,CONTROL *control,FILES *files,OPTIONS *options,SYSTEM *system,int iFile) { int lTmp=-1,bTmp; AddOptionBool(files->Infile[iFile].cIn,options->cName,&bTmp,&lTmp,control->Io.iVerbose); if (lTmp >= 0) { CheckDuplication(files,options,files->Infile[iFile].cIn,lTmp,control->Io.iVerbose); /* Option was found */ control->bOutputEigen = bTmp; UpdateFoundOption(&files->Infile[iFile],options,lTmp,iFile); } else AssignDefaultInt(options,&control->bOutputEigen,files->iNumInputs); } void ReadOverrideMaxEcc(BODY *body,CONTROL *control,FILES *files,OPTIONS *options,SYSTEM *system,int iFile) { int lTmp=-1,bTmp; AddOptionBool(files->Infile[iFile].cIn,options->cName,&bTmp,&lTmp,control->Io.iVerbose); if (lTmp >= 0) { /* Option was found */ control->Halt[iFile-1].bOverrideMaxEcc = bTmp; UpdateFoundOption(&files->Infile[iFile],options,lTmp,iFile); } else control->Halt[iFile-1].bOverrideMaxEcc = options->dDefault; // AssignDefaultInt(options,&control->Halt[iFile-1].bOverrideMaxEcc,files->iNumInputs); } void ReadHaltHillStab(BODY *body,CONTROL *control,FILES *files,OPTIONS *options,SYSTEM *system,int iFile) { int lTmp=-1,bTmp; AddOptionBool(files->Infile[iFile].cIn,options->cName,&bTmp,&lTmp,control->Io.iVerbose); if (lTmp >= 0) { CheckDuplication(files,options,files->Infile[iFile].cIn,lTmp,control->Io.iVerbose); /* Option was found */ control->Halt[iFile-1].bHillStab = bTmp; UpdateFoundOption(&files->Infile[iFile],options,lTmp,iFile); } else control->Halt[iFile-1].bHillStab = options->dDefault; } void ReadHaltCloseEnc(BODY *body,CONTROL *control,FILES *files,OPTIONS *options,SYSTEM *system,int iFile) { int lTmp=-1,bTmp; AddOptionBool(files->Infile[iFile].cIn,options->cName,&bTmp,&lTmp,control->Io.iVerbose); if (lTmp >= 0) { CheckDuplication(files,options,files->Infile[iFile].cIn,lTmp,control->Io.iVerbose); /* Option was found */ control->Halt[iFile-1].bCloseEnc = bTmp; UpdateFoundOption(&files->Infile[iFile],options,lTmp,iFile); } else control->Halt[iFile-1].bCloseEnc = options->dDefault; } void ReadEigenSet(BODY *body,CONTROL *control,FILES *files,OPTIONS *options,SYSTEM *system,int iFile) { int lTmp=-1,bTmp; AddOptionBool(files->Infile[iFile].cIn,options->cName,&bTmp,&lTmp,control->Io.iVerbose); if (lTmp >= 0) { /* Option was found */ body[iFile-1].bEigenSet = bTmp; UpdateFoundOption(&files->Infile[iFile],options,lTmp,iFile); } else body[iFile-1].bEigenSet = options->dDefault; // AssignDefaultInt(options,&control->Halt[iFile-1].bOverrideMaxEcc,files->iNumInputs); } void ReadEigenvalue(BODY *body,CONTROL *control,FILES *files,OPTIONS *options,SYSTEM *system,int iFile) { /* This parameter cannot exist in the primary file */ int lTmp=-1; double dTmp; AddOptionDouble(files->Infile[iFile].cIn,options->cName,&dTmp,&lTmp,control->Io.iVerbose); if (lTmp >= 0) { NotPrimaryInput(iFile,options->cName,files->Infile[iFile].cIn,lTmp,control->Io.iVerbose); dTmp *= DEGRAD/3600./YEARSEC; body[iFile-1].dEigenvalue = dTmp; UpdateFoundOption(&files->Infile[iFile],options,lTmp,iFile); } else if (iFile > 0) body[iFile-1].dEigenvalue = options->dDefault; } void ReadEigenvector(BODY *body,CONTROL *control,FILES *files,OPTIONS *options,SYSTEM *system,int iFile) { /* This parameter cannot exist in the primary file */ int lTmp=-1; double dTmp; AddOptionDouble(files->Infile[iFile].cIn,options->cName,&dTmp,&lTmp,control->Io.iVerbose); if (lTmp >= 0) { NotPrimaryInput(iFile,options->cName,files->Infile[iFile].cIn,lTmp,control->Io.iVerbose); body[iFile-1].dEigenvector = dTmp; UpdateFoundOption(&files->Infile[iFile],options,lTmp,iFile); } else if (iFile > 0) body[iFile-1].dEigenvector = options->dDefault; } void ReadOrbitModel(BODY *body,CONTROL *control,FILES *files,OPTIONS *options,SYSTEM *system,int iFile) { /* This parameter can exist in any file, but only once */ int lTmp=-1; char cTmp[OPTLEN]; /* Tide Model, use #defined variables */ AddOptionString(files->Infile[iFile].cIn,options->cName,cTmp,&lTmp,control->Io.iVerbose); if (lTmp >= 0) { /* This parameter can not appear in the primary input, as it is module specific (it's easier to code this way. It should also only appear in one body file so as different tidal models cannot be called. */ NotPrimaryInput(iFile,options->cName,files->Infile[iFile].cIn,lTmp,control->Io.iVerbose); CheckDuplication(files,options,files->Infile[iFile].cIn,lTmp,control->Io.iVerbose); if (!memcmp(sLower(cTmp),"ll2",3)) { control->Evolve.iDistOrbModel = LL2; } else if (!memcmp(sLower(cTmp),"rd4",3)) { control->Evolve.iDistOrbModel = RD4; } else { if (control->Io.iVerbose >= VERBERR) fprintf(stderr,"ERROR: Unknown argument to %s: %s. Options are ll2 or rd4.\n",options->cName,cTmp); LineExit(files->Infile[iFile].cIn,lTmp); } UpdateFoundOption(&files->Infile[iFile],options,lTmp,iFile); } else AssignDefaultInt(options,&control->Evolve.iDistOrbModel,files->iNumInputs); } void InitializeOptionsDistOrb(OPTIONS *options,fnReadOption fnRead[]) { sprintf(options[OPT_DFCRIT].cName,"dDfcrit"); sprintf(options[OPT_DFCRIT].cDescr,"Tolerance parameter for recalculating semi- functions"); sprintf(options[OPT_DFCRIT].cDefault,"0.1"); options[OPT_DFCRIT].dDefault = 0.1; options[OPT_DFCRIT].iType = 2; options[OPT_DFCRIT].iMultiFile = 0; fnRead[OPT_DFCRIT] = &ReadDfCrit; sprintf(options[OPT_INVPLANE].cName,"bInvPlane"); sprintf(options[OPT_INVPLANE].cDescr,"Convert input coordinates to invariable plane coordinates"); sprintf(options[OPT_INVPLANE].cDefault,"0"); options[OPT_INVPLANE].dDefault = 0; options[OPT_INVPLANE].iType = 0; options[OPT_INVPLANE].iMultiFile = 0; fnRead[OPT_INVPLANE] = &ReadInvPlane; sprintf(options[OPT_ORBITMODEL].cName,"sOrbitModel"); sprintf(options[OPT_ORBITMODEL].cDescr,"Orbit Model: ll2 [laplace-lagrange (eigen), 2nd order] rd4 [direct dist-fxn, 4th order]"); sprintf(options[OPT_ORBITMODEL].cDefault,"rd4"); options[OPT_ORBITMODEL].dDefault = RD4; options[OPT_ORBITMODEL].iType = 1; fnRead[OPT_ORBITMODEL] = &ReadOrbitModel; sprintf(options[OPT_ORMAXECC].cName,"bOverrideMaxEcc"); sprintf(options[OPT_ORMAXECC].cDescr,"Override default maximum eccentricity in DistOrb (MaxEcc = MAXORBDISTORB)"); sprintf(options[OPT_ORMAXECC].cDefault,"0"); options[OPT_ORMAXECC].dDefault = 0; options[OPT_ORMAXECC].iType = 0; options[OPT_ORMAXECC].iMultiFile = 0; fnRead[OPT_ORMAXECC] = &ReadOverrideMaxEcc; sprintf(options[OPT_HALTHILLSTAB].cName,"bHaltHillStab"); sprintf(options[OPT_HALTHILLSTAB].cDescr,"Enforce Hill stability criterion (halt if failed)"); sprintf(options[OPT_HALTHILLSTAB].cDefault,"0"); options[OPT_HALTHILLSTAB].dDefault = 0; options[OPT_HALTHILLSTAB].iType = 0; options[OPT_HALTHILLSTAB].iMultiFile = 0; fnRead[OPT_HALTHILLSTAB] = &ReadHaltHillStab; sprintf(options[OPT_HALTCLOSEENC].cName,"bHaltCloseEnc"); sprintf(options[OPT_HALTCLOSEENC].cDescr,"Halt if orbits get too close"); sprintf(options[OPT_HALTCLOSEENC].cDefault,"0"); options[OPT_HALTCLOSEENC].dDefault = 0; options[OPT_HALTCLOSEENC].iType = 0; options[OPT_HALTCLOSEENC].iMultiFile = 0; fnRead[OPT_HALTCLOSEENC] = &ReadHaltCloseEnc; sprintf(options[OPT_EIGENSET].cName,"bEigenSet"); sprintf(options[OPT_EIGENSET].cDescr,"Set this to provide eigenvalues/vectors at input"); sprintf(options[OPT_EIGENSET].cDefault,"0"); options[OPT_EIGENSET].dDefault = 0; options[OPT_EIGENSET].iType = 0; options[OPT_EIGENSET].iMultiFile = 0; fnRead[OPT_EIGENSET] = &ReadEigenSet; sprintf(options[OPT_EIGENVALUE].cName,"dEigenvalue"); sprintf(options[OPT_EIGENVALUE].cDescr,"Set this to provide eigenvalues/vectors at input"); sprintf(options[OPT_EIGENVALUE].cDefault,"0"); options[OPT_EIGENVALUE].dDefault = 0; options[OPT_EIGENVALUE].iType = 0; options[OPT_EIGENVALUE].iMultiFile = 0; fnRead[OPT_EIGENVALUE] = &ReadEigenvalue; sprintf(options[OPT_EIGENVECTOR].cName,"dEigenvector"); sprintf(options[OPT_EIGENVECTOR].cDescr,"Set this to provide eigenvalues/vectors at input"); sprintf(options[OPT_EIGENVECTOR].cDefault,"0"); options[OPT_EIGENVECTOR].dDefault = 0; options[OPT_EIGENVECTOR].iType = 0; options[OPT_EIGENVECTOR].iMultiFile = 0; fnRead[OPT_EIGENVECTOR] = &ReadEigenvector; sprintf(options[OPT_OUTPUTLAPL].cName,"bOutputLapl"); sprintf(options[OPT_OUTPUTLAPL].cDescr,"Output Laplace functions and related data"); sprintf(options[OPT_OUTPUTLAPL].cDefault,"0"); options[OPT_OUTPUTLAPL].dDefault = 0; options[OPT_OUTPUTLAPL].iType = 0; options[OPT_OUTPUTLAPL].iMultiFile = 0; fnRead[OPT_OUTPUTLAPL] = &ReadOutputLapl; sprintf(options[OPT_OUTPUTEIGEN].cName,"bOutputEigen"); sprintf(options[OPT_OUTPUTEIGEN].cDescr,"Output Eigenvalues"); sprintf(options[OPT_OUTPUTEIGEN].cDefault,"0"); options[OPT_OUTPUTEIGEN].dDefault = 0; options[OPT_OUTPUTEIGEN].iType = 0; options[OPT_OUTPUTEIGEN].iMultiFile = 0; fnRead[OPT_OUTPUTEIGEN] = &ReadOutputEigen; } void ReadOptionsDistOrb(BODY *body,CONTROL *control,FILES *files,OPTIONS *options,SYSTEM *system,fnReadOption fnRead[],int iBody) { int iOpt; for (iOpt=OPTSTARTDISTORB;iOpt<OPTENDDISTORB;iOpt++) { if (options[iOpt].iType != -1) { fnRead[iOpt](body,control,files,&options[iOpt],system,iBody+1); } } } /******************* Verify DISTORB ******************/ /* * * Pericenter/Ascending node * */ double fndCorrectDomain(double angle) { while (angle >= 2*PI) { angle -= 2*PI; } while (angle < 0.0) { angle += 2*PI; } return angle; } double fndCalcLongP(double dLongA, double dArgP) { double varpi; varpi = fndCorrectDomain(dLongA + dArgP); return varpi; } double fndCalcLongA(double dLongP, double dArgP) { double Omega; Omega = fndCorrectDomain(dLongP - dArgP); return Omega; } void VerifyOrbitModel(CONTROL *control,FILES *files,OPTIONS *options) { int iFile,iFound=0; char cTmp[8]; for (iFile=0;iFile<files->iNumInputs;iFile++) { if (options[OPT_ORBITMODEL].iLine[iFile] >= 0) iFound++; } if (iFound > 1) { if (control->Io.iVerbose > VERBERR) { fprintf(stderr,"ERROR: Option %s set multiple times.\n",options[OPT_ORBITMODEL].cName); for (iFile=0;iFile<files->iNumInputs;iFile++) { if (options[OPT_ORBITMODEL].iLine[iFile] >= 0) fprintf(stderr,"\tFile %s, Line: %d\n",files->Infile[0].cIn,options[OPT_ORBITMODEL].iLine[iFile]); } } exit(EXIT_INPUT); } if (iFound == 0) { strcpy(cTmp,options[OPT_ORBITMODEL].cDefault); if (!memcmp(sLower(cTmp),"ll2",3)) { control->Evolve.iDistOrbModel = LL2; } else if (!memcmp(sLower(cTmp),"rd4",3)) { control->Evolve.iDistOrbModel = RD4; } if (control->Io.iVerbose >= VERBINPUT) fprintf(stderr,"WARNING: %s not set in any file, defaulting to %s.\n",options[OPT_ORBITMODEL].cName,options[OPT_ORBITMODEL].cDefault); /* Chicanery. Since I only want this set once, I will make it seem like the user set it. */ options[OPT_ORBITMODEL].iLine[0] = 1; } } // void VerifyStabilityHalts(CONTROL *control,FILES *files,OPTIONS *options) { // int iFile, iHillSet, iCloseSet; // /* make sure user doesn't set both bHaltHillStab and bHaltCloseEnc */ // // } void VerifyPericenter(BODY *body,CONTROL *control,OPTIONS *options,char cFile[],int iBody,int iVerbose) { /* First see if longitude of ascending node and longitude of pericenter and nothing else set, i.e. the user input the default parameters */ if (options[OPT_LONGA].iLine[iBody+1] > -1 && options[OPT_LONGP].iLine[iBody+1] > -1 && options[OPT_ARGP].iLine[iBody+1] == -1) return; /* If none are set, raise error */ if (options[OPT_LONGA].iLine[iBody+1] == -1 && options[OPT_LONGP].iLine[iBody+1] == -1 && options[OPT_ARGP].iLine[iBody+1] == -1) { if (iVerbose >= VERBERR) fprintf(stderr,"ERROR: Must set two of %s, %s, and %s in File: %s.\n",options[OPT_LONGA].cName,options[OPT_LONGP].cName,options[OPT_ARGP].cName, cFile); exit(EXIT_INPUT); } /* At least 2 must be set */ if ((options[OPT_LONGA].iLine[iBody+1] == -1 && options[OPT_LONGP].iLine[iBody+1] == -1) || (options[OPT_LONGA].iLine[iBody+1] == -1 && options[OPT_ARGP].iLine[iBody+1] == -1) || (options[OPT_LONGP].iLine[iBody+1] == -1 && options[OPT_ARGP].iLine[iBody+1] == -1)) { if (iVerbose >= VERBERR) fprintf(stderr,"ERROR: Must set two of %s, %s, and %s in File: %s.\n",options[OPT_LONGA].cName,options[OPT_LONGP].cName,options[OPT_ARGP].cName, cFile); exit(EXIT_INPUT); } /* Were all set? */ if (options[OPT_LONGA].iLine[iBody+1] > -1 && options[OPT_LONGP].iLine[iBody+1] > -1 && options[OPT_ARGP].iLine[iBody+1] > -1) { VerifyTripleExit(options[OPT_LONGA].cName,options[OPT_LONGP].cName,options[OPT_ARGP].cName,options[OPT_LONGA].iLine[iBody+1],options[OPT_LONGP].iLine[iBody+1],options[OPT_ARGP].iLine[iBody+1],cFile,iVerbose); exit(EXIT_INPUT); } /* Was LONGA set? */ if (options[OPT_LONGA].iLine[iBody+1] > -1) { if (options[OPT_LONGP].iLine[iBody+1] > -1) /* LONGA and LONGP were the only two set - Nothing to do */ return; if (options[OPT_ARGP].iLine[iBody+1] > -1) /* Must get radius from density */ body[iBody].dLongP = fndCalcLongP(body[iBody].dLongA,body[iBody].dArgP); return; } /* Was LongP set? */ if (options[OPT_LONGP].iLine[iBody+1] > -1) { if (options[OPT_LONGA].iLine[iBody+1] > -1) /* LONGA and LONGP were the only two set - Nothing to do */ return; if (options[OPT_ARGP].iLine[iBody+1] > -1) /* Must get radius from density */ body[iBody].dLongA = fndCalcLongA(body[iBody].dLongP,body[iBody].dArgP); return; } } /* In the following, iBody is the current body number that is getting assigned, iPert counts the number of bodies perturbing iBody, and iBodyPert is the body number of the current perturbing body. */ /* The indexing gets a bit confusing here. iPert = 0 to iGravPerts-1 correspond to all perturbing planets, iPert = iGravPerts corresponds to the stellar general relativistic correction, if applied. */ void InitializeHeccDistOrbRD4(BODY *body,UPDATE *update,int iBody,int iPert) { update[iBody].iaType[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]] = 2; update[iBody].padDHeccDtDistOrb[iPert] = &update[iBody].daDerivProc[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]]; update[iBody].iNumBodies[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]]=2; update[iBody].iaBody[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]] = malloc(update[iBody].iNumBodies[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]]*sizeof(int)); update[iBody].iaBody[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]][0] = iBody; update[iBody].iaBody[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]][1] = body[iBody].iaGravPerts[iPert]; } void InitializeKeccDistOrbRD4(BODY *body,UPDATE *update,int iBody,int iPert) { update[iBody].iaType[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]] = 2; update[iBody].padDKeccDtDistOrb[iPert] = &update[iBody].daDerivProc[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]]; update[iBody].iNumBodies[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]]=2; update[iBody].iaBody[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]] = malloc(update[iBody].iNumBodies[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]]*sizeof(int)); update[iBody].iaBody[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]][0] = iBody; update[iBody].iaBody[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]][1] = body[iBody].iaGravPerts[iPert]; } void InitializeHeccDistOrbGR(BODY *body,UPDATE *update,int iBody,int iPert) { update[iBody].iaType[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]] = 2; update[iBody].padDHeccDtDistOrb[iPert] = &update[iBody].daDerivProc[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]]; update[iBody].iNumBodies[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]]=2; update[iBody].iaBody[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]] = malloc(update[iBody].iNumBodies[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]]*sizeof(int)); update[iBody].iaBody[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]][0] = iBody; update[iBody].iaBody[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]][1] = 0; } void InitializeKeccDistOrbGR(BODY *body,UPDATE *update,int iBody,int iPert) { update[iBody].iaType[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]] = 2; update[iBody].padDKeccDtDistOrb[iPert] = &update[iBody].daDerivProc[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]]; update[iBody].iNumBodies[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]]=2; update[iBody].iaBody[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]] = malloc(update[iBody].iNumBodies[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]]*sizeof(int)); update[iBody].iaBody[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]][0] = iBody; update[iBody].iaBody[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]][1] = 0; } void InitializePincDistOrbRD4(BODY *body,UPDATE *update,int iBody,int iPert) { update[iBody].iaType[update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]] = 2; update[iBody].padDPincDtDistOrb[iPert] = &update[iBody].daDerivProc[update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]]; update[iBody].iNumBodies[update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]]=2; update[iBody].iaBody[update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]] = malloc(update[iBody].iNumBodies[update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]]*sizeof(int)); update[iBody].iaBody[update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]][0] = iBody; update[iBody].iaBody[update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]][1] = body[iBody].iaGravPerts[iPert]; } void InitializeQincDistOrbRD4(BODY *body,UPDATE *update,int iBody,int iPert) { update[iBody].iaType[update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]] = 2; update[iBody].padDQincDtDistOrb[iPert] = &update[iBody].daDerivProc[update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]]; update[iBody].iNumBodies[update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]]=2; update[iBody].iaBody[update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]] = malloc(update[iBody].iNumBodies[update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]]*sizeof(int)); update[iBody].iaBody[update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]][0] = iBody; update[iBody].iaBody[update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]][1] = body[iBody].iaGravPerts[iPert]; } void VerifyPerturbersDistOrbRD4(BODY *body,int iNumBodies,int iBody) { int iPert=0, j; // body[iBody].iaGravPerts = malloc(body[iBody].iGravPerts*sizeof(int)); for (j=1;j<iNumBodies;j++) { if (j != iBody) { if (body[j].bDistOrb == 0) { fprintf(stderr,"ERROR: DistOrb must be the called for all planets\n"); exit(EXIT_INPUT); } body[iBody].iaGravPerts[iPert] = j; iPert++; } } } void InitializeHeccDistOrbLL2(BODY *body,UPDATE *update,int iBody,int iPert) { if (body[iBody].bEqtide) { update[iBody].iaType[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]] = 2; } else { update[iBody].iaType[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]] = 3; } update[iBody].padDHeccDtDistOrb[iPert] = &update[iBody].daDerivProc[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]]; update[iBody].iNumBodies[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]]=2; update[iBody].iaBody[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]] = malloc(update[iBody].iNumBodies[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]]*sizeof(int)); update[iBody].iaBody[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]][0] = iBody; update[iBody].iaBody[update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]][1] = body[iBody].iaGravPerts[iPert]; } void InitializeKeccDistOrbLL2(BODY *body,UPDATE *update,int iBody,int iPert) { if (body[iBody].bEqtide) { update[iBody].iaType[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]] = 2; } else { update[iBody].iaType[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]] = 3; } update[iBody].padDKeccDtDistOrb[iPert] = &update[iBody].daDerivProc[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]]; update[iBody].iNumBodies[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]]=2; update[iBody].iaBody[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]] = malloc(update[iBody].iNumBodies[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]]*sizeof(int)); update[iBody].iaBody[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]][0] = iBody; update[iBody].iaBody[update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]][1] = body[iBody].iaGravPerts[iPert]; } void InitializePincDistOrbLL2(BODY *body,UPDATE *update,int iBody,int iPert) { update[iBody].iaType[update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]] = 3; update[iBody].padDPincDtDistOrb[iPert] = &update[iBody].daDerivProc[update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]]; update[iBody].iNumBodies[update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]]=2; update[iBody].iaBody[update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]] = malloc(update[iBody].iNumBodies[update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]]*sizeof(int)); update[iBody].iaBody[update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]][0] = iBody; update[iBody].iaBody[update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]][1] = body[iBody].iaGravPerts[iPert]; } void InitializeQincDistOrbLL2(BODY *body,UPDATE *update,int iBody,int iPert) { update[iBody].iaType[update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]] = 3; update[iBody].padDQincDtDistOrb[iPert] = &update[iBody].daDerivProc[update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]]; update[iBody].iNumBodies[update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]]=2; update[iBody].iaBody[update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]] = malloc(update[iBody].iNumBodies[update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]]*sizeof(int)); update[iBody].iaBody[update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]][0] = iBody; update[iBody].iaBody[update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]][1] = body[iBody].iaGravPerts[iPert]; } void VerifyPerturbersDistOrbLL2(BODY *body,int iNumBodies,int iBody) { int iPert=0, j; // body[iBody].iaGravPerts = malloc(body[iBody].iGravPerts*sizeof(int)); for (j=1;j<iNumBodies;j++) { if (body[j].bDistOrb == 0) { fprintf(stderr,"ERROR: DistOrb must be the called for all planets\n"); exit(EXIT_INPUT); } body[iBody].iaGravPerts[iPert] = j; iPert++; } } void VerifyGRCorrLL2(BODY *body, int iNumBodies) { int iBody; for (iBody=2;iBody<iNumBodies;iBody++) { if (body[iBody].bGRCorr != body[1].bGRCorr) { fprintf(stderr,"ERROR: bGRCorr must be the same for all planets in DistOrb LL2 model\n"); exit(EXIT_INPUT); } } } void AssignDistOrbDerivatives(BODY *body,EVOLVE *evolve,UPDATE *update,fnUpdateVariable ***fnUpdate,int iBody) { int iPert; if (evolve->iDistOrbModel == RD4) { body[iBody].iGravPerts = evolve->iNumBodies - 2; //will need to change this for zero mass particles in future /* The indexing gets a bit confusing here. iPert = 0 to iGravPerts-1 correspond to all perturbing planets, iPert = iGravPerts corresponds to the stellar general relativistic correction, if applied */ /* Setup Semi-major axis functions (LaplaceF) for secular terms*/ if (iBody >= 1) { /* Body updates */ for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) { /* h = Ecc*sin(LongP) */ fnUpdate[iBody][update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]] = &fndDistOrbRD4DhDt; /* k = Ecc*cos(LongP) */ fnUpdate[iBody][update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]] = &fndDistOrbRD4DkDt; /* p = s*sin(LongA) */ fnUpdate[iBody][update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]] = &fndDistOrbRD4DpDt; /* q = s*cos(LongA) */ fnUpdate[iBody][update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]] = &fndDistOrbRD4DqDt; } if (body[iBody].bGRCorr) { /* Body updates for general relativistic correction, indexing star as a "perturber"*/ fnUpdate[iBody][update[iBody].iHecc][update[iBody].iaHeccDistOrb[body[iBody].iGravPerts]] = &fndApsidalGRDhDt; fnUpdate[iBody][update[iBody].iKecc][update[iBody].iaKeccDistOrb[body[iBody].iGravPerts]] = &fndApsidalGRDkDt; } } } else if (evolve->iDistOrbModel == LL2) { body[iBody].iGravPerts = evolve->iNumBodies - 1; VerifyPerturbersDistOrbLL2(body,evolve->iNumBodies,iBody); for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) { if (body[iBody].bEqtide) { fnUpdate[iBody][update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]] = &fndDistOrbLL2DhDt; fnUpdate[iBody][update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]] = &fndDistOrbLL2DkDt; } else { fnUpdate[iBody][update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]] = &fndDistOrbLL2Hecc; fnUpdate[iBody][update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]] = &fndDistOrbLL2Kecc; } /* p = s*sin(LongA) */ fnUpdate[iBody][update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]] = &fndDistOrbLL2Pinc; /* q = s*cos(LongA) */ fnUpdate[iBody][update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]] = &fndDistOrbLL2Qinc; } } } void NullDistOrbDerivatives(BODY *body,EVOLVE *evolve,UPDATE *update,fnUpdateVariable ***fnUpdate,int iBody) { int iPert; if (evolve->iDistOrbModel == RD4) { body[iBody].iGravPerts = evolve->iNumBodies - 2; //will need to change this for zero mass particles in future /* The indexing gets a bit confusing here. iPert = 0 to iGravPerts-1 correspond to all perturbing planets, iPert = iGravPerts corresponds to the stellar general relativistic correction, if applied */ /* Setup Semi-major axis functions (LaplaceF) for secular terms*/ if (iBody >= 1) { /* Body updates */ for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) { /* h = Ecc*sin(LongP) */ fnUpdate[iBody][update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]] = &fndUpdateFunctionTiny; /* k = Ecc*cos(LongP) */ fnUpdate[iBody][update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]] = &fndUpdateFunctionTiny; /* p = s*sin(LongA) */ fnUpdate[iBody][update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]] = &fndUpdateFunctionTiny; /* q = s*cos(LongA) */ fnUpdate[iBody][update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]] = &fndUpdateFunctionTiny; } if (body[iBody].bGRCorr) { /* Body updates for general relativistic correction, indexing star as a "perturber"*/ fnUpdate[iBody][update[iBody].iHecc][update[iBody].iaHeccDistOrb[body[iBody].iGravPerts]] = &fndUpdateFunctionTiny; fnUpdate[iBody][update[iBody].iKecc][update[iBody].iaKeccDistOrb[body[iBody].iGravPerts]] = &fndUpdateFunctionTiny; } } } else if (evolve->iDistOrbModel == LL2) { body[iBody].iGravPerts = evolve->iNumBodies - 1; VerifyPerturbersDistOrbLL2(body,evolve->iNumBodies,iBody); for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) { if (body[iBody].bEqtide) { fnUpdate[iBody][update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]] = &fndUpdateFunctionTiny; fnUpdate[iBody][update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]] = &fndUpdateFunctionTiny; } else { fnUpdate[iBody][update[iBody].iHecc][update[iBody].iaHeccDistOrb[iPert]] = &fndUpdateFunctionTiny; fnUpdate[iBody][update[iBody].iKecc][update[iBody].iaKeccDistOrb[iPert]] = &fndUpdateFunctionTiny; } /* p = s*sin(LongA) */ fnUpdate[iBody][update[iBody].iPinc][update[iBody].iaPincDistOrb[iPert]] = &fndUpdateFunctionTiny; /* q = s*cos(LongA) */ fnUpdate[iBody][update[iBody].iQinc][update[iBody].iaQincDistOrb[iPert]] = &fndUpdateFunctionTiny; } } } void VerifyDistOrb(BODY *body,CONTROL *control,FILES *files,OPTIONS *options,OUTPUT *output,SYSTEM *system,UPDATE *update,int iBody,int iModule) { int i, j=0, iPert=0, jBody=0,kBody; VerifyOrbitModel(control,files,options); // VerifyStabilityHalts(control,files,options); body[iBody].dMeanA = 0.0; if (control->Evolve.iDistOrbModel == RD4) { /* The indexing gets a bit confusing here. iPert = 0 to iGravPerts-1 correspond to all perturbing planets, iPert = iGravPerts corresponds to the stellar general relativistic correction, if applied */ /* Setup Semi-major axis functions (LaplaceF) for secular terms*/ if (iBody == 1) { system->daLOrb = malloc(3*sizeof(double)); system->fnLaplaceF = malloc(LAPLNUM*sizeof(fnLaplaceFunction*)); system->fnLaplaceDeriv = malloc(LAPLNUM*sizeof(fnLaplaceFunction*)); for (j=0;j<LAPLNUM;j++) { system->fnLaplaceF[j] = malloc(1*sizeof(fnLaplaceFunction)); system->fnLaplaceDeriv[j] = malloc(1*sizeof(fnLaplaceFunction)); } system->fnLaplaceF[0][0] = &fndSemiMajAxF1; system->fnLaplaceF[1][0] = &fndSemiMajAxF2; system->fnLaplaceF[2][0] = &fndSemiMajAxF3; system->fnLaplaceF[3][0] = &fndSemiMajAxF4; system->fnLaplaceF[4][0] = &fndSemiMajAxF5; system->fnLaplaceF[5][0] = &fndSemiMajAxF6; system->fnLaplaceF[6][0] = &fndSemiMajAxF7; system->fnLaplaceF[7][0] = &fndSemiMajAxF8; system->fnLaplaceF[8][0] = &fndSemiMajAxF9; system->fnLaplaceF[9][0] = &fndSemiMajAxF10; system->fnLaplaceF[10][0] = &fndSemiMajAxF11; system->fnLaplaceF[11][0] = &fndSemiMajAxF12; system->fnLaplaceF[12][0] = &fndSemiMajAxF13; system->fnLaplaceF[13][0] = &fndSemiMajAxF14; system->fnLaplaceF[14][0] = &fndSemiMajAxF15; system->fnLaplaceF[15][0] = &fndSemiMajAxF16; system->fnLaplaceF[16][0] = &fndSemiMajAxF17; system->fnLaplaceF[17][0] = &fndSemiMajAxF18; system->fnLaplaceF[18][0] = &fndSemiMajAxF19; system->fnLaplaceF[19][0] = &fndSemiMajAxF20; system->fnLaplaceF[20][0] = &fndSemiMajAxF21; system->fnLaplaceF[21][0] = &fndSemiMajAxF22; system->fnLaplaceF[22][0] = &fndSemiMajAxF23; system->fnLaplaceF[23][0] = &fndSemiMajAxF24; system->fnLaplaceF[24][0] = &fndSemiMajAxF25; system->fnLaplaceF[25][0] = &fndSemiMajAxF26; system->fnLaplaceDeriv[0][0] = &fndDSemiF1Dalpha; system->fnLaplaceDeriv[1][0] = &fndDSemiF2Dalpha; system->fnLaplaceDeriv[2][0] = &fndDSemiF3Dalpha; system->fnLaplaceDeriv[3][0] = &fndDSemiF4Dalpha; system->fnLaplaceDeriv[4][0] = &fndDSemiF5Dalpha; system->fnLaplaceDeriv[5][0] = &fndDSemiF6Dalpha; system->fnLaplaceDeriv[6][0] = &fndDSemiF7Dalpha; system->fnLaplaceDeriv[7][0] = &fndDSemiF8Dalpha; system->fnLaplaceDeriv[8][0] = &fndDSemiF9Dalpha; system->fnLaplaceDeriv[9][0] = &fndDSemiF10Dalpha; system->fnLaplaceDeriv[10][0] = &fndDSemiF11Dalpha; system->fnLaplaceDeriv[11][0] = &fndDSemiF12Dalpha; system->fnLaplaceDeriv[12][0] = &fndDSemiF13Dalpha; system->fnLaplaceDeriv[13][0] = &fndDSemiF14Dalpha; system->fnLaplaceDeriv[14][0] = &fndDSemiF15Dalpha; system->fnLaplaceDeriv[15][0] = &fndDSemiF16Dalpha; system->fnLaplaceDeriv[16][0] = &fndDSemiF17Dalpha; system->fnLaplaceDeriv[17][0] = &fndDSemiF18Dalpha; system->fnLaplaceDeriv[18][0] = &fndDSemiF19Dalpha; system->fnLaplaceDeriv[19][0] = &fndDSemiF20Dalpha; system->fnLaplaceDeriv[20][0] = &fndDSemiF21Dalpha; system->fnLaplaceDeriv[21][0] = &fndDSemiF22Dalpha; system->fnLaplaceDeriv[22][0] = &fndDSemiF23Dalpha; system->fnLaplaceDeriv[23][0] = &fndDSemiF24Dalpha; system->fnLaplaceDeriv[24][0] = &fndDSemiF25Dalpha; system->fnLaplaceDeriv[25][0] = &fndDSemiF26Dalpha; system->daLaplaceC = malloc((1)*sizeof(double**)); system->daLaplaceD = malloc((1)*sizeof(double**)); system->daAlpha0 = malloc((1)*sizeof(double**)); system->daLaplaceC[0] = malloc(fniNchoosek(control->Evolve.iNumBodies-1,2)*sizeof(double*)); system->daLaplaceD[0] = malloc(fniNchoosek(control->Evolve.iNumBodies-1,2)*sizeof(double*)); system->daAlpha0[0] = malloc(fniNchoosek(control->Evolve.iNumBodies-1,2)*sizeof(double*)); for (i=0;i<fniNchoosek(control->Evolve.iNumBodies-1,2);i++) { system->daLaplaceC[0][i] = malloc(LAPLNUM*sizeof(double)); system->daLaplaceD[0][i] = malloc(LAPLNUM*sizeof(double)); system->daAlpha0[0][i] = malloc(LAPLNUM*sizeof(double)); } system->iaLaplaceN = malloc((control->Evolve.iNumBodies)*sizeof(int*)); for (i=1;i<control->Evolve.iNumBodies;i++) { system->iaLaplaceN[i] = malloc((control->Evolve.iNumBodies)*sizeof(int)); } if (control->bOutputEigen) { system->daEigenValEcc = malloc(2*sizeof(double*)); system->daEigenVecEcc = malloc((control->Evolve.iNumBodies-1)*sizeof(double*)); system->daEigenValInc = malloc(2*sizeof(double*)); system->daEigenVecInc = malloc((control->Evolve.iNumBodies-1)*sizeof(double*)); system->daEigenPhase = malloc(2*sizeof(double*)); system->daA = malloc((control->Evolve.iNumBodies-1)*sizeof(double*)); system->daB = malloc((control->Evolve.iNumBodies-1)*sizeof(double*)); system->daAsoln = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daBsoln = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daAcopy = malloc((control->Evolve.iNumBodies-1)*sizeof(double*)); for (jBody=0;jBody<(control->Evolve.iNumBodies-1);jBody++) { system->daA[jBody] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daB[jBody] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daEigenVecEcc[jBody] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daEigenVecInc[jBody] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daAcopy[jBody] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); } for (i=0;i<2;i++) { system->daEigenValEcc[i] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daEigenValInc[i] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daEigenPhase[i] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); } system->daScale = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->iaRowswap = malloc((control->Evolve.iNumBodies-1)*sizeof(int)); } } if (iBody >= 1) { VerifyPericenter(body,control,options,files->Infile[iBody+1].cIn,iBody,control->Io.iVerbose); body[iBody].iGravPerts = control->Evolve.iNumBodies - 2; //will need to change this for zero mass particles in future VerifyPerturbersDistOrbRD4(body,control->Evolve.iNumBodies,iBody); control->fnPropsAux[iBody][iModule] = &PropsAuxDistOrb; CalcHK(body,iBody); CalcPQ(body,iBody); body[iBody].daLOrb = malloc(3*sizeof(double)); body[iBody].daLOrbTmp = malloc(3*sizeof(double)); /* Body updates */ for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) { /* h = Ecc*sin(LongP) */ InitializeHeccDistOrbRD4(body,update,iBody,iPert); /* k = Ecc*cos(LongP) */ InitializeKeccDistOrbRD4(body,update,iBody,iPert); /* p = s*sin(LongA) */ InitializePincDistOrbRD4(body,update,iBody,iPert); /* q = s*cos(LongA) */ InitializeQincDistOrbRD4(body,update,iBody,iPert); jBody = body[iBody].iaGravPerts[iPert]; for (j=0;j<26;j++) { if (body[iBody].dSemi < body[jBody].dSemi) { system->iaLaplaceN[iBody][jBody] = fniCombCount(iBody,jBody,control->Evolve.iNumBodies-1); system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][j] = system->fnLaplaceF[j][0](body[iBody].dSemi/body[jBody].dSemi, 0); system->daLaplaceD[0][system->iaLaplaceN[iBody][jBody]][j] = system->fnLaplaceDeriv[j][0](body[iBody].dSemi/body[jBody].dSemi, 0); system->daAlpha0[0][system->iaLaplaceN[iBody][jBody]][j] = body[iBody].dSemi/body[jBody].dSemi; } else if (body[iBody].dSemi > body[jBody].dSemi) { system->iaLaplaceN[iBody][jBody] = fniCombCount(jBody,iBody,control->Evolve.iNumBodies-1); system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][j] = system->fnLaplaceF[j][0](body[jBody].dSemi/body[iBody].dSemi, 0); system->daLaplaceD[0][system->iaLaplaceN[iBody][jBody]][j] = system->fnLaplaceDeriv[j][0](body[jBody].dSemi/body[iBody].dSemi, 0); system->daAlpha0[0][system->iaLaplaceN[iBody][jBody]][j] = body[jBody].dSemi/body[iBody].dSemi; } } } if (iBody == control->Evolve.iNumBodies-1) { if (control->bInvPlane) { /* Must initialize dMeanA to prevent memory corruption. This parameter has no real meaning in DistOrb runs, but inv_plave requires it. I will set it to zero for each body. --RKB */ for (kBody=0;kBody<control->Evolve.iNumBodies;kBody++) body[kBody].dMeanA = 0; inv_plane(body, system, control->Evolve.iNumBodies); } } if (body[iBody].bGRCorr) { /* Body updates for general relativistic correction, indexing star as a "perturber"*/ InitializeHeccDistOrbGR(body,update,iBody,body[iBody].iGravPerts); InitializeKeccDistOrbGR(body,update,iBody,body[iBody].iGravPerts); } } } else if (control->Evolve.iDistOrbModel == LL2) { VerifyPericenter(body,control,options,files->Infile[iBody+1].cIn,iBody,control->Io.iVerbose); control->fnPropsAux[iBody][iModule] = &PropsAuxDistOrb; CalcHK(body,iBody); CalcPQ(body,iBody); if (body[iBody].bEigenSet == 1) { /* XXX really stupid hack */ system->daEigenValEcc = malloc(2*sizeof(double*)); system->daEigenValInc = malloc(2*sizeof(double*)); system->daEigenVecEcc = malloc((control->Evolve.iNumBodies-1)*sizeof(double*)); system->daEigenVecInc = malloc((control->Evolve.iNumBodies-1)*sizeof(double*)); system->daEigenPhase = malloc(2*sizeof(double*)); system->daEigenValEcc[0] = malloc(1*sizeof(double)); system->daEigenValInc[0] = malloc(1*sizeof(double)); system->daEigenVecEcc[0] = malloc(1*sizeof(double)); system->daEigenVecInc[0] = malloc(1*sizeof(double)); system->daEigenPhase[0] = malloc(1*sizeof(double)); system->daEigenPhase[1] = malloc(1*sizeof(double)); system->daEigenValEcc[0][0] = 0.0; //system->daEigenValInc[0][0] = -0.000123627489; system->daEigenValInc[0][0] = -0.000119874715; system->daEigenVecEcc[0][0] = 0.0; //system->daEigenVecInc[0][0] = 0.00506143322; system->daEigenVecInc[0][0] = 0.0036367199; system->daEigenPhase[0][0] = 0.0; // system->daEigenPhase[1][0] = atan2(body[iBody].dHecc,body[iBody].dKecc); system->daEigenPhase[1][0] = 2.6348951757; } else { /* Conditions for recalc'ing eigenvalues */ if (iBody == 1) { system->daLOrb = malloc(3*sizeof(double)); system->daLaplaceD = malloc(1*sizeof(double*)); system->daAlpha0 = malloc(1*sizeof(double*)); system->iaLaplaceN = malloc((control->Evolve.iNumBodies)*sizeof(int*)); system->daAlpha0[0] = malloc(fniNchoosek(control->Evolve.iNumBodies-1,2)*sizeof(double*)); system->daLaplaceD[0] = malloc(fniNchoosek(control->Evolve.iNumBodies-1,2)*sizeof(double*)); for (j=0;j<fniNchoosek(control->Evolve.iNumBodies-1,2);j++) { system->daLaplaceD[0][j] = malloc(2*sizeof(double)); system->daAlpha0[0][j] = malloc(1*sizeof(double)); } for (j=1;j<(control->Evolve.iNumBodies);j++) { system->iaLaplaceN[j] = malloc((control->Evolve.iNumBodies)*sizeof(int)); } } for (jBody=1;jBody<(control->Evolve.iNumBodies);jBody++) { body[jBody].daLOrb = malloc(3*sizeof(double)); body[jBody].daLOrbTmp = malloc(3*sizeof(double)); if (body[iBody].dSemi < body[jBody].dSemi) { system->iaLaplaceN[iBody][jBody] = fniCombCount(iBody,jBody,control->Evolve.iNumBodies-1); system->daAlpha0[0][system->iaLaplaceN[iBody][jBody]][0] = body[iBody].dSemi/body[jBody].dSemi; system->daLaplaceD[0][system->iaLaplaceN[iBody][jBody]][0] = fndDerivLaplaceCoeff(1,body[iBody].dSemi/body[jBody].dSemi,1,1.5); system->daLaplaceD[0][system->iaLaplaceN[iBody][jBody]][1] = fndDerivLaplaceCoeff(1,body[iBody].dSemi/body[jBody].dSemi,2,1.5); } else if (body[iBody].dSemi > body[jBody].dSemi) { system->iaLaplaceN[iBody][jBody] = fniCombCount(jBody,iBody,control->Evolve.iNumBodies-1); system->daAlpha0[0][system->iaLaplaceN[iBody][jBody]][0] = body[jBody].dSemi/body[iBody].dSemi; system->daLaplaceD[0][system->iaLaplaceN[iBody][jBody]][0] = fndDerivLaplaceCoeff(1,body[jBody].dSemi/body[iBody].dSemi,1,1.5); system->daLaplaceD[0][system->iaLaplaceN[iBody][jBody]][1] = fndDerivLaplaceCoeff(1,body[jBody].dSemi/body[iBody].dSemi,2,1.5); } } // body[iBody].dSemiPrev = body[iBody].dSemiPrev; if (iBody == (control->Evolve.iNumBodies-1)) { VerifyGRCorrLL2(body,control->Evolve.iNumBodies); if (control->bInvPlane) { inv_plane(body, system, control->Evolve.iNumBodies); } system->daEigenValEcc = malloc(2*sizeof(double*)); system->daEigenVecEcc = malloc((control->Evolve.iNumBodies-1)*sizeof(double*)); system->daEigenValInc = malloc(2*sizeof(double*)); system->daEigenVecInc = malloc((control->Evolve.iNumBodies-1)*sizeof(double*)); system->daEigenPhase = malloc(2*sizeof(double*)); system->daA = malloc((control->Evolve.iNumBodies-1)*sizeof(double*)); system->daB = malloc((control->Evolve.iNumBodies-1)*sizeof(double*)); system->daAsoln = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daBsoln = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daAcopy = malloc((control->Evolve.iNumBodies-1)*sizeof(double*)); for (jBody=0;jBody<(control->Evolve.iNumBodies-1);jBody++) { system->daA[jBody] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daB[jBody] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daEigenVecEcc[jBody] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daEigenVecInc[jBody] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daAcopy[jBody] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); } for (i=0;i<2;i++) { system->daEigenValEcc[i] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daEigenValInc[i] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daEigenPhase[i] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); } system->daScale = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->iaRowswap = malloc((control->Evolve.iNumBodies-1)*sizeof(int)); SolveEigenVal(body,&control->Evolve,system); system->daetmp = malloc((control->Evolve.iNumBodies-1)*sizeof(double*)); system->daitmp = malloc((control->Evolve.iNumBodies-1)*sizeof(double*)); system->iaRowswap = malloc((control->Evolve.iNumBodies-1)*sizeof(int)); system->dah0 = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->dak0 = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->dap0 = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daq0 = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); for (i=0;i<(control->Evolve.iNumBodies-1);i++) { system->daetmp[i] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daitmp[i] = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); } system->daS = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); system->daT = malloc((control->Evolve.iNumBodies-1)*sizeof(double)); ScaleEigenVec(body,&control->Evolve,system); } } body[iBody].iGravPerts = control->Evolve.iNumBodies - 1; VerifyPerturbersDistOrbLL2(body,control->Evolve.iNumBodies,iBody); for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) { /* h = Ecc*sin(LongP) */ InitializeHeccDistOrbLL2(body,update,iBody,iPert); /* k = Ecc*cos(LongP) */ InitializeKeccDistOrbLL2(body,update,iBody,iPert); /* p = s*sin(LongA) */ InitializePincDistOrbLL2(body,update,iBody,iPert); /* q = s*cos(LongA) */ InitializeQincDistOrbLL2(body,update,iBody,iPert); } // if (body[iBody].bGRCorr) { // fprintf(stderr,"ERROR: %s cannot be used in LL2 orbital solution.\n",options[OPT_GRCORR].cName); // LineExit(files->Infile[iBody+1].cIn,options[OPT_GRCORR].iLine[iBody+1]); // } } control->fnForceBehavior[iBody][iModule]=&ForceBehaviorDistOrb; control->Evolve.fnBodyCopy[iBody][iModule]=&BodyCopyDistOrb; } /***************** DISTORB Update *****************/ void InitializeUpdateDistOrb(BODY *body,UPDATE *update,int iBody) { if (iBody > 0) { if (update[iBody].iNumHecc == 0) update[iBody].iNumVars++; update[iBody].iNumHecc += body[iBody].iGravPerts; if (update[iBody].iNumKecc == 0) update[iBody].iNumVars++; update[iBody].iNumKecc += body[iBody].iGravPerts; if (update[iBody].iNumPinc == 0) update[iBody].iNumVars++; update[iBody].iNumPinc += body[iBody].iGravPerts; if (update[iBody].iNumQinc == 0) update[iBody].iNumVars++; update[iBody].iNumQinc += body[iBody].iGravPerts; if (body[iBody].bGRCorr) { if (body[iBody].iDistOrbModel == RD4) { update[iBody].iNumHecc += 1; update[iBody].iNumKecc += 1; } } } } void FinalizeUpdateHeccDistOrb(BODY *body,UPDATE *update,int *iEqn,int iVar,int iBody,int iFoo) { /* The indexing gets a bit confusing here. iPert = 0 to iGravPerts-1 correspond to all perturbing planets, iPert = iGravPerts corresponds to the stellar general relativistic correction, if applied */ int iPert; if (body[iBody].bGRCorr) { update[iBody].padDHeccDtDistOrb = malloc((body[iBody].iGravPerts+1)*sizeof(double*)); update[iBody].iaHeccDistOrb = malloc((body[iBody].iGravPerts+1)*sizeof(int)); for (iPert=0;iPert<body[iBody].iGravPerts+1;iPert++) { update[iBody].iaModule[iVar][*iEqn] = DISTORB; update[iBody].iaHeccDistOrb[iPert] = (*iEqn)++; } } else { update[iBody].padDHeccDtDistOrb = malloc(body[iBody].iGravPerts*sizeof(double*)); update[iBody].iaHeccDistOrb = malloc(body[iBody].iGravPerts*sizeof(int)); for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) { update[iBody].iaModule[iVar][*iEqn] = DISTORB; update[iBody].iaHeccDistOrb[iPert] = (*iEqn)++; } } } void FinalizeUpdateKeccDistOrb(BODY *body,UPDATE *update,int *iEqn,int iVar,int iBody,int iFoo) { /* The indexing gets a bit confusing here. iPert = 0 to iGravPerts-1 correspond to all perturbing planets, iPert = iGravPerts corresponds to the stellar general relativistic correction, if applied */ int iPert; if (body[iBody].bGRCorr) { update[iBody].padDKeccDtDistOrb = malloc((body[iBody].iGravPerts+1)*sizeof(double*)); update[iBody].iaKeccDistOrb = malloc((body[iBody].iGravPerts+1)*sizeof(int)); for (iPert=0;iPert<body[iBody].iGravPerts+1;iPert++) { update[iBody].iaModule[iVar][*iEqn] = DISTORB; update[iBody].iaKeccDistOrb[iPert] = (*iEqn)++; } } else { update[iBody].padDKeccDtDistOrb = malloc(body[iBody].iGravPerts*sizeof(double*)); update[iBody].iaKeccDistOrb = malloc(body[iBody].iGravPerts*sizeof(int)); for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) { update[iBody].iaModule[iVar][*iEqn] = DISTORB; update[iBody].iaKeccDistOrb[iPert] = (*iEqn)++; } } } void FinalizeUpdatePincDistOrb(BODY *body,UPDATE *update,int *iEqn,int iVar,int iBody,int iFoo) { int iPert; update[iBody].padDPincDtDistOrb = malloc(body[iBody].iGravPerts*sizeof(double*)); update[iBody].iaPincDistOrb = malloc(body[iBody].iGravPerts*sizeof(int)); for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) { update[iBody].iaModule[iVar][*iEqn] = DISTORB; update[iBody].iaPincDistOrb[iPert] = (*iEqn)++; } } void FinalizeUpdateQincDistOrb(BODY *body,UPDATE *update,int *iEqn,int iVar,int iBody,int iFoo) { int iPert; update[iBody].padDQincDtDistOrb = malloc(body[iBody].iGravPerts*sizeof(double*)); update[iBody].iaQincDistOrb = malloc(body[iBody].iGravPerts*sizeof(int)); for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) { update[iBody].iaModule[iVar][*iEqn] = DISTORB; update[iBody].iaQincDistOrb[iPert] = (*iEqn)++; } } /***************** DISTORB Halts *****************/ void CountHaltsDistOrb(HALT *halt,int *iNumHalts) { if (halt->bOverrideMaxEcc == 0) { if (halt->dMaxEcc==1) { (*iNumHalts)++; } } /* halt for close encounters */ if (halt->bHillStab || halt->bCloseEnc) (*iNumHalts)++; } void VerifyHaltDistOrb(BODY *body,CONTROL *control,OPTIONS *options,int iBody,int *iHalt) { int iHaltMaxEcc=0,iNumMaxEcc=0; // If set for one body, set for all /* Mandatory halt for DistOrb */ if (body[iBody].bDistOrb) { if (control->Halt[iBody].bOverrideMaxEcc==0) { /* If you don't override max ecc, and you HAVEN'T set it manually for this body, default to MAXECCDISTORB (== 0.6627434) */ if (control->Halt[iBody].dMaxEcc==1) { control->Halt[iBody].dMaxEcc = MAXECCDISTORB; control->fnHalt[iBody][(*iHalt)++] = &fniHaltMaxEcc; } } // control->Halt[iBody].bHillStab = HILLSTABDISTORB; if (control->Halt[iBody].bHillStab) { control->fnHalt[iBody][(*iHalt)++] = &fniHaltHillStab; } else if (control->Halt[iBody].bCloseEnc) { control->fnHalt[iBody][(*iHalt)++] = &fniHaltCloseEnc; } } } int fniHaltHillStab(BODY *body,EVOLVE *evolve,HALT *halt,IO *io,UPDATE *update,int iBody) { int iPert, jBody; double mu1, mu2, alpha, gamma1, gamma2, delta, crit, hill; if (halt->bHillStab == 1) { for (iBody=1;iBody<evolve->iNumBodies;iBody++) { /* I have to loop over iBody here, ultimately because I want to have to set bHaltHillStab only once, not in every file. There is no easy way to set bHillStab for one body and distribute that to all others before the number of halts are counted. So, I just set it once and check Hill stability for all planets during the one call of HaltHillStab(). */ for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) { jBody = body[iBody].iaGravPerts[iPert]; if (body[jBody].dSemi < body[iBody].dSemi) { //jBody is the inner planet mu1 = body[jBody].dMass/body[0].dMass; mu2 = body[iBody].dMass/body[0].dMass; gamma1 = sqrt(1-(body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc)); gamma2 = sqrt(1-(body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc)); delta = sqrt(body[iBody].dSemi/body[jBody].dSemi); } else if (body[jBody].dSemi > body[iBody].dSemi) { //jBody is the outer planet mu2 = body[jBody].dMass/body[0].dMass; mu1 = body[iBody].dMass/body[0].dMass; gamma2 = sqrt(1-(body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc)); gamma1 = sqrt(1-(body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc)); delta = sqrt(body[jBody].dSemi/body[iBody].dSemi); } alpha = mu1 + mu2; crit = 1.0 + pow((3./alpha),(4./3))*mu1*mu2; hill = pow(alpha,-3)*(mu1+mu2/(delta*delta))*(mu1*gamma1+mu2*gamma2*delta)*\ (mu1*gamma1+mu2*gamma2*delta); if (hill < crit) { if (io->iVerbose >= VERBPROG) { printf("HALT: hill stability criterion failed for planets %d and %d",iBody,jBody); printf(" at %.2e years\n",evolve->dTime/YEARSEC); } return 1; } } } } return 0; } int fniHaltCloseEnc(BODY *body,EVOLVE *evolve,HALT *halt,IO *io,UPDATE *update,int iBody) { int iPert, jBody; double dDR; if (halt->bCloseEnc == 1) { for (iBody=1;iBody<evolve->iNumBodies;iBody++) { for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) { jBody = body[iBody].iaGravPerts[iPert]; if (body[jBody].dSemi < body[iBody].dSemi) { //comparing apocentre of inner planet with pericentre of outer dDR = fabs(body[iBody].dRPeri-body[jBody].dRApo); if (dDR < 4*fndMutualHillRad(body,iBody,jBody)) { if (io->iVerbose >= VERBPROG) { printf("HALT: close encounter between planets %d and %d = ",iBody,jBody); printf(" at %.2e years\n",evolve->dTime/YEARSEC); } return 1; } } else if (body[jBody].dSemi > body[iBody].dSemi) { //comparing apocentre of inner planet with pericentre of outer dDR = fabs(body[jBody].dRPeri-body[iBody].dRApo); if (dDR < 4*fndMutualHillRad(body,iBody,jBody)) { if (io->iVerbose >= VERBPROG) { printf("HALT: close encounter between planets %d and %d = ",iBody,jBody); printf(" at %.2e years\n",evolve->dTime/YEARSEC); } return 1; } } } } } return 0; } /************* DISTORB Outputs ******************/ void WriteEigen(CONTROL *control, SYSTEM *system) { char cEccEigFile[NAMELEN], cIncEigFile[NAMELEN]; int iBody; FILE *fecc, *finc; sprintf(cEccEigFile,"%s.Ecc.Eigen",system->cName); sprintf(cIncEigFile,"%s.Inc.Eigen",system->cName); if (control->Evolve.dTime==0) { fecc = fopen(cEccEigFile,"w"); finc = fopen(cIncEigFile,"w"); } else { fecc = fopen(cEccEigFile,"a"); finc = fopen(cIncEigFile,"a"); } fprintd(fecc,control->Evolve.dTime/fdUnitsTime(control->Units[1].iTime),control->Io.iSciNot,control->Io.iDigits); fprintf(fecc," "); fprintd(finc,control->Evolve.dTime/fdUnitsTime(control->Units[1].iTime),control->Io.iSciNot,control->Io.iDigits); fprintf(finc," "); for (iBody=1;iBody<(control->Evolve.iNumBodies);iBody++) { fprintd(fecc,system->daEigenValEcc[0][iBody-1],control->Io.iSciNot,control->Io.iDigits); fprintf(fecc," "); fprintd(finc,system->daEigenValInc[0][iBody-1],control->Io.iSciNot,control->Io.iDigits); fprintf(finc," "); } fprintf(fecc,"\n"); fprintf(finc,"\n"); fclose(fecc); fclose(finc); } void WriteBodyDEccDtDistOrb(BODY *body,CONTROL *control,OUTPUT *output,SYSTEM *system,UNITS *units,UPDATE *update,int iBody,double *dTmp,char cUnit[]) { double dDeriv; int iPert; /* Ensure that we don't overwrite derivative */ dDeriv=0; for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) dDeriv += 1./sqrt(body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc)*(body[iBody].dHecc*(*(update[iBody].padDHeccDtDistOrb[iPert]))+body[iBody].dKecc*(*(update[iBody].padDKeccDtDistOrb[iPert]))); *dTmp = dDeriv; if (output->bDoNeg[iBody]) { *dTmp *= output->dNeg; strcpy(cUnit,output->cNeg); } else { *dTmp *= fdUnitsTime(units->iTime); fsUnitsRate(units->iTime,cUnit); } } void WriteBodyDSincDtDistOrb(BODY *body,CONTROL *control,OUTPUT *output,SYSTEM *system,UNITS *units,UPDATE *update,int iBody,double *dTmp,char cUnit[]) { double dDeriv; int iPert; /* Ensure that we don't overwrite derivative */ dDeriv=0; for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) dDeriv += 1./sqrt(body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc)*(body[iBody].dPinc*(*(update[iBody].padDPincDtDistOrb[iPert]))+body[iBody].dQinc*(*(update[iBody].padDQincDtDistOrb[iPert]))); *dTmp = dDeriv; if (output->bDoNeg[iBody]) { *dTmp *= output->dNeg; strcpy(cUnit,output->cNeg); } else { *dTmp *= fdUnitsTime(units->iTime); fsUnitsRate(units->iTime,cUnit); } } void WriteBodyDLongPDtDistOrb(BODY *body,CONTROL *control,OUTPUT *output,SYSTEM *system,UNITS *units,UPDATE *update,int iBody,double *dTmp,char cUnit[]) { double dDeriv; int iPert; /* Ensure that we don't overwrite derivative */ dDeriv=0; for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) dDeriv += 1./(body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc)*(body[iBody].dKecc*(*(update[iBody].padDHeccDtDistOrb[iPert]))-body[iBody].dHecc*(*(update[iBody].padDKeccDtDistOrb[iPert]))); *dTmp = dDeriv; if (output->bDoNeg[iBody]) { *dTmp *= output->dNeg; strcpy(cUnit,output->cNeg); } else { *dTmp *= fdUnitsTime(units->iTime); *dTmp /= fdUnitsAngle(units->iAngle); // fsUnitsAngle(units->iAngle,cUnit); fsUnitsAngRate(units,cUnit); } } void WriteBodyDLongADtDistOrb(BODY *body,CONTROL *control,OUTPUT *output,SYSTEM *system,UNITS *units,UPDATE *update,int iBody,double *dTmp,char cUnit[]) { double dDeriv; int iPert; /* Ensure that we don't overwrite derivative */ dDeriv=0; for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) dDeriv += 1./(body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc)*(body[iBody].dQinc*(*(update[iBody].padDPincDtDistOrb[iPert]))-body[iBody].dPinc*(*(update[iBody].padDQincDtDistOrb[iPert]))); *dTmp = dDeriv; if (output->bDoNeg[iBody]) { *dTmp *= output->dNeg; strcpy(cUnit,output->cNeg); } else { *dTmp *= fdUnitsTime(units->iTime); *dTmp /= fdUnitsAngle(units->iAngle); // fsUnitsAngle(units->iAngle,cUnit); fsUnitsAngRate(units,cUnit); } } void WriteBodyDIncDtDistOrb(BODY *body,CONTROL *control,OUTPUT *output,SYSTEM *system,UNITS *units,UPDATE *update,int iBody,double *dTmp,char cUnit[]) { double dDeriv; int iPert; /* Ensure that we don't overwrite derivative */ dDeriv=0; for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) dDeriv += 2./sqrt((1-(body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc))*(body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc))*(body[iBody].dPinc*(*(update[iBody].padDPincDtDistOrb[iPert]))+body[iBody].dQinc*(*(update[iBody].padDQincDtDistOrb[iPert]))); *dTmp = dDeriv; if (output->bDoNeg[iBody]) { *dTmp *= output->dNeg; strcpy(cUnit,output->cNeg); } else { *dTmp *= fdUnitsTime(units->iTime); *dTmp /= fdUnitsAngle(units->iAngle); // fsUnitsAngle(units->iAngle,cUnit); fsUnitsAngRate(units,cUnit); } } void WriteBodySinc(BODY *body,CONTROL *control,OUTPUT *output,SYSTEM *system,UNITS *units,UPDATE *update,int iBody,double *dTmp,char cUnit[]) { *dTmp = sqrt(body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc); strcpy(cUnit,""); } /* void WriteBodyLongA(BODY *body,CONTROL *control,OUTPUT *output,SYSTEM *system,UNITS *units,UPDATE *update,int iBody,double *dTmp,char cUnit[]) { if (body[iBody].bDistOrb) { *dTmp = atan2(body[iBody].dPinc, body[iBody].dQinc); } else if (body[iBody].bGalHabit) { *dTmp = body[iBody].dLongA; } while (*dTmp < 0.0) { *dTmp += 2*PI; } while (*dTmp > 2*PI) { *dTmp -= 2*PI; } if (output->bDoNeg[iBody]) { *dTmp *= output->dNeg; strcpy(cUnit,output->cNeg); } else { *dTmp /= fdUnitsAngle(units->iAngle); fsUnitsAngle(units->iAngle,cUnit); } } */ void WriteBodyPinc(BODY *body,CONTROL *control,OUTPUT *output,SYSTEM *system,UNITS *units,UPDATE *update,int iBody,double *dTmp,char cUnit[]) { *dTmp = body[iBody].dPinc; strcpy(cUnit,""); } void WriteBodyQinc(BODY *body,CONTROL *control,OUTPUT *output,SYSTEM *system,UNITS *units,UPDATE *update,int iBody,double *dTmp,char cUnit[]) { *dTmp = body[iBody].dQinc; strcpy(cUnit,""); } void WriteBodyDHeccDtDistOrb(BODY *body,CONTROL *control,OUTPUT *output,SYSTEM *system,UNITS *units,UPDATE *update,int iBody,double *dTmp,char cUnit[]) { /* need to put check for star's output options in verify */ double dDeriv; int iPert; /* Ensure that we don't overwrite pdDrotDt */ dDeriv=0; for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) dDeriv += *(update[iBody].padDHeccDtDistOrb[iPert]); *dTmp = dDeriv; if (output->bDoNeg[iBody]) { *dTmp *= output->dNeg; strcpy(cUnit,output->cNeg); } else { *dTmp *= fdUnitsTime(units->iTime); fsUnitsRate(units->iTime,cUnit); } } void WriteBodyDKeccDtDistOrb(BODY *body,CONTROL *control,OUTPUT *output,SYSTEM *system,UNITS *units,UPDATE *update,int iBody,double *dTmp,char cUnit[]) { /* need to put check for star's output options in verify */ double dDeriv; int iPert; /* Ensure that we don't overwrite pdDrotDt */ dDeriv=0; for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) dDeriv += *(update[iBody].padDKeccDtDistOrb[iPert]); *dTmp = dDeriv; if (output->bDoNeg[iBody]) { *dTmp *= output->dNeg; strcpy(cUnit,output->cNeg); } else { *dTmp *= fdUnitsTime(units->iTime); fsUnitsRate(units->iTime,cUnit); } } void WriteBodyDPincDtDistOrb(BODY *body,CONTROL *control,OUTPUT *output,SYSTEM *system,UNITS *units,UPDATE *update,int iBody,double *dTmp,char cUnit[]) { /* need to put check for star's output options in verify */ double dDeriv; int iPert; /* Ensure that we don't overwrite pdDrotDt */ dDeriv=0; for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) dDeriv += *(update[iBody].padDPincDtDistOrb[iPert]); *dTmp = dDeriv; if (output->bDoNeg[iBody]) { *dTmp *= output->dNeg; strcpy(cUnit,output->cNeg); } else { *dTmp *= fdUnitsTime(units->iTime); fsUnitsRate(units->iTime,cUnit); } } void WriteBodyDQincDtDistOrb(BODY *body,CONTROL *control,OUTPUT *output,SYSTEM *system,UNITS *units,UPDATE *update,int iBody,double *dTmp,char cUnit[]) { /* need to put check for star's output options in verify */ double dDeriv; int iPert; /* Ensure that we don't overwrite pdDrotDt */ dDeriv=0; for (iPert=0;iPert<body[iBody].iGravPerts;iPert++) dDeriv += *(update[iBody].padDQincDtDistOrb[iPert]); *dTmp = dDeriv; if (output->bDoNeg[iBody]) { *dTmp *= output->dNeg; strcpy(cUnit,output->cNeg); } else { *dTmp *= fdUnitsTime(units->iTime); fsUnitsRate(units->iTime,cUnit); } } void InitializeOutputDistOrb(OUTPUT *output,fnWriteOutput fnWrite[]) { sprintf(output[OUT_DECCDTDISTORB].cName,"DEccDtDistOrb"); sprintf(output[OUT_DECCDTDISTORB].cDescr,"Body's decc/dt in DistOrb"); sprintf(output[OUT_DECCDTDISTORB].cNeg,"1/year"); output[OUT_DECCDTDISTORB].bNeg = 1; output[OUT_DECCDTDISTORB].dNeg = YEARSEC; output[OUT_DECCDTDISTORB].iModuleBit = DISTORB; fnWrite[OUT_DECCDTDISTORB] = &WriteBodyDEccDtDistOrb; sprintf(output[OUT_DSINCDTDISTORB].cName,"DSincDtDistOrb"); sprintf(output[OUT_DSINCDTDISTORB].cDescr,"Body's dsin(.5*Inc)/dt in DistOrb"); sprintf(output[OUT_DSINCDTDISTORB].cNeg,"1/year"); output[OUT_DSINCDTDISTORB].bNeg = 1; output[OUT_DSINCDTDISTORB].dNeg = YEARSEC; output[OUT_DSINCDTDISTORB].iNum = 1; output[OUT_DSINCDTDISTORB].iModuleBit = DISTORB; fnWrite[OUT_DSINCDTDISTORB] = &WriteBodyDSincDtDistOrb; sprintf(output[OUT_DINCDTDISTORB].cName,"DIncDtDistOrb"); sprintf(output[OUT_DINCDTDISTORB].cDescr,"Body's dInc/dt in DistOrb"); sprintf(output[OUT_DINCDTDISTORB].cNeg,"deg/year"); output[OUT_DINCDTDISTORB].bNeg = 1; output[OUT_DINCDTDISTORB].dNeg = YEARSEC/DEGRAD; output[OUT_DINCDTDISTORB].iNum = 1; output[OUT_DINCDTDISTORB].iModuleBit = DISTORB; fnWrite[OUT_DINCDTDISTORB] = &WriteBodyDIncDtDistOrb; sprintf(output[OUT_DLONGPDTDISTORB].cName,"DLongPDtDistOrb"); sprintf(output[OUT_DLONGPDTDISTORB].cDescr,"Body's dvarpi/dt in DistOrb"); sprintf(output[OUT_DLONGPDTDISTORB].cNeg,"deg/yr"); output[OUT_DLONGPDTDISTORB].bNeg = 1; output[OUT_DLONGPDTDISTORB].dNeg = YEARSEC/DEGRAD; output[OUT_DLONGPDTDISTORB].iNum = 1; output[OUT_DLONGPDTDISTORB].iModuleBit = DISTORB; fnWrite[OUT_DLONGPDTDISTORB] = &WriteBodyDLongPDtDistOrb; sprintf(output[OUT_DLONGADTDISTORB].cName,"DLongADtDistOrb"); sprintf(output[OUT_DLONGADTDISTORB].cDescr,"Body's dOmega/dt in DistOrb"); sprintf(output[OUT_DLONGADTDISTORB].cNeg,"deg/yr"); output[OUT_DLONGADTDISTORB].bNeg = 1; output[OUT_DLONGADTDISTORB].dNeg = YEARSEC/DEGRAD; output[OUT_DLONGADTDISTORB].iNum = 1; output[OUT_DLONGADTDISTORB].iModuleBit = DISTORB; fnWrite[OUT_DLONGADTDISTORB] = &WriteBodyDLongADtDistOrb; sprintf(output[OUT_SINC].cName,"Sinc"); sprintf(output[OUT_SINC].cDescr,"Body's sin(1/2*Inclination) in DistOrb"); output[OUT_SINC].iNum = 1; output[OUT_SINC].iModuleBit = DISTORB; fnWrite[OUT_SINC] = &WriteBodySinc; sprintf(output[OUT_PINC].cName,"Pinc"); sprintf(output[OUT_PINC].cDescr,"Body's p = s*sin(Omega) in DistOrb"); output[OUT_PINC].iNum = 1; output[OUT_PINC].iModuleBit = DISTORB; fnWrite[OUT_PINC] = &WriteBodyPinc; sprintf(output[OUT_QINC].cName,"Qinc"); sprintf(output[OUT_QINC].cDescr,"Body's q = s* cos(Omega) in DistOrb"); output[OUT_QINC].iNum = 1; output[OUT_QINC].iModuleBit = DISTORB; fnWrite[OUT_QINC] = &WriteBodyQinc; sprintf(output[OUT_DHECCDTDISTORB].cName,"DHeccDtDistOrb"); sprintf(output[OUT_DHECCDTDISTORB].cDescr,"Body's dh/dt in DistOrb"); sprintf(output[OUT_DHECCDTDISTORB].cNeg,"1/year"); output[OUT_DHECCDTDISTORB].bNeg = 1; output[OUT_DHECCDTDISTORB].dNeg = YEARSEC; output[OUT_DHECCDTDISTORB].iNum = 1; output[OUT_DHECCDTDISTORB].iModuleBit = DISTORB; fnWrite[OUT_DHECCDTDISTORB] = &WriteBodyDHeccDtDistOrb; sprintf(output[OUT_DKECCDTDISTORB].cName,"DKeccDtDistOrb"); sprintf(output[OUT_DKECCDTDISTORB].cDescr,"Body's dk/dt in DistOrb"); sprintf(output[OUT_DKECCDTDISTORB].cNeg,"1/year"); output[OUT_DKECCDTDISTORB].bNeg = 1; output[OUT_DKECCDTDISTORB].dNeg = YEARSEC; output[OUT_DKECCDTDISTORB].iNum = 1; output[OUT_DKECCDTDISTORB].iModuleBit = DISTORB; fnWrite[OUT_DKECCDTDISTORB] = &WriteBodyDKeccDtDistOrb; sprintf(output[OUT_DPINCDTDISTORB].cName,"DPincDtDistOrb"); sprintf(output[OUT_DPINCDTDISTORB].cDescr,"Body's dp/dt in DistOrb"); sprintf(output[OUT_DPINCDTDISTORB].cNeg,"1/year"); output[OUT_DPINCDTDISTORB].bNeg = 1; output[OUT_DPINCDTDISTORB].dNeg = YEARSEC; output[OUT_DPINCDTDISTORB].iNum = 1; output[OUT_DPINCDTDISTORB].iModuleBit = DISTORB; fnWrite[OUT_DPINCDTDISTORB] = &WriteBodyDPincDtDistOrb; sprintf(output[OUT_DQINCDTDISTORB].cName,"DQincDtDistOrb"); sprintf(output[OUT_DQINCDTDISTORB].cDescr,"Body's dq/dt in DistOrb"); sprintf(output[OUT_DQINCDTDISTORB].cNeg,"1/year"); output[OUT_DQINCDTDISTORB].bNeg = 1; output[OUT_DQINCDTDISTORB].dNeg = YEARSEC; output[OUT_DQINCDTDISTORB].iNum = 1; output[OUT_DQINCDTDISTORB].iModuleBit = DISTORB; fnWrite[OUT_DQINCDTDISTORB] = &WriteBodyDQincDtDistOrb; } /************ DISTORB Logging Functions **************/ void LogOptionsDistOrb(CONTROL *control, FILE *fp) { fprintf(fp,"-------- DISTORB Options -----\n\n"); } void LogDistOrb(BODY *body,CONTROL *control,OUTPUT *output,SYSTEM *system,UPDATE *update,fnWriteOutput fnWrite[],FILE *fp) { int iOut; fprintf(fp,"\n----- DISTORB PARAMETERS ------\n"); for (iOut=OUTSTARTDISTORB;iOut<OUTBODYSTARTDISTORB;iOut++) { if (output[iOut].iNum > 0) WriteLogEntry(body,control,&output[iOut],system,update,fnWrite[iOut],fp,0); } } void LogBodyDistOrb(BODY *body,CONTROL *control,OUTPUT *output,SYSTEM *system,UPDATE *update,fnWriteOutput fnWrite[],FILE *fp,int iBody) { int iOut; fprintf(fp,"----- DISTORB PARAMETERS (%s)------\n",body[iBody].cName); for (iOut=OUTBODYSTARTDISTORB;iOut<OUTENDDISTORB;iOut++) { if (output[iOut].iNum > 0) WriteLogEntry(body,control,&output[iOut],system,update,fnWrite[iOut],fp,iBody); } } /************* MODULE Functions ***********/ void AddModuleDistOrb(MODULE *module,int iBody,int iModule) { module->iaModule[iBody][iModule] = DISTORB; module->fnInitializeUpdateTmpBody[iBody][iModule] = &InitializeUpdateTmpBodyDistOrb; module->fnCountHalts[iBody][iModule] = &CountHaltsDistOrb; module->fnLogBody[iBody][iModule] = &LogBodyDistOrb; module->fnReadOptions[iBody][iModule] = &ReadOptionsDistOrb; module->fnVerify[iBody][iModule] = &VerifyDistOrb; module->fnAssignDerivatives[iBody][iModule] = &AssignDistOrbDerivatives; module->fnNullDerivatives[iBody][iModule] = &NullDistOrbDerivatives; module->fnVerifyHalt[iBody][iModule] = &VerifyHaltDistOrb; module->fnInitializeBody[iBody][iModule] = &InitializeBodyDistOrb; module->fnInitializeUpdate[iBody][iModule] = &InitializeUpdateDistOrb; module->fnInitializeOutput[iBody][iModule] = &InitializeOutputDistOrb; module->fnFinalizeUpdateHecc[iBody][iModule] = &FinalizeUpdateHeccDistOrb; module->fnFinalizeUpdateKecc[iBody][iModule] = &FinalizeUpdateKeccDistOrb; module->fnFinalizeUpdatePinc[iBody][iModule] = &FinalizeUpdatePincDistOrb; module->fnFinalizeUpdateQinc[iBody][iModule] = &FinalizeUpdateQincDistOrb; } /************* DistOrb Functions ************/ void PropsAuxDistOrb(BODY *body,EVOLVE *evolve,UPDATE *update,int iBody) { /* Conflict XXX -- Hopefully this is wrong as there should be no calls to Pizza in DISTORB if (body[iBody].bPoise) { body[iBody].dLongP = atan2(body[iBody].dHecc,body[iBody].dKecc); body[iBody].dEcc = sqrt(body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc); } */ body[iBody].dLongP = atan2(body[iBody].dHecc,body[iBody].dKecc); body[iBody].dEcc = sqrt(body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc); body[iBody].dSinc = sqrt(body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc); body[iBody].dRPeri = (1.0-sqrt(body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc))* \ body[iBody].dSemi; body[iBody].dRApo = (1.0+sqrt(body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc))* \ body[iBody].dSemi; } void ForceBehaviorDistOrb(BODY *body,MODULE *module,EVOLVE *evolve,IO *io,SYSTEM *system,UPDATE *update,fnUpdateVariable ***fnUpdate,int iBody,int iModule) { } /* Factorial function. Nuff sed. */ unsigned long int fniFactorial(unsigned int n) { unsigned long int result; if (n == 0) result = 1; else result = n * fniFactorial(n - 1); return result; } /** Number of combinations of k in N @param N Size of set @param k Size of desired subset @return Binomial coefficient N choose k */ int fniNchoosek(int N, int k) { if (N < 0 || k < 0 || N > 10 || k > N) { printf("Error: received N = %d, k = %d\n",N,k); } return fniFactorial(N) / (fniFactorial(k)*fniFactorial(N-k)); } /** Gives the index of a pair of values in N choose 2. For example, for 4 planets, the index for the pair (1,2) -> 0, (1,3) -> 1, (1,4) -> 2, (2,3) -> 3, etc. @param x Index of first planet @param y Index of second planet @param N Number of planets in system @return Index corresponding to planet pair (x,y) */ int fniCombCount(int x, int y, int N) { if (x < y) { return N*(x-1) + (y-1) - fniNchoosek(x+1, 2); } else { return N*(y-1) + (x-1) - fniNchoosek(y+1, 2); } } /** Calculates components AB matrices to find eigenvalues in LL2 problem @param body Struct containing all body information and variables @param j Index j in Laplace coefficients @param jBody Index of perturbed body @param kBody Index of perturbing body @return Component of A or B matrix in rad/year */ double fndABmatrix(BODY *body, int j, int jBody, int kBody) { double AB, alpha, abar, b, n; if (body[jBody].dSemi > body[kBody].dSemi) { alpha = body[kBody].dSemi/body[jBody].dSemi; //internal perturber abar = 1.0; } else if (body[jBody].dSemi < body[kBody].dSemi) { alpha = body[jBody].dSemi/body[kBody].dSemi; //external perturber abar = alpha; } n = KGAUSS*sqrt((body[0].dMass+body[jBody].dMass)/MSUN/(body[jBody].dSemi/AUM*\ body[jBody].dSemi/AUM*body[jBody].dSemi/AUM)); b = fndLaplaceCoeff(alpha, j, 1.5); AB = n/4.0*body[kBody].dMass/(body[0].dMass+body[jBody].dMass)*alpha*abar*b; return AB*365.25; //returns in units of rad/year } /** Calculates mutual hill radii between two bodies @param body Struct containing all body information and variables @param iBody Index of interior body @param jBody Index of exterior body @return Mutual hill radii in meters */ double fndMutualHillRad(BODY *body, int iBody, int jBody) { return 0.5*pow((body[iBody].dMass+body[jBody].dMass)/body[0].dMass,1./3)*\ (body[iBody].dSemi+body[jBody].dSemi); } /** Post-Newtonian correction to AB matrix in LL2 solution @param body Struct containing all body information and variables @param jBody Index of perturbed body @param kBody Index of perturbing body @return Correction to component of AB matrix (added to A and B) in rad/year */ double fndGRCorrMatrix(BODY *body, int jBody, int kBody) { double n, GRC; n = KGAUSS*sqrt((body[0].dMass+body[jBody].dMass)/MSUN/(body[jBody].dSemi/AUM*\ body[jBody].dSemi/AUM*body[jBody].dSemi/AUM)); if (jBody == kBody) { GRC = 3*n*n*n*body[jBody].dSemi/AUM*body[jBody].dSemi/AUM/(cLIGHT/AUM*DAYSEC*\ cLIGHT/AUM*DAYSEC* (1.0-body[jBody].dHecc*body[jBody].dHecc-\ body[jBody].dKecc*body[jBody].dKecc)); return GRC*365.25; } else { return 0.0; } } /** Finds all eigenvalues of an upper Hess. matrix amat @param amat Matrix to find eigenvalues of @param origsize Size of original matrix @param real The real components of the eigenvalues @param imag The imaginary components of the eigenvalues (usually ~ 0) */ void HessEigen(double **amat, int origsize, double real[], double imag[]) { int size, m, smallsub, k, j, iterations, i, mmin; double radic, ulcorner, lrcorner, hhvector, v, u, exshift, s, r, q, p, anorm, cond, value; //s, r, q, and p are defined in numerical recipes eqns 11.6.23, 11.6.25 anorm = fabs(amat[0][0]); for (i = 1; i <= origsize-1; i++) for (j = (i-1); j <= origsize-1; j++) anorm += fabs(amat[i][j]); size = origsize-1; exshift = 0.0; while (size >= 0) { iterations = 0; do { for (smallsub = size; smallsub >= 1; smallsub--) { s = fabs(amat[smallsub-1][smallsub-1]) + fabs(amat[smallsub][smallsub]); if (s == 0.0) s = anorm; cond = fabs(amat[smallsub][smallsub-1])+s; if ((float)cond ==(float) s) break; } lrcorner = amat[size][size]; if (smallsub == size) { real[size] = lrcorner + exshift; imag[size--] = 0.0; } else { ulcorner = amat[size-1][size-1]; hhvector = amat[size][size-1]*amat[size-1][size]; if (smallsub == (size-1)) { p = 0.5*(ulcorner-lrcorner); q = p*p + hhvector; radic = sqrt(fabs(q)); lrcorner += exshift; if (q >= 0.0) { radic = p+(double)fiSign(p)*radic; real[size-1] = real[size] = lrcorner+radic; if (radic) real[size] = lrcorner-hhvector/radic; imag[size-1] = imag[size] = 0.0; } else { real[size-1] = real[size] = lrcorner + p; imag[size-1] = -(imag[size] = radic); } size -= 2; } else { if (iterations == 30) { fprintf(stderr,"Too many iterations in HessEigen routine\n"); exit(EXIT_INPUT); } if (iterations == 10 || iterations == 20) { exshift += lrcorner; for (i = 0; i <= size; i++) amat[i][i] -= lrcorner; s = fabs(amat[size][size-1])+fabs(amat[size-1][size-2]); ulcorner = lrcorner = 0.75*s; hhvector = -0.4375*s*s; } ++iterations; for (m = (size-2); m >= smallsub; m--) { radic = amat[m][m]; r = lrcorner-radic; s = ulcorner-radic; p = (r*s-hhvector)/amat[m+1][m] + amat[m][m+1]; q = amat[m+1][m+1] - radic - r - s; r = amat[m+2][m+1]; s = fabs(p) + fabs(q) + fabs(r); p /= s; q /= s; r /= s; if (m == smallsub) break; u = fabs(amat[m][m-1])*(fabs(q) + fabs(r)); v = fabs(p)*(fabs(amat[m-1][m-1]) + fabs(radic) + fabs(amat[m+1][m+1])); if ((float)(u + v) ==(float) v) break; } for (i = m+2; i <= size; i++) { amat[i][i-2] = 0.0; if (i != (m+2)) amat[i][i-3] = 0.0; } for (k = m; k <= size-1; k++) { if (k != m) { p = amat[k][k-1]; q = amat[k+1][k-1]; r =0.0; if (k != (size-1)) r = amat[k+2][k-1]; if ((lrcorner = fabs(p) + fabs(q) + fabs(r)) != 0.0) { p /= lrcorner; q /= lrcorner; r /= lrcorner; } } value = sqrt(p*p+q*q+r*r); s = (double)fiSign(p)*value; if (s != 0.0) { if (k == m) { if (smallsub != m) amat[k][k-1] = -amat[k][k-1]; } else amat[k][k-1] = -s*lrcorner; p += s; lrcorner = p/s; ulcorner = q/s; radic = r/s; q /= p; r /= p; for (j = k; j <= size; j++) { p = amat[k][j] + q*amat[k+1][j]; if (k != (size-1)) { p += r*amat[k+2][j]; amat[k+2][j] -= p*radic; } amat[k+1][j] -= p*ulcorner; amat[k][j] -= p*lrcorner; } mmin = size < k+3 ? size : k+3; for (i = smallsub; i <= mmin; i++) { p = lrcorner*amat[i][k] + ulcorner*amat[i][k+1]; if (k != (size-1)) { p += radic*amat[i][k+2]; amat[i][k+2] -= p*r; } amat[i][k+1] -= p*q; amat[i][k] -= p; } } } } } } while (smallsub < size-1); } } /** Swaps two rows in a matrix @param matrix Matrix in question @param size The number of rows/columns in matrix (square) @param i One of the rows to be swapped @param j The other row to be swapped */ void RowSwap(double **matrix, int size, int i, int j) { /* swap the ith and jth rows in matrix of size size*/ int k; double dummy; for (k=0;k<size;k++) { dummy = matrix[i][k]; matrix[i][k] = matrix[j][k]; matrix[j][k] = dummy; } } /** Swaps two columns in a matrix @param matrix Matrix in question @param size The number of rows/columns in matrix (square) @param i One of the columns to be swapped @param j The other column to be swapped */ void ColSwap(double **matrix, int size, int i, int j) { /* swap the ith and jth rows in matrix of size size*/ int k; double dummy; for (k=0;k<size;k++) { dummy = matrix[k][i]; matrix[k][i] = matrix[k][j]; matrix[k][j] = dummy; } } /** Reduces a matrix to Upper Hessenberg form @param a Matrix in question @param size The number of rows/columns in matrix a (square) */ void HessReduce(double **a, int size) { int r, rp, rmax, i, j; double max, n; for (r=0;r<size;r++) { max = 0; for (rp=r+1;rp<size;rp++) { if (fabs(a[rp][r])>max) { max = fabs(a[rp][r]); rmax = rp; } } if (max) { RowSwap(a,size,rmax,r+1); ColSwap(a,size,rmax,r+1); for (i=r+2;i<size;i++) { n = a[i][r]/a[r+1][r]; for (j=0;j<size;j++) { a[i][j] -= n*a[r+1][j]; } for (j=0;j<size;j++) { a[j][r+1] += n*a[j][i]; } } } } } /** Balances a matrix @param a Matrix to be balanced @param size The number of rows/columns in matrix a (square) */ void BalanceMatrix(double **a, int size) { int i, j, end = 0; double rownorm, colnorm, factor; while (end == 0) { for (i=0;i<size;i++) { rownorm = 0.0; colnorm = 0.0; for (j=0;j<size;j++) { rownorm += a[i][j]*a[i][j]; colnorm += a[j][i]*a[j][i]; } rownorm = pow(rownorm,0.5); colnorm = pow(colnorm,0.5); factor = sqrt(rownorm/colnorm); for (j=0;j<size;j++) { a[i][j] /= factor; a[j][i] *= factor; } if ((factor*colnorm*factor*colnorm+rownorm/factor*rownorm/factor) > 0.95*(colnorm*colnorm+rownorm*rownorm)) { end = 1; } } } } /** Decomposes matrix to LU form @param amat Matrix to be LU'ed @param copy Copy of matrix containing LU decomposition @param scale Vector of scale factors used in decomposition @param rowswap Indices of swapped rows @param size Size of matrix (square) */ void LUDecomp(double **amat, double **copy, double *scale, int *rowswap, int size) { double sumk, scaletmp, dummy; int i, j, k, swapi; for (i=0;i<size;i++) { scale[i] = 0.0; for (j=0;j<size;j++) { if (fabs(amat[i][j]) > scale[i]) { scale[i] = fabs(amat[i][j]); } } if (scale[i] == 0.0) { fprintf(stderr,"Singular matrix in routine LUDecomp"); exit(EXIT_INPUT); } for (j=0;j<size;j++) { copy[i][j] = amat[i][j]; } scale[i] = 1.0/scale[i]; } for (j=0;j<size;j++) { scaletmp = 0.0; swapi = j; for (i=0;i<size;i++) { sumk = 0.0; if (i<j) { for (k=0;k<i;k++) { sumk += copy[i][k]*copy[k][j]; } } else { for (k=0;k<j;k++) { sumk += copy[i][k]*copy[k][j]; } } copy[i][j] -= sumk; if (i>=j) { if (fabs(scale[i]*copy[i][j]) >= scaletmp) { scaletmp = fabs(scale[i]*copy[i][j]); swapi = i; } } } if (swapi != j) { RowSwap(copy,size,swapi,j); dummy=scale[j]; scale[j]=scale[swapi]; scale[swapi]=dummy; } if (copy[j][j] == 0) { copy[j][j] = TEENY; } for (i=j+1;i<size;i++) { copy[i][j] /= copy[j][j]; } rowswap[j] = swapi; } } /** Solves system of equations involving an LU matrix @param lumat LU matrix @param soln Vector containing output solution @param swap Indices of swapped rows @param size Size of matrix (square) */ void LUSolve(double **lumat, double *soln, int *swap, int size) { int i, j; double dummy, sumj; for (i=0;i<size;i++) { if (swap[i] != i) { dummy = soln[i]; soln[i] = soln[swap[i]]; soln[swap[i]] = dummy; } } for (i=0;i<size;i++) { sumj = 0.0; for (j=0;j<i;j++) { sumj += lumat[i][j]*soln[j]; } soln[i] = soln[i] - sumj; //diagonals of L matrix are all = 1, so division is unnecessary } for (i=(size-1);i>=0;i--) { sumj = 0.0; for (j=i+1;j<size;j++) { sumj += lumat[i][j]*soln[j]; } soln[i] = (soln[i] - sumj)/lumat[i][i]; } } /** Find eccentricity eigenvectors for LL2 solution @param system Struct containing system information @param count Index of eigenvalue @param pls Number of planets */ void FindEigenVecEcc(SYSTEM *system, int count, int pls) { int jj, i, iter = 5; // iter = # of iterations of inverse routine float d; // parity for LU factorization double mag; // normalization for eigenvector // Subtracts eigenvalue from diagonal elements for (jj = 0; jj <= (pls-1); jj++) { system->daA[jj][jj] -= system->daEigenValEcc[0][count-1]; system->daAsoln[jj] = 1.0 / sqrt(pls); for (i=0;i<pls;i++) { system->daAcopy[jj][i] = system->daA[jj][i]; } } LUDecomp(system->daA, system->daAcopy, system->daScale, system->iaRowswap, pls); // Finds eigenvectors by inverse iteration, normalizing at each step for (i = 1; i <= iter; i++) { LUSolve(system->daAcopy,system->daAsoln,system->iaRowswap,pls); mag = 0.0; for (jj = 0; jj <= (pls-1); jj++) { mag += system->daAsoln[jj]*system->daAsoln[jj]; } for (jj = 0; jj <= (pls-1); jj++) { system->daAsoln[jj] /= sqrt(mag); } } } /** Find inclination eigenvectors for LL2 solution @param system Struct containing system information @param count Index of eigenvalue @param pls Number of planets */ void FindEigenVecInc(SYSTEM *system, int count, int pls) { int jj, i, iter = 5; // iter = # of iterations of inverse routine float d; // parity for LU factorization double mag; // normalization for eigenvector // Subtracts eigenvalue from diagonal elements for (jj = 0; jj <= (pls-1); jj++) { system->daB[jj][jj] -= system->daEigenValInc[0][count-1]; system->daBsoln[jj] = 1.0 / sqrt(pls); for (i=0;i<pls;i++) { system->daAcopy[jj][i] = system->daB[jj][i]; } } LUDecomp(system->daB, system->daAcopy, system->daScale, system->iaRowswap, pls); // Finds eigenvectors by inverse iteration, normalizing at each step for (i = 1; i <= iter; i++) { LUSolve(system->daAcopy,system->daBsoln,system->iaRowswap,pls); mag = 0.0; for (jj = 0; jj <= (pls-1); jj++) { mag += system->daBsoln[jj]*system->daBsoln[jj]; } for (jj = 0; jj <= (pls-1); jj++) { system->daBsoln[jj] /= sqrt(mag); } } } /** Find eigenvalues for LL2 solution @param body Struct containing all body information and variables @param evolve Struct containing evolve information @param system Struct containing system information */ void SolveEigenVal(BODY *body, EVOLVE *evolve, SYSTEM *system) { /* This solves the eigenvalue problem and provides an explicit solution to the orbital evolution */ double parity; int j, k, count, i,iBody; /*First pass through calculates matrices and eigenvalues. Each subsequent pass redefines the matrices because they are destroyed by eigenvalue routines, then calculates eigenvectors. */ for (count=0;count<(evolve->iNumBodies);count++) { /* Calculate the initial matrix */ for (j=0;j<(evolve->iNumBodies-1);j++) { system->daA[j][j] = 0.0; system->daB[j][j] = 0.0; for (k=0;k<(evolve->iNumBodies-1);k++) { if (j!=k) { system->daA[j][j] += fndABmatrix(body,1,j+1,k+1); system->daA[j][k] = -fndABmatrix(body,2,j+1,k+1); system->daB[j][j] += -fndABmatrix(body,1,j+1,k+1); system->daB[j][k] = fndABmatrix(body,1,j+1,k+1); } } if (body[j+1].bGRCorr) system->daA[j][j] += fndGRCorrMatrix(body,j+1,j+1); } if (count==0) { BalanceMatrix(system->daA, (evolve->iNumBodies-1)); //balance matrix HessReduce(system->daA, (evolve->iNumBodies-1)); //reduce to upper Hess form BalanceMatrix(system->daB, (evolve->iNumBodies-1)); //balance matrix HessReduce(system->daB, (evolve->iNumBodies-1)); //reduce to upper Hess form HessEigen(system->daA, (evolve->iNumBodies-1), system->daEigenValEcc[0], system->daEigenValEcc[1]); HessEigen(system->daB, (evolve->iNumBodies-1), system->daEigenValInc[0], system->daEigenValInc[1]); } else { FindEigenVecEcc(system,count,(evolve->iNumBodies-1)); FindEigenVecInc(system,count,(evolve->iNumBodies-1)); for (j=0;j<(evolve->iNumBodies-1);j++) { system->daEigenVecEcc[j][count-1] = system->daAsoln[j]; system->daEigenVecInc[j][count-1] = system->daBsoln[j]; } } } } /** Scales eigenvectors to initial conditions @param body Struct containing all body information and variables @param evolve Struct containing evolve information @param system Struct containing system information */ void ScaleEigenVec(BODY *body, EVOLVE *evolve, SYSTEM *system) { int i, j, count; float parity; for (i=0;i<(evolve->iNumBodies-1);i++) { system->dah0[i] = body[i+1].dHecc; system->dak0[i] = body[i+1].dKecc; system->dap0[i] = body[i+1].dPinc; system->daq0[i] = body[i+1].dQinc; for (j=0;j<(evolve->iNumBodies-1);j++) { system->daetmp[i][j] = system->daEigenVecEcc[i][j]; system->daitmp[i][j] = system->daEigenVecInc[i][j]; } } LUDecomp(system->daEigenVecEcc,system->daetmp,system->daScale,system->iaRowswap,(evolve->iNumBodies-1)); LUSolve(system->daetmp,system->dah0,system->iaRowswap,(evolve->iNumBodies-1)); LUSolve(system->daetmp,system->dak0,system->iaRowswap,(evolve->iNumBodies-1)); LUDecomp(system->daEigenVecInc,system->daitmp,system->daScale,system->iaRowswap,(evolve->iNumBodies-1)); LUSolve(system->daitmp,system->dap0,system->iaRowswap,(evolve->iNumBodies-1)); LUSolve(system->daitmp,system->daq0,system->iaRowswap,(evolve->iNumBodies-1)); for (i=0;i<(evolve->iNumBodies-1);i++) { system->daS[i] = sqrt(system->dah0[i]*system->dah0[i] + system->dak0[i]*system->dak0[i]); system->daT[i] = sqrt(system->dap0[i]*system->dap0[i] + system->daq0[i]*system->daq0[i]); for (j=0;j<(evolve->iNumBodies-1);j++) { system->daEigenVecEcc[j][i] *= system->daS[i]; system->daEigenVecInc[j][i] *= system->daT[i]; } system->daEigenPhase[0][i] = atan2(system->dah0[i],system->dak0[i]); system->daEigenPhase[1][i] = atan2(system->dap0[i],system->daq0[i]); } } /** Recalculates Semi-major axis terms in case where RD4 solution is coupled to eqtide @param body Struct containing all body information and variables @param evolve Struct containing evolve information @param system Struct containing system information @param iVerbose Verbosity level of output (currently not in use) */ void RecalcLaplace(BODY *body,EVOLVE *evolve,SYSTEM *system,int iVerbose) { double alpha1, dalpha; int j, iBody, jBody, done=0; j = 0; for (iBody=1;iBody<evolve->iNumBodies-1;iBody++) { for (jBody=iBody+1;jBody<evolve->iNumBodies;jBody++) { if (body[iBody].dSemi < body[jBody].dSemi) { alpha1 = body[iBody].dSemi/body[jBody].dSemi; } else if (body[iBody].dSemi > body[jBody].dSemi) { alpha1 = body[jBody].dSemi/body[iBody].dSemi; } for (j=0;j<26;j++) { dalpha = fabs(alpha1 - system->daAlpha0[0][system->iaLaplaceN[iBody][jBody]][j]); if (dalpha > fabs(system->dDfcrit/system->daLaplaceD[0][system->iaLaplaceN[iBody][jBody]][j])) { system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][j] = system->fnLaplaceF[j][0](alpha1, 0); system->daLaplaceD[0][system->iaLaplaceN[iBody][jBody]][j] = system->fnLaplaceDeriv[j][0](alpha1, 0); system->daAlpha0[0][system->iaLaplaceN[iBody][jBody]][j] = alpha1; // if (iVerbose > VERBPROG) // // printf("Laplace function %d recalculated for bodies (%d, %d) at %f years\n",j+1,iBody,jBody,evolve->dTime/YEARSEC); } } } } } /** Recalculates eigenvalues in case where LL2 solution is coupled to eqtide @param body Struct containing all body information and variables @param evolve Struct containing evolve information @param system Struct containing system information */ void RecalcEigenVals(BODY *body, EVOLVE *evolve, SYSTEM *system) { int iBody, jBody, j, done = 0; double alpha1, dalpha=-1, dalphaTmp; for (iBody=1;iBody<evolve->iNumBodies-1;iBody++) { for (jBody=iBody+1;jBody<evolve->iNumBodies;jBody++) { if (body[iBody].dSemi < body[jBody].dSemi) { alpha1 = body[iBody].dSemi/body[jBody].dSemi; } else if (body[iBody].dSemi > body[jBody].dSemi) { alpha1 = body[jBody].dSemi/body[iBody].dSemi; } for (j=0;j<2;j++) { dalphaTmp = fabs((alpha1 - system->daAlpha0[0][system->iaLaplaceN[iBody][jBody]][0])*system->daLaplaceD[0][system->iaLaplaceN[iBody][jBody]][j]); if (dalphaTmp > dalpha) { dalpha = dalphaTmp; } } } } if (dalpha > system->dDfcrit) { SolveEigenVal(body,evolve,system); ScaleEigenVec(body,evolve,system); for (iBody=1;iBody<evolve->iNumBodies-1;iBody++) { for (jBody=iBody+1;jBody<evolve->iNumBodies;jBody++) { for (j=0;j<2;j++) { system->daLaplaceD[0][system->iaLaplaceN[iBody][jBody]][j] = fndDerivLaplaceCoeff(1,alpha1,j+1,1.5); system->daAlpha0[0][system->iaLaplaceN[iBody][jBody]][j] = alpha1; } } } // printf("Eigenvalues recalculated at %f years\n",evolve->dTime/YEARSEC); } } /* * Invariable plane calculations */ /** First x-term associated rotation into 3D Cartesian coordinates @param body Struct containing all body information and variables @param iBody Index of body in question @return First x-term in rotation into 3D coordinates */ double fndXangle1(BODY *body, int iBody) { return cos(body[iBody].dLongA)*cos(body[iBody].dLongP-body[iBody].dLongA) - sin(body[iBody].dLongA)*sin(body[iBody].dLongP-body[iBody].dLongA)*(1.0-2.*body[iBody].dSinc*body[iBody].dSinc); } /** Second x-term associated rotation into 3D Cartesian coordinates @param body Struct containing all body information and variables @param iBody Index of body in question @return Second x-term in rotation into 3D coordinates */ double fndXangle2(BODY *body, int iBody) { return -cos(body[iBody].dLongA)*sin(body[iBody].dLongP-body[iBody].dLongA) - sin(body[iBody].dLongA)*cos(body[iBody].dLongP-body[iBody].dLongA)*(1.0-2.*body[iBody].dSinc*body[iBody].dSinc); } /** First y-term associated rotation into 3D Cartesian coordinates @param body Struct containing all body information and variables @param iBody Index of body in question @return First y-term in rotation into 3D coordinates */ double fndYangle1(BODY *body, int iBody) { return sin(body[iBody].dLongA)*cos(body[iBody].dLongP-body[iBody].dLongA) + cos(body[iBody].dLongA)*sin(body[iBody].dLongP-body[iBody].dLongA)*(1.0-2.*body[iBody].dSinc*body[iBody].dSinc); } /** Second y-term associated rotation into 3D Cartesian coordinates @param body Struct containing all body information and variables @param iBody Index of body in question @return Second y-term in rotation into 3D coordinates */ double fndYangle2(BODY *body, int iBody) { return -sin(body[iBody].dLongA)*sin(body[iBody].dLongP-body[iBody].dLongA) + cos(body[iBody].dLongA)*cos(body[iBody].dLongP-body[iBody].dLongA)*(1.0-2.*body[iBody].dSinc*body[iBody].dSinc); } /** First z-term associated rotation into 3D Cartesian coordinates @param body Struct containing all body information and variables @param iBody Index of body in question @return First z-term in rotation into 3D coordinates */ double fndZangle1(BODY *body, int iBody) { return sin(body[iBody].dLongP-body[iBody].dLongA)*(2.*body[iBody].dSinc*sqrt(1.0-body[iBody].dSinc*body[iBody].dSinc)); } /** Second z-term associated rotation into 3D Cartesian coordinates @param body Struct containing all body information and variables @param iBody Index of body in question @return Second z-term in rotation into 3D coordinates */ double fndZangle2(BODY *body, int iBody) { return cos(body[iBody].dLongP-body[iBody].dLongA)*(2.*body[iBody].dSinc*sqrt(1.0-body[iBody].dSinc*body[iBody].dSinc)); } /** Calculates x-position in orbital plane @param body Struct containing all body information and variables @param iBody Index of body in question @return Position of planet in x direction (au) */ double fndXinit(BODY *body, int iBody) { return body[iBody].dSemi/AUM * (cos(body[iBody].dEccA) - body[iBody].dEcc); } /** Calculates y-position in orbital plane @param body Struct containing all body information and variables @param iBody Index of body in question @return Position of planet in y direction (au/day) */ double fndYinit(BODY *body, int iBody) { return body[iBody].dSemi/AUM * sqrt(1.0-body[iBody].dEcc*body[iBody].dEcc) * sin(body[iBody].dEccA); } /** Calculates x-velocity in orbital plane @param body Struct containing all body information and variables @param iBody Index of body in question @return Velocity of planet in x direction (au/day) */ double fndVxi(BODY *body, int iBody) { double x, y, mu, n; x = fndXinit(body, iBody); y = fndYinit(body, iBody); mu = KGAUSS*KGAUSS*(body[0].dMass+body[iBody].dMass)/MSUN; n = sqrt(mu/(body[iBody].dSemi/AUM*body[iBody].dSemi/AUM*body[iBody].dSemi/AUM)); return -body[iBody].dSemi/AUM*body[iBody].dSemi/AUM*n*sin(body[iBody].dEccA)\ /sqrt(x*x+y*y); } /** Calculates y-velocity in orbital plane @param body Struct containing all body information and variables @param iBody Index of body in question @return Velocity of planet in y direction (au/day) */ double fndVyi(BODY *body, int iBody) { double x, y, mu, n, v; x = fndXinit(body, iBody); y = fndYinit(body, iBody); mu = KGAUSS*KGAUSS*(body[0].dMass+body[iBody].dMass)/MSUN; n = sqrt(mu/(body[iBody].dSemi/AUM*body[iBody].dSemi/AUM*body[iBody].dSemi/AUM)); v = body[iBody].dSemi/AUM*body[iBody].dSemi/AUM*n*\ sqrt((1.0-body[iBody].dEcc*body[iBody].dEcc)/(x*x+y*y))*cos(body[iBody].dEccA); return v; } /** Solves kepler's equation for one body @param body Struct containing all body information and variables @param iBody Index of body in question */ void kepler_eqn(BODY *body, int iBody) { double di1, di2, di3, fi, fi1, fi2, fi3; if (body[iBody].dMeanA == 0) { body[iBody].dEccA = 0; } else { body[iBody].dEccA = body[iBody].dMeanA + fiSign(sin(body[iBody].dMeanA))*0.85*body[iBody].dEcc; di3 = 1.0; while (di3 > 1e-15) { fi = body[iBody].dEccA - body[iBody].dEcc*sin(body[iBody].dEccA) - body[iBody].dMeanA; fi1 = 1.0 - body[iBody].dEcc*cos(body[iBody].dEccA); fi2 = body[iBody].dEcc*sin(body[iBody].dEccA); fi3 = body[iBody].dEcc*cos(body[iBody].dEccA); di1 = -fi/fi1; di2 = -fi/(fi1+0.5*di1*fi2); di3 = -fi/(fi1+0.5*di2*fi2+1./6.*di2*di2*fi3); body[iBody].dEccA += di3; } } } /** Converts osculating orbital elements to Cartesian coordinates (in au & au/day) @param body Struct containing all body information and variables @param iNumBodies Number of bodies in the system (star & planets) */ void osc2cart(BODY *body, int iNumBodies) { int iBody; double xtmp, ytmp, vxtmp, vytmp; for (iBody=0;iBody<iNumBodies;iBody++) { body[iBody].daCartPos = malloc(3*sizeof(double)); body[iBody].daCartVel = malloc(3*sizeof(double)); if (iBody == 0) { body[iBody].daCartPos[0] = 0; body[iBody].daCartPos[1] = 0; body[iBody].daCartPos[2] = 0; body[iBody].daCartVel[0] = 0; body[iBody].daCartVel[1] = 0; body[iBody].daCartVel[2] = 0; } else { kepler_eqn(body, iBody); xtmp = fndXinit(body, iBody); ytmp = fndYinit(body, iBody); vxtmp = fndVxi(body, iBody); vytmp = fndVyi(body, iBody); body[iBody].daCartPos[0] = xtmp*(fndXangle1(body,iBody))+ytmp*(fndXangle2(body,iBody)); body[iBody].daCartPos[1] = xtmp*(fndYangle1(body,iBody))+ytmp*(fndYangle2(body,iBody)); body[iBody].daCartPos[2] = xtmp*(fndZangle1(body,iBody))+ytmp*(fndZangle2(body,iBody)); body[iBody].daCartVel[0] = vxtmp*(fndXangle1(body,iBody))+vytmp*(fndXangle2(body,iBody)); body[iBody].daCartVel[1] = vxtmp*(fndYangle1(body,iBody))+vytmp*(fndYangle2(body,iBody)); body[iBody].daCartVel[2] = vxtmp*(fndZangle1(body,iBody))+vytmp*(fndZangle2(body,iBody)); } } } /** Converts astrocentric Cartesian coordinates to barycentric @param body Struct containing all body information and variables @param iNumBodies Number of bodies in the system (star & planets) */ void astro2bary(BODY *body, int iNumBodies) { int i, iBody; double *xcom, *vcom, mtotal; xcom = malloc(3*sizeof(double)); vcom = malloc(3*sizeof(double)); mtotal = 0; for (iBody=0;iBody<iNumBodies;iBody++) mtotal += body[iBody].dMass; for (i=0;i<3;i++) { xcom[i] = 0; vcom[i] = 0; for (iBody=1;iBody<iNumBodies;iBody++) { xcom[i] += (body[iBody].dMass*body[iBody].daCartPos[i]/mtotal); vcom[i] += (body[iBody].dMass*body[iBody].daCartVel[i]/mtotal); } } for (i=0;i<3;i++) { for (iBody=0;iBody<iNumBodies;iBody++) { body[iBody].daCartPos[i] -= xcom[i]; body[iBody].daCartVel[i] -= vcom[i]; } } free(xcom); free(vcom); } /** Converts barycentric Cartesian coordinates to astrocentric @param body Struct containing all body information and variables @param iNumBodies Number of bodies in the system (star & planets) */ void bary2astro(BODY *body, int iNumBodies) { int i, iBody; double xtmp, vtmp; for (i=0;i<3;i++) { xtmp = body[0].daCartPos[i]; vtmp = body[0].daCartVel[i]; for (iBody=0;iBody<iNumBodies;iBody++) { body[iBody].daCartPos[i] -= xtmp; body[iBody].daCartVel[i] -= vtmp; } } } /** Calculates cross product of vectors @param a First vector of cross prodect @param b Second vector of cross product @param c Resulting product containing cross product */ void cross(double *a, double *b, double *c) { c[0] = a[1]*b[2] - b[1]*a[2]; c[1] = a[2]*b[0] - b[2]*a[0]; c[2] = a[0]*b[1] - b[0]*a[1]; } /** Calculates angular momentum vector of planetary system @param body Struct containing all body information and variables @param AngMom Resulting angular momentum vector @param iNumBodies Number of bodies in the system (star & planets) */ void angularmom(BODY *body, double *AngMom, int iNumBodies) { double *rxptmp; int i, iBody; rxptmp = malloc(3*sizeof(double)); osc2cart(body, iNumBodies); astro2bary(body, iNumBodies); for (i=0;i<3;i++) AngMom[i]=0; for (iBody=0;iBody<iNumBodies;iBody++) { cross(body[iBody].daCartPos, body[iBody].daCartVel, rxptmp); for (i=0;i<3;i++) { // XXX Why divide by MSUN and not stellar mass? AngMom[i] += body[iBody].dMass/MSUN*rxptmp[i]; } } free(rxptmp); } /** Rotate coordinates into invariable plane @param body Struct containing all body information and variables @param system Struct containing system information @param iNumBodies Number of bodies in the system (star & planets) */ void rotate_inv(BODY *body, SYSTEM *system, int iNumBodies) { double *xtmp, *vtmp; int iBody; xtmp = malloc(3*sizeof(double)); vtmp = malloc(3*sizeof(double)); for (iBody=0;iBody<iNumBodies;iBody++) { xtmp[0] = body[iBody].daCartPos[0]*cos(system->dThetaInvP)+body[iBody].daCartPos[1]*sin(system->dThetaInvP); xtmp[1] = -body[iBody].daCartPos[0]*sin(system->dThetaInvP)+body[iBody].daCartPos[1]*cos(system->dThetaInvP); xtmp[2] = body[iBody].daCartPos[2]; vtmp[0] = body[iBody].daCartVel[0]*cos(system->dThetaInvP)+body[iBody].daCartVel[1]*sin(system->dThetaInvP); vtmp[1] = -body[iBody].daCartVel[0]*sin(system->dThetaInvP)+body[iBody].daCartVel[1]*cos(system->dThetaInvP); vtmp[2] = body[iBody].daCartVel[2]; body[iBody].daCartPos[0] = xtmp[0]*cos(system->dPhiInvP)-xtmp[2]*sin(system->dPhiInvP); body[iBody].daCartPos[1] = xtmp[1]; body[iBody].daCartPos[2] = xtmp[0]*sin(system->dPhiInvP)+xtmp[2]*cos(system->dPhiInvP); body[iBody].daCartVel[0] = vtmp[0]*cos(system->dPhiInvP)-vtmp[2]*sin(system->dPhiInvP); body[iBody].daCartVel[1] = vtmp[1]; body[iBody].daCartVel[2] = vtmp[0]*sin(system->dPhiInvP)+vtmp[2]*cos(system->dPhiInvP); } free(xtmp); free(vtmp); } /** Calculates the magnitude of a vector @param vector Any vector you what the magnitude of @return The magnitude of vector */ double normv(double *vector) { return sqrt(vector[0]*vector[0]+vector[1]*vector[1]+vector[2]*vector[2]); } /** Converts Cartesian coordinates (in au & au/day) to osculating orbital elements @param body Struct containing all body information and variables @param iNumBodies Number of bodies in the system (star & planets) */ void cart2osc(BODY *body, int iNumBodies) { int iBody; double r, vsq, rdot, mu, *h, hsq, sinwf, coswf, sinf, cosf, sinw, cosw, cosE, f; h = malloc(3*sizeof(double)); for (iBody=1;iBody<iNumBodies;iBody++) { r = normv(body[iBody].daCartPos); vsq = normv(body[iBody].daCartVel)*normv(body[iBody].daCartVel); rdot = (body[iBody].daCartPos[0]*body[iBody].daCartVel[0]+body[iBody].daCartPos[1]*body[iBody].daCartVel[1]+\ body[iBody].daCartPos[2]*body[iBody].daCartVel[2])/r; mu = KGAUSS*KGAUSS*(body[0].dMass+body[iBody].dMass)/MSUN; cross(body[iBody].daCartPos, body[iBody].daCartVel, h); hsq = normv(h)*normv(h); body[iBody].dSemi = pow((2.0/r - vsq/mu),-1)*AUM; if (body[iBody].dEcc != 0) { body[iBody].dEcc = sqrt(1.0 - hsq/(mu*body[iBody].dSemi/AUM)); } body[iBody].dSinc = sin(0.5 * acos(h[2]/normv(h))); body[iBody].dLongA = atan2(h[0],-h[1]); if (body[iBody].dLongA < 0) body[iBody].dLongA += 2.0*PI; sinwf = body[iBody].daCartPos[2] / (r*2.*body[iBody].dSinc*sqrt(1.0-body[iBody].dSinc*body[iBody].dSinc)); coswf = (body[iBody].daCartPos[0]/r + sin(body[iBody].dLongA)*sinwf*(1.0-2.*body[iBody].dSinc*body[iBody].dSinc))/cos(body[iBody].dLongA); sinf = body[iBody].dSemi/AUM*(1.0-body[iBody].dEcc*body[iBody].dEcc)*rdot/(normv(h)*body[iBody].dEcc); cosf = (body[iBody].dSemi/AUM*(1.0-body[iBody].dEcc*body[iBody].dEcc)/r - 1.0)/body[iBody].dEcc; if (body[iBody].dEcc != 0) { sinw = sinwf*cosf - coswf*sinf; cosw = sinwf*sinf + coswf*cosf; body[iBody].dArgP = atan2(sinw,cosw); body[iBody].dLongP = atan2(sinw, cosw) + body[iBody].dLongA; if (body[iBody].dLongP >= 2.*PI) { body[iBody].dLongP -= 2.*PI; } else if (body[iBody].dLongP < 0.0) { body[iBody].dLongP += 2.*PI; } if (body[iBody].dArgP >= 2.*PI) { body[iBody].dArgP -= 2.*PI; } else if (body[iBody].dArgP < 0.0) { body[iBody].dArgP += 2.*PI; } } f = atan2(sinf, cosf); if (f >= 2.*PI) { f -= 2.*PI; } else if (f < 0.0) { f += 2.*PI; } cosE = (cos(f)+body[iBody].dEcc) / (1.0+body[iBody].dEcc*cos(f)); if (f <= PI) body[iBody].dEccA = acos(cosE); if (f > PI) body[iBody].dEccA = 2.*PI - acos(cosE); body[iBody].dMeanA = body[iBody].dEccA - body[iBody].dEcc*sin(body[iBody].dEccA); if (body[iBody].dMeanA < 0) body[iBody].dMeanA += 2*PI; if (body[iBody].dMeanA >= 2*PI) body[iBody].dMeanA -= 2*PI; } free(h); } /** Calculates coordinates of planetary system with respect to invariable plane @param body Struct containing all body information and variables @param system Struct containing system information @param iNumBodies Number of bodies in the system (star & planets) */ void inv_plane(BODY *body, SYSTEM *system, int iNumBodies) { int iBody; double AngMom[3] = {0.0,0.0,0.0}; /* locally allocates this memory */ /* Loop below calculates true anomaly at equinox for planets with DistRot enabled. This angle is invariant under rotations. */ for (iBody=1;iBody<iNumBodies;iBody++) { if (body[iBody].bDistRot) { // XXX No mention of other modules is allowed!! body[iBody].dTrueApA = 2*PI - (body[iBody].dPrecA+body[iBody].dLongP); while (body[iBody].dTrueApA<0) { body[iBody].dTrueApA += 2*PI; } } } angularmom(body, AngMom, iNumBodies); system->dThetaInvP = atan2(AngMom[1],AngMom[0]); system->dPhiInvP = atan2(sqrt(AngMom[0]*AngMom[0]+AngMom[1]*AngMom[1]),AngMom[2]); rotate_inv(body, system, iNumBodies); bary2astro(body, iNumBodies); cart2osc(body, iNumBodies); /* Loop below recalculates precession param for planets with DistRot enabled.*/ for (iBody=1;iBody<iNumBodies;iBody++) { if (body[iBody].bDistRot) { body[iBody].dPrecA = 2*PI - (body[iBody].dTrueApA+body[iBody].dLongP); while (body[iBody].dPrecA<0) { body[iBody].dPrecA += 2*PI; } CalcXYZobl(body, iBody); } CalcHK(body, iBody); CalcPQ(body, iBody); } } // /* * Semi-major axis functions */ /** Laplace coefficient used in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @param dIndexS Index s of Laplace Coefficients (usually s = 1/2, 3/2, or 5/2) @return Laplace coefficient */ double fndLaplaceCoeff(double dAxRatio, int iIndexJ, double dIndexS) { /* Calculates Laplace coefficients via series form (M&D eqn 6.68) taking dAxRatio = ratio of semi-major axes and j and s as arguments */ double fac = 1.0, sum = 1.0, term = 1.0; int k, n = 1; if (iIndexJ == 1) fac = dIndexS * dAxRatio; else { for (k = 1; k <= iIndexJ; k++) fac *= (dIndexS + k - 1.0) / (k) * dAxRatio; } while (term >= 1.0e-15*sum) { term = 1.0; for (k = 1; k <= n; k++) { term *= (dIndexS + k - 1.0) * (dIndexS + iIndexJ + k - 1.0) / (k * (iIndexJ + k)) * dAxRatio*dAxRatio; } sum = sum + term; n++; } return 2.0*fac*sum; } /** Derivative in d/d(alpha) of Laplace coefficient used in disturbing function @param iNthDeriv Order of derivative to be taken @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @param dIndexS Index s of Laplace Coefficients (usually s = 1/2, 3/2, or 5/2) @return Laplace coefficient */ double fndDerivLaplaceCoeff(int iNthDeriv, double dAxRatio, int iIndexJ, double dIndexS) { /* Calculates nth order derivative of Laplace coefficient using a recursive scheme */ double result; if (iNthDeriv == 1) result = dIndexS * (fndLaplaceCoeff(dAxRatio, abs(iIndexJ-1), dIndexS + 1.0) - 2 * dAxRatio * \ fndLaplaceCoeff(dAxRatio, iIndexJ, dIndexS + 1.0) + fndLaplaceCoeff(dAxRatio, iIndexJ + 1, dIndexS + 1.0)); else if (iNthDeriv == 2) result = dIndexS * (fndDerivLaplaceCoeff(1,dAxRatio,abs(iIndexJ-1),dIndexS+1.) - 2 * dAxRatio * \ fndDerivLaplaceCoeff(1,dAxRatio,iIndexJ,dIndexS+1.)+fndDerivLaplaceCoeff(1,dAxRatio,iIndexJ+1,dIndexS+1.) -\ 2 * fndLaplaceCoeff(dAxRatio,iIndexJ,dIndexS+1.)); else result = dIndexS * (fndDerivLaplaceCoeff(iNthDeriv-1,dAxRatio,abs(iIndexJ-1),dIndexS+1.) - 2 * dAxRatio * \ fndDerivLaplaceCoeff(iNthDeriv-1,dAxRatio,iIndexJ,dIndexS+1.)+fndDerivLaplaceCoeff(iNthDeriv-1,dAxRatio,iIndexJ+1,dIndexS+1.) - 2 * (iNthDeriv-1) * fndDerivLaplaceCoeff(iNthDeriv-2,dAxRatio,iIndexJ,dIndexS+1.)); return result; } /*--------- f1 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF1(double dAxRatio, int iIndexJ) { return 1./2 * fndLaplaceCoeff(A(iIndexJ)); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF1Dalpha(double dAxRatio, int iIndexJ) { return 1./2 * fndDerivLaplaceCoeff(1,A(iIndexJ)); } /*--------- f2 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF2(double dAxRatio, int iIndexJ) { return 1./8* (-4.*iIndexJ*iIndexJ * fndLaplaceCoeff(A(iIndexJ)) + 2.*dAxRatio * fndDerivLaplaceCoeff(1,A(iIndexJ))\ + dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,A(iIndexJ)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF2Dalpha(double dAxRatio, int iIndexJ) { return 1./8 * ( (2.-4.*iIndexJ*iIndexJ)*fndDerivLaplaceCoeff(1,A(iIndexJ)) + 4.*dAxRatio*fndDerivLaplaceCoeff(2,A(iIndexJ)) + dAxRatio*dAxRatio*fndDerivLaplaceCoeff(3,A(iIndexJ)) ); } /*--------- f3 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF3(double dAxRatio, int iIndexJ) { return -1./4*dAxRatio * ( fndLaplaceCoeff(B(abs(iIndexJ-1))) + fndLaplaceCoeff(B(iIndexJ+1)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF3Dalpha(double dAxRatio, int iIndexJ) { return -1./4*( (fndLaplaceCoeff(B(abs(iIndexJ-1))) + fndLaplaceCoeff(B(iIndexJ+1))) + dAxRatio*(fndDerivLaplaceCoeff(1,B(abs(iIndexJ-1))) + fndDerivLaplaceCoeff(1,B(iIndexJ+1))) ); } /*--------- f4 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF4(double dAxRatio, int iIndexJ) { return 1./128 * ( (-9.*iIndexJ*iIndexJ + 16.*iIndexJ*iIndexJ*iIndexJ*iIndexJ) * fndLaplaceCoeff(A(iIndexJ)) \ -8.*iIndexJ*iIndexJ*dAxRatio * fndDerivLaplaceCoeff(1,A(iIndexJ)) \ - 8.*iIndexJ*iIndexJ*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,A(iIndexJ)) \ + 4.*dAxRatio*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,A(iIndexJ)) \ + dAxRatio*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(4,A(iIndexJ)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF4Dalpha(double dAxRatio, int iIndexJ) { return 1./128 * ( (-17.*iIndexJ*iIndexJ+16.*iIndexJ*iIndexJ*iIndexJ*iIndexJ)*fndDerivLaplaceCoeff(1,A(iIndexJ)) \ - 24.*iIndexJ*iIndexJ*dAxRatio*fndDerivLaplaceCoeff(2,A(iIndexJ)) \ + (12.-8.*iIndexJ*iIndexJ)*dAxRatio*dAxRatio*fndDerivLaplaceCoeff(3,A(iIndexJ)) \ + (8.*dAxRatio*dAxRatio*dAxRatio)*fndDerivLaplaceCoeff(4,A(iIndexJ)) \ + dAxRatio*dAxRatio*dAxRatio*dAxRatio*fndDerivLaplaceCoeff(5,A(iIndexJ)) ); } /*--------- f5 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF5(double dAxRatio, int iIndexJ) { return 1./32 * ( 16.*iIndexJ*iIndexJ*iIndexJ*iIndexJ * fndLaplaceCoeff(A(iIndexJ)) \ + (4. - 16.*iIndexJ*iIndexJ) * dAxRatio * fndDerivLaplaceCoeff(1,A(iIndexJ)) \ + (14. - 8.*iIndexJ*iIndexJ) * dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,A(iIndexJ)) \ + 8.*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,A(iIndexJ)) \ + dAxRatio*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(4,A(iIndexJ)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF5Dalpha(double dAxRatio, int iIndexJ) { return 1./32 * ( (4.-16.*iIndexJ*iIndexJ+16.*iIndexJ*iIndexJ*iIndexJ*iIndexJ)*fndDerivLaplaceCoeff(1,A(iIndexJ)) \ + (32.-32.*iIndexJ*iIndexJ)*dAxRatio*fndDerivLaplaceCoeff(2,A(iIndexJ)) \ + (38.-8.*iIndexJ*iIndexJ)*dAxRatio*dAxRatio*fndDerivLaplaceCoeff(3,A(iIndexJ)) \ + 12.*dAxRatio*dAxRatio*dAxRatio*fndDerivLaplaceCoeff(4,A(iIndexJ)) \ + dAxRatio*dAxRatio*dAxRatio*dAxRatio*fndDerivLaplaceCoeff(5,A(iIndexJ)) ); } /*--------- f6 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF6(double dAxRatio, int iIndexJ) { return 1./128 * ( (-17.*iIndexJ*iIndexJ + 16.*iIndexJ*iIndexJ*iIndexJ*iIndexJ) * fndLaplaceCoeff(A(iIndexJ)) \ + (1. - iIndexJ*iIndexJ) * 24. * dAxRatio * fndDerivLaplaceCoeff(1,A(iIndexJ)) \ + (36. - 8.*iIndexJ*iIndexJ) * dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,A(iIndexJ)) \ + 12.*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,A(iIndexJ)) \ + dAxRatio*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(4,A(iIndexJ)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF6Dalpha(double dAxRatio, int iIndexJ) { return 1./128 * ( (24.-41.*iIndexJ*iIndexJ+16.*iIndexJ*iIndexJ*iIndexJ*iIndexJ)*fndDerivLaplaceCoeff(1,A(iIndexJ)) \ + (96.- 40.*iIndexJ*iIndexJ)*dAxRatio*fndDerivLaplaceCoeff(2,A(iIndexJ)) \ + (72.-8.*iIndexJ*iIndexJ)*dAxRatio*dAxRatio*fndDerivLaplaceCoeff(3,A(iIndexJ)) \ + (16.*dAxRatio*dAxRatio*dAxRatio)*fndDerivLaplaceCoeff(4,A(iIndexJ)) \ + dAxRatio*dAxRatio*dAxRatio*dAxRatio*fndDerivLaplaceCoeff(5,A(iIndexJ)) ); } /*--------- f7 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF7(double dAxRatio, int iIndexJ) { return 1./16*( (-2.+4.*iIndexJ*iIndexJ)*dAxRatio*(fndLaplaceCoeff(B(abs(iIndexJ-1)))+fndLaplaceCoeff(B(iIndexJ+1))) - 4.*dAxRatio*dAxRatio * (fndDerivLaplaceCoeff(1,B(abs(iIndexJ-1))) + fndDerivLaplaceCoeff(1,B(iIndexJ+1))) \ - dAxRatio*dAxRatio*dAxRatio * (fndDerivLaplaceCoeff(2,B(abs(iIndexJ-1))) + fndDerivLaplaceCoeff(2,B(iIndexJ+1))) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF7Dalpha(double dAxRatio, int iIndexJ) { return 1./16 * ( (-2.+4.*iIndexJ*iIndexJ)*(fndLaplaceCoeff(B(abs(iIndexJ-1))) + fndLaplaceCoeff(B(iIndexJ+1))) \ -(10.-4.*iIndexJ*iIndexJ)*dAxRatio*(fndDerivLaplaceCoeff(1,B(abs(iIndexJ-1)))+fndDerivLaplaceCoeff(1,B(iIndexJ+1)))\ - 7.*dAxRatio*dAxRatio*(fndDerivLaplaceCoeff(2,B(abs(iIndexJ-1)))+fndDerivLaplaceCoeff(2,B(iIndexJ+1)))\ - dAxRatio*dAxRatio*dAxRatio*(fndDerivLaplaceCoeff(3,B(abs(iIndexJ-1)))+fndDerivLaplaceCoeff(3,B(iIndexJ+1))) ); } /*--------- f8 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF8(double dAxRatio, int iIndexJ) { return 3./16 * dAxRatio*dAxRatio * ( fndLaplaceCoeff(C(abs(iIndexJ-2))) \ + 4. * fndLaplaceCoeff(C(iIndexJ)) + fndLaplaceCoeff(C(iIndexJ+2)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF8Dalpha(double dAxRatio, int iIndexJ) { return 3./16 * dAxRatio* ( 2*(fndLaplaceCoeff(C(abs(iIndexJ-2))) \ + 4. * fndLaplaceCoeff(C(iIndexJ)) + fndLaplaceCoeff(C(iIndexJ+2))) \ + dAxRatio*(fndDerivLaplaceCoeff(1,C(abs(iIndexJ-2))) \ + 4. * fndDerivLaplaceCoeff(1,C(iIndexJ)) + fndDerivLaplaceCoeff(1,C(iIndexJ+2))) ); } /*--------- f9 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF9(double dAxRatio, int iIndexJ) { return 1./4 * dAxRatio * (fndLaplaceCoeff(B(abs(iIndexJ-1))) + fndLaplaceCoeff(B(iIndexJ+1))) \ + 3./8 * dAxRatio*dAxRatio * ( fndLaplaceCoeff(C(abs(iIndexJ-2))) + 10. * fndLaplaceCoeff(C(iIndexJ)) \ + fndLaplaceCoeff(C(iIndexJ+2)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF9Dalpha(double dAxRatio, int iIndexJ) { return 1./4 * ( (fndLaplaceCoeff(B(abs(iIndexJ-1))) + fndLaplaceCoeff(B(iIndexJ+1))) \ + dAxRatio*(fndDerivLaplaceCoeff(1,B(abs(iIndexJ-1))) + fndDerivLaplaceCoeff(1,B(iIndexJ+1))) ) \ + 3./8 * dAxRatio * ( 2*(fndLaplaceCoeff(C(abs(iIndexJ-2))) + 10. * fndLaplaceCoeff(C(iIndexJ)) \ + fndLaplaceCoeff(C(iIndexJ+2))) + dAxRatio*(fndDerivLaplaceCoeff(1,C(abs(iIndexJ-2)))\ + 10. * fndDerivLaplaceCoeff(1,C(iIndexJ)) + fndDerivLaplaceCoeff(1,C(iIndexJ+2))) ); } /*--------- f10 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF10(double dAxRatio, int iIndexJ) { return 1./4 * ( (2. + 6.*iIndexJ + 4.*iIndexJ*iIndexJ) * fndLaplaceCoeff(A(iIndexJ+1)) \ - 2. * dAxRatio * fndDerivLaplaceCoeff(1,A(iIndexJ+1)) \ - dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,A(iIndexJ+1)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF10Dalpha(double dAxRatio, int iIndexJ) { return 1./4 * ( (6.*iIndexJ + 4.*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(1,A(iIndexJ+1)) \ - 4. * dAxRatio * fndDerivLaplaceCoeff(2,A(iIndexJ+1)) \ - dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,A(iIndexJ+1)) ); } /*--------- f11 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF11(double dAxRatio, int iIndexJ) { return 1./32*((-6.*iIndexJ-26.*iIndexJ*iIndexJ-36.*iIndexJ*iIndexJ*iIndexJ \ -16*iIndexJ*iIndexJ*iIndexJ*iIndexJ)*fndLaplaceCoeff(A(iIndexJ+1))\ + dAxRatio * (6*iIndexJ + 12*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(1,A(iIndexJ+1)) \ + dAxRatio*dAxRatio * (-4. + 7*iIndexJ + 8*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(2,A(iIndexJ+1)) \ - 6.*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,A(iIndexJ+1)) \ - dAxRatio*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(4,A(iIndexJ+1)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF11Dalpha(double dAxRatio, int iIndexJ) { return 1./32*((-14.*iIndexJ*iIndexJ-36.*iIndexJ*iIndexJ*iIndexJ-16*iIndexJ*iIndexJ*iIndexJ*iIndexJ)*fndDerivLaplaceCoeff(1,A(iIndexJ+1))\ + dAxRatio * (-8.+20.*iIndexJ+28.*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(2,A(iIndexJ+1)) \ + dAxRatio*dAxRatio * (-22.+7.*iIndexJ+8.*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(3,A(iIndexJ+1)) \ - 10.*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(4,A(iIndexJ+1)) \ - dAxRatio*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(5,A(iIndexJ+1)) ); } /*--------- f12 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF12(double dAxRatio, int iIndexJ) { return 1./32 * ( (4. + 2.*iIndexJ - 22.*iIndexJ*iIndexJ - 36.*iIndexJ*iIndexJ*iIndexJ - 16.*iIndexJ*iIndexJ*iIndexJ*iIndexJ) * \ fndLaplaceCoeff(A(iIndexJ+1)) \ + dAxRatio * (-4. + 22.*iIndexJ + 20.*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(1,A(iIndexJ+1)) \ + dAxRatio*dAxRatio * (-22. + 7.*iIndexJ + 8.*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(2,A(iIndexJ+1)) \ - 10.*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,A(iIndexJ+1)) \ - dAxRatio*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(4,A(iIndexJ+1)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF12Dalpha(double dAxRatio, int iIndexJ) { return 1./32 * ( (24.*iIndexJ-2.*iIndexJ*iIndexJ-36.*iIndexJ*iIndexJ*iIndexJ-16.*iIndexJ*iIndexJ*iIndexJ*iIndexJ) * \ fndDerivLaplaceCoeff(1,A(iIndexJ+1)) \ + dAxRatio * (-48. + 36.*iIndexJ + 36.*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(2,A(iIndexJ+1)) \ + dAxRatio*dAxRatio * (-52. + 7.*iIndexJ + 8.*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(3,A(iIndexJ+1)) \ - 14.*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(4,A(iIndexJ+1)) \ - dAxRatio*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(5,A(iIndexJ+1)) ); } /*--------- f13 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF13(double dAxRatio, int iIndexJ) { return 1./8*((-6.*iIndexJ-4.*iIndexJ*iIndexJ)*dAxRatio*(fndLaplaceCoeff(B(iIndexJ))+fndLaplaceCoeff(B(iIndexJ+2)))\ + 4.*dAxRatio*dAxRatio * (fndDerivLaplaceCoeff(1,B(iIndexJ)) + fndDerivLaplaceCoeff(1,B(iIndexJ+2)))\ + dAxRatio*dAxRatio*dAxRatio * (fndDerivLaplaceCoeff(2,B(iIndexJ)) + fndDerivLaplaceCoeff(2,B(iIndexJ+2))) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF13Dalpha(double dAxRatio, int iIndexJ) { return 1./8*( (-6.*iIndexJ-4.*iIndexJ*iIndexJ)*(fndLaplaceCoeff(B(iIndexJ))+fndLaplaceCoeff(B(iIndexJ+2)))\ + (8.-6.*iIndexJ-4.*iIndexJ*iIndexJ)*dAxRatio \ * (fndDerivLaplaceCoeff(1,B(iIndexJ))+fndDerivLaplaceCoeff(1,B(iIndexJ+2)))\ + 7.*dAxRatio*dAxRatio * (fndDerivLaplaceCoeff(2,B(iIndexJ)) + fndDerivLaplaceCoeff(2,B(iIndexJ+2))) \ + dAxRatio*dAxRatio*dAxRatio * (fndDerivLaplaceCoeff(3,B(iIndexJ)) + fndDerivLaplaceCoeff(3,B(iIndexJ+2))) ); } /*--------- f14 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF14(double dAxRatio, int iIndexJ) { return dAxRatio * fndLaplaceCoeff(B(iIndexJ+1)); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF14Dalpha(double dAxRatio, int iIndexJ) { return fndLaplaceCoeff(B(iIndexJ+1)) + dAxRatio*fndDerivLaplaceCoeff(1,B(iIndexJ+1)); } /*--------- f15 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF15(double dAxRatio, int iIndexJ) { return 1./4 * ( (2. - 4.*iIndexJ*iIndexJ) * dAxRatio * fndLaplaceCoeff(B(iIndexJ+1)) \ + 4.*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(1,B(iIndexJ+1)) \ + dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(iIndexJ+1)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF15Dalpha(double dAxRatio, int iIndexJ) { return 1./4 * ( (2.-4.*iIndexJ*iIndexJ) * fndLaplaceCoeff(B(iIndexJ+1)) \ + (10.-4.*iIndexJ*iIndexJ)*dAxRatio * fndDerivLaplaceCoeff(1,B(iIndexJ+1)) \ + 7.*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(iIndexJ+1)) \ + dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,B(iIndexJ+1)) ); } /*--------- f16 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF16(double dAxRatio, int iIndexJ) { return -1./2 * dAxRatio * fndLaplaceCoeff(B(iIndexJ+1)) \ -3.* dAxRatio*dAxRatio * fndLaplaceCoeff(C(iIndexJ)) - 3./2 * dAxRatio*dAxRatio * fndLaplaceCoeff(C(iIndexJ+2)); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF16Dalpha(double dAxRatio, int iIndexJ) { return -1./2 * ( fndLaplaceCoeff(B(iIndexJ+1)) + dAxRatio*fndDerivLaplaceCoeff(1,B(iIndexJ+1)) ) \ -3.* dAxRatio * ( 2.*(fndLaplaceCoeff(C(iIndexJ)) + 1./2 * fndLaplaceCoeff(C(iIndexJ+2))) \ + dAxRatio*(fndDerivLaplaceCoeff(1,C(iIndexJ)) + 1./2 * fndDerivLaplaceCoeff(1,C(iIndexJ+2))) ); } /*--------- f17 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF17(double dAxRatio, int iIndexJ) { return 1./64 * ( (12. + 64.*iIndexJ + 109.*iIndexJ*iIndexJ + 72.*iIndexJ*iIndexJ*iIndexJ + 16.*iIndexJ*iIndexJ*iIndexJ*iIndexJ) \ * fndLaplaceCoeff(A(iIndexJ+2)) \ - dAxRatio * (12. + 28.*iIndexJ + 16.*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(1,A(iIndexJ+2)) \ + dAxRatio*dAxRatio * (6. - 14.*iIndexJ - 8.*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(2,A(iIndexJ+2)) \ + 8.*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,A(iIndexJ+2)) \ + dAxRatio*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(4,A(iIndexJ+2)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF17Dalpha(double dAxRatio, int iIndexJ) { return 1./64 * ( (36.*iIndexJ + 93.*iIndexJ*iIndexJ + 72.*iIndexJ*iIndexJ*iIndexJ*iIndexJ + 16.*iIndexJ*iIndexJ*iIndexJ*iIndexJ) \ * fndDerivLaplaceCoeff(1,A(iIndexJ+2)) \ - dAxRatio * (56.*iIndexJ + 32.*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(2,A(iIndexJ+2)) \ + dAxRatio*dAxRatio * (30. - 14.*iIndexJ - 8.*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(3,A(iIndexJ+2)) \ + 12.*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(4,A(iIndexJ+2)) \ + dAxRatio*dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(5,A(iIndexJ+2)) ); } /*--------- f18 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF18(double dAxRatio, int iIndexJ) { return 1./16 * ( (12. - 15.*iIndexJ + 4.*iIndexJ*iIndexJ) * dAxRatio * fndLaplaceCoeff(B(abs(iIndexJ-1))) \ + dAxRatio*dAxRatio * (8. - 4.*iIndexJ) * fndDerivLaplaceCoeff(1,B(abs(iIndexJ-1))) \ + dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(abs(iIndexJ-1))) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF18Dalpha(double dAxRatio, int iIndexJ) { return 1./16 * ( (12. - 15.*iIndexJ + 4.*iIndexJ*iIndexJ) * fndLaplaceCoeff(B(abs(iIndexJ-1))) \ + dAxRatio * (28. - 23.*iIndexJ + 4.*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(1,B(abs(iIndexJ-1))) \ + (11.-4.*iIndexJ)*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(abs(iIndexJ-1))) \ + dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,B(abs(iIndexJ-1)))); } /*--------- f19 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF19(double dAxRatio, int iIndexJ) { return 1./8 * ( (6. - 4.*iIndexJ) * iIndexJ * dAxRatio * fndLaplaceCoeff(B(iIndexJ)) \ + dAxRatio*dAxRatio * (-4. + 4.*iIndexJ) * fndDerivLaplaceCoeff(1,B(iIndexJ)) \ - dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(iIndexJ)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF19Dalpha(double dAxRatio, int iIndexJ) { return 1./8 * ( (6. - 4.*iIndexJ) * iIndexJ * fndLaplaceCoeff(B(iIndexJ)) \ + dAxRatio * (-8. + 14.*iIndexJ - 4.*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(1,B(iIndexJ)) \ + (-7.+4.*iIndexJ)*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(iIndexJ)) \ - dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,B(iIndexJ)) ); } /*--------- f20 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF20(double dAxRatio, int iIndexJ) { return 1./16 * ( (3. + 4.*iIndexJ) * iIndexJ * dAxRatio * fndLaplaceCoeff(B(iIndexJ+1)) \ - 4.*iIndexJ * dAxRatio*dAxRatio * fndDerivLaplaceCoeff(1,B(iIndexJ+1)) \ + dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(iIndexJ+1)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF20Dalpha(double dAxRatio, int iIndexJ) { return 1./16 * ( (3. + 4.*iIndexJ) * iIndexJ * fndLaplaceCoeff(B(iIndexJ+1)) \ + (-5.*iIndexJ + 4.*iIndexJ*iIndexJ) * dAxRatio * fndDerivLaplaceCoeff(1,B(iIndexJ+1)) \ + (3.-4.*iIndexJ)*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(iIndexJ+1)) \ + dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,B(iIndexJ+1)) ); } /*--------- f21 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF21(double dAxRatio, int iIndexJ) { return 1./8 * ( (-12. + 15.*iIndexJ - 4.*iIndexJ*iIndexJ) * dAxRatio * fndLaplaceCoeff(B(abs(iIndexJ-1))) \ + dAxRatio*dAxRatio * (-8. + 4.*iIndexJ) * fndDerivLaplaceCoeff(1,B(abs(iIndexJ-1))) \ - dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(abs(iIndexJ-1))) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF21Dalpha(double dAxRatio, int iIndexJ) { return 1./8 * ( (-12. + 15.*iIndexJ - 4.*iIndexJ*iIndexJ) * fndLaplaceCoeff(B(abs(iIndexJ-1))) \ + dAxRatio * (-28. + 23.*iIndexJ -4.*iIndexJ*iIndexJ) * fndDerivLaplaceCoeff(1,B(abs(iIndexJ-1))) \ + (-11.+4.*iIndexJ)* dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(abs(iIndexJ-1))) \ - dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,B(abs(iIndexJ-1))) ); } /*--------- f22 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF22(double dAxRatio, int iIndexJ) { return 1./4 * ( dAxRatio * iIndexJ * (6. + 4.*iIndexJ) * fndLaplaceCoeff(B(iIndexJ)) \ - 4. * dAxRatio*dAxRatio * fndDerivLaplaceCoeff(1,B(iIndexJ)) \ - dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(iIndexJ)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF22Dalpha(double dAxRatio, int iIndexJ) { return 1./4 * ( iIndexJ * (6. + 4.*iIndexJ) * fndLaplaceCoeff(B(iIndexJ)) \ + (-8.+6.*iIndexJ+4.*iIndexJ*iIndexJ) * dAxRatio * fndDerivLaplaceCoeff(1,B(iIndexJ)) \ - 7.*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(iIndexJ)) \ - dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,B(iIndexJ)) ); } /*--------- f23 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF23(double dAxRatio, int iIndexJ) { return 1./4 * ( dAxRatio * iIndexJ * (6. + 4.*iIndexJ) * fndLaplaceCoeff(B(iIndexJ+2)) \ - 4. * dAxRatio*dAxRatio * fndDerivLaplaceCoeff(1,B(iIndexJ+2)) \ - dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(iIndexJ+2)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF23Dalpha(double dAxRatio, int iIndexJ) { return 1./4 * ( iIndexJ * (6. + 4.*iIndexJ) * fndLaplaceCoeff(B(iIndexJ+2)) \ + (-8.+6.*iIndexJ+4.*iIndexJ*iIndexJ) * dAxRatio * fndDerivLaplaceCoeff(1,B(iIndexJ+2)) \ - 7.*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(iIndexJ+2)) \ - dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,B(iIndexJ+2)) ); } /*--------- f24 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF24(double dAxRatio, int iIndexJ) { return 1./4 * ( (-6. + 4.*iIndexJ) * iIndexJ * dAxRatio * fndLaplaceCoeff(B(iIndexJ)) \ + 4.*dAxRatio*dAxRatio * (1. - iIndexJ) * fndDerivLaplaceCoeff(1,B(iIndexJ)) \ + dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(iIndexJ)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF24Dalpha(double dAxRatio, int iIndexJ) { return 1./4 * ( (-6. + 4.*iIndexJ) * iIndexJ * fndLaplaceCoeff(B(iIndexJ)) \ + (8.-14.*iIndexJ+4.*iIndexJ*iIndexJ)*dAxRatio* fndDerivLaplaceCoeff(1,B(iIndexJ)) \ + (7.-4.*iIndexJ)*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(iIndexJ)) \ + dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,B(iIndexJ)) ); } /*--------- f25 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF25(double dAxRatio, int iIndexJ) { return 1./8 * ( (-3. - 4.*iIndexJ) * iIndexJ * dAxRatio * fndLaplaceCoeff(B(iIndexJ+1)) \ + 4.*iIndexJ*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(1,B(iIndexJ+1)) \ - dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(iIndexJ+1)) ); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF25Dalpha(double dAxRatio, int iIndexJ) { return 1./8 * ( (-3. - 4.*iIndexJ) * iIndexJ * fndLaplaceCoeff(B(iIndexJ+1)) \ + (5.*iIndexJ-4.*iIndexJ*iIndexJ)*dAxRatio * fndDerivLaplaceCoeff(1,B(iIndexJ+1)) \ + (-3.+4.*iIndexJ)* dAxRatio*dAxRatio * fndDerivLaplaceCoeff(2,B(iIndexJ+1)) \ - dAxRatio*dAxRatio*dAxRatio * fndDerivLaplaceCoeff(3,B(iIndexJ+1)) ); } /*--------- f26 ----------------------*/ /** Semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Semi-major axis term */ double fndSemiMajAxF26(double dAxRatio, int iIndexJ) { return 1./2 * dAxRatio * fndLaplaceCoeff(B(iIndexJ+1)) + 3./4 * dAxRatio*dAxRatio * fndLaplaceCoeff(C(iIndexJ)) \ + 3./2 * dAxRatio*dAxRatio * fndLaplaceCoeff(C(iIndexJ+2)); } /** Derivative in d/d(alpha) of semi-major axis term in disturbing function @param dAxRatio Ratio of inner planet's semi to outer planet's (must be < 1) @param iIndexJ Index j of Laplace Coefficients (j = 0 for secular model) @return Derivative of semi-major axis term */ double fndDSemiF26Dalpha(double dAxRatio, int iIndexJ) { return 1./2 * ( fndLaplaceCoeff(B(iIndexJ+1)) + dAxRatio*fndDerivLaplaceCoeff(1,B(iIndexJ+1)) ) \ + 3./4 * dAxRatio * ( 2.*(fndLaplaceCoeff(C(iIndexJ)) + 2.*fndLaplaceCoeff(C(iIndexJ+2))) \ + dAxRatio*(fndDerivLaplaceCoeff(1,C(iIndexJ)) + 2.*fndDerivLaplaceCoeff(1,C(iIndexJ+2))) ) ; } //----------------Disturbing function h k p q---------------------------------------------- //--------dR/dh-----------(inner body)------------------------------------------------------ /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dh term for interior body */ double fndDdistDhDir01(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dHecc*( system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][1] + 2*(body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][3] + (body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][4] + (body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc+body[jBody].dPinc*body[jBody].dPinc+body[jBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][6] ); } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dh term for interior body */ double fndDdistDhDir02(BODY *body, SYSTEM *system, int iBody, int jBody) { return body[jBody].dHecc*( system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][9] + (body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][11] + (body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc+body[jBody].dPinc*body[jBody].dPinc+body[jBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][12] ) + (2*body[iBody].dHecc*body[iBody].dKecc*body[jBody].dKecc + 3*body[iBody].dHecc*body[iBody].dHecc*body[jBody].dHecc+body[jBody].dHecc*body[iBody].dKecc*body[iBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][10]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dh term for interior body */ double fndDdistDhDir03(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dHecc*(body[iBody].dPinc*body[jBody].dPinc+body[iBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][14]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dh term for interior body */ double fndDdistDhDir04(BODY *body, SYSTEM *system, int iBody, int jBody) { return (2*body[iBody].dHecc*(body[jBody].dHecc*body[jBody].dHecc-body[jBody].dKecc*body[jBody].dKecc)+4*body[jBody].dHecc*body[iBody].dKecc*body[jBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][16]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dh term for interior body */ double fndDdistDhDir05(BODY *body, SYSTEM *system, int iBody, int jBody) { return (2*body[iBody].dHecc*(body[iBody].dPinc*body[iBody].dPinc-body[iBody].dQinc*body[iBody].dQinc)+4*body[iBody].dPinc*body[iBody].dQinc*body[iBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][17]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dh term for interior body */ double fndDdistDhDir06(BODY *body, SYSTEM *system, int iBody, int jBody) { return (body[jBody].dHecc*(body[iBody].dPinc*body[iBody].dPinc-body[iBody].dQinc*body[iBody].dQinc)+2*body[jBody].dKecc*body[iBody].dPinc*body[iBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][18]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dh term for interior body */ double fndDdistDhDir08(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*(body[iBody].dHecc*(body[iBody].dPinc*body[jBody].dPinc-body[iBody].dQinc*body[jBody].dQinc) + body[iBody].dKecc*(body[jBody].dPinc*body[iBody].dQinc+body[jBody].dQinc*body[iBody].dPinc))*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][20]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dh term for interior body */ double fndDdistDhDir09(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dHecc*(body[iBody].dQinc*body[jBody].dQinc+body[iBody].dPinc*body[jBody].dPinc) + body[jBody].dKecc*(body[iBody].dPinc*body[jBody].dQinc-body[iBody].dQinc*body[jBody].dPinc) )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][21]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dh term for interior body */ double fndDdistDhDir010(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dHecc*(body[iBody].dQinc*body[jBody].dQinc+body[iBody].dPinc*body[jBody].dPinc) + body[jBody].dKecc*(body[iBody].dQinc*body[jBody].dPinc-body[iBody].dPinc*body[jBody].dQinc) )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][22]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dh term for interior body */ double fndDdistDhDir011(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dHecc*(body[iBody].dPinc*body[jBody].dPinc-body[iBody].dQinc*body[jBody].dQinc) + body[jBody].dKecc*(body[iBody].dQinc*body[jBody].dPinc+body[iBody].dPinc*body[jBody].dQinc) )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][23]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dh term for interior body */ double fndDdistDhDir013(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( 2*body[iBody].dHecc*(body[jBody].dPinc*body[jBody].dPinc-body[jBody].dQinc*body[jBody].dQinc) + 4*body[jBody].dPinc*body[jBody].dQinc*body[iBody].dKecc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][17]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dh term for interior body */ double fndDdistDhDir014(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dHecc*(body[jBody].dPinc*body[jBody].dPinc-body[jBody].dQinc*body[jBody].dQinc) + 2*body[jBody].dKecc*body[jBody].dPinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][18]; } /** Sums over secular dR/dh terms of disturbing function for interior body @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Total dR/dh for interior body */ double fndDdisturbDHecc(BODY *body, SYSTEM *system, int *iaBody) { double y, dMfac, dSemiPrm; dMfac = KGAUSS*KGAUSS*body[iaBody[1]].dMass/MSUN; dSemiPrm = body[iaBody[1]].dSemi/AUM; y = ( fndDdistDhDir01(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhDir02(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhDir03(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhDir04(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhDir05(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhDir06(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhDir08(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhDir09(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhDir010(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhDir011(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhDir013(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhDir014(body, system, iaBody[0], iaBody[1]) ) * dMfac/dSemiPrm; return y; } //---------dR/dh'------------------------------------------------------------------ /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dh term for exterior body */ double fndDdistDhPrmDir01(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dHecc*(system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][1] + (body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][4] + 2*(body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][5] + (body[jBody].dPinc*body[jBody].dPinc+body[jBody].dQinc*body[jBody].dQinc + body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][6]); } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dh term for exterior body */ double fndDdistDhPrmDir02(BODY *body, SYSTEM *system, int iBody, int jBody) { return body[jBody].dHecc*(system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][9] + (body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][10] + (body[jBody].dPinc*body[jBody].dPinc+body[jBody].dQinc*body[jBody].dQinc+body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][12]) + (2*body[iBody].dHecc*body[jBody].dKecc*body[iBody].dKecc + 3*body[iBody].dHecc*body[iBody].dHecc*body[jBody].dHecc + body[jBody].dHecc*body[iBody].dKecc*body[iBody].dKecc) * system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][11]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dh term for exterior body */ double fndDdistDhPrmDir03(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dHecc*(body[iBody].dPinc*body[jBody].dPinc+body[iBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][14]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dh term for exterior body */ double fndDdistDhPrmDir04(BODY *body, SYSTEM *system, int iBody, int jBody) { return (2*body[iBody].dHecc*(body[jBody].dHecc*body[jBody].dHecc-body[jBody].dKecc*body[jBody].dKecc) + 4*body[jBody].dHecc*body[jBody].dKecc*body[iBody].dKecc) * system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][16]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dh term for exterior body */ double fndDdistDhPrmDir06(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dHecc*(body[jBody].dPinc*body[jBody].dPinc-body[jBody].dQinc*body[jBody].dQinc) + 2*body[jBody].dKecc*body[jBody].dPinc*body[jBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][18]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dh term for exterior body */ double fndDdistDhPrmDir07(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( 2*body[iBody].dHecc*(body[jBody].dPinc*body[jBody].dPinc-body[jBody].dQinc*body[jBody].dQinc) + 4*body[jBody].dPinc*body[jBody].dQinc*body[iBody].dKecc ) * system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][19]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dh term for exterior body */ double fndDdistDhPrmDir09(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dHecc*(body[iBody].dQinc*body[jBody].dQinc+body[iBody].dPinc*body[jBody].dPinc) + body[jBody].dKecc*(body[iBody].dPinc*body[jBody].dQinc-body[iBody].dQinc*body[jBody].dPinc) ) * system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][21]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dh term for exterior body */ double fndDdistDhPrmDir010(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dHecc*(body[iBody].dQinc*body[jBody].dQinc+body[iBody].dPinc*body[jBody].dPinc) + body[jBody].dKecc*(body[iBody].dQinc*body[jBody].dPinc-body[iBody].dPinc*body[jBody].dQinc) ) * system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][22]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dh term for exterior body */ double fndDdistDhPrmDir011(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dHecc*(-body[iBody].dQinc*body[jBody].dQinc+body[iBody].dPinc*body[jBody].dPinc) + body[jBody].dKecc*(body[iBody].dQinc*body[jBody].dPinc+body[iBody].dPinc*body[jBody].dQinc) )* system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][23]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dh term for exterior body */ double fndDdistDhPrmDir012(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[iBody].dHecc*(body[iBody].dPinc*body[jBody].dPinc-body[iBody].dQinc*body[jBody].dQinc) + body[iBody].dKecc*(body[iBody].dPinc*body[jBody].dQinc+body[iBody].dQinc*body[jBody].dPinc) )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][24]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dh term for exterior body */ double fndDdistDhPrmDir014(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dHecc*(body[iBody].dPinc*body[iBody].dPinc-body[iBody].dQinc*body[iBody].dQinc) + 2*body[jBody].dKecc*body[iBody].dPinc*body[iBody].dQinc ) *system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][18]; } /** Derivative in d/dh of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dh term for exterior body */ double fndDdistDhPrmDir015(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[iBody].dHecc*(body[iBody].dPinc*body[iBody].dPinc-body[iBody].dQinc*body[iBody].dQinc) + 2*body[iBody].dPinc*body[iBody].dQinc*body[iBody].dKecc ) * system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][19]; } /** Sums over secular dR/dh terms of disturbing function for exterior body @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Total dR/dh for exterior body */ double fndDdisturbDHeccPrime(BODY *body, SYSTEM *system, int *iaBody) { double y, dMfac, dSemiPrm; dMfac = KGAUSS*KGAUSS*body[iaBody[1]].dMass/MSUN; dSemiPrm = body[iaBody[0]].dSemi/AUM; y = ( fndDdistDhPrmDir01(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhPrmDir02(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhPrmDir03(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhPrmDir04(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhPrmDir06(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhPrmDir07(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhPrmDir09(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhPrmDir010(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhPrmDir011(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhPrmDir012(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhPrmDir014(body, system, iaBody[0], iaBody[1]) \ + fndDdistDhPrmDir015(body, system, iaBody[0], iaBody[1]) ) * dMfac/dSemiPrm; return y; } //------------dR/dk-------------------------------------------------------------- /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dk term for interior body */ double fndDdistDkDir01(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dKecc*( system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][1] + 2*(body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][3] + (body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][4] + (body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc + body[jBody].dPinc*body[jBody].dPinc+body[jBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][6] ); } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dk term for interior body */ double fndDdistDkDir02(BODY *body, SYSTEM *system, int iBody, int jBody) { return body[jBody].dKecc*( system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][9] + (body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][11] + (body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc+body[jBody].dPinc*body[jBody].dPinc+body[jBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][12] ) + (3*body[iBody].dKecc*body[iBody].dKecc*body[jBody].dKecc+body[jBody].dKecc*body[iBody].dHecc*body[iBody].dHecc+2*body[iBody].dKecc*body[iBody].dHecc*body[jBody].dHecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][10]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dk term for interior body */ double fndDdistDkDir03(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dKecc*(body[iBody].dPinc*body[jBody].dPinc+body[iBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][14]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dk term for interior body */ double fndDdistDkDir04(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( 2*body[iBody].dKecc*(body[jBody].dKecc*body[jBody].dKecc-body[jBody].dHecc*body[jBody].dHecc) + 4*body[iBody].dHecc*body[jBody].dHecc*body[jBody].dKecc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][16]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dk term for interior body */ double fndDdistDkDir05(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( 2*body[iBody].dKecc*(body[iBody].dQinc*body[iBody].dQinc-body[iBody].dPinc*body[iBody].dPinc) + 4*body[iBody].dPinc*body[iBody].dQinc*body[iBody].dHecc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][17]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dk term for interior body */ double fndDdistDkDir06(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*(body[iBody].dQinc*body[iBody].dQinc-body[iBody].dPinc*body[iBody].dPinc) + 2*body[jBody].dHecc*body[iBody].dPinc*body[iBody].dQinc )* system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][18]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dk term for interior body */ double fndDdistDkDir08(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[iBody].dKecc*(body[jBody].dQinc*body[iBody].dQinc - body[jBody].dPinc*body[iBody].dPinc) + body[iBody].dHecc*(body[jBody].dPinc*body[iBody].dQinc + body[jBody].dQinc*body[iBody].dPinc) ) * system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][20]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dk term for interior body */ double fndDdistDkDir09(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*(body[jBody].dQinc*body[iBody].dQinc + body[jBody].dPinc*body[iBody].dPinc) + body[jBody].dHecc*(body[jBody].dPinc*body[iBody].dQinc - body[jBody].dQinc*body[iBody].dPinc) ) * system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][21]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dk term for interior body */ double fndDdistDkDir010(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*(body[jBody].dQinc*body[iBody].dQinc + body[jBody].dPinc*body[iBody].dPinc) + body[jBody].dHecc*(body[jBody].dQinc*body[iBody].dPinc - body[jBody].dPinc*body[iBody].dQinc) ) * system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][22]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dk term for interior body */ double fndDdistDkDir011(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*(body[jBody].dQinc*body[iBody].dQinc-body[jBody].dPinc*body[iBody].dPinc) + body[jBody].dHecc*(body[jBody].dPinc*body[iBody].dQinc+body[jBody].dQinc*body[iBody].dPinc) ) * system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][23]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dk term for interior body */ double fndDdistDkDir013(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( 2*body[iBody].dKecc*(body[jBody].dQinc*body[jBody].dQinc-body[jBody].dPinc*body[jBody].dPinc) + 4*body[jBody].dPinc*body[jBody].dQinc*body[iBody].dHecc ) * system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][17]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dk term for interior body */ double fndDdistDkDir014(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*(body[jBody].dQinc*body[jBody].dQinc-body[jBody].dPinc*body[jBody].dPinc) + 2*body[jBody].dHecc*body[jBody].dPinc*body[jBody].dQinc ) * system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][18]; } /** Sums over secular dR/dk terms of disturbing function for interior body @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Total dR/dk for interior body */ double fndDdisturbDKecc(BODY *body, SYSTEM *system, int *iaBody) { double y, dMfac, dSemiPrm; dMfac = KGAUSS*KGAUSS*body[iaBody[1]].dMass/MSUN; dSemiPrm = body[iaBody[1]].dSemi/AUM; y = ( fndDdistDkDir01(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkDir02(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkDir03(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkDir04(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkDir05(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkDir06(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkDir08(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkDir09(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkDir010(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkDir011(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkDir013(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkDir014(body, system, iaBody[0], iaBody[1]) ) * dMfac/dSemiPrm; return y; } //----------dR/dk'------------------------------------------------------------ /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dk term for exterior body */ double fndDdistDkPrmDir01(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dKecc*(system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][1] + (body[jBody].dHecc*body[jBody].dHecc + body[jBody].dKecc*body[jBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][4] + 2*(body[iBody].dHecc*body[iBody].dHecc + body[iBody].dKecc*body[iBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][5] + (body[jBody].dPinc*body[jBody].dPinc+body[jBody].dQinc*body[jBody].dQinc + body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][6]); } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dk term for exterior body */ double fndDdistDkPrmDir02(BODY *body, SYSTEM *system, int iBody, int jBody) { return body[jBody].dKecc*(system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][9] + (body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][10] + (body[jBody].dPinc*body[jBody].dPinc+body[jBody].dQinc*body[jBody].dQinc + body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][12]) + (body[iBody].dHecc*body[iBody].dHecc*body[jBody].dKecc+3*body[jBody].dKecc*body[iBody].dKecc*body[iBody].dKecc+2*body[iBody].dKecc*body[jBody].dHecc*body[iBody].dHecc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][11]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dk term for exterior body */ double fndDdistDkPrmDir03(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dKecc*(body[jBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][14]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dk term for exterior body */ double fndDdistDkPrmDir04(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[iBody].dKecc*(body[jBody].dKecc*body[jBody].dKecc-body[jBody].dHecc*body[jBody].dHecc) + 2*body[jBody].dHecc*body[iBody].dHecc*body[jBody].dKecc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][16]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dk term for exterior body */ double fndDdistDkPrmDir06(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*(body[jBody].dQinc*body[jBody].dQinc - body[jBody].dPinc*body[jBody].dPinc) + 2*body[jBody].dHecc*body[jBody].dPinc*body[jBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][18]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dk term for exterior body */ double fndDdistDkPrmDir07(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[iBody].dKecc*(body[jBody].dQinc*body[jBody].dQinc-body[jBody].dPinc*body[jBody].dPinc) + 2*body[jBody].dPinc*body[jBody].dQinc*body[iBody].dHecc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][19]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dk term for exterior body */ double fndDdistDkPrmDir09(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*(body[iBody].dQinc*body[jBody].dQinc+body[iBody].dPinc*body[jBody].dPinc) - body[jBody].dHecc*(body[iBody].dPinc*body[jBody].dQinc-body[iBody].dQinc*body[jBody].dPinc) )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][21]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dk term for exterior body */ double fndDdistDkPrmDir010(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*(body[iBody].dQinc*body[jBody].dQinc + body[iBody].dPinc*body[jBody].dPinc) - body[jBody].dHecc*(body[iBody].dQinc*body[jBody].dPinc-body[iBody].dPinc*body[jBody].dQinc) )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][22]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dk term for exterior body */ double fndDdistDkPrmDir011(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*(body[jBody].dQinc*body[iBody].dQinc-body[jBody].dPinc*body[iBody].dPinc) + body[jBody].dHecc*(body[iBody].dPinc*body[jBody].dQinc+body[iBody].dQinc*body[jBody].dPinc) )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][23]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dk term for exterior body */ double fndDdistDkPrmDir012(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[iBody].dKecc*(body[iBody].dQinc*body[jBody].dQinc-body[iBody].dPinc*body[jBody].dPinc) + body[iBody].dHecc*(body[iBody].dPinc*body[jBody].dQinc+body[iBody].dQinc*body[jBody].dPinc) )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][24]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dk term for exterior body */ double fndDdistDkPrmDir014(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*(body[iBody].dQinc*body[iBody].dQinc-body[iBody].dPinc*body[iBody].dPinc) + 2*body[jBody].dHecc*body[iBody].dPinc*body[iBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][18]; } /** Derivative in d/dk of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dk term for exterior body */ double fndDdistDkPrmDir015(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[iBody].dKecc*(body[iBody].dQinc*body[iBody].dQinc-body[iBody].dPinc*body[iBody].dPinc) + 2*body[iBody].dPinc*body[iBody].dQinc*body[iBody].dHecc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][19]; } /** Sums over secular dR/dk terms of disturbing function for exterior body @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Total dR/dk for exterior body */ double fndDdisturbDKeccPrime(BODY *body, SYSTEM *system, int *iaBody) { double y, dMfac, dSemiPrm; dMfac = KGAUSS*KGAUSS*body[iaBody[1]].dMass/MSUN; dSemiPrm = body[iaBody[0]].dSemi/AUM; y = ( fndDdistDkPrmDir01(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkPrmDir02(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkPrmDir03(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkPrmDir04(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkPrmDir06(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkPrmDir07(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkPrmDir09(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkPrmDir010(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkPrmDir011(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkPrmDir012(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkPrmDir014(body, system, iaBody[0], iaBody[1]) \ + fndDdistDkPrmDir015(body, system, iaBody[0], iaBody[1]) ) * dMfac/dSemiPrm; return y; } //------------dR/dp---------------------------------------------------------// /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dp term for interior body */ double fndDdistDpDir01(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dPinc*( system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][2] + (body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc+body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][6] + 2*(body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][7] + (body[jBody].dPinc*body[jBody].dPinc+body[jBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][8] ); } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dp term for interior body */ double fndDdistDpDir02(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dPinc*(body[iBody].dHecc*body[jBody].dHecc + body[iBody].dKecc*body[jBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][12]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dp term for interior body */ double fndDdistDpDir03(BODY *body, SYSTEM *system, int iBody, int jBody) { return body[jBody].dPinc*( system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][13] + (body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc+body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][14] + (body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc+body[jBody].dPinc*body[jBody].dPinc+body[jBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][15] ) + 2*body[iBody].dPinc*(body[iBody].dPinc*body[jBody].dPinc+body[iBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][15]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dp term for interior body */ double fndDdistDpDir05(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[iBody].dPinc*body[iBody].dHecc*body[iBody].dHecc-body[iBody].dPinc*body[iBody].dKecc*body[iBody].dKecc+2*body[iBody].dQinc*body[iBody].dHecc*body[iBody].dKecc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][17]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dp term for interior body */ double fndDdistDpDir06(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[iBody].dHecc*body[jBody].dHecc*body[iBody].dPinc - body[iBody].dKecc*body[jBody].dKecc*body[iBody].dPinc + body[jBody].dHecc*body[iBody].dKecc*body[iBody].dQinc + body[jBody].dKecc*body[iBody].dHecc*body[iBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][18]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dp term for interior body */ double fndDdistDpDir07(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*(body[iBody].dPinc*body[jBody].dHecc*body[jBody].dHecc - body[iBody].dPinc*body[jBody].dKecc*body[jBody].dKecc + 2*body[iBody].dQinc*body[jBody].dHecc*body[jBody].dKecc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][19]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dp term for interior body */ double fndDdistDpDir08(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dPinc*body[iBody].dHecc*body[iBody].dHecc-body[jBody].dPinc*body[iBody].dKecc*body[iBody].dKecc+2*body[iBody].dHecc*body[iBody].dKecc*body[jBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][20]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dp term for interior body */ double fndDdistDpDir09(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*body[iBody].dKecc*body[jBody].dPinc + body[jBody].dHecc*body[iBody].dHecc*body[jBody].dPinc - body[jBody].dHecc*body[iBody].dKecc*body[jBody].dQinc + body[jBody].dKecc*body[iBody].dHecc*body[jBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][21]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dp term for interior body */ double fndDdistDpDir010(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*body[iBody].dKecc*body[jBody].dPinc + body[jBody].dHecc*body[iBody].dHecc*body[jBody].dPinc + body[jBody].dHecc*body[iBody].dKecc*body[jBody].dQinc - body[jBody].dKecc*body[iBody].dHecc*body[jBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][22]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dp term for interior body */ double fndDdistDpDir011(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( -body[jBody].dKecc*body[iBody].dKecc*body[jBody].dPinc + body[jBody].dHecc*body[iBody].dHecc*body[jBody].dPinc + body[jBody].dHecc*body[iBody].dKecc*body[jBody].dQinc + body[jBody].dKecc*body[iBody].dHecc*body[jBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][23]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dp term for interior body */ double fndDdistDpDir012(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( -body[jBody].dKecc*body[jBody].dKecc*body[jBody].dPinc + body[jBody].dHecc*body[jBody].dHecc*body[jBody].dPinc + 2*body[jBody].dHecc*body[jBody].dKecc*body[jBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][24]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dp term for interior body */ double fndDdistDpDir016(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*(body[iBody].dPinc*body[jBody].dPinc*body[jBody].dPinc-body[iBody].dPinc*body[jBody].dQinc*body[jBody].dQinc+2*body[jBody].dPinc*body[jBody].dQinc*body[iBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][25]; } /** Sums over secular dR/dp terms of disturbing function for interior body @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Total dR/dp for interior body */ double fndDdisturbDPinc(BODY *body, SYSTEM *system, int *iaBody) { double y, dMfac, dSemiPrm; dMfac = KGAUSS*KGAUSS*body[iaBody[1]].dMass/MSUN; dSemiPrm = body[iaBody[1]].dSemi/AUM; y = ( fndDdistDpDir01(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpDir02(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpDir03(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpDir05(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpDir06(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpDir07(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpDir08(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpDir09(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpDir010(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpDir011(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpDir012(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpDir016(body, system, iaBody[0], iaBody[1]) ) * dMfac/dSemiPrm; return y; } //-------dR/dp'------------------------------------------------------------// /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dp term for exterior body */ double fndDdistDpPrmDir01(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dPinc*( system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][2] + (body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc+body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][6] + 2*(body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][7] + (body[jBody].dPinc*body[jBody].dPinc+body[jBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][8] ); } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dp term for exterior body */ double fndDdistDpPrmDir02(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dPinc*(body[jBody].dHecc*body[iBody].dHecc+body[jBody].dKecc*body[iBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][12]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dp term for exterior body */ double fndDdistDpPrmDir03(BODY *body, SYSTEM *system, int iBody, int jBody) { return body[jBody].dPinc*( system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][13] + (body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc+body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][14] + (body[jBody].dPinc*body[jBody].dPinc+body[jBody].dQinc*body[jBody].dQinc+body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][15] ) + 2*body[iBody].dPinc*(body[jBody].dPinc*body[iBody].dPinc+body[jBody].dQinc*body[iBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][15]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dp term for exterior body */ double fndDdistDpPrmDir08(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( -body[jBody].dKecc*body[jBody].dKecc*body[jBody].dPinc+body[jBody].dHecc*body[jBody].dHecc*body[jBody].dPinc+2*body[jBody].dHecc*body[jBody].dKecc*body[jBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][20]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dp term for exterior body */ double fndDdistDpPrmDir09(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[iBody].dKecc*body[jBody].dKecc*body[jBody].dPinc + body[iBody].dHecc*body[jBody].dHecc*body[jBody].dPinc + body[iBody].dHecc*body[jBody].dKecc*body[jBody].dQinc - body[iBody].dKecc*body[jBody].dHecc*body[jBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][21]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dp term for exterior body */ double fndDdistDpPrmDir010(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[iBody].dKecc*body[jBody].dKecc*body[jBody].dPinc + body[iBody].dHecc*body[jBody].dHecc*body[jBody].dPinc - body[iBody].dHecc*body[jBody].dKecc*body[jBody].dQinc + body[iBody].dKecc*body[jBody].dHecc*body[jBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][22]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dp term for exterior body */ double fndDdistDpPrmDir011(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( -body[iBody].dKecc*body[jBody].dKecc*body[jBody].dPinc + body[iBody].dHecc*body[jBody].dHecc*body[jBody].dPinc + body[iBody].dHecc*body[jBody].dKecc*body[jBody].dQinc + body[iBody].dKecc*body[jBody].dHecc*body[jBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][23]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dp term for exterior body */ double fndDdistDpPrmDir012(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( -body[iBody].dKecc*body[iBody].dKecc*body[jBody].dPinc + body[iBody].dHecc*body[iBody].dHecc*body[jBody].dPinc + 2*body[iBody].dHecc*body[iBody].dKecc*body[jBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][24]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dp term for exterior body */ double fndDdistDpPrmDir013(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( -body[iBody].dPinc*body[jBody].dKecc*body[jBody].dKecc + body[iBody].dPinc*body[jBody].dHecc*body[jBody].dHecc + 2*body[iBody].dQinc*body[jBody].dHecc*body[jBody].dKecc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][17]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dp term for exterior body */ double fndDdistDpPrmDir014(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( -body[iBody].dKecc*body[jBody].dKecc*body[iBody].dPinc + body[iBody].dHecc*body[jBody].dHecc*body[iBody].dPinc + body[iBody].dHecc*body[jBody].dKecc*body[iBody].dQinc + body[iBody].dKecc*body[jBody].dHecc*body[iBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][18]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dp term for exterior body */ double fndDdistDpPrmDir015(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( -body[iBody].dPinc*body[iBody].dKecc*body[iBody].dKecc + body[iBody].dPinc*body[iBody].dHecc*body[iBody].dHecc + 2*body[iBody].dQinc*body[iBody].dHecc*body[iBody].dKecc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][19]; } /** Derivative in d/dp of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dp term for exterior body */ double fndDdistDpPrmDir016(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( -body[iBody].dPinc*body[jBody].dQinc*body[jBody].dQinc + body[jBody].dPinc*body[jBody].dPinc*body[iBody].dPinc + 2*body[iBody].dQinc*body[jBody].dPinc*body[jBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][25]; } /** Sums over secular dR/dp terms of disturbing function for exterior body @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Total dR/dp for exterior body */ double fndDdisturbDPincPrime(BODY *body, SYSTEM *system, int *iaBody) { double y, dMfac, dSemiPrm; dMfac = KGAUSS*KGAUSS*body[iaBody[1]].dMass/MSUN; dSemiPrm = body[iaBody[0]].dSemi/AUM; y = ( fndDdistDpPrmDir01(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpPrmDir02(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpPrmDir03(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpPrmDir08(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpPrmDir09(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpPrmDir010(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpPrmDir011(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpPrmDir012(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpPrmDir013(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpPrmDir014(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpPrmDir015(body, system, iaBody[0], iaBody[1]) \ + fndDdistDpPrmDir016(body, system, iaBody[0], iaBody[1]) ) * dMfac/dSemiPrm; return y; } //--------------dR/dq-------------------------------------------------------// /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dq term for interior body */ double fndDdistDqDir01(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dQinc*( system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][2] + (body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc+body[jBody].dKecc*body[jBody].dKecc+body[jBody].dHecc*body[jBody].dHecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][6] + 2*(body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][7] + (body[jBody].dPinc*body[jBody].dPinc+body[jBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][8] ); } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dq term for interior body */ double fndDdistDqDir02(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dQinc*(body[iBody].dHecc*body[jBody].dHecc+body[iBody].dKecc*body[jBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][12]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dq term for interior body */ double fndDdistDqDir03(BODY *body, SYSTEM *system, int iBody, int jBody) { return body[jBody].dQinc*( system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][13] + (body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc+body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][14] + (body[iBody].dPinc*body[iBody].dPinc + body[iBody].dQinc*body[iBody].dQinc + body[jBody].dPinc*body[jBody].dPinc + body[jBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][15] ) + 2*body[iBody].dQinc*(body[iBody].dPinc*body[jBody].dPinc+body[iBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][15]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dq term for interior body */ double fndDdistDqDir05(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[iBody].dQinc*body[iBody].dKecc*body[iBody].dKecc - body[iBody].dQinc*body[iBody].dHecc*body[iBody].dHecc + 2*body[iBody].dPinc*body[iBody].dHecc*body[iBody].dKecc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][17]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dq term for interior body */ double fndDdistDqDir06(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[jBody].dKecc*body[iBody].dKecc*body[iBody].dQinc - body[jBody].dHecc*body[iBody].dHecc*body[iBody].dQinc + body[jBody].dHecc*body[iBody].dKecc*body[iBody].dPinc + body[jBody].dKecc*body[iBody].dHecc*body[iBody].dPinc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][18]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dq term for interior body */ double fndDdistDqDir07(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[iBody].dQinc*body[jBody].dKecc*body[jBody].dKecc - body[iBody].dQinc*body[jBody].dHecc*body[jBody].dHecc + 2*body[iBody].dPinc*body[jBody].dHecc*body[jBody].dKecc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][19]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dq term for interior body */ double fndDdistDqDir08(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[iBody].dKecc*body[iBody].dKecc*body[jBody].dQinc - body[iBody].dHecc*body[iBody].dHecc*body[jBody].dQinc + 2*body[iBody].dHecc*body[iBody].dKecc*body[jBody].dPinc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][20]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dq term for interior body */ double fndDdistDqDir09(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*body[iBody].dKecc*body[jBody].dQinc + body[jBody].dHecc*body[iBody].dHecc*body[jBody].dQinc + body[jBody].dHecc*body[iBody].dKecc*body[jBody].dPinc - body[jBody].dKecc*body[iBody].dHecc*body[jBody].dPinc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][21]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dq term for interior body */ double fndDdistDqDir010(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*body[iBody].dKecc*body[jBody].dQinc + body[iBody].dHecc*body[jBody].dHecc*body[jBody].dQinc - body[jBody].dHecc*body[iBody].dKecc*body[jBody].dPinc + body[jBody].dKecc*body[iBody].dHecc*body[jBody].dPinc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][22]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dq term for interior body */ double fndDdistDqDir011(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*body[iBody].dKecc*body[jBody].dQinc - body[jBody].dHecc*body[iBody].dHecc*body[jBody].dQinc + body[jBody].dHecc*body[iBody].dKecc*body[jBody].dPinc + body[jBody].dKecc*body[iBody].dHecc*body[jBody].dPinc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][23]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dq term for interior body */ double fndDdistDqDir012(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*body[jBody].dKecc*body[jBody].dQinc - body[jBody].dHecc*body[jBody].dHecc*body[jBody].dQinc + 2*body[jBody].dHecc*body[jBody].dKecc*body[jBody].dPinc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][24]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of interior body @param jBody Index of exterior body @return dR/dq term for interior body */ double fndDdistDqDir016(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[iBody].dQinc*body[jBody].dQinc*body[jBody].dQinc - body[iBody].dQinc*body[jBody].dPinc*body[jBody].dPinc + 2*body[jBody].dPinc*body[jBody].dQinc*body[iBody].dPinc )*system->daLaplaceC[0][system->iaLaplaceN[iBody][jBody]][25]; } /** Sums over secular dR/dq terms of disturbing function for interior body @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Total dR/dq for interior body */ double fndDdisturbDQinc(BODY *body, SYSTEM *system, int *iaBody) { double y, dMfac, dSemiPrm; dMfac = KGAUSS*KGAUSS*body[iaBody[1]].dMass/MSUN; dSemiPrm = body[iaBody[1]].dSemi/AUM; y = ( fndDdistDqDir01(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqDir02(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqDir03(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqDir05(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqDir06(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqDir07(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqDir08(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqDir09(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqDir010(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqDir011(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqDir012(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqDir016(body, system, iaBody[0], iaBody[1]) ) * dMfac/dSemiPrm; return y; } //------dR/dq'--------------------------------------------------------------// /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dq term for exterior body */ double fndDdistDqPrmDir01(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dQinc*( system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][2] + (body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc+body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][6] + 2*(body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][7] + (body[jBody].dPinc*body[jBody].dPinc+body[jBody].dQinc*body[jBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][8] ); } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dq term for exterior body */ double fndDdistDqPrmDir02(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*body[iBody].dQinc*(body[jBody].dHecc*body[iBody].dHecc+body[jBody].dKecc*body[iBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][12]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dq term for exterior body */ double fndDdistDqPrmDir03(BODY *body, SYSTEM *system, int iBody, int jBody) { return body[jBody].dQinc*( system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][13] + (body[jBody].dHecc*body[jBody].dHecc+body[jBody].dKecc*body[jBody].dKecc+body[iBody].dHecc*body[iBody].dHecc+body[iBody].dKecc*body[iBody].dKecc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][14] + (body[jBody].dPinc*body[jBody].dPinc+body[jBody].dQinc*body[jBody].dQinc+body[iBody].dPinc*body[iBody].dPinc+body[iBody].dQinc*body[iBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][15] ) + 2*body[iBody].dQinc*(body[jBody].dPinc*body[iBody].dPinc+body[jBody].dQinc*body[iBody].dQinc)*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][15]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dq term for exterior body */ double fndDdistDqPrmDir08(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[jBody].dKecc*body[jBody].dKecc*body[jBody].dQinc - body[jBody].dHecc*body[jBody].dHecc*body[jBody].dQinc + 2*body[jBody].dHecc*body[jBody].dKecc*body[jBody].dPinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][20]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dq term for exterior body */ double fndDdistDqPrmDir09(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[iBody].dKecc*body[jBody].dKecc*body[jBody].dQinc + body[iBody].dHecc*body[jBody].dHecc*body[jBody].dQinc - body[iBody].dHecc*body[jBody].dKecc*body[jBody].dPinc + body[iBody].dKecc*body[jBody].dHecc*body[jBody].dPinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][21]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dq term for exterior body */ double fndDdistDqPrmDir010(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[iBody].dKecc*body[jBody].dKecc*body[jBody].dQinc + body[iBody].dHecc*body[jBody].dHecc*body[jBody].dQinc + body[iBody].dHecc*body[jBody].dKecc*body[jBody].dPinc - body[iBody].dKecc*body[jBody].dHecc*body[jBody].dPinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][22]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dq term for exterior body */ double fndDdistDqPrmDir011(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[iBody].dKecc*body[jBody].dKecc*body[jBody].dQinc - body[iBody].dHecc*body[jBody].dHecc*body[jBody].dQinc + body[iBody].dHecc*body[jBody].dKecc*body[jBody].dPinc + body[iBody].dKecc*body[jBody].dHecc*body[jBody].dPinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][23]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dq term for exterior body */ double fndDdistDqPrmDir012(BODY *body, SYSTEM *system, int iBody, int jBody) { return ( body[iBody].dKecc*body[iBody].dKecc*body[jBody].dQinc - body[iBody].dHecc*body[iBody].dHecc*body[jBody].dQinc + 2*body[iBody].dHecc*body[iBody].dKecc*body[jBody].dPinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][24]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dq term for exterior body */ double fndDdistDqPrmDir013(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[iBody].dQinc*body[jBody].dKecc*body[jBody].dKecc - body[iBody].dQinc*body[jBody].dHecc*body[jBody].dHecc + 2*body[iBody].dPinc*body[jBody].dHecc*body[jBody].dKecc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][17]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dq term for exterior body */ double fndDdistDqPrmDir014(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[iBody].dQinc*body[jBody].dKecc*body[iBody].dKecc - body[iBody].dQinc*body[jBody].dHecc*body[iBody].dHecc + body[iBody].dHecc*body[jBody].dKecc*body[iBody].dPinc + body[iBody].dKecc*body[jBody].dHecc*body[iBody].dPinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][18]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dq term for exterior body */ double fndDdistDqPrmDir015(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[iBody].dQinc*body[iBody].dKecc*body[iBody].dKecc - body[iBody].dQinc*body[iBody].dHecc*body[iBody].dHecc + 2*body[iBody].dPinc*body[iBody].dHecc*body[iBody].dKecc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][19]; } /** Derivative in d/dq of disturbing function term @param body Struct containing all body information and variables @param system Struct containing system information @param iBody Index of exterior body @param jBody Index of interior body @return dR/dq term for exterior body */ double fndDdistDqPrmDir016(BODY *body, SYSTEM *system, int iBody, int jBody) { return 2*( body[jBody].dQinc*body[jBody].dQinc*body[iBody].dQinc - body[jBody].dPinc*body[jBody].dPinc*body[iBody].dQinc + 2*body[iBody].dPinc*body[jBody].dPinc*body[jBody].dQinc )*system->daLaplaceC[0][system->iaLaplaceN[jBody][iBody]][25]; } /** Sums over secular dR/dq terms of disturbing function for exterior body @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Total dR/dq for exterior body */ double fndDdisturbDQincPrime(BODY *body, SYSTEM *system, int *iaBody) { double y, dMfac, dSemiPrm; dMfac = KGAUSS*KGAUSS*body[iaBody[1]].dMass/MSUN; dSemiPrm = body[iaBody[0]].dSemi/AUM; y = ( fndDdistDqPrmDir01(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqPrmDir02(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqPrmDir03(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqPrmDir08(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqPrmDir09(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqPrmDir010(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqPrmDir011(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqPrmDir012(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqPrmDir013(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqPrmDir014(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqPrmDir015(body, system, iaBody[0], iaBody[1]) \ + fndDdistDqPrmDir016(body, system, iaBody[0], iaBody[1]) ) * dMfac/dSemiPrm; return y; } //--------Relativistic correction--------------------------------------------------------- /** Relativistic precession of periastron @param body Struct containing all body information and variables @param iaBody Array containing indices of bodies associated with interaction @return Derivative d(longp)/dt due to general relativity */ double fndApsidalGRCorrection(BODY *body, int *iaBody) { double n; n = KGAUSS*sqrt((body[0].dMass+body[iaBody[0]].dMass)/MSUN/(body[iaBody[0]].dSemi/AUM*\ body[iaBody[0]].dSemi/AUM*body[iaBody[0]].dSemi/AUM)); return 3*n*n*n*body[iaBody[0]].dSemi/AUM*body[iaBody[0]].dSemi/AUM/(cLIGHT/AUM*DAYSEC*cLIGHT/AUM*DAYSEC*(1.0-body[iaBody[0]].dHecc*body[iaBody[0]].dHecc-body[iaBody[0]].dKecc*body[iaBody[0]].dKecc))/DAYSEC; } /** Relativistic correction to derivative of variable Hecc = e*sin(longp) in RD4 solution @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Derivative dh/dt due to general relativity */ double fndApsidalGRDhDt(BODY *body, SYSTEM *system, int *iaBody) { return body[iaBody[0]].dKecc*fndApsidalGRCorrection(body,iaBody); } /** Relativistic correction to derivative of variable Kecc = e*sin(longp) in RD4 solution @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Derivative dk/dt due to general relativity */ double fndApsidalGRDkDt(BODY *body, SYSTEM *system, int *iaBody) { return -body[iaBody[0]].dHecc*fndApsidalGRCorrection(body,iaBody); } //-------------------DistOrb's equations in h k p q (4th order direct integration RD4)-------------------- /** Derivative of variable Hecc = e*sin(longp) in RD4 solution @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Derivative dh/dt */ double fndDistOrbRD4DhDt(BODY *body, SYSTEM *system, int *iaBody) { double sum = 0.0, dMu, y; //Here, iaBody[0] = body in question, iaBody[1] = perturber dMu = KGAUSS*KGAUSS*(body[0].dMass+body[iaBody[0]].dMass)/MSUN; y = fabs(1-body[iaBody[0]].dHecc*body[iaBody[0]].dHecc-body[iaBody[0]].dKecc*body[iaBody[0]].dKecc); if (body[iaBody[0]].dSemi < body[iaBody[1]].dSemi) { sum += ( sqrt(y)*fndDdisturbDKecc(body, system, iaBody) + body[iaBody[0]].dKecc*(body[iaBody[0]].dPinc*fndDdisturbDPinc(body, system, iaBody) +body[iaBody[0]].dQinc*fndDdisturbDQinc(body, system, iaBody))/(2*sqrt(y)) ) / sqrt(dMu*body[iaBody[0]].dSemi/AUM); } else if (body[iaBody[0]].dSemi > body[iaBody[1]].dSemi) { sum += ( sqrt(y)*fndDdisturbDKeccPrime(body, system, iaBody) + body[iaBody[0]].dKecc*(body[iaBody[0]].dPinc*fndDdisturbDPincPrime(body, system, iaBody) +body[iaBody[0]].dQinc*fndDdisturbDQincPrime(body, system, iaBody))/(2*sqrt(y)) ) / sqrt(dMu*body[iaBody[0]].dSemi/AUM); } return sum/DAYSEC; } /** Derivative of variable Kecc = e*cos(longp) in RD4 solution @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Derivative dk/dt */ double fndDistOrbRD4DkDt(BODY *body, SYSTEM *system, int *iaBody) { double sum = 0.0, dMu, y; dMu = KGAUSS*KGAUSS*(body[0].dMass+body[iaBody[0]].dMass)/MSUN; y = fabs(1-body[iaBody[0]].dHecc*body[iaBody[0]].dHecc-body[iaBody[0]].dKecc*body[iaBody[0]].dKecc); if (body[iaBody[0]].dSemi < body[iaBody[1]].dSemi) { sum += -( sqrt(y)*fndDdisturbDHecc(body, system, iaBody) + body[iaBody[0]].dHecc*(body[iaBody[0]].dPinc*fndDdisturbDPinc(body, system, iaBody) +body[iaBody[0]].dQinc*fndDdisturbDQinc(body, system, iaBody))/(2*sqrt(y)) ) / sqrt(dMu*body[iaBody[0]].dSemi/AUM); } else if (body[iaBody[0]].dSemi > body[iaBody[1]].dSemi) { sum += -( sqrt(y)*fndDdisturbDHeccPrime(body, system, iaBody) + body[iaBody[0]].dHecc*(body[iaBody[0]].dPinc*fndDdisturbDPincPrime(body, system, iaBody) +body[iaBody[0]].dQinc*fndDdisturbDQincPrime(body, system, iaBody))/(2*sqrt(y)) ) / sqrt(dMu*body[iaBody[0]].dSemi/AUM); } return sum/DAYSEC; } /** Derivative of variable Pinc = sin(inc/2)*sin(longa) in RD4 solution @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Derivative dp/dt */ double fndDistOrbRD4DpDt(BODY *body, SYSTEM *system, int *iaBody) { double sum = 0.0, dMu, y; dMu = KGAUSS*KGAUSS*(body[0].dMass+body[iaBody[0]].dMass)/MSUN; y = fabs(1-body[iaBody[0]].dHecc*body[iaBody[0]].dHecc-body[iaBody[0]].dKecc*body[iaBody[0]].dKecc); if (body[iaBody[0]].dSemi < body[iaBody[1]].dSemi) { sum += ( body[iaBody[0]].dPinc*(-body[iaBody[0]].dKecc*fndDdisturbDHecc(body, system, iaBody)+body[iaBody[0]].dHecc*fndDdisturbDKecc(body, system, iaBody)) + 1.0/2.0*fndDdisturbDQinc(body, system, iaBody) )/(2*sqrt(dMu*body[iaBody[0]].dSemi/AUM*(y))); } else if (body[iaBody[0]].dSemi > body[iaBody[1]].dSemi) { sum += ( body[iaBody[0]].dPinc*(-body[iaBody[0]].dKecc*fndDdisturbDHeccPrime(body, system, iaBody)+body[iaBody[0]].dHecc*fndDdisturbDKeccPrime(body, system, iaBody)) + 1.0/2.0*fndDdisturbDQincPrime(body, system, iaBody) )/(2*sqrt(dMu*body[iaBody[0]].dSemi/AUM*(y))); } return sum/DAYSEC; } /** Derivative of variable Qinc = sin(inc/2)*cos(longa) in RD4 solution @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Derivative dq/dt */ double fndDistOrbRD4DqDt(BODY *body, SYSTEM *system, int *iaBody) { double sum = 0.0, dMu, y; dMu = KGAUSS*KGAUSS*(body[0].dMass+body[iaBody[0]].dMass)/MSUN; y = fabs(1-body[iaBody[0]].dHecc*body[iaBody[0]].dHecc-body[iaBody[0]].dKecc*body[iaBody[0]].dKecc); if (body[iaBody[0]].dSemi < body[iaBody[1]].dSemi) { sum += ( body[iaBody[0]].dQinc*(-body[iaBody[0]].dKecc*fndDdisturbDHecc(body, system, iaBody)+body[iaBody[0]].dHecc*fndDdisturbDKecc(body, system, iaBody)) - 1.0/2.0*fndDdisturbDPinc(body, system, iaBody) )/(2*sqrt(dMu*body[iaBody[0]].dSemi/AUM*(y))); } else if (body[iaBody[0]].dSemi > body[iaBody[1]].dSemi) { sum += ( body[iaBody[0]].dQinc*(-body[iaBody[0]].dKecc*fndDdisturbDHeccPrime(body, system, iaBody)+body[iaBody[0]].dHecc*fndDdisturbDKeccPrime(body, system, iaBody)) - 1.0/2.0*fndDdisturbDPincPrime(body, system, iaBody) )/(2*sqrt(dMu*body[iaBody[0]].dSemi/AUM*(y))); } return sum/DAYSEC; } //-------------------DistOrb's equations in h k p q (2nd order Laplace-Lagrange LL2)-------------------- /** Value of variable Hecc = e*sin(longp) at time dAge, in the LL2 solution (not a derivative) @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Hecc at time dAge */ double fndDistOrbLL2Hecc(BODY *body, SYSTEM *system, int *iaBody) { return system->daEigenVecEcc[iaBody[0]-1][iaBody[1]-1]*sin(system->daEigenValEcc[0][iaBody[1]-1]/YEARSEC*body[iaBody[0]].dAge+system->daEigenPhase[0][iaBody[1]-1]); } /** Value of variable Kecc = e*cos(longp) at time dAge, in the LL2 solution (not a derivative) @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Kecc at time dAge */ double fndDistOrbLL2Kecc(BODY *body, SYSTEM *system, int *iaBody) { return system->daEigenVecEcc[iaBody[0]-1][iaBody[1]-1]*cos(system->daEigenValEcc[0][iaBody[1]-1]/YEARSEC*body[iaBody[0]].dAge+system->daEigenPhase[0][iaBody[1]-1]); } /** Value of variable Pinc = sin(inc/2)*sin(longp) at time dAge, in the LL2 solution (not a derivative) @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Pinc at time dAge */ double fndDistOrbLL2Pinc(BODY *body, SYSTEM *system, int *iaBody) { return system->daEigenVecInc[iaBody[0]-1][iaBody[1]-1]*sin(system->daEigenValInc[0][iaBody[1]-1]/YEARSEC*body[iaBody[0]].dAge+system->daEigenPhase[1][iaBody[1]-1]); } /** Value of variable Qinc = sin(inc/2)*cos(longp) at time dAge, in the LL2 solution (not a derivative) @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Qinc at time dAge */ double fndDistOrbLL2Qinc(BODY *body, SYSTEM *system, int *iaBody) { return system->daEigenVecInc[iaBody[0]-1][iaBody[1]-1]*cos(system->daEigenValInc[0][iaBody[1]-1]/YEARSEC*body[iaBody[0]].dAge+system->daEigenPhase[1][iaBody[1]-1]); } /** Provides derivative of variable Hecc = e*sin(longp) to couple eqtide to LL2 solution. @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Derivative dh/dt */ double fndDistOrbLL2DhDt(BODY *body, SYSTEM *system, int *iaBody) { return system->daEigenVecEcc[iaBody[0]-1][iaBody[1]-1]*system->daEigenValEcc[0][iaBody[1]-1]/YEARSEC*cos(system->daEigenValEcc[0][iaBody[1]-1]/YEARSEC*body[iaBody[0]].dAge+system->daEigenPhase[0][iaBody[1]-1]); } /** Provides derivative of variable Kecc = e*sin(longp) to couple eqtide to LL2 solution. @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Derivative dk/dt */ double fndDistOrbLL2DkDt(BODY *body, SYSTEM *system, int *iaBody) { return -system->daEigenVecEcc[iaBody[0]-1][iaBody[1]-1]*system->daEigenValEcc[0][iaBody[1]-1]/YEARSEC*sin(system->daEigenValEcc[0][iaBody[1]-1]/YEARSEC*body[iaBody[0]].dAge+system->daEigenPhase[0][iaBody[1]-1]); } /** Provides derivative of variable Pinc = sin(inc/2)*sin(longa) to couple distrot to LL2 solution. @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Derivative dp/dt */ double fndDistOrbLL2DpDt(BODY *body, SYSTEM *system, int *iaBody) { /* Derivatives used by DistRot */ return system->daEigenVecInc[iaBody[0]-1][iaBody[1]-1]*system->daEigenValInc[0][iaBody[1]-1]/YEARSEC*cos(system->daEigenValInc[0][iaBody[1]-1]/YEARSEC*body[iaBody[0]].dAge+system->daEigenPhase[1][iaBody[1]-1]); } /** Provides derivative of variable Qinc = sin(inc/2)*cos(longa) to couple distrot to LL2 solution. @param body Struct containing all body information and variables @param system Struct containing system information @param iaBody Array containing indices of bodies associated with interaction @return Derivative dq/dt */ double fndDistOrbLL2DqDt(BODY *body, SYSTEM *system, int *iaBody) { /* Derivatives used by DistRot */ return -system->daEigenVecInc[iaBody[0]-1][iaBody[1]-1]*system->daEigenValInc[0][iaBody[1]-1]/YEARSEC*sin(system->daEigenValInc[0][iaBody[1]-1]/YEARSEC*body[iaBody[0]].dAge+system->daEigenPhase[1][iaBody[1]-1]); }
<gh_stars>0 package com.opalfire.foodorder.models; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class CartAddon { @SerializedName("addon_product") @Expose private Addon addonProduct; @SerializedName("addon_product_id") @Expose private Integer addonProductId; @SerializedName("deleted_at") @Expose private Object deletedAt; @SerializedName("id") @Expose private Integer id; @SerializedName("quantity") @Expose private Integer quantity; @SerializedName("user_cart_id") @Expose private Integer userCartId; public Integer getId() { return this.id; } public void setId(Integer num) { this.id = num; } public Integer getUserCartId() { return this.userCartId; } public void setUserCartId(Integer num) { this.userCartId = num; } public Integer getAddonProductId() { return this.addonProductId; } public void setAddonProductId(Integer num) { this.addonProductId = num; } public Integer getQuantity() { return this.quantity; } public void setQuantity(Integer num) { this.quantity = num; } public Object getDeletedAt() { return this.deletedAt; } public void setDeletedAt(Object obj) { this.deletedAt = obj; } public Addon getAddonProduct() { return this.addonProduct; } public void setAddonProduct(Addon addon) { this.addonProduct = addon; } }
<reponame>healer1064/Gimbal import { TableInstanceOptions } from 'cli-table3'; import { Column, Config, Data, Finder, Renders } from '@/typings/components/Table'; import cliRenderer from './renderer/cli'; import htmlRenderer from './renderer/html'; import markdownRenderer from './renderer/markdown'; class Table { private columns: Column[] = []; private data: Data[] = []; private options?: TableInstanceOptions; public constructor(config?: Config) { if (config) { if (config.columns) { this.columns = config.columns; } if (config.data) { this.data = config.data; } if (config.options) { this.options = config.options; } } } public addColumn(column: Column, index?: number): void { const { columns } = this; if (index == null) { columns.push(column); } else { columns.splice(index, 0, column); } } public getColumn(index: number): Column | void { return this.columns[index]; } public findColumn(callback: Finder, getIndex = false): Column | number | void { if (getIndex) { return this.columns.findIndex(callback); } return this.columns.find(callback); } public removeColumn(column: Column): void { const { columns } = this; const index = columns.indexOf(column); if (index !== -1) { columns.splice(index, 1); } } public add(item: Data, index?: number): void { const { data } = this; if (index == null) { data.push(item); } else { data.splice(index, 0, item); } } public find(callback: Finder, getIndex = false): Data | number | void { if (getIndex) { return this.data.findIndex(callback); } return this.data.find(callback); } public get(index: number): Data | void { return this.data[index]; } public remove(item: Data): void { const { data } = this; const index = data.indexOf(item); if (index !== -1) { data.splice(index, 1); } } public set(data: Data[]): void { this.data = data; } public render(type: Renders): Promise<string> { const { columns, data, options } = this; switch (type) { case 'cli': return cliRenderer({ columns, data, options }); case 'markdown': return markdownRenderer({ columns, data, options }); case 'html': return htmlRenderer({ columns, data, options }); default: return Promise.resolve(''); } } } export default Table;
#!/usr/bin/env bash # Copyright 2020 Amazon.com Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -x set -o errexit set -o nounset set -o pipefail RELEASE_BRANCH="$1" MAKE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)" source "${MAKE_ROOT}/build/lib/init.sh" ASSET_ROOT=$OUTPUT_DIR/${RELEASE_BRANCH} if [ ! -d ${ASSET_ROOT}/bin ]; then echo "${ASSET_ROOT}/bin does not exist. Run 'make local-images && make tarballs' before running" exit 1 fi FIND=find if which gfind &>/dev/null; then FIND=gfind elif which gnudate &>/dev/null; then FIND=gnufind fi SHA256SUM=$(dirname ${ASSET_ROOT})/SHA256SUM SHA512SUM=$(dirname ${ASSET_ROOT})/SHA512SUM rm -f $SHA256SUM rm -f $SHA512SUM echo "Writing artifact hashes to SHA256SUM/SHA512SUM files..." cd $ASSET_ROOT for file in $(find ${ASSET_ROOT} -type f -not -path '*\.sha[25][51][62]' ); do filepath=$(realpath --relative-base=${ASSET_ROOT} $file ) sha256sum "$filepath" | tee -a $SHA256SUM > "$file.sha256" || return 1 sha512sum "$filepath" | tee -a $SHA512SUM > "$file.sha512" || return 1 done mv $SHA256SUM $SHA512SUM "$ASSET_ROOT" sha256sum SHA256SUM > "SHA256SUM.sha256" || return 1 sha512sum SHA256SUM > "SHA256SUM.sha512" || return 1 sha256sum SHA512SUM > "SHA512SUM.sha256" || return 1 sha512sum SHA512SUM > "SHA512SUM.sha512" || return 1 cd -
<reponame>openlibraryenvironment/ui-directory import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { Accordion, Col, KeyValue, NoValue, Row } from '@folio/stripes/components'; import { Address } from '../components'; function renderAddress(address, index, count) { return ( <Address key={`Address[${index}], ${address.addressLabel}`} {...{ address, index, count }} /> ); } class ContactInformation extends React.Component { static propTypes = { record: PropTypes.object, id: PropTypes.string, onToggle: PropTypes.func, open: PropTypes.bool, }; render() { const { record } = this.props; const addresses = record.addresses || []; return ( <Accordion id={this.props.id} label={<FormattedMessage id="ui-directory.information.heading.contactInformation" />} open={this.props.open} onToggle={this.props.onToggle} > <Row> <Col xs={4}> <KeyValue label={<FormattedMessage id="ui-directory.information.mainPhoneNumber" />} value={record.phoneNumber ? record.phoneNumber : <NoValue />} /> </Col> <Col xs={4}> <KeyValue label={<FormattedMessage id="ui-directory.information.mainEmailAddress" />} value={record.emailAddress ? record.emailAddress : <NoValue />} /> </Col> <Col xs={4}> <KeyValue label={<FormattedMessage id="ui-directory.information.mainContactName" />} value={record.contactName ? record.contactName : <NoValue />} /> </Col> </Row> {addresses.sort((a, b) => { const addressA = a.addressLabel.toUpperCase(); const addressB = b.addressLabel.toUpperCase(); return (addressA < addressB) ? -1 : (addressA > addressB) ? 1 : 0; }).map((address, i) => renderAddress(address, i + 1, addresses.length))} </Accordion> ); } } export default ContactInformation;
<reponame>mrkumar83/alexa-skills-kit-java-clone package localeventsearch.storage.mock; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import localeventsearch.storage.Event; import localeventsearch.storage.EventType; import localeventsearch.storage.LocalEventSearchElasticsearchClient; public class MockLocalEventSearchService implements LocalEventSearchElasticsearchClient { /* { "_index" : "events", "_type" : "events", "_id" : "2978624", "_score" : 1.0, "_source" : { "id" : "2978624", "description" : "<NAME>", "locationString" : "Yoshi's Oakland", "locationAddress" : "510 Embarcadero West, Oakland, CA 94607, United States", "latitude" : 37.79637749999999, "longitude" : -122.2782598, "popularity" : 2, "eventType" : "CONCERT", "date" : "2016-09-07T00:00:00-0700", "source" : "http://www.pollstar.com/event/2978624&source=rss" } }, */ @Override public Event findEvent(String category, String eventName, String timeGap) { Event retEvent = new Event(); retEvent.id = "2978624"; retEvent.description = eventName; retEvent.locationString = "Yoshi's Oakland"; retEvent.locationAddress = "510 Embarcadero West, Oakland, CA 94607, United States"; retEvent.latitude = 37.79637749999999; retEvent.longitude = -122.2782598; retEvent.popularity = 2; retEvent.eventType = EventType.CONCERT; retEvent.date = new Date(); retEvent.source = "http://www.pollstar.com/event/2978624&source=rss"; return retEvent; } /* { "_index" : "events", "_type" : "events", "_id" : "2994230", "_score" : 1.0, "_source" : { "id" : "2994230", "description" : "Eminence Ensemble", "locationString" : "Hotel Utah", "locationAddress" : "500 4th St, San Francisco, CA 94107, United States", "latitude" : 37.7793954, "longitude" : -122.3980837, "popularity" : 2, "eventType" : "CONCERT", "date" : "2016-09-09T00:00:00-0700", "source" : "http://www.pollstar.com/event/2994230&source=rss" } }, */ @Override public Event findEvent(String query) { Event retEvent = new Event(); retEvent.id = "2994230"; retEvent.description = "Eminence Ensemble"; retEvent.locationString = "Hotel Utah"; retEvent.locationAddress = "500 4th St, San Francisco, CA 94107, United States"; retEvent.latitude = 37.7793954; retEvent.longitude = -122.3980837; retEvent.popularity = 2; retEvent.eventType = EventType.CONCERT; retEvent.date = new Date(); retEvent.source = "http://www.pollstar.com/event/2994230&source=rss"; return retEvent; } @Override public List<Event> findEventList(String category, String eventName, String timeGap) { // TODO Auto-generated method stub return null; } @Override public List<Event> findEventList(String query) throws Exception { // TODO Auto-generated method stub return null; } }
<reponame>spartan-brent/EternalMessage import React, { Component } from 'react' import SimpleStorageContract from './contracts/SimpleStorage.json' import getWeb3 from './utils/getWeb3' // animate import { StyleSheet, css } from 'aphrodite'; import { spaceInLeft, spaceOutRight } from 'react-magic'; import './css/oswald.css' import './css/open-sans.css' import './css/pure-min.css' import './App.css' // animate style const styles = StyleSheet.create({ in: { animationName: spaceInLeft, animationDuration: '2s' }, out: { animationName: spaceOutRight, animationDuration: '2s' } }); const contractAddress = "0x1d991274d9a2faaf5e7298b9494195c2f91bde30" // 合约地址 var simpleStorageInstance // 合约实例 class App extends Component { constructor(props) { super(props) this.state = { word: null, from: null, timestamp: null, random: 0, count: 0, input: '', web3: null, emptyTip: "还没有留言,快来创建全世界第一条留言吧~", firstTimeLoad: true, loading: false, loadingTip: "留言写入所需时间不等(10s~5min),请耐心等待~", waitingTip: "留言写入所需时间不等(10s~5min),请耐心等待~", successTip: "留言成功", animate: "", in: css(styles.in), out: css(styles.out) } } componentWillMount() { getWeb3 .then(results => { this.setState({ web3: results.web3 }) this.instantiateContract() }) .catch(() => { console.log('Error finding web3.') }) } // 循环从区块上随机读取留言 randerWord() { const that = this setInterval(() => { let random_num = Math.random() * (this.state.count? this.state.count: 0) this.setState({ random: parseInt(random_num) }) console.log("setInterval读取", this.state.random) simpleStorageInstance.getRandomWord(this.state.random) .then(result => { console.log("setInterval读取成功", result) if(result[1]!=this.setState.word){ this.setState({ animate: this.state.out }) setTimeout(() => { that.setState({ count: result[0].c[0], word: result[1], from: result[2], timestamp: result[3], animate: this.state.in }) }, 2000) } }) }, 10000) } instantiateContract() { const that = this const contract = require('truffle-contract') const simpleStorage = contract(SimpleStorageContract) simpleStorage.setProvider(this.state.web3.currentProvider) // Get accounts. this.state.web3.eth.getAccounts((error, accounts) => { simpleStorage.at(contractAddress).then(instance => { simpleStorageInstance = instance //console.log("合约实例获取成功") }) .then(result => { return simpleStorageInstance.getRandomWord(this.state.random) }) .then(result => { //console.log("读取成功", result) if(result[1]!=this.setState.word){ this.setState({ animate: this.state.out }) setTimeout(() => { that.setState({ count: result[0].c[0], word: result[1], from: result[2], timestamp: result[3], animate: this.state.in, firstTimeLoad: false }) }, 2000) }else{ this.setState({ firstTimeLoad: false }) } this.randerWord() }) }) } render() { return ( <div className="container"> <header className="header">永不消逝的留言</header> <main> <div className="main-container"> <div className="showword"> <div className={this.state.magic}> { (simpleStorageInstance && !this.state.firstTimeLoad) ? <span className={this.state.animate}>{this.state.word || this.state.emptyTip}</span> : <img src={require("../public/loading/loading-bubbles.svg")} width="64" height="64"/> } </div> <p className={this.state.animate}> <span>{this.state.word? "来源:"+this.state.from: ""}</span> <span>{this.state.word? "时间:"+this.formatTime(this.state.timestamp): ""}</span> </p> </div> <div className="setword"> <input type="text" value={this.state.input} onChange={e => this.inputWord(e)}/> <button onClick={() => this.setWord()}>写入</button> </div> <div className="tips"> <div> <p>注意事项:</p> <ul> <li>浏览器需要安装 Matemask 扩展程序</li> <li>网络切换至 Ropoetn Test Network</li> <li>留言写入区块链时间不等(10s~5min),请耐心等待</li> <li>留言为随机展示,每个人留言的展示机会平等</li> </ul> </div> </div> </div> </main> <footer>By <a href="https://www.ldsun.com" target="_blank">阿欣</a></footer> <div className={this.state.loading? "loading show": "loading"}> <img src={require("../public/loading/loading-bubbles.svg")} width="128" height="128"/> <p>Matemask 钱包确认支付后开始写入留言</p> <p>{this.state.loadingTip}</p> </div> </div> ); } inputWord(e){ this.setState({ input: e.target.value }) } // 写入区块链 setWord(){ if(!this.state.input) return const that = this this.setState({ loading: true }) let timestamp = new Date().getTime() simpleStorageInstance.setWord(this.state.input, String(timestamp), {from: this.state.web3.eth.accounts[0]}) .then(result => { this.setState({ loadingTip: that.state.successTip }) setTimeout(() => { that.setState({ loading: false, input: '', loadingTip: that.state.waitingTip }) }, 1500) }) .catch(e => { // 拒绝支付 this.setState({ loading: false }) }) } // 时间戳转义 formatTime(timestamp) { let date = new Date(Number(timestamp)) let year = date.getFullYear() let month = date.getMonth() + 1 let day = date.getDate() let hour = date.getHours() let minute = date.getMinutes() let second = date.getSeconds() let fDate = [year, month, day, ].map(this.formatNumber) return fDate[0] + '年' + fDate[1] + '月' + fDate[2] + '日' + ' ' + [hour, minute, second].map(this.formatNumber).join(':') } /** 小于10的数字前面加0 */ formatNumber(n) { n = n.toString() return n[1] ? n : '0' + n } } export default App
<reponame>jrfaller/maracas package mainclient.methodNowStatic; import main.methodNowStatic.MethodNowStatic; public class MethodNowStaticExt extends MethodNowStatic { public int methodNowStaticClientSuperKeyAccess() { return super.methodNowStatic(); } public int methodNowStaticClientNoSuperKeyAccess() { return methodNowStatic(); } }
#!/bin/bash # Copyright (c) 2018 The ZJU-SEL 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. set -o errexit set -o nounset set -o pipefail for d in $(find . -type d -a \( -iwholename './pkg*' -o -iwholename './cmd*' \) -not -iwholename './pkg/api*'); do echo for directory ${d} ... gometalinter \ --exclude='error return value not checked.*(Close|Log|Print).*\(errcheck\)$' \ --exclude='.*_test\.go:.*error return value not checked.*\(errcheck\)$' \ --exclude='duplicate of.*_test.go.*\(dupl\)$' \ --exclude='.*/mock_.*\.go:.*\(golint\)$' \ --exclude='declaration of "err" shadows declaration.*\(vetshadow\)$' \ --exclude='struct of size .* could be .* \(maligned\)$' \ --disable=aligncheck \ --disable=gotype \ --disable=gas \ --cyclo-over=60 \ --dupl-threshold=100 \ --tests \ --deadline=600s "${d}" done
#!/usr/bin/env bash set -o errexit #abort if any command fails me=$(basename "$0") help_message="\ Usage: $me [-c FILE] [<options>] Deploy generated files to a git branch. Options: -h, --help Show this help information. -v, --verbose Increase verbosity. Useful for debugging. -e, --allow-empty Allow deployment of an empty directory. -m, --message MESSAGE Specify the message used when committing on the deploy branch. -n, --no-hash Don't append the source commit's hash to the deploy commit's message. -c, --config-file PATH Override default & environment variables' values with those in set in the file at 'PATH'. Must be the first option specified. Variables: GIT_DEPLOY_DIR Folder path containing the files to deploy. GIT_DEPLOY_BRANCH Commit deployable files to this branch. GIT_DEPLOY_REPO Push the deploy branch to this repository. These variables have default values defined in the script. The defaults can be overridden by environment variables. Any environment variables are overridden by values set in a '.env' file (if it exists), and in turn by those set in a file specified by the '--config-file' option." parse_args() { # Set args from a local environment file. if [ -e ".env" ]; then source .env fi # Set args from file specified on the command-line. if [[ $1 = "-c" || $1 = "--config-file" ]]; then source "$2" shift 2 fi # Parse arg flags # If something is exposed as an environment variable, set/overwrite it # here. Otherwise, set/overwrite the internal variable instead. while : ; do if [[ $1 = "-h" || $1 = "--help" ]]; then echo "$help_message" return 0 elif [[ $1 = "-v" || $1 = "--verbose" ]]; then verbose=true shift elif [[ $1 = "-e" || $1 = "--allow-empty" ]]; then allow_empty=true shift elif [[ ( $1 = "-m" || $1 = "--message" ) && -n $2 ]]; then commit_message=$2 shift 2 elif [[ $1 = "-n" || $1 = "--no-hash" ]]; then GIT_DEPLOY_APPEND_HASH=false shift else break fi done # Set internal option vars from the environment and arg flags. All internal # vars should be declared here, with sane defaults if applicable. # Source directory & target branch. deploy_directory=${GIT_DEPLOY_DIR:-dist} deploy_branch=${GIT_DEPLOY_BRANCH:-gh-pages} #if no user identity is already set in the current git environment, use this: default_username=${GIT_DEPLOY_USERNAME:-deploy.sh} default_email=${GIT_DEPLOY_EMAIL:-} #repository to deploy to. must be readable and writable. repo=${GIT_DEPLOY_REPO:-origin} #append commit hash to the end of message by default append_hash=${GIT_DEPLOY_APPEND_HASH:-true} } main() { parse_args "$@" enable_expanded_output if ! git diff --exit-code --quiet --cached; then echo Aborting due to uncommitted changes in the index >&2 return 1 fi commit_title=`git log -n 1 --format="%s" HEAD` commit_hash=` git log -n 1 --format="%H" HEAD` #default commit message uses last title if a custom one is not supplied if [[ -z $commit_message ]]; then commit_message="publish: $commit_title" fi #append hash to commit message unless no hash flag was found if [ $append_hash = true ]; then commit_message="$commit_message"$'\n\n'"generated from commit $commit_hash" fi previous_branch=`git rev-parse --abbrev-ref HEAD` if [ ! -d "$deploy_directory" ]; then echo "Deploy directory '$deploy_directory' does not exist. Aborting." >&2 return 1 fi # must use short form of flag in ls for compatibility with OS X and BSD if [[ -z `ls -A "$deploy_directory" 2> /dev/null` && -z $allow_empty ]]; then echo "Deploy directory '$deploy_directory' is empty. Aborting. If you're sure you want to deploy an empty tree, use the --allow-empty / -e flag." >&2 return 1 fi if git ls-remote --exit-code $repo "refs/heads/$deploy_branch" ; then # deploy_branch exists in $repo; make sure we have the latest version disable_expanded_output git fetch --force $repo $deploy_branch:$deploy_branch enable_expanded_output fi # check if deploy_branch exists locally if git show-ref --verify --quiet "refs/heads/$deploy_branch" then incremental_deploy else initial_deploy fi restore_head } initial_deploy() { git --work-tree "$deploy_directory" checkout --orphan $deploy_branch git --work-tree "$deploy_directory" add --all commit+push } incremental_deploy() { #make deploy_branch the current branch git symbolic-ref HEAD refs/heads/$deploy_branch #put the previously committed contents of deploy_branch into the index git --work-tree "$deploy_directory" reset --mixed --quiet git --work-tree "$deploy_directory" add --all set +o errexit diff=$(git --work-tree "$deploy_directory" diff --exit-code --quiet HEAD --)$? set -o errexit case $diff in 0) echo No changes to files in $deploy_directory. Skipping commit.;; 1) commit+push;; *) echo git diff exited with code $diff. Aborting. Staying on branch $deploy_branch so you can debug. To switch back to master, use: git symbolic-ref HEAD refs/heads/master && git reset --mixed >&2 return $diff ;; esac } commit+push() { set_user_id git --work-tree "$deploy_directory" commit -m "$commit_message" disable_expanded_output #--quiet is important here to avoid outputting the repo URL, which may contain a secret token git push --quiet $repo $deploy_branch enable_expanded_output } #echo expanded commands as they are executed (for debugging) enable_expanded_output() { if [ $verbose ]; then set -o xtrace set +o verbose fi } #this is used to avoid outputting the repo URL, which may contain a secret token disable_expanded_output() { if [ $verbose ]; then set +o xtrace set -o verbose fi } set_user_id() { if [[ -z `git config user.name` ]]; then git config user.name "$default_username" fi if [[ -z `git config user.email` ]]; then git config user.email "$default_email" fi } restore_head() { if [[ $previous_branch = "HEAD" ]]; then #we weren't on any branch before, so just set HEAD back to the commit it was on git update-ref --no-deref HEAD $commit_hash $deploy_branch else git symbolic-ref HEAD refs/heads/$previous_branch fi git reset --mixed } filter() { sed -e "s|$repo|\$repo|g" } sanitize() { "$@" 2> >(filter 1>&2) | filter } [[ $1 = --source-only ]] || main "$@"
import pandas as pd from pathlib import Path datasets_path = Path.joinpath(Path.cwd(),'dataset') df3 = pd.read_excel(Path.joinpath(datasets_path,'game_data.xlsx')) fullJsonMiddleFormat = "" for i in range(len(df3)): # print(df3['GAMES'].iloc[i]) tagKey = """{"tag":""" tagValue = "'" + str(f"{df3['GAMES'].iloc[i]}") + "'," TAG = tagKey + tagValue patternsKey = """"patterns":""" patternsValue = "'" + f"{df3['GAMES'].iloc[i]} requirements" + "'" + "," + "'" + f"{df3['GAMES'].iloc[i]}" + "'" PATTERNS = patternsKey + f"[{patternsValue}]," txt = df3['MR'].iloc[i] cpu = "\\" + "n" + txt[txt.find("CPU"):txt.find("GPU")] + "\\" + "n" gpu = cpu + txt[txt.find("GPU"):txt.find("RAM")] + "\\" + "n" ram = gpu + txt[txt.find("RAM"):txt.find("VRAM")] + "\\" + "n" vram = ram + txt[txt.find("VRAM"):] + "\\" + "n" + "\\" + "n" txt2 = df3['RR'].iloc[i] cpu2 = "\\" + "n" + txt2[txt2.find("CPU"):txt2.find("GPU")] + "\\" + "n" gpu2 = cpu2 + txt2[txt2.find("GPU"):txt2.find("RAM")] + "\\" + "n" ram2 = gpu2 + txt2[txt2.find("RAM"):txt2.find("VRAM")] + "\\" + "n" vram2 = ram2 + txt2[txt2.find("VRAM"):] responsesKey = """"responses":""" responsesValue = "['MINIMUM" + f"{vram}" + "\\" + "n" + "\\" + "n" + "RECOMMENDED" + f"{vram2}" + "']," REPONSES = responsesKey + f"{responsesValue}" jsonMiddleFormat = "\n\t" + TAG + "\n\t" + PATTERNS + "\n\t" + REPONSES + "\n\t" + """"context": [""]},\n\n\t""" fullJsonMiddleFormat = fullJsonMiddleFormat + jsonMiddleFormat fullJsonFormat = """{"intents":[\n\t""" + fullJsonMiddleFormat[:-1] + """\n\t]}""" # print(fullJsonFormat) #convert json to text file text_file = open("intents.json", "wt") n = text_file.write(fullJsonFormat) text_file.close()
def longestCommonPrefix(strings): if len(strings) == 0: return "" prefix = strings[0] for i in range(1, len(strings)): j = 0 while j < len(prefix) and j < len(strings[i]) and strings[i][j] == prefix[j]: j += 1 prefix = prefix[:j] return prefix result = longestCommonPrefix(["apple", "application", "arena"]) print(result)
import matplotlib.pyplot as plt def visualize_bg_values(dup_bgval_upload1, dup_bgval_upload2): plt.subplot(2, 1, 1) plt.plot(dup_bgval_upload1, 'g-') plt.ylabel('dup_bgval_upload1') plt.subplot(2, 1, 2) plt.plot(dup_bgval_upload2) plt.show() # Example usage dup_bgval_upload1 = [120, 130, 125, 140, 135] dup_bgval_upload2 = [115, 118, 122, 128, 130] visualize_bg_values(dup_bgval_upload1, dup_bgval_upload2)
<gh_stars>0 -- phpMyAdmin SQL Dump -- version 5.0.4 -- https://www.phpmyadmin.net/ -- -- Host: localhost -- Waktu pembuatan: 16 Jul 2021 pada 00.29 -- Versi server: 8.0.22 -- Versi PHP: 7.4.14 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `sppv2_db` -- -- -------------------------------------------------------- -- -- Struktur dari tabel `provinsi` -- CREATE TABLE `provinsi` ( `id_provinsi` int NOT NULL, `kode_provinsi` varchar(10) NOT NULL, `nama` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `provinsi` -- INSERT INTO `provinsi` (`id_provinsi`, `kode_provinsi`, `nama`) VALUES (0, 'id-xx', '#N/A'), (1, 'id-ac', 'Prov. Aceh'), (2, 'id-ba', 'Prov. Bali'), (3, 'id-bb', 'Prov. Bangka Belitung'), (4, 'id-bt', 'Prov. Banten'), (5, 'id-be', 'Prov. Bengkulu'), (6, 'id-yo', 'Prov. D.I. Yogyakarta'), (7, 'id-jk', 'Prov. D.K.I. Jakarta'), (8, 'id-go', 'Prov. Gorontalo'), (9, 'id-ja', 'Prov. Jambi'), (10, 'id-jr', 'Prov. Jawa Barat'), (11, 'id-jt', 'Prov. Jawa Tengah'), (12, 'id-ji', 'Prov. Jawa Timur'), (13, 'id-kb', 'Prov. Kalimantan Barat'), (14, 'id-ks', 'Prov. Kalimantan Selatan'), (15, 'id-kt', 'Prov. Kalimantan Tengah'), (16, 'id-ki', 'Prov. Kalimantan Timur'), (17, 'id-ku', 'Prov. Kalimantan Utara'), (18, 'id-kr', 'Prov. Kepulauan Riau'), (19, 'id-1024', 'Prov. Lampung'), (20, 'id-ma', 'Prov. Maluku'), (21, 'id-la', 'Prov. Maluku Utara'), (22, 'id-nb', 'Prov. Nusa Tenggara Barat'), (23, 'id-nt', 'Prov. Nusa Tenggara Timur'), (24, 'id-pa', 'Prov. Papua'), (25, 'id-ib', 'Prov. Papua Barat'), (26, 'id-ri', 'Prov. Riau'), (27, 'id-sr', 'Prov. Sulawesi Barat'), (28, 'id-se', 'Prov. Sulawesi Selatan'), (29, 'id-st', 'Prov. Sulawesi Tengah'), (30, 'id-sg', 'Prov. Sulawesi Tenggara'), (31, 'id-sw', 'Prov. Sulawesi Utara'), (32, 'id-sb', 'Prov. Sumatera Barat'), (33, 'id-sl', 'Prov. Sumatera Selatan'), (34, 'id-su', 'Prov. Sumatera Utara'); -- -- Indexes for dumped tables -- -- -- Indeks untuk tabel `provinsi` -- ALTER TABLE `provinsi` ADD PRIMARY KEY (`id_provinsi`); -- -- AUTO_INCREMENT untuk tabel yang dibuang -- -- -- AUTO_INCREMENT untuk tabel `provinsi` -- ALTER TABLE `provinsi` MODIFY `id_provinsi` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=35; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
jam F_CPU=8000000 "CCFLAGS=-include DuinodeV5.h" -dx UPLOAD_SPEED=57600 u0 && picocom -b 57600 /dev/ttyUSB0
<html> <head> <title>Form Submission</title> </head> <body> <h1>Submission Form</h1> <form action="submit.php" method="post"> <label for="first_name">First Name:</label> <input type="text" name="first_name" id="first_name" /> <label for="last_name">Last Name:</label> <input type="text" name="last_name" id="last_name" /> <label for="email">Email:</label> <input type="email" name="email" id="email" /> <input type="submit" value="Submit" /> </form> </body> </html> <?php // Connect to the database $db = new mysqli("localhost", "username", "password", "database"); // Prepare the query $stmt = $db->prepare("INSERT INTO users (first_name, last_name, email) VALUES (?, ?, ?)"); $stmt->bind_param("sss", $_POST['first_name'], $_POST['last_name'], $_POST['email']); // Execute the query $stmt->execute(); ?>
<gh_stars>0 package widget import ( "image/color" "fyne.io/fyne" "fyne.io/fyne/canvas" "fyne.io/fyne/driver/desktop" "fyne.io/fyne/theme" ) type scrollBarOrientation int // We default to vertical as 0 due to that being the original orientation offered const ( scrollBarOrientationVertical scrollBarOrientation = 0 scrollBarOrientationHorizontal scrollBarOrientation = 1 ) type scrollBarRenderer struct { scrollBar *scrollBar minSize fyne.Size } func (r *scrollBarRenderer) BackgroundColor() color.Color { return theme.ScrollBarColor() } func (r *scrollBarRenderer) Destroy() { } func (r *scrollBarRenderer) Layout(size fyne.Size) { } func (r *scrollBarRenderer) MinSize() fyne.Size { return r.minSize } func (r *scrollBarRenderer) Objects() []fyne.CanvasObject { return nil } func (r *scrollBarRenderer) Refresh() { } var _ desktop.Hoverable = (*scrollBar)(nil) var _ fyne.Draggable = (*scrollBar)(nil) type scrollBar struct { BaseWidget area *scrollBarArea draggedDistanceHoriz int draggedDistanceVert int dragStartHoriz int dragStartVert int isDragged bool orientation scrollBarOrientation } func (s *scrollBar) MinSize() fyne.Size { s.ExtendBaseWidget(s) return s.BaseWidget.MinSize() } func (s *scrollBar) CreateRenderer() fyne.WidgetRenderer { s.ExtendBaseWidget(s) return &scrollBarRenderer{scrollBar: s} } func (s *scrollBar) DragEnd() { } func (s *scrollBar) Dragged(e *fyne.DragEvent) { if !s.isDragged { s.isDragged = true switch s.orientation { case scrollBarOrientationHorizontal: s.dragStartHoriz = s.Position().X case scrollBarOrientationVertical: s.dragStartVert = s.Position().Y } s.draggedDistanceHoriz = 0 s.draggedDistanceVert = 0 } switch s.orientation { case scrollBarOrientationHorizontal: s.draggedDistanceHoriz += e.DraggedX s.area.moveHorizontalBar(s.draggedDistanceHoriz + s.dragStartHoriz) case scrollBarOrientationVertical: s.draggedDistanceVert += e.DraggedY s.area.moveVerticalBar(s.draggedDistanceVert + s.dragStartVert) } } func (s *scrollBar) MouseIn(e *desktop.MouseEvent) { s.area.MouseIn(e) } func (s *scrollBar) MouseMoved(*desktop.MouseEvent) { } func (s *scrollBar) MouseOut() { s.area.MouseOut() } func newScrollBar(area *scrollBarArea) *scrollBar { return &scrollBar{area: area, orientation: area.orientation} } type scrollBarAreaRenderer struct { area *scrollBarArea bar *scrollBar orientation scrollBarOrientation objects []fyne.CanvasObject } func (s *scrollBarAreaRenderer) BackgroundColor() color.Color { return color.Transparent } func (s *scrollBarAreaRenderer) Destroy() { } func (s *scrollBarAreaRenderer) Layout(size fyne.Size) { switch s.orientation { case scrollBarOrientationHorizontal: s.updateHorizontalBarPosition() case scrollBarOrientationVertical: s.updateVerticalBarPosition() } } func (s *scrollBarAreaRenderer) MinSize() fyne.Size { var min int min = theme.ScrollBarSize() switch s.orientation { case scrollBarOrientationHorizontal: if !s.area.isTall { min = theme.ScrollBarSmallSize() * 2 } return fyne.NewSize(theme.ScrollBarSize(), min) default: if !s.area.isWide { min = theme.ScrollBarSmallSize() * 2 } return fyne.NewSize(min, theme.ScrollBarSize()) } } func (s *scrollBarAreaRenderer) Objects() []fyne.CanvasObject { return s.objects } func (s *scrollBarAreaRenderer) Refresh() { switch s.orientation { case scrollBarOrientationHorizontal: s.updateHorizontalBarPosition() default: s.updateVerticalBarPosition() } canvas.Refresh(s.bar) } func (s *scrollBarAreaRenderer) updateHorizontalBarPosition() { barWidth := s.horizontalBarWidth() barRatio := float32(0.0) if s.area.scroll.Offset.X != 0 { barRatio = float32(s.area.scroll.Offset.X) / float32(s.area.scroll.Content.Size().Width-s.area.scroll.Size().Width) } barX := int(float32(s.area.scroll.size.Width-barWidth) * barRatio) var barY, barHeight int if s.area.isTall { barHeight = theme.ScrollBarSize() } else { barY = theme.ScrollBarSmallSize() barHeight = theme.ScrollBarSmallSize() } s.bar.Resize(fyne.NewSize(barWidth, barHeight)) s.bar.Move(fyne.NewPos(barX, barY)) } func (s *scrollBarAreaRenderer) updateVerticalBarPosition() { barHeight := s.verticalBarHeight() barRatio := float32(0.0) if s.area.scroll.Offset.Y != 0 { barRatio = float32(s.area.scroll.Offset.Y) / float32(s.area.scroll.Content.Size().Height-s.area.scroll.Size().Height) } barY := int(float32(s.area.scroll.size.Height-barHeight) * barRatio) var barX, barWidth int if s.area.isWide { barWidth = theme.ScrollBarSize() } else { barX = theme.ScrollBarSmallSize() barWidth = theme.ScrollBarSmallSize() } s.bar.Resize(fyne.NewSize(barWidth, barHeight)) s.bar.Move(fyne.NewPos(barX, barY)) } func (s *scrollBarAreaRenderer) horizontalBarWidth() int { portion := float32(s.area.size.Width) / float32(s.area.scroll.Content.Size().Width) if portion > 1.0 { portion = 1.0 } return int(float32(s.area.size.Width) * portion) } func (s *scrollBarAreaRenderer) verticalBarHeight() int { portion := float32(s.area.size.Height) / float32(s.area.scroll.Content.Size().Height) if portion > 1.0 { portion = 1.0 } return int(float32(s.area.size.Height) * portion) } var _ desktop.Hoverable = (*scrollBarArea)(nil) type scrollBarArea struct { BaseWidget isWide bool isTall bool scroll *ScrollContainer orientation scrollBarOrientation } func (s *scrollBarArea) CreateRenderer() fyne.WidgetRenderer { s.ExtendBaseWidget(s) bar := newScrollBar(s) return &scrollBarAreaRenderer{area: s, bar: bar, orientation: s.orientation, objects: []fyne.CanvasObject{bar}} } // MinSize returns the size that this widget should not shrink below func (s *scrollBarArea) MinSize() fyne.Size { s.ExtendBaseWidget(s) return s.BaseWidget.MinSize() } func (s *scrollBarArea) MouseIn(*desktop.MouseEvent) { switch s.orientation { case scrollBarOrientationHorizontal: s.isTall = true case scrollBarOrientationVertical: s.isWide = true } Refresh(s.scroll) } func (s *scrollBarArea) MouseMoved(*desktop.MouseEvent) { } func (s *scrollBarArea) MouseOut() { switch s.orientation { case scrollBarOrientationHorizontal: s.isTall = false case scrollBarOrientationVertical: s.isWide = false } Refresh(s.scroll) } func (s *scrollBarArea) moveHorizontalBar(x int) { render := Renderer(s).(*scrollBarAreaRenderer) barWidth := render.horizontalBarWidth() scrollWidth := s.scroll.Size().Width maxX := scrollWidth - barWidth if x < 0 { x = 0 } else if x > maxX { x = maxX } ratio := float32(x) / float32(maxX) s.scroll.Offset.X = int(ratio * float32(s.scroll.Content.Size().Width-scrollWidth)) Refresh(s.scroll) } func (s *scrollBarArea) moveVerticalBar(y int) { render := Renderer(s).(*scrollBarAreaRenderer) barHeight := render.verticalBarHeight() scrollHeight := s.scroll.Size().Height maxY := scrollHeight - barHeight if y < 0 { y = 0 } else if y > maxY { y = maxY } ratio := float32(y) / float32(maxY) s.scroll.Offset.Y = int(ratio * float32(s.scroll.Content.Size().Height-scrollHeight)) Refresh(s.scroll) } func newScrollBarArea(scroll *ScrollContainer, orientation scrollBarOrientation) *scrollBarArea { return &scrollBarArea{scroll: scroll, orientation: orientation} } type scrollRenderer struct { scroll *ScrollContainer vertArea *scrollBarArea horizArea *scrollBarArea leftShadow, rightShadow fyne.CanvasObject topShadow, bottomShadow fyne.CanvasObject objects []fyne.CanvasObject } func (s *scrollRenderer) BackgroundColor() color.Color { return theme.BackgroundColor() } func (s *scrollRenderer) Destroy() { } func (s *scrollRenderer) Layout(size fyne.Size) { // The scroll bar needs to be resized and moved on the far right s.horizArea.Resize(fyne.NewSize(size.Width, s.horizArea.MinSize().Height)) s.vertArea.Resize(fyne.NewSize(s.vertArea.MinSize().Width, size.Height)) s.horizArea.Move(fyne.NewPos(0, s.scroll.Size().Height-s.horizArea.Size().Height)) s.vertArea.Move(fyne.NewPos(s.scroll.Size().Width-s.vertArea.Size().Width, 0)) s.leftShadow.Resize(fyne.NewSize(0, size.Height)) s.rightShadow.Resize(fyne.NewSize(0, size.Height)) s.topShadow.Resize(fyne.NewSize(size.Width, 0)) s.bottomShadow.Resize(fyne.NewSize(size.Width, 0)) s.rightShadow.Move(fyne.NewPos(s.scroll.size.Width, 0)) s.bottomShadow.Move(fyne.NewPos(0, s.scroll.size.Height)) c := s.scroll.Content c.Resize(c.MinSize().Union(size)) s.updatePosition() } func (s *scrollRenderer) MinSize() fyne.Size { return fyne.NewSize(25, 25) // TODO consider the smallest useful scroll view? } func (s *scrollRenderer) Objects() []fyne.CanvasObject { return s.objects } func (s *scrollRenderer) Refresh() { s.Layout(s.scroll.Size()) } func (s *scrollRenderer) calculateScrollPosition(contentSize int, scrollSize int, offset int, area *scrollBarArea) { if contentSize <= scrollSize { if area == s.horizArea { s.scroll.Offset.X = 0 } else { s.scroll.Offset.Y = 0 } area.Hide() } else if s.scroll.Visible() { area.Show() if contentSize-offset < scrollSize { if area == s.horizArea { s.scroll.Offset.X = contentSize - scrollSize } else { s.scroll.Offset.Y = contentSize - scrollSize } } } } func (s *scrollRenderer) calculateShadows(offset int, contentSize int, scrollSize int, shadowStart fyne.CanvasObject, shadowEnd fyne.CanvasObject) { if !s.scroll.Visible() { return } if offset > 0 { shadowStart.Show() } else { shadowStart.Hide() } if offset < contentSize-scrollSize { shadowEnd.Show() } else { shadowEnd.Hide() } } func (s *scrollRenderer) updatePosition() { scrollWidth := s.scroll.Size().Width contentWidth := s.scroll.Content.Size().Width scrollHeight := s.scroll.Size().Height contentHeight := s.scroll.Content.Size().Height s.calculateScrollPosition(contentWidth, scrollWidth, s.scroll.Offset.X, s.horizArea) s.calculateScrollPosition(contentHeight, scrollHeight, s.scroll.Offset.Y, s.vertArea) s.scroll.Content.Move(fyne.NewPos(-s.scroll.Offset.X, -s.scroll.Offset.Y)) canvas.Refresh(s.scroll.Content) s.calculateShadows(s.scroll.Offset.X, contentWidth, scrollWidth, s.leftShadow, s.rightShadow) s.calculateShadows(s.scroll.Offset.Y, contentHeight, scrollHeight, s.topShadow, s.bottomShadow) Renderer(s.vertArea).Layout(s.scroll.size) Renderer(s.horizArea).Layout(s.scroll.size) } // ScrollContainer defines a container that is smaller than the Content. // The Offset is used to determine the position of the child widgets within the container. type ScrollContainer struct { BaseWidget Content fyne.CanvasObject Offset fyne.Position horizontalDraggedDistance int verticalDraggedDistance int hbar *scrollBarArea vbar *scrollBarArea } // CreateRenderer is a private method to Fyne which links this widget to its renderer func (s *ScrollContainer) CreateRenderer() fyne.WidgetRenderer { s.impl = s s.hbar = newScrollBarArea(s, scrollBarOrientationHorizontal) s.vbar = newScrollBarArea(s, scrollBarOrientationVertical) leftShadow := newShadow(shadowRight, theme.Padding()*2) rightShadow := newShadow(shadowLeft, theme.Padding()*2) topShadow := newShadow(shadowBottom, theme.Padding()*2) bottomShadow := newShadow(shadowTop, theme.Padding()*2) return &scrollRenderer{ objects: []fyne.CanvasObject{s.Content, s.hbar, s.vbar, topShadow, bottomShadow}, scroll: s, horizArea: s.hbar, vertArea: s.vbar, leftShadow: leftShadow, rightShadow: rightShadow, topShadow: topShadow, bottomShadow: bottomShadow, } } // DragEnd will stop scrolling on mobile has stopped func (s *ScrollContainer) DragEnd() { } // Dragged will scroll on any drag - bar or otherwise - for mobile func (s *ScrollContainer) Dragged(e *fyne.DragEvent) { if !fyne.CurrentDevice().IsMobile() { return } maxX := s.Content.Size().Width maxY := s.Content.Size().Height s.horizontalDraggedDistance -= e.DraggedX s.verticalDraggedDistance -= e.DraggedY if s.horizontalDraggedDistance > maxX { s.horizontalDraggedDistance = maxX } else if s.horizontalDraggedDistance < 0 { s.horizontalDraggedDistance = 0 } if s.verticalDraggedDistance > maxY { s.verticalDraggedDistance = maxY } else if s.verticalDraggedDistance < 0 { s.verticalDraggedDistance = 0 } s.Offset.X = s.horizontalDraggedDistance s.Offset.Y = s.verticalDraggedDistance s.Refresh() } // MinSize returns the smallest size this widget can shrink to func (s *ScrollContainer) MinSize() fyne.Size { s.ExtendBaseWidget(s) return s.BaseWidget.MinSize() } // Scrolled is called when an input device triggers a scroll event func (s *ScrollContainer) Scrolled(ev *fyne.ScrollEvent) { if s.Content.Size().Width <= s.Size().Width && s.Content.Size().Height <= s.Size().Height { return } if s.hbar.Visible() && !s.vbar.Visible() { s.Offset.X -= ev.DeltaY s.Offset.Y -= ev.DeltaX } else { s.Offset.X -= ev.DeltaX s.Offset.Y -= ev.DeltaY } if s.Offset.X < 0 { s.Offset.X = 0 } else if s.Offset.X+s.Size().Width >= s.Content.Size().Width { s.Offset.X = s.Content.Size().Width - s.Size().Width } if s.Offset.Y < 0 { s.Offset.Y = 0 } else if s.Offset.Y+s.Size().Height >= s.Content.Size().Height { s.Offset.Y = s.Content.Size().Height - s.Size().Height } Refresh(s) } // NewScrollContainer creates a scrollable parent wrapping the specified content. // Note that this may cause the MinSize to be smaller than that of the passed objects. func NewScrollContainer(content fyne.CanvasObject) *ScrollContainer { s := &ScrollContainer{Content: content} s.ExtendBaseWidget(s) return s }
import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {HomeRoutingModule} from './home-routing.module'; import {HomeComponent} from './home.component'; import {SharedModule} from '../shared/shared.module'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {HttpClientModule} from '@angular/common/http'; import {CoreModule} from '../core/core.module'; import { MatButtonModule, MatCardModule, MatDividerModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatOptionModule, MatSelectModule, MatStepperModule } from '@angular/material'; @NgModule({ declarations: [HomeComponent], imports: [ CommonModule, SharedModule, HomeRoutingModule, BrowserAnimationsModule, FormsModule, HttpClientModule, CoreModule, SharedModule, MatCardModule, MatStepperModule, MatFormFieldModule, MatButtonModule, MatDividerModule, MatListModule, MatIconModule, MatInputModule, MatOptionModule, MatSelectModule, MatGridListModule, ReactiveFormsModule, ] }) export class HomeModule { }
#!/bin/bash #name=T5tttt #name=T1t1t #name=pMSSM_b1 name=T1tttt_madgraph #name=T1bbbb_madgraph #name=T2tt #name=T1tttt mod=_ucsb1776 t="$(date +%s)" echo Deleting supplementary files created from splitting process. sleep 1 rm ./files/pj_eff_*.sh rm ./files/pj_eff_*.jdl mv ../btagEff_Ldp_${name}_*.txt ./txt/ldp/eff mv ../lightMistag_Ldp_${name}_*.txt ./txt/ldp/mistag mv ../eventCount_Ldp_${name}_*.txt ./txt/ldp/count mv ../btagEff_Sig_${name}_*.txt ./txt/sig/eff mv ../lightMistag_Sig_${name}_*.txt ./txt/sig/mistag mv ../eventCount_Sig_${name}_*.txt ./txt/sig/count mv ../btagEff_Sl_${name}_*.txt ./txt/sl/eff mv ../lightMistag_Sl_${name}_*.txt ./txt/sl/mistag mv ../eventCount_Sl_${name}_*.txt ./txt/sl/count for file in ./txt/ldp/eff/*.txt do head $file >> btagEff_${name}${mod}_LDP.txt echo >> btagEff_${name}${mod}_LDP.txt done for file in ./txt/ldp/mistag/*.txt do head $file >> lightMistag_${name}${mod}_LDP.txt echo >> lightMistag_${name}${mod}_LDP.txt done for file in ./txt/ldp/count/*.txt do head $file >> rawCounts_${name}${mod}_LDP.txt echo >> rawCounts_${name}${mod}_LDP.txt done for file in ./txt/sig/eff/*.txt do head $file >> btagEff_${name}${mod}_SIG.txt echo >> btagEff_${name}${mod}_SIG.txt done for file in ./txt/sig/mistag/*.txt do head $file >> lightMistag_${name}${mod}_SIG.txt echo >> lightMistag_${name}${mod}_SIG.txt done for file in ./txt/sig/count/*.txt do head $file >> rawCounts_${name}${mod}_SIG.txt echo >> rawCounts_${name}${mod}_SIG.txt done for file in ./txt/sl/eff/*.txt do head $file >> btagEff_${name}${mod}_SL.txt echo >> btagEff_${name}${mod}_SL.txt done for file in ./txt/sl/mistag/*.txt do head $file >> lightMistag_${name}${mod}_SL.txt echo >> lightMistag_${name}${mod}_SL.txt done for file in ./txt/sl/count/*.txt do head $file >> rawCounts_${name}${mod}_SL.txt echo >> rawCounts_${name}${mod}_SL.txt done rm ./txt/ldp/eff/* rm ./txt/sig/eff/* rm ./txt/sl/eff/* rm ./txt/ldp/count/* rm ./txt/sig/count/* rm ./txt/sl/count/* rm ./txt/ldp/mistag/* rm ./txt/sig/mistag/* rm ./txt/sl/mistag/* t="$(($(date +%s)-t))" printf "Time it took to run this program: %02d:%02d:%02d\n" "$((t/3600))" "$((t/60))" "$((t%60))" exit
import nltk nltk.download('vader_lexicon') from nltk.sentiment.vader import SentimentIntensityAnalyzer def sentiment_analyzer(sentence): sid = SentimentIntensityAnalyzer() sentiment = sid.polarity_scores(sentence)['compound'] if sentiment >= 0.05: return 'positive' elif sentiment <= -0.05: return 'negative' else: return 'neutral' sentiment_analyzer('I love this movie!') // Output: 'positive'
<reponame>kasuganosora/journey package structure type Tag struct { Id int64 Name []byte Slug string }
# You may uncomment the following lines if you want `ls' to be colorized: export LS_OPTIONS='--color=auto' eval "`dircolors`" alias ls='ls $LS_OPTIONS' alias ll='ls $LS_OPTIONS -l' alias l='ls $LS_OPTIONS -lA'
def process_sequences(matrix, Out1, Out2, Out3): max_score = maxScore # Assuming maxScore is defined elsewhere concatenated_sequences = Out1 + Out3 + Out2 return max_score, concatenated_sequences
SELECT AVG(rating) FROM product_reviews WHERE product_id = '<product_id>';
#!/bin/bash # # Start OGEMA with default configuration (Equinox OSGi and no security) # LAUNCHER=${OGEMA_LAUNCHER:-./ogema-launcher.jar} CONFIG=${OGEMA_CONFIG:-config/config.xml} PROPERTIES=${OGEMA_PROPERTIES:-config/ogema.properties} OPTIONS=$OGEMA_OPTIONS JAVA=${JAVA_HOME:+${JAVA_HOME}/bin/}java EXTENSIONS=bin/ext$(find bin/ext/ -iname "*jar" -printf :%p) VMOPTS="$VMOPTS -cp $LAUNCHER:$EXTENSIONS" if [[ " $@ " =~ " --verbose " ]]; then VMOPTS="$VMOPTS -Dequinox.ds.debug=true -Dequinox.ds.print=true" echo $JAVA $VMOPTS org.ogema.launcher.OgemaLauncher --config $CONFIG --properties $PROPERTIES $OPTIONS $* fi $JAVA $VMOPTS org.ogema.launcher.OgemaLauncher --config $CONFIG --properties $PROPERTIES $OPTIONS $*