text
stringlengths
1
1.05M
from advML.function import advML_deep_package def FGSM(model,input,lable,epsilon): if(advML_deep_package == 'pytorch'): from torch.nn import Module from torch import Tensor assert isinstance(model,Module),'Model should be a child-class of Module' assert isinstance(input,Tensor),'Input should be a Tensor' assert isinstance(lable,Tensor),'Lable should be a Tensor' return FGSM_pytorch(model,input,lable,epsilon) else: assert 0>1,"The deep package is unsupported!" def FGSM_pytorch(model,input,lable,epsilon): import torch.nn as nn import torch #import torch.clamp as clamp input.requires_grad = True predict = model(input) criterion = nn.CrossEntropyLoss() loss = criterion(predict,lable) model.zero_grad() loss.backward() grad = input.grad.data perturbed_input = input + epsilon*(grad.sign()) perturbed_input = torch.clamp(perturbed_input,0,1) return perturbed_input
<filename>open-sphere-base/control-panels/src/main/java/io/opensphere/controlpanels/timeline/AbstractTimelineLayer.java package io.opensphere.controlpanels.timeline; import java.awt.BasicStroke; import java.awt.Component; import java.awt.EventQueue; import java.awt.Graphics2D; import java.awt.Point; import java.awt.event.MouseEvent; import java.util.Collection; import java.util.List; import java.util.function.Supplier; import javax.swing.JMenu; import javax.swing.JMenuItem; import io.opensphere.core.control.action.context.TimespanContextKey; import io.opensphere.core.model.time.TimeSpan; import io.opensphere.core.units.duration.Duration; import io.opensphere.core.util.ObservableValue; import io.opensphere.core.util.awt.AWTUtilities; import io.opensphere.core.util.collections.New; import io.opensphere.core.util.collections.StreamUtilities; import io.opensphere.core.util.swing.ButtonTextPredicate; /** * Abstract timeline layer. */ public abstract class AbstractTimelineLayer implements TimelineLayer { /** The dot circumference (odd number). */ protected static final int DOT_CIRCUMFERENCE = 7; /** The dot padding. */ protected static final int DOT_PADDING = DOT_CIRCUMFERENCE - 1 >> 1; /** Menu items. */ private final List<Supplier<? extends Collection<? extends JMenuItem>>> myMenuItemSuppliers = New.list(0); /** The list of temporary layers that only exist for a single paint. */ private final List<TimelineLayer> myTemporaryLayers = New.list(); /** The timeline UI model. */ private TimelineUIModel myUIModel; /** * Utility method to subtract a duration from an observable time span. * * @param timeSpan the time span * @param duration the duration */ public static void minus(ObservableValue<TimeSpan> timeSpan, Duration duration) { timeSpan.set(timeSpan.get().minus(duration)); } /** * Utility method to add a duration to an observable time span. * * @param timeSpan the time span * @param duration the duration */ public static void plus(ObservableValue<TimeSpan> timeSpan, Duration duration) { timeSpan.set(timeSpan.get().plus(duration)); } /** * Add supplier of context menu items for this layer that will be called to * supply menu items each time a context menu is created. * * @param menuItemSupplier The menu item supplier. */ public void addMenuItemSupplier(Supplier<? extends Collection<? extends JMenuItem>> menuItemSupplier) { myMenuItemSuppliers.add(menuItemSupplier); } @Override public boolean canDrag(Point p) { return false; } @Override public int getDragPriority(Point p) { return 0; } @Override public Object drag(Object dragObject, Point from, Point to, boolean beginning, Duration dragTime) { return null; } @Override public void getMenuItems(Point p, List<JMenuItem> menuItems) { if (canDrag(p)) { for (Supplier<? extends Collection<? extends JMenuItem>> supplier : myMenuItemSuppliers) { menuItems.addAll(supplier.get()); } } } @Override public List<? extends Component> getMenuItems(String contextId, TimespanContextKey key) { return null; } @Override public int getPriority() { return 0; } @Override public List<TimelineLayer> getTemporaryLayers() { return myTemporaryLayers; } @Override public String getToolTipText(MouseEvent event, String incoming) { return incoming; } /** * Gets the UI model. * * @return the UI model */ public TimelineUIModel getUIModel() { return myUIModel; } @Override public boolean hasDragObject(Object dragObject) { return false; } /** * Determines if this layer is being dragged or can be dragged. * * @return whether this layer is being dragged or can be dragged */ public boolean isDraggingOrCanDrag() { return hasDragObject(getUIModel().getDraggingObject()) || getUIModel().getDraggingObject() == null && canDrag(getUIModel().getLastMousePoint()); } @Override public void mouseEvent(MouseEvent e) { } @Override public void paint(Graphics2D g2d) { assert EventQueue.isDispatchThread(); myTemporaryLayers.clear(); } @Override public void setUIModel(TimelineUIModel model) { myUIModel = model; } /** * Look for the new menu in the list of existing menu items, and if a * duplicate is found, transfer the children to the existing menu; otherwise * just add the new menu to the list. * * @param menuItems The list of existing menu items. * @param newMenu The new menu. */ protected void deconflictMenus(List<JMenuItem> menuItems, JMenu newMenu) { JMenuItem existingMenu = StreamUtilities.filterOne(menuItems, new ButtonTextPredicate<JMenuItem>(newMenu.getText())); if (existingMenu == null) { menuItems.add(newMenu); } else { for (Component component : newMenu.getMenuComponents()) { existingMenu.add(component); } } } /** * Convenience method to draw a line from the top to bottom of the timeline * at the given x location. * * @param g2d the graphics context * @param x the x location */ protected void drawLine(Graphics2D g2d, int x) { int maxY = AWTUtilities.getMaxY(myUIModel.getTimelinePanelBounds()) - 1; g2d.drawLine(x, myUIModel.getTimelinePanelBounds().y + 1, x, maxY); } /** A dashed stroke. */ protected static class DashedStroke extends BasicStroke { /** Constructor. */ public DashedStroke() { super(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10, new float[] { 5, 3 }, 0); } } }
public class DatabaseQueryPlan { // Other members and methods of the class can be included here /// <summary> /// Gets a value indicating whether the query plan being logged is valid and /// can be executed against. /// </summary> /// <value><c>true</c> if the query plan is valid; otherwise, <c>false</c>.</value> public bool QueryPlanIsValid { get { // Add logic to determine the validity of the query plan // For example, check if the required tables and columns exist, if the syntax is correct, etc. // Replace the following return statement with your actual logic return IsQueryPlanValid(); } } private bool IsQueryPlanValid() { // Replace this with actual logic to determine the validity of the query plan // For example, check if the required tables and columns exist, if the syntax is correct, etc. // Return true if the query plan is valid, false otherwise return true; // Placeholder, replace with actual logic } }
<filename>arcade_universe/corruptor.py """ Based on the pylearn2's corruptor class. Corruptor classes: classes that encapsulate the noise process for the DAE training criterion. """ # Third-party imports import numpy as np class Corruptor(object): def __init__(self, corruption_level, rng=2001): """ Allocate a corruptor object. Parameters ---------- corruption_level : float Some measure of the amount of corruption to do. What this means will be implementation specific. rng : RandomState object or seed NumPy random number generator object (or seed for creating one) used to initialize a RandomStreams. """ # The default rng should be build in a deterministic way rng = np.random.RandomState(rng) seed = int(rng.randint(2 ** 30)) self.s_rng = np.random.RandomState(seed) self.corruption_level = corruption_level def __call__(self, inputs): """ (Symbolically) corrupt the inputs with a noise process. Parameters ---------- inputs : numpy nd array. Texture to be corrupted. Returns ------- corrupted : Return the corrupted texture. Notes ----- In the base class, this is just a stub. """ raise NotImplementedError() def corruption_free_energy(self, corrupted_X, X): raise NotImplementedError() class DummyCorruptor(Corruptor): def __call__(self, inputs): return inputs class BinomialCorruptor(Corruptor): """ A binomial corruptor sets inputs to 0 with probability 0 < `corruption_level` < 1. """ def _corrupt(self, x): return self.s_rng.binomial( size=x.shape, n=1, p=1 - self.corruption_level ) * x def __call__(self, inputs): """ (Symbolically) corrupt the inputs with a binomial (masking) noise. Parameters ---------- inputs : numpy nd array. Contains the Returns ------- corrupted : numpy nd array. Corrupted texture. where individual inputs have been masked with independent probability equal to `self.corruption_level`. """ #if isinstance(inputs, tensor.Variable): return self._corrupt(inputs) #else: # return [self._corrupt(inp) for inp in inputs] class GaussianCorruptor(Corruptor): """ A Gaussian corruptor transforms inputs by adding zero mean isotropic Gaussian noise. """ def __init__(self, stdev, rng=2001): super(GaussianCorruptor, self).__init__(corruption_level=stdev, rng=rng) def _corrupt(self, x): noise = self.s_rng.normal( size=x.shape, loc=0., scale=self.corruption_level ) rval = abs(noise + x) % 255 return rval def __call__(self, inputs): """ (Symbolically) corrupt the inputs with Gaussian noise. Parameters ---------- inputs : tensor_like, or list of tensor_likes Theano symbolic(s) representing a (list of) (mini)batch of inputs to be corrupted, with the first dimension indexing training examples and the second indexing data dimensions. Returns ------- corrupted : tensor_like, or list of tensor_likes Theano symbolic(s) representing the corresponding corrupted inputs, where individual inputs have been corrupted by zero mean Gaussian noise with standard deviation equal to `self.corruption_level`. """ #if isinstance(inputs, tensor.Variable): return self._corrupt(inputs) #return [self._corrupt(inp) for inp in inputs] ################################################## def get(str): """ Evaluate str into a corruptor object, if it exists """ obj = globals()[str] if issubclass(obj, Corruptor): return obj else: raise NameError(str)
<filename>src/BackgroundThread.java import java.util.*; import java.time.*; public class BackgroundThread { Timer statusTimer; private static final int updateInterval = 5000; private final Thread t = new Thread(() -> { statusTimer = new Timer(); statusTimer.scheduleAtFixedRate(new TimerTask() { public void run() { update(); } }, 0, updateInterval); }); BackgroundThread() { t.start(); } private void update() { Instant start = Monkey.getStartTime() != null ? Monkey.getStartTime() : Instant.now(); Instant now = Instant.now(); Duration timeElapsed = Duration.between(start, now); printStatus(Monkey.getAttempts(), timeElapsed); } private void printStatus(long attempts, Duration timeElapsed) { System.out.println("Current number of attempts: " + attempts); if (timeElapsed.toMinutes() == 0) { System.out.println("Time elapsed: " + timeElapsed.toSecondsPart() + " seconds"); } else if (timeElapsed.toMinutes() == 1){ System.out.println("Time elapsed: " + timeElapsed.toMinutes() + " minute and " + timeElapsed.toSecondsPart() + " seconds"); } else if (timeElapsed.toHours() == 0){ System.out.println("Time elapsed: " + timeElapsed.toMinutes() + " minutes and " + timeElapsed.toSecondsPart() + " seconds"); } else if (timeElapsed.toHours() == 1) { System.out.println("Time elapsed: : " + timeElapsed.toHours() + " hour " + timeElapsed.toMinutesPart() + " minutes and " + timeElapsed.toSecondsPart() + " seconds"); } else { System.out.println("Time elapsed: " + timeElapsed.toHours() + " hours " + timeElapsed.toMinutesPart() + " minutes and " + timeElapsed.toSecondsPart() + " seconds"); } } public void shutdown() { statusTimer.cancel(); statusTimer.purge(); t.interrupt(); } }
function quickSort(arr: number[]) { if (arr.length <= 1) { return arr; } const pivot = arr[0]; const left = arr.slice(1).filter((n: number) => n <= pivot); const right = arr.slice(1).filter((n: number) => n > pivot); return [...quickSort(left), pivot, ...quickSort(right)]; } console.log(quickSort([5, 8, 1, 6, 9, 0])); // Output: [0, 1, 5, 6, 8, 9]
<reponame>jing-si/plant<filename>project/gardener/src/main/java/kr/co/gardener/admin/dao/other/impl/StateDaoImpl.java<gh_stars>1-10 package kr.co.gardener.admin.dao.other.impl; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import kr.co.gardener.admin.dao.other.StateDao; import kr.co.gardener.admin.model.other.State; import kr.co.gardener.util.ComboItem; import kr.co.gardener.util.Pager; @Repository public class StateDaoImpl implements StateDao{ @Autowired SqlSession sql; @Override public List<State> list_pager(Pager pager) { return sql.selectList("state.list_pager", pager); } @Override public float total(Pager pager) { return sql.selectOne("state.total", pager); } @Override public void insert_list(List<State> list) { sql.insert("state.insert_list", list); } @Override public void delete_list(List<State> list) { sql.delete("state.delete_list", list); } @Override public void update_list(List<State> list) { sql.update("state.update_list", list); } }
package com.freud.zk.zkclient; import java.util.Arrays; import java.util.List; import org.I0Itec.zkclient.IZkChildListener; import org.I0Itec.zkclient.IZkDataListener; import org.I0Itec.zkclient.IZkStateListener; import org.I0Itec.zkclient.ZkClient; import org.apache.zookeeper.Watcher.Event.KeeperState; /** * * Zookeeper - ZkClient * * @author Freud * */ public class ZkClientZookeeper { private static final int SECOND = 1000; public static void main(String[] args) throws Exception { ZkClient zk = new ZkClient("localhost:2181", 5 * SECOND); System.out.println("Server connected..."); String root = "/hifreud"; String path = root + "/sayhi"; String path2 = root + "/sayhello"; Thread.sleep(1 * SECOND); // 添加服务器状态监听 zk.subscribeStateChanges(new ZkStateListener()); // 添加子节点状态监听->将监听创建,减少,删除子节点状态 zk.subscribeChildChanges(root, new ZkChildListener()); // 为各个节点添加数据状态监听 zk.subscribeDataChanges(root, new ZkDataListener()); zk.subscribeDataChanges(path, new ZkDataListener()); zk.subscribeDataChanges(path2, new ZkDataListener()); System.out.println("Listener added..."); Thread.sleep(1 * SECOND); boolean exist = zk.exists(path); if (!exist) { System.out.println("Create node : " + path); // 递归创建节点 zk.createPersistent(path, true); } Thread.sleep(1 * SECOND); exist = zk.exists(path2); if (!exist) { System.out.println("Create node : " + path2); // 递归创建节点 zk.createPersistent(path2, true); } Thread.sleep(1 * SECOND); exist = zk.exists(path); if (exist) { // 向节点添加数据 String data = "say hi!"; System.out.println("Write data to node " + path + " : " + data); zk.writeData(path, data); } Thread.sleep(1 * SECOND); exist = zk.exists(path); if (exist) { // 获取节点数据 Object data = zk.readData(path); System.out.println("Read data from node " + path + " : " + data); } Thread.sleep(1 * SECOND); exist = zk.exists(path); if (exist) { // 获取所有子节点 List<String> children = zk.getChildren(root); System.out.println("Get all children from node " + root + " : " + ((children == null || children.isEmpty()) ? "[]" : Arrays.toString(children.toArray()))); } Thread.sleep(1 * SECOND); exist = zk.exists(root); if (exist) { System.out.println("Delete node : " + root); // 递归删除节点 zk.deleteRecursive(root); } Thread.sleep(2 * SECOND); // 关闭连接 zk.close(); System.out.println("Server closeed..."); } } class ZkStateListener implements IZkStateListener { /** * 服务端起停操作触发 */ @SuppressWarnings("deprecation") public void handleStateChanged(KeeperState state) throws Exception { String stateStr = null; switch (state) { case Disconnected: stateStr = "Disconnected"; break; case Expired: stateStr = "Expired"; break; case NoSyncConnected: stateStr = "NoSyncConnected"; break; case SyncConnected: stateStr = "SyncConnected"; break; case Unknown: default: stateStr = "Unknow"; break; } System.out.println("[Callback]State changed to [" + stateStr + "]"); } public void handleNewSession() throws Exception { System.out.println("[Callback]New session created.."); } } class ZkDataListener implements IZkDataListener { public void handleDataChange(String dataPath, Object data) throws Exception { System.out.println("[Callback]Node data changed to (" + dataPath + ", " + data + "]"); } public void handleDataDeleted(String dataPath) throws Exception { System.out.println("[Callback]Delete node (" + dataPath + ")"); } } class ZkChildListener implements IZkChildListener { public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception { System.out .println("[Callback]Child path changed, root(" + parentPath + "), changed to " + ((currentChilds == null || currentChilds.isEmpty()) ? "[]" : Arrays.toString(currentChilds .toArray()))); } }
package com.yoga.weixinapp.wxapi; import com.fasterxml.jackson.annotation.JsonInclude; import com.google.gson.annotations.SerializedName; import com.yoga.weixinapp.ao.WxmpDataItem; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.util.Map; @Getter @Setter @NoArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class WxSendSubscribeRequest { @SerializedName("touser") private String openid; @SerializedName("template_id") private String templateId; @SerializedName("page") private String page; private Map<String, WxmpDataItem> data; @SerializedName("miniprogram_state") private String state = "formal"; //developer为开发版;trial为体验版;formal为正式版 private String lang = "zh_CN("; //zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文) public WxSendSubscribeRequest(String openid, String templateId, String page, Map<String, WxmpDataItem> data, String state) { this.openid = openid; this.templateId = templateId; this.page = page; this.data = data; this.state = state; } }
#!/bin/bash ## Bash script for setting up a ROS/Gazebo development environment for PX4 on Ubuntu LTS (16.04). ## It installs the common dependencies for all targets (including Qt Creator) and the ROS Kinetic/Gazebo 7 (the default). ## ## Installs: ## - Common dependencies libraries and tools as defined in `ubuntu_sim_common_deps.sh` ## - ROS Kinetic (including Gazebo7) ## - MAVROS echo "Downloading dependent script 'ubuntu_sim_common_deps.sh'" # Source the ubuntu_sim_common_deps.sh script directly from github common_deps=$(wget https://raw.githubusercontent.com/PX4/Devguide/master/build_scripts/ubuntu_sim_common_deps.sh -O -) wget_return_code=$? # If there was an error downloading the dependent script, we must warn the user and exit at this point. if [[ $wget_return_code -ne 0 ]]; then echo "Error downloading 'ubuntu_sim_common_deps.sh'. Sorry but I cannot proceed further :("; exit 1; fi # Otherwise source the downloaded script. . <(echo "${common_deps}") # ROS Kinetic/Gazebo (ROS Kinetic includes Gazebo7 by default) ## Gazebo simulator dependencies sudo apt-get install protobuf-compiler libeigen3-dev libopencv-dev -y ## ROS Gazebo: http://wiki.ros.org/kinetic/Installation/Ubuntu ## Setup keys sudo sh -c 'echo "deb http://packages.ros.org/ros/ubuntu $(lsb_release -sc) main" > /etc/apt/sources.list.d/ros-latest.list' sudo -E apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654 ## For keyserver connection problems substitute hkp://pgp.mit.edu:80 or hkp://keyserver.ubuntu.com:80 above. sudo apt-get update ## Get ROS/Gazebo sudo apt-get install ros-kinetic-desktop-full -y ## Initialize rosdep sudo rosdep init rosdep update ## Setup environment variables rossource="source /opt/ros/kinetic/setup.bash" if grep -Fxq "$rossource" ~/.bashrc; then echo ROS setup.bash already in .bashrc; else echo "$rossource" >> ~/.bashrc; fi eval $rossource ## Get rosinstall sudo apt-get install python-rosinstall -y # MAVROS: https://dev.px4.io/en/ros/mavros_installation.html ## Create catkin workspace mkdir -p ~/catkin_ws/src cd ~/catkin_ws ## Install dependencies sudo apt-get install python-wstool python-rosinstall-generator python-catkin-tools -y ## Initialise wstool wstool init ~/catkin_ws/src ## Build MAVROS ### Get source (upstream - released) rosinstall_generator --upstream mavros | tee /tmp/mavros.rosinstall ### Get latest released mavlink package rosinstall_generator mavlink | tee -a /tmp/mavros.rosinstall ### Setup workspace & install deps wstool merge -t src /tmp/mavros.rosinstall wstool update -t src if ! rosdep install --from-paths src --ignore-src --rosdistro kinetic -y; then # (Use echo to trim leading/trailing whitespaces from the unsupported OS name unsupported_os=$(echo $(rosdep db 2>&1| grep Unsupported | awk -F: '{print $2}')) rosdep install --from-paths src --ignore-src --rosdistro kinetic -y --os ubuntu:xenial fi ## Build! catkin build ## Re-source environment to reflect new packages/build environment catkin_ws_source="source ~/catkin_ws/devel/setup.bash" if grep -Fxq "$catkin_ws_source" ~/.bashrc; then echo ROS catkin_ws setup.bash already in .bashrc; else echo "$catkin_ws_source" >> ~/.bashrc; fi eval $catkin_ws_source echo "Downloading dependent script 'install_geographiclib_datasets.sh'" # Source the install_geographiclib_datasets.sh script directly from github install_geo=$(wget https://raw.githubusercontent.com/mavlink/mavros/master/mavros/scripts/install_geographiclib_datasets.sh -O -) wget_return_code=$? # If there was an error downloading the dependent script, we must warn the user and exit at this point. if [[ $wget_return_code -ne 0 ]]; then echo "Error downloading 'install_geographiclib_datasets.sh'. Sorry but I cannot proceed further :("; exit 1; fi # Otherwise source the downloaded script. sudo bash -c "$install_geo" # Go to the firmware directory clone_dir=~/src cd $clone_dir/Firmware if [[ ! -z $unsupported_os ]]; then >&2 echo -e "\033[31mYour OS ($unsupported_os) is unsupported. Assumed an Ubuntu 16.04 installation," >&2 echo -e "and continued with the installation, but if things are not working as" >&2 echo -e "expected you have been warned." fi
from offline_processing import * import numpy as np import pandas as pd import soundfile as sf import matplotlib.pyplot as plt import pathlib as Path def read_wav(wav_path: Path = r"C:\Users\Anthony\Desktop\backups\PublicSpeaking.wav"): """The function receives a path for a wav file and then converts it into a pd.Series and returns the series if the data is relevant (without the last few minutes of silence) Input: wav_path : Path - Path to the wave file Output: wav_data : pd.Series - Series with the raw audio data """ wav_list = [] data, _ = sf.read(wav_path) wav_list.append(data) wav_data = pd.Series(wav_list[0], name = "Sound") wav_data = wav_data[0:38500000] return wav_data def short_wav(wav_data: pd.Series , avg_chunk: int = 4096/2): """ This function matches the length of the wav_data to the general Dataframe by averaging according to the avg_chunk Input: wav_data : pd.Series - Series with the raw audio data avg_chunk : int - The conversion number adapting the legnths. Output: processes_wav_data: pd.Series - Series with the raw audio data after averaging. """ processes_wav_data = wav_data.groupby(np.arange(len(wav_data))//avg_chunk).mean().copy() return processes_wav_data def plot_wav(processes_wav_data): """ This function plots the processed wav data Input: processes_wav_data: pd.Series - Series with the raw audio data after averaging. Output: None """ processes_wav_data.plot() plt.show() def avg_chunk_creator(raw_data: DataFrame, wav_data: pd.Series): """ This function creates the conversion number that matches between the Dataframe and the pd.Series Input: raw_data : Dataframe - raw data of the stress measures wav_data : pd.Series - Series with the raw audio data Output: avg_chunk : int - The conversion number adapting the legnths. """ wav_length = wav_data.size df_length = raw_data["GSR"].size avg_chunk = wav_length/df_length return avg_chunk def merge_all_data(raw_data: DataFrame, processes_wav_data: pd.Series): """ This function converts the pd.Series and the Dataframe into one Dataframe The wav data is under the header WAV. Input: raw_data : Dataframe - raw data of the stress measures processes_wav_data: pd.Series - Series with the raw audio data after averaging. Output: all_data: Dataframe - The Dataframe after merging """ all_data = raw_data.copy() all_data["WAV"] = processes_wav_data return all_data def correlation_creator(column1: pd.Series, column2: pd.Series): """ This function receives two columns with measures of either stress or audio data and returns the correlation between the two measures. Input: column1: pd.Series - The first measure column2: pd.Series - The second measure Output: correlation: float - The correlation """ correlation = column1.corr(column2) return correlation if __name__ == "__main__": data = OfflineAnalysisANS(data_path = r"Data.csv") data.read_data() wav_data = read_wav() avg_chunk = avg_chunk_creator(data.raw_data, wav_data) processes_wav_data = short_wav(wav_data, avg_chunk) plot_wav(processes_wav_data) all_data = merge_all_data(data.raw_data, processes_wav_data) print("WAV and ECG correlation", correlation_creator(all_data["ECG"], all_data["WAV"])) print("WAV and ECG correlation",correlation_creator(all_data["GSR"], all_data["WAV"])) print("WAV and ECG correlation",correlation_creator(all_data["RESP"], all_data["WAV"]))
package app.javachat.Models; import java.io.Serializable; public class ChatInfo implements Serializable { private User user; private int otherChatPort, otherCallListenerPort; private int localChatPort; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public int getOtherChatPort() { return otherChatPort; } public void setOtherChatPort(int otherChatPort) { this.otherChatPort = otherChatPort; } public int getOtherCallListenerPort() { return otherCallListenerPort; } public void setOtherCallListenerPort(int otherCallListenerPort) { this.otherCallListenerPort = otherCallListenerPort; } public int getLocalChatPort() { return localChatPort; } public void setLocalChatPort(int localChatPort) { this.localChatPort = localChatPort; } @Override public String toString() { return "ChatInfo{" + "user=" + user + ", otherChatPort=" + otherChatPort + ", otherCallPort=" + otherCallListenerPort + ", localChatPort=" + localChatPort + '}'; } }
<gh_stars>0 package me.batizhao.ims.unit.controller; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.fasterxml.jackson.databind.ObjectMapper; import me.batizhao.common.core.util.ResultEnum; import me.batizhao.common.security.component.PecadoUser; import me.batizhao.common.security.util.SecurityUtils; import me.batizhao.ims.api.domain.Role; import me.batizhao.ims.api.domain.User; import me.batizhao.ims.api.domain.UserRole; import me.batizhao.ims.api.vo.UserInfoVO; import me.batizhao.ims.controller.UserController; import me.batizhao.ims.service.UserDepartmentService; import me.batizhao.ims.service.UserPostService; import me.batizhao.ims.service.UserRoleService; import me.batizhao.ims.service.UserService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.text.StringContainsInOrder.stringContainsInOrder; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * 注意,在 Spring Security 启用的情况下: * 1. post、put、delete 方法要加上 with(csrf()),否则会返回 403,因为这里控制了 config 扫描范围 csrf.disable 并没有生效 * 2. 单元测试要控制扫描范围,防止 Spring Security Config 自动初始化,尤其是 UserDetailsService 自定义的情况(会加载 Mapper) * 3. 测试方法要加上 @WithMockUser,否则会返回 401 * * @author batizhao * @since 2020-02-10 */ @WebMvcTest(UserController.class) public class UserControllerUnitTest extends BaseControllerUnitTest { @Autowired private ObjectMapper objectMapper; @Autowired private MockMvc mvc; /** * 所有实现的接口都要 Mock */ @MockBean private UserService userService; @MockBean private UserRoleService userRoleService; @MockBean private UserPostService userPostService; @MockBean private UserDepartmentService userDepartmentService; private List<User> userList; private IPage<User> userPageList; /** * Prepare test data. */ @BeforeEach public void setUp() { userList = new ArrayList<>(); userList.add(new User().setId(1L).setEmail("<EMAIL>").setUsername("zhangsan").setName("张三")); userList.add(new User().setId(2L).setEmail("<EMAIL>").setUsername("lisi").setName("李四")); userList.add(new User().setId(3L).setEmail("<EMAIL>").setUsername("wangwu").setName("王五")); userPageList = new Page<>(); userPageList.setRecords(userList); } @Test @WithMockUser public void givenUserName_whenFindUser_thenUserJson() throws Exception { String username = "zhangsan"; List<Role> roleList = new ArrayList<>(); roleList.add(new Role().setId(1L).setName("admin")); roleList.add(new Role().setId(2L).setName("common")); User user = userList.get(0); when(userService.findByUsername(username)).thenReturn(user); UserInfoVO userInfoVO = new UserInfoVO(); userInfoVO.setUser(user); userInfoVO.setRoles(roleList.stream().map(Role::getName).collect(Collectors.toList())); when(userService.getUserInfo(user.getId())).thenReturn(userInfoVO); mvc.perform(get("/user").param("username", username)) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.code").value(ResultEnum.SUCCESS.getCode())) .andExpect(jsonPath("$.data.user.email").value("<EMAIL>")) .andExpect(jsonPath("$.data.roles", hasSize(2))); verify(userService).findByUsername(anyString()); } // @Test // @WithMockUser // public void givenName_whenFindUser_thenUserListJson() throws Exception { // String name = "张三"; // // //对数据集进行条件过滤 // doAnswer(invocation -> { // Object arg0 = invocation.getArgument(0); // // userList = userList.stream() // .filter(p -> p.getName().equals(arg0)).collect(Collectors.toList()); // // return userList; // }).when(userService).findByName(name); // // mvc.perform(get("/user").param("name", name)) // .andDo(print()) // .andExpect(status().isOk()) // .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) // .andExpect(jsonPath("$.code").value(ResultEnum.SUCCESS.getCode())) // .andExpect(jsonPath("$.data", hasSize(1))) // .andExpect(jsonPath("$.data[0].username", equalTo("zhangsan"))); // // verify(userService).findByName(name); // } @Test @WithMockUser public void givenId_whenFindUser_thenUserJson() throws Exception { Long id = 1L; when(userService.findById(id)).thenReturn(userList.get(0)); mvc.perform(get("/user/{id}", id)) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.code").value(ResultEnum.SUCCESS.getCode())) .andExpect(jsonPath("$.data.email").value("<EMAIL>")); verify(userService).findById(anyLong()); } @Test @WithMockUser public void givenNothing_whenFindAllUser_thenUserListJson() throws Exception { when(userService.findUsers(any(User.class), any(Page.class), any())).thenReturn(userPageList); mvc.perform(get("/users")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.code").value(ResultEnum.SUCCESS.getCode())) .andExpect(content().string(stringContainsInOrder("zhangsan", "lisi", "wangwu"))) .andExpect(jsonPath("$.data.records", hasSize(3))) .andExpect(jsonPath("$.data.records[0].username", equalTo("zhangsan"))); verify(userService).findUsers(any(User.class), any(Page.class), any()); } @Test @WithMockUser public void givenJson_whenSaveUser_thenSuccessJson() throws Exception { User requestBody = new User().setEmail("<EMAIL>").setUsername("zhaoliu").setPassword("<PASSWORD>").setName("xxx"); when(userService.saveOrUpdateUser(any(User.class))) .thenReturn(userList.get(0)); mvc.perform(post("/user").with(csrf()) .content(objectMapper.writeValueAsString(requestBody)) .contentType(MediaType.APPLICATION_JSON)) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.code").value(ResultEnum.SUCCESS.getCode())) .andExpect(jsonPath("$.data.id", equalTo(1))); verify(userService).saveOrUpdateUser(any(User.class)); } @Test @WithMockUser public void givenJson_whenUpdateUser_thenSuccessJson() throws Exception { User requestBody = new User().setId(2L).setEmail("<EMAIL>").setUsername("zhaoliu").setPassword("<PASSWORD>").setName("xxx"); when(userService.saveOrUpdateUser(any(User.class))) .thenReturn(userList.get(1)); mvc.perform(post("/user").with(csrf()) .content(objectMapper.writeValueAsString(requestBody)) .contentType(MediaType.APPLICATION_JSON)) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.code").value(ResultEnum.SUCCESS.getCode())) .andExpect(jsonPath("$.data.id", equalTo(2))) .andExpect(jsonPath("$.data.username", equalTo("lisi"))); verify(userService).saveOrUpdateUser(any(User.class)); } /** * 删除成功的情况 * * @throws Exception */ @Test @WithMockUser public void givenId_whenDeleteUser_thenSuccess() throws Exception { when(userService.deleteByIds(anyList())).thenReturn(true); mvc.perform(delete("/user").param("ids", "1,2").with(csrf())) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.code").value(ResultEnum.SUCCESS.getCode())) .andExpect(jsonPath("$.data").value(true)); verify(userService).deleteByIds(anyList()); } /** * 更新用户状态 * * @throws Exception */ @Test @WithMockUser public void givenUser_whenUpdateStatus_thenSuccess() throws Exception { User requestBody = new User().setId(2L).setStatus("close"); when(userService.updateStatus(any(User.class))).thenReturn(true); mvc.perform(post("/user/status").with(csrf()) .content(objectMapper.writeValueAsString(requestBody)) .contentType(MediaType.APPLICATION_JSON)) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.code").value(ResultEnum.SUCCESS.getCode())) .andExpect(jsonPath("$.data").value(true)); verify(userService).updateStatus(any(User.class)); } /** * Mock Static Method * @throws Exception */ @Test @WithMockUser public void givenNothing_whenGetUserInfo_thenSuccess() throws Exception { PecadoUser pecadoUser = new PecadoUser(1L, Collections.singletonList(2), Collections.singletonList(1L), "zhangsan", "N_A", true, true, true, true, AuthorityUtils.commaSeparatedStringToAuthorityList("admin")); try (MockedStatic<SecurityUtils> mockStatic = mockStatic(SecurityUtils.class)) { mockStatic.when(SecurityUtils::getUser).thenReturn(pecadoUser); SecurityUtils.getUser(); mockStatic.verify(times(1), SecurityUtils::getUser); UserInfoVO userInfoVO = new UserInfoVO(); userInfoVO.setUser(userList.get(0)); doReturn(userInfoVO).when(userService).getUserInfo(1L); mvc.perform(get("/user/me")) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.code").value(ResultEnum.SUCCESS.getCode())) .andExpect(jsonPath("$.data.user.username").value("zhangsan")); } } @Test @WithMockUser public void giveUserRoles_whenAdd_thenSuccess() throws Exception { List<UserRole> userRoleList = new ArrayList<>(); userRoleList.add(new UserRole().setUserId(1L).setRoleId(1L)); userRoleList.add(new UserRole().setUserId(1L).setRoleId(2L)); doReturn(true).when(userRoleService).updateUserRoles(any(List.class)); mvc.perform(post("/user/role").with(csrf()) .content(objectMapper.writeValueAsString(userRoleList)) .contentType(MediaType.APPLICATION_JSON)) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.code").value(ResultEnum.SUCCESS.getCode())) .andExpect(jsonPath("$.data").value(true)); } }
#!/usr/bin/env bash nohup hpts -s 127.0.0.1:${SOCKS5_PORT:=1080} -p ${HTTP_PROXY_PORT:=3080} >/dev/null 2>&1 & nohup nginx > /dev/null 2>&1 & mkdir -p ~/.ssh adduser ssh-tunnel echo "root:${ROOT_PASSWORD:=123456}" | chpasswd ssh-keygen -q -t rsa -N '' -f /etc/ssh/ssh_host_rsa_key <<<y >/dev/null 2>&1 sed -i 's/#Port 22/Port '"${SSH_PORT:=1022}"'/' /etc/ssh/sshd_config sed -i 's/#PermitTunnel no/PermitTunnel yes/' /etc/ssh/sshd_config sed -i 's/#PasswordAuthentication yes/PasswordAuthentication yes/' /etc/ssh/sshd_config sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config sed -i 's/AllowTcpForwarding no/AllowTcpForwarding yes/' /etc/ssh/sshd_config sed -i 's/GatewayPorts no/GatewayPorts yes/' /etc/ssh/sshd_config nohup /usr/sbin/sshd -D > /dev/null 2>&1 & function spawn { if [[ -z ${PIDS+x} ]]; then PIDS=(); fi "$@" & PIDS+=($!) } function join { if [[ ! -z ${PIDS+x} ]]; then for pid in "${PIDS[@]}"; do wait "${pid}" done fi } function on_kill { if [[ ! -z ${PIDS+x} ]]; then for pid in "${PIDS[@]}"; do kill "${pid}" 2> /dev/null done fi kill "${ENTRYPOINT_PID}" 2> /dev/null } export ENTRYPOINT_PID="${BASHPID}" trap "on_kill" EXIT trap "on_kill" SIGINT spawn socks5 if [[ -n "${SOCKS5_UP}" ]]; then spawn "${SOCKS5_UP}" "$@" elif [[ $# -gt 0 ]]; then "$@" fi if [[ $# -eq 0 || "${DAEMON_MODE}" == true ]]; then join fi
<gh_stars>1-10 const express = require('express'); const router = express.Router(); const authenticate = require('../middlewares/authenticate'); const { isEmpty } = require('lodash'); const { retrieveAncestors } = require('../utils'); const { isUserCapable } = require('../utils/bloggingappcms'); const { compiledModels } = require('../models'); const assert = require('assert'); router.post('/add', authenticate, (req, res, next) => { const { currentUser } = req; const { _id, title, slug, content, status, parent } = req.body; const errors = {}; if ( status === 'publish' && !isUserCapable('publish', 'page', currentUser) ) return res.sendStatus(403); if ( !title ) errors.title = 'Please enter some title.'; if ( !slug || /[^\w-]+/g.test(slug) || /[A-Z]/.test(slug) ) errors.slug = 'Must only contain dash, underscore and lowercase alphanumeric characters.'; if ( !isEmpty(errors) ) return res.status(401).json({ errors }); if ( _id === undefined ) { // New post compiledModels[currentUser.collectionPrefix].Page .findOne( { slug }, (err, duplicate) => { assert.ifError(err); if (!duplicate) { const newPost = { author: currentUser._id, title, slug, content, status }; retrieveAncestors( compiledModels[currentUser.collectionPrefix].Page, parent, newPost, res, modified => { compiledModels[currentUser.collectionPrefix].Page .create( modified, (err, doc) => { assert.ifError(err); res.status(201).json(doc); } ); }); } else { errors.slug = 'Duplicate slug'; res.status(409).json({ errors }); } } ); } else { // Modify post compiledModels[currentUser.collectionPrefix].Page .findOne( { _id }, (err, editing) => { assert.ifError(err); if (editing) { if ( isUserCapable( 'edit', 'page', currentUser, editing ) ) { compiledModels[currentUser.collectionPrefix].Page .findOne( { slug }, (err, duplicate) => { if ( ( editing.slug === slug && duplicate ) || ( editing.slug !== slug && !duplicate ) ) { editing.title = title; editing.slug = slug; editing.content = content; editing.status = status; editing.modified = Date.now(); retrieveAncestors( compiledModels[currentUser.collectionPrefix].Page, parent, editing, res, modified => { modified.save(err => { assert.ifError(err); return res.json(modified); }); }); } else { errors.slug = 'Duplicate slug'; res.status(409).json({ errors }); } } ); } else { res.sendStatus(403); } } else { res.sendStatus(404); } } ); } }); router.get('/', authenticate, (req, res, next) => { const { currentUser, query: { slug, collectionPrefix, status, _id } } = req; if ( slug || _id ) { const params = {}; if (slug) params.slug = slug; else if (_id) params._id = _id; compiledModels[collectionPrefix].Page .findOne(params) .populate({ path: 'author ancestors parent', select: '-hash -email' }) .exec((err, doc) => { assert.ifError(err); if ( doc && ( doc.status === 'publish' || isUserCapable( 'edit', 'page', currentUser, doc ) ) ) return res.json(doc); res.sendStatus(404); }); } else { const q = {}; if ( status ) q.status = status; compiledModels[collectionPrefix].Page .find( q ) .populate({ path: 'author ancestors parent', select: '-hash -email' }) .sort('-date') .exec((err, docs) => { assert.ifError(err); res.json(docs); }); } }); router.post('/edit', authenticate, (req, res, next) => { const { currentUser } = req; const { _id } = req.body; compiledModels[currentUser.collectionPrefix].Page .findOne( { _id }, (err, doc) => { assert.ifError(err); if (doc) { if ( isUserCapable( 'edit', 'page', currentUser, doc ) ) { res.json(doc); } else { res.sendStatus(403); } } else { res.sendStatus(404); } } ); }); router.delete('/:_id?', authenticate, (req, res, next) => { const { currentUser, params: { _id }, query: { ids } } = req; if (_id) { // single delete compiledModels[currentUser.collectionPrefix].Page .findOne( { _id }, (err, doc) => { assert.ifError(err); if (doc) { if ( isUserCapable( 'delete', 'page', currentUser, doc ) ) { if (doc.status !== 'trash') { doc.status = 'trash'; doc.save(err => assert.ifError(err)); } else { doc.status = 'delete'; doc.remove(); } doc.populate({ path: 'author ancestors parent', select: '-hash -email' }, (err, doc) => { assert.ifError(err); res.send(doc); }); } else { res.sendStatus(403); } } else { res.sendStatus(404); } } ); } else { // multiple delete compiledModels[currentUser.collectionPrefix].Page .find( { _id: { $in: ids } }, (err, docs) => { assert.ifError(err); let nextStatus; docs.forEach(doc => { if ( isUserCapable( 'delete', 'page', currentUser, doc ) ) { if (doc.status !== 'trash') { doc.status = 'trash'; doc.save(err => assert.ifError(err)); } else { doc.status = 'delete'; doc.remove(); } if (!nextStatus) nextStatus = doc.status; } }); res.send({ n: docs.length, status: nextStatus }); } ); } }); module.exports = router;
# # The BSD 3-Clause License. http://www.opensource.org/licenses/BSD-3-Clause # # This file is part of MinGW-W64(mingw-builds: https://github.com/niXman/mingw-builds) project. # Copyright (c) 2011-2020 by niXman (i dotty nixman doggy gmail dotty com) # Copyright (c) 2012-2015 by Alexpux (alexpux doggy gmail dotty com) # All rights reserved. # # Project: MinGW-W64 ( http://sourceforge.net/projects/mingw-w64/ ) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # - Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the distribution. # - Neither the name of the 'MinGW-W64' nor the names of its contributors may # be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ************************************************************************** PKG_VERSION=4.8.5 PKG_NAME=gcc-${PKG_VERSION} PKG_DIR_NAME=gcc-${PKG_VERSION} PKG_TYPE=.tar.bz2 PKG_URLS=( "https://ftp.gnu.org/gnu/gcc/gcc-${PKG_VERSION}/gcc-${PKG_VERSION}${PKG_TYPE}" ) PKG_PRIORITY=main # PKG_PATCHES=( gcc/gcc-4.7-stdthreads.patch gcc/gcc-4.8-iconv.patch gcc/gcc-4.8-libstdc++export.patch gcc/gcc-4.8.3-libatomic-cygwin.patch gcc/gcc-4.8.2-build-more-gnattools.mingw.patch gcc/gcc-4.8.2-dont-escape-arguments-that-dont-need-it-in-pex-win32.c.patch gcc/gcc-4.8.2-fix-for-windows-not-minding-non-existant-parent-dirs.patch gcc/gcc-4.8.2-windows-lrealpath-no-force-lowercase-nor-backslash.patch gcc/lto-plugin-use-static-libgcc.patch gcc/gcc-4.6-fix_mismatch_in_gnu_inline_attributes.patch ) # PKG_CONFIGURE_FLAGS=( --host=$HOST --build=$BUILD --target=$TARGET # --prefix=$MINGWPREFIX --with-sysroot=$PREFIX --with-gxx-include-dir=$MINGWPREFIX/$TARGET/include/c++ # $LINK_TYPE_GCC # $( [[ $USE_MULTILIB == yes ]] \ && echo "--enable-targets=all --enable-multilib" \ || echo "--disable-multilib" \ ) --enable-languages=$ENABLE_LANGUAGES,lto --enable-libstdcxx-time=yes --enable-threads=$THREADS_MODEL --enable-libgomp --enable-lto --enable-graphite --enable-checking=release --enable-fully-dynamic-string --enable-version-specific-runtime-libs $( [[ $EXCEPTIONS_MODEL == dwarf ]] \ && echo "--disable-sjlj-exceptions --with-dwarf2" \ ) $( [[ $EXCEPTIONS_MODEL == sjlj ]] \ && echo "--enable-sjlj-exceptions" \ ) # --disable-libstdcxx-pch --disable-libstdcxx-debug $( [[ $BOOTSTRAPING == yes ]] \ && echo "--enable-bootstrap" \ || echo "--disable-bootstrap" \ ) --disable-rpath --disable-win32-registry --disable-nls --disable-werror --disable-symvers # --with-gnu-as --with-gnu-ld # $PROCESSOR_OPTIMIZATION $PROCESSOR_TUNE # --with-libiconv --with-system-zlib --with-{gmp,mpfr,mpc,isl,cloog}=$PREREQ_DIR/$HOST-$LINK_TYPE_SUFFIX --enable-cloog-backend=isl --with-pkgversion="\"$BUILD_ARCHITECTURE-$THREADS_MODEL-$EXCEPTIONS_MODEL${REV_STRING}, $MINGW_W64_PKG_STRING\"" --with-bugurl=$BUG_URL # CFLAGS="\"$COMMON_CFLAGS\"" CXXFLAGS="\"$COMMON_CXXFLAGS\"" CPPFLAGS="\"$COMMON_CPPFLAGS\"" LDFLAGS="\"$COMMON_LDFLAGS $( [[ $BUILD_ARCHITECTURE == i686 ]] && echo -Wl,--large-address-aware )\"" MAKEINFO=missing LD_FOR_TARGET=$PREFIX/bin/ld.exe ) # PKG_MAKE_FLAGS=( -j$JOBS all ) # PKG_INSTALL_FLAGS=( -j1 DESTDIR=$BASE_BUILD_DIR $( [[ $STRIP_ON_INSTALL == yes ]] && echo install-strip || echo install ) ) # **************************************************************************
#!/bin/bash mkdir -p ~/.config/nvim ln -sf ~/dotfiles/vimrc ~/.config/nvim/init.vim git clone https://github.com/k-takata/minpac.git ~/.config/nvim/pack/minpac/opt/minpac ln -sf ~/dotfiles/spin/zshrc ~/.zshrc
#!/bin/bash echo -e "Executing create_docs" if [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_BRANCH" == "master" ]; then echo -e "Generating Jazzy output \n" jazzy --clean --author "Jonathan Landon" --author_url https://ovenbits.com --github_url https://github.com/jlandon/Alexandria --xcodebuild-arguments "-scheme,Alexandria" --module Alexandria --root-url https://jlandon.github.io/Alexandria --theme apple pushd docs echo -e "Creating gh-pages\n" git init git config user.email "travis@travis-ci.org" git config user.name "travis-ci" git add -A git commit -m "Publishing documentation from Travis build of $TRAVIS_COMMIT" git push --force --quiet "https://${GH_TOKEN}@github.com/jlandon/Alexandria.git" master:gh-pages > /dev/null 2>&1 echo -e "Published documentation to gh-pages.\n" popd fi
/** * a player entity */ game.PlayerEntity = me.Entity.extend({ /** * constructor */ init : function (x, y, settings) { settings.image="tiny_dungeon_monsters"; settings.width = 16; settings.height = 16; settings.framewidth = 16; settings.frameheight = 16; settings.type = 'player'; // call the constructor this._super(me.Entity, 'init', [x, y, settings]); // set the default horizontal & vertical speed (accel vector) this.body.setVelocity(1, 1); this.body.gravity = 0; this.body.removeShapeAt(0); this.body.addShape(new me.Rect(0, 0, 14, 16)); this.body.collisionType = me.collision.types.PLAYER_OBJECT; // set the display to follow our position on both axis me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH); // ensure the player is updated even when outside of the viewport this.alwaysUpdate = true; this.stance = "idle"; // player props this.hp = 100; this.damage = 10; // define a basic walking animation (using all frames) this.renderable.addAnimation("walk.right", [0,16]); this.renderable.addAnimation("walk.left", [1,17]); this.renderable.addAnimation("attack.right", [2,18],100); this.renderable.addAnimation("attack.left", [3,19],100); this.renderable.addAnimation("stand.right", [0]); this.renderable.addAnimation("stand.left", [1]); // set the standing animation as default this.renderable.setCurrentAnimation("walk.right"); this.facing = "left"; }, /* * update the player pos */ // left right update : function (dt) { if (me.input.isKeyPressed('left')) { this.facing = "left"; // update the entity velocity this.body.vel.x -= this.body.accel.x * me.timer.tick; } else if (me.input.isKeyPressed('right')) { this.facing = "right"; // update the entity velocity this.body.vel.x += this.body.accel.x * me.timer.tick; } else { this.body.vel.x = 0; } // up down if (me.input.isKeyPressed('up')) { // update the entity velocity this.body.vel.y -= this.body.accel.y * me.timer.tick; } else if (me.input.isKeyPressed('down')) { // update the entity velocity this.body.vel.y += this.body.accel.y * me.timer.tick; } else { this.body.vel.y = 0; } // interact and action if(me.input.isKeyPressed('action')) { this.stance = "attack"; } // Animate considering the facing if( this.facing == "left") { this.renderable.anchorPoint.set(0.75, 0.5); } else { this.renderable.anchorPoint.set(0.25, 0.5); } if (this.stance == "idle") { if (this.body.vel.y != 0 || this.body.vel.x != 0) { if (!this.renderable.isCurrentAnimation("walk." + this.facing)) { this.renderable.setCurrentAnimation("walk." + this.facing); } } else { if (!this.renderable.isCurrentAnimation("stand." + this.facing)) { this.renderable.setCurrentAnimation("stand." + this.facing); } } } else { if (!this.renderable.isCurrentAnimation("attack." + this.facing)) { this.renderable.setCurrentAnimation("attack." + this.facing, (function (){ this.stance = "idle"; return false; // do not reset to first frame }).bind(this)); } } // apply physics to the body (this moves the entity) this.body.update(dt); // handle collisions against other shapes me.collision.check(this); // return true if we moved or if the renderable was updated return (this._super(me.Entity, 'update', [dt]) || this.body.vel.x !== 0 || this.body.vel.y !== 0); }, /** * colision handler * (called when colliding with other objects) */ onCollision : function (response, other) { // Make all other objects solid return true; }, doDamage: function(attacker){ this.hp = this.hp - attacker.damage; if (attacker.facing == 'left') { this.pos.x -= 3 }; if (attacker.facing == 'right') { this.pos.x += 3 }; } });
<gh_stars>1-10 package com.github.passerr.idea.plugins.spring.web; import com.github.passerr.idea.plugins.BaseTableModel; import com.github.passerr.idea.plugins.IdeaDialog; import com.github.passerr.idea.plugins.IdeaJbTable; import com.github.passerr.idea.plugins.IdeaPanelWithButtons; import com.github.passerr.idea.plugins.spring.web.highlight.FileTemplateTokenType; import com.github.passerr.idea.plugins.spring.web.highlight.TemplateHighlighter; import com.github.passerr.idea.plugins.spring.web.po.ApiDocObjectSerialPo; import com.github.passerr.idea.plugins.spring.web.po.ApiDocSettingPo; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.EditorSettings; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.ex.util.LayerDescriptor; import com.intellij.openapi.editor.ex.util.LayeredLexerEditorHighlighter; import com.intellij.openapi.editor.highlighter.EditorHighlighter; import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.fileTypes.PlainSyntaxHighlighter; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.util.Pair; import com.intellij.testFramework.LightVirtualFile; import com.intellij.ui.BrowserHyperlinkListener; import com.intellij.ui.PanelWithButtons; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.SeparatorFactory; import com.intellij.ui.ToolbarDecorator; import com.intellij.ui.table.JBTable; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ItemEvent; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Function; /** * api文档配置视图 * @author xiehai * @date 2021/06/30 19:39 * @Copyright(c) tellyes tech. inc. co.,ltd */ public abstract class ApiDocConfigViews { /** * 根据已有配置生成视图 * @param setting {@link ApiDocSettingPo} * @return {@link List} */ public static List<Pair<String, JPanel>> panels(ApiDocSettingPo setting) { return Arrays.asList( Pair.pair("Api模版", apiTemplatePanel(setting)), Pair.pair("查询参数", queryParamPanel(setting)), Pair.pair("报文体", bodyParamPanel(setting)), Pair.pair("序列化", serialPanel(setting)) ); } /** * api模版视图 * @param setting {@link ApiDocSettingPo} * @return {@link JPanel} */ private static JPanel apiTemplatePanel(ApiDocSettingPo setting) { JPanel panel = new JPanel(new GridBagLayout()); // 编辑模块 EditorFactory editorFactory = EditorFactory.getInstance(); Document document = editorFactory.createDocument(setting.getTemplate()); document.addDocumentListener(new DocumentListener() { @Override public void documentChanged(DocumentEvent e) { setting.setStringTemplate(e.getDocument().getText()); } }); Editor editor = editorFactory.createEditor(document); EditorSettings editorSettings = editor.getSettings(); editorSettings.setVirtualSpace(false); editorSettings.setLineMarkerAreaShown(false); editorSettings.setIndentGuidesShown(true); editorSettings.setLineNumbersShown(true); editorSettings.setFoldingOutlineShown(false); editorSettings.setAdditionalColumnsCount(3); editorSettings.setAdditionalLinesCount(3); editorSettings.setCaretRowShown(false); ((EditorEx) editor).setHighlighter(createVelocityHighlight()); JPanel templatePanel = new JPanel(new GridBagLayout()); templatePanel.add( SeparatorFactory.createSeparator("模版:", null), new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, JBUI.insetsBottom(2), 0, 0 ) ); templatePanel.add( editor.getComponent(), new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, JBUI.insetsTop(2), 0, 0 ) ); panel.add( templatePanel, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTH, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0, 0 ) ); // 描述模块 JEditorPane desc = new JEditorPane(UIUtil.HTML_MIME, ""); desc.setEditable(false); desc.setEditorKit(UIUtil.getHTMLEditorKit()); desc.addHyperlinkListener(new BrowserHyperlinkListener()); desc.setText(ResourceUtil.readAsString("/api-doc-desc.html")); desc.setCaretPosition(0); JPanel descriptionPanel = new JPanel(new GridBagLayout()); descriptionPanel.add( SeparatorFactory.createSeparator("描述:", null), new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, JBUI.insetsBottom(2), 0, 0 ) ); descriptionPanel.add( ScrollPaneFactory.createScrollPane(desc), new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, JBUI.insetsTop(2), 0, 0 ) ); panel.add( descriptionPanel, new GridBagConstraints(0, 1, 1, 1, 1, 1, GridBagConstraints.NORTH, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0, 0 ) ); return panel; } /** * 查询参数视图 * @param setting {@link ApiDocSettingPo} * @return {@link JPanel} */ private static JPanel queryParamPanel(ApiDocSettingPo setting) { JPanel panel = new JPanel(new GridBagLayout()); PanelWithButtons top = new IdeaPanelWithButtons("忽略类型:") { @Override protected JComponent createMainComponent() { BaseTableModel<String> model = new BaseTableModel<>( Collections.singletonList("类型"), setting.getQueryParamIgnoreTypes()); JBTable table = new IdeaJbTable(model); // 弹出层构建器 BiFunction<StringBuilder, Runnable, JComponent> function = (s, r) -> { JPanel p = new JPanel(new GridBagLayout()); GridBagConstraints gb = new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, JBUI.insets(0, 0, 5, 10), 0, 0 ); JLabel typeLabel = new JLabel("类型"); p.add(typeLabel, gb); JTextField textField = new JTextField(s.toString()); textField.getDocument() .addDocumentListener( new com.intellij.ui.DocumentAdapter() { @Override protected void textChanged(javax.swing.event.DocumentEvent e) { s.setLength(0); s.append(textField.getText()); r.run(); } }); Dimension oldPreferredSize = textField.getPreferredSize(); textField.setPreferredSize(new Dimension(300, oldPreferredSize.height)); gb.gridx = 1; gb.gridwidth = GridBagConstraints.REMAINDER; gb.weightx = 1; p.add(textField, gb); r.run(); return p; }; return ToolbarDecorator.createDecorator(table) .setAddAction(it -> new IdeaDialog<StringBuilder>(panel) .title("新增忽略类型") .value(new StringBuilder()) .okAction(t -> setting.getQueryParamIgnoreTypes().add(t.toString())) .changePredicate(t -> t.length() > 0) .componentFunction(t -> function.apply(t.getValue(), t::onChange)) .doInit() .showAndGet() ) .setAddActionName("新增") .setEditAction(it -> new IdeaDialog<StringBuilder>(panel) .title("编辑忽略类型") .value(new StringBuilder(model.getRow(table.getSelectedRow()))) .okAction(t -> setting.getQueryParamIgnoreTypes().set(table.getSelectedRow(), t.toString()) ) .changePredicate(t -> t.length() > 0) .componentFunction(t -> function.apply(t.getValue(), t::onChange)) .doInit() .showAndGet() ) .setEditActionName("编辑") .setRemoveAction(it -> model.removeRow(table.getSelectedRow())) .setRemoveActionName("删除") .disableUpDownActions() .createPanel(); } }; PanelWithButtons bottom = new IdeaPanelWithButtons("忽略注解:") { @Override protected JComponent createMainComponent() { BaseTableModel<String> model = new BaseTableModel<>( Collections.singletonList("注解"), setting.getQueryParamIgnoreAnnotations()); JBTable table = new IdeaJbTable(model); // 弹出层构建器 BiFunction<StringBuilder, Runnable, JComponent> function = (s, r) -> { JPanel p = new JPanel(new GridBagLayout()); GridBagConstraints gb = new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, JBUI.insets(0, 0, 5, 10), 0, 0 ); JLabel typeLabel = new JLabel("注解"); p.add(typeLabel, gb); JTextField textField = new JTextField(s.toString()); textField.getDocument() .addDocumentListener( new com.intellij.ui.DocumentAdapter() { @Override protected void textChanged(javax.swing.event.DocumentEvent e) { s.setLength(0); s.append(textField.getText()); r.run(); } }); Dimension oldPreferredSize = textField.getPreferredSize(); textField.setPreferredSize(new Dimension(300, oldPreferredSize.height)); gb.gridx = 1; gb.gridwidth = GridBagConstraints.REMAINDER; gb.weightx = 1; p.add(textField, gb); r.run(); return p; }; return ToolbarDecorator.createDecorator(table) .setAddAction(it -> new IdeaDialog<StringBuilder>(panel) .title("新增忽略注解") .value(new StringBuilder()) .okAction(t -> setting.getQueryParamIgnoreAnnotations().add(t.toString())) .changePredicate(t -> t.length() > 0) .componentFunction(t -> function.apply(t.getValue(), t::onChange)) .doInit() .showAndGet() ) .setAddActionName("新增") .setEditAction(it -> new IdeaDialog<StringBuilder>(panel) .title("编辑忽略注解") .value(new StringBuilder(model.getRow(table.getSelectedRow()))) .okAction(t -> setting.getQueryParamIgnoreAnnotations().set(table.getSelectedRow(), t.toString()) ) .changePredicate(t -> t.length() > 0) .componentFunction(t -> function.apply(t.getValue(), t::onChange)) .doInit() .showAndGet() ) .setEditActionName("编辑") .setRemoveAction(it -> model.removeRow(table.getSelectedRow())) .setRemoveActionName("删除") .disableUpDownActions() .createPanel(); } }; panel.add( top, new GridBagConstraints( 0, 0, 1, 1, 1, 1, GridBagConstraints.NORTH, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0, 0 ) ); panel.add( bottom, new GridBagConstraints( 0, 1, 1, 1, 1, 1, GridBagConstraints.NORTH, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0, 0 ) ); return panel; } /** * 报文参数忽略类型设置 * @param setting {@link ApiDocSettingPo} * @return {@link JPanel} */ private static JPanel bodyParamPanel(ApiDocSettingPo setting) { JPanel panel = new JPanel(new GridBagLayout()); PanelWithButtons bottom = new IdeaPanelWithButtons("忽略注解(字段上的注解):") { @Override protected JComponent createMainComponent() { BaseTableModel<String> model = new BaseTableModel<>( Collections.singletonList("注解"), setting.getBodyIgnoreAnnotations()); JBTable table = new IdeaJbTable(model); // 弹出层构建器 BiFunction<StringBuilder, Runnable, JComponent> function = (s, r) -> { JPanel p = new JPanel(new GridBagLayout()); GridBagConstraints gb = new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, JBUI.insets(0, 0, 5, 10), 0, 0 ); JLabel typeLabel = new JLabel("注解"); p.add(typeLabel, gb); JTextField textField = new JTextField(s.toString()); textField.getDocument() .addDocumentListener( new com.intellij.ui.DocumentAdapter() { @Override protected void textChanged(javax.swing.event.DocumentEvent e) { s.setLength(0); s.append(textField.getText()); r.run(); } }); Dimension oldPreferredSize = textField.getPreferredSize(); textField.setPreferredSize(new Dimension(300, oldPreferredSize.height)); gb.gridx = 1; gb.gridwidth = GridBagConstraints.REMAINDER; gb.weightx = 1; p.add(textField, gb); r.run(); return p; }; return ToolbarDecorator.createDecorator(table) .setAddAction(it -> new IdeaDialog<StringBuilder>(panel) .title("新增忽略注解") .value(new StringBuilder()) .okAction(t -> setting.getBodyIgnoreAnnotations().add(t.toString())) .changePredicate(t -> t.length() > 0) .componentFunction(t -> function.apply(t.getValue(), t::onChange)) .doInit() .showAndGet() ) .setAddActionName("新增") .setEditAction(it -> new IdeaDialog<StringBuilder>(panel) .title("编辑忽略注解") .value(new StringBuilder(model.getRow(table.getSelectedRow()))) .okAction(t -> setting.getBodyIgnoreAnnotations().set(table.getSelectedRow(), t.toString()) ) .changePredicate(t -> t.length() > 0) .componentFunction(t -> function.apply(t.getValue(), t::onChange)) .doInit() .showAndGet() ) .setEditActionName("编辑") .setRemoveAction(it -> model.removeRow(table.getSelectedRow())) .setRemoveActionName("删除") .disableUpDownActions() .createPanel(); } }; panel.add( bottom, new GridBagConstraints( 0, 0, 1, 1, 1, 1, GridBagConstraints.NORTH, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0, 0 ) ); return panel; } /** * 序列化配置 * @param setting {@link ApiDocSettingPo} * @return {@link JPanel} */ private static JPanel serialPanel(ApiDocSettingPo setting) { JPanel panel = new JPanel(new GridBagLayout()); PanelWithButtons top = new IdeaPanelWithButtons("") { @Override protected JComponent createMainComponent() { BaseTableModel<ApiDocObjectSerialPo> model = new BaseTableModel<ApiDocObjectSerialPo>( Arrays.asList("类型", "别名", "序列化默认值"), setting.getObjects()) { @Override protected List<Function<ApiDocObjectSerialPo, Object>> columns() { return Arrays.asList( ApiDocObjectSerialPo::getType, ApiDocObjectSerialPo::getAlias, ApiDocObjectSerialPo::getValue ); } }; JBTable table = new IdeaJbTable(model); // 弹出层构建器 Function<IdeaDialog<ApiDocObjectSerialPo>, JComponent> function = dialog -> { ApiDocObjectSerialPo s = dialog.getValue(); JPanel p = new JPanel(new GridBagLayout()); GridBagConstraints gb = new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, JBUI.insets(0, 0, 5, 10), 0, 0 ); JLabel typeLabel = new JLabel("类型"); p.add(typeLabel, gb); JTextField textField = new JTextField(); Optional.ofNullable(s.getType()).ifPresent(textField::setText); textField.getDocument() .addDocumentListener( new com.intellij.ui.DocumentAdapter() { @Override protected void textChanged(javax.swing.event.DocumentEvent e) { s.setType(textField.getText()); dialog.onChange(); } }); Dimension oldPreferredSize = textField.getPreferredSize(); textField.setPreferredSize(new Dimension(300, oldPreferredSize.height)); gb.gridx = 1; gb.gridwidth = GridBagConstraints.REMAINDER; gb.weightx = 1; p.add(textField, gb); JLabel aliasLabel = new JLabel("别名"); gb.gridy++; gb.gridx = 0; gb.gridwidth = 1; gb.weightx = 0; p.add(aliasLabel, gb); JComboBox<String> aliasCombobox = new ComboBox<>( Arrays.stream(AliasType.values()) .map(AliasType::getType) .toArray(String[]::new) ); aliasCombobox.addItemListener(e -> { if (e.getStateChange() == ItemEvent.SELECTED) { s.setAlias((String) e.getItem()); } dialog.onChange(); }); if (Objects.isNull(s.getAlias())) { // 新增的时候默认选中第一个 s.setAlias(aliasCombobox.getItemAt(0)); } aliasCombobox.setSelectedItem(s.getAlias()); gb.gridx = 1; gb.fill = GridBagConstraints.NONE; gb.gridwidth = GridBagConstraints.REMAINDER; gb.weightx = 0; p.add(aliasCombobox, gb); JLabel valueLabel = new JLabel("序列化默认值"); gb.gridy++; gb.gridx = 0; gb.gridwidth = 1; gb.weightx = 0; p.add(valueLabel, gb); JTextField valueField = new JTextField(); Optional.ofNullable(s.getValue()).ifPresent(valueField::setText); valueField.getDocument() .addDocumentListener( new com.intellij.ui.DocumentAdapter() { @Override protected void textChanged(javax.swing.event.DocumentEvent e) { s.setValue(valueField.getText()); dialog.onChange(); } }); valueField.setPreferredSize(new Dimension(300, oldPreferredSize.height)); gb.gridx = 1; gb.gridwidth = GridBagConstraints.REMAINDER; gb.weightx = 1; p.add(valueField, gb); dialog.onChange(); return p; }; return ToolbarDecorator.createDecorator(table) .setAddAction(it -> new IdeaDialog<ApiDocObjectSerialPo>(panel) .title("新增序列化") .value(new ApiDocObjectSerialPo()) .okAction(setting.getObjects()::add) .changePredicate(ApiDocObjectSerialPo::isOk) .componentFunction(function) .doInit() .showAndGet() ) .setAddActionName("新增") .setEditAction(it -> new IdeaDialog<ApiDocObjectSerialPo>(panel) .title("编辑序列化") .value(model.getRow(table.getSelectedRow())) .okAction(t -> setting.getObjects().set(table.getSelectedRow(), t)) .changePredicate(ApiDocObjectSerialPo::isOk) .componentFunction(function) .doInit() .showAndGet() ) .setEditActionName("编辑") .setRemoveAction(it -> model.removeRow(table.getSelectedRow())) .setRemoveActionName("删除") .disableUpDownActions() .createPanel(); } }; panel.add( top, new GridBagConstraints( 0, 0, 1, 1, 1, 1, GridBagConstraints.NORTH, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0, 0 ) ); return panel; } private static EditorHighlighter createVelocityHighlight() { FileType ft = FileTypeManager.getInstance().getFileTypeByExtension("ft"); if (ft != FileTypes.UNKNOWN) { return EditorHighlighterFactory.getInstance() .createEditorHighlighter( ProjectManagerEx.getInstance().getDefaultProject(), new LightVirtualFile("aaa.psr.spring.web.ft") ); } SyntaxHighlighter ohl = Optional.ofNullable(SyntaxHighlighterFactory.getSyntaxHighlighter(FileTypes.PLAIN_TEXT, null, null)) .orElseGet(PlainSyntaxHighlighter::new); final EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); LayeredLexerEditorHighlighter highlighter = new LayeredLexerEditorHighlighter(new TemplateHighlighter(), scheme); highlighter.registerLayer(FileTemplateTokenType.TEXT, new LayerDescriptor(ohl, "")); return highlighter; } }
#!/bin/bash -l #SBATCH -A ***REMOVED*** #SBATCH -p core #SBATCH -n 6 #SBATCH -t 04:00:00 #SBATCH -J Kraken2_LFerr #SBATCH --mail-type=ALL #SBATCH --mail-user robymetallo@users.noreply.github.com # Load modules module load bioinfo-tools module load Kraken2 # Input/Output Dir IN_DIR="$HOME/prj/analysis/RNA/01_processed_reads/00_trimmed" OUT_DIR="$HOME/prj/data/RNA_data/kraken2/trimmed_reads" # Copy DB locally MY_DB_DIR="$SNIC_TMP/Kraken2" MY_DB=$MY_DB_DIR/${KRAKEN2_DEFAULT_DB##*/} mkdir -p "$MY_DB" cp -av "$KRAKEN2_DEFAULT_DB"/* "$MY_DB/" # MY_DB="$KRAKEN2_DEFAULT_DB" mkdir -p "$OUT_DIR" find $IN_DIR -wholename '*$IN_DIR*/*_OK_1.fastq.gz' | while read FILE; do BASE_NAME=`basename "$FILE" _OK_1.fastq.gz` BASE_DIR=`dirname "$FILE"` # Kraken2 2.0.7-beta-bc14b13 command time -v \ kraken2 --threads 6 \ --db "$MY_DB" \ --report "$OUT_DIR/$BASE_NAME.report" \ --output dev/null \ "$BASE_DIR/$BASE_NAME"_OK_*.fastq.gz "$BASE_DIR/$BASE_NAME""_singletons.fastq.gz" done;
<reponame>Keyrim/STM32_Test_Area<gh_stars>0 /* * Regu_orientation.h * * Created on: Dec 13, 2020 * Author: Théo */ #ifndef REGULATION_REGU_ORIENTATION_H_ #define REGULATION_REGU_ORIENTATION_H_ #include "../Estimators/orientation.h" #include "../../Drivers/Inc/Pid.h" #include "../config.h" #define REGU_ORIENTATION_FREQUENCY GYRO_FREQUENCY typedef enum regulation_mode_e{ REGULATION_MODE_OFF, REGULATION_MODE_MANUAL }regulation_mode_e; typedef struct regu_orientation_t{ orientation_t * orientation ; regulation_mode_e mode ; PID_t pid_angular_speed ; PID_t pid_angular_pos ; float consigne_angular_pos; float consigne_angular_speed; int16_t motor_consigne; float * output; //Output for the motor }regu_orientation_t; void REGULATION_ORIENTATION_Init(regu_orientation_t * regu_orientation_, orientation_t * orientation_, float * output); void REGULATION_ORIENTATION_Set_Regulation_Mode(regulation_mode_e regu_mode); void REGULATION_ORIENTATION_Process(void); #endif /* REGULATION_REGU_ORIENTATION_H_ */
export PRINT_MISSING_DOCKER="\e[1mCould not find docker.\e[3m\n\nMost systems can install Docker by running:\n\nwget -qO- https://get.docker.com/ | sh" # helper_function export PRINT_FAIL_MESSAGE="[failed]" export PRINT_DONE_MESSAGE="[Done.]" export PRINT_NOT_FOUND_MESSAGE="[not found]" export PRINT_NOT_RUNNING_MESSAGE="[not running]" export PRINT_STOPPED_MESSAGE="[stopped]" export PRINT_ALREADY_RUNNING="[already running]" export PRINT_ALREADY_EXISTS="[already exists]" export PRINT_INVALID_OPTION_MESSAGE="[invalid option]" export PRINT_INVALID_PATH_MESSAGE="[invalid PATH]" export PRINT_SOMETHING_WENT_WRONG="Something went wrong. Exiting." export PRINT_STATUS="Status" export PRINT_RESTORE="Restore" export PRINT_EXIT="Exit" export PRINT_EXITING="Exiting" export PRINT_DELETING="Deleting" export PRINT_REMOVE="Remove" export PRINT_KEEPING="Keeping" export PRINT_DID_NOT_CHANGE="[did not change]" export PRINT_ALL="All" export PRINT_INSTALLED="Installed" export PRINT_GREEN="Green" export PRINT_CONFIGURED="Configured" export PRINT_ORANGE="Orange" export PRINT_PROMPT_CONFIRM_SHURE="Are you sure?" export PRINT_PROMPT_CONFIRM_QUESTION="Continue?" export PRINT_PROMPT_CONFIRM_KEEP_VOLUMES="Keep volumes?" export PRINT_EXITING="Exiting..." export PRINT_PROMPT_CONFIRM_YES="[Yes]" export PRINT_PROMPT_CONFIRM_NO="[No]" export PRINT_PROMPT_CONFIRM_ERROR="[Invalid Input]" export PRINT_VALIDATE_FQDN_USE="is already in use" export PRINT_VALIDATE_FQDN_INVALID="is not a valid domain" export PRINT_SERVICE_MANAGE_MESSAGE="Please select the service you want to manage" # init.menu export PRINT_DESTROY_ALL="Destroy everything" export PRINT_RESET_DOCKERBUNKER="Reset dockerbunker to its initial state" export PRINT_CONATIENRS="Container(s)" export PRINT_VOLUMES="Volume(s)" export PRINT_NGINX_CONFIG_FILES="nginx configuration file(s)" export PRINT_ENVIRONMENT_FILES="environment file(s)" export PRINT_SSL_CERT="SSL Certificates" export PRINT_START_ALL_STOPPED_CONTAINERS="Start all stopped containers" export PRINT_STOP_ALL_RUNNING_CONTAINERS="Stop all running containers" export PRINT_START_NGINX_CONTAINER="Start nginx container" export PRINT_STOP_NGINX_CONTAINER="Stop nginx container" export PRINT_RESTART_NGINX_CONTAINER="Restart nginx container" export PRINT_RESTART_ALL_CONTAINERS="Restart all containers" export PRINT_DESTROY_EVERYTHING="Destroy everything" # menu_function_server export PRINT_RESTART_NGINX="Restarting nginx container" export PRINT_RESTART_NGINX_TEST_ERROR="\`nginx -t\` failed. Trying to add missing containers to dockerbunker-network." export PRINT_RESTART_NGINX_TEST_ERROR_AGAIN="\`nginx -t\` failed again. Please resolve issue and try again." export PRINT_START_NGINX="Starting nginx container" export PRINT_STOP_NGINX="Stopping nginx container" export PRINT_DEACTIVATE_NGINX_CONF="Deactivating nginx configuration" export PRINT_REMOVE_NGINX_CONF="Removing nginx configuration" export PRINT_REMOVE_NETWORKS="Removing networks" # menu_functions_certificate export PRINT_REMOVE_SSL_CERTIFICATE="Removing SSL Certificates" export PRINT_RENEW_LE_CERT="Renew Let's Encrypt certificate" export PRINT_GENERATE_SS_CERT="Generate self-signed certificate" export PRINT_OPTAIN_LS_CERT="Obtain Let's Encrypt certificate" # menu_function_service export PRINT_STARTING_CONTAINERS="Starting containers" export PRINT_RESTARTING_CONTAINERS="Restarting containers" export PRINT_STOPING_CONTAINERS="Stopping containers" export PRINT_REMOVE_CONTAINERS="Removing containers" export PRINT_REMOVE_VOLUMES="Removing volumes" export PRINT_REMOVE_ALL_IMAGES="Remove all images?" export PRINT_REMOVING_IMAGES="Removing images" export PRINT_REMOVING="Removing" export PRINT_DECOMPRESSING="Decompressing" export PRINT_REMVEHTML_DIRECTORY="Remove HTML directory" # menu_function export PRINT_CONTAINER_MISSING="container missing" export PRINT_RETURN_TO_PREVIOUSE_MENU="Return to previous menu" export PRINT_MENU_REINSTALL_SERVICE="Reinstall service" export PRINT_MENU_BACKUP_SERVICE="Backup Service" export PRINT_MENU_UPGRADE_IMAGE="Upgrade Image(s)" export PRINT_MENU_DESTROY_SERVICE="Destroy" export PRINT_MENU_START_CONTAINERS="Start container(s)" export PRINT_MENU_RESTART_CONTAINERS="Restart container(s)" export PRINT_MENU_STOP_CONTAINERS="Stop container(s)" export PRINT_MENU_RESTORE_SERVICE="Restore Service" export PRINT_MENU_RESTORE_MISSING_CONTAINER="Restore missing containers" export PRINT_MENU_RECONFIGURE_SERVICE="Reconfigure service" export PRINT_MENU_MANAGE_SITES="Manage Sites" export PRINT_MENU_CONFIGURE_SITES="Configure Site" export PRINT_MENU_CONFIGURE_SERVICE="Configure Service" export PRINT_MENU_SETUP_SERVICE="Setup service" export PRINT_MENU_REMOVE_SITE="Remove site" export PRINT_MENU_PRVIOUSE_MENU="Back to previous menu" export PRINT_CONFIGURE="Configure" export PRINT_RECONFIGURE="Reconfigure" export PRINT_SETUP="Setup" export PRINT_REINSTALL="Reinstall" export PRINT_RESTROING_CONTAINERS="Restoring containers" export PRINT_UPGRADE="Upgrade" export PRINT_RESTART="Restart" export PRINT_START="Start" export PRINT_DESTROY="Destroy" export PRINT_CONTAINERS_ARE_MISSING="The following containers are missing" export PRINT_FOLLWONING_WILL_REMOVED="The following will be removed:" export PRINT_THE_FOLLOWING_SERVICES_WILL_BE_REMOVED="The following Services will be removed:" export PRINT_ALL_VOLUMES_WILL_BE_REMOVED="All volumes will be removed. Continue?" export PRINT_NO_EXISTING_SITE_FOUND="No existing sites found" export PRINT_NO_ENVORINMENT_FILE_FOUND="No environment file found for: " export PRINT_PLEASE_CHOOSE_A_NUMBER="Please choose a number from 1 to" export PRINT_COMPESSING_VOLUMES="Compressing volumes" export PRINT_BACKING_UP_CONFIG_FILES="Backing up configuration files" export PRINT_BACKING_UP_CERT="Backing up SSL certificate" export PRINT_BACKING_UP_NGINX_CONF="Backing up nginx configuration" export PRINT_BACKING_UP_ENV_FILE="Backing up environemt file(s)" export PRINT_COULD_NOT_FIND_ENV_FILE="Could not find environment file(s) for" export PRINT_COOSE_A_BACKUP="Please choose a backup" export PRINT_COULD_NOT_FIND="Could not find" export PRINT_RESTORING_CONFIGURATION="Restoring configuration files" export PRINT_RESTORING_NGINX_CONF="Restoring nginx configuration" export PRINT_RESTORING_SSL_CERT="Restoring SSL certificate" export PRINT_RESTORING_ENV="Restoring environemt file(s)" export PRINT_CHECKING_SERVICE_STATUS="Checking service status" # setup_certificate_functions export PRINT_PROMPT_CONFIRM_USE_LETSENCRYPT="Use Letsencrypt instead of a self-signed certificate?" export PRINT_ENTER_LETSENCRYPT_EMAIL="Enter E-mail Adress for Let's Encrypt:" export PRINT_ENTER_LETSENCRYPT_EMAIL_GLOBAL="Use this address globally for every future service configured to obtain a Let's Encrypt certificate?" export PRINT_GENERATING_SSL_CERT="Generating self-signed certificate for" export PRINT_INCLUDE_OTHER_DOMAINS_IN_CERT="Include other domains in certificate besides" export PRINT_CERT_DOMAIN_INVALID="Please enter a valid domain!" export PRINT_CERT_DOMAIN_INPUT_MESSGE="Enter domains, separated by spaces" export PRINT_CONTAINER_NOT_RUNNING="container not running. Exiting" export PRINT_SYMLINK_LETSENCRYPT_CERT="Symlinking letsencrypt certificate" # setup_docker_functions export PRINT_PULLING="Pulling" export PRINT_PULLING_NEW_IMAGES="Pulling new images" export PRINT_COULD_NOT_FIND_IMAGE_DIGEST="Could not find digests of current images." export PRINT_TAKING_DOWN_SERVICE="Taking down:" export PRINT_BRINGIN_UP_SERVICE="Bringing up:" export PRINT_IMAGES_DID_NOT_CHANGE="Image(s) did not change." export PRINT_PROMPT_DELETE_OLD_IMAGES="Delete all old images?" export PRINT_CREATING_VOLUMES="Creating volumes" # setup_server_function export PRINT_PROMPT_CONFIRM_USE_DEFAULT_NGINX_CONF="Use default Service Nginx.Config File?" export PRINT_PROMPT_CONFIRM_SET_NEW_NGINX_SERVICE_PATH="Set new Service Config Path" export PRINT_MOVING_NGINX_CONFIG="Moving nginx configuration in place" export PRINT_NGINX_CONFIG_ISSUE="Nginx configuration file could not be found. Exiting." # menus # export PRINT_MENU_TASK_DESTROY_SERVICE="destroy_service" # certbot export PRINT_CERTBOT_RESTART_SERVER_SUCCESS="Successfully restarted nginx-dockerbunker" export PRINT_CERTBOT_RESTART_SERVER_ERROR="Restart of nginx-dockerbunker failed"
#!/bin/sh # PLANET-4782 # List existing deprecated keys echo "Usage of '_campaign_page_template' meta key..." wp db query 'SELECT wp.*, wp2.meta_key as theme_key, wp2.meta_value as theme_value FROM wp_postmeta wp LEFT JOIN wp_postmeta wp2 ON ( wp.post_id = wp2.post_id AND wp2.meta_key = "theme" ) WHERE wp.meta_key="_campaign_page_template";' # Convert deprecated keys to new keys if possible echo "Replacing key with 'theme'" wp db query 'UPDATE wp_postmeta SET meta_key = "theme" WHERE meta_key="_campaign_page_template" AND post_id NOT IN ( SELECT * FROM( SELECT post_id FROM wp_postmeta wpp WHERE meta_key="theme" ) AS e );' # Delete left-over duplicates echo "Deleting leftovers" wp db query 'DELETE FROM wp_postmeta WHERE meta_key="_campaign_page_template";' echo "Done."
<filename>src/main/java/com/letv/hive/udaf/GenericUDAFMinServerTime.java package com.letv.hive.udaf; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.parse.SemanticException; import org.apache.hadoop.hive.ql.udf.generic.AbstractGenericUDAFResolver; import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils.ObjectInspectorCopyOption; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils; /** * @author taox */ public class GenericUDAFMinServerTime extends AbstractGenericUDAFResolver { static final Log LOG = LogFactory.getLog(GenericUDAFMinServerTime.class.getName()); @Override public GenericUDAFEvaluator getEvaluator(TypeInfo[] parameters) throws SemanticException { if (parameters.length != 2) { throw new UDFArgumentTypeException(parameters.length - 2, "Exactly two argument is expected."); } ObjectInspector oi = TypeInfoUtils.getStandardJavaObjectInspectorFromTypeInfo(parameters[0]); if (!ObjectInspectorUtils.compareSupported(oi)) { throw new UDFArgumentTypeException(parameters.length - 1, "Cannot support comparison of map<> type or complex type containing map<>."); } return new GenericUDAFMinServerTimeEvaluator(); } public static class GenericUDAFMinServerTimeEvaluator extends GenericUDAFEvaluator { ObjectInspector inputOI; ObjectInspector inputOI2; ObjectInspector outputOI; ObjectInspector outputOI2; @Override public ObjectInspector init(Mode m, ObjectInspector[] parameters) throws HiveException{ assert (parameters.length == 2); super.init(m, parameters); inputOI = parameters[0]; inputOI2 = parameters[1]; // Copy to Java object because that saves object creation time. // Note that on average the number of copies is log(N) so that's not // very important. outputOI = ObjectInspectorUtils.getStandardObjectInspector(inputOI, ObjectInspectorCopyOption.JAVA); outputOI2 = ObjectInspectorUtils.getStandardObjectInspector(inputOI2, ObjectInspectorCopyOption.JAVA); return outputOI; } /** class for storing the current max value */ static class MinAgg implements AggregationBuffer { Object o; Object out; } @Override public AggregationBuffer getNewAggregationBuffer() throws HiveException { MinAgg result = new MinAgg(); return result; } @Override public void reset(AggregationBuffer agg) throws HiveException { MinAgg myagg = (MinAgg) agg; myagg.o = null; myagg.out = null; } @Override public void iterate(AggregationBuffer agg, Object[] parameters) throws HiveException { assert (parameters.length == 2); Object partial = parameters[0]; if(partial!=null){ MinAgg myagg = (MinAgg) agg; int r = ObjectInspectorUtils.compare(myagg.o, outputOI, partial, inputOI); if (myagg.o == null || r > 0) { myagg.o = ObjectInspectorUtils.copyToStandardObject(partial, inputOI, ObjectInspectorCopyOption.JAVA); myagg.out = ObjectInspectorUtils.copyToStandardObject(parameters[1], inputOI2, ObjectInspectorCopyOption.JAVA); } } } @Override public Object terminatePartial(AggregationBuffer agg) throws HiveException { return null; } @Override public void merge(AggregationBuffer agg, Object partial) throws HiveException { if (partial != null) { MinAgg myagg = (MinAgg) agg; int r = ObjectInspectorUtils.compare(myagg.o, outputOI, partial, inputOI); if (myagg.o == null || r > 0) { myagg.o = ObjectInspectorUtils.copyToStandardObject(partial, inputOI, ObjectInspectorCopyOption.JAVA); } } } @Override public Object terminate(AggregationBuffer agg) throws HiveException { return null; } } }
from __future__ import annotations import contextlib from typing import Iterator, Mapping, Sequence import numpy as np from pycid.core.cpd import Outcome @contextlib.contextmanager def temp_seed(seed: int) -> Iterator[None]: state = np.random.get_state() np.random.seed(seed) try: yield finally: np.random.set_state(state) class RandomCPD: """ Sample a random CPD, with outcomes in the given domain """ def __init__(self, domain: Sequence[Outcome] = None, smoothness: float = 1.0, seed: int = None) -> None: """ Parameters ---------- variable: Name of variable domain: List of possible outcomes, defaults to [0, 1] smoothness: How different the probabilities for different probabilities are. When small (e.g. 0.001), most probability mass falls on a single outcome, and when large (e.g. 1000), the distribution approaches a uniform distribution. seed: Set the random seed """ self.seed = seed or np.random.randint(0, 10000) self.smoothness = smoothness self.domain = domain or [0, 1] def __call__(self, **parent_values: Outcome) -> Mapping[Outcome, float]: with temp_seed(self.seed + hash(frozenset(parent_values.items())) % 2**31 - 1): prob_vec = np.random.dirichlet(np.ones(len(self.domain)) * self.smoothness, size=1).flat # type: ignore return {self.domain[i]: prob for i, prob in enumerate(prob_vec)} # type: ignore def __name__(self) -> str: return f"RandomCPD({self.domain})"
export default { name: 'zerothLiveSites' }
#!bin/bash #!bin/bash #Created: 20/11/2021 #Upgrade 20/11/2021 #by: C-F_Payloadgen #Successful update #MESSAGE: Never stop learning, if you are here is out of curiosity and try to learn shell or bash with the help of google search among others and so you will have more ease of course take time but you will learn even if editing so never say you can't code, Coding is fun clear while : do #menu banner clear Slowprint= echo -e "\e[1;33m(__________Coding family___________)\e[1;35m The family beyond, that makes anything happens in a second" echo -e "\e[1;33mV= 4.0 ultimate \e[1;38m (99) Spanish (98) English " echo "" echo -e "\e[1;31m[1]\e[1;32m HOST & SSL EXTRACTOR" echo -e "\e[1;31m[2]\e[1;32m HTTP/HTTPS STATUS RESPONSE" echo -e "\e[1;31m[3]\e[1;32m SAVE HOSTS EXTRACTED" echo -e "\e[1;31m[4]\e[1;32m GENERATE PAYLOADS" echo -e "\e[1;31m[5]\e[1;32m SEE OPEN PORTS FOR WEB AND HOST" echo -e "\e[1;31m[6]\e[1;32m SEE PROXY OF HOST & WEB" echo -e "\e[1;31m[7]\e[1;32m USER MANUAL HOST E." echo -e "\e[1;31m[8]\e[1;32m MESSAGE FROM THE CREATOR" echo -e "\e[1;31m[0]\e[1;32m EXIT C-F_Payloadgen" echo "" echo -e "\e[1;36m" echo -n "Select option tobe serve:" read opcion #lista de menu echo -e "\e[0m" case $opcion in 1)echo "" echo -n "HOST: "; read HOST; bash .scan.sh $HOST echo "" echo -e "\e[0m"; echo -e "\e[1;31mpress enter to continue with the script...!\e[0m"; read foo ;; 2)echo "" echo "Showing host status..."; echo "" bash .status.sh echo "" echo -e "\e[1;31mpress enter to continue with the script...\e[0m" read foo ;; 3)echo "" echo -e "\e[1;33mPaste the host to show the status\e[0m"; echo -e "\e[1;31mRemember CTRL + C to go out\e[0m"; echo -e "\e[1;36mHOST: \e[0m"; cat>lista-host.txt ;; 4)clear bash .payload read foo; ;; 5)echo "" echo -ne "\e[1;31m DOMAIN(IP/WEB): "; read MAIN echo -ne "\e[1;31m PORTS(53,80): "; read RTS sleep 2 echo -e "\e[1;32m"; nmap -p $RTS $MAIN read foo ;; 6)echo -ne "\e[1;31mSITE WEB/IP: "; read WEB echo "" echo -e "\e[1;32m" curl https://api.hackertarget.com/geoip/?q=$WEB read foo ;; 7)echo -e "\e[1;32mFollow all instructions for the proper use of the tool..."; sleep 2.5 cat Guide.txt read foo ;; 12.25)clear echo -e "\e[1;32mEntering the secret menu..."; sleep 2 bash ._ read foo ;; 8)echo "" echo -e "\e[1;33mCREDITS TO THE DEVELOPER\e[0m" echo "" echo -e "\e[1;31mCoding family: The place where coders are born" echo -e "\e[1;32m" echo "YOUTUBE : https://youtube.com/ " echo "TELEGRAM: https://t.me/ " echo "TELEGRAM: https://t.me/ " echo "FACEBOOK: https://m.facebook.com/groups/ " echo "FACEBOOK: https://m.facebook.com/ " echo "" echo -e "\e[1;31mCOMPLEMENTS OF THE CODING FAMILY\e[0m" echo "" echo -e "\e[1;36mNever stop learning, coding is is fun 😊... :)\e[0m" echo "" read foo; ;; 98)clear echo "translating to english language..."; sleep 3 bash C-F_Payloadgen.sh ;; 99)clear echo "Translating to spanish language..."; sleep 3 bash .C-F_Payloadgen.sh ;; #Fin del menu/in the end 0)clear exit 0;; #error *)clear echo "Invalid command..."; sleep 1.5 ;; esac done
#!/usr/bin/env bash # # for Azure Pipelines job where # vmImage: 'ubuntu-16.04' # or # vmImage: 'macOS-10.14' # # XXX: nearly identical to .circleci/build-install-run.sh # XXX: very similar to tools/build-install.sh set -e set -u set -o pipefail # initial $PWD is at project root directory readonly PACKAGE_NAME='goto_http_redirect_server' readonly PROGRAM_NAME='goto_http_redirect_server' readonly REALPATH='./tools/realpath.sh' # dump much information about the Azure Pipelines environment set -x whoami hostname pwd cat /etc/os-release || true env | sort ls -la . uname -a docker info || true python --version python -m pip --version python -m pip list -vvv # install and upgrade necessary packages python -m pip install --quiet --upgrade pip python -m pip install --quiet --upgrade setuptools python -m pip install --quiet --user twine python -m pip install --quiet --user mypy python -m pip --version python -m twine --version python -m mypy --version # condensed from tools/build-install.sh # update path with potential pip install locations usersite=$(python -B -c 'import site; print(site.USER_SITE);') userbase=$(python -B -c 'import site; print(site.USER_BASE);') userbasebin=${userbase}/bin # --user install location on Ubuntu export PATH="${PATH}:${usersite}:${userbase}:${userbasebin}" SERVER_TEST=$("${REALPATH}" "./tools/ci/server-test.sh") python -m mypy 'goto_http_redirect_server/goto_http_redirect_server.py' # build version=$(python -B -c 'from goto_http_redirect_server import goto_http_redirect_server as gh;print(gh.__version__)') python setup.py -v bdist_wheel cv_whl=$("${REALPATH}" "./dist/${PACKAGE_NAME}-${version}-py3-none-any.whl") python -m twine check "${cv_whl}" cd .. # move out of project directory so pip install behaves correctly # install python -m pip install --user --verbose "${cv_whl}" # run "${PROGRAM_NAME}" --version # server test chmod -v +x "${SERVER_TEST}" "${SERVER_TEST}" # uninstall python -m pip uninstall --yes --verbose "${PACKAGE_NAME}"
package my.company.web.elements; import org.openqa.selenium.support.FindBy; import ru.yandex.qatools.htmlelements.element.Button; import ru.yandex.qatools.htmlelements.element.HtmlElement; import ru.yandex.qatools.htmlelements.element.TextInput; /** * @author <NAME> eroshenkoam * 5/6/13, 5:13 PM */ public class SearchArrow extends HtmlElement { @FindBy(xpath = ".//input[@class='b-form-input__input']") public TextInput requestInput; @FindBy(xpath = ".//input[@class='b-form-button__input']") public Button searchButton; public void searchFor(String request) { requestInput.clear(); requestInput.sendKeys(request); searchButton.click(); } }
import React from 'react'; import { BrowserRouter } from 'react-router-dom'; import MainRouter from './MainRouter'; import { isAuthenticated } from './Api'; import Navigation from './Components/Navbar'; import Footer from './Components/Footer'; // const App = () => ( // <BrowserRouter> // <div> // <Navigation /> // {isAuthenticated() ? ( // <div style={{ marginLeft: '165px', marginTop: '70px' }}> // <MainRouter /> // </div> // ) : ( // <div style={{ marginTop: '70px' }}> // <MainRouter /> // </div> // )} // <Footer /> // </div> // </BrowserRouter> // ); // export default App; class App extends React.Component { render() { return ( <BrowserRouter> <div> <Navigation /> {isAuthenticated() ? ( <div style={{ marginLeft: '0px', marginTop: '70px' }}> <MainRouter /> </div> ) : ( <div style={{ marginTop: '70px' }}> <MainRouter /> </div> )} <Footer /> </div> </BrowserRouter> ); } } export default App;
$(document).ready( async () => { await autoFillTowers(); await checkGame(); autoFillCoeff(); const $this = this; $(document).on('click', '.tile_btn__1b-Eh', function () { if (game === null) return; const slot = $(this).attr('data-id'); $.ajax({ type: 'POST', url: '/tower/next', data: { slot: slot }, success: data => { if (data.success) { game.setGame(data.game, slot); } else { $.notify({ type: 'error', message: data.message }); } } }); }); $(document).on('click', '.claim', function () { if (game === null) return; $.ajax({ type: 'POST', url: '/tower/claim', success: data => { if (data.success) { game.setGame(data.game, 0); } else { $.notify({ type: 'error', message: data.message }); } } }); }); $(document).on('click', '.btn-change', function () { $('.dropdown-item[data-id="balance"]').click(); }); }); let coeff = { 1: [1.25, 1.562, 1.953, 2.441, 3.051, 3.814, 4.768, 5.96, 7.45, 9.313], 2: [1.666, 2.777, 4.629, 7.716, 12.86, 21.433, 35.722, 59.537, 99.229, 165.381], 3: [2.5, 6.25, 15.625, 39.062, 97.656, 244.14, 610.351, 1525.878, 3814.697, 9536.743], 4: [5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625] }; let game = null; let config = { bombs: 1, bet: 0.00, activeGame: false }; $(document).on('click', '.selectBomb', function(e) { if ($(this).hasClass('isActive') || config.activeGame) return; const bomb = $(this).attr('data-bomb'); const lastBtn = $(`.btn[data-bomb=${config.bombs}]`); config.bombs = parseInt(bomb); autoFillCoeff(); autoFillTowers(); $(this).addClass('isActive'); lastBtn.removeClass('isActive'); }); $(document).on('click', '.btn-play', async () => { if (config.activeGame) return; game = null; $('.game-tooltip').remove(); config.bet = parseFloat($('#sum').val()); $.ajax({ type: 'POST', url: '/tower/newGame', data: { bombs: config.bombs, bet: config.bet, balance: localStorage.getItem('balance') || 'balance' }, success: async (data) => { if (data.success) { await autoFillTowers(); config.activeGame = true; game = new Tower(data.game); } else { $.notify({ type: 'error', message: data.message }) } }, error: async () => { $.notify({ type: 'error', message: 'Произошла ошибка на сервере' }) } }); }); const autoFillTowers = async () => { let html = ''; $('.tower_payoutItemActive__1xYqA').removeClass('tower_payoutItemActive__1xYqA'); for (let i = 0; i < 10; i++) { html += '<div class="tile_row__2H-Sa">'; for (let l = 0; l < 5; l++) { html += '<div class="tile_item__eJPTt">'+ '<button type="button" class="tile_btn__1b-Eh" data-id="'+l+'">'+ '<span class="tile_appear__3kqK4"></span>'+ '<span class="tile_bombFrame__2GtMm"></span>'+ '<span class="tile_main__2babg"></span>'+ '</button>'+ '</div>'; } html += '</div>' } $('#TowerComponent').html(html); }; const autoFillCoeff = () => { const coef = coeff[config.bombs]; for (let i = 0; i < 10; i++) { const e = (coef[i] - coef[i] * 5 / 100).toFixed(2); $(`#coeff_${i + 1}`).html(`x${e}`); } }; const checkGame = () => { $.ajax({ type: 'POST', url: '/tower/init', success: (data) => { if (data.game !== null) { $(`.btn[data-bomb=${data.game.state.count}]`).click(); config = { bombs: data.game.state.count, bet: data.game.bet, activeGame: true }; $('#sum').val(config.bet); game = new Tower(data.game); } } }); }; class Tower { constructor(data) { this.game = data; this.lastSlot = -1; $('.btn-play').addClass('claim'); this.currentRevealed(); this.currentStep(); } currentStep() { const step = this.game.state.revealed.length; const block = $($(`.tile_row__2H-Sa`)[step]); if (step === 0) { $('.claim').prop('disabled', true); } else { $('.claim').prop('disabled', false); } $('.claim').html(`Забрать ${this.game.state.claim}`); block.addClass('tile_isActive__2d3mO'); } currentRevealed() { for (let i = 0; i < this.game.state.revealed.length; i++) { const bombs = this.game.state.field[i]; const block = $($(`.tile_row__2H-Sa`)[i]); block.removeClass('tile_isActive__2d3mO'); let html = ''; for (let l = 0; l < 5; l++) { if (bombs.find(x => x === l) !== undefined) { if (bombs.find(x => x === parseInt(this.game.state.revealed[i])) !== undefined) { html += '<div class="tile_item__eJPTt tile_hasMine__1W4Zt"><button type="button" class="tile_btn__1b-Eh tile_isMine__3hfGe tile_isClickable__QnuY3"><span class="tile_appear__3kqK4"></span><span class="tile_bombFrame__2GtMm tile_isAnimate__gWjgT"></span><span class="tile_main__2babg tile_isRevealed__1vm7Q tile_isMine__3hfGe"></span></button></div>'; } else { html += '<div class="tile_item__eJPTt tile_hasMine__1W4Zt"><button type="button" class="tile_btn__1b-Eh tile_isMine__3hfGe"><span class="tile_appear__3kqK4"></span><span class="tile_bombFrame__2GtMm"></span><span class="tile_main__2babg tile_isRevealed__1vm7Q tile_isMine__3hfGe"></span></button></div>'; } } else { if (parseInt(this.game.state.revealed[i]) === l) { html += '<div class="tile_item__eJPTt"><button type="button" class="tile_btn__1b-Eh tile_isRevealed__1vm7Q tile_isClickable__QnuY3"><span class="tile_appear__3kqK4 tile_isAnimate__gWjgT"></span><span class="tile_bombFrame__2GtMm"></span><span class="tile_main__2babg tile_isAnimate__gWjgT tile_isRevealed__1vm7Q"></span></button></div>'; } else { html += '<div class="tile_item__eJPTt"><button type="button" class="tile_btn__1b-Eh tile_isRevealed__1vm7Q"><span class="tile_appear__3kqK4"></span><span class="tile_bombFrame__2GtMm"></span><span class="tile_main__2babg tile_isAnimate__gWjgT tile_isRevealed__1vm7Q"></span></button></div>'; } } } block.html(html); } $(`#coeff_${this.game.state.revealed.length}`).addClass('tower_payoutItemActive__1xYqA'); } lastRevealed() { let i = 0; if (this.game.state.revealed.length > 0) { i = this.game.state.revealed.length - 1; } if (this.game.state.revealed.length > 1) $(`#coeff_${this.game.state.revealed.length - 1}`).removeClass('tower_payoutItemActive__1xYqA'); const bombs = this.game.state.field[i]; const block = $($(`.tile_row__2H-Sa`)[i]); block.removeClass('tile_isActive__2d3mO'); let html = ''; for (let l = 0; l < 5; l++) { if (bombs.find(x => x === l) !== undefined) { html += '<div class="tile_item__eJPTt tile_hasMine__1W4Zt"><button type="button" class="tile_btn__1b-Eh tile_isMine__3hfGe"><span class="tile_appear__3kqK4"></span><span class="tile_bombFrame__2GtMm"></span><span class="tile_main__2babg tile_isRevealed__1vm7Q tile_isMine__3hfGe"></span></button></div>'; } else { if (parseInt(this.game.state.revealed[i]) === l) { html += '<div class="tile_item__eJPTt"><button type="button" class="tile_btn__1b-Eh tile_isRevealed__1vm7Q tile_isClickable__QnuY3"><span class="tile_appear__3kqK4 tile_isAnimate__gWjgT"></span><span class="tile_bombFrame__2GtMm"></span><span class="tile_main__2babg tile_isAnimate__gWjgT tile_isRevealed__1vm7Q"></span></button></div>'; } else { html += '<div class="tile_item__eJPTt"><button type="button" class="tile_btn__1b-Eh tile_isRevealed__1vm7Q"><span class="tile_appear__3kqK4"></span><span class="tile_bombFrame__2GtMm"></span><span class="tile_main__2babg tile_isAnimate__gWjgT tile_isRevealed__1vm7Q"></span></button></div>'; } } } block.html(html); $(`#coeff_${this.game.state.revealed.length}`).addClass('tower_payoutItemActive__1xYqA'); } nextRevealed(boom) { for (let i = this.game.state.revealed.length; i < 10; i++) { const bombs = this.game.state.field[i]; const block = $($(`.tile_row__2H-Sa`)[i]); block.removeClass('tile_isActive__2d3mO'); let lastSlot = this.lastSlot; let html = ''; for (let l = 0; l < 5; l++) { if (bombs.find(x => x === parseInt(l)) !== undefined) { if (bombs.find(x => x === parseInt(lastSlot)) !== undefined && l === parseInt(lastSlot) && !boom) { boom = true; html += '<div class="tile_item__eJPTt tile_hasMine__1W4Zt"><button type="button" class="tile_btn__1b-Eh tile_isMine__3hfGe tile_isClickable__QnuY3"><span class="tile_appear__3kqK4"></span><span class="tile_bombFrame__2GtMm tile_isAnimate__gWjgT"></span><span class="tile_main__2babg tile_isRevealed__1vm7Q tile_isMine__3hfGe"></span></button></div>'; } else { html += '<div class="tile_item__eJPTt tile_hasMine__1W4Zt"><button type="button" class="tile_btn__1b-Eh tile_isMine__3hfGe"><span class="tile_appear__3kqK4"></span><span class="tile_bombFrame__2GtMm"></span><span class="tile_main__2babg tile_isRevealed__1vm7Q tile_isMine__3hfGe"></span></button></div>'; } } else { html += '<div class="tile_item__eJPTt"><button type="button" class="tile_btn__1b-Eh tile_isRevealed__1vm7Q"><span class="tile_appear__3kqK4"></span><span class="tile_bombFrame__2GtMm"></span><span class="tile_main__2babg tile_isRevealed__1vm7Q"></span></button></div>'; } } block.html(html); } } boom() { this.nextRevealed(false); $('.btn-play').removeClass('claim'); $('.btn-play').prop('disabled', false); $('.btn-play').html('Играть'); config.activeGame = false; } end() { if (this.game.state.revealed.length < 10) { this.nextRevealed(true); } else { this.lastRevealed(); } $('.btn-play').removeClass('claim'); $('.btn-play').prop('disabled', false); $('.btn-play').html('Играть'); config.activeGame = false; if (this.game.currency === 'bonus') { $('.tower_component__3oM-1').append(`<div class="game-tooltip isTransparent isActive demo won">`+ `<div class="wrap">`+ `<div class="payout">x${this.game.coeff}</div>`+ `<div class="badge">`+ `<div class="text">Демо-режим</div>`+ `</div>`+ `<div class="status">Вы выиграли <span class="profit">${(this.game.bet * this.game.coeff).toFixed(2)}</span>`+ `</div>`+ `<button type="button" class="btn btn-change">Играть на деньги</button>`+ `</div>`+ `</div>`); } else { $('.tower_component__3oM-1').append(`<div class="game-tooltip isTransparent isActive won">`+ `<div class="wrap">`+ `<div class="payout">x${this.game.coeff}</div>`+ `<div class="badge">`+ `<div class="text">Победа</div>`+ `</div>`+ `<div class="status">Вы выиграли <span class="profit">${(this.game.bet * this.game.coeff).toFixed(2)}</span>`+ `</div>`+ `</div>`+ `</div>`); } } setGame(data, slot) { this.lastSlot = slot; this.game = data; if (this.game.active) { this.currentStep(); this.lastRevealed(); } else { if (this.game.status === 2) { this.boom(); } else { this.end(); } } } }
package dsp import ( "math" "strconv" ) var ( BlackmanFreqCoeff = []float64{0.16 / 4, -1.0 / 4, (1 - 0.16) / 2, -1.0 / 4, 0.16 / 4} HammingFreqCoeff = []float64{(0.53836 - 1) / 2, 0.53836, (0.53836 - 1) / 2} HanningFreqCoeff = []float64{-0.25, 0.5, -0.25} BlackmanFreqCoeff32 = []float32{0.16 / 4, -1.0 / 4, (1 - 0.16) / 2, -1.0 / 4, 0.16 / 4} HammingFreqCoeff32 = []float32{(0.53836 - 1) / 2, 0.53836, (0.53836 - 1) / 2} HanningFreqCoeff32 = []float32{-0.25, 0.5, -0.25} ) func TriangleWindow(output []float64) { for n := range output { output[n] = 1 - math.Abs((float64(n)-float64(len(output)-1)/2.0)/(float64(len(output)+1)/2.0)) } } func TriangleWindowF32(output []float32) { for n := range output { output[n] = float32(1 - math.Abs((float64(n)-float64(len(output)-1)/2.0)/(float64(len(output)+1)/2.0))) } } func HammingWindow(output []float64) { window(output, []float64{0.53836, 1 - 0.53836}) } func HammingWindowF32(output []float32) { windowF32(output, []float64{0.53836, 1 - 0.53836}) } func HanningWindow(output []float64) { for n := range output { output[n] = 0.5 * (1 - math.Cos(2*math.Pi*float64(n)/float64(len(output)-1))) } } func HanningWindowF32(output []float32) { for n := range output { output[n] = float32(0.5 * (1 - math.Cos(2*math.Pi*float64(n)/float64(len(output)-1)))) } } func BlackmanWindow(output []float64) { a := 0.16 window(output, []float64{(1.0 - a) / 2.0, 1.0 / 2.0, a / 2.0}) } func BlackmanWindowF32(output []float32) { a := 0.16 windowF32(output, []float64{(1.0 - a) / 2.0, 1.0 / 2.0, a / 2.0}) } func NuttallWindow(output []float64) { window(output, []float64{0.355768, 0.487396, 0.144232, 0.012604}) } func NuttallWindowF32(output []float32) { windowF32(output, []float64{0.355768, 0.487396, 0.144232, 0.012604}) } func window(output []float64, a []float64) { if len(a) < 1 || len(a) > 4 { panic("invalid window length " + strconv.Itoa(len(a))) } nn := float64(len(output) - 1) for n := range output { fn := float64(n) v := a[0] if len(a) > 1 { v -= a[1] * math.Cos(2*math.Pi*fn/nn) } if len(a) > 2 { v += a[2] * math.Cos(4*math.Pi*fn/nn) } if len(a) > 3 { v -= a[3] * math.Cos(6*math.Pi*fn/nn) } output[n] = v } } func windowF32(output []float32, a []float64) { if len(a) < 1 || len(a) > 4 { panic("invalid window length " + strconv.Itoa(len(a))) } nn := float64(len(output) - 1) for n := range output { fn := float64(n) v := a[0] if len(a) > 1 { v -= a[1] * math.Cos(2*math.Pi*fn/nn) } if len(a) > 2 { v += a[2] * math.Cos(4*math.Pi*fn/nn) } if len(a) > 3 { v -= a[3] * math.Cos(6*math.Pi*fn/nn) } output[n] = float32(v) } }
const locators = { contactLink: "a#contact-link", submitButton: "button#submit-button", phone: "input.form__control[name='phone']", }; const init = (I) => { const timeout = 30; I.amOnPage("/"); I.waitForElement(locators.contactLink, timeout); I.waitForVisible(locators.contactLink, timeout); I.click(locators.contactLink); I.wait(1); I.waitForVisible(locators.phone, timeout); I.fillField(locators.phone, "1234567890"); // Enter a valid phone number I.waitForVisible(locators.submitButton, timeout); I.click(locators.submitButton); I.waitForText("Form submitted successfully", timeout); // Assertion for successful form submission };
#!/bin/bash script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" report_error() { RED=$(tput setaf 1) NO_COLOR=$(tput sgr0) cat <<EOF ${RED}error:${NO_COLOR} input is invalid build_image Build an Occlum Docker image for a specific OS USAGE: build_image.sh <OCCLUM_LABEL> <OS_NAME> <OCCLUM_LABEL>: An arbitrary string chosen by the user to describe the version of Occlum preinstalled in the Docker image, e.g., "latest", "0.12.0", "prerelease", and etc. <OS_NAME>: The name of the OS distribution that the Docker image is based on. Currently, <OS_NAME> must be one of the following values: ubuntu18.04 Use Ubuntu 18.04 as the base image centos7.5 Use CentOS 7.5 as the base image centos8.1 Use CentOS 8.1 as the base image The resulting Docker image will have "occlum/occlum:<OCCLUM_LABEL>-<OS_NAME>" as its label. EOF exit 1 } set -e if [[ ( "$#" < 2 ) ]] ; then report_error fi occlum_label=$1 os_name=$2 function check_item_in_list() { item=$1 list=$2 [[ $list =~ (^|[[:space:]])$item($|[[:space:]]) ]] } check_item_in_list "$os_name" "ubuntu18.04 centos7.5 centos8.1" || report_error cd "$script_dir/.." docker build -f "$script_dir/Dockerfile.$os_name" -t "occlum/occlum:$occlum_label-$os_name" .
SELECT title, price, sales FROM books ORDER BY sales DESC LIMIT 10;
conda env create -f build_env.yaml -p ./venv
<reponame>ningg/spring-boot-starter-learn package top.ningg.spring.service; /** * 为字符串,增加前缀和后缀. */ public interface IWrapService { /** * 为字符串增加前缀和后缀. * * @param word 输入的字符串. * @return 增加了前缀和后缀的字符串. */ String wrap(String word); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ed.biodare2.backend.repo.isa_dom.dataimport; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonFormat; /** * * @author tzielins */ @JsonFormat(shape = JsonFormat.Shape.STRING) public enum TimeType { NONE, TIME_IN_HOURS, TIME_IN_MINUTES, TIME_IN_SECONDS, IMG_NUMBER; /* @JsonCreator public static TimeType forValue(String name) { return TimeType.valueOf(name); } */ }
<reponame>crmag1/Java-Project package com.persado.assignment.project.service; import com.persado.assignment.project.dto.UserDTO; import com.persado.assignment.project.mapper.UserMapper; import com.persado.assignment.project.repository.LoanRepository; import com.persado.assignment.project.repository.UserRepository; import com.persado.assignment.project.model.Loan; import com.persado.assignment.project.model.User; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @Service public class UserServiceImpl implements UserService { private UserRepository userRepository; private LoanRepository loanRepository; private UserMapper userMapper; @Autowired public UserServiceImpl( UserRepository userRepository, LoanRepository loanRepository, UserMapper userMapper) { this.userRepository = userRepository; this.loanRepository = loanRepository; this.userMapper = userMapper; } @Override public List<UserDTO> findAll() { return userMapper.usersToUserDtos(userRepository.findAll()); } @Override public void save(UserDTO userDTO) { User user = userMapper.userDtoToUser(userDTO); userRepository.save(user); } @Override public String delete(Long id) { StringBuilder errorMessage = new StringBuilder(); // Get the Loans for the User with the given id. List<Loan> loans = loanRepository.findByUserIdAndReturnDateIsNull(id); // If the User has books on loan, create a String with the name of the books. for(int i = 0; i < loans.size(); i++) { if(StringUtils.isEmpty(errorMessage.toString())) { errorMessage.append(loans.get(i).getBook().getName()); } else{ errorMessage.append(", " + loans.get(i).getBook().getName()); } } // If the User does not have any books on loan, perform the delete action. if(loans.size() == 0) { userRepository.deleteById(id); } return errorMessage.toString(); } }
var app = angular.module('donor', ['ui.router', 'ngAnimate', 'uiGmapgoogle-maps', 'angular-loading-bar', 'ngMaterial', 'ngMdIcons']); app.config(function ($mdThemingProvider) { var customPrimary = { '50': '#fbb4af', '100': '#f99d97', '200': '#f8877f', '300': '#f77066', '400': '#f55a4e', '500': '#F44336', '600': '#f32c1e', '700': '#ea1c0d', '800': '#d2190b', '900': '#ba160a', 'A100': '#fccbc7', 'A200': '#fde1df', 'A400': '#fff8f7', 'A700': '#a21309' }; $mdThemingProvider .definePalette('customPrimary', customPrimary); var customAccent = { '50': '#6d5200', '100': '#866500', '200': '#a07800', '300': '#b98b00', '400': '#d39e00', '500': '#ecb100', '600': '#ffc720', '700': '#ffce3a', '800': '#ffd453', '900': '#ffda6d', 'A100': '#ffc720', 'A200': '#FFC107', 'A400': '#ecb100', 'A700': '#ffe186' }; $mdThemingProvider .definePalette('customAccent', customAccent); var customWarn = { '50': '#ffb8a1', '100': '#ffa588', '200': '#ff916e', '300': '#ff7e55', '400': '#ff6a3b', '500': '#FF5722', '600': '#ff4408', '700': '#ee3900', '800': '#d43300', '900': '#bb2d00', 'A100': '#ffcbbb', 'A200': '#ffdfd4', 'A400': '#fff2ee', 'A700': '#a12700' }; $mdThemingProvider .definePalette('customWarn', customWarn); $mdThemingProvider.theme('default') .primaryPalette('customPrimary') .accentPalette('customAccent') .warnPalette('customWarn') }); app.config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.when('/dashboard', '/dashboard/principal'); $urlRouterProvider.otherwise('/dashboard'); $stateProvider .state('dashboard', { url: '/dashboard', templateUrl: 'views/dashboard.html', controller:"PrincipalCtrl" }).state('principal', { url: '/principal', parent: 'dashboard', templateUrl: 'views/principal.html', controller:"PrincipalCtrl" }) }); app.controller('AppCtrl', function ($rootScope, $scope, $timeout, $mdSidenav, $log, $state) { //$scope.language = localStorage.getItem('language'); });
#!/bin/bash # If desired, you can call it with a number, e.g. "runall 013" to # skip examples up to but not including 013-selectize. trap '' SIGINT shiny () { echo $i R --quiet --slave -e "shiny::runApp(\"$1\", port=5151, launch.browser=TRUE)" } for i in $( ls -d */ ); do if [ "$i" \> "$1" ]; then shiny $i fi done
#!/bin/bash set -eufo pipefail for os in "$@"; do if [ ! -f "${os}.Vagrantfile" ]; then echo "${os}.Vagrantfile not found" exit 1 fi export VAGRANT_VAGRANTFILE=assets/vagrant/${os}.Vagrantfile if ! ( cd ../.. && vagrant up ); then exit 1 fi vagrant ssh -c "./test-chezmoi.sh" vagrant_ssh_exit_code=$? vagrant destroy -f || exit 1 if [ $vagrant_ssh_exit_code -ne 0 ]; then exit $vagrant_ssh_exit_code fi done
const hljs = require("highlight.js"); const syntaxHighlight = require("eleventy-plugin-highlightjs"); const pluginTOC = require("eleventy-plugin-nesting-toc"); const markdownShortcode = require("eleventy-plugin-markdown-shortcode"); const { default: Icons, Spots } = require("@stackoverflow/stacks-icons"); const { version } = require("../package.json"); module.exports = function(eleventyConfig) { eleventyConfig.setQuietMode(true); // Reduce the console output eleventyConfig.addLayoutAlias('home', 'layouts/home.html'); eleventyConfig.addLayoutAlias('page', 'layouts/page.html'); // Icon shortcode eleventyConfig.addLiquidShortcode("icon", function(name, classes, dimension) { var svg = Icons[name]; var defaultClasses = "svg-icon icon" + name; if (!svg) { return `<span class="fc-danger">Invalid icon: ${name}</span>`; } // If we have classes, add them if (classes != null) { svg = svg.replace(defaultClasses, defaultClasses + " " + classes); } // If we need to change the size, do that too if (dimension != null) { svg = svg.replace('width="18" height="18"', 'width="' + dimension + '" height="' + dimension + '"'); } return svg; }); // Spot shortcode eleventyConfig.addLiquidShortcode("spot", function(name, classes, dimension) { var svg = Spots[name]; if (!svg) { return `<span class="fc-danger">Invalid spot: ${name}</span>`; } var defaultClasses = "svg-spot spot" + name; // If we have classes, add them if (classes != null) { svg = svg.replace(defaultClasses, defaultClasses + " " + classes); } // If we need to change the size, do that too if (dimension != null) { svg = svg.replace('width="18" height="18"', 'width="' + dimension + '" height="' + dimension + '"'); } return svg; }); // Header shortcode eleventyConfig.addLiquidShortcode("header", function(tag, text) { var slug = text.replace(/\s+/g, '-').toLowerCase(); var linkIcon = Icons["Link"]; var output = ''; output += '<div class="d-flex jc-space-between ai-end pe-none stacks-header">'; output += '<' + tag + ' class="flex--item fl-grow1 stacks-' + tag + '" id="'+ slug +'">'; output += '<span class="pe-auto">' + text + '</span>'; output += '</' + tag + '>'; output += '<a class="d-flex flex__center mbn6 s-btn s-btn__muted pe-auto" href="#'+ slug +'">'; output += '<span class="v-visible-sr">Section titled ' + text + '</span>'; output += linkIcon; output += '</a>'; output += '</div>'; return output; }); // Tip shortcode eleventyConfig.addPairedShortcode("tip", function(content, type, classes, interiorClasses) { var spot = ""; if (type == "warning") { spot = Spots["Alert"]; type = "s-notice__warning"; } else { spot = Spots["AlertCircle"]; type = "s-notice__info"; } if (classes == null) { classes = "mb48"; } if (interiorClasses == null) { interiorClasses = "ai-start"; } var output = ''; output += '<div class="s-notice bar-md s-anchors s-anchors__inherit s-anchors__underlined ' + type + ' ' + classes + '">'; output += '<div class="d-flex gs16 ' + interiorClasses + '">'; output += '<div class="flex--item">'; output += spot; output += '</div>'; output += '<div class="flex--item fs-body2 lh-lg">'; output += content output += '</div>'; output += '</div>'; output += '</div>'; return output; }); // Version shortcode eleventyConfig.addLiquidShortcode("version", function() { return {version}.version; }); // highlightjs line-numbering support // add `linenums` or `linenums:startNumber` to the start of your code for detection class HljsInsertLineNums { constructor() { this.shouldInsert = false; this.startNumber = 1; } "before:highlight"(data) { var match = /^linenums(:\d+)?/.exec(data.code); if (!match) { return; } var startNumber = +(match[1] || "").slice(1) || 1; this.shouldInsert = true; this.startNumber = startNumber; data.code = data.code.replace(/^linenums(:\d+)?/, ""); } "after:highlight"(result) { if (!this.shouldInsert) { return; } var startNumber = this.startNumber; var content = result.value; var lines = content.split(/\r?\n/); var output = ""; for (var i = 0; i < lines.length; i++) { output += "<div>" + (i + startNumber) + "</div>"; } var newContent = '<code class="s-code-block--line-numbers">' + output + "</code>" + content; result.value = newContent; this.shouldInsert = false; } } // Add syntax highlighting eleventyConfig.addPlugin(syntaxHighlight, { className: "s-code-block", init: function ({ hljs }) { // TODO custom plugin taken from Prod - should probably be an npm package? hljs.addPlugin(new HljsInsertLineNums()); }, }); // Add markdown shortcode eleventyConfig.addPlugin(markdownShortcode, { html: true, highlight: function (str, lang) { if (lang && hljs.getLanguage(lang)) { return '<pre class="language-' + lang + ' s-code-block"><code class="language-' + lang + ' s-code-block">' + hljs.highlight(str, {language: lang}).value + '</code></pre>'; } return ''; // use external default escaping } }); // Add submenu generation eleventyConfig.addPlugin(pluginTOC, {tags: ['h2', 'h3'], wrapper: 'nav aria-label="Table of contents"'}); // Copy these files over to _site eleventyConfig.addPassthroughCopy('assets'); eleventyConfig.addPassthroughCopy('email/templates/code'); eleventyConfig.addPassthroughCopy('email/templates/examples'); }
package com.leetcode; public class Solution_718 { public int findLength(int[] nums1, int[] nums2) { int ans = 0; int[][] dp = new int[nums2.length + 1][nums1.length + 1]; for (int i = 1; i < nums2.length + 1; i++) { for (int j = 1; j < nums1.length + 1; j++) { dp[i][j] = nums2[i - 1] != nums1[j - 1] ? 0 : dp[i - 1][j - 1] + 1; ans = Math.max(ans, dp[i][j]); } } return ans; } }
package main import ( "net/url" "strings" "testing" ) func TestSetupCliApp(t *testing.T) { app := setupCliApp() if app == nil { t.Fatalf("App should not be nil") } if app.Name != "goforecast" { t.Fatalf("Expected app name of \"goforecast\", got: %s", app.Name) } if len(app.Commands) < 1 { t.Fatalf("Expected app to have 1+ commands defined, got: %d", len(app.Commands)) } } func TestBuildGeocodingURL(t *testing.T) { u, err := buildGeocodingURL("http", nil) if err != nil { t.Fatalf("Expected no error, got: %s", err) } if u == nil { t.Fatal("URL should never be nil without error") } if !strings.Contains(u.String(), geocodeHost) { t.Fatalf("Expected url (%s) to contain geocode host (%s)", u.String(), geocodeHost) } if !strings.Contains(u.String(), geocodePath) { t.Fatalf("Expected url (%s) to contain geocode path (%s)", u.String(), geocodePath) } vals := map[string][]string{ "foo": []string{"bar", "baz"}, } u, err = buildGeocodingURL("http", url.Values(vals)) if err != nil { t.Fatalf("Expected no error, got: %s", err) } if u == nil { t.Fatal("URL should never be nil without error") } } func TestParseGeocodingAddr(t *testing.T) { zip := "94109" vals := parseGeocodingAddr(zip) if addr, ok := vals["address"]; !ok || len(addr) != 1 || addr[0] != zip { t.Fatalf("Expected address of %s, got %v", zip, addr) } }
package ctrlgitops import ( "context" "runtime/debug" "time" orbcfg "github.com/caos/orbos/pkg/orb" "github.com/caos/orbos/pkg/labels" "github.com/caos/orbos/internal/executables" "github.com/caos/orbos/internal/operator/orbiter" "github.com/caos/orbos/internal/operator/orbiter/kinds/orb" "github.com/caos/orbos/mntr" "github.com/caos/orbos/pkg/git" ) type OrbiterConfig struct { Recur bool Deploy bool Verbose bool Version string OrbConfigPath string GitCommit string } func Orbiter(ctx context.Context, monitor mntr.Monitor, conf *OrbiterConfig, orbctlGit *git.Client) error { go checks(monitor, orbctlGit) finishedChan := make(chan struct{}) takeoffChan := make(chan struct{}) healthyChan := make(chan bool) if conf.Recur { go orbiter.Instrument(monitor, healthyChan) } else { go func() { for range healthyChan { } }() } on := func() { takeoffChan <- struct{}{} } go on() var initialized bool loop: for { select { case <-finishedChan: break loop case <-takeoffChan: iterate(conf, orbctlGit, !initialized, ctx, monitor, finishedChan, healthyChan, func(iterated bool) { if iterated { initialized = true } time.Sleep(time.Second * 30) go on() }) } } return nil } func iterate(conf *OrbiterConfig, gitClient *git.Client, firstIteration bool, ctx context.Context, monitor mntr.Monitor, finishedChan chan struct{}, healthyChan chan bool, done func(iterated bool)) { var err error defer func() { go func() { if err != nil { healthyChan <- false return } }() }() orbFile, err := orbcfg.ParseOrbConfig(conf.OrbConfigPath) if err != nil { monitor.Error(err) done(false) return } if err := gitClient.Configure(orbFile.URL, []byte(orbFile.Repokey)); err != nil { monitor.Error(err) done(false) return } if err := gitClient.Clone(); err != nil { monitor.Error(err) done(false) return } if firstIteration { started := float64(time.Now().UTC().Unix()) go func() { for range time.Tick(30 * time.Minute) { monitor.WithField("since", started).CaptureMessage("ORBITER is running") } }() executables.Populate() monitor.WithFields(map[string]interface{}{ "version": conf.Version, "commit": conf.GitCommit, "verbose": conf.Verbose, "repoURL": orbFile.URL, }).Info("Orbiter took off") } adaptFunc := orb.AdaptFunc( labels.MustForOperator("ORBOS", "orbiter.caos.ch", conf.Version), orbFile, conf.GitCommit, !conf.Recur, conf.Deploy, gitClient, ) takeoffConf := &orbiter.Config{ OrbiterCommit: conf.GitCommit, GitClient: gitClient, Adapt: adaptFunc, FinishedChan: finishedChan, OrbConfig: *orbFile, } takeoff := orbiter.Takeoff(monitor, takeoffConf, healthyChan) go func() { defer func() { monitor.RecoverPanic(recover()) }() started := time.Now() takeoff() monitor.WithFields(map[string]interface{}{ "took": time.Since(started), }).Info("Iteration done") debug.FreeOSMemory() done(true) }() }
#!/bin/bash echo "RUN THIS SCRIPT BEFORE AB'S, TO PREVENT AB FROM ACCIDENTALLY OVERWRITING FILES IF THE MAX NUMBER DM KNEW ABOUT WAS SMALLER THAN THE BIGGEST REAL NUMBER" for f in $(find ./ -type d ) do LIST=`exec ls /c/Users/jadedResearcher/IdeaProjects/DollLibCorrect/example/images/$f/*.png | sort -rV` big=-113 bigNum=-113 for doop in $LIST do big="${doop##*/}" bigNum="${big%.*}" re='^[0-9]+$' if ! [[ $bigNum =~ $re ]] ; then echo "error: $bigNum is not a number, trying next." else echo $bigNum is definitely a number. it has to be. break; fi done echo last biggest number is $bigNum for file in `ls $f/*.png | sort -V` do bigNum=$((bigNum + 1)) newFile=${f}/${bigNum}jr.png echo $file but it seems it should be $newFile `exec mv $file $newFile` done done
function inArray(arr, key, val) { for (let i = 0; i < arr.length; i++) { if (arr[i][key] === val) { return i } } return -1 } Page({ data: { value: '', placeholder: '', devices: [], connected: false, searchDevices: [] }, onLoad(query) { this.initPage(query) this.openBluetoothAdapter() }, initPage(query){ let placeholder = '搜索' this.setData({ placeholder }) }, search(e) { const value = e.detail.value const _this = this this.setData({ value }) let devicesData = this.data.devices let searchData = [] for (let i = 0; i < devicesData.length; i++) { let item = devicesData[i] let name = item.name if (name.search(value) != -1) { searchData.push(item) } } this.setData({"searchDevices": searchData}) }, goDetail(e) { const ds = e.currentTarget.dataset const deviceId = ds.deviceId const name = ds.name wx.showLoading() wx.createBLEConnection({ deviceId, success: () => { this.setData({ connected: true, name, deviceId, }) wx.navigateTo({ url: `/pages/subPages/device-detail/device-detail?deviceId=${deviceId}` }) }, complete() { wx.hideLoading() } }) }, openBluetoothAdapter() { wx.openBluetoothAdapter({ success: (res) => { this.startBluetoothDevicesDiscovery() }, fail: (res) => { if (res.errCode === 10001) { wx.showModal({ title: '错误', content: '未找到蓝牙设备, 请打开蓝牙后重试。', showCancel: false }) wx.onBluetoothAdapterStateChange(function (res) { if (res && res.available) { this.startBluetoothDevicesDiscovery() } }) } } }) }, startBluetoothDevicesDiscovery() { if (this._discoveryStarted) { return } this._discoveryStarted = true wx.startBluetoothDevicesDiscovery({ allowDuplicatesKey: true, success: (res) => { this.onBluetoothDeviceFound() }, }) }, onBluetoothDeviceFound() { wx.onBluetoothDeviceFound((res) => { res.devices.forEach(device => { if (!device.name && !device.localName) { return } const foundDevices = this.data.devices const idx = inArray(foundDevices, 'deviceId', device.deviceId) const data = {} if (idx === -1) { data[`devices[${foundDevices.length}]`] = device } else { data[`devices[${idx}]`] = device } this.setData(data) }) }) } })
<gh_stars>0 import net.runelite.mapping.Export; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("q") public abstract class class16 extends Node { @ObfuscatedName("l") @ObfuscatedGetter( intValue = -2104011211 ) @Export("Interpreter_intStackSize") static int Interpreter_intStackSize; @ObfuscatedName("lx") @ObfuscatedGetter( intValue = 2074784147 ) @Export("menuX") static int menuX; class16() { } // L: 48 @ObfuscatedName("f") @ObfuscatedSignature( descriptor = "(Lnu;I)V", garbageValue = "-1239860939" ) abstract void vmethod356(Buffer var1); @ObfuscatedName("o") @ObfuscatedSignature( descriptor = "(Lp;I)V", garbageValue = "1583378087" ) abstract void vmethod352(class3 var1); @ObfuscatedName("u") @ObfuscatedSignature( descriptor = "(Lnu;I)Ljava/lang/String;", garbageValue = "-1639083149" ) public static String method258(Buffer var0) { String var1; try { int var2 = var0.readUShortSmart(); // L: 67 if (var2 > 32767) { // L: 68 var2 = 32767; } byte[] var3 = new byte[var2]; // L: 69 var0.offset += class227.huffman.decompress(var0.array, var0.offset, var3, 0, var2); // L: 70 String var4 = class303.decodeStringCp1252(var3, 0, var2); // L: 71 var1 = var4; // L: 72 } catch (Exception var6) { // L: 74 var1 = "Cabbage"; // L: 75 } return var1; // L: 78 } @ObfuscatedName("fy") @ObfuscatedSignature( descriptor = "(I)V", garbageValue = "-2104011211" ) static final void method259() { ApproximateRouteStrategy.method1205(); // L: 2384 FloorUnderlayDefinition.FloorUnderlayDefinition_cached.clear(); // L: 2386 KitDefinition.KitDefinition_cached.clear(); // L: 2389 ObjectComposition.ObjectDefinition_cached.clear(); // L: 2392 ObjectComposition.ObjectDefinition_cachedModelData.clear(); // L: 2393 ObjectComposition.ObjectDefinition_cachedEntities.clear(); // L: 2394 ObjectComposition.ObjectDefinition_cachedModels.clear(); // L: 2395 MusicPatchPcmStream.method4123(); // L: 2397 WorldMapLabelSize.method2678(); // L: 2398 class22.method320(); // L: 2399 SpotAnimationDefinition.SpotAnimationDefinition_cached.clear(); // L: 2401 SpotAnimationDefinition.SpotAnimationDefinition_cachedModels.clear(); // L: 2402 WorldMapAreaData.method3212(); // L: 2404 VarpDefinition.VarpDefinition_cached.clear(); // L: 2406 Clock.method2600(); // L: 2408 WorldMapLabelSize.method2676(); // L: 2409 ParamComposition.method5096(); // L: 2410 ParamComposition.ParamDefinition_cached.clear(); // L: 2412 WorldMapElement.WorldMapElement_cachedSprites.clear(); // L: 2415 PlayerComposition.PlayerAppearance_cachedModels.clear(); // L: 2418 ReflectionCheck.method1172(); // L: 2420 ((TextureProvider)Rasterizer3D.Rasterizer3D_textureLoader).clear(); // L: 2421 Script.Script_cached.clear(); // L: 2422 TriBool.archive0.clearFiles(); // L: 2423 class367.archive1.clearFiles(); // L: 2424 class5.archive3.clearFiles(); // L: 2425 ItemContainer.archive4.clearFiles(); // L: 2426 class157.archive5.clearFiles(); // L: 2427 class8.archive6.clearFiles(); // L: 2428 class12.archive7.clearFiles(); // L: 2429 SoundSystem.archive8.clearFiles(); // L: 2430 AbstractWorldMapData.archive9.clearFiles(); // L: 2431 class373.archive10.clearFiles(); // L: 2432 class10.archive11.clearFiles(); // L: 2433 BuddyRankComparator.archive12.clearFiles(); // L: 2434 } // L: 2435 @ObfuscatedName("gg") @ObfuscatedSignature( descriptor = "(IIIIIIIIIB)V", garbageValue = "-60" ) @Export("updatePendingSpawn") static final void updatePendingSpawn(int var0, int var1, int var2, int var3, int var4, int var5, int var6, int var7, int var8) { PendingSpawn var9 = null; // L: 6772 for (PendingSpawn var10 = (PendingSpawn)Client.pendingSpawns.last(); var10 != null; var10 = (PendingSpawn)Client.pendingSpawns.previous()) { // L: 6773 6774 6779 if (var0 == var10.plane && var10.x == var1 && var2 == var10.y && var3 == var10.type) { // L: 6775 var9 = var10; // L: 6776 break; } } if (var9 == null) { // L: 6781 var9 = new PendingSpawn(); // L: 6782 var9.plane = var0; // L: 6783 var9.type = var3; // L: 6784 var9.x = var1; // L: 6785 var9.y = var2; // L: 6786 long var11 = 0L; // L: 6788 int var13 = -1; // L: 6789 int var14 = 0; // L: 6790 int var15 = 0; // L: 6791 if (var9.type == 0) { // L: 6792 var11 = WorldMapArea.scene.getBoundaryObjectTag(var9.plane, var9.x, var9.y); } if (var9.type == 1) { // L: 6793 var11 = WorldMapArea.scene.getWallDecorationTag(var9.plane, var9.x, var9.y); } if (var9.type == 2) { // L: 6794 var11 = WorldMapArea.scene.getGameObjectTag(var9.plane, var9.x, var9.y); } if (var9.type == 3) { var11 = WorldMapArea.scene.getFloorDecorationTag(var9.plane, var9.x, var9.y); // L: 6795 } if (0L != var11) { // L: 6796 int var16 = WorldMapArea.scene.getObjectFlags(var9.plane, var9.x, var9.y, var11); // L: 6797 var13 = WorldMapSection1.Entity_unpackID(var11); // L: 6798 var14 = var16 & 31; // L: 6799 var15 = var16 >> 6 & 3; // L: 6800 } var9.objectId = var13; // L: 6802 var9.field1203 = var14; // L: 6803 var9.field1199 = var15; // L: 6804 Client.pendingSpawns.addFirst(var9); // L: 6806 } var9.id = var4; // L: 6808 var9.field1196 = var5; // L: 6809 var9.orientation = var6; // L: 6810 var9.delay = var7; // L: 6811 var9.hitpoints = var8; // L: 6812 } // L: 6813 }
<reponame>bjfletcher/playframework /* * Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com> */ package play.api.libs.ws.ning import akka.stream.Materializer import org.asynchttpclient._ import play.api._ import play.api.inject.ApplicationLifecycle import play.api.libs.ws._ import play.api.libs.ws.ahc.{ AhcWSClientConfigParser, AhcWSAPI, AhcWSClient, AhcWSRequest } import play.api.libs.ws.ssl._ /** * A WS client backed by a Ning AsyncHttpClient. * * If you need to debug Ning, set logger.com.ning.http.client=DEBUG in your application.conf file. * * @param config a client configuration object */ @deprecated("Use AhcWSClient instead", "2.5") case class NingWSClient(config: AsyncHttpClientConfig)(implicit materializer: Materializer) extends WSClient { private val ahcWsClient = AhcWSClient(config) def underlying[T]: T = ahcWsClient.underlying private[libs] def executeRequest[T](request: Request, handler: AsyncHandler[T]): ListenableFuture[T] = ahcWsClient.executeRequest(request, handler) def close(): Unit = ahcWsClient.close() def url(url: String): WSRequest = AhcWSRequest(ahcWsClient, url, "GET", EmptyBody, Map(), Map(), None, None, None, None, None, None, None) } @deprecated("Use AhcWSClient instead", "2.5") object NingWSClient { /** * Convenient factory method that uses a [[WSClientConfig]] value for configuration instead of an [[https://asynchttpclient.github.io/async-http-client/apidocs/com/ning/http/client/AsyncHttpClientConfig.html org.asynchttpclient.AsyncHttpClientConfig]]. * * Typical usage: * * {{{ * val client = NingWSClient() * val request = client.url(someUrl).get() * request.foreach { response => * doSomething(response) * client.close() * } * }}} * * @param config configuration settings */ def apply(config: NingWSClientConfig = NingWSClientConfig())(implicit materializer: Materializer): NingWSClient = { val client = new NingWSClient(new NingAsyncHttpClientConfigBuilder(config).build()) new SystemConfiguration().configure(config.wsClientConfig) client } } /** * Ning WS API implementation components. */ @deprecated("Use AhcWSClient instead", "2.5") trait NingWSComponents { def environment: Environment def configuration: Configuration def applicationLifecycle: ApplicationLifecycle def materializer: Materializer lazy val wsClientConfig: WSClientConfig = new WSConfigParser(configuration, environment).parse() private lazy val ahcWsClientConfig = new AhcWSClientConfigParser(wsClientConfig, configuration, environment).parse() lazy val ningWsClientConfig: NingWSClientConfig = NingWSClientConfig( wsClientConfig = wsClientConfig, maxConnectionsPerHost = ahcWsClientConfig.maxConnectionsPerHost, maxConnectionsTotal = ahcWsClientConfig.maxConnectionsTotal, maxConnectionLifetime = ahcWsClientConfig.maxConnectionLifetime, idleConnectionInPoolTimeout = ahcWsClientConfig.idleConnectionInPoolTimeout, maxNumberOfRedirects = ahcWsClientConfig.maxNumberOfRedirects, maxRequestRetry = ahcWsClientConfig.maxRequestRetry, disableUrlEncoding = ahcWsClientConfig.disableUrlEncoding, keepAlive = ahcWsClientConfig.keepAlive ) lazy val wsApi: WSAPI = new AhcWSAPI(environment, ahcWsClientConfig, applicationLifecycle)(materializer) lazy val wsClient: WSClient = wsApi.client }
<reponame>brandontthompson/service import express from 'express'; import { middleware, service } from '../index'; (() => { // service.register(); service.register(require('./testservice').test); service.use(express.urlencoded({extended:false})); service.use(express.json()); service.use(require('./middleware.test').testmiddleware); service.use(middleware.simpleError) service.init(); })();
<reponame>rodinwow/petri-net-model<gh_stars>0 import $ from 'jquery'; export default class PetriNetView { constructor(PetriNetController) { this._ctrl = PetriNetController; this.init(); } init() { this.initializeHandlers(); this.updateView(); } initializeHandlers() { $('.btn-group').on('click', this.implementTransition.bind(this)); this.$positions = $('.petri_position').toArray(); } implementTransition(e) { let target = e.target || event.target; let tsId = target.id; if (target.type != 'button' || this._ctrl.bannedTransitions.has(tsId)) return; this._ctrl.executeTransition(tsId); this.updateView(); } updateView() { let $positions = this.$positions; let positions = this._ctrl.positions; this.updatePositions($positions, positions); this.updateTransitions(); } updatePositions($positions, positions) { $positions.forEach(elt => { for (let i = 0; i < positions.length; i++) { if (elt.id === positions[i].title) { elt.innerHTML = positions[i].chips; break; } } }); } updateTransitions() { this._ctrl.bannedTransitions.forEach(elt => $('#' + elt).removeClass('disabled')); this._ctrl.updateTransitions(); this._ctrl.bannedTransitions.forEach(elt => $('#' + elt).addClass('disabled')); } }
<filename>src/main/scala/scalation/analytics/par/Regression.scala //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** @author <NAME> * @version 1.3 * @date Wed Feb 20 17:39:57 EST 2013 * @see LICENSE (MIT style license file). */ package scalation.analytics.par import math.pow import scalation.linalgebra.{Fac_QR_H, VectoD} import scalation.linalgebra.par._ import scalation.plot.Plot import scalation.util.{Error, time} import scalation.analytics.Predictor import scalation.analytics.RegTechnique._ //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `Regression` class supports multiple linear regression. In this case, * 'x' is multi-dimensional [1, x_1, ... x_k]. Fit the parameter vector 'b' in * the regression equation * <p> * y = b dot x + e = b_0 + b_1 * x_1 + ... b_k * x_k + e * <p> * where 'e' represents the residuals (the part not explained by the model). * Use Least-Squares (minimizing the residuals) to fit the parameter vector * <p> * b = x_pinv * y [ alternative: b = solve (y) ] * <p> * where 'x_pinv' is the pseudo-inverse. Three techniques are provided: * <p> * 'Fac_QR' // QR Factorization: slower, more stable (default) * 'Fac_Cholesky' // Cholesky Factorization: faster, less stable (reasonable choice) * 'Inverse' // Inverse/Gaussian Elimination, classical textbook technique (outdated) * <p> * This version uses parallel processing to speed up execution. * @see see.stanford.edu/materials/lsoeldsee263/05-ls.pdf * @param x the input/design m-by-n matrix augmented with a first column of ones * @param y the response vector * @param technique the technique used to solve for b in x.t*x*b = x.t*y */ class Regression (x: MatrixD, y: VectorD, technique: RegTechnique = QR) extends Predictor with Error { if (y != null && x.dim1 != y.dim) flaw ("constructor", "dimensions of x and y are incompatible") if (x.dim1 <= x.dim2) flaw ("constructor", "not enough data rows in matrix to use regression") private val DEBUG = false // debug flag private val k = x.dim2 - 1 // number of variables (k = n-1) private val m = x.dim1.toDouble // number of data points (rows) private val r_df = (m-1.0) / (m-k-1.0) // ratio of degrees of freedom private var rSquared = -1.0 // coefficient of determination (quality of fit) private var rBarSq = -1.0 // Adjusted R-squared private var fStat = -1.0 // F statistic (quality of fit) type Fac_QR = Fac_QR_H [MatrixD] // change as needed private val fac = technique match { // select the factorization technique case QR => new Fac_QR (x) // QR Factorization case Cholesky => new Fac_Cholesky (x.t * x) // Cholesky Factorization case _ => null // don't factor, use inverse } // match private val x_pinv = technique match { // pseudo-inverse of x case QR => val (q, r) = fac.factor12 (); r.inverse * q.t case Cholesky => fac.factor (); null // don't compute it directly case _ => (x.t * x).inverse * x.t // classic textbook technique } // match //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Train the predictor by fitting the parameter vector (b-vector) in the * multiple regression equation * y = b dot x + e = [b_0, ... b_k] dot [1, x_1 , ... x_k] + e * using the least squares method. */ def train () { b = if (x_pinv == null) fac.solve (y) else x_pinv * y // parameter vector [b_0, b_1, ... b_k] val e = y - x * b // residual/error vector val sse = e dot e // residual/error sum of squares val sst = (y dot y) - pow (y.sum, 2) / m // total sum of squares val ssr = sst - sse // regression sum of squares rSquared = ssr / sst // coefficient of determination (R-squared) rBarSq = 1.0 - (1.0-rSquared) * r_df // R-bar-squared (adjusted R-squared) fStat = ssr * (m-k-1.0) / (sse * k) // F statistic (msr / mse) } // train //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Retrain the predictor by fitting the parameter vector (b-vector) in the * multiple regression equation * yy = b dot x + e = [b_0, ... b_k] dot [1, x_1 , ... x_k] + e * using the least squares method. * @param yy the new response vector */ def train (yy: VectorD) { b = if (x_pinv == null) fac.solve (yy) else x_pinv * yy // parameter vector [b_0, b_1, ... b_k] val e = yy - x * b // residual/error vector val sse = e dot e // residual/error sum of squares val sst = (yy dot yy) - pow (yy.sum, 2) / m // total sum of squares val ssr = sst - sse // regression sum of squares rSquared = ssr / sst // coefficient of determination rBarSq = 1.0 - (1.0-rSquared) * r_df // R-bar-squared (adjusted R-squared) fStat = ssr * (m-k-1.0) / (sse * k) // F statistic (msr / mse) } // train //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Return the quality of the fit, including 'rSquared'. */ def fit: VectorD = VectorD (rSquared, rBarSq, fStat) //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Predict the value of y = f(z) by evaluating the formula y = b dot z, * e.g., (b_0, b_1, b_2) dot (1, z_1, z_2). * @param z the new vector to predict */ def predict (z: VectoD): Double = b dot z //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Perform backward elimination to remove the least predictive variable * from the model, returning the variable to eliminate, the new parameter * vector, the new R-squared value and the new F statistic. */ def backElim (): Tuple3 [Int, VectoD, VectorD] = { var j_max = -1 // index of variable to eliminate var b_max: VectoD = null // parameter values for best solution var ft_max = VectorD (3); ft_max.set (-1.0) // optimize on quality of fit (ft(0) is rSquared) for (j <- 1 to k) { val keep = m.toInt // i-value large enough to not exclude any rows in slice val rg_j = new Regression (x.sliceExclude (keep, j), y) // regress with x_j removed rg_j.train () val b = rg_j.coefficient val ft = rg_j.fit if (ft(0) > ft_max(0)) { j_max = j; b_max = b; ft_max = ft } } // for (j_max, b_max, ft_max) } // backElim //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Compute the Variance Inflation Factor 'VIF' for each variable to test * for multi-collinearity by regressing 'xj' against the rest of the variables. * A VIF over 10 indicates that over 90% of the variance of 'xj' can be predicted * from the other variables, so 'xj' is a candidate for removal from the model. */ def vif: VectorD = { val vifV = new VectorD (k) // VIF vector for (j <- 1 to k) { val keep = m.toInt // i-value large enough to not exclude any rows in slice val x_j = x.col(j) // x_j is jth column in x val rg_j = new Regression (x.sliceExclude (keep, j), x_j) // regress with x_j removed rg_j.train () vifV(j-1) = 1.0 / (1.0 - rg_j.fit(0)) // store vif for x_1 in vifV(0) } // for vifV } // vif } // Regression class //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `RegressionTest` object tests `Regression` class using the following * regression equation. * <p> * y = b dot x = b_0 + b_1*x_1 + b_2*x_2. * <p> * Test regression and backward elimination. * @see http://statmaster.sdu.dk/courses/st111/module03/index.html */ object RegressionTest extends App { // 5 data points: constant term, x_1 coordinate, x_2 coordinate val x = new MatrixD ((5, 3), 1.0, 36.0, 66.0, // 5-by-3 matrix 1.0, 37.0, 68.0, 1.0, 47.0, 64.0, 1.0, 32.0, 53.0, 1.0, 1.0, 101.0) val y = VectorD (745.0, 895.0, 442.0, 440.0, 1598.0) val z = VectorD (1.0, 20.0, 80.0) println ("x = " + x) println ("y = " + y) val rg = new Regression (x, y) rg.train () println ("fit = " + rg.fit) val yp = rg.predict (z) // predict y for one point println ("predict (" + z + ") = " + yp) // val yyp = rg.predict (x) // predict y for several points // println ("predict (" + x + ") = " + yyp) // // new Plot (x.col(1), y, yyp) // new Plot (x.col(2), y, yyp) println ("reduced model: fit = " + rg.backElim ()) // eliminate least predictive variable } // RegressionTest object //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `RegressionTest2` object tests `Regression` class using the following * regression equation. * <p> * y = b dot x = b_0 + b_1*x1 + b_2*x_2. * <p> * Test regression using QR Decomposition and Gaussian Elimination for computing * the pseudo-inverse. */ object RegressionTest2 extends App { // 4 data points: constant term, x_1 coordinate, x_2 coordinate val x = new MatrixD ((4, 3), 1.0, 1.0, 1.0, // 4-by-3 matrix 1.0, 1.0, 2.0, 1.0, 2.0, 1.0, 1.0, 2.0, 2.0) val y = VectorD (6.0, 8.0, 7.0, 9.0) val z = VectorD (1.0, 2.0, 3.0) var rg: Regression = null println ("x = " + x) println ("y = " + y) println ("-------------------------------------------------") println ("Fit the parameter vector b using QR Factorization") rg = new Regression (x, y) // use QR Factorization rg.train () println ("fit = " + rg.fit) val yp = rg.predict (z) // predict y for on3 point println ("predict (" + z + ") = " + yp) // val yyp = rg.predict (x) // predict y for several points // println ("predict (" + x + ") = " + yyp) // // new Plot (x.col(1), y, yyp) // new Plot (x.col(2), y, yyp) println ("-------------------------------------------------") println ("Fit the parameter vector b using Cholesky Factorization") rg = new Regression (x, y, Cholesky) // use Cholesky Factorization rg.train () println ("fit = " + rg.fit) println ("predict (" + z + ") = " + rg.predict (z)) println ("-------------------------------------------------") println ("Fit the parameter vector b using Matrix Inversion") rg = new Regression (x, y, Inverse) // use Matrix Inversion rg.train () println ("fit = " + rg.fit) println ("predict (" + z + ") = " + rg.predict (z)) } // RegressionTest2 object //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `RegressionTest3` object tests the multi-collinearity method in the * `Regression` class using the following regression equation. * <p> * y = b dot x = b_0 + b_1*x_1 + b_2*x_2 + b_3*x_3 + b_4 * x_4 * <p> * @see online.stat.psu.edu/online/development/stat501/12multicollinearity/05multico_vif.html * @see online.stat.psu.edu/online/development/stat501/data/bloodpress.txt */ object RegressionTest3 extends App { // 20 data points: Constant x_1 x_2 x_3 x_4 // Age Weight Dur Stress val x = new MatrixD ((20, 5), 1.0, 47.0, 85.4, 5.1, 33.0, 1.0, 49.0, 94.2, 3.8, 14.0, 1.0, 49.0, 95.3, 8.2, 10.0, 1.0, 50.0, 94.7, 5.8, 99.0, 1.0, 51.0, 89.4, 7.0, 95.0, 1.0, 48.0, 99.5, 9.3, 10.0, 1.0, 49.0, 99.8, 2.5, 42.0, 1.0, 47.0, 90.9, 6.2, 8.0, 1.0, 49.0, 89.2, 7.1, 62.0, 1.0, 48.0, 92.7, 5.6, 35.0, 1.0, 47.0, 94.4, 5.3, 90.0, 1.0, 49.0, 94.1, 5.6, 21.0, 1.0, 50.0, 91.6, 10.2, 47.0, 1.0, 45.0, 87.1, 5.6, 80.0, 1.0, 52.0, 101.3, 10.0, 98.0, 1.0, 46.0, 94.5, 7.4, 95.0, 1.0, 46.0, 87.0, 3.6, 18.0, 1.0, 46.0, 94.5, 4.3, 12.0, 1.0, 48.0, 90.5, 9.0, 99.0, 1.0, 56.0, 95.7, 7.0, 99.0) // response BP val y = VectorD (105.0, 115.0, 116.0, 117.0, 112.0, 121.0, 121.0, 110.0, 110.0, 114.0, 114.0, 115.0, 114.0, 106.0, 125.0, 114.0, 106.0, 113.0, 110.0, 122.0) val rg = new Regression (x, y) time { rg.train () } println ("fit = " + rg.fit) // fit model y = b_0 + b_1*x_1 + b_2*x_2 + b_3*x_3 + b_4*x_4 println ("vif = " + rg.vif) // test multi-collinearity (VIF) } // RegressionTest3 object
#!/bin/bash #============================================================ # https://github.com/P3TERX/Actions-OpenWrt # File name: diy-part2.sh # Description: OpenWrt DIY script part 2 (After Update feeds) # Lisence: MIT # Author: P3TERX # Blog: https://p3terx.com #============================================================ # Modify default IP #sed -i 's/192.168.1.1/192.168.50.5/g' package/base-files/files/bin/config_generate #sed -i '$a src-git lienol https://github.com/Lienol/openwrt-package' feeds.conf.default #git clone https://github.com/kenzok8/openwrt-packages package/op-packages #================================================= #================================================= #获取OpenAppFilter git clone https://github.com/destan19/OpenAppFilter.git package/diy-packages/luci-app-oaf # 获取luci-app-adguardhome git clone https://github.com/rufengsuixing/luci-app-adguardhome package/diy-packages/luci-app-adguardhome # 获取hello world和依赖 git clone https://github.com/jerrykuku/lua-maxminddb package/diy-packages/helloworld/lua-maxminddb git clone https://github.com/jerrykuku/luci-app-vssr package/diy-packages/helloworld/luci-app-vssr # 获取passwall git clone -b 3.6-40 https://github.com/liuran001/luci-app-passwall package/diy-packages/passwall # 获取Lienol-package git clone https://github.com/Lienol/openwrt-package package/diy-packages/lienol # 获取luci-app-diskman和依赖 mkdir -p package/diy-packages/luci-app-diskman && \ mkdir -p package/diy-packages/parted && \ wget https://raw.githubusercontent.com/lisaac/luci-app-diskman/master/Makefile -O package/diy-packages/luci-app-diskman/Makefile wget https://raw.githubusercontent.com/lisaac/luci-app-diskman/master/Parted.Makefile -O package/diy-packages/parted/Makefile # 获取luci-app-serverchan git clone https://github.com/tty228/luci-app-serverchan package/diy-packages/luci-app-serverchan # 获取luci-app-openclash git clone -b master https://github.com/vernesong/OpenClash package/diy-packages/openclash #================================================= sed -i '/set luci.main.mediaurlbase=\/luci-static\/bootstrap/d' feeds/luci/themes/luci-theme-bootstrap/root/etc/uci-defaults/30_luci-theme-bootstrap #================================================= # 清除旧版argon主题并拉取最新版 cd package/lean rm -rf luci-theme-argon git clone -b 18.06 https://github.com/jerrykuku/luci-theme-argon luci-theme-argon #================================================= #================================================= # 修改BaiduPCS-web来源 rm -rf baidupcs-web git clone https://github.com/liuran001/baidupcs-web-lede baidupcs-web
import { createSelector } from 'reselect'; import { initialState } from './reducer'; const selectExperimentDetail = state => state.get('experimentDetail', initialState); const makeSelectExperimentDetail = () => createSelector(selectExperimentDetail, experimentDetailState => experimentDetailState.get('experiment'), ); const makeSelectExperimentId = () => createSelector(selectExperimentDetail, experimentDetailState => experimentDetailState.get('experimentId'), ); const makeSelectExperimentName = () => createSelector(selectExperimentDetail, experimentDetailState => { const expId = experimentDetailState.get('experimentId'); const shortExpId = experimentDetailState.get('shortExperimentId'); const expName = experimentDetailState.get('experimentName'); if (expId === expName) { return shortExpId; } return expName; }); const makeSelectShortExperimentId = () => createSelector(selectExperimentDetail, experimentDetailState => experimentDetailState.get('shortExperimentId'), ); const makeSelectLabels = () => createSelector(selectExperimentDetail, experimentDetailState => experimentDetailState.get('labels'), ); const makeSelectTab = () => createSelector(selectExperimentDetail, experimentDetailState => experimentDetailState.get('tabKey'), ); export { selectExperimentDetail, makeSelectExperimentDetail, makeSelectExperimentId, makeSelectShortExperimentId, makeSelectExperimentName, makeSelectLabels, makeSelectTab, };
mkdir -p Build cd Build cmake -D CMAKE_C_COMPILER=clang-9 -D CMAKE_CXX_COMPILER=clang++-9 -D CMAKE_CXX_FLAGS="-O3" ..
<gh_stars>10-100 import { graphql } from "gatsby"; // Used for settings export const ghostSettingsFields = graphql` fragment GhostSettingsFields on GhostSettings { title description logo icon cover_image facebook twitter lang timezone codeinjection_head codeinjection_foot codeinjection_styles navigation { label url } } `; // Used for site config export const siteMetadataFields = graphql` fragment SiteMetadataFields on SiteSiteMetadata { siteUrl postsPerPage siteTitleMeta siteDescriptionMeta shareImageWidth shareImageHeight shortTitle siteIcon backgroundColor themeColor siteTitle siteDescription language logoUrl alternateLogoUrl coverUrl metadata { title description } twitterCard { title description imageUrl username } facebookCard { title description imageUrl appId height width } } `;
aws iam create-role --role-name LambdaEC2StopStart --assume-role-policy-document \ '{"Version": "2012-10-17","Statement": [{ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}' curl https://raw.githubusercontent.com/aissa-laribi/awsops/main/ec2/Start-EC2-Instances-Mornightly/role-permissions.json > iam.json aws iam create-policy --policy-name LambdaEC2Start --policy-document file://iam.json aws iam put-role-policy --role-name LambdaEC2Start --policy-name LambdaEC2Start --policy-document file://iam.json
<gh_stars>100-1000 package io.github.intellij.dlanguage.run; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.configurations.*; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.CompilerModuleExtension; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.util.PathUtil; import com.intellij.util.xmlb.XmlSerializer; import org.bouncycastle.math.raw.Mod; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class DlangRunAppConfiguration extends ModuleBasedConfiguration<RunConfigurationModule, Module> { private String workDir; private String additionalParams; private Map<String, String> envVars; public DlangRunAppConfiguration(final String name, final Project project, final ConfigurationFactory factory) { super(name, new RunConfigurationModule(project), factory); final Collection<Module> modules = this.getValidModules(); if (!modules.isEmpty()) { //Get first valid module and use it this.setModule(modules.iterator().next()); } workDir = project.getBasePath(); envVars = new HashMap<>(); } public String getExecutablePath() { @Nullable final Module module = getConfigurationModule().getModule(); if (module != null && !module.isDisposed()) { final String outputPath = ModuleRootManager.getInstance(module) .getModuleExtension(CompilerModuleExtension.class) .getCompilerOutputUrl(); String filename = module.getName(); if (SystemInfo.isWindows) { filename += ".exe"; } final File outputFile = new File(VfsUtilCore.urlToPath(outputPath), filename); return outputFile.getPath(); } else { return ""; } } @Override public Collection<Module> getValidModules() { final Module[] modules = ModuleManager.getInstance(getProject()).getModules(); final DMDRunner appRunner = new DMDRunner(); final ArrayList<Module> res = new ArrayList<>(); for (final Module module : modules) { if (appRunner.isValidModule(module)) { res.add(module); } } return res; } @Override public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() { return new DlangRunAppConfigurationEditor(); } @Nullable @Override public RunProfileState getState(@NotNull final Executor executor, @NotNull final ExecutionEnvironment env) throws ExecutionException { return new DlangRunAppState(env, this); } @Override public void writeExternal(@NotNull final Element element) throws WriteExternalException { if (envVars == null) { envVars = new HashMap<>(); } super.writeExternal(element); XmlSerializer.serializeInto(this, element); } @Override public void readExternal(@NotNull final Element element) throws InvalidDataException { super.readExternal(element); readModule(element); XmlSerializer.deserializeInto(this, element); } /* Getters and Setters. Autogenerated by IntelliJ IDEA */ public String getWorkDir() { return workDir; } public void setWorkDir(final String workDir) { this.workDir = workDir; } public String getAdditionalParams() { return additionalParams; } public void setAdditionalParams(final String additionalParams) { this.additionalParams = additionalParams; } public Map<String, String> getEnvVars() { return envVars; } public void setEnvVars(final Map<String, String> envVars) { this.envVars = envVars; } }
class ListManager: def __init__(self): self.dontstrip = {} def add_list(self, role, values): """ Add a list of values to the dictionary under the given role. Args: role (str): The role under which the list of values will be stored. values (list): The list of values to be added. Returns: None """ self.dontstrip[role] = values def remove_list(self, role): """ Remove the list associated with the given role from the dictionary. Args: role (str): The role whose list will be removed. Returns: None """ if role in self.dontstrip: del self.dontstrip[role] def strip_values(self, role): """ Strip whitespace from all the values in the list associated with the given role. Args: role (str): The role whose list values will be stripped. Returns: None """ if role in self.dontstrip: self.dontstrip[role] = [value.strip() for value in self.dontstrip[role]]
package io.opensphere.core.util.ref; /** * Wrapper for a {@link java.lang.ref.ReferenceQueue} that works with * {@link Reference}s. * * @param <T> The type of object in the queue. */ public class ReferenceQueue<T> { /** The wrapped reference queue. */ private final java.lang.ref.ReferenceQueue<T> myReferenceQueue = new java.lang.ref.ReferenceQueue<>(); /** * Polls this queue to see if a reference object is available. If one is * available without further delay then it is removed from the queue and * returned. Otherwise this method immediately returns <tt>null</tt>. * * @return A reference object, if one was immediately available, otherwise * <code>null</code> */ @SuppressWarnings("unchecked") public Reference<? extends T> poll() { java.lang.ref.Reference<? extends T> ref = myReferenceQueue.poll(); return ref == null ? null : ((ReferenceProvider<T>)ref).getReference(); } /** * Removes the next reference object in this queue, blocking until one * becomes available. * * @return A reference object, blocking until one becomes available * @throws InterruptedException If the wait is interrupted */ public Reference<? extends T> remove() throws InterruptedException { return remove(0); } /** * Removes the next reference object in this queue, blocking until either * one becomes available or the given timeout period expires. * * <p> * This method does not offer real-time guarantees: It schedules the timeout * as if by invoking the {@link Object#wait(long)} method. * * @param timeout If positive, block for up to <code>timeout</code> * milliseconds while waiting for a reference to be added to this * queue. If zero, block indefinitely. * * @return A reference object, if one was available within the specified * timeout period, otherwise <code>null</code> * * @throws IllegalArgumentException If the value of the timeout argument is * negative * * @throws InterruptedException If the timeout wait is interrupted */ @SuppressWarnings("unchecked") public Reference<? extends T> remove(long timeout) throws IllegalArgumentException, InterruptedException { java.lang.ref.Reference<? extends T> removed = myReferenceQueue.remove(timeout); return removed == null ? null : ((ReferenceProvider<T>)removed).getReference(); } /** * Accessor for the wrapped reference queue. * * @return The wrapped reference queue. */ protected java.lang.ref.ReferenceQueue<T> getReferenceQueue() { return myReferenceQueue; } }
<reponame>imwalrus/finalProject package co.finalproject.farm.app.user.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import co.finalproject.farm.app.user.service.UserService; import co.finalproject.farm.app.user.service.UserVO; @Service public class UserServiceImpl implements UserService { @Autowired UserMapper userDAO; //아이디 중복체크 public int idCheck(UserVO vo) { int result = userDAO.idCheck(vo); return result; } //이메일 중복체크 public int emailCheck(UserVO vo) { int result = userDAO.emailCheck(vo); return result; } //로그인 public UserVO loginCheck(UserVO vo) { return userDAO.loginCheck(vo); } //아이디 찾기 public UserVO idFind(UserVO vo) { return userDAO.idFind(vo); } //비밀번호 찾기 public int pwFind(UserVO vo) { int result = userDAO.pwFind(vo); return result; } //회원 단건조회(아이디로 조회) public UserVO getUser(UserVO vo) { return userDAO.getUser(vo); } //회원 전체조회 public List<UserVO> getUserList(UserVO vo) { return userDAO.getUserList(vo); } //회원가입 public int insertUser(UserVO vo) { int result = userDAO.insertUser(vo); return result; } //회원 정보수정 public int updateUser(UserVO vo) { int result = userDAO.updateUser(vo); return result; } //회원 권한 변경(user-> farmer) public int updateUserToFarmer(UserVO vo) { int result = userDAO.updateUserToFarmer(vo); return result; } //회원탈퇴 또는 관리자 페이지 내에서 수정 public int deleteUser(UserVO vo) { int result = userDAO.deleteUser(vo); return result; } //회원탈퇴 또는 관리자 페이지 내에서 회원 삭제 public int memberOut(UserVO vo) { int result = userDAO.memberOut(vo); return result; } }
#!/usr/bin/env sh alias tr64='tr "+/" "-_"'
#!/bin/bash HOMEBREW_TAPS=() HOMEBREW_FORMULAE=() HOMEBREW_CASKS=() MAS_APPS=() HOMEBREW_KEEP_FORMULAE=() HOMEBREW_KEEP_CASKS=() FORCE_IBREW=() LOGIN_ITEMS=() HOMEBREW_TAPS+=( homebrew/cask-drivers homebrew/cask-fonts homebrew/cask-versions homebrew/services azure/functions ) # Terminal-based HOMEBREW_FORMULAE+=( # Utilities csvkit exiftool imagemagick s3cmd unison # Networking iperf3 openconnect vpn-slice # Network monitoring iftop # Shows network traffic by service and host nload # Shows bandwidth by interface # System #acme.sh dosfstools mtools nmap ) # Desktop HOMEBREW_TAPS+=( federico-terzi/espanso ) HOMEBREW_FORMULAE+=( federico-terzi/espanso/espanso # PDF ghostscript mupdf-tools pandoc poppler pstoedit qpdf # Multimedia (video) youtube-dl yt-dlp ) HOMEBREW_CASKS+=( adobe-acrobat-reader alt-tab chromium firefox flycut hammerspoon imageoptim inkscape iterm2 keepassxc keepingyouawake libreoffice messenger microsoft-teams mysides nextcloud pencil scribus-dev skype spotify stretchly the-unarchiver transmission typora # PDF basictex # Photography adobe-dng-converter # Multimedia (video) handbrake subler vlc # System displaycal geekbench hex-fiend # Non-free acorn microsoft-office ) MAS_APPS+=( 409183694 # Keynote 409203825 # Numbers 409201541 # Pages # 526298438 # Lightshot Screenshot 441258766 # Magnet # 420212497 # Byword 404705039 # Graphic 1295203466 # Microsoft Remote Desktop 1303222628 # Paprika 1055273043 # PDF Expert # 506189836 # Harvest 585829637 # Todoist ) # Development HOMEBREW_TAPS+=( adoptopenjdk/openjdk lkrms/virt-manager #mongodb/brew ) HOMEBREW_FORMULAE+=( autopep8 cmake emscripten gdb # Email msmtp # SMTP client s-nail # `mail` and `mailx` commands # git git-cola git-filter-repo # node nvm yarn # composer # python # perltidy # mariadb #mongodb/brew/mongodb-community # shellcheck shfmt # lua luarocks # Platforms awscli azure-cli azure-functions-core-tools@3 wp-cli ) FORCE_IBREW+=( php php@7.2 php@7.3 php@7.4 lkrms/virt-manager/virt-manager ) HOMEBREW_CASKS+=( android-studio dbeaver-community font-jetbrains-mono http-toolkit robo-3t sequel-pro sourcetree sublime-merge sublime-text visual-studio-code # adoptopenjdk/openjdk/adoptopenjdk11 meld ) MAS_APPS+=( 497799835 # Xcode ) # Hardware-related HOMEBREW_CASKS+=( sonos ) HOMEBREW_KEEP_FORMULAE+=( meson ninja ocaml # php php@7.2 php@7.3 php@7.4 # libvirt qemu lkrms/virt-manager/virt-manager # ddcctl ) HOMEBREW_KEEP_CASKS+=( bbedit google-chrome key-codes lingon-x microsoft-azure-storage-explorer shortcutdetective teamviewer # makemkv mkvtoolnix # virtualbox virtualbox-extension-pack # logitech-g-hub logitech-gaming-software monitorcontrol ) LOGIN_ITEMS+=( "/Applications/AltTab.app" "/Applications/Flycut.app" "/Applications/Hammerspoon.app" "/Applications/Lightshot Screenshot.app" "/Applications/Magnet.app" "/Applications/Mail.app" "/Applications/Messenger.app" "/Applications/Microsoft Teams.app" "/Applications/Nextcloud.app" "/Applications/Skype.app" "/Applications/Todoist.app" "/System/Applications/Mail.app" )
import logging class CustomArray: def __init__(self): self.data = [] def push_item(self, item): self.data.append(item) def delete_item(self, index): if 0 <= index < len(self.data): del self.data[index] else: logging.error("Index out of range") # Execution of the given code snippet my_array = CustomArray() my_array.push_item('Hi') my_array.push_item('you') my_array.push_item('are') my_array.push_item('!') logging.info(my_array.data) # Output: ['Hi', 'you', 'are', '!'] my_array.delete_item(3) my_array.push_item('nice') logging.info(my_array.data) # Output: ['Hi', 'you', 'are', 'nice']
package com.qurux.coffeevizbeer.widget; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.view.View; import android.widget.RemoteViews; import com.google.firebase.auth.FirebaseAuth; import com.qurux.coffeevizbeer.R; import com.qurux.coffeevizbeer.helper.FireBaseHelper; import com.qurux.coffeevizbeer.ui.HomeActivity; /** * Implementation of App Widget functionality. */ public class PostsWidget extends AppWidgetProvider { private static final String REFRESH_ACTION = "com.qurux.coffeevizbeer.appwidget.action.REFRESH"; static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.posts_widget); Intent intent = new Intent(context, HomeActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); views.setOnClickPendingIntent(R.id.widget_frame, pendingIntent); views.setRemoteAdapter(R.id.posts_widget_list, new Intent(context, PostsRemoteViewService.class)); if (FirebaseAuth.getInstance().getCurrentUser() == null) { views.setTextViewText(R.id.widget_static_text, context.getString(R.string.widget_please_login)); } else { views.setTextViewText(R.id.widget_static_text, context.getString(R.string.appwidget_text)); } Intent intentSync = new Intent(context, PostsWidget.class); intentSync.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); //You need to specify the action for the intent. Right now that intent is doing nothing for there is no action to be broadcasted. PendingIntent pendingSync = PendingIntent.getBroadcast(context, 0, intentSync, PendingIntent.FLAG_UPDATE_CURRENT); //You need to specify a proper flag for the intent. Or else the intent will become deleted. views.setOnClickPendingIntent(R.id.widget_refresh_button, pendingSync); Intent startActivityIntent = new Intent(context, HomeActivity.class); PendingIntent startActivityPendingIntent = PendingIntent.getActivity(context, 0, startActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT); views.setPendingIntentTemplate(R.id.posts_widget_list, startActivityPendingIntent); appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.posts_widget_list); // Instruct the widget manager to update the widget appWidgetManager.updateAppWidget(appWidgetId, views); } public static void sendRefreshBroadcast(Context context) { Intent intent = new Intent(REFRESH_ACTION); intent.setComponent(new ComponentName(context, PostsWidget.class)); context.sendBroadcast(intent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // There may be multiple widgets active, so update all of them for (int appWidgetId : appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId); } } @Override public void onEnabled(Context context) { // Enter relevant functionality for when the first widget is created } @Override public void onDisabled(Context context) { // Enter relevant functionality for when the last widget is disabled } @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); if (FirebaseAuth.getInstance().getCurrentUser() == null) { return; } final String action = intent.getAction(); final RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.posts_widget); if (REFRESH_ACTION.equals(action)) { // refresh all your widgets AppWidgetManager mgr = AppWidgetManager.getInstance(context); ComponentName cn = new ComponentName(context, PostsWidget.class); int[] appWidgetIds = mgr.getAppWidgetIds(cn); remoteViews.setViewVisibility(R.id.widget_refresh_button, View.GONE); remoteViews.setViewVisibility(R.id.widget_refresh_button_loading, View.VISIBLE); onUpdate(context, mgr, appWidgetIds); } else if (action.equals(AppWidgetManager.ACTION_APPWIDGET_UPDATE)) { FireBaseHelper.setNewPostListener(context); remoteViews.setViewVisibility(R.id.widget_refresh_button, View.VISIBLE); remoteViews.setViewVisibility(R.id.widget_refresh_button_loading, View.GONE); ComponentName cn = new ComponentName(context, PostsWidget.class); (AppWidgetManager.getInstance(context)).updateAppWidget(cn, remoteViews); } } }
<filename>src/packages/api/resources/default/controller.ts import { Request, Response } from 'express' import * as httpStatus from 'http-status' import { getConnection } from 'typeorm' import { User } from '~/packages/database/models/user' import logger from '~/packages/api/helpers/logging' export const health = async (req: Request, res: Response): Promise<Response> => { const UsersTable = getConnection().getRepository(User) const numUsers = await UsersTable.createQueryBuilder().getCount() logger.log({ level: 'info', message: 'Health check', data: `numUsers: ${numUsers}`, }) return res.status(httpStatus.OK).json({ status: 'OK', version: 0.1, c: numUsers }) }
<reponame>coboyoshi/uvicore import uvicore from uvicore.support import module from uvicore.typing import Dict, List from uvicore.support.dumper import dump, dd from uvicore.contracts import Email @uvicore.service() class Mail: def __init__(self, *, mailer: str = None, mailer_options: Dict = None, to: List = [], cc: List = [], bcc: List = [], from_name: str = None, from_address: str = None, subject: str = None, html: str = None, text: str = None, attachments: List = [], ) -> None: # Get mailer and options from config self._config = uvicore.config.app.mail.clone() self._mailer = mailer or self._config.default self._mailer_options = self._config.mailers[self._mailer].clone().merge(mailer_options) # New message superdict self._message: Email = Email() self._message.to = to self._message.cc = cc self._message.bcc = bcc self._message.from_name = from_name or self._config.from_name self._message.from_address = from_address or self._config.from_address self._message.subject = subject self._message.html = html self._message.text = text self._message.attachments = attachments def mailer(self, mailer: str): self._mailer = mailer self._mailer_options = self._config.mailers[self._mailer].clone() return self def mailer_options(self, options: Dict): self._mailer_options.merge(Dict(options)) return self def to(self, to: List): self._message.to = to return self def cc(self, cc: List): self._message.cc = cc return self def bcc(self, bcc: List): self._message.bcc = bcc return self def from_name(self, from_name: str): self._message.from_name = from_name return self def from_address(self, from_address: str): self._message.from_address = from_address return self def subject(self, subject: str): self._message.subject = subject return self def html(self, html: str): self._message.html = html return self def text(self, text: str): self._message.text = text return self def attachments(self, attachments: List): self._message.attachments = attachments return self async def send(self): # Use dynamic module based on mailer driver driver = module.load(self._mailer_options.driver).object await driver.send(self._message, self._mailer_options)
#! /bin/bash #SBATCH -o /home/hpc/pr63so/di69fol/workspace/SWEET_2015_12_26/benchmarks_performance/rexi_tests_lrz_freq_waves/2015_12_30_scalability_rexi_fd/run_rexi_fd_m0092_t028_n0128_r0028_a1.txt ###SBATCH -e /home/hpc/pr63so/di69fol/workspace/SWEET_2015_12_26/benchmarks_performance/rexi_tests_lrz_freq_waves/2015_12_30_scalability_rexi_fd/run_rexi_fd_m0092_t028_n0128_r0028_a1.err #SBATCH -J rexi_fd_m0092_t028_n0128_r0028_a1 #SBATCH --get-user-env #SBATCH --clusters=mpp2 #SBATCH --ntasks=28 #SBATCH --cpus-per-task=28 #SBATCH --exclusive #SBATCH --export=NONE #SBATCH --time=03:00:00 #declare -x NUMA_BLOCK_ALLOC_VERBOSITY=1 declare -x KMP_AFFINITY="granularity=thread,compact,1,0" declare -x OMP_NUM_THREADS=28 echo "OMP_NUM_THREADS=$OMP_NUM_THREADS" echo . /etc/profile.d/modules.sh module unload gcc module unload fftw module unload python module load python/2.7_anaconda_nompi module unload intel module load intel/16.0 module unload mpi.intel module load mpi.intel/5.1 module load gcc/5 cd /home/hpc/pr63so/di69fol/workspace/SWEET_2015_12_26/benchmarks_performance/rexi_tests_lrz_freq_waves/2015_12_30_scalability_rexi_fd cd ../../../ . local_software/env_vars.sh # force to use FFTW WISDOM data declare -x SWEET_FFTW_LOAD_WISDOM_FROM_FILE="FFTW_WISDOM_nofreq_T28" time -p mpiexec.hydra -genv OMP_NUM_THREADS 28 -envall -ppn 1 -n 28 ./build/rexi_fd_m_tyes_a1 --initial-freq-x-mul=2.0 --initial-freq-y-mul=1.0 -f 1 -g 1 -H 1 -X 1 -Y 1 --compute-error 1 -t 50 -R 4 -C 0.3 -N 128 -U 0 -S 0 --use-specdiff-for-complex-array 0 --rexi-h 0.8 --timestepping-mode 1 --staggering 0 --rexi-m=92 -C -5.0
<gh_stars>0 /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ import React from 'react'; import { render } from 'enzyme'; import { requiredProps } from '../../../test/required_props'; import { EuiPinnableListGroup, EuiPinnableListGroupItemProps, } from './pinnable_list_group'; const someListItems: EuiPinnableListGroupItemProps[] = [ { label: 'Label with iconType', iconType: 'stop', }, { label: 'Custom extra action', extraAction: { iconType: 'bell', alwaysShow: true, 'aria-label': 'bell', }, }, { label: 'Active link', isActive: true, href: '#', }, { label: 'Button with onClick', pinned: true, onClick: (e) => { console.log('Visualize clicked', e); }, }, { label: 'Link with href', href: '#', }, { label: 'Not pinnable', href: '#', pinnable: false, }, ]; describe('EuiPinnableListGroup', () => { test('is rendered', () => { const component = render( <EuiPinnableListGroup {...requiredProps} listItems={someListItems} onPinClick={() => {}} /> ); expect(component).toMatchSnapshot(); }); test('can have custom pin icon titles', () => { const component = render( <EuiPinnableListGroup {...requiredProps} listItems={someListItems} onPinClick={() => {}} pinTitle={(item: EuiPinnableListGroupItemProps) => `Pin ${item.label} to the top` } unpinTitle={(item: EuiPinnableListGroupItemProps) => `Unpin ${item.label} to the top` } /> ); expect(component).toMatchSnapshot(); }); });
<reponame>maxwellburson/42_ft_db /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_command.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rle <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/04/28 14:04:53 by rle #+# #+# */ /* Updated: 2017/05/05 23:02:51 by rle ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_db.h" static int parse_commmand(char *line, struct s_command *command, struct s_header *header) { if (get_command_type(line, command)) { if (command->type == CLOSE || command->type == CLEAR \ || command->type == DELETE || command->type == GETALL) return (1); else if (-1 == get_field(line, header, &command->field)) { write(1, "Invalid field\n", 14); return (0); } else if (value_size(line) > header->fields[command->field].value_size) { write(1, "Value size is too large\n", 24); return (0); } else if (!get_value(line, command, header)) return (0); return (1); } return (0); } int get_next_command(struct s_command *command, struct s_header *header) { char *line; int ret; ret = 0; ft_bzero(command, sizeof(*command)); while (ret != 1) { if (-1 == get_next_line(&line)) break ; ret = parse_commmand(line, command, header); free(line); if (ret == -1) break ; } return (ret); }
#!/usr/bin/env python3 # encoding: utf-8 import gym import platform import numpy as np from gym.spaces import (Box, Discrete, Tuple) from typing import Dict from copy import deepcopy from rls.utils.display import colorize from rls.utils.logging_utils import get_logger logger = get_logger(__name__) try: import gym_minigrid except ImportError: logger.warning(colorize("import gym_minigrid failed, using 'pip3 install gym-minigrid' install it.", color='yellow')) pass try: # if wanna render, added 'renders=True' or(depends on env) 'render=True' in gym.make() function manually. import pybullet_envs except ImportError: logger.warning(colorize("import pybullet_envs failed, using 'pip3 install PyBullet' install it.", color='yellow')) pass try: import gym_donkeycar except ImportError: logger.warning(colorize("import gym_minigrid failed, using 'pip install gym_donkeycar' install it.", color='yellow')) pass try: import highway_env except ImportError: logger.warning(colorize("import highway_env failed, using 'pip install --user git+https://github.com/eleurent/highway-env' install it.", color='yellow')) pass from rls.envs.gym_wrapper.utils import build_env from rls.utils.np_utils import int2action_index from rls.utils.indexs import SingleAgentEnvArgs class gym_envs(object): def __init__(self, config: Dict): ''' Input: gym_env_name: gym training environment id, i.e. CartPole-v0 n: environment number render_mode: mode of rendering, optional: first, last, all, random_[num] -> i.e. random_2, [list] -> i.e. [0, 2, 4] ''' self.n = config['env_num'] # environments number render_mode = config.get('render_mode', 'first') self.info_env = build_env(config) self._initialize(env=self.info_env) self.info_env.close() del self.info_env # Import gym env vectorize wrapper class if config['vector_env_type'] == 'multiprocessing': from rls.envs.gym_wrapper.multiprocessing_wrapper import MultiProcessingEnv as AsynVectorEnvClass elif config['vector_env_type'] == 'threading': from rls.envs.gym_wrapper.threading_wrapper import MultiThreadEnv as AsynVectorEnvClass elif config['vector_env_type'] == 'ray': import platform # TODO: check it assert platform.system() != "Windows", 'Ray wrapper can be used in non-windows systems.' from rls.envs.gym_wrapper.ray_wrapper import RayEnv as AsynVectorEnvClass elif config['vector_env_type'] == 'vector': from rls.envs.gym_wrapper.vector_wrapper import VectorEnv as AsynVectorEnvClass else: raise Exception('The vector_env_type of gym in config.yaml doesn\'in the list of [multiprocessing, threading, ray, vector]. Please check your configurations.') self.envs = AsynVectorEnvClass(build_env, config, self.n, config['env_seed']) self._get_render_index(render_mode) def _initialize(self, env): assert isinstance(env.observation_space, (Box, Discrete)) and isinstance(env.action_space, (Box, Discrete)), 'action_space and observation_space must be one of available_type' # process observation ObsSpace = env.observation_space if isinstance(ObsSpace, Box): self.s_dim = ObsSpace.shape[0] if len(ObsSpace.shape) == 1 else 0 # self.obs_high = ObsSpace.high # self.obs_low = ObsSpace.low else: self.s_dim = int(ObsSpace.n) if len(ObsSpace.shape) == 3: self.obs_type = 'visual' self.visual_sources = 1 self.visual_resolutions = list(ObsSpace.shape) else: self.obs_type = 'vector' self.visual_sources = 0 self.visual_resolutions = [] # process action ActSpace = env.action_space if isinstance(ActSpace, Box): assert len(ActSpace.shape) == 1, 'if action space is continuous, the shape length of action must equal to 1' self.action_type = 'continuous' self._is_continuous = True self.a_dim = ActSpace.shape[0] elif isinstance(ActSpace, Tuple): assert all([isinstance(i, Discrete) for i in ActSpace]) == True, 'if action space is Tuple, each item in it must have type Discrete' self.action_type = 'Tuple(Discrete)' self._is_continuous = False self.a_dim = int(np.asarray([i.n for i in ActSpace]).prod()) self.discrete_action_dim_list = [i.n for i in ActSpace] else: self.action_type = 'discrete' self._is_continuous = False self.a_dim = env.action_space.n self.discrete_action_dim_list = [env.action_space.n] self.reward_threshold = env.env.spec.reward_threshold # reward threshold refer to solved self.EnvSpec = SingleAgentEnvArgs( s_dim=self.s_dim, a_dim=self.a_dim, visual_sources=self.visual_sources, visual_resolutions=self.visual_resolutions, is_continuous=self._is_continuous, n_agents=self.n ) @property def is_continuous(self): return self._is_continuous def _get_render_index(self, render_mode): ''' get render windows list, i.e. [0, 1] when there are 4 training enviornment. ''' assert isinstance(render_mode, (list, str)), 'render_mode must have type of str or list.' if isinstance(render_mode, list): assert all([isinstance(i, int) for i in render_mode]), 'items in render list must have type of int' assert min(index) >= 0, 'index must larger than zero' assert max(index) <= self.n, 'render index cannot larger than environment number.' self.render_index = render_mode elif isinstance(render_mode, str): if render_mode == 'first': self.render_index = [0] elif render_mode == 'last': self.render_index = [-1] elif render_mode == 'all': self.render_index = [i for i in range(self.n)] else: a, b = render_mode.split('_') if a == 'random' and 0 < int(b) <= self.n: import random self.render_index = random.sample([i for i in range(self.n)], int(b)) else: raise Exception('render_mode must be first, last, all, [list] or random_[num]') def render(self, record=False): ''' render game windows. ''' self.envs.render(record, self.render_index) def close(self): ''' close all environments. ''' self.envs.close() def sample_actions(self): ''' generate random actions for all training environment. ''' return np.asarray(self.envs.sample()) def reset(self): obs = np.asarray(self.envs.reset()) if self.obs_type == 'visual': obs = obs[:, np.newaxis, ...] return obs def step(self, actions): actions = np.array(actions) if not self.is_continuous: actions = int2action_index(actions, self.discrete_action_dim_list) if self.action_type == 'discrete': actions = actions.reshape(-1,) elif self.action_type == 'Tuple(Discrete)': actions = actions.reshape(self.n, -1).tolist() results = self.envs.step(actions) obs, reward, done, info = [np.asarray(e) for e in zip(*results)] reward = reward.astype('float32') dones_index = np.where(done)[0] if dones_index.shape[0] > 0: correct_new_obs = self.partial_reset(obs, dones_index) else: correct_new_obs = obs if self.obs_type == 'visual': obs = obs[:, np.newaxis, ...] correct_new_obs = correct_new_obs[:, np.newaxis, ...] return obs, reward, done, info, correct_new_obs def partial_reset(self, obs, dones_index): correct_new_obs = deepcopy(obs) partial_obs = np.asarray(self.envs.reset(dones_index.tolist())) correct_new_obs[dones_index] = partial_obs return correct_new_obs
# USAGE: # sash machine-name - connects via SSH to a machine in your Amazon account with this machine name # function private_dns_to_name { if [ -z $1 ]; then echo "Please enter private dns (ip-10-0-0-XX)" return 1 fi local instance_id instance_name instance_id=$(aws ec2 describe-instances --filter "Name=private-dns-name,Values=$1.*" --query "Reservations[*].Instances[*].InstanceId" --output text) if [ -z $instance_id ]; then instance_id=$(aws ec2 describe-instances --filter "Name=private-dns-name,Values=$1*" --query "Reservations[*].Instances[*].InstanceId" --output text) fi if [ -z $instance_id ]; then echo "No machine found with private dns $1" fi instance_name=$(aws ec2 describe-tags --filter "Name=key,Values=Name" "Name=resource-id,Values=$instance_id" --query "Tags[].Value" --output text) echo $instance_name } # connect to machine function sash { if [ -z $1 ]; then echo "Please enter machine name" return 1 fi local instance ip pem instance=$(aws ec2 describe-instances --filters "Name=tag:Name,Values=$1" --query 'Reservations[*].Instances[].[KeyName,PublicIpAddress]' --output text) if [ -z "${instance}" ]; then echo Could not find an instance named $1 return 1 else ip=$(echo $instance | awk '{print $2}') pem=$(echo $instance | awk '{print $1}') echo "Connecting to $1 ($ip)" ssh -i ~/.aws/$pem.pem ubuntu@$ip fi } function clear_sash { unset -v _sash_instances } # completion command function _sash { if [ -z "${_sash_instances}" ]; then _sash_instances="$( aws ec2 describe-tags --filter Name=key,Values=Name Name=resource-type,Values=instance --query Tags[].Value --output text )" fi local curw COMPREPLY=() curw=${COMP_WORDS[COMP_CWORD]} COMPREPLY=($(compgen -W "${_sash_instances}" -- $curw)) return 0 } complete -F _sash sash
package io.github.rcarlosdasilva.weixin.model.request.user; import com.google.common.base.Strings; import io.github.rcarlosdasilva.weixin.common.ApiAddress; import io.github.rcarlosdasilva.weixin.model.request.base.BasicWeixinRequest; /** * 获取用户列表请求模型 * * @author <a href="mailto:<EMAIL>"><NAME></a> */ public class UserOpenIdListRequest extends BasicWeixinRequest { private String nextOpenId; public UserOpenIdListRequest() { this.path = ApiAddress.URL_USER_ALL_OPENID_LIST; } /** * 第一个拉取的OpenId. * * @param nextOpenId * open_id */ public void setNextOpenId(String nextOpenId) { this.nextOpenId = nextOpenId; } @Override public String toString() { StringBuilder sb = new StringBuilder(this.path).append("?access_token=") .append(this.accessToken); if (!Strings.isNullOrEmpty(this.nextOpenId)) { sb.append("&next_openid=").append(this.nextOpenId); } return sb.toString(); } }
docker run -d -h $HOSTNAME -v /mnt/media/music/Spotify-Ripper:/data --name spotify-ripper darrenwatt/spotify-ripper
#!/bin/bash ########################################################################## # LICENSE CDDL 1.0 + GPL 2.0 # # Author M. Ritschel # Company Trivadis GmbH Hamburg # Date 08.03.2017 # Copyright (c) 1982-2017 Trivadis GmbH. All rights reserved. # # Docker Basis Oracle Database # ------------------------------ # Database Start-Script # # ########################################################################## source $SCRIPT_DIR/colorecho # Check that ORACLE_HOME is set if [ "$ORACLE_HOME" == "" ]; then script_name=`basename "$0"` echo_yellow "$script_name: ERROR - ORACLE_HOME is not set. Please set ORACLE_HOME and PATH before invoking this script." exit 1; fi; # Start Listener lsnrctl start # Start database sqlplus / as sysdba << EOF STARTUP; EOF
#!/bin/bash echo "Format validation is not yet enabled for DiligentFX module on MacOS"
#!/usr/bin/env bash composer install PL_PLATFORM="${1:-"PRO"}" export PL_PLATFORM xdg-open http://localhost:7000/Views/$PL_PLATFORM/index.php cd $PWD/src && php -S localhost:7000
def is_increasing_sequence(array): previous = array[0] for current in array[1:]: if current <= previous: return False previous = current return True
if [ -f "${name}" ]; then # File already present, need to update it # Add your update logic here else # File not present, need to clone it # Add your clone logic here fi
require 'rspec/given' require 'spec_helper' describe Given::NaturalAssertion do before do pending "Natural Assertions disabled for JRuby" unless Given::NATURAL_ASSERTIONS_SUPPORTED end describe "#content?" do context "with empty block" do FauxThen { } Then { expect(na).to_not have_content } end context "with block returning false" do FauxThen { false } Then { expect(na).to have_content } end end describe "passing criteria" do context "with true" do FauxThen { true } Then { _gvn_block_passed?(faux_block) } end context "with false" do FauxThen { false } Then { ! _gvn_block_passed?(faux_block) } end context "with to_bool/true" do Given(:res) { double(:to_bool => true) } FauxThen { res } Then { _gvn_block_passed?(faux_block) } end context "with to_bool/false" do Given(:res) { double(:to_bool => false) } FauxThen { res } Then { ! _gvn_block_passed?(faux_block) } end end describe "failure messages" do let(:msg) { na.message } Invariant { expect(msg).to match(/^FauxThen expression/) } context "with equals assertion" do Given(:a) { 1 } FauxThen { a == 2 } Then { expect(msg).to match(/\bexpected: +1\b/) } Then { expect(msg).to match(/\bto equal: +2\b/) } Then { expect(msg).to match(/\bfalse +<- +a == 2\b/) } Then { expect(msg).to match(/\b1 +<- +a\b/) } end context "with equals assertion with do/end" do Given(:a) { 1 } FauxThen do a == 2 end Then { expect(msg).to match(/\bexpected: +1\b/) } Then { expect(msg).to match(/\bto equal: +2\b/) } Then { expect(msg).to match(/\bfalse +<- +a == 2\b/) } Then { expect(msg).to match(/\b1 +<- +a\b/) } end context "with not-equals assertion" do Given(:a) { 1 } FauxThen { a != 1 } Then { expect(msg).to match(/\bexpected: +1\b/) } Then { expect(msg).to match(/\bto not equal: +1\b/) } Then { expect(msg).to match(/\bfalse +<- +a != 1\b/) } Then { expect(msg).to match(/\b1 +<- +a\b/) } end context "with less than assertion" do Given(:a) { 1 } FauxThen { a < 1 } Then { expect(msg).to match(/\bexpected: +1\b/) } Then { expect(msg).to match(/\bto be less than: +1\b/) } Then { expect(msg).to match(/\bfalse +<- +a < 1\b/) } Then { expect(msg).to match(/\b1 +<- +a\b/) } end context "with less than or equal to assertion" do Given(:a) { 1 } FauxThen { a <= 0 } Then { expect(msg).to match(/\bexpected: +1\b/) } Then { expect(msg).to match(/\bto be less or equal to: +0\b/) } Then { expect(msg).to match(/\bfalse +<- +a <= 0\b/) } Then { expect(msg).to match(/\b1 +<- +a\b/) } end context "with greater than assertion" do Given(:a) { 1 } FauxThen { a > 1 } Then { expect(msg).to match(/\bexpected: +1\b/) } Then { expect(msg).to match(/\bto be greater than: +1\b/) } Then { expect(msg).to match(/\bfalse +<- +a > 1\b/) } Then { expect(msg).to match(/\b1 +<- +a\b/) } end context "with greater than or equal to assertion" do Given(:a) { 1 } FauxThen { a >= 3 } Then { expect(msg).to match(/\bexpected: +1\b/) } Then { expect(msg).to match(/\bto be greater or equal to: +3\b/) } Then { expect(msg).to match(/\bfalse +<- +a >= 3\b/) } Then { expect(msg).to match(/\b1 +<- +a\b/) } end context "with match assertion" do Given(:s) { "Hello" } FauxThen { s =~ /HI/ } Then { expect(msg).to match(/\bexpected: +"Hello"$/) } Then { expect(msg).to match(/\bto match: +\/HI\/$/) } Then { expect(msg).to match(/\bnil +<- +s =~ \/HI\/$/) } Then { expect(msg).to match(/"Hello" +<- +s$/) } end context "with not match assertion" do Given(:s) { "Hello" } FauxThen { s !~ /Hello/ } Then { expect(msg).to match(/\bexpected: +"Hello"$/) } Then { expect(msg).to match(/\bto not match: +\/Hello\/$/) } Then { expect(msg).to match(/\bfalse +<- +s !~ \/Hello\/$/) } Then { expect(msg).to match(/"Hello" +<- +s$/) } end context "with exception" do Given(:ary) { nil } FauxThen { ary[1] == 3 } Then { expect(msg).to match(/\bexpected: +NoMethodError/) } Then { expect(msg).to match(/\bto equal: +3$/) } Then { expect(msg).to match(/\bNoMethodError.+NilClass\n +<- +ary\[1\] == 3$/) } Then { expect(msg).to match(/\bNoMethodError.+NilClass\n +<- +ary\[1\]$/) } Then { expect(msg).to match(/\bnil +<- +ary$/) } end context "with value with newlines" do class FunkyInspect def inspect "XXXX\nYYYY" end def ok? false end end Given(:zzzz) { FunkyInspect.new } FauxThen { zzzz.ok? } Then { expect(msg).to match(/\n false <- zzzz\.ok\?/) } Then { expect(msg).to match(/\n XXXX\n/) } Then { expect(msg).to match(/\n YYYY\n/) } Then { expect(msg).to match(/\n <- zzzz$/) } end end describe "bad Then blocks" do context "with no statements" do FauxThen { } When(:result) { na.message } Then { expect(result).to_not have_failed } end context "with multiple statements" do FauxThen { ary = nil ary[1] == 3 } When(:result) { na.message } Then { expect(result).to have_failed(Given::InvalidThenError, /multiple.*statements/i) } end end end
<gh_stars>1-10 package cn.cerc.jexport.excel; public class ColumnTest { }
from django.test import TestCase from ...generic.tests.test_serializers import ResourceSerializerMixin from ..factories import TagFactory from ..serializers import TagSerializer class TagSerializerTestCase(ResourceSerializerMixin, TestCase): serializer_class = TagSerializer factory_class = TagFactory
import React from 'react'; import { StyleSheet, Text, View, TouchableOpacity, FlatList, CheckBox } from 'react-native'; const App = () => { const [tasks, setTasks] = React.useState([ { id: '1', title: 'Task 1', isComplete: false }, { id: '2', title: 'Task 2', isComplete: false }, { id: '3', title: 'Task 3', isComplete: false } ]); const handlePress = id => { setTasks( tasks.map(task => { if (task.id === id){ return { ...task, isComplete: !task.isComplete }; } return task; }) ); }; return ( <View style={styles.container}> <FlatList data={tasks} keyExtractor={item => item.id} renderItem={({ item }) => ( <TouchableOpacity onPress={() => handlePress(item.id)}> <View style={styles.row}> <CheckBox value={item.isComplete} onValueChange={() => handlePress(item.id)} style={styles.checkBox} /> <Text style={styles.text}>{item.title}</Text> </View> </TouchableOpacity> )} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, row: { flexDirection: 'row', alignItems: 'center', paddingVertical: 10 }, checkBox: { marginHorizontal: 10 }, text: { fontSize: 18 } }); export default App;
package org.multibit.hd.core.wallet; /** * Copyright 2015 multibit.org * * Licensed under the MIT license (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.google.common.base.Optional; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.bitcoinj.core.*; import org.bitcoinj.crypto.MnemonicCode; import org.joda.time.DateTime; import org.joda.time.Days; import org.joda.time.Hours; import org.joda.time.Minutes; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.multibit.commons.files.SecureFiles; import org.multibit.commons.utils.Dates; import org.multibit.hd.brit.core.seed_phrase.Bip39SeedPhraseGenerator; import org.multibit.hd.brit.core.seed_phrase.SeedPhraseGenerator; import org.multibit.hd.core.config.Configurations; import org.multibit.hd.core.dto.WalletIdTest; import org.multibit.hd.core.dto.WalletSummary; import org.multibit.hd.core.events.ShutdownEvent; import org.multibit.hd.core.managers.BackupManager; import org.multibit.hd.core.managers.InstallationManager; import org.multibit.hd.core.managers.WalletManager; import org.multibit.hd.core.services.CoreServices; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import static org.bitcoinj.core.Coin.COIN; import static org.bitcoinj.testing.FakeTxBuilder.createFakeTx; import static org.fest.assertions.Assertions.assertThat; public class UnconfirmedTransactionDetectorTest { private static final Logger log = LoggerFactory.getLogger(UnconfirmedTransactionDetectorTest.class); private NetworkParameters mainNet; private Wallet wallet; private ECKey myKey; private Address myAddress; @SuppressFBWarnings({"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", "NP_NONNULL_PARAM_VIOLATION"}) @Before public void setUp() throws Exception { InstallationManager.unrestricted = true; Configurations.currentConfiguration = Configurations.newDefaultConfiguration(); // Start the core services CoreServices.main(null); mainNet = NetworkParameters.fromID(NetworkParameters.ID_MAINNET); assertThat(mainNet).isNotNull(); } @After public void tearDown() throws Exception { // Order is important here CoreServices.shutdownNow(ShutdownEvent.ShutdownType.SOFT); InstallationManager.shutdownNow(ShutdownEvent.ShutdownType.SOFT); BackupManager.INSTANCE.shutdownNow(); WalletManager.INSTANCE.shutdownNow(ShutdownEvent.ShutdownType.HARD); } @Test public void testWindowOfInterest() throws Exception { // Get the application directory File applicationDirectory = SecureFiles.createTemporaryDirectory(); WalletManager walletManager = WalletManager.INSTANCE; BackupManager.INSTANCE.initialise(applicationDirectory, Optional.<File>absent()); byte[] entropy = MnemonicCode.INSTANCE.toEntropy(Bip39SeedPhraseGenerator.split(WalletIdTest.SEED_PHRASE_1)); SeedPhraseGenerator seedGenerator = new Bip39SeedPhraseGenerator(); byte[] seed = seedGenerator.convertToSeed(Bip39SeedPhraseGenerator.split(WalletIdTest.SEED_PHRASE_1)); long nowInSeconds = Dates.nowInSeconds(); WalletSummary walletSummary = walletManager .getOrCreateMBHDSoftWalletSummaryFromEntropy( applicationDirectory, entropy, seed, nowInSeconds, "credentials", "Example", "Example", false); // No need to sync assertThat(walletSummary).isNotNull(); assertThat(walletSummary.getWallet()).isNotNull(); wallet = walletSummary.getWallet(); myKey = wallet.currentReceiveKey(); myAddress = myKey.toAddress(mainNet); DateTime now = Dates.nowUtc(); // There are no unconfirmed transactions in the wallet so there should be no replay date Optional<DateTime> replayDate = UnconfirmedTransactionDetector.calculateReplayDate(wallet, now); assertThat(!replayDate.isPresent()).isTrue(); // Receive some unconfirmed coin Transaction unconfirmedTransaction = sendMoneyToWallet(); assertThat(unconfirmedTransaction).isNotNull(); // The unconfirmed transaction is dated "now" so WILL NOT in the window of interest (4 hours old to 4 days old) replayDate = UnconfirmedTransactionDetector.calculateReplayDate(wallet, now); assertThat(!replayDate.isPresent()).isTrue(); // The unconfirmed transaction WILL be of interest in 4 hours plus a minute replayDate = UnconfirmedTransactionDetector.calculateReplayDate(wallet, now.plus(Hours.FOUR).plus(Minutes.ONE)); assertThat(replayDate.isPresent()).isTrue(); assertThat(replayDate.get().toDate()).isEqualTo(unconfirmedTransaction.getUpdateTime()); // The unconfirmed transaction WILL be of interest in 4 days minus a minute replayDate = UnconfirmedTransactionDetector.calculateReplayDate(wallet, now.plus(Days.FOUR).minus(Minutes.ONE)); assertThat(replayDate.isPresent()).isTrue(); assertThat(replayDate.get().toDate()).isEqualTo(unconfirmedTransaction.getUpdateTime()); // The unconfirmed transaction WILL NOT be of interest in 4 days plus a minute replayDate = UnconfirmedTransactionDetector.calculateReplayDate(wallet, now.plus(Days.FOUR).plus(Minutes.ONE)); assertThat(!replayDate.isPresent()).isTrue(); } private Transaction sendMoneyToWallet() throws VerificationException { Transaction tx = createFakeTx(mainNet, COIN, myAddress); // Pending/broadcast tx. if (wallet.isPendingTransactionRelevant(tx)) { wallet.receivePending(tx, null); } return wallet.getTransaction(tx.getHash()); // Can be null if tx is a double spend that's otherwise irrelevant. } }
<gh_stars>0 import axios from 'axios'; import { FC, useState } from 'react'; import { useParams } from 'react-router-dom'; import IssueContributorsGallery from '../../../components/Issue/Contributor/IssueContributorsGallery'; import { useMountEffect } from '../../../hooks/useMountEffect'; import { UserTemplate } from '../../../types/ModelContentTemplate'; import { INestedIssue, IUser } from '../../../types/ModelTypes'; interface ManageContributorsProps { issue: INestedIssue, displayOnly: boolean, } const ManageContributors: FC<ManageContributorsProps> = (props) => { const { projectId } = useParams<{ projectId: string }>(); const [projectContributors, setProjectContributors] = useState<[IUser]>([UserTemplate]); useMountEffect(fetchContributors); function fetchContributors() { // necessary for displaying archived issue without contributors if(!props.displayOnly) { axios.get(`/users/getUsersByProject/${projectId}`) .then(resp => { setProjectContributors(resp.data); }).catch((err) => { console.log(err); });; } } function updateContributors() { const contributorsToId = props.issue.contributors.map(contributor => contributor._id); const requestBody = { contributors: contributorsToId, } axios.post(`/issues/update/${props.issue._id}`, requestBody) .catch((err) => { console.log(err); }) } return ( <IssueContributorsGallery projectContributors={projectContributors} issue={props.issue} updateContributors={updateContributors} /> ); } export default ManageContributors;
<reponame>Rodrigoplp/gift-card-server const Merchant = require('mongoose').model('Merchant'); const localStrategy = require('passport-local').Strategy; module.exports = new localStrategy({ usernameField: 'merchant_email', passwordField: 'password', session: false, passReqToCallback: true }, (req, email, password, done) => { const userData = { merchant_email: email.trim(), password: <PASSWORD>(), merchant_name: req.body.merchant_name.trim(), number: req.body.number }; const newMerchant = new Merchant(userData); newMerchant.save((err, doc) => { if (err) { console.log('Err: ' + err); return done(err); } return done(null, doc); }); });
docker rm user-interface docker rmi vulcans/user-interface docker build -t vulcans/user-interface . && docker-compose up
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const validator_1 = __importDefault(require("../utils/validator")); const languages_1 = require("../utils/languages"); const { exec } = require('child_process'); const fs = require('fs'); const rimraf = require('rimraf'); let tempPath = '../temp/'; if (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'circle') tempPath = './temp/'; function createDirectory(data, lang, callback) { return __awaiter(this, void 0, void 0, function* () { const folder = `${tempPath}${data.uuid}`; fs.mkdir(folder, (folderErr) => { if (folderErr) console.log(folderErr); fs.writeFile(`${folder}/input.txt`, data.stdin, (inputErr) => { if (inputErr) console.log(inputErr); fs.writeFile(`${folder}/output.txt`, '', (outputErr) => { if (outputErr) console.log(outputErr); fs.writeFile(`${folder}/source.${lang.extension}`, data.code, (codeErr) => { if (codeErr) console.log(codeErr); callback(); }); }); }); }); }); } function runCode(data, callback) { return __awaiter(this, void 0, void 0, function* () { const errors = validator_1.default(data); if (errors.length > 0) console.log(errors); else { const language = languages_1.languageNameFromAlias(data.lang); if (language) { createDirectory(data, language, () => { const args = `./temp/${data.uuid}/source.${language.extension} ${language.name} ${language.timeout} ${language.compiled} ${language.compileCmd} ${language.runCmd} ${language.runFile} ${language.outputFile}`; let command = `cd ..&&python3 execute.py ${args}`; if (process.env.NODE_ENV === 'test') command = `python3 execute.py ${args}`; exec(command, (execErr, stdout, stderr) => { if (execErr) console.log(execErr); fs.readFile(`${tempPath}${data.uuid}/output.txt`, 'utf8', (readErr, content) => { if (readErr) console.log(readErr); const result = { output: content, stderr, status: stdout, submissionID: data.uuid ? data.uuid : 0 }; callback(result); }); rimraf(`${tempPath}${data.uuid}`, (delErr) => { if (delErr) console.log(delErr); }); }); }); } } }); } exports.default = runCode;
const mongoose = require("mongoose"); const Schema = mongoose.Schema; /** * Cart model * @type {"mongoose".Schema} */ const cartSchema = new Schema({ qrCode: { type: String, required: true, unique: true }, store: { type: mongoose.Schema.Types.ObjectId, ref: "Store", required: [true, "Store is required"] }, model: { type: String, enum: ["BASKET", "CART"], required: true, default: "CART" } }); cartSchema.index({ qrCode: 1, store: 1}, { unique: true }); export const Cart = mongoose.model("Cart", cartSchema );
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.testgrid.deployment.tinkerer.websocket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import javax.websocket.CloseReason; import javax.websocket.Session; /** * This class represents common web socket endpoint to manage Remote Sessions. * * @since 1.0.0 */ public class SubscriptionEndpoint { private static final Logger logger = LoggerFactory.getLogger(SubscriptionEndpoint.class); /** * Web socket onOpen use when client connect to web socket url. * * @param session - Web socket Session * @param clientId - client Identifier */ public void onOpen(Session session, String clientId) { if (logger.isDebugEnabled()) { logger.debug("Web Socket open from client with RemoteSession id: " + session.getId() + " client id: " + clientId); } } /** * Web socket onMessage - When client sends a message. * * @param session - Registered session. * @param message - String Message which needs to send to peer. * @param clientId - client Identifier. */ public void onMessage(Session session, String message, String clientId) { if (logger.isDebugEnabled()) { logger.debug("Received message from client for RemoteSession id: " + session.getId() + " client id: " + clientId); } } /** * Web socket onMessage use When client sends a message. * * @param session - Registered session. * @param clientId - client Identifier. * @param message - Byte Message which needs to send to peer. */ public void onMessage(Session session, byte[] message, String clientId) { if (logger.isDebugEnabled()) { logger.debug("Received message from client for RemoteSession id: " + session.getId() + " client id: " + clientId); } } /** * Web socket onClose use to handle socket connection close. * * @param session - Registered session. * @param clientId - client Identifier. * @param reason - Status code for web-socket close. */ public void onClose(Session session, CloseReason reason, String clientId) { if (logger.isDebugEnabled()) { logger.debug("Web Socket closed due to " + reason.getReasonPhrase() + ", for session ID:" + session.getId() + ", for request URI - " + session.getRequestURI() + " client id: " + clientId); } } /** * Web socket onError use to handle socket connection error. * * @param session - Registered session. * @param throwable - Web socket exception. * @param clientId - client Identifier. */ public void onError(Session session, Throwable throwable, String clientId) { if (throwable instanceof IOException) { // This is normal if client terminated without graceful shutdown. logger.warn("Client connection lost. " + throwable.getMessage()); if (logger.isDebugEnabled()) { logger.debug("Error occurred in session ID: " + session.getId() + ", client id: " + clientId + ", for request URI - " + session.getRequestURI() + ", " + throwable.getMessage(), throwable); } } else { logger.error("Error occurred in session ID: " + session.getId() + ", client id: " + clientId + ", for request URI - " + session.getRequestURI() + ", " + throwable.getMessage(), throwable); } try { if (session.isOpen()) { session.close(new CloseReason(CloseReason.CloseCodes.PROTOCOL_ERROR, "Unexpected Error Occurred")); } } catch (IOException ex) { // This is normal if client terminated without graceful shutdown. logger.warn("Failed to disconnect the client. " + ex.getMessage()); if (logger.isDebugEnabled()) { logger.debug("Error details:", ex); } } } }
import { basename } from "https://deno.land/std@0.122.0/path/mod.ts"; import { Service } from '../service.ts'; import { Payload, Client } from '../client.ts'; import { AppwriteException } from '../exception.ts'; import type { Models } from '../models.d.ts'; export type UploadProgress = { $id: string; progress: number; sizeUploaded: number; chunksTotal: number; chunksUploaded: number; } export class Account extends Service { /** * Get Account * * Get currently logged in user data as JSON object. * * @throws {AppwriteException} * @returns {Promise} */ async get<Preferences extends Models.Preferences>(): Promise<Models.User<Preferences>> { let path = '/account'; let payload: Payload = {}; return await this.client.call('get', path, { 'content-type': 'application/json', }, payload); } /** * Delete Account * * Delete a currently logged in user account. Behind the scene, the user * record is not deleted but permanently blocked from any access. This is done * to avoid deleted accounts being overtaken by new users with the same email * address. Any user-related resources like documents or storage files should * be deleted separately. * * @throws {AppwriteException} * @returns {Promise} */ async delete(): Promise<Response> { let path = '/account'; let payload: Payload = {}; return await this.client.call('delete', path, { 'content-type': 'application/json', }, payload); } /** * Update Account Email * * Update currently logged in user account email address. After changing user * address, the user confirmation status will get reset. A new confirmation * email is not sent automatically however you can use the send confirmation * email endpoint again to send the confirmation email. For security measures, * user password is required to complete this request. * This endpoint can also be used to convert an anonymous account to a normal * one, by passing an email address and a new password. * * * @param {string} email * @param {string} password * @throws {AppwriteException} * @returns {Promise} */ async updateEmail<Preferences extends Models.Preferences>(email: string, password: string): Promise<Models.User<Preferences>> { if (typeof email === 'undefined') { throw new AppwriteException('Missing required parameter: "email"'); } if (typeof password === 'undefined') { throw new AppwriteException('Missing required parameter: "password"'); } let path = '/account/email'; let payload: Payload = {}; if (typeof email !== 'undefined') { payload['email'] = email; } if (typeof password !== 'undefined') { payload['password'] = password; } return await this.client.call('patch', path, { 'content-type': 'application/json', }, payload); } /** * Get Account Logs * * Get currently logged in user list of latest security activity logs. Each * log returns user IP address, location and date and time of log. * * @param {number} limit * @param {number} offset * @throws {AppwriteException} * @returns {Promise} */ async getLogs(limit?: number, offset?: number): Promise<Models.LogList> { let path = '/account/logs'; let payload: Payload = {}; if (typeof limit !== 'undefined') { payload['limit'] = limit; } if (typeof offset !== 'undefined') { payload['offset'] = offset; } return await this.client.call('get', path, { 'content-type': 'application/json', }, payload); } /** * Update Account Name * * Update currently logged in user account name. * * @param {string} name * @throws {AppwriteException} * @returns {Promise} */ async updateName<Preferences extends Models.Preferences>(name: string): Promise<Models.User<Preferences>> { if (typeof name === 'undefined') { throw new AppwriteException('Missing required parameter: "name"'); } let path = '/account/name'; let payload: Payload = {}; if (typeof name !== 'undefined') { payload['name'] = name; } return await this.client.call('patch', path, { 'content-type': 'application/json', }, payload); } /** * Update Account Password * * Update currently logged in user password. For validation, user is required * to pass in the new password, and the old password. For users created with * OAuth and Team Invites, oldPassword is optional. * * @param {string} password * @param {string} oldPassword * @throws {AppwriteException} * @returns {Promise} */ async updatePassword<Preferences extends Models.Preferences>(password: string, oldPassword?: string): Promise<Models.User<Preferences>> { if (typeof password === 'undefined') { throw new AppwriteException('Missing required parameter: "password"'); } let path = '/account/password'; let payload: Payload = {}; if (typeof password !== '<PASSWORD>') { payload['password'] = password; } if (typeof oldPassword !== 'undefined') { payload['oldPassword'] = <PASSWORD>; } return await this.client.call('patch', path, { 'content-type': 'application/json', }, payload); } /** * Get Account Preferences * * Get currently logged in user preferences as a key-value object. * * @throws {AppwriteException} * @returns {Promise} */ async getPrefs<Preferences extends Models.Preferences>(): Promise<Preferences> { let path = '/account/prefs'; let payload: Payload = {}; return await this.client.call('get', path, { 'content-type': 'application/json', }, payload); } /** * Update Account Preferences * * Update currently logged in user account preferences. The object you pass is * stored as is, and replaces any previous value. The maximum allowed prefs * size is 64kB and throws error if exceeded. * * @param {object} prefs * @throws {AppwriteException} * @returns {Promise} */ async updatePrefs<Preferences extends Models.Preferences>(prefs: object): Promise<Models.User<Preferences>> { if (typeof prefs === 'undefined') { throw new AppwriteException('Missing required parameter: "prefs"'); } let path = '/account/prefs'; let payload: Payload = {}; if (typeof prefs !== 'undefined') { payload['prefs'] = prefs; } return await this.client.call('patch', path, { 'content-type': 'application/json', }, payload); } /** * Create Password Recovery * * Sends the user an email with a temporary secret key for password reset. * When the user clicks the confirmation link he is redirected back to your * app password reset URL with the secret key and email address values * attached to the URL query string. Use the query string params to submit a * request to the [PUT * /account/recovery](/docs/client/account#accountUpdateRecovery) endpoint to * complete the process. The verification link sent to the user's email * address is valid for 1 hour. * * @param {string} email * @param {string} url * @throws {AppwriteException} * @returns {Promise} */ async createRecovery(email: string, url: string): Promise<Models.Token> { if (typeof email === 'undefined') { throw new AppwriteException('Missing required parameter: "email"'); } if (typeof url === 'undefined') { throw new AppwriteException('Missing required parameter: "url"'); } let path = '/account/recovery'; let payload: Payload = {}; if (typeof email !== 'undefined') { payload['email'] = email; } if (typeof url !== 'undefined') { payload['url'] = url; } return await this.client.call('post', path, { 'content-type': 'application/json', }, payload); } /** * Create Password Recovery (confirmation) * * Use this endpoint to complete the user account password reset. Both the * **userId** and **secret** arguments will be passed as query parameters to * the redirect URL you have provided when sending your request to the [POST * /account/recovery](/docs/client/account#accountCreateRecovery) endpoint. * * Please note that in order to avoid a [Redirect * Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md) * the only valid redirect URLs are the ones from domains you have set when * adding your platforms in the console interface. * * @param {string} userId * @param {string} secret * @param {string} password * @param {string} passwordAgain * @throws {AppwriteException} * @returns {Promise} */ async updateRecovery(userId: string, secret: string, password: string, passwordAgain: string): Promise<Models.Token> { if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } if (typeof secret === 'undefined') { throw new AppwriteException('Missing required parameter: "secret"'); } if (typeof password === '<PASSWORD>') { throw new AppwriteException('Missing required parameter: "password"'); } if (typeof passwordAgain === 'undefined') { throw new AppwriteException('Missing required parameter: "passwordAgain"'); } let path = '/account/recovery'; let payload: Payload = {}; if (typeof userId !== 'undefined') { payload['userId'] = userId; } if (typeof secret !== 'undefined') { payload['secret'] = secret; } if (typeof password !== '<PASSWORD>') { payload['password'] = password; } if (typeof passwordAgain !== 'undefined') { payload['passwordAgain'] = passwordAgain; } return await this.client.call('put', path, { 'content-type': 'application/json', }, payload); } /** * Get Account Sessions * * Get currently logged in user list of active sessions across different * devices. * * @throws {AppwriteException} * @returns {Promise} */ async getSessions(): Promise<Models.SessionList> { let path = '/account/sessions'; let payload: Payload = {}; return await this.client.call('get', path, { 'content-type': 'application/json', }, payload); } /** * Delete All Account Sessions * * Delete all sessions from the user account and remove any sessions cookies * from the end client. * * @throws {AppwriteException} * @returns {Promise} */ async deleteSessions(): Promise<Response> { let path = '/account/sessions'; let payload: Payload = {}; return await this.client.call('delete', path, { 'content-type': 'application/json', }, payload); } /** * Get Session By ID * * Use this endpoint to get a logged in user's session using a Session ID. * Inputting 'current' will return the current session being used. * * @param {string} sessionId * @throws {AppwriteException} * @returns {Promise} */ async getSession(sessionId: string): Promise<Models.Session> { if (typeof sessionId === 'undefined') { throw new AppwriteException('Missing required parameter: "sessionId"'); } let path = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); let payload: Payload = {}; return await this.client.call('get', path, { 'content-type': 'application/json', }, payload); } /** * Update Session (Refresh Tokens) * * @param {string} sessionId * @throws {AppwriteException} * @returns {Promise} */ async updateSession(sessionId: string): Promise<Models.Session> { if (typeof sessionId === 'undefined') { throw new AppwriteException('Missing required parameter: "sessionId"'); } let path = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); let payload: Payload = {}; return await this.client.call('patch', path, { 'content-type': 'application/json', }, payload); } /** * Delete Account Session * * Use this endpoint to log out the currently logged in user from all their * account sessions across all of their different devices. When using the * Session ID argument, only the unique session ID provided is deleted. * * * @param {string} sessionId * @throws {AppwriteException} * @returns {Promise} */ async deleteSession(sessionId: string): Promise<Response> { if (typeof sessionId === 'undefined') { throw new AppwriteException('Missing required parameter: "sessionId"'); } let path = '/account/sessions/{sessionId}'.replace('{sessionId}', sessionId); let payload: Payload = {}; return await this.client.call('delete', path, { 'content-type': 'application/json', }, payload); } /** * Create Email Verification * * Use this endpoint to send a verification message to your user email address * to confirm they are the valid owners of that address. Both the **userId** * and **secret** arguments will be passed as query parameters to the URL you * have provided to be attached to the verification email. The provided URL * should redirect the user back to your app and allow you to complete the * verification process by verifying both the **userId** and **secret** * parameters. Learn more about how to [complete the verification * process](/docs/client/account#accountUpdateVerification). The verification * link sent to the user's email address is valid for 7 days. * * Please note that in order to avoid a [Redirect * Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md), * the only valid redirect URLs are the ones from domains you have set when * adding your platforms in the console interface. * * * @param {string} url * @throws {AppwriteException} * @returns {Promise} */ async createVerification(url: string): Promise<Models.Token> { if (typeof url === 'undefined') { throw new AppwriteException('Missing required parameter: "url"'); } let path = '/account/verification'; let payload: Payload = {}; if (typeof url !== 'undefined') { payload['url'] = url; } return await this.client.call('post', path, { 'content-type': 'application/json', }, payload); } /** * Create Email Verification (confirmation) * * Use this endpoint to complete the user email verification process. Use both * the **userId** and **secret** parameters that were attached to your app URL * to verify the user email ownership. If confirmed this route will return a * 200 status code. * * @param {string} userId * @param {string} secret * @throws {AppwriteException} * @returns {Promise} */ async updateVerification(userId: string, secret: string): Promise<Models.Token> { if (typeof userId === 'undefined') { throw new AppwriteException('Missing required parameter: "userId"'); } if (typeof secret === 'undefined') { throw new AppwriteException('Missing required parameter: "secret"'); } let path = '/account/verification'; let payload: Payload = {}; if (typeof userId !== 'undefined') { payload['userId'] = userId; } if (typeof secret !== 'undefined') { payload['secret'] = secret; } return await this.client.call('put', path, { 'content-type': 'application/json', }, payload); } }
import { Directive, ElementRef,OnInit, Output, EventEmitter } from '@angular/core'; import {} from '@types/googlemaps'; // const google = require('@types/googlemaps'); declare var google: any; @Directive({ selector: '[google-place]' }) export class GooglePlacesDirective implements OnInit { @Output() onSelect: EventEmitter<any> = new EventEmitter(); private element: HTMLInputElement; constructor(private elRef: ElementRef) { this.element = elRef.nativeElement; } ngOnInit() { setTimeout(()=> { const autocomplete = new google.maps.places.Autocomplete(this.element); google.maps.event.addListener(autocomplete, 'place_changed', () => { this.onSelect.emit(this.getFormattedAddress(autocomplete.getPlace())); }); }, 1000); } getFormattedAddress(place) { let location_obj = {}; console.log(place.geometry.location.lat(),"lat"); console.log(place.geometry.location.lng(),"lng"); location_obj['lat'] = place.geometry.location.lat(); location_obj['long'] = place.geometry.location.lng(); for (let i in place.address_components) { let item = place.address_components[i]; location_obj['formatted_address'] = place.formatted_address; if(item['types'].indexOf("locality") > -1) { location_obj['locality'] = item['long_name'] } else if (item['types'].indexOf("administrative_area_level_1") > -1) { location_obj['admin_area_l1'] = item['short_name'] } else if (item['types'].indexOf("street_number") > -1) { location_obj['street_number'] = item['short_name'] } else if (item['types'].indexOf("route") > -1) { location_obj['route'] = item['long_name'] } else if (item['types'].indexOf("country") > -1) { location_obj['country'] = item['long_name'] } else if (item['types'].indexOf("postal_code") > -1) { location_obj['postal_code'] = item['short_name'] } } console.log(location_obj); return location_obj; } }
package compile import "github.com/eddieowens/axon" type Package struct { } func (*Package) Bindings() []axon.Binding { return []axon.Binding{ axon.Bind(CmdKey).To().StructPtr(new(compileCmd)), } }
set -x # Elevate priviledges, retaining the environment. sudo -E su # Install dev tools. yum install -y "@Development Tools" python2-pip openssl-devel python-devel gcc libffi-devel # Get the OKD 3.11 installer. pip install -I ansible==2.6.5 git clone -b release-3.11 https://github.com/openshift/openshift-ansible # # Get the OpenShift 3.10 installer. # pip install -I ansible==2.6.5 # git clone -b release-3.10 https://github.com/openshift/openshift-ansible # Get the OpenShift 3.9 installer. # pip install -I ansible==2.4.3.0 # git clone -b release-3.9 https://github.com/openshift/openshift-ansible # Get the OpenShift 3.7 installer. # pip install -Iv ansible==2.4.1.0 # git clone -b release-3.7 https://github.com/openshift/openshift-ansible # Get the OpenShift 3.6 installer. # pip install -Iv ansible==2.3.0.0 # git clone -b release-3.6 https://github.com/openshift/openshift-ansible # Run the playbook. ANSIBLE_HOST_KEY_CHECKING=False /usr/local/bin/ansible-playbook -i ./inventory.cfg ./openshift-ansible/playbooks/prerequisites.yml ANSIBLE_HOST_KEY_CHECKING=False /usr/local/bin/ansible-playbook -i ./inventory.cfg ./openshift-ansible/playbooks/deploy_cluster.yml # If needed, uninstall with the below: # ansible-playbook playbooks/adhoc/uninstall.yml
def linear_transform(matrix): for i in range(len(matrix)): for j in range(len(matrix[0])): matrix[i][j] = matrix[i][j] * 2 return matrix
import React, { Component } from "react"; class NewsletterForm extends Component { constructor(props) { super(props); this.state = { name: "", email: "", }; } handleChange = (event) => { this.setState({ [event.target.name]: event.target.value }); } handleSubmit = (event) => { event.preventDefault(); alert(`Thank you ${this.state.name} for signing up`); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name <input type="text" name="name" value={this.state.name} onChange={this.handleChange} /> </label> <label> Email <input type="text" name="email" value={this.state.email} onChange={this.handleChange} /> </label> <input type="submit" value="Sign Up" /> </form> ); } } export default NewsletterForm;
<reponame>lehmier/aopify<filename>examples/around.js var aopify = require('../lib/index.js'); /* Parse a string as JSON */ var parseJson = function(str) { return JSON.parse(str); }; console.log(parseJson('{"x":3}')); /* aopify and wrap in a try-catch */ parseJson = aopify(parseJson); parseJson.around = function(options) { try { return options.proceed.apply(this, options.args); } catch (e) { console.log(e); return null; } }; /* Parse malformed JSON. */ console.log(parseJson('{')); // Output: // // { x: 3 } // [SyntaxError: Unexpected end of input] // null
#!/bin/bash VER=1.21 #----------------------------------------------------------------# # # # Section Manager by Teqno # # # # This will simplify the add/remove of sections for people # # that finds it too tedious to manually do the work. It checks # # for various scripts in /glftpd/bin folder including the script # # pzs-ng and adds the proper lines. Be sure to put the right # # paths for glftpd and pzs-ng before running this script and # # don't forget to rehash the bot after the script is done. This # # manager is intended for incoming sections only and not archive # # # # If the script cam't find the file defined in the path below # # the script will just skip it. # # # # This script only add/remove sections directly under /site and # # not under any other location # # # # # #--[ Settings ]--------------------------------------------------# glroot=/glftpd # path for glftpd dir pzsbot=$glroot/sitebot/scripts/pzs-ng/ngBot.conf # path for ngBot.conf pzsng=$glroot/backup/pzs-ng # path for pzs-ng incoming=/dev/sda1 # path for incoming device for glftpd # Leave them empty if you want to disable them turautonuke=$glroot/bin/tur-autonuke.conf # path for tur-autonuke turspace=$glroot/bin/tur-space.conf # path for tur-space approve=$glroot/bin/approve.sh # path for approve addaffil=$glroot/bin/addaffil.sh # path for customized eur0pre addaffil script included in glFTPD installer foopre=$glroot/etc/pre.cfg # path for foopre turlastul=$glroot/bin/tur-lastul.sh # path for tur-lastul psxcimdb=$glroot/etc/psxc-imdb.conf # path for psxc-imdb #--[ Script Start ]----------------------------------------------# clear rootdir=`pwd` function start { echo "Already configured sections: "`cat $pzsbot | grep "set sections" | sed 's/REQUEST//g' | cut -d "\"" -f2` while [[ -z $section ]] do echo -n "What section do you want to manage, if not listed just type it in : "; read section done section=${section^^} echo -n "What do you wanna do with $section ? [A]dd [R]remove, default A : "; read action echo -n "Is this a dated section ? [Y]es [N]o, default N : "; read day echo -n "Does it contain zip files ? [Y]es [N]o, default N : "; read zipfiles echo -n "Is this a movie section ? [Y]es [N]o, default N : " ; read movie case $action in [Rr]) if [ `cat $pzsbot | grep "set sections" | cut -d "\"" -f2 | sed 's/ /\n/g' | grep "$section$" | wc -l` = "0" ] then echo "Section does not exist, please try again." exit 2 else actionname="Removed the section from" echo -n "Remove folder $section under $glroot/site ? [Y]es [N]o, default N : " ; read remove case $remove in [Yy]) echo "Removing $section, please wait..." rm -rf $glroot/site/$section echo "$actionname $glroot/site" ;; *) echo "Remember, section folder $section needs to be removed under $glroot/site" ;; esac fi ;; *) if [ `cat $pzsbot | grep "set sections" | cut -d "\"" -f2 | sed 's/ /\n/g' | grep "$section$" | wc -l` = "1" ] then echo "Section already exist, please try again." exit 2 else actionname="Added the section to" echo -n "Create folder $section under $glroot/site ? [Y]es [N]o, default N : " ; read create case $create in [Yy]) echo "$actionname $glroot/site" mkdir -m 777 $glroot/site/$section ;; *) echo "Remember, section folder $section needs to be created under $glroot/site" ;; esac fi ;; esac } function turautonuke { if [ -f "$turautonuke" ] then case $action in [Rr]) sed -i "/\/site\/$section$/d" $turautonuke ;; *) case $day in [Yy]) sed -i '/^DIRS/a '"/site/$section/\$today" $turautonuke sed -i '/^DIRS/a '"/site/$section/\$yesterday" $turautonuke ;; *) sed -i '/^DIRS/a '"/site/$section" $turautonuke ;; esac ;; esac echo "$actionname Tur-Autonuke" else echo "Tur-Autonuker config file not found" fi } function turspace { if [ -f "$turspace" ] then case $action in [Rr]) sed -i "/\/site\/$section:/d" $turspace ;; *) case $day in [Yy]) sed -i '/^\[INCOMING\]/a '"INC$section=$incoming:$glroot/site/$section:DATED" $turspace ;; *) sed -i '/^\[INCOMING\]/a '"INC$section=$incoming:$glroot/site/$section:" $turspace ;; esac ;; esac echo "$actionname Tur-Space" else echo "Tur-Space config file not found" fi } function pzsng { if [ -f "$pzsng/zipscript/conf/zsconfig.h" ] then case $action in [Rr]) sed -i -e "s/\/site\/$section\/%m%d\///gI" -e "s/\/site\/$section\///gI" $pzsng/zipscript/conf/zsconfig.h sed -i 's/ "$/"/g' $pzsng/zipscript/conf/zsconfig.h sed -i 's/" /"/g' $pzsng/zipscript/conf/zsconfig.h sed -i '/\//s/\/ \//\/ \//g' $pzsng/zipscript/conf/zsconfig.h ;; *) case $day in [Yy]) sed -i "/\bcleanupdirs_dated\b/ s/\"$/ \/site\/$section\/%m%d\/\"/" $pzsng/zipscript/conf/zsconfig.h ;; *) sed -i "/\bcleanupdirs\b/ s/\"$/ \/site\/$section\/\"/" $pzsng/zipscript/conf/zsconfig.h ;; esac case $zipfiles in [Yy]) sed -i "/\bzip_dirs\b/ s/\"$/ \/site\/$section\/\"/" $pzsng/zipscript/conf/zsconfig.h ;; *) sed -i "/\bsfv_dirs\b/ s/\"$/ \/site\/$section\/\"/" $pzsng/zipscript/conf/zsconfig.h ;; esac sed -i "/\bcheck_for_missing_nfo_dirs\b/ s/\"$/ \/site\/$section\/\"/" $pzsng/zipscript/conf/zsconfig.h ;; esac echo echo -n "Recompiling PZS-NG for changes to go into effect, please wait..." cd $pzsng && make distclean >/dev/null 2>&1 && ./configure -q && make >/dev/null 2>&1 && make install >/dev/null 2>&1 && cd $rootdir echo -e " \e[32mDone\e[0m" echo "$actionname PZS-NG" else echo "PZS-NG config file not found" fi } function pzsbot { if [ -f "$pzsbot" ] then case $action in [Rr]) before=`cat $pzsbot | grep "set sections" | cut -d "\"" -f2` after=`cat $pzsbot | grep "set sections" | cut -d "\"" -f2 | sed 's/ /\n/g' | grep -vw "$section$" | sort | xargs` sed -i "/set sections/s/$before/$after/gI" $pzsbot sed -i "/set paths("$section")/d" $pzsbot sed -i "/set chanlist("$section")/d" $pzsbot ;; *) case $day in [Yy]) sed -i '/set paths(REQUEST)/i set paths('"$section"') "/site/'"$section"'/*/*"' $pzsbot ;; *) sed -i '/set paths(REQUEST)/i set paths('"$section"') "/site/'"$section"'/*"' $pzsbot ;; esac sed -i '/set chanlist(REQUEST)/i set chanlist('"$section"') "$mainchan"' $pzsbot sed -i "/set sections/s/\"$/\ $section\"/g" $pzsbot ;; esac sed -i '/set sections/s/ / /g' $pzsbot sed -i '/set sections/s/ "/"/g' $pzsbot sed -i '/set sections/s/" /"/g' $pzsbot echo "$actionname PZS-NG bot" else echo "PZS-NG bot config file not found" fi } function approve { if [ -f "$approve" ] then case $action in [Rr]) sed -i "/$section$/d" $approve ;; *) if [[ ${section^^} != @(0DAY|MP3|FLAC|EBOOKS) ]] then sed -i '/^SECTIONS="/a '"$section" $approve else sed -i '/^DAYSECTIONS="/a '"$section" $approve fi ;; esac sections=`cat $approve | sed -n '/^SECTIONS="/,/"/p' | grep -v DAYSECTIONS | grep -v NUMDAYFOLDERS | grep -v SECTIONS | grep -v "\"" | wc -l` daysections=`cat $approve | sed -n '/^DAYSECTIONS="/,/"/p' | grep -v DAYSECTIONS | grep -v NUMDAYFOLDERS | grep -v SECTIONS | grep -v "\"" | wc -l` current=`cat $approve | grep -i ^numfolders= | cut -d "\"" -f2` ncurrent=`cat $approve | grep -i ^numdayfolders= | cut -d "\"" -f2` sed -i -e "s/^NUMFOLDERS=\".*\"/NUMFOLDERS=\"$sections\"/" $approve sed -i -e "s/^NUMDAYFOLDERS=\".*\"/NUMDAYFOLDERS=\"$daysections\"/" $approve echo "$actionname Approve" else echo "Approve config file not found" fi } function eur0pre { if [[ -f "$addaffil" && -f "$foopre" ]] then case $action in [Rr]) before=`cat $addaffil | grep "allow=" | cut -d "=" -f2 | cut -d "'" -f1 | uniq` after=`cat $addaffil | grep "allow=" | cut -d "=" -f2 | cut -d "'" -f1 | uniq | sed 's/|/\n/g' | sort | grep -vw "$section$" | xargs | sed 's/ /|/g'` sed -i "/allow=/s/$before/$after/g" $addaffil before=`cat $foopre | grep "allow="| cut -d "=" -f2 | cut -d "'" -f1 | uniq` after=`cat $foopre | grep "allow="| cut -d "=" -f2 | uniq | sed 's/|/\n/g' | sort | grep -vw "$section$" | xargs | sed 's/ /|/g'` sed -i "/allow=/s/$before/$after/g" $foopre sed -i "/section.$section\./d" $foopre ;; *) sed -i "s/.allow=/.allow=$section\|/" $addaffil sed -i "s/.allow=/.allow=$section\|/" $foopre if [[ ${section^^} != @(0DAY|MP3|FLAC|EBOOKS) ]] then echo "section.$section.name=$section" >> $foopre echo "section.$section.dir=/site/$section" >> $foopre echo "section.$section.gl_credit_section=0" >> $foopre echo "section.$section.gl_stat_section=0" >> $foopre else echo "section.$section.name=$section" >> $foopre echo "section.$section.dir=/site/$section/MMDD" >> $foopre echo "section.$section.gl_credit_section=0" >> $foopre echo "section.$section.gl_stat_section=0" >> $foopre fi ;; esac sed -i "/allow=/s/=|/=/" $addaffil sed -i "/allow=/s/||/|/" $addaffil sed -i "/allow=/s/|'/'/" $addaffil sed -i "/allow=/s/=|/=/" $foopre sed -i "/allow=/s/||/|/" $foopre sed -i "/allow=/s/|$//" $foopre echo "$actionname addaffil + foo-pre" else echo "Either addaffil or foopre config file not found" fi } function turlastul { if [ -f "$turlastul" ] then case $action in [Rr]) before=`cat $turlastul | grep "sections="| cut -d "=" -f2 | tr -d "\""` after=`cat $turlastul | grep "sections="| cut -d "=" -f2 | tr -d "\"" | sed 's/ /\n/g' | sort | grep -vw "$section$" | xargs` sed -i "/sections=/s/$before/$after/g" $turlastul ;; *) sed -i "s/^sections=\"/sections=\"$section /" $turlastul ;; esac sed -i '/^sections=/s/ / /g' $turlastul sed -i '/^sections=/s/" /"/g' $turlastul sed -i '/^sections=/s/ "/"/g' $turlastul echo "$actionname Tur-Lastul" else echo "Tur-Lastul config file not found" fi } function psxcimdb { if [ -f "$psxcimdb" ] then case $movie in [Yy]) case $action in [Rr]) sed -i "/^SCANDIRS/ s/\/site\/\b$section\b//" $psxcimdb ;; *) sed -i "s/^SCANDIRS=\"/SCANDIRS=\"\/site\/$section /" $psxcimdb ;; esac sed -i '/^SCANDIRS=/s/ / /g' $psxcimdb sed -i '/^SCANDIRS=/s/" /"/g' $psxcimdb sed -i '/^SCANDIRS=/s/ "/"/g' $psxcimdb echo "$actionname PSXC-IMDB" ;; esac else echo "PSXC-IMDB config file not found" fi } case `ls $glroot/site` in 0DAY*|FLAC*|MP3*|EBOOK*) echo ;; *) sed -i /dated.sh/d /var/spool/cron/crontabs/root ;; esac start pzsng pzsbot turautonuke turspace approve eur0pre turlastul psxcimdb echo echo -e "\e[31mBe sure to rehash the bot or the updated settings will not take effect\e[0m" echo exit 0