text stringlengths 1 1.05M |
|---|
<filename>node_modules/@reactivex/rxjs/dist/amd/util/errorObject.js<gh_stars>1-10
define(["require", "exports"], function (require, exports) {
"use strict";
// typeof any so that it we don't have to cast when comparing a result to the error object
exports.errorObject = { e: {} };
});
//# sourceMappingURL=errorObject.js.map |
/**
*
* @author <NAME>
* @matricola: 560049
* @project Word Quizzle
* @A.A 2019 - 2020 [UNIPI]
*
*/
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JDialog;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SocketChannel;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.awt.event.ActionEvent;
import javax.swing.JPasswordField;
import javax.swing.JPanel;
import java.awt.Font;
import java.awt.CardLayout;
import javax.swing.JSeparator;
import java.awt.Color;
import java.awt.Dialog.ModalityType;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;
import javax.swing.JSplitPane;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTextPane;
public class WqClientGUI {
private JFrame contentPane;
private JTextField usrSignUp;
private JPasswordField pswSignUp;
private JPasswordField confirmPswSignUp;
private JTextField usrLogin;
private JPasswordField pswLogin;
private JTextField userSearch;
private JTextField translatedWord;
private JButton signUpButton;
private JButton btnShowScore;
private JButton btnRefresh;
private JButton btnLogin;
private JButton btnLogout;
private JButton btnAddFriend;
private JButton btnRanking;
private JButton btnSend;
private static final String[] options = { MyUtilities.MATCH_LIST, MyUtilities.SCORE_LIST, MyUtilities.CANCEL };
// Used to process/interpret requests/responses to/from the server
private JsonHandler jsonHandler;
private String usr = null;
private SocketChannel clientSocket;
private DatagramSocket clientUdpSocket;
private AtomicBoolean safeExit;
private AtomicBoolean busy;
private boolean canWrite;
private boolean stop;
private Lock lock;
private Condition cond;
// Launch the application.
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WqClientGUI window = new WqClientGUI();
window.contentPane.setTitle(MyUtilities.WORD_QUIZZLE);
window.contentPane.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
// Create the application.
public WqClientGUI() {
jsonHandler = new JsonHandler();
safeExit = new AtomicBoolean(false);
busy = new AtomicBoolean(false);
initialize();
}
// Exit procedure for the client side
private void exit() {
try {
safeExit.set(true);
if(clientSocket != null)
clientSocket.close();
if(clientUdpSocket != null)
clientUdpSocket.close();
if(usr != null)
usr = null;
busy.set(false);
} catch (IOException ioe) {
ErrorMacro.softIoExceptionHandling(ioe);
}
}
// Simply use the socket channel for send requests/traductions to the server
private boolean send(String request) {
ByteBuffer length = ByteBuffer.allocate(Integer.BYTES);
length.putInt(request.length());
length.flip();
ByteBuffer req = ByteBuffer.wrap(request.getBytes());
try {
while(length.hasRemaining()) // Write all
clientSocket.write(length);
while(req.hasRemaining())
clientSocket.write(req);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.COMM_ERROR);
ErrorMacro.clientIoExceptionHandling(ioe, clientSocket, clientUdpSocket, usr, safeExit, busy);
return false;
}
return true;
}
// Simply use the socket channel for receive server responses
private Map<String, String> receive() {
ByteBuffer length = ByteBuffer.allocate(Integer.BYTES);
ByteBuffer rsp = ByteBuffer.allocate(MyUtilities.BUFFER_SIZE);
try {
while(length.hasRemaining()) { // Read all
long nread = clientSocket.read(length);
if(nread < 0) { // Disconnection
JOptionPane.showMessageDialog(contentPane, MyUtilities.CONNECTION_CLOSED);
exit();
return null;
}
}
length.flip();
int len = length.getInt();
while(rsp.position() != len) {
long nread = clientSocket.read(rsp);
if(nread < 0) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.CONNECTION_CLOSED);
exit();
return null;
}
}
rsp.flip();
} catch (IOException ioe) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.COMM_ERROR);
ErrorMacro.clientIoExceptionHandling(ioe, clientSocket, clientUdpSocket, usr, safeExit, busy);
return null;
}
return jsonHandler.fromJson(new String(rsp.array()).trim());
}
// Combine the methods send and receive (see above)
private Map<String, String> sendAndReceive(String rqst, String errMsg) {
if(!send(rqst)) {
JOptionPane.showMessageDialog(contentPane, errMsg);
return null;
}
Map<String, String> retval = receive();
if(retval == null) {
JOptionPane.showMessageDialog(contentPane, errMsg);
return null;
}
return retval;
}
// Receive the begin advertisement with a timeout for the handling of the udp packet loss and the translation service latency
private Map<String, String> receiveBegin() {
try { // Wrapping the underlying socket to set a read timeout
clientSocket.socket().setSoTimeout(MyUtilities.TIMEOUT_UDP);
ReadableByteChannel wrappedChannel =
Channels.newChannel(clientSocket.socket().getInputStream());
ByteBuffer length = ByteBuffer.allocate(Integer.BYTES);
ByteBuffer rsp = ByteBuffer.allocate(MyUtilities.BUFFER_SIZE);
while(length.hasRemaining()) { // Read all
long nread = wrappedChannel.read(length);
if(nread < 0) { // Disconnection
JOptionPane.showMessageDialog(contentPane, MyUtilities.CONNECTION_CLOSED);
exit();
return null;
}
}
length.flip();
int len = length.getInt();
while(rsp.position() != len) {
long nread = wrappedChannel.read(rsp);
if(nread < 0) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.CONNECTION_CLOSED);
exit();
return null;
}
}
rsp.flip();
// Reset the timeout ( 0 = infinite timeout )
clientSocket.socket().setSoTimeout(0);
return jsonHandler.fromJson(new String(rsp.array()).trim());
} catch(SocketTimeoutException ste) {
try {
clientSocket.socket().setSoTimeout(0);
} catch (SocketException se) { // Handled like a soft IOException for convenience
ErrorMacro.softIoExceptionHandling(se);
}
return Collections.singletonMap(MyUtilities.UNAUTHORIZED_CODE, MyUtilities.BEGIN_NOT_RECEIVED);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.COMM_ERROR);
ErrorMacro.clientIoExceptionHandling(ioe, clientSocket, clientUdpSocket, usr, safeExit, busy);
return null;
}
}
// Function called by the palyers to handle the match session
private void handleMatch(JTextPane commBox) {
CardLayout cl = (CardLayout)contentPane.getContentPane().getLayout();
/** Wait for BEGIN; since the challenge acceptance response (sent in udp) can be lost,
* a timer is used to receive Begin's adv; this timer can sometimes also be useful for
* communicating the excessive latency of the translation service that it can sometimes have.
**/
//Map<String, String> retval = receive();
Map<String, String> retval = receiveBegin();
if(retval == null) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.MATCH_ERR);
cl.show(contentPane.getContentPane(), "name_95218890939100");
return;
}
if(retval.containsKey(MyUtilities.SERVER_ERROR_CODE))
JOptionPane.showMessageDialog(contentPane, retval.get(MyUtilities.SERVER_ERROR_CODE));
else if(retval.containsKey(MyUtilities.UNAUTHORIZED_CODE))
JOptionPane.showMessageDialog(contentPane, retval.get(MyUtilities.UNAUTHORIZED_CODE));
else if(retval.containsKey(MyUtilities.SUCCESS_CODE)) {
commBox.setText(MyUtilities.TRANSLATE_FOLLOWING);
btnSend.setEnabled(true);
// Initialize the variables for socket write synchronization
canWrite = false;
lock = new ReentrantLock();
cond = lock.newCondition();
stop = false;
// Loop for receive the words to translate
for(int i = 0; i < 10 ; i++) {
retval = receive();
if(retval == null) {
commBox.setText("");
btnSend.setEnabled(false);
JOptionPane.showMessageDialog(contentPane, MyUtilities.MATCH_ERR);
cl.show(contentPane.getContentPane(), "name_95218890939100");
return;
}
if(retval.containsKey(MyUtilities.SERVER_ERROR_CODE)) {
JOptionPane.showMessageDialog(contentPane, retval.get(MyUtilities.SERVER_ERROR_CODE));
busy.set(false);
commBox.setText("");
btnSend.setEnabled(false);
cl.show(contentPane.getContentPane(), "name_98987579688700");
return;
}
else if(retval.containsKey(MyUtilities.UNAUTHORIZED_CODE)) {
JOptionPane.showMessageDialog(contentPane, retval.get(MyUtilities.UNAUTHORIZED_CODE));
busy.set(false);
commBox.setText("");
btnSend.setEnabled(false);
cl.show(contentPane.getContentPane(), "name_98987579688700");
return;
}
else if(retval.containsKey(MyUtilities.SUCCESS_CODE)) {
JOptionPane.showMessageDialog(contentPane, retval.get(MyUtilities.SUCCESS_CODE));
busy.set(false);
commBox.setText("");
btnSend.setEnabled(false);
cl.show(contentPane.getContentPane(), "name_98987579688700");
return;
}
else if(retval.containsKey(MyUtilities.TRANSLATE)) {
StyledDocument document = (StyledDocument) commBox.getDocument();
try {
document.insertString(document.getLength(),
MyUtilities.CHALLENGE_NUM + (i + 1) + MyUtilities.OF +
retval.get(MyUtilities.TRANSLATE), null);
} catch (BadLocationException ble) {
exit();
commBox.setText("");
btnSend.setEnabled(false);
JOptionPane.showMessageDialog(contentPane, MyUtilities.SOMETHING_WRONG_CL);
System.exit(-1);
}
// Enable the writing of translated word
lock.lock();
canWrite = true;
if(i == 9)
stop = true;
cond.signal();
lock.unlock();
}
}
retval = receive();
if(retval == null) {
commBox.setText("");
btnSend.setEnabled(false);
JOptionPane.showMessageDialog(contentPane, MyUtilities.MATCH_ERR);
cl.show(contentPane.getContentPane(), "name_95218890939100");
return;
}
if(retval.containsKey(MyUtilities.UNAUTHORIZED_CODE))
JOptionPane.showMessageDialog(contentPane, retval.get(MyUtilities.UNAUTHORIZED_CODE));
else if(retval.containsKey(MyUtilities.SUCCESS_CODE))
JOptionPane.showMessageDialog(contentPane, retval.get(MyUtilities.SUCCESS_CODE));
}
busy.set(false);
commBox.setText("");
btnSend.setEnabled(false);
cl.show(contentPane.getContentPane(), "name_98987579688700");
}
// Initialize the contents of the frame.
private void initialize() {
contentPane = new JFrame();
contentPane.setBounds(100, 100, 450, 300);
contentPane.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane.getContentPane().setLayout(new CardLayout(0, 0));
JPanel rootJPanel = new JPanel();
contentPane.getContentPane().add(rootJPanel, "name_95218890939100");
rootJPanel.setLayout(null);
JPanel matchPanel = new JPanel();
contentPane.getContentPane().add(matchPanel, "name_267004884614900");
matchPanel.setLayout(null);
JSplitPane usrOp = new JSplitPane();
contentPane.getContentPane().add(usrOp, "name_98987579688700");
JSeparator separator = new JSeparator();
separator.setOrientation(SwingConstants.VERTICAL);
separator.setBackground(Color.BLACK);
separator.setForeground(Color.BLACK);
separator.setBounds(223, 0, 2, 261);
rootJPanel.add(separator);
JLabel lblNewLabel_1 = new JLabel("<NAME> 560049 2019 - 2020");
lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 9));
lblNewLabel_1.setBounds(0, 249, 188, 12);
rootJPanel.add(lblNewLabel_1);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(31, 27, 86, 14);
rootJPanel.add(lblUsername);
JLabel lblNewLabel = new JLabel("Password");
lblNewLabel.setBounds(31, 87, 86, 14);
rootJPanel.add(lblNewLabel);
JLabel lblConfirmPassword = new JLabel("<PASSWORD>");
lblConfirmPassword.setBounds(31, 143, 141, 14);
rootJPanel.add(lblConfirmPassword);
usrSignUp = new JTextField();
usrSignUp.setBounds(31, 52, 141, 20);
rootJPanel.add(usrSignUp);
usrSignUp.setColumns(10);
pswSignUp = new JPasswordField();
pswSignUp.setBounds(31, 112, 141, 20);
rootJPanel.add(pswSignUp);
pswSignUp.setColumns(10);
confirmPswSignUp = new JPasswordField();
confirmPswSignUp.setBounds(31, 168, 141, 20);
rootJPanel.add(confirmPswSignUp);
confirmPswSignUp.setColumns(10);
JLabel lblUsername_1 = new JLabel("Username");
lblUsername_1.setBounds(268, 55, 86, 14);
rootJPanel.add(lblUsername_1);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(268, 115, 86, 14);
rootJPanel.add(lblPassword);
usrLogin = new JTextField();
usrLogin.setBounds(268, 84, 141, 20);
rootJPanel.add(usrLogin);
usrLogin.setColumns(10);
pswLogin = new JPasswordField();
pswLogin.setBounds(268, 140, 141, 20);
rootJPanel.add(pswLogin);
pswLogin.setColumns(10);
JPanel panel = new JPanel();
usrOp.setRightComponent(panel);
panel.setLayout(null);
JLabel lblSe = new JLabel("Search user");
lblSe.setBounds(100, 31, 113, 14);
panel.add(lblSe);
userSearch = new JTextField();
userSearch.setBounds(100, 56, 214, 20);
panel.add(userSearch);
userSearch.setColumns(10);
translatedWord = new JTextField();
translatedWord.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
btnSend.doClick();
}
});
translatedWord.setBounds(10, 228, 315, 20);
matchPanel.add(translatedWord);
translatedWord.setColumns(10);
JTextPane commBox = new JTextPane();
commBox.setBounds(10, 11, 414, 205);
commBox.setEditable(false);
matchPanel.add(commBox);
// Send the sign up request and receive response
signUpButton = new JButton("Sign Up");
signUpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) { // Password confirmation
if(!Arrays.equals(pswSignUp.getPassword(), confirmPswSignUp.getPassword())) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.USR_DIFFERENT_PSW);
return;
}
try {
Registry reg = LocateRegistry.getRegistry(MyUtilities.SIGN_UP_PORT);
WqSignUp stub = (WqSignUp)reg.lookup(MyUtilities.SERVER_SIGN_UP_NAME);
// Notify the response received by the server
Map<String, String> retval =
jsonHandler.fromJson(stub.signUp(usrSignUp.getText(), String.valueOf(pswSignUp.getPassword())));
if(retval.containsKey(MyUtilities.CLIENT_ERROR_CODE))
JOptionPane.showMessageDialog(contentPane, MyUtilities.ERR_ENTERING_PARS + retval.get(MyUtilities.CLIENT_ERROR_CODE));
else if(retval.containsKey(MyUtilities.RETRY_WITH_CODE))
JOptionPane.showMessageDialog(contentPane, MyUtilities.URS_TAKEN + retval.get(MyUtilities.RETRY_WITH_CODE));
else if(retval.containsKey(MyUtilities.SUCCESS_CODE)) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.SUCCESSFUL_REG + retval.get(MyUtilities.SUCCESS_CODE));
// Clean the fields so the client can perform another registration without have to delete the previous information itself
usrSignUp.setText(null);
pswSignUp.setText(null);
confirmPswSignUp.setText(null);
}
} catch (RemoteException | NotBoundException re_nbe) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.CONNECTION_FAIL);
}
}
});
signUpButton.setBounds(31, 207, 86, 31);
rootJPanel.add(signUpButton);
// Send the show score request and receive the server response
btnShowScore = new JButton("Show Score");
btnShowScore.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String showScoreRequest = jsonHandler.toJson(Collections.singletonMap(MyUtilities.SHOW_SCORE, userSearch.getText()));
CardLayout cl = (CardLayout)contentPane.getContentPane().getLayout();
Map<String, String> retval = sendAndReceive(showScoreRequest, MyUtilities.SHOW_SCORE_ERR_REQ);
if(retval == null) {
cl.show(contentPane.getContentPane(), "name_95218890939100");
return;
}
if(retval.containsKey(MyUtilities.CLIENT_ERROR_CODE))
JOptionPane.showMessageDialog(contentPane, MyUtilities.ERR_ENTERING_PARS + retval.get(MyUtilities.CLIENT_ERROR_CODE));
else if(retval.containsKey(MyUtilities.SUCCESS_CODE))
JOptionPane.showMessageDialog(contentPane, userSearch.getText() + MyUtilities.SPACE + retval.get(MyUtilities.SUCCESS_CODE));
}
});
btnShowScore.setBounds(157, 121, 107, 23);
panel.add(btnShowScore);
// Handle the match request to the player and the show score request (only for friends players)
JList<String> friendList = new JList<String>();
friendList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
String opponent = friendList.getModel().getElementAt(friendList.getSelectedIndex());
int retval = JOptionPane.showOptionDialog(contentPane, MyUtilities.WHAT_DU_WANT_TO_DO, MyUtilities.USER_SELECTED +
opponent, JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if(retval == 2 || retval == JOptionPane.CLOSED_OPTION)
return;
else if(retval == 1) {
userSearch.setText(opponent);
btnShowScore.doClick();
userSearch.setText(null);
return;
}
else {
String matchRequest = jsonHandler.toJson(Collections.singletonMap(MyUtilities.MATCH, usr + MyUtilities.SPLIT + opponent));
CardLayout cl = (CardLayout)contentPane.getContentPane().getLayout();
Map<String, String> retvalRqst = sendAndReceive(matchRequest, MyUtilities.MATCH_ERR_SEND_REQ);
if(retvalRqst == null) {
cl.show(contentPane.getContentPane(), "name_95218890939100");
return;
}
if(retvalRqst.containsKey(MyUtilities.CLIENT_ERROR_CODE))
JOptionPane.showMessageDialog(contentPane, MyUtilities.ERR_ENTERING_PARS + retvalRqst.get(MyUtilities.CLIENT_ERROR_CODE));
else if(retvalRqst.containsKey(MyUtilities.RETRY_WITH_CODE))
JOptionPane.showMessageDialog(contentPane, retvalRqst.get(MyUtilities.RETRY_WITH_CODE));
else if(retvalRqst.containsKey(MyUtilities.SERVER_ERROR_CODE))
JOptionPane.showMessageDialog(contentPane, retvalRqst.get(MyUtilities.SERVER_ERROR_CODE));
else if(retvalRqst.containsKey(MyUtilities.SUCCESS_CODE)) {
busy.set(true);
cl.show(contentPane.getContentPane(), "name_267004884614900");
// Non modal advertisement displayed while waiting for the challenged's player response
JOptionPane jop = new JOptionPane(MyUtilities.WAITING_FOR_MATCH_RP);
JDialog dialog = jop.createDialog(contentPane, MyUtilities.MATCHMAKING);
dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
dialog.setModalityType(ModalityType.MODELESS);
dialog.setVisible(true);
new Thread() {
@Override
public void run() {
Map<String, String> matchRetval = receive();
if(matchRetval == null) {
dialog.setVisible(false);
JOptionPane.showMessageDialog(contentPane, MyUtilities.MATCH_ERR);
cl.show(contentPane.getContentPane(), "name_95218890939100");
return;
}
dialog.setVisible(false);
if(matchRetval.containsKey(MyUtilities.RETRY_WITH_CODE)) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.MATCH_RQST_TIMEOUT);
busy.set(false);
cl.show(contentPane.getContentPane(), "name_98987579688700");
return;
}
else if(matchRetval.containsKey(MyUtilities.SERVER_ERROR_CODE)) {
JOptionPane.showMessageDialog(contentPane, matchRetval.get(MyUtilities.SERVER_ERROR_CODE));
busy.set(false);
cl.show(contentPane.getContentPane(), "name_98987579688700");
return;
}
else if(matchRetval.containsKey(MyUtilities.MATCH)) {
if(matchRetval.get(MyUtilities.MATCH).equals(MyUtilities.MATCH_REFUSED)) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.CLIENT_MATCH_REFUSED);
busy.set(false);
cl.show(contentPane.getContentPane(), "name_98987579688700");
return;
}
handleMatch(commBox);
return;
}
// This code should't be never reached
busy.set(false);
}
}.start();
}
}
}
});
friendList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
usrOp.setLeftComponent(friendList);
// Send the friend list request and receive response; refresh the friend list displayed in the user interface
btnRefresh = new JButton("Refresh");
btnRefresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String friendListRequest = jsonHandler.toJson(Collections.singletonMap(MyUtilities.FRIEND_LIST, usr));
CardLayout cl = (CardLayout)contentPane.getContentPane().getLayout();
Map<String, String> retval = sendAndReceive(friendListRequest, MyUtilities.FRIEND_LIST_ERR_REQ);
if(retval == null) {
cl.show(contentPane.getContentPane(), "name_95218890939100");
return;
}
if(retval.containsKey(MyUtilities.CLIENT_ERROR_CODE))
JOptionPane.showMessageDialog(contentPane, MyUtilities.ERR_ENTERING_PARS + retval.get(MyUtilities.CLIENT_ERROR_CODE));
else if(retval.containsKey(MyUtilities.SUCCESS_CODE)){ // Success
ToClientLst toClientLst = new ToClientLst();
DefaultListModel<String> dml = new DefaultListModel<String>();
for(ToClientLst.PlayerFriends pf : toClientLst.getClientLst(retval.get(MyUtilities.SUCCESS_CODE)))
dml.addElement(pf.getUsr());
friendList.setModel(dml);
userSearch.setText(null);
}
}
});
btnRefresh.setBounds(109, 225, 89, 23);
panel.add(btnRefresh);
// Send the login request and receive the server response
btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try { // Open the connection with the Server and the
clientSocket = SocketChannel.open(new InetSocketAddress(InetAddress.getLoopbackAddress(), MyUtilities.TCP_CONTROL_PORT));
clientUdpSocket = new DatagramSocket();
} catch (IOException ioe) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.CONNECTION_FAIL);
return;
}
// Create login request, send the request, receive the response
String loginRequest = jsonHandler.toJson(Collections.singletonMap(MyUtilities.LOGIN,
usrLogin.getText() + MyUtilities.SPLIT + String.valueOf(pswLogin.getPassword())
+ MyUtilities.SPLIT + String.valueOf(clientUdpSocket.getLocalPort())));
Map<String, String> retval = sendAndReceive(loginRequest, MyUtilities.LOGIN_ERR_SEND_REQ);
if(retval == null)
return;
usr = usrLogin.getText();
if(retval.containsKey(MyUtilities.CLIENT_ERROR_CODE)) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.ERR_ENTERING_PARS + retval.get(MyUtilities.CLIENT_ERROR_CODE));
exit();
}
else if(retval.containsKey(MyUtilities.UNAUTHORIZED_CODE)) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.CLIENT_ALREADY_ON);
exit();
}
else if(retval.containsKey(MyUtilities.SUCCESS_CODE)) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.CLIENT_ONLINE + retval.get(MyUtilities.SUCCESS_CODE));
usrLogin.setText(null);
pswLogin.setText(null);
CardLayout cl = (CardLayout)contentPane.getContentPane().getLayout();
cl.show(contentPane.getContentPane(), "name_98987579688700");
btnRefresh.doClick();
// Run the thread that listen for udp messages (match request) and send the response
new Thread() {
@Override
public void run() {
while(true) {
byte[] buf = new byte[MyUtilities.BYTE_ARRAY_SIZE];
DatagramPacket matchReqPkt = new DatagramPacket(buf, buf.length);
try {
clientUdpSocket.receive(matchReqPkt); // Wait for incoming match request
Map<String, String> rqst = jsonHandler.fromJson(new String(matchReqPkt.getData()).trim());
String rqstVal = rqst.get(MyUtilities.MATCH);
if(rqstVal == null) // Not a match request, the message is ignored
continue;
long timestamp = System.currentTimeMillis();
// Show the match request only if the player is not busy on another match and if the user operation pane is displayed
if(!busy.get() && usrOp.isShowing()) {
int retval = JOptionPane.showConfirmDialog(contentPane, rqstVal + MyUtilities.DO_YOU_ACCEPT);
if(retval == JOptionPane.CANCEL_OPTION || retval == JOptionPane.CLOSED_OPTION)
continue;
else if(retval == JOptionPane.NO_OPTION) {
String refuse = jsonHandler.toJson(Collections.singletonMap(MyUtilities.MATCH, MyUtilities.MATCH_REFUSED));
DatagramPacket refusePkt = new DatagramPacket(refuse.getBytes(), refuse.length(), InetAddress.getLoopbackAddress(), matchReqPkt.getPort());
clientUdpSocket.send(refusePkt);
}
else {
if(System.currentTimeMillis() < timestamp + MyUtilities.TIMEOUT) {
String accept = jsonHandler.toJson(Collections.singletonMap(MyUtilities.MATCH, MyUtilities.MATCH_ACCEPTED));
DatagramPacket acceptPkt = new DatagramPacket(accept.getBytes(), accept.length(), InetAddress.getLoopbackAddress(), matchReqPkt.getPort());
clientUdpSocket.send(acceptPkt);
cl.show(contentPane.getContentPane(), "name_267004884614900");
new Thread() {
@Override
public void run() {
handleMatch(commBox);
}
}.start();
}
else
JOptionPane.showMessageDialog(contentPane, MyUtilities.MATCH_RQST_TIMEOUT);
}
}
} catch (IOException ioe) {
if(safeExit.get()) {
safeExit.set(false);
return;
}
JOptionPane.showMessageDialog(contentPane, MyUtilities.CLIENT_UDP_LIS_ERR);
ErrorMacro.clientIoExceptionHandlingUDP(ioe, clientSocket, clientUdpSocket, usr, busy);
System.exit(-1);
}
}
}
}.start();
}
}
});
btnLogin.setBounds(268, 181, 76, 31);
rootJPanel.add(btnLogin);
JLabel lblWordQuizzle = new JLabel("Word Quizzle");
lblWordQuizzle.setFont(new Font("Yu Gothic UI", Font.BOLD | Font.ITALIC, 14));
lblWordQuizzle.setBounds(340, 0, 94, 30);
rootJPanel.add(lblWordQuizzle);
// Send the logout request and receive the server response
btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String logoutRequest = jsonHandler.toJson(Collections.singletonMap(MyUtilities.LOGOUT, usr));
CardLayout cl = (CardLayout)contentPane.getContentPane().getLayout();
Map<String, String> retval = sendAndReceive(logoutRequest, MyUtilities.LOGOUT_ERR_SEND_REQ);
if(retval == null) {
cl.show(contentPane.getContentPane(), "name_95218890939100");
return;
}
// With the GUI the fisrt two should't be displayed (no error(s))
if(retval.containsKey(MyUtilities.CLIENT_ERROR_CODE))
JOptionPane.showMessageDialog(contentPane, MyUtilities.ERR_ENTERING_PARS + retval.get(MyUtilities.CLIENT_ERROR_CODE));
else if(retval.containsKey(MyUtilities.UNAUTHORIZED_CODE))
JOptionPane.showMessageDialog(contentPane, MyUtilities.CLIENT_ALREADY_OFF);
else if(retval.containsKey(MyUtilities.SUCCESS_CODE)) {
JOptionPane.showMessageDialog(contentPane, MyUtilities.CLIENT_OFFLINE + retval.get(MyUtilities.SUCCESS_CODE));
exit();
cl.show(contentPane.getContentPane(), "name_95218890939100");
}
}
});
btnLogout.setBounds(208, 225, 89, 23);
panel.add(btnLogout);
// Send the add friend request and receive the server response
btnAddFriend = new JButton("Add Friend");
btnAddFriend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String addFriendRequest = jsonHandler.toJson(Collections.singletonMap(MyUtilities.ADD_FRIEND, usr + MyUtilities.SPLIT + userSearch.getText()));
CardLayout cl = (CardLayout)contentPane.getContentPane().getLayout();
Map<String, String> retval = sendAndReceive(addFriendRequest, MyUtilities.ADD_FRIEND_ERR_REQ);
if(retval == null) {
cl.show(contentPane.getContentPane(), "name_95218890939100");
return;
}
if(retval.containsKey(MyUtilities.CLIENT_ERROR_CODE))
JOptionPane.showMessageDialog(contentPane, MyUtilities.ERR_ENTERING_PARS + retval.get(MyUtilities.CLIENT_ERROR_CODE));
else if(retval.containsKey(MyUtilities.SUCCESS_CODE)) {
JOptionPane.showMessageDialog(contentPane, userSearch.getText() + MyUtilities.SPACE + retval.get(MyUtilities.SUCCESS_CODE));
userSearch.setText(null);
}
}
});
btnAddFriend.setBounds(157, 87, 107, 23);
panel.add(btnAddFriend);
// Send the ranking request and receive the server response
btnRanking = new JButton("Ranking");
btnRanking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String rankingRequest = jsonHandler.toJson(Collections.singletonMap(MyUtilities.SHOW_RANKING, usr));
CardLayout cl = (CardLayout)contentPane.getContentPane().getLayout();
Map<String, String> retval = sendAndReceive(rankingRequest, MyUtilities.RANKING_ERR_REQ);
if(retval == null) {
cl.show(contentPane.getContentPane(), "name_95218890939100");
return;
}
if(retval.containsKey(MyUtilities.CLIENT_ERROR_CODE))
JOptionPane.showMessageDialog(contentPane, MyUtilities.ERR_ENTERING_PARS + retval.get(MyUtilities.CLIENT_ERROR_CODE));
else if(retval.containsKey(MyUtilities.SUCCESS_CODE)){
ToClientLst toClientLst = new ToClientLst();
StringBuilder strB = new StringBuilder();
for(ToClientLst.PlayerFriends pf : toClientLst.getClientLst(retval.get(MyUtilities.SUCCESS_CODE)))
strB.append(String.format("%s : %d" + System.lineSeparator(), pf.getUsr(), pf.getScore()));
JOptionPane.showMessageDialog(contentPane, strB.toString());
}
}
});
btnRanking.setBounds(10, 225, 89, 23);
panel.add(btnRanking);
// Button activated only when the first word to translate is available
btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
CardLayout cl = (CardLayout)contentPane.getContentPane().getLayout();
String translation = jsonHandler.toJson(Collections.singletonMap(MyUtilities.TRANSLATION, translatedWord.getText()));
lock.lock();
while(!canWrite) {
try {
if(!stop)
cond.await();
else
return;
} catch (InterruptedException e) {
return;
}
}
// Exit safely in case of error
if(!send(translation)) {
commBox.setText("");
btnSend.setEnabled(false);
translatedWord.setText(null);
JOptionPane.showMessageDialog(contentPane, MyUtilities.MATCH_ERR);
cl.show(contentPane.getContentPane(), "name_95218890939100");
return;
}
StyledDocument document = (StyledDocument) commBox.getDocument();
try {
document.insertString(document.getLength(), MyUtilities.GET_TEXT_RES +
translatedWord.getText() + System.lineSeparator(), null);
} catch (BadLocationException ble) {
exit();
commBox.setText("");
btnSend.setEnabled(false);
translatedWord.setText(null);
JOptionPane.showMessageDialog(contentPane, MyUtilities.SOMETHING_WRONG_CL);
System.exit(-1);
}
canWrite = false;
lock.unlock();
translatedWord.setText(null);
}
});
btnSend.setBounds(335, 227, 89, 23);
btnSend.setEnabled(false);
matchPanel.add(btnSend);
}
}
|
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# This is an example docker build script. It is not intended for PRODUCTION use
set -euo pipefail
AIRFLOW_SOURCES="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../../" && pwd)"
cd "${AIRFLOW_SOURCES}"
# [START build]
export AIRFLOW_VERSION=2.2.2
docker build . \
--build \
--build-arg PYTHON_BASE_IMAGE="python:3.7-slim-bullseye" \
--build-arg AIRFLOW_VERSION="${AIRFLOW_VERSION}" \
--tag "my-pypi-selected-version:0.0.1"
# [END build]
docker rmi --force "my-pypi-selected-version:0.0.1"
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.moon = void 0;
var moon = {
"viewBox": "0 0 20 20",
"children": [{
"name": "path",
"attribs": {
"d": "M13.719,1.8c0.686,0.385,1.332,0.867,1.916,1.449c3.42,3.422,3.42,8.966,0,12.386c-3.42,3.42-8.965,3.42-12.386,0\r\n\tc-0.583-0.584-1.065-1.231-1.449-1.916c3.335,1.867,7.633,1.387,10.469-1.449C15.106,9.433,15.587,5.136,13.719,1.8z"
}
}]
};
exports.moon = moon; |
import sublime
import sublime_plugin
import json
from os.path import dirname, realpath, join, splitext, basename
try:
# Python 2
from node_bridge import node_bridge
except:
from .node_bridge import node_bridge
def get_setting(view, key):
settings = view.settings().get('Stylus Supremacy')
if settings is None:
settings = sublime.load_settings('Stylus Supremacy.sublime-settings')
return settings.get(key)
BIN_PATH = join(sublime.packages_path(), dirname(realpath(__file__)), 'stylussupremacy.js')
class StylusSupremacyCommand(sublime_plugin.TextCommand):
def run(self, edit):
if not self.is_stylus():
# print("File's type isn't stylus one, ignoring format.")
return
if not self.has_selection():
region = sublime.Region(0, self.view.size())
originalBuffer = self.view.substr(region)
fixed = self.fix(originalBuffer)
if fixed:
self.view.replace(edit, region, fixed)
return
for region in self.view.sel():
if region.empty():
continue
originalBuffer = self.view.substr(region)
fixed = self.fix(originalBuffer)
if fixed:
self.view.replace(edit, region, fixed)
def is_stylus(self):
return self.view.settings().get('syntax').endswith("Stylus.tmLanguage")
def fix(self, data):
try:
return node_bridge(data, BIN_PATH, [json.dumps({
'insertColons': get_setting(self.view, 'insertColons'),
'insertSemicolons': get_setting(self.view, 'insertSemicolons'),
'insertBraces': get_setting(self.view, 'insertBraces'),
'insertNewLineAroundImports': get_setting(self.view, 'insertNewLineAroundImports'),
'insertNewLineAroundBlocks': get_setting(self.view, 'insertNewLineAroundBlocks'),
'insertNewLineAroundProperties': get_setting(self.view, 'insertNewLineAroundProperties'),
'insertNewLineAroundOthers': get_setting(self.view, 'insertNewLineAroundOthers'),
'preserveNewLinesBetweenPropertyValues': get_setting(self.view, 'preserveNewLinesBetweenPropertyValues'),
'insertSpaceBeforeComment': get_setting(self.view, 'insertSpaceBeforeComment'),
'insertSpaceAfterComment': get_setting(self.view, 'insertSpaceAfterComment'),
'insertSpaceAfterComma': get_setting(self.view, 'insertSpaceAfterComma'),
'insertSpaceInsideParenthesis': get_setting(self.view, 'insertSpaceInsideParenthesis'),
'insertParenthesisAfterNegation': get_setting(self.view, 'insertParenthesisAfterNegation'),
'insertParenthesisAroundIfCondition': get_setting(self.view, 'insertParenthesisAroundIfCondition'),
'insertNewLineBeforeElse': get_setting(self.view, 'insertNewLineBeforeElse'),
'insertLeadingZeroBeforeFraction': get_setting(self.view, 'insertLeadingZeroBeforeFraction'),
'selectorSeparator': get_setting(self.view, 'selectorSeparator'),
'tabStopChar': get_setting(self.view, 'tabStopChar'),
'newLineChar': get_setting(self.view, 'newLineChar'),
'quoteChar': get_setting(self.view, 'quoteChar'),
'sortProperties': get_setting(self.view, 'sortProperties'),
'alwaysUseImport': get_setting(self.view, 'alwaysUseImport'),
'alwaysUseNot': get_setting(self.view, 'alwaysUseNot'),
'alwaysUseAtBlock': get_setting(self.view, 'alwaysUseAtBlock'),
'alwaysUseExtends': get_setting(self.view, 'alwaysUseExtends'),
'alwaysUseNoneOverZero': get_setting(self.view, 'alwaysUseNoneOverZero'),
'alwaysUseZeroWithoutUnit': get_setting(self.view, 'alwaysUseZeroWithoutUnit'),
'reduceMarginAndPaddingValues': get_setting(self.view, 'reduceMarginAndPaddingValues'),
'ignoreFiles': get_setting(self.view, 'ignoreFiles'),
})])
except Exception as e:
sublime.error_message('Stylus Supremacy\n%s' % e)
def has_selection(self):
for sel in self.view.sel():
start, end = sel
if start != end:
return True
return False
|
from sklearn.cluster import KMeans
# Define the data matrix X
X = get_item_data()
# Cluster items into n groups
kmeans = KMeans(n_clusters=n).fit(X)
labels = kmeans.labels_
# Group similar items
for item_id, label in zip(item_ids, labels):
set_category(item_id, label) |
#!/bin/bash
mkdir -p /etc/origin/master/
touch /etc/origin/master/htpasswd
## Default variables to use
[ ! -d openshift-ansible ] && git clone https://github.com/openshift/openshift-ansible.git -b release-3.11 --depth=1
ansible-playbook -i inventory.ini openshift-ansible/playbooks/prerequisites.yml
ansible-playbook -i inventory.ini openshift-ansible/playbooks/deploy_cluster.yml
htpasswd -b /etc/origin/master/htpasswd admin admin123
oc adm policy add-cluster-role-to-user cluster-admin admin
|
<reponame>Mirmik/crow
/** @file */
#ifndef CROW_BROCKER_TCP_SUBSCRIBER_H
#define CROW_BROCKER_TCP_SUBSCRIBER_H
#include <map>
#include <nos/inet/tcp_socket.h>
#include <string>
#include "subscriber.h"
namespace crowker_implementation
{
class tcp_subscriber : public subscriber
{
public:
nos::inet::tcp_socket *sock;
static std::map<nos::inet::netaddr, tcp_subscriber> allsubs;
static tcp_subscriber *get(const nos::inet::netaddr addr)
{
return &allsubs[addr];
}
void publish(const std::string &theme, const std::string &data,
options *opts) override;
};
} // namespace crowker_implementation
#endif |
<gh_stars>1-10
import { Controller } from "stimulus"
export default class extends Controller {
observer!: MutationObserver
initialize() {
this.observer = new MutationObserver(this.refreshArticles)
}
connect() {
this.element.setAttribute("role", "feed")
this.refreshArticles()
this.observer.observe(this.element, { childList: true })
}
disconnect() {
this.observer.disconnect()
}
navigate(event: KeyboardEvent) {
const { ctrlKey, key, target } = event
if (target instanceof Element) {
const article = this.articleElements.find(element => element.contains(target))
if (article) {
const index = this.articleElements.indexOf(article)
const firstIndex = 0
const lastIndex = this.articleElements.length - 1
let nextArticle
switch (key) {
case "PageUp":
nextArticle = this.articleElements[Math.max(firstIndex, index - 1)]
break
case "PageDown":
nextArticle = this.articleElements[Math.min(lastIndex, index + 1)]
break
case "Home":
if (ctrlKey) nextArticle = this.articleElements[firstIndex]
break
case "End":
if (ctrlKey) nextArticle = this.articleElements[lastIndex]
break
}
if (nextArticle) {
event.preventDefault()
nextArticle.focus()
}
}
}
}
private refreshArticles = () => {
const size = this.articleElements.length + 1
this.element.setAttribute("aria-setsize", size.toString())
this.articleElements.forEach((element, index) => {
element.setAttribute("tabindex", "0")
element.setAttribute("aria-posinset", (index + 1).toString())
})
}
private get articleElements(): HTMLElement[] {
return Array.from(this.element.querySelectorAll<HTMLElement>("* > article, * > [role=article]"))
}
}
|
package com.firoz.mymvpboilerplate.executor;
import com.firoz.mymvpboilerplate.interactor.AbstractInteractor;
/**
* Created by firoz on 1/4/17.
*/
public interface Execution {
/**
* This executor is responsible for running interactors on background threads.
*/
interface MyBackExecutor {
void execute(final AbstractInteractor interactor);
}
/**
* This interface will define a class
* that will enable interactors to run certain operations on the main (UI) thread.
*/
interface MyUIExecutor {
void post(Runnable runnable);
}
}
|
<filename>src/main/java/de/lmu/cis/ocrd/ml/features/NamedFeature.java
package de.lmu.cis.ocrd.ml.features;
abstract class NamedFeature extends BaseFeatureImplementation {
private static final long serialVersionUID = -4851942231267570448L;
private final String name;
NamedFeature(String name) {
this.name = name;
}
@Override
public final String getName() {
return name.replaceAll("\\s+", "_");
}
}
|
<reponame>wl04/HackerRank-solutions
// Solution
class MyCalculator implements AdvancedArithmetic {
public int divisor_sum(int num) {
if (num == 1) {
return 1;
}
else {
int sum = 1 + num; // Any number can be devided by 1 and by the number itself
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
sum += i;
}
}
return sum;
}
}
}
|
g++49 -O3 -fomit-frame-pointer -c test_timing.cpp
gcc49 -O3 -fomit-frame-pointer -o libco.o -c ../libco.c
g++49 -O3 -fomit-frame-pointer -o test_timing libco.o test_timing.o
rm -f *.o
|
<reponame>Accessible-Concepts/scrumlr.io
import {useLocation} from "react-router";
import {useLayoutEffect} from "react";
const ScrollToTop = () => {
const location = useLocation();
useLayoutEffect(() => {
// scroll to top on route change
window.scrollTo(0, 0);
}, [location.pathname]);
return null;
};
export default ScrollToTop;
|
import React from "react";
import { Link } from "@reach/router";
import styled from "react-emotion";
import colors from "../colors";
const Header = styled("header")`
background-color: ${colors.background};
position: sticky;
top: 0;
z-index: 10;
`;
const NavBar = () => (
<Header>
<Link to="/">SITE HEADER HERE</Link>
<Link to="/details">
<span aria-label="next-page" role="img">
➡️
</span>
</Link>
</Header>
);
export default NavBar;
|
#!/bin/bash
if git diff origin/master -- mars | grep -q "old mode"; then
echo "Unexpected file mode changed. You may call"
echo " git config core.fileMode false"
echo "before committing to the repo."
git diff origin/master -- mars | grep -B 2 -A 2 "old mode"
exit 1
fi
|
#!/usr/bin/env sh
# generated from catkin/cmake/template/setup.sh.in
# Sets various environment variables and sources additional environment hooks.
# It tries it's best to undo changes from a previously sourced setup file before.
# Supported command line options:
# --extend: skips the undoing of changes from a previously sourced setup file
# (in plain sh shell which does't support arguments for sourced scripts you
# can set the environment variable `CATKIN_SETUP_UTIL_ARGS=--extend` instead)
# since this file is sourced either use the provided _CATKIN_SETUP_DIR
# or fall back to the destination set at configure time
: ${_CATKIN_SETUP_DIR:=/home/workspace/ros-basics/catkin_ws/install}
_SETUP_UTIL="$_CATKIN_SETUP_DIR/_setup_util.py"
unset _CATKIN_SETUP_DIR
if [ ! -f "$_SETUP_UTIL" ]; then
echo "Missing Python script: $_SETUP_UTIL"
return 22
fi
# detect if running on Darwin platform
_UNAME=`uname -s`
_IS_DARWIN=0
if [ "$_UNAME" = "Darwin" ]; then
_IS_DARWIN=1
fi
unset _UNAME
# make sure to export all environment variables
export CMAKE_PREFIX_PATH
if [ $_IS_DARWIN -eq 0 ]; then
export LD_LIBRARY_PATH
else
export DYLD_LIBRARY_PATH
fi
unset _IS_DARWIN
export PATH
export PKG_CONFIG_PATH
export PYTHONPATH
# remember type of shell if not already set
if [ -z "$CATKIN_SHELL" ]; then
CATKIN_SHELL=sh
fi
# invoke Python script to generate necessary exports of environment variables
# use TMPDIR if it exists, otherwise fall back to /tmp
if [ -d "${TMPDIR:-}" ]; then
_TMPDIR="${TMPDIR}"
else
_TMPDIR=/tmp
fi
_SETUP_TMP=`mktemp "${_TMPDIR}/setup.sh.XXXXXXXXXX"`
unset _TMPDIR
if [ $? -ne 0 -o ! -f "$_SETUP_TMP" ]; then
echo "Could not create temporary file: $_SETUP_TMP"
return 1
fi
CATKIN_SHELL=$CATKIN_SHELL "$_SETUP_UTIL" $@ ${CATKIN_SETUP_UTIL_ARGS:-} >> "$_SETUP_TMP"
_RC=$?
if [ $_RC -ne 0 ]; then
if [ $_RC -eq 2 ]; then
echo "Could not write the output of '$_SETUP_UTIL' to temporary file '$_SETUP_TMP': may be the disk if full?"
else
echo "Failed to run '\"$_SETUP_UTIL\" $@': return code $_RC"
fi
unset _RC
unset _SETUP_UTIL
rm -f "$_SETUP_TMP"
unset _SETUP_TMP
return 1
fi
unset _RC
unset _SETUP_UTIL
. "$_SETUP_TMP"
rm -f "$_SETUP_TMP"
unset _SETUP_TMP
# source all environment hooks
_i=0
while [ $_i -lt $_CATKIN_ENVIRONMENT_HOOKS_COUNT ]; do
eval _envfile=\$_CATKIN_ENVIRONMENT_HOOKS_$_i
unset _CATKIN_ENVIRONMENT_HOOKS_$_i
eval _envfile_workspace=\$_CATKIN_ENVIRONMENT_HOOKS_${_i}_WORKSPACE
unset _CATKIN_ENVIRONMENT_HOOKS_${_i}_WORKSPACE
# set workspace for environment hook
CATKIN_ENV_HOOK_WORKSPACE=$_envfile_workspace
. "$_envfile"
unset CATKIN_ENV_HOOK_WORKSPACE
_i=$((_i + 1))
done
unset _i
unset _CATKIN_ENVIRONMENT_HOOKS_COUNT
|
<gh_stars>1-10
package malte0811.controlengineering.logic.schematic.client;
import com.mojang.blaze3d.vertex.PoseStack;
import malte0811.controlengineering.logic.schematic.Schematic;
import malte0811.controlengineering.logic.schematic.SchematicNet;
import malte0811.controlengineering.logic.schematic.symbol.*;
import malte0811.controlengineering.util.math.Vec2d;
import net.minecraft.client.Minecraft;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
public class ClientSymbols {
private static final Map<SchematicSymbol<?>, ClientSymbol<?, ?>> CLIENT_SYMBOLS = new HashMap<>();
public static void init() {
final int secondColumn = 13;
register(SchematicSymbols.CONSTANT, ClientConstantSymbol::new);
registerWithOverlay(SchematicSymbols.INPUT_PIN_ANALOG, ClientIOSymbol::new, "A", 4, 0);
registerWithOverlay(SchematicSymbols.INPUT_PIN_DIGITAL, ClientIOSymbol::new, "D", 4, 0);
register(SchematicSymbols.OUTPUT_PIN, ClientIOSymbol::new);
register(SchematicSymbols.AND2, 0, 0);
register(SchematicSymbols.AND3, 0, 14);
register(SchematicSymbols.OR2, 0, 7);
register(SchematicSymbols.OR3, 0, 21);
register(SchematicSymbols.NAND2, secondColumn, 0);
register(SchematicSymbols.NAND3, secondColumn, 14);
register(SchematicSymbols.NOR2, secondColumn, 7);
register(SchematicSymbols.NOR3, secondColumn, 21);
register(SchematicSymbols.XOR2, 0, 28);
register(SchematicSymbols.XOR3, 0, 35);
register(SchematicSymbols.NOT, secondColumn, 28);
register(SchematicSymbols.RS_LATCH, secondColumn, 49);
register(SchematicSymbols.SCHMITT_TRIGGER, 0, 42);
register(SchematicSymbols.DIGITIZER, secondColumn, 42);
register(SchematicSymbols.COMPARATOR, secondColumn, 35);
register(SchematicSymbols.D_LATCH, 0, 49);
register(SchematicSymbols.DELAY_LINE, 0, 56);
registerMUX(SchematicSymbols.ANALOG_MUX, "A");
registerMUX(SchematicSymbols.DIGITAL_MUX, "D");
register(SchematicSymbols.VOLTAGE_DIVIDER, ClientDividerSymbol::new);
register(SchematicSymbols.ANALOG_ADDER, 24, 11);
register(SchematicSymbols.INVERTING_AMPLIFIER, ClientInvAmpSymbol::new);
register(SchematicSymbols.TEXT, ClientTextSymbol::new);
register(SchematicSymbols.CONFIG_SWITCH, ClientConfigSwitch::new);
}
public static <State> void renderCenteredInBox(
SymbolInstance<State> inst, PoseStack transform, int x, int y, int xSpace, int ySpace
) {
final var level = Objects.requireNonNull(Minecraft.getInstance().level);
final var type = inst.getType();
final var width = type.getXSize(inst.getCurrentState(), level);
final var height = type.getYSize(inst.getCurrentState(), level);
final var scale = Math.max(1, Math.min(width / (float) xSpace, height / (float) ySpace));
transform.pushPose();
transform.translate(x + xSpace / 2., y + ySpace / 2., 0);
transform.scale(scale, scale, 1);
transform.translate(-width / 2., -height / 2., 0);
render(inst, transform, 0, 0);
transform.popPose();
}
public static <State> void render(SymbolInstance<State> inst, PoseStack transform, int x, int y) {
render(inst.getType(), transform, x, y, inst.getCurrentState());
}
public static <State>
void render(SchematicSymbol<State> serverSymbol, PoseStack transform, int x, int y, State state) {
getClientSymbol(serverSymbol).render(transform, x, y, state);
}
public static void render(PlacedSymbol placed, PoseStack transform) {
render(placed.symbol(), transform, placed.position().x(), placed.position().y());
}
public static void render(Schematic schematic, PoseStack stack, Vec2d mouse) {
for (PlacedSymbol s : schematic.getSymbols()) {
render(s, stack);
}
for (SchematicNet net : schematic.getNets()) {
net.render(stack, mouse, schematic.getSymbols());
}
}
public static <State>
void createInstanceWithUI(
SchematicSymbol<State> symbol, Consumer<? super SymbolInstance<State>> onDone, State initialState
) {
getClientSymbol(symbol).createInstanceWithUI(onDone, initialState);
}
public static <State>
void createInstanceWithUI(SchematicSymbol<State> symbol, Consumer<? super SymbolInstance<State>> onDone) {
createInstanceWithUI(symbol, onDone, symbol.getInitialState());
}
@SuppressWarnings("unchecked")
private static <State, Symbol extends SchematicSymbol<State>>
ClientSymbol<State, Symbol> getClientSymbol(Symbol server) {
return (ClientSymbol<State, Symbol>) CLIENT_SYMBOLS.get(server);
}
private static void register(CellSymbol cell, int uMin, int vMin) {
register(cell, new ClientCellSymbol(cell, uMin, vMin));
}
private static void registerMUX(CellSymbol cell, String overlay) {
register(cell, new ClientOverlaySymbol<>(new ClientCellSymbol(cell, 13, 56), overlay, 3, 3));
}
private static <State, Symbol extends SchematicSymbol<State>>
void register(Symbol server, Function<Symbol, ClientSymbol<State, Symbol>> makeClient) {
register(server, makeClient.apply(server));
}
private static <State, Symbol extends SchematicSymbol<State>>
void registerWithOverlay(
Symbol server,
Function<Symbol, ClientSymbol<State, Symbol>> makeClient,
String overlay, float xOff, float yOff
) {
register(server, new ClientOverlaySymbol<>(makeClient.apply(server), overlay, xOff, yOff));
}
private static <State, Symbol extends SchematicSymbol<State>>
void register(Symbol server, ClientSymbol<State, Symbol> client) {
CLIENT_SYMBOLS.put(server, client);
}
}
|
#!/usr/bin/env bash
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
function exit_with_usage {
cat << EOF
usage: package
run package command based on different spark version.
Inputs are specified with the following environment variables:
MLSQL_SPARK_VERSION - the spark version, 2.4/3.0 default 2.4
DRY_RUN true|false default false
DISTRIBUTION true|false default false
DATASOURCE_INCLUDED true|false default false
EOF
exit 1
}
set -e
set -o pipefail
if [[ $@ == *"help"* ]]; then
exit_with_usage
fi
SELF=$(cd $(dirname $0) && pwd)
cd $SELF
cd ..
MLSQL_SPARK_VERSION=${MLSQL_SPARK_VERSION:-2.4}
DRY_RUN=${DRY_RUN:-false}
DISTRIBUTION=${DISTRIBUTION:-false}
OSS_ENABLE=${OSS_ENABLE:-false}
DATASOURCE_INCLUDED=${DATASOURCE_INCLUDED:-false}
COMMAND=${COMMAND:-package}
ENABLE_JYTHON=${ENABLE_JYTHON=-true}
ENABLE_CHINESE_ANALYZER=${ENABLE_CHINESE_ANALYZER=-true}
ENABLE_HIVE_THRIFT_SERVER=${ENABLE_HIVE_THRIFT_SERVER=-true}
for env in MLSQL_SPARK_VERSION DRY_RUN DISTRIBUTION; do
if [[ -z "${!env}" ]]; then
echo "===$env must be set to run this script==="
echo "===Please run ./dev/package.sh help to get how to use.==="
exit 1
fi
done
if [[ ${ENABLE_CHINESE_ANALYZER} = true && ! -f $SELF/../dev/ansj_seg-5.1.6.jar && ! -f $SELF/../dev/nlp-lang-1.7.8.jar ]]
then
echo "When ENABLE_CHINESE_ANALYZER=true, ansj_seg-5.1.6.jar && nlp-lang-1.7.8.jar should be in ./dev/"
exit 1
fi
# before we compile and package, correct the version in MLSQLVersion
#---------------------
unameOut="$(uname -s)"
case "${unameOut}" in
Linux*) machine=Linux;;
Darwin*) machine=Mac;;
CYGWIN*) machine=Cygwin;;
MINGW*) machine=MinGw;;
*) machine="UNKNOWN:${unameOut}"
esac
echo ${machine}
current_version=$(cat pom.xml|grep -e '<version>.*</version>' | head -n 1 | tail -n 1 | cut -d'>' -f2 | cut -d '<' -f1)
MLSQL_VERSION_FILE="./streamingpro-core/src/main/java/tech/mlsql/core/version/MLSQLVersion.scala"
if [[ "${machine}" == "Linux" ]]
then
sed -i "s/MLSQL_VERSION_PLACEHOLDER/${current_version}/" ${MLSQL_VERSION_FILE}
elif [[ "${machine}" == "Mac" ]]
then
sed -i '' "s/MLSQL_VERSION_PLACEHOLDER/${current_version}/" ${MLSQL_VERSION_FILE}
else
echo "Windows is not supported yet"
exit 0
fi
#---------------------
BASE_PROFILES="-Ponline "
if [[ "${ENABLE_HIVE_THRIFT_SERVER}" == "true" ]]; then
BASE_PROFILES="$BASE_PROFILES -Phive-thrift-server"
fi
if [[ "${ENABLE_JYTHON}" == "true" ]]; then
BASE_PROFILES="$BASE_PROFILES -Pjython-support"
fi
if [[ "${ENABLE_CHINESE_ANALYZER}" == "true" ]]; then
BASE_PROFILES="$BASE_PROFILES -Pchinese-analyzer-support"
fi
if [[ "$MLSQL_SPARK_VERSION" == "2.4" ]]; then
BASE_PROFILES="$BASE_PROFILES -Pscala-2.11"
else
BASE_PROFILES="$BASE_PROFILES -Pscala-2.12"
fi
BASE_PROFILES="$BASE_PROFILES -Pspark-$MLSQL_SPARK_VERSION.0 -Pstreamingpro-spark-$MLSQL_SPARK_VERSION.0-adaptor"
if [[ ${DISTRIBUTION} == "true" ]];then
BASE_PROFILES="$BASE_PROFILES -Passembly"
else
BASE_PROFILES="$BASE_PROFILES -pl streamingpro-mlsql -am"
fi
export MAVEN_OPTS="-Xmx6000m"
SKIPTEST=""
TESTPROFILE=""
if [[ "${COMMAND}" == "package" ]];then
BASE_PROFILES="$BASE_PROFILES -Pshade"
fi
if [[ "${COMMAND}" == "package" || "${COMMAND}" == "install" || "${COMMAND}" == "deploy" ]];then
SKIPTEST="-DskipTests"
fi
if [[ "${COMMAND}" == "test" ]];then
TESTPROFILE="-Punit-test"
fi
if [[ "${COMMAND}" == "deploy" ]];then
BASE_PROFILES="$BASE_PROFILES -Prelease-sign-artifacts"
BASE_PROFILES="$BASE_PROFILES -Pdisable-java8-doclint"
fi
if [[ "${OSS_ENABLE}" == "true" ]];then
BASE_PROFILES="$BASE_PROFILES -Paliyun-oss"
fi
if [[ "$DATASOURCE_INCLUDED" == "true" ]];then
BASE_PROFILES="$BASE_PROFILES -Punit-test"
fi
if [[ ${DRY_RUN} == "true" ]];then
cat << EOF
mvn clean ${COMMAND} ${SKIPTEST} ${BASE_PROFILES} ${TESTPROFILE}
EOF
else
cat << EOF
mvn clean ${COMMAND} ${SKIPTEST} ${BASE_PROFILES} ${TESTPROFILE}
EOF
mvn clean ${COMMAND} ${SKIPTEST} ${BASE_PROFILES} ${TESTPROFILE}
fi
|
#!/bin/bash
function usage() {
echo "Usage: "$0" <ip> <start> <end>"
if [ -n "$1" ] ; then
echo "Error: "$1"!"
fi
exit
}
if ! [ $# -eq 3 ] ; then
usage
fi
ip=$1
start=$2
end=$3
n=0
for i in $(seq $start $end); do
tmp=`nmap -sP $ip"."$i | grep -B 1 'Host is up' |grep 'scan report' |cut -d ' ' -f 5`
if [ -n "$tmp" ] ; then
echo $tmp
n=$[$n+1]
fi
done
echo
echo $n" hosts are up."
exit
|
# Source this file to prepare a mac for running scripts
hash greadlink 2>/dev/null || { echo >&2 "Required tool greadlink is not installed, please run 'brew install coreutils'"; exit 1; }
hash gfind 2>/dev/null || { echo >&2 "Required tool gfind is not installed, please run 'brew install findutils'"; exit 1; }
hash gsed 2>/dev/null || { echo >&2 "Required tool gsed is not installed, please run 'brew install gnu-sed'"; exit 1; }
if [[ ! -d /tmp/docker-solr-bin ]]; then
mkdir -p /tmp/docker-solr-bin >/dev/null 2>&1
ln -s /usr/local/bin/greadlink /tmp/docker-solr-bin/readlink
ln -s /usr/local/bin/gfind /tmp/docker-solr-bin/find
ln -s /usr/local/bin/gsed /tmp/docker-solr-bin/sed
fi
if [[ ! $PATH == *"docker-solr-bin"* ]]; then
export PATH=/tmp/docker-solr-bin:$PATH
echo "Configuring for macOS - adding /tmp/docker-solr-bin first in path"
fi |
#! /bin/bash
set -euxo pipefail
SCRIPT_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
pushd "$SCRIPT_DIR"
az extension add --upgrade --yes --name connectedk8s
az extension add --upgrade --yes --name k8s-extension
az extension add --upgrade --yes --name customlocation
az provider register --namespace Microsoft.ExtendedLocation --wait
az provider register --namespace Microsoft.Web --wait
az provider register --namespace Microsoft.KubernetesConfiguration --wait
az extension remove --name appservice-kube
az extension add --upgrade --yes --name appservice-kube
popd
set -euxo pipefail |
<filename>javascript-version/bot/commands/moderation/slowmode.js
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports = {
category: 'Moderation',
aliases: [''],
minArgs: 1,
maxArgs: -1,
expectedArgs: 'please enter a time in minutes',
description: 'changes slowmode on a channel',
callback: async ({message, args, text, client, prefix, instance}) => {
if (message.member.hasPermission('MANAGE_CHANNELS')|| message.author.id == 3<PASSWORD>) {
if (!args[0]) return message.channel.send('please include a number');
let time = args[0];
let times = time * 60;
let reason = args.slice(1).join(' ');
if (!reason) reason = 'No reason provided';
async function slowmode() {
await message.channel
.setRateLimitPerUser(times)
.catch((error) =>
message.channel.send(
`Sorry ${message.author} I couldn't execute because of : ${error}`
)
);
const Embed = new Discord.MessageEmbed()
.setColor(0x00ae86)
.setTimestamp()
.setAuthor(
`slowmode has been set to ${args[0]} minutes reason: ${reason}`
);
message.reply(Embed).then((msg) => {
msg.delete({ timeout: 5000 });
});
}
slowmode();
return
}
const Embed = new Discord.MessageEmbed()
.setColor('#03fc49')
.setTitle(`Error, you are not allowed to do this`)
message.reply(Embed)
return
},
};
|
#!/bin/bash
BM="$1"
pushd ../
./streamlined_experiment.py --hs arquinn-QV15174.dift-pg0.apt.emulab.net -p Br@nf0rd123 -t $BM --sf server_config.first.1 --nr 1 --offset 0 --sc --ec /experiment.config.1 --only_seq &>run.test.$BM.0.1&
sleep 2
./streamlined_experiment.py --hs arquinn-QV15174.dift-pg0.apt.emulab.net -p Br@nf0rd123 -t $BM --sf server_config.second.1 --nr 1 --offset 1 --sc --ec /experiment.config.1 --only_seq &>run.test.$BM.1.1&
sleep 2
./streamlined_experiment.py --hs arquinn-QV15174.dift-pg0.apt.emulab.net -p Br@nf0rd123 -t $BM --sf server_config.third.1 --nr 1 --offset 2 --sc --ec /experiment.config.1 --only_seq &>run.test.$BM.2.1&
sleep 2
./streamlined_experiment.py --hs arquinn-QV15174.dift-pg0.apt.emulab.net -p Br@nf0rd123 -t $BM --sf server_config.fourth.1 --nr 1 --offset 3 --sc --ec /experiment.config.1 --only_seq &>run.tes.$BM.3.1&
sleep 2
./streamlined_experiment.py --hs arquinn-QV15174.dift-pg0.apt.emulab.net -p Br@nf0rd123 -t $BM --sf server_config.fifth.1 --nr 1 --offset 4 --sc --ec /experiment.config.1 --only_seq
popd |
<filename>lib-arch-app-initializer/src/main/java/ltd/dolink/arch/initializer/ApplicationOwner.java<gh_stars>0
package ltd.dolink.arch.initializer;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.HasDefaultViewModelProviderFactory;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.ProcessLifecycleOwner;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProvider.Factory;
import androidx.lifecycle.ViewModelStore;
import androidx.lifecycle.ViewModelStoreOwner;
public class ApplicationOwner implements LifecycleOwner, ViewModelStoreOwner, HasDefaultViewModelProviderFactory {
private static ApplicationOwner applicationOwner;
private final Application application;
private final ViewModelStore viewModelStore;
private final ViewModelProvider.Factory factory;
public ApplicationOwner(Application application) {
this.application = application;
applicationOwner = this;
viewModelStore = new ViewModelStore();
factory = (Factory) ViewModelProvider.AndroidViewModelFactory.getInstance(application);
}
@NonNull
public static ApplicationOwner getInstance() {
return applicationOwner;
}
@NonNull
public Application getApplication() {
return application;
}
@NonNull
@Override
public ViewModelStore getViewModelStore() {
return viewModelStore;
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return ProcessLifecycleOwner.get().getLifecycle();
}
@NonNull
@Override
public Factory getDefaultViewModelProviderFactory() {
return factory;
}
}
|
name = input("Enter your name:")
print("Welcome to my program " + name + "!") |
package io.opensphere.wfs.state;
import io.opensphere.core.Toolbox;
import io.opensphere.core.modulestate.AbstractModuleStateController;
import io.opensphere.server.toolbox.ServerToolbox;
import io.opensphere.server.toolbox.WFSLayerConfigurationManager;
import io.opensphere.wfs.state.activate.WFSDataTypeBuilder;
import io.opensphere.wfs.state.activate.WFSStateActivator;
import io.opensphere.wfs.state.controllers.WFSNodeReader;
import io.opensphere.wfs.state.deactivate.WFSStateDeactivator;
import io.opensphere.wfs.state.save.WFSStateSaver;
/**
* Base class for WFS state controller.
*/
public abstract class BaseWFSStateController extends AbstractModuleStateController
{
/** The State saver. */
private final WFSStateSaver myStateSaver;
/** The Activator. */
private final WFSStateActivator myActivator;
/** The Deactivator. */
private final WFSStateDeactivator myDeactivator;
/**
* The toolbox through which application state is accessed.
*/
private final Toolbox myToolbox;
/**
* Instantiates a new base wfs state controller.
*
* @param toolbox the toolbox
*/
public BaseWFSStateController(Toolbox toolbox)
{
myToolbox = toolbox;
myStateSaver = new WFSStateSaver(toolbox);
WFSLayerConfigurationManager configurationManager = toolbox.getPluginToolboxRegistry()
.getPluginToolbox(ServerToolbox.class).getLayerConfigurationManager();
myActivator = new WFSStateActivator(toolbox, new WFSDataTypeBuilder(toolbox), new WFSNodeReader(configurationManager));
myDeactivator = new WFSStateDeactivator(toolbox);
}
/**
* Gets the value of the {@link #myToolbox} field.
*
* @return the value stored in the {@link #myToolbox} field.
*/
public Toolbox getToolbox()
{
return myToolbox;
}
/**
* Gets the activator.
*
* @return the activator
*/
public WFSStateActivator getActivator()
{
return myActivator;
}
/**
* Gets the deactivator.
*
* @return the deactivator
*/
public WFSStateDeactivator getDeactivator()
{
return myDeactivator;
}
/**
* Gets the layer state saver.
*
* @return The state saver.
*/
public WFSStateSaver getSaver()
{
return myStateSaver;
}
}
|
for (int i = 0; i < n; i++) {
int j = i;
while (j < n) {
sum += a[i][j] * b[j];
j++;
}
} |
<filename>js/menu.js<gh_stars>1-10
let menuBtn = document.getElementById("menu-toggle");
let menuContainer = document.getElementById("menu-container");
let menuIsOpen = false;
function showMenu() {
if(document.body.clientWidth > 1480) {
menuContainer.style.display = "none";
menuContainer.style.top = "-100%";
menuIsOpen = false;
menuContainer.style.transition = "all 0.4s";
menuBtn.innerHTML = "<i class='bx bx-menu'></i>";
}
}
window.onload = showMenu;
window.onresize = showMenu;
menuBtn.addEventListener("click", () => {
if(menuIsOpen) {
menuIsOpen = false;
menuContainer.style.display = "none";
menuContainer.style.top = "-100%";
menuContainer.style.transition = "all 0.4s";
menuBtn.style.color = "rgba(255, 255, 255, 0.85)";
menuBtn.innerHTML = "<i class='bx bx-menu'></i>";
} else {
menuIsOpen = true;
menuContainer.style.display = "block";
menuContainer.style.top = "150px";
menuContainer.style.transition = "all 0.4s";
menuBtn.style.color = "white";
menuBtn.innerHTML = "<i class='bx bx-x' ></i>";
}
})
|
<gh_stars>1-10
package com.duy.imageoverlay.data;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v7.widget.SwitchCompat;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;
import com.alexvasilkov.gestures.Settings;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.duy.imageoverlay.R;
import com.duy.imageoverlay.adapters.IntervalAdapter;
import com.duy.imageoverlay.adapters.ModeAdapter;
import com.duy.imageoverlay.views.GirdFrameLayout;
import com.duy.imageoverlay.views.ImageUtils;
import com.flask.colorpicker.ColorPickerView;
import com.flask.colorpicker.OnColorSelectedListener;
import com.flask.colorpicker.builder.ColorPickerClickListener;
import com.flask.colorpicker.builder.ColorPickerDialogBuilder;
import java.io.File;
import java.io.IOException;
/**
* Created by Duy on 17-Feb-17.
*/
public class GridViewSetting implements View.OnClickListener {
private static final String TAG = GridViewSetting.class.getSimpleName();
private static final float OVERSCROLL = 32f;
private static final long SLOW_ANIMATIONS = 1000L;
private final Database mDatabase;
private final Activity mActivity;
private final ViewGroup mContainerSetting;
private final SubsamplingScaleImageView photoView;
private OnImageListener imageListener;
private GirdFrameLayout mGridLayout;
private Spinner spinnerColor, spinnerInterval, spinnerMode;
private SwitchCompat showVerticalSwitch;
private SwitchCompat showHorizontalSwitch;
private SwitchCompat enabledSwitch;
private Button btnChooseColor;
private View mColorPreview;
private Spinner spinnerSizePaint;
private View mBackgroundReview;
private Uri uriOriginalImage;
private boolean isPanEnabled = true;
private boolean isZoomEnabled = true;
private boolean isRotationEnabled = false;
private boolean isRestrictRotation = false;
private boolean isOverscrollXEnabled = false;
private boolean isOverscrollYEnabled = false;
private boolean isOverzoomEnabled = true;
private boolean isExitEnabled = false;
private boolean isFillViewport = true;
private Settings.Fit fitMethod = Settings.Fit.INSIDE;
private int gravity = Gravity.CENTER;
private boolean isSlow = false;
private TypeFilter typeFilter = TypeFilter.NORMAL;
private Spinner spinnerFilters;
public GridViewSetting(Activity mActivity,
GirdFrameLayout girdFrameLayout,
ViewGroup mContainerView1,
SubsamplingScaleImageView photoView) {
this.mActivity = mActivity;
this.mContainerSetting = mContainerView1;
this.photoView = photoView;
this.mGridLayout = girdFrameLayout;
this.mDatabase = new Database(mActivity);
}
public void setup() {
setupModesSpinner();
setupIntervalSpinner();
setupColorLines();
setupShowVerticalSwitch();
setupShowHorizontalSwitch();
setupEnabledSwitch();
setupSizePaint();
setupBackground();
setupFilter();
}
private void setupFilter() {
spinnerFilters = (Spinner) findViewById(R.id.spinner_filter);
spinnerFilters.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0)
typeFilter = TypeFilter.NORMAL;
else
typeFilter = TypeFilter.BW;
if (uriOriginalImage != null) {
new LoadImageTask().execute(uriOriginalImage);
} else {
Toast.makeText(mActivity, R.string.msg_select_img, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerFilters.setSelection(mDatabase.getInt(Database.FILTER_TYPE, 0));
}
private void addSwitch(boolean checked, int titleId) {
float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, mActivity.getResources().getDisplayMetrics());
SwitchCompat item = new SwitchCompat(mActivity);
item.setChecked(checked);
item.setText(titleId);
item.setId(titleId);
item.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
item.setOnClickListener(this);
item.setMinHeight((int) pixels);
mContainerSetting.addView(item);
}
@Override
public void onClick(View view) {
Log.d(TAG, "onClick: " + view.toString());
switch (view.getId()) {
case R.string.menu_enable_pan:
isPanEnabled = !isPanEnabled;
break;
case R.string.menu_enable_zoom:
isZoomEnabled = !isZoomEnabled;
break;
case R.string.menu_enable_rotation:
isRotationEnabled = !isRotationEnabled;
break;
case R.string.menu_restrict_rotation:
isRestrictRotation = !isRestrictRotation;
break;
case R.string.menu_enable_overscroll_x:
isOverscrollXEnabled = !isOverscrollXEnabled;
break;
case R.string.menu_enable_overscroll_y:
isOverscrollYEnabled = !isOverscrollYEnabled;
break;
case R.string.menu_enable_overzoom:
isOverzoomEnabled = !isOverzoomEnabled;
break;
case R.string.menu_enable_exit:
isExitEnabled = !isExitEnabled;
break;
case R.string.menu_fill_viewport:
isFillViewport = !isFillViewport;
break;
case R.string.menu_enable_slow:
isSlow = !isSlow;
break;
default:
break;
}
onSetupGestureView(photoView);
}
public void onSetupGestureView(SubsamplingScaleImageView view) {
}
/**
* set event for set background
*/
private void setupBackground() {
mBackgroundReview = findViewById(R.id.color_bg);
int color = mDatabase.getInt(Database.COLOR_BACKGROUND, Color.WHITE);
mBackgroundReview.setBackgroundColor(color);
mGridLayout.setBackgroundColor(color);
findViewById(R.id.btn_color_bg).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
ColorPickerDialogBuilder
.with(mActivity)
.setTitle("Choose color")
.initialColor(mDatabase.getInt(Database.COLOR_BACKGROUND, Color.WHITE))
.wheelType(ColorPickerView.WHEEL_TYPE.FLOWER)
.density(12)
.setOnColorSelectedListener(new OnColorSelectedListener() {
@Override
public void onColorSelected(int selectedColor) {
Log.d(TAG, "onColorSelected: 0x" + Integer.toHexString(selectedColor));
}
})
.setPositiveButton("OK", new ColorPickerClickListener() {
@Override
public void onClick(DialogInterface dialog, int selectedColor, Integer[] allColors) {
mGridLayout.setBackgroundColor(selectedColor);
mDatabase.putInt(Database.COLOR_BACKGROUND, selectedColor);
mBackgroundReview.setBackgroundColor(selectedColor);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.build()
.show();
}
});
}
/**
* set data for spinner mode
*/
private void setupModesSpinner() {
spinnerMode = (Spinner) findViewById(R.id.debug_mode);
final ModeAdapter adapter = new ModeAdapter(mActivity);
spinnerMode.setAdapter(adapter);
spinnerMode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mGridLayout.setMode(adapter.getItem(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//top-left
spinnerMode.setSelection(mDatabase.getInt(Database.MODE_POSITION, 1));
}
private View findViewById(int id) {
return mActivity.findViewById(id);
}
private void setupIntervalSpinner() {
spinnerInterval = (Spinner) findViewById(R.id.debug_interval);
final IntervalAdapter adapter = new IntervalAdapter(mActivity);
spinnerInterval.setAdapter(adapter);
spinnerInterval.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mGridLayout.setIntervalDp(adapter.getItem(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerInterval.setSelection(mDatabase.getInt(Database.INTERVAL_POSITION, 2));
}
private void setupColorLines() {
mColorPreview = findViewById(R.id.color_preview);
int color = mDatabase.getInt(Database.COLOR_LINE, Color.BLACK);
mColorPreview.setBackgroundColor(color);
mGridLayout.setColor(color);
btnChooseColor = (Button) findViewById(R.id.btn_choose_color);
btnChooseColor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
ColorPickerDialogBuilder
.with(mActivity)
.setTitle("Choose color")
.initialColor(mDatabase.getInt(Database.COLOR_LINE, Color.WHITE))
.wheelType(ColorPickerView.WHEEL_TYPE.FLOWER)
.density(12)
.setOnColorSelectedListener(new OnColorSelectedListener() {
@Override
public void onColorSelected(int selectedColor) {
Log.d(TAG, "onColorSelected: 0x" + Integer.toHexString(selectedColor));
}
})
.setPositiveButton("OK", new ColorPickerClickListener() {
@Override
public void onClick(DialogInterface dialog, int selectedColor, Integer[] allColors) {
mGridLayout.setColor(selectedColor);
mDatabase.putInt(Database.COLOR_LINE, selectedColor);
mColorPreview.setBackgroundColor(selectedColor);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.build()
.show();
}
});
}
private void setupShowVerticalSwitch() {
showVerticalSwitch = (SwitchCompat) findViewById(R.id.debug_show_vertical);
showVerticalSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mGridLayout.setDrawVerticalLines(isChecked);
}
});
showVerticalSwitch.setChecked(mDatabase.get(Database.DRAW_VERTICAL_LINE, true));
}
private void setupShowHorizontalSwitch() {
showHorizontalSwitch = (SwitchCompat) findViewById(R.id.debug_show_horizontal);
showHorizontalSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mGridLayout.setDrawHorizontalLines(isChecked);
}
});
showHorizontalSwitch.setChecked(mDatabase.get(Database.DRAW_HORIZONTAL_LINE, true));
}
private void setupEnabledSwitch() {
enabledSwitch = (SwitchCompat) findViewById(R.id.debug_enabled);
enabledSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mGridLayout.setEnabled(isChecked);
}
});
}
/**
* save data to storage
*/
public void onPause() {
/**
* recycle bitmap
*/
// originalBitmap = null;
mDatabase.putInt(Database.MODE_POSITION, spinnerMode.getSelectedItemPosition());
mDatabase.putInt(Database.INTERVAL_POSITION, spinnerInterval.getSelectedItemPosition());
mDatabase.putBool(Database.DRAW_VERTICAL_LINE, showVerticalSwitch.isChecked());
mDatabase.putBool(Database.DRAW_HORIZONTAL_LINE, showHorizontalSwitch.isChecked());
mDatabase.putString(Database.PAINT_SIZE_POSITION, spinnerSizePaint.getSelectedItem().toString());
if (uriOriginalImage != null)
mDatabase.putString(Database.LASTEST_FILE, uriOriginalImage.toString());
}
private void setupSizePaint() {
spinnerSizePaint = (Spinner) findViewById(R.id.spinner_size_paint);
final String[] arr = mActivity.getResources().getStringArray(R.array.size_paint);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(mActivity, android.R.layout.simple_list_item_1, arr);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinnerSizePaint.setAdapter(arrayAdapter);
spinnerSizePaint.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemSelected: " + arr[position]);
mGridLayout.setPaintWidth(Integer.parseInt(arr[position]));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// int position = mDatabase.getInt(Database.PAINT_SIZE_POSITION, 0);
// Log.d(TAG, "setupSizePaint: " + position);
// spinnerSizePaint.setSelection(position);
}
public OnImageListener getImageListener() {
return imageListener;
}
public void setImageListener(OnImageListener imageListener) {
this.imageListener = imageListener;
}
/**
* reload image
*
* @param uri
*/
public void onImageChange(Uri uri) {
Log.d(TAG, "onImageChange: uri" + uri.toString());
this.uriOriginalImage = uri;
new LoadImageTask().execute(uri);
// photoView.setImage(ImageSource.uri(uri));
}
private Bitmap createImageWithFilter(Bitmap bitmap) {
if (typeFilter == TypeFilter.NORMAL) {
return bitmap;
} else {
// Filter myFilter = new Filter();
// myFilter.addSubFilter(new BrightnessSubfilter(30));
// myFilter.addSubFilter(new ContrastSubfilter(1.1f));
// Bitmap outputImage = myFilter.processFilter(bitmap);
// return outputImage;
return bitmap;
}
}
public void onImageChange(String path) {
try {
File file = new File(path);
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
bitmap = createImageWithFilter(bitmap);
// this.originalBitmap = bitmap;
photoView.setImage(ImageSource.bitmap(bitmap));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* this method used to load image when resume activity or restart app
*/
public void onResume() {
// if (!mDatabase.getString(Database.LASTEST_FILE).isEmpty()) {
// try {
// uriOriginalImage = Uri.parse(mDatabase.getString(Database.LASTEST_FILE));
// new LoadImageTask().execute(uriOriginalImage);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
}
private enum TypeFilter {
NORMAL, BW
}
/**
* class load image
*/
public class LoadImageTask extends AsyncTask<Uri, Void, Bitmap> {
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(mActivity);
dialog.setMessage("Loading");
dialog.setCancelable(false);
dialog.show();
}
@Override
protected Bitmap doInBackground(Uri... params) {
Log.d(TAG, "doInBackground: ");
Bitmap bitmap;
try {
bitmap = MediaStore.Images.Media.getBitmap(mActivity.getContentResolver(), params[0]);
if (typeFilter == TypeFilter.NORMAL) {
return bitmap;
} else {
return ImageUtils.createBlackAndWhite(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap != null) {
photoView.setImage(ImageSource.bitmap(bitmap));
} else {
Toast.makeText(mActivity, "Failed", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}
@Override
protected void onCancelled() {
super.onCancelled();
dialog.dismiss();
}
@Override
protected void onCancelled(Bitmap bitmap) {
super.onCancelled(bitmap);
dialog.dismiss();
}
}
}
|
# -*- encoding: utf-8 -*-
# stub: backports 3.18.2 ruby lib
Gem::Specification.new do |s|
s.name = "backports".freeze
s.version = "3.18.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.metadata = { "bug_tracker_uri" => "https://github.com/marcandre/backports/issues", "changelog_uri" => "https://github.com/marcandre/backports/blob/master/CHANGELOG.md", "source_code_uri" => "https://github.com/marcandre/backports" } if s.respond_to? :metadata=
s.require_paths = ["lib".freeze]
s.authors = ["Marc-Andr\u00E9 Lafortune".freeze]
s.date = "2020-08-26"
s.description = "Essential backports that enable many of the nice features of Ruby for earlier versions.".freeze
s.email = ["<EMAIL>".freeze]
s.homepage = "http://github.com/marcandre/backports".freeze
s.licenses = ["MIT".freeze]
s.rubygems_version = "3.0.3".freeze
s.summary = "Backports of Ruby features for older Ruby.".freeze
s.installed_by_version = "3.0.3" if s.respond_to? :installed_by_version
end
|
import React from 'react';
const MealDashboard = () => (
<div className="diary">
<div className="nutrient-titles">
<div className="calories">Calories</div>
<div className="calcium">Calcium</div>
<div className="iron">Iron</div>
<div className="protein">Protein</div>
</div>
<div className="meal-container">
<div className="breakfast">
<h6>Breakfast</h6>
</div>
<div className="nutrient-count valign-wrapper">
<div className="value">100</div>
<div className="value">100</div>
<div className="value">100</div>
<div className="value">100</div>
</div>
</div>
<div className="meal-container">
<div className="lunch">
<h6>Lunch</h6>
</div>
<div className="nutrient-count valign-wrapper">
<div className="value">100</div>
<div className="value">100</div>
<div className="value">100</div>
<div className="value">100</div>
</div>
</div>
<div className="meal-container">
<div className="dinner">
<h6>Dinner</h6>
</div>
<div className="nutrient-count valign-wrapper">
<div className="value">100</div>
<div className="value">100</div>
<div className="value">100</div>
<div className="value">100</div>
</div>
</div>
<div className="meal-container">
<div className="snacks">
<h6>Snacks</h6>
</div>
<div className="nutrient-count valign-wrapper">
<div className="value">100</div>
<div className="value">100</div>
<div className="value">100</div>
<div className="value">100</div>
</div>
</div>
</div>
);
export default Meal;
|
class Movie < ApplicationRecord
belongs_to :genre
has_many :reviews, dependent: :destroy
has_many :users, through: :reviews
accepts_nested_attributes_for :genre
validates :title, presence: true
validates :synopsis, length: { in: 20..300}
validates :year, numericality: { greater_than: 1890 }
before_validation :titlecase
scope :order_by_year_desc, -> { order(year: :desc)}
scope :order_by_year_asc, -> { order(year: :asc)}
# sort movies abc and zyx
scope :alphabetically, -> { order(title: :asc)}
scope :alphabetically_reverse, -> { order(title: :desc)}
# search for movie by title
scope :search_by_title, -> (title) { where("title == ?", title)}
def format
"#{self.title} (#{self.year})"
end
def average_rating
sum = 0
count = 0
self.reviews.each do |rev|
sum += rev.rating
count += 1
end
avg = sum/count.to_f
avg.round(2)
end
def genre_attributes=(attribute_hash)
if !attribute_hash['name'].blank?
self.genre = Genre.find_or_create_by(attribute_hash)
end
end
private
def titlecase
self.title = self.title.titleize
end
end
|
import {
init,
classModule,
propsModule,
styleModule,
eventListenersModule,
h,
} from "snabbdom";
// diff 算法核心函数
const patch = init([
// Init patch function with chosen modules
classModule, // makes it easy to toggle classes
propsModule, // for setting properties on DOM elements
styleModule, // handles styling on elements with support for animations
eventListenersModule, // attaches event listeners
]);
var myNode = h("a",
{
props: {
href:'http:www.baidu.com',
target: "_blank"
}
},
'百度一下')
console.log(myNode)
const myNode2 = h("div", {
class: { box:'true' },
props: {}
}, "我是一个空盒子")
const myNode3 = h("div", "我是一个空盒子")
// h 函数也可以进行嵌套
const myNode4 = h('ul',"我是副元素",[
h("li",{key:1},[
h("h1","我又来来")
]),
h("li",{key:3},"栗子"), // 在生成的页面中修改此行 内容 栗子 为==“丑八怪”,点击后,发现这里没有发生变化,说明页面此处没有处理,是最小更新
// 当然如果前面有新增元素时候会发现发生变化了 ,因为这里没有加key
// 加上key以后就会发生没有变化
h("li",{key:4},"葡萄"),
h("li",{key:5},"香蕉"),
h("li",{key:6},h("h2","我是不带[]进来的")),
])
// 让虚拟节点上树
var container = document.getElementById("container")
patch(container, myNode4)
document.getElementById('btn').addEventListener('click', function(){
const myNode5 = h('ul',"我是副元素",[
h("li",{key:1}, [
h("h1","我又来来")
]),
h("li",{key:2},"我是新加的"),
h("li",{key:3},"栗子"),
h("li",{key:4},"葡萄"),
h("li",{key:5},"香蕉"),
h("li",{key:6},h("h2","我是不带[]进来的")),
h("li",{key:7},h("h2","我是不带[]进来的")),
h("li",{key:8},h("h2","我是不带[]进来的")),
h("li",{key:9},h("h2","我是不带[]进来的")),
h("li",{key:10},h("h2","我是不带[]进来的")),
h("li",{key:11},h("h2","我是不带[]进来的")),
h("li",{key:12},h("h2","我是不带[]进来的")),
h("li",{key:13},h("h2","我是不带[]进来的")),
])
patch(myNode4, myNode5)
}) |
<filename>scripts/changeScanner/getChanges.js
const { exec } = require('shelljs');
const getChanges = () => {
const execute = exec(`git diff --name-only latest ./packages`, {
silent: true,
}).stdout;
const changedFiles = execute.split('\n').filter(Boolean);
const changedPackages = {};
changedFiles.forEach(fileName => {
const nameParts = fileName.split('/');
const packageName = nameParts[2];
const filePath = nameParts.splice(3).join('/');
(changedPackages[packageName] = changedPackages[packageName] || []).push(
filePath,
);
});
return changedPackages;
};
module.exports = getChanges;
|
<filename>tests/afqmc/Ne_cc-pvdz/scf/scf.py
#! /usr/bin/env python3
import sys
import os
from pyscf import gto, scf, tools
import numpy
mol = gto.Mole(atom=[['Ne', (0,0,0)]],
basis='cc-pvdz',
unit='Angstrom',
verbose=4)
mol.build()
mf = scf.RHF(mol)
mf.chkfile = 'neon.chk.h5'
mf.kernel()
hcore = mf.get_hcore()
fock = mf.get_veff()
# ascii fcidump is converted using fcidump_to_qmcpack.py.
tools.fcidump.from_scf(mf, 'FCIDUMP')
nmo = mf.mo_coeff.shape[-1]
wfn_header = """&FCI
UHF = 0
CMajor
NCI = 1
TYPE = matrix
/"""
orbmat = numpy.identity(nmo,dtype=numpy.complex128)
with open("wfn_rhf.dat", 'w') as f:
f.write(wfn_header+'\n')
f.write('Coefficients: 1.0\n')
f.write('Determinant: 1\n')
for i in range(0,mol.nelec[0]):
occ = '0.0 '*i + '1.0' + ' 0.0'*(nmo-i-1) + '\n'
f.write(occ)
# Alternatively add FullMO to the header above and replace for loop above
# with double loop below.
# for i in range(0,nmo):
# for j in range(0,nmo):
# val = orbmat[i,j]
# f.write('(%.10e,%.10e) '%(val.real, val.imag))
# f.write('\n')
|
#!/bin/bash
#SBATCH --time=24:00:00
#SBATCH --nodes=1 --ntasks-per-node=2 --cpus-per-task=2
#SBATCH --gres=gpu:1
#SBATCH --partition=gpu
#SBATCH --mem=80G
DATASET=$1
CLASS=$2
module load Julia/1.5.1-linux-x86_64
module load Python/3.8.2-GCCcore-9.3.0
julia ./fAnoGAN_one_class.jl $DATASET $CLASS
|
#!/bin/bash
set -e
source $(dirname $0)/common.sh
repository=$(pwd)/distribution-repository
pushd git-repo > /dev/null
run_maven -f spring-boot-tests/spring-boot-smoke-tests/pom.xml clean install -U -Dfull -Drepository=file://${repository} -Duser.name=concourse
popd > /dev/null
|
<reponame>azjezz/waffle<gh_stars>1-10
<?hh // strict
namespace Waffle\Container;
use type Waffle\Container\Exception\ContainerException;
use type Waffle\Contract\Container\ContainerInterface;
trait ContainerAwareTrait
{
require implements ContainerAwareInterface;
protected ?ContainerInterface $container;
/**
* Set a container.
*/
public function setContainer(ContainerInterface $container): this
{
$this->container = $container;
return $this;
}
/**
* Get the container.
*/
public function getContainer(): ContainerInterface
{
if ($this->container instanceof ContainerInterface) {
return $this->container;
}
throw new ContainerException('No container implementation has been set.');
}
}
|
#include<stdio.h>
void main() {
int m[3][3], t[3][3], i, j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("Enter the m[%d][%d] element : ",i,j);
scanf("%d",&m[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
t[j][i] = m[i][j];
}
}
printf("\nThe transpose of the matrix is: \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d\t",t[i][j]);
printf("\n");
}
}
// Output:
// The transpose of the matrix is:
// 1 4 7
// 2 5 8
// 3 6 9 |
class BankAccount:
total_transactions = 0
def __init__(self):
self.balance = 0
def deposit(self, amount):
self.balance += amount
BankAccount.total_transactions += 1
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
BankAccount.total_transactions += 1
def get_balance(self):
return self.balance
@classmethod
def get_total_transactions(cls):
return cls.total_transactions |
import multer from "multer";
import FileConstants from "../constants/file.constants";
import { generateFileName } from "../utils/file.utils";
const storage = multer.diskStorage({
destination: `${FileConstants.BASE_DIR}`,
filename: function (req: any, file: any, cb: any) {
cb(null, generateFileName(file));
},
});
const fileFilter = (req: any, file: any, cb: any) => {
switch (file.mimetype) {
case "image/jpg":
case "image/jpeg":
case "image/png":
return cb(null, true);
default:
return cb(new Error("Unsupported file type"), false);
}
};
export const singleOrNone = (field: string) => {
try {
return multer({ storage: storage, fileFilter: fileFilter }).single(field);
} catch (err) {
return multer({ storage: storage, fileFilter: fileFilter }).none();
}
};
export default { singleOrNone };
|
#!/bin/bash
# Script to sync the dotfiles
. sudov.sh
. functions.sh
# Get rsync
pinstall rsync
# Sync up dotfiles
rsync -avh --no-perms ../dotfiles ~
|
def simulate_vehicle_movement(axle_spacing, total_axles, direction):
# Initialize the current axle location as 0
current_loc = 0
final_locations = []
# Simulate the movement of each axle based on the direction
for axle_num in range(1, total_axles + 1):
current_loc = mlob.move_axle_loc(axle_spacing, axle_num, current_loc, total_axles, direction)
final_locations.append(current_loc)
return final_locations |
package io.github.tehstoneman.cashcraft;
import java.util.Random;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.github.tehstoneman.cashcraft.api.CashCraftAPI;
import io.github.tehstoneman.cashcraft.common.item.CashCraftItemGroup;
import io.github.tehstoneman.cashcraft.config.CashCraftConfig;
import io.github.tehstoneman.cashcraft.economy.Economy;
import io.github.tehstoneman.cashcraft.economy.Trade;
import io.github.tehstoneman.cashcraft.proxy.ClientProxy;
import io.github.tehstoneman.cashcraft.proxy.IProxy;
import io.github.tehstoneman.cashcraft.proxy.ServerProxy;
import net.minecraft.item.ItemGroup;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
@Mod( ModInfo.MOD_ID )
public class CashCraft
{
public static final Logger LOGGER = LogManager.getLogger( ModInfo.MOD_ID );
public static final ItemGroup ITEM_GROUP = new CashCraftItemGroup();
public static final IProxy PROXY = DistExecutor.<IProxy> runForDist( () -> ClientProxy::new, () -> ServerProxy::new );
public static final Random RANDOM = new Random();
public CashCraft()
{
CashCraftConfig.register( ModLoadingContext.get() );
// Register network messages
// simpleNetworkWrapper = NetworkRegistry.INSTANCE.newSimpleChannel( ModInfo.MODID );
// simpleNetworkWrapper.registerMessage( SyncConfigMessage.Handler.class, SyncConfigMessage.class, MESSAGE_ID_UPDATE, Side.CLIENT );
// Initialize API
CashCraftAPI.economy = new Economy();
CashCraftAPI.trade = new Trade();
// Register the setup method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener( this::setup );
}
public void setup( FMLCommonSetupEvent event )
{
PROXY.setup( event );
}
}
|
<filename>src/steering_wheel_shield.cpp
#include "steering_wheel_shield.h"
#include "steering_wheel_definitions.h"
namespace steering_wheel_shield {
inline void set_csx() { GPIOC_PSOR = CSX_MASK; }
inline void clr_csx() { GPIOC_PCOR = CSX_MASK; }
inline void set_dcx() { GPIOC_PSOR = DCX_MASK; }
inline void clr_dcx() { GPIOC_PCOR = DCX_MASK; }
inline void set_wrx() { GPIOC_PSOR = WRX_MASK; }
inline void clr_wrx() { GPIOC_PCOR = WRX_MASK; }
inline void set_rdx() { GPIOC_PSOR = RDX_MASK; }
inline void clr_rdx() { GPIOC_PCOR = RDX_MASK; }
inline void set_rst() { GPIOE_PSOR = RST_MASK; }
inline void clr_rst() { GPIOE_PCOR = RST_MASK; }
inline void clr_data() {
GPIOB_PCOR = PORTB_DATA_MASK;
GPIOC_PCOR = PORTC_DATA_MASK;
};
void write_command(uint8_t* data, uint8_t n) {
clr_csx();
clr_dcx();
GPIOC_PSOR = data[0] << 4;
clr_wrx();
NOPN(0, 0, 9);
set_wrx();
NOPN(0, 0, 3);
GPIOC_PCOR = data[0] << 4;
set_dcx();
for (int i = 1; i < n; i++) {
GPIOC_PSOR = data[i] << 4;
clr_wrx();
NOPN(0, 0, 9);
set_wrx();
NOPN(0, 0, 3);
GPIOC_PCOR = data[i] << 4;
}
set_csx();
}
void set_window(uint16_t start_x, uint16_t end_x, uint16_t start_y, uint16_t end_y) {
uint8_t buf[5];
buf[0] = HX8357_SET_COLUMN_ADDRESS;
buf[1] = (start_x >> 8) & 0xFF;
buf[2] = start_x & 0xFF;
buf[3] = (end_x >> 8) & 0xFF;
buf[4] = end_x & 0xFF;
write_command(buf, 5);
buf[0] = HX8357_SET_PAGE_ADDRESS;
buf[1] = (start_y >> 8) & 0xFF;
buf[2] = start_y & 0xFF;
buf[3] = (end_y >> 8) & 0xFF;
buf[4] = end_y & 0xFF;
write_command(buf, 5);
}
void fill_screen() {
clr_csx();
clr_dcx();
GPIOC_PSOR = HX8357_WRITE_MEMORY_START << 4;
clr_wrx();
NOPN(0, 0, 9);
set_wrx();
NOPN(0, 0, 3);
GPIOC_PCOR = HX8357_WRITE_MEMORY_START << 4;
set_dcx();
GPIOC_PSOR = 0x000003F0;
for (int i = 0; i < 320; i++) {
for (int j = 0; j < 480; j++) {
clr_wrx();
NOPN(0, 0, 9);
set_wrx();
NOPN(0, 0, 3);
}
}
GPIOC_PCOR = 0x000003F0;
}
void reset() {
set_csx();
set_dcx();
set_wrx();
set_rdx();
set_rst();
clr_data();
delay(100);
clr_rst();
delay(100);
set_rst();
delay(100);
uint8_t buf[16];
buf[0] = HX8357_SET_POWER;
buf[1] = 0x44;
buf[2] = 0x41;
buf[3] = 0x06;
write_command(buf, 4);
buf[0] = HX8357_SET_VCOM;
buf[1] = 0x40;
buf[2] = 0x10;
write_command(buf, 3);
buf[0] = HX8357_SET_POWER_NORMAL;
buf[1] = 0x05;
buf[2] = 0x12;
write_command(buf, 3);
buf[0] = HX8357_SET_PANEL_DRIVING;
buf[1] = 0x14;
buf[2] = 0x3B;
buf[3] = 0x00;
buf[4] = 0x02;
buf[5] = 0x11;
write_command(buf, 6);
buf[0] = HX8357_SET_DISPLAY_FRAME;
buf[1] = 0x0C;
write_command(buf, 2);
buf[0] = HX8357_SET_PANEL_RELATED;
buf[1] = 0x01;
write_command(buf, 2);
buf[0] = HX8357_SET_GAMMA;
buf[1] = 0x00;
buf[2] = 0x15;
buf[3] = 0x00;
buf[4] = 0x22;
buf[5] = 0x00;
buf[6] = 0x08;
buf[7] = 0x77;
buf[8] = 0x26;
buf[9] = 0x77;
buf[10] = 0x22;
buf[11] = 0x04;
buf[12] = 0x00;
write_command(buf, 13);
buf[0] = HX8357_SET_ADDRESS_MODE;
buf[1] = 0xC0;
write_command(buf, 2);
buf[0] = HX8357_SET_PIXEL_FORMAT;
buf[1] = 0x06;
write_command(buf, 2);
set_window(0, 319, 0, 479);
buf[0] = HX8357_SET_DISPLAY_MODE;
buf[1] = 0x00;
write_command(buf, 2);
buf[0] = HX8357_EXIT_SLEEP_MODE;
write_command(buf, 1);
delay(120);
buf[0] = HX8357_SET_DISPLAY_ON;
write_command(buf, 1);
delay(10);
}
void begin() {
PORTB_PCR0 = PCR_MUX(1);
PORTB_PCR1 = PCR_MUX(1);
PORTB_PCR2 = PCR_MUX(1);
PORTB_PCR3 = PCR_MUX(1);
PORTB_PCR10 = PCR_MUX(1);
PORTB_PCR11 = PCR_MUX(1);
PORTB_PCR16 = PCR_MUX(1);
PORTB_PCR17 = PCR_MUX(1);
PORTB_PCR18 = PCR_MUX(1);
PORTB_PCR19 = PCR_MUX(1);
PORTC_PCR0 = PCR_MUX(1);
PORTC_PCR1 = PCR_MUX(1);
PORTC_PCR2 = PCR_MUX(1);
PORTC_PCR3 = PCR_MUX(1);
PORTC_PCR4 = PCR_MUX(1);
PORTC_PCR5 = PCR_MUX(1);
PORTC_PCR6 = PCR_MUX(1);
PORTC_PCR7 = PCR_MUX(1);
PORTC_PCR8 = PCR_MUX(1);
PORTC_PCR9 = PCR_MUX(1);
PORTC_PCR10 = PCR_MUX(1);
PORTC_PCR11 = PCR_MUX(1);
PORTE_PCR26 = PCR_MUX(1);
GPIOB_PDDR |= 0x000F0C0F;
GPIOC_PDDR |= 0x00000FFF;
GPIOE_PDDR |= 0x04000000;
reset();
}
} // namespace steering_wheel_shield
|
#!/bin/bash
if [ -z "$SGXLKL_ROOT" ]; then
echo "ERROR: 'SGXLKL_ROOT' is undefined. Please export SGXLKL_ROOT=<SGX-LKL-OE> source code repository"
exit 1
fi
if [ -z "$SGXLKL_PREFIX" ]; then
echo "ERROR: 'SGXLKL_PREFIX' is undefined. Please export SGXLKL_PREFIX=<install-prefix>"
exit 1
fi
if [ -z "$SGXLKL_BUILD_MODE" ]; then
echo "ERROR: 'SGXLKL_BUILD_MODE' is undefined. Please export SGXLKL_BUILD_MODE=<mode>"
exit 1
fi
# shellcheck source=.azure-pipelines/scripts/junit_utils.sh
. "$SGXLKL_ROOT/.azure-pipelines/scripts/junit_utils.sh"
# Initialize the variables.
if [[ "$SGXLKL_BUILD_MODE" == "debug" ]]; then
make_args=( "DEBUG=true" )
elif [[ "$SGXLKL_BUILD_MODE" == "nonrelease" ]]; then
make_args=( )
else
echo "unknown SGXLKL_BUILD_MODE: $SGXLKL_BUILD_MODE"
exit 1
fi
make_install_args=( "${make_args[@]}" "PREFIX=$SGXLKL_PREFIX" )
test_name="Compile and build ($SGXLKL_BUILD_MODE)"
test_class="Build"
test_suite="sgx-lkl-oe"
error_message_file_path="report/$test_name.error"
stack_trace_file_path="report/$test_name.stack"
# Start the test timer.
JunitTestStarted "$test_name"
# Ensure that we have a clean build tree
make distclean
# Install the Open Enclave build dependencies for Azure
sudo bash "$SGXLKL_ROOT/openenclave/scripts/ansible/install-ansible.sh"
sudo ansible-playbook "$SGXLKL_ROOT/openenclave/scripts/ansible/oe-contributors-acc-setup-no-driver.yml"
# Let's build
make "${make_args[@]}" && make install "${make_install_args[@]}"
make_exit=$?
# Process the result
if [[ "$make_exit" == "0" ]] && [[ -f build/sgx-lkl-run-oe ]] && [[ -f build/libsgxlkl.so.signed ]] && [[ -f build/libsgxlkl.so ]]; then
JunitTestFinished "$test_name" "passed" "$test_class" "$test_suite"
else
echo "'$test_name' exited with $make_exit" > "$error_message_file_path"
make "${make_args[@]}" > "$stack_trace_file_path" 2>&1
JunitTestFinished "$test_name" "failed" "$test_class" "$test_suite"
fi
exit $make_exit
|
/***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#include "ObjectWrapperTest.hpp"
#include "oatpp/core/Types.hpp"
namespace oatpp { namespace test { namespace core { namespace data { namespace mapping { namespace type {
namespace {
template<class T, class Clazz = oatpp::data::mapping::type::__class::Void>
using ObjectWrapper = oatpp::data::mapping::type::ObjectWrapper<T, Clazz>;
}
void ObjectWrapperTest::onRun() {
{
OATPP_LOGI(TAG, "Check default valueType is assigned (default tparam Clazz)...");
ObjectWrapper<std::string> pw;
OATPP_ASSERT(!pw);
OATPP_ASSERT(pw == nullptr);
OATPP_ASSERT(pw.getValueType() == oatpp::data::mapping::type::__class::Void::getType());
OATPP_LOGI(TAG, "OK");
}
{
OATPP_LOGI(TAG, "Check default valueType is assigned (specified tparam Clazz)...");
ObjectWrapper<std::string, oatpp::data::mapping::type::__class::String> pw;
OATPP_ASSERT(!pw);
OATPP_ASSERT(pw == nullptr);
OATPP_ASSERT(pw.getValueType() == oatpp::data::mapping::type::__class::String::getType());
OATPP_LOGI(TAG, "OK");
}
{
OATPP_LOGI(TAG, "Check valueType is assigned from constructor...");
ObjectWrapper<std::string> pw(oatpp::data::mapping::type::__class::String::getType());
OATPP_ASSERT(!pw);
OATPP_ASSERT(pw == nullptr);
OATPP_ASSERT(pw.getValueType() == oatpp::data::mapping::type::__class::String::getType());
OATPP_LOGI(TAG, "OK");
}
{
OATPP_LOGI(TAG, "Check valueType is assigned from copy constructor...");
ObjectWrapper<std::string> pw1(oatpp::data::mapping::type::__class::String::getType());
ObjectWrapper<std::string> pw2(pw1);
OATPP_ASSERT(pw2.getValueType() == oatpp::data::mapping::type::__class::String::getType());
OATPP_LOGI(TAG, "OK");
}
{
OATPP_LOGI(TAG, "Check valueType is assigned from move constructor...");
ObjectWrapper<std::string> pw1(oatpp::data::mapping::type::__class::String::getType());
ObjectWrapper<std::string> pw2(std::move(pw1));
OATPP_ASSERT(pw2.getValueType() == oatpp::data::mapping::type::__class::String::getType());
OATPP_LOGI(TAG, "OK");
}
{
OATPP_LOGI(TAG, "Check valueType is NOT assigned from copy-assign operator...");
ObjectWrapper<std::string> pw1(oatpp::data::mapping::type::__class::String::getType());
ObjectWrapper<std::string> pw2;
bool throws = false;
try {
pw2 = pw1;
} catch (std::runtime_error& e) {
throws = true;
}
OATPP_ASSERT(pw2.getValueType() == oatpp::data::mapping::type::__class::Void::getType());
OATPP_ASSERT(throws)
OATPP_LOGI(TAG, "OK");
}
{
OATPP_LOGI(TAG, "Check valueType is NOT assigned from move-assign operator...");
ObjectWrapper<std::string> pw1(oatpp::data::mapping::type::__class::String::getType());
ObjectWrapper<std::string> pw2;
bool throws = false;
try {
pw2 = std::move(pw1);
} catch (std::runtime_error& e) {
throws = true;
}
OATPP_ASSERT(pw2.getValueType() == oatpp::data::mapping::type::__class::Void::getType());
OATPP_ASSERT(throws)
OATPP_LOGI(TAG, "OK");
}
{
OATPP_LOGI(TAG, "Check copy-assign operator. Check == operator...");
ObjectWrapper<std::string> pw1;
OATPP_ASSERT(!pw1);
OATPP_ASSERT(pw1 == nullptr);
OATPP_ASSERT(pw1.getValueType() == oatpp::data::mapping::type::__class::Void::getType());
ObjectWrapper<std::string> pw2 = std::make_shared<std::string>("Hello!");
OATPP_ASSERT(pw2);
OATPP_ASSERT(pw2 != nullptr);
OATPP_ASSERT(pw2.getValueType() == oatpp::data::mapping::type::__class::Void::getType());
pw1 = pw2;
OATPP_ASSERT(pw1);
OATPP_ASSERT(pw1 != nullptr);
OATPP_ASSERT(pw2);
OATPP_ASSERT(pw2 != nullptr);
OATPP_ASSERT(pw1 == pw2);
OATPP_ASSERT(pw1.get() == pw2.get());
OATPP_LOGI(TAG, "OK");
}
{
OATPP_LOGI(TAG, "Check != operator...");
ObjectWrapper<std::string, oatpp::data::mapping::type::__class::String> pw1(std::make_shared<std::string>("Hello!"));
OATPP_ASSERT(pw1);
OATPP_ASSERT(pw1 != nullptr);
OATPP_ASSERT(pw1.getValueType() == oatpp::data::mapping::type::__class::String::getType());
ObjectWrapper<std::string, oatpp::data::mapping::type::__class::String> pw2(std::make_shared<std::string>("Hello!"));
OATPP_ASSERT(pw2);
OATPP_ASSERT(pw2 != nullptr);
OATPP_ASSERT(pw2.getValueType() == oatpp::data::mapping::type::__class::String::getType());
OATPP_ASSERT(pw1 != pw2);
OATPP_ASSERT(pw1.get() != pw2.get());
OATPP_LOGI(TAG, "OK");
}
{
OATPP_LOGI(TAG, "Check move-assign operator. Check != operator...");
ObjectWrapper<std::string> pw1;
OATPP_ASSERT(!pw1);
OATPP_ASSERT(pw1 == nullptr);
OATPP_ASSERT(pw1.getValueType() == oatpp::data::mapping::type::__class::Void::getType());
ObjectWrapper<std::string> pw2 = std::make_shared<std::string>("Hello!");
OATPP_ASSERT(pw2);
OATPP_ASSERT(pw2 != nullptr);
OATPP_ASSERT(pw2.getValueType() == oatpp::data::mapping::type::__class::Void::getType());
pw1 = std::move(pw2);
OATPP_ASSERT(pw1);
OATPP_ASSERT(pw1 != nullptr);
OATPP_ASSERT(!pw2);
OATPP_ASSERT(pw2 == nullptr);
OATPP_ASSERT(pw1 != pw2);
OATPP_ASSERT(pw1.get() != pw2.get());
OATPP_LOGI(TAG, "OK");
}
{
OATPP_LOGI(TAG, "Check oatpp::Void type reassigned");
oatpp::Void v;
v = oatpp::String("test");
OATPP_ASSERT(v.getValueType() == oatpp::String::Class::getType());
v = oatpp::Int32(32);
OATPP_ASSERT(v.getValueType() == oatpp::Int32::Class::getType());
oatpp::Int32 i = v.cast<oatpp::Int32>();
OATPP_ASSERT(i.getValueType() == oatpp::Int32::Class::getType());
OATPP_ASSERT(i == 32);
}
}
}}}}}}
|
#pragma once
#define MAX_BONE_INFLUENCE 4
#include "TNAH/Core/Core.h"
#include "TNAH/Core/Timestep.h"
#include "TNAH/Renderer/VertexArray.h"
#include "TNAH/Renderer/RenderingBuffers.h"
#include "TNAH/Renderer/Shader.h"
#include "TNAH/Renderer/Material.h"
#include "Animation.h"
#include "BoneInfo.h"
#pragma warning(push, 0)
#include <Assimp/Importer.hpp>
#include <Assimp/scene.h>
#include <Assimp/postprocess.h>
#include <vector>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include<glm/gtx/matrix_decompose.hpp>
#pragma warning(pop)
namespace tnah {
/**
* @struct Vertex
*
* @brief A vertex.
*
* @author <NAME>
* @date 12/09/2021
*/
struct Vertex
{
/** @brief The position */
glm::vec3 Position;
/** @brief The normal */
glm::vec3 Normal;
/** @brief The tangent */
glm::vec3 Tangent;
/** @brief The bitangents */
glm::vec3 Bitangents;
/** @brief The texcoord */
glm::vec2 Texcoord;
/** @brief bone IDs */
uint32_t IDs[MAX_BONE_INFLUENCE];
/** @brief The weights of bones */
float Weights[MAX_BONE_INFLUENCE];
/**
* @fn void AddBoneData(uint32_t BoneID, float Weight)
*
* @brief Adds bone data
*
* @author <NAME>
* @date 12/09/2021
*
* @param BoneID Identifier for the bone.
* @param Weight The weight.
*/
void AddBoneData(uint32_t BoneID, float Weight)
{
for (size_t i = 0; i < 4; i++)
{
if (Weights[i] == 0.0)
{
IDs[i] = BoneID;
Weights[i] = Weight;
return;
}
}
// TODO: Keep top weights
TNAH_CORE_WARN("Vertex has more than four bones/weights affecting it, extra data will be discarded (BoneID={0}, Weight={1})", BoneID, Weight);
}
};
/**
* @struct MeshTexture
*
* @brief A mesh texture
*
* @author <NAME>
* @date 12/09/2021
*/
struct MeshTexture
{
/** @brief The texture */
Ref<Texture2D> Texture;
/** @brief Full pathname of the texture file */
std::string TexturePath;
/**
* @fn MeshTexture(Ref<Texture2D> texture, const std::string& path)
*
* @brief Constructor
*
* @author <NAME>
* @date 12/09/2021
*
* @param texture The texture.
* @param path Full pathname of the file.
*/
MeshTexture(Ref<Texture2D> texture, const std::string& path)
:Texture(texture), TexturePath(path)
{}
};
/**
* @struct MeshShader
*
* @brief A mesh shader.
*
* @author <NAME>
* @date 12/09/2021
*/
struct MeshShader
{
/** @brief The shader */
Ref<Shader> Shader;
/** @brief Full pathname of the vertex shader file */
std::string VertexShaderPath;
/** @brief Full pathname of the fragment shader file */
std::string FragmentShaderPath;
/**
* @fn MeshShader(Ref<tnah::Shader> shader, const std::string& vertex, const std::string& fragment)
*
* @brief Constructor
*
* @author <NAME>
* @date 12/09/2021
*
* @param shader The shader.
* @param vertex The vertex.
* @param fragment The fragment.
*/
MeshShader(Ref<tnah::Shader> shader, const std::string& vertex, const std::string& fragment)
:Shader(shader), VertexShaderPath(vertex), FragmentShaderPath(fragment)
{}
};
/**
* @class Mesh
*
* @brief A mesh class responsible for handling the meshes of models
*
* @author <NAME>
* @date 12/09/2021
*/
class Mesh {
public:
/**
* @fn Mesh::Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices, std::vector<Ref<Texture2D>> textures, bool animated);
*
* @brief Constructor
*
* @author <NAME>
* @date 12/09/2021
*
* @param vertices The vertices.
* @param indices The indices.
* @param textures The textures.
* @param animated True if animated.
*/
Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices, std::vector<Ref<Texture2D>> textures, bool animated);
/**
* @fn Ref<VertexArray> Mesh::GetMeshVertexArray() const
*
* @brief Gets mesh vertex array
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The mesh vertex array.
*/
Ref<VertexArray> GetMeshVertexArray() const {return m_Vao;}
/**
* @fn Ref<VertexBuffer> Mesh::GetMeshVertexBuffer() const
*
* @brief Gets mesh vertex buffer
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The mesh vertex buffer.
*/
Ref<VertexBuffer> GetMeshVertexBuffer() const {return m_Vbo;}
/**
* @fn Ref<IndexBuffer> Mesh::GetMeshIndexBuffer() const
*
* @brief Gets mesh index buffer
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The mesh index buffer.
*/
Ref<IndexBuffer> GetMeshIndexBuffer() const {return m_Ibo;}
/**
* @fn Ref<Material> Mesh::GetMeshMaterial() const
*
* @brief Gets mesh material
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The mesh material.
*/
Ref<Material> GetMeshMaterial() const {return m_Material;}
/**
* @fn std::vector<glm::vec3> Mesh::GetVertexPositions() const;
*
* @brief Gets vertex positions
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The vertex positions.
*/
std::vector<glm::vec3> GetVertexPositions() const;
/**
* @fn std::vector<uint32_t> Mesh::GetIndices() const
*
* @brief Gets the indices
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The indices.
*/
std::vector<uint32_t> GetIndices() const { return m_Indices; }
private:
/** @brief The vertices */
std::vector<Vertex> m_Vertices;
/** @brief The indices */
std::vector<uint32_t> m_Indices;
/** @brief True if animated */
bool m_Animated;
/** @brief The vao */
Ref<VertexArray> m_Vao;
/** @brief The vbo */
Ref<VertexBuffer> m_Vbo;
/** @brief The ibo */
Ref<IndexBuffer> m_Ibo;
/** @brief The VertexBufferLayout */
VertexBufferLayout m_BufferLayout;
/** @brief The material */
Ref<Material> m_Material;
friend class EditorUI;
};
/**
* @class Model
*
* @brief A model class that inherits from the refCounted class, which allows model to use the Ref *. Responsible for the loading and handling of models
*
* @author <NAME>
* @date 12/09/2021
*/
class Model : public RefCounted
{
public:
/**
* @fn static Ref<Model> Model::Create(const std::string& filePath);
*
* @brief Creates a new model
*
* @author <NAME>
* @date 12/09/2021
*
* @param filePath Full pathname of the file.
*
* @returns A model
*/
static Ref<Model> Create(const std::string& filePath);
/**
* @fn Model::Model();
*
* @brief Default constructor
*
* @author <NAME>
* @date 12/09/2021
*/
Model();
/**
* @fn Model::Model(const std::string& filePath);
*
* @brief Constructor
*
* @author <NAME>
* @date 12/09/2021
*
* @param filePath Full pathname of the file.
*/
Model(const std::string& filePath);
/**
* @fn auto& Model::GetAnimation()
*
* @brief Gets the animation
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The animation.
*/
auto& GetAnimation() { return m_Animation; }
/**
* @fn std::vector<Mesh> Model::GetMeshes() const
*
* @brief Gets the meshes
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The meshes.
*/
std::vector<Mesh> GetMeshes() const { return m_Meshes; }
/**
* @fn uint32_t Model::GetNumberOfMeshes() const
*
* @brief Gets number of meshes
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The number of meshes.
*/
uint32_t GetNumberOfMeshes() const { return static_cast<uint32_t>(m_Meshes.size()); }
/**
* @fn auto& Model::GetBoneInfoMap()
*
* @brief Gets bone information map
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The bone information map.
*/
auto& GetBoneInfoMap() { return m_BoneInfoMap; }
/**
* @fn int& Model::GetBoneCount()
*
* @brief Gets bone count
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The bone count.
*/
int& GetBoneCount() { return m_BoneCounter; }
const Resource& GetResource() const { return m_Resource; }
private:
/** @brief The meshes */
std::vector<Mesh> m_Meshes;
Resource m_Resource;
/** @brief The animation */
Animation m_Animation;
/** @brief The bone information map */
std::map<std::string, BoneInfo> m_BoneInfoMap;
/** @brief The bone counter */
int m_BoneCounter = 0;
/** @brief True if is animated, false if not */
bool m_IsAnimated = false;
/**
* @fn glm::mat4 Model::AiToGLM(aiMatrix4x4t<float> m);
*
* @brief Converts aiMatrix to glm::mat4
*
* @author <NAME>
* @date 12/09/2021
*
* @param m An aiMatrix4x4t to process.
*
* @returns A glm::mat4.
*/
glm::mat4 AiToGLM(aiMatrix4x4t<float> m);
/**
* @fn glm::vec3 Model::AiToGLM(aiVector3t<float> v);
*
* @brief Converts aiVector to glm::vec3
*
* @author <NAME>
* @date 12/09/2021
*
* @param v An aiVector3t to process.
*
* @returns A glm::vec3.
*/
glm::vec3 AiToGLM(aiVector3t<float> v);
/**
* @fn glm::quat Model::AiToGLM(aiQuaterniont<float> q);
*
* @brief Converts aiQuaterniont to glm::quat
*
* @author <NAME>
* @date 12/09/2021
*
* @param q An aiQuaterniont to process.
*
* @returns A glm::quat.
*/
glm::quat AiToGLM(aiQuaterniont<float> q);
/**
* @fn void Model::SetVertexBoneDataToDefault(Vertex& vertex);
*
* @brief Sets vertex bone data to default
*
* @author <NAME>
* @date 12/09/2021
*
* @param [in,out] vertex The vertex.
*/
void SetVertexBoneDataToDefault(Vertex& vertex);
/**
* @fn void Model::SetVertexBoneData(Vertex& vertex, int boneID, float weight);
*
* @brief Sets vertex bone data
*
* @author <NAME>
* @date 12/09/2021
*
* @param [in,out] vertex The vertex.
* @param boneID Identifier for the bone.
* @param weight The weight.
*/
void SetVertexBoneData(Vertex& vertex, int boneID, float weight);
/**
* @fn void Model::ExtractBoneWeightForVertices(std::vector<Vertex>& vertices, aiMesh* mesh, const aiScene* scene);
*
* @brief Extracts the bone weight for vertices
*
* @author <NAME>
* @date 12/09/2021
*
* @param [in,out] vertices The vertices.
* @param [in,out] mesh If non-null, the mesh.
* @param scene The scene.
*/
void ExtractBoneWeightForVertices(std::vector<Vertex>& vertices, aiMesh* mesh, const aiScene* scene);
/**
* @fn void Model::LoadModel(const std::string& filePath);
*
* @brief Loads a model
*
* @author <NAME>
* @date 12/09/2021
*
* @param filePath Full pathname of the file.
*/
void LoadModel(const std::string& filePath);
/**
* @fn void Model::ProcessNode(aiNode* node, const aiScene* scene);
*
* @brief Process the node
*
* @author <NAME>
* @date 12/09/2021
*
* @param [in,out] node If non-null, the node.
* @param scene The scene.
*/
void ProcessNode(aiNode* node, const aiScene* scene);
/**
* @fn Mesh Model::ProcessMesh(aiMesh* mesh, const aiScene* scene, bool animated);
*
* @brief Process the mesh
*
* @author <NAME>
* @date 12/09/2021
*
* @param [in,out] mesh If non-null, the mesh.
* @param scene The scene.
* @param animated True if animated.
*
* @returns A Mesh.
*/
Mesh ProcessMesh(aiMesh* mesh, const aiScene* scene, bool animated);
/**
* @fn std::vector<Ref<Texture2D>> Model::LoadMaterialTextures(const aiScene* scene, aiMaterial* material, aiTextureType type, const std::string& typeName);
*
* @brief Loads material textures
*
* @author <NAME>
* @date 12/09/2021
*
* @param scene The scene.
* @param [in,out] material If non-null, the material.
* @param type The type.
* @param typeName Name of the type.
*
* @returns The material textures.
*/
std::vector<Ref<Texture2D>> LoadMaterialTextures(const aiScene* scene, aiMaterial* material, aiTextureType type, const std::string& typeName);
friend class EditorUI;
friend class Serializer;
};
}
|
# Copyright (c) 2020 ETH Zurich
#
# SPDX-License-Identifier: BSL-1.0
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
source $SPACK_ROOT/share/spack/setup-env.sh
export CRAYPE_LINK_TYPE=dynamic
export APPS_ROOT="/apps/daint/SSL/HPX/packages"
export CXX_STD="17"
export BOOST_ROOT="${APPS_ROOT}/boost-1.69.0-gcc-8.3.0-c++17-release"
export HWLOC_ROOT="${APPS_ROOT}/hwloc-2.0.3-gcc-8.3.0"
module load daint-gpu
module load cudatoolkit
spack load cmake
spack load ninja
export CXX=`which CC`
export CC=`which cc`
configure_extra_options="-DCMAKE_BUILD_TYPE=Debug"
configure_extra_options+=" -DHPX_WITH_CUDA=ON"
configure_extra_options+=" -DHPX_WITH_CUDA_CLANG=ON"
configure_extra_options+=" -DHPX_CUDA_CLANG_FLAGS=\"--cuda-gpu-arch=sm_60\""
configure_extra_options+=" -DHPX_WITH_MALLOC=system"
configure_extra_options+=" -DHPX_WITH_CXX${CXX_STD}=ON"
configure_extra_options+=" -DHPX_WITH_DEPRECATION_WARNINGS=OFF"
configure_extra_options+=" -DHPX_WITH_COMPILER_WARNINGS=ON"
configure_extra_options+=" -DHPX_WITH_COMPILER_WARNINGS_AS_ERRORS=ON"
configure_extra_options+=" -DHPX_WITH_SPINLOCK_DEADLOCK_DETECTION=ON"
|
#!/usr/bin/env bash
docker-compose up -d --build
echo "Install composer"
docker exec automaintenancetracker_web_1 composer install
echo "Install npm package for angular"
docker exec automaintenancetracker_web_1 npm install --prefix ./resources/auto-app/
echo "Build prod mode"
docker exec automaintenancetracker_web_1 npm run build:prod:aot --prefix ./resources/auto-app/
while [ 1 ]
do
MIGRATION="$(docker exec automaintenancetracker_web_1 bash ./docker/wait-for-it.sh db:3306 -t 5 -s -- ./vendor/bin/doctrine-module migrations:migrate -n)"
if [ -z "$MIGRATION" ]
then
echo "Mysql is not ready"
else
echo "Mysql is ready"
exit
fi
done |
<reponame>ChristopherChudzicki/mathbox
// TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
import { Matrix } from "./matrix.js";
export class Area extends Matrix {
static initClass() {
this.traits = [
"node",
"buffer",
"active",
"data",
"source",
"index",
"matrix",
"texture",
"raw",
"span:x",
"span:y",
"area",
"sampler:x",
"sampler:y",
];
}
updateSpan() {
let inverseX, inverseY;
const dimensions = this.props.axes;
let { width } = this.props;
let { height } = this.props;
const { centeredX } = this.props;
const { centeredY } = this.props;
const padX = this.props.paddingX;
const padY = this.props.paddingY;
const rangeX = this._helpers.span.get("x.", dimensions[0]);
const rangeY = this._helpers.span.get("y.", dimensions[1]);
this.aX = rangeX.x;
this.aY = rangeY.x;
const spanX = rangeX.y - rangeX.x;
const spanY = rangeY.y - rangeY.x;
width += padX * 2;
height += padY * 2;
if (centeredX) {
inverseX = 1 / Math.max(1, width);
this.aX += (spanX * inverseX) / 2;
}
else {
inverseX = 1 / Math.max(1, width - 1);
}
if (centeredY) {
inverseY = 1 / Math.max(1, height);
this.aY += (spanY * inverseY) / 2;
}
else {
inverseY = 1 / Math.max(1, height - 1);
}
this.bX = spanX * inverseX;
this.bY = spanY * inverseY;
this.aX += padX * this.bX;
return (this.aY += padY * this.bY);
}
callback(callback) {
this.updateSpan();
if (this.last === callback) {
return this._callback;
}
this.last = callback;
if (callback.length <= 5) {
return (this._callback = (emit, i, j) => {
const x = this.aX + this.bX * i;
const y = this.aY + this.bY * j;
return callback(emit, x, y, i, j);
});
}
else {
return (this._callback = (emit, i, j) => {
const x = this.aX + this.bX * i;
const y = this.aY + this.bY * j;
return callback(emit, x, y, i, j, this.bufferClock, this.bufferStep);
});
}
}
make() {
super.make();
this._helpers.span.make();
return this._listen(this, "span.range", this.updateSpan);
}
unmake() {
super.unmake();
return this._helpers.span.unmake();
}
}
Area.initClass();
|
// PrimeNumber.php
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class PrimeNumber extends Constraint
{
public $message = 'The number {{ value }} is not a prime number.';
public function validatedBy()
{
return PrimeNumberValidator::class;
}
}
// PrimeNumberValidator.php
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class PrimeNumberValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (!$this->isPrime($value)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $value)
->addViolation();
}
}
private function isPrime($number)
{
if ($number <= 1) {
return false;
}
for ($i = 2; $i <= sqrt($number); $i++) {
if ($number % $i === 0) {
return false;
}
}
return true;
}
}
// NumberEntity.php
use Symfony\Component\Validator\Constraints as Assert;
class NumberEntity
{
/**
* @Assert\NotBlank
* @PrimeNumber
*/
private $number;
public function getNumber()
{
return $this->number;
}
public function setNumber($number)
{
$this->number = $number;
}
} |
<reponame>dcoloma/gaia
'use strict';
var CustomLogoPath = {
poweron: {
video: '/resources/power/carrier_power_on.mp4',
image: '/resources/power/carrier_power_on.png'
},
poweroff: {
video: '/resources/power/carrier_power_off.mp4',
image: '/resources/power/carrier_power_off.png'
}
};
// Function to animate init starting logo
var InitLogoHandler = {
ready: false,
animated: false,
readyCallBack: null,
logoLoader: null,
get carrierLogo() {
delete this.carrierLogo;
return (this.carrierLogo = document.getElementById('carrier-logo'));
},
get osLogo() {
delete this.osLogo;
return (this.osLogo = document.getElementById('os-logo'));
},
init: function ilh_init(logoLoader) {
window.addEventListener('ftuopen', this);
window.addEventListener('ftuskip', this);
this.logoLoader = logoLoader;
logoLoader.onnotfound = this._removeCarrierPowerOn.bind(this);
logoLoader.onload = this._appendCarrierPowerOn.bind(this);
},
handleEvent: function ilh_handleEvent() {
this.animate();
},
_removeCarrierPowerOn: function ilh_removeCarrierPowerOn() {
var self = this;
if (this.carrierLogo) {
this.carrierLogo.parentNode.removeChild(self.carrierLogo);
this._setReady();
} else {
var self = this;
document.addEventListener('DOMContentLoaded', function() {
if (self.carrierLogo) {
self.carrierLogo.parentNode.removeChild(self.carrierLogo);
}
self._setReady();
});
}
},
_appendCarrierPowerOn: function ilh_appendCarrierPowerOn() {
if (this.carrierLogo) {
this.carrierLogo.appendChild(this.logoLoader.element);
this._setReady();
} else {
var self = this;
document.addEventListener('DOMContentLoaded', function() {
self.carrierLogo.appendChild(self.logoLoader.element);
self._setReady();
});
}
},
_setReady: function ilh_setReady() {
this.ready = true;
var elem = this.logoLoader.element;
if (elem && elem.tagName.toLowerCase() == 'video') {
// Play video just after the element is first painted.
window.addEventListener('mozChromeEvent', function startVideo(e) {
if (e.detail.type == 'system-first-paint') {
window.removeEventListener('mozChromeEvent', startVideo);
if (elem && elem.ended === false) {
elem.play();
}
}
});
}
if (this.readyCallBack) {
this.readyCallBack();
this.readyCallBack = null;
}
},
_waitReady: function ilh_waitReady(callback) {
this.readyCallBack = callback;
},
animate: function ilh_animate(callback) {
var self = this;
if (!this.ready) {
this._waitReady(this.animate.bind(this, callback));
return;
}
if (this.animated)
return;
this.animated = true;
// No carrier logo - Just animate OS logo.
if (!self.logoLoader.found) {
self.osLogo.classList.add('hide');
// Has carrier logo - Animate carrier logo, then OS logo.
} else {
// CarrierLogo is not transparent until now
// to prevent flashing.
self.carrierLogo.className = 'transparent';
var elem = self.logoLoader.element;
if (elem.tagName.toLowerCase() == 'video' && !elem.ended) {
// compability: ensure movie being played here in case
// system-first-paint is not supported by Gecko.
elem.play();
elem.onended = function() {
elem.classList.add('hide');
};
} else {
elem.classList.add('hide');
}
self.carrierLogo.addEventListener('transitionend',
function transCarrierLogo(evt) {
evt.stopPropagation();
self.carrierLogo.removeEventListener('transitionend', transCarrierLogo);
if (elem.tagName.toLowerCase() == 'video') {
// XXX workaround of bug 831747
// Unload the video. This releases the video decoding hardware
// so other apps can use it.
elem.removeAttribute('src');
elem.load();
}
self.carrierLogo.parentNode.removeChild(self.carrierLogo);
self.osLogo.classList.add('hide');
self.carrierPowerOnElement = null;
});
}
self.osLogo.addEventListener('transitionend', function transOsLogo() {
self.osLogo.removeEventListener('transitionend', transOsLogo);
self.osLogo.parentNode.removeChild(self.osLogo);
if (callback) {
callback();
}
});
}
};
InitLogoHandler.init(new LogoLoader(CustomLogoPath.poweron));
|
import React, { Component } from 'react';
import styled from 'styled-components';
import { FaChevronRight } from 'react-icons/fa';
import axios from 'axios';
import NumberFormat from 'react-number-format';
import Graph from './Graph';
import Rank from './Rank';
const ActiveContainer = styled.div`
flex: 35;
width: 100%;
min-height: 400px;
padding-bottom: 30px;
background-color: #4185f5;
box-shadow: 0 3px 5px rgba(57, 63, 72, 0.3);
@media screen and (max-width: 960px) {
margin-top: 30px;
width: 95%;
}
`;
const Title = styled.div`
font-size: 14px;
padding-top: 30px;
padding-left: 30px;
color: #fff;
`;
const TotalConfirmed = styled.div`
font-size: 40px;
padding-left: 30px;
color: #fff;
`;
const GraphPerDay = styled.div`
font-size: 12px;
padding-top: 30px;
padding-bottom: 7px;
margin-right: 30px;
margin-left: 30px;
color: #fff;
border-bottom: 0.5px solid #8eb6f9;
`;
const DataGraph = styled.div`
padding-top: 30px;
padding-left: 30px;
`;
const TopCountry = styled.div`
font-size: 12px;
padding-bottom: 7px;
margin-top: 30px;
margin-right: 30px;
margin-left: 30px;
color: #fff;
border-bottom: 0.5px solid #8eb6f9;
`;
const TopCountryData = styled.div`
display: flex;
justify-content: space-between;
font-size: 12px;
padding-bottom: 7px;
margin-right: 30px;
color: #fff;
`;
const ReportContainer = styled.div`
width: 100%;
border-top: 1px solid #8eb6f9;
`;
const Report = styled.div`
font-size: 16px;
color: #fff;
margin-top: 30px;
margin-right: 30px;
float: right;
`;
class Active extends Component {
constructor(props) {
super(props);
this.state = {
posts: [],
};
}
componentDidMount() {
axios
.get('https://covid19.mathdro.id/api')
.then(response => {
// console.log(response.data.confirmed)
this.setState({ posts: response.data.confirmed });
})
.catch(error => {
console.log(error);
});
}
render() {
const { posts } = this.state;
return (
<ActiveContainer>
<Title>Confirmed</Title>
{
<TotalConfirmed>
<NumberFormat
thousandSeparator
displayType="text"
value={posts.value}
/>
</TotalConfirmed>
}
<GraphPerDay>Total confirmed per day</GraphPerDay>
<DataGraph>
<Graph />
</DataGraph>
<TopCountry>Top country by city confirmed</TopCountry>
<TopCountryData>
<Rank />
</TopCountryData>
<ReportContainer>
<Report>
REAL-TIME REPORT <FaChevronRight />
</Report>
</ReportContainer>
</ActiveContainer>
);
}
}
export default Active;
|
class FlaggedEmails:
def __init__(self):
self.flagged_emails = []
def add_email(self, email):
self.flagged_emails.append(email)
def unflag_all(self):
while self.flagged_emails:
self.flagged_emails.pop() |
<filename>packages/vite-app-ts/src/components/Shared/OwnerMark.tsx<gh_stars>1-10
import { UserOutlined } from '@ant-design/icons';
import React, { FC } from 'react';
import { primaryColor } from '~~/styles/styles';
const OwnerMark: FC = () => (
<UserOutlined
style={{
color: primaryColor,
// background: "hsla(209deg, 100%, 92%, 1)",
borderRadius: '50%',
width: '1.25rem',
height: '1.25rem',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
border: `1px solid ${primaryColor}`,
}}
/>
);
export default OwnerMark;
|
#!/bin/bash
# yum update
# yum upgrade -y
# 关闭防火墙
systemctl stop firewalld
systemctl disable firewalld
# 关闭 selinux
setenforce 0
sed -i "s#SELINUX=enforcing#SELINUX=disabled#g" /etc/selinux/config |
<reponame>domenic/mojo
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Invokes gperf for the GN build. The first argument is the path to gperf.
# TODO(brettw) this can be removed once the run_executable rules have been
# checked in for the GN build.
import subprocess
import sys
subprocess.check_call(sys.argv[1:])
|
import os
def construct_connection_string(engine: str, name: str, user: str) -> str:
# Assuming the password is not provided as an input parameter for security reasons
# Construct the database connection string without including the password
connection_string = f"{engine}://{user}@<host>:<port>/{name}"
return connection_string |
/*
Bemærk: Modulet er kun konsolbaseret.
*/
// Inkluderer mit eget modul, der er lokaliseret i 'node_modules'
var myModule = require('mymodule');
// Kalder metoden fra mit modul på variablen 'myModule'
myModule.konverterValuta(10); // Her er det 10 DKK, der bliver omregnet til EURO. |
#!/usr/bin/env bash
# basset -o errexit
# set -o pipefail
# todo: turn on after #1295
# set -o nounset
# This entrypoint is used to play nicely with the current cookiecutter configuration.
# Since docker-compose relies heavily on environment variables itself for configuration, we'd have to define multiple
# environment variables just to support cookiecutter out of the box. That makes no sense, so this little entrypoint
# does all this for us.
export REDIS_URL=redis://redis:6379
# the official postgres image uses 'postgres' as default user if not set explictly.
if [ -z "${POSTGRES_USER}" ]; then
base_postgres_image_default_user='postgres'
export POSTGRES_USER="${base_postgres_image_default_user}"
fi
export DATABASE_URL="postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"
export CELERY_BROKER_URL="${REDIS_URL}"
postgres_ready() {
python << END
import sys
import psycopg2
try:
psycopg2.connect(
dbname="${POSTGRES_DB}",
user="${POSTGRES_USER}",
password="${POSTGRES_PASSWORD}",
host="${POSTGRES_HOST}",
port="${POSTGRES_PORT}",
)
except psycopg2.OperationalError:
sys.exit(-1)
sys.exit(0)
END
}
until postgres_ready; do
>&2 echo 'Waiting for PostgreSQL to become available...'
sleep 1
done
>&2 echo 'PostgreSQL is available'
GREEN='\033[0;32m'
BLUEE='\033[0;34m'
ORANG='\033[0;33m'
NC='\033[0m'
echo -e "${BLUEE}------------------------------------------------------------------------------------------------${NC}"
echo -e "${GREEN} [Datalab Utils] ${NC}"
echo -e "${ORANG} This scripts installs MSSQL drivers ${NC}"
echo -e "${ORANG} E. Marinetto (nenetto@gmail.com) ${NC}"
echo -e "${BLUEE}------------------------------------------------------------------------------------------------${NC}"
echo -e "${GREEN}[Datalab Utils] ${ORANG}Creating log${NC}"
DIRECTORY=$(cd `dirname $0` && pwd)
LOGFILE=$DIRECTORY'/installation.log'
echo -e "${GREEN}[Datalab Utils] ${ORANG}Updating sources${NC}"
apt-get update >> $LOGFILE 2>$LOGFILE && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends apt-utils >> $LOGFILE 2>$LOGFILE
echo -e "${GREEN}[Datalab Utils] ${ORANG}Installing apt-transport-https${NC}"
DEBIAN_FRONTEND=noninteractive apt-get -y install apt-transport-https curl >> $LOGFILE
echo -e "${GREEN}[Datalab Utils] ${ORANG}Adding key${NC}"
curl https://packages.microsoft.com/keys/microsoft.asc 2>$LOGFILE | apt-key add - >> $LOGFILE 2>$LOGFILE
#Download appropriate package for the OS version
#Choose only ONE of the following, corresponding to your OS version
#Debian 8
echo -e "${GREEN}[Datalab Utils] ${ORANG}Adding sources${NC}"
curl https://packages.microsoft.com/config/debian/8/prod.list > /etc/apt/sources.list.d/mssql-release.list 2>$LOGFILE
#Debian 9
#curl https://packages.microsoft.com/config/debian/9/prod.list > /etc/apt/sources.list.d/mssql-release.list
echo -e "${GREEN}[Datalab Utils] ${ORANG}Updating sources${NC}"
apt-get update >> $LOGFILE
echo -e "${GREEN}[Datalab Utils] ${ORANG}Installing msodbcsql13${NC}"
DEBIAN_FRONTEND=noninteractive ACCEPT_EULA=Y apt-get -y install msodbcsql >> $LOGFILE
# optional: for bcp and sqlcmd
echo -e "${GREEN}[Datalab Utils] ${ORANG}Installing mssql-tools13${NC}"
DEBIAN_FRONTEND=noninteractive ACCEPT_EULA=Y apt-get -y install mssql-tools >> $LOGFILE
# optional: for unixODBC development headers
echo -e "${GREEN}[Datalab Utils] ${ORANG}Installing unixodbc-dev${NC}"
DEBIAN_FRONTEND=noninteractive apt-get install -y unixodbc-dev >> $LOGFILE
echo -e "${GREEN}[Datalab Utils] ${ORANG}Installing libssl1.0.0${NC}"
echo "deb http://security.debian.org/debian-security jessie/updates main" >> /etc/apt/sources.list
apt-get update >> $LOGFILE
DEBIAN_FRONTEND=noninteractive apt-get install libssl1.0.0 >>$LOGFILE
echo -e "${GREEN}[Datalab Utils] ${ORANG}Installing python-pyodbc${NC}"
DEBIAN_FRONTEND=noninteractive apt-get -y install python-pyodbc >> $LOGFILE
echo -e "${GREEN}[Datalab Utils] ${ORANG}Installing locales${NC}"
DEBIAN_FRONTEND=noninteractive apt-get -y install locales >> $LOGFILE
echo "en_US.UTF-8 UTF-8" > /etc/locale.gen
locale-gen >> $LOGFILE
echo -e "${BLUEE}------------------------------------------------------------------------------------------------${NC}"
echo -e "${GREEN} [Datalab Utils] ${NC}"
echo -e "${GREEN} FINISHED :D ${NC}"
echo -e "${BLUEE}------------------------------------------------------------------------------------------------${NC}"
exec "$@"
|
function isPalindrome(inputStr) {
// Store the reverse of the input string.
reversedStr = inputStr.split('').reverse().join('');
// Compare the reversed string with the input string.
return inputStr === reversedStr;
}
console.log(isPalindrome("racecar")); // prints true |
import React from 'react';
export function ShortcutItem(props) {
const { clickHandler, letter, label } = props;
return (
<a href="#"
className="btn btn-primary btn-sm"
role="button"
onClick={e => {
e.preventDefault();
return clickHandler(label);
}}>
<span className="badge">{letter}</span> {label}
</a>
);
}
|
#!/bin/bash
# tdnn_lstm_1l is same as tdnn_lstm_1b, but with the per-frame dropout
# added with location 4 in LSTM layer, see paper:
# http://www.danielpovey.com/files/2017_interspeech_dropout.pdf
# ./local/chain/compare_wer_general.sh tdnn_lstm_1b_ld5_sp tdnn_lstm_1l_ld5_sp
# System tdnn_lstm_1b_ld5_sp tdnn_lstm_1l_ld5_sp
# WER on train_dev(tg) 13.06 12.41
# WER on train_dev(fg) 12.13 11.59
# WER on eval2000(tg) 15.1 14.8
# WER on eval2000(fg) 13.9 13.5
# Final train prob -0.047 -0.069
# Final valid prob -0.093 -0.095
# Final train prob (xent) -0.735 -0.913
# Final valid prob (xent) -1.0151 -1.0820
# exp/chain/tdnn_lstm_1b_ld5_sp: num-iters=327 nj=3..16 num-params=39.6M dim=40+100->6074 combine=-0.062->-0.061 xent:train/valid[217,326,final]=(-0.877,-0.741,-0.735/-1.08,-1.02,-1.02) logprob:train/valid[217,326,final]=(-0.063,-0.048,-0.047/-0.095,-0.093,-0.093)
# exp/chain/tdnn_lstm_1l_ld5_sp: num-iters=327 nj=3..16 num-params=39.6M dim=40+100->6074 combine=-0.088->-0.084 xent:train/valid[217,326,final]=(-3.32,-0.961,-0.913/-3.40,-1.13,-1.08) logprob:train/valid[217,326,final]=(-0.176,-0.072,-0.069/-0.198,-0.097,-0.095)
set -e
# configs for 'chain'
stage=12
train_stage=-10
get_egs_stage=-10
speed_perturb=true
dir=exp/chain/tdnn_lstm_1l # Note: _sp will get added to this if $speed_perturb == true.
decode_iter=
decode_dir_affix=
# training options
leftmost_questions_truncate=-1
chunk_width=150
chunk_left_context=40
chunk_right_context=0
xent_regularize=0.025
self_repair_scale=0.00001
label_delay=5
dropout_schedule='0,0@0.20,0.3@0.50,0'
# decode options
extra_left_context=50
extra_right_context=0
frames_per_chunk=
remove_egs=false
common_egs_dir=
affix=
# End configuration section.
echo "$0 $@" # Print the command line for logging
. ./cmd.sh
. ./path.sh
. ./utils/parse_options.sh
if ! cuda-compiled; then
cat <<EOF && exit 1
This script is intended to be used with GPUs but you have not compiled Kaldi with CUDA
If you want to use GPUs (and have them), go to src/, and configure and make on a machine
where "nvcc" is installed.
EOF
fi
# The iVector-extraction and feature-dumping parts are the same as the standard
# nnet3 setup, and you can skip them by setting "--stage 8" if you have already
# run those things.
suffix=
if [ "$speed_perturb" == "true" ]; then
suffix=_sp
fi
dir=$dir${affix:+_$affix}
if [ $label_delay -gt 0 ]; then dir=${dir}_ld$label_delay; fi
dir=${dir}$suffix
train_set=train_nodup$suffix
ali_dir=exp/tri4_ali_nodup$suffix
treedir=exp/chain/tri5_7d_tree$suffix
lang=data/lang_chain_2y
# if we are using the speed-perturbed data we need to generate
# alignments for it.
local/nnet3/run_ivector_common.sh --stage $stage \
--speed-perturb $speed_perturb \
--generate-alignments $speed_perturb || exit 1;
if [ $stage -le 9 ]; then
# Get the alignments as lattices (gives the CTC training more freedom).
# use the same num-jobs as the alignments
nj=$(cat exp/tri4_ali_nodup$suffix/num_jobs) || exit 1;
steps/align_fmllr_lats.sh --nj $nj --cmd "$train_cmd" data/$train_set \
data/lang exp/tri4 exp/tri4_lats_nodup$suffix
rm exp/tri4_lats_nodup$suffix/fsts.*.gz # save space
fi
if [ $stage -le 10 ]; then
# Create a version of the lang/ directory that has one state per phone in the
# topo file. [note, it really has two states.. the first one is only repeated
# once, the second one has zero or more repeats.]
rm -rf $lang
cp -r data/lang $lang
silphonelist=$(cat $lang/phones/silence.csl) || exit 1;
nonsilphonelist=$(cat $lang/phones/nonsilence.csl) || exit 1;
# Use our special topology... note that later on may have to tune this
# topology.
steps/nnet3/chain/gen_topo.py $nonsilphonelist $silphonelist >$lang/topo
fi
if [ $stage -le 11 ]; then
# Build a tree using our new topology.
steps/nnet3/chain/build_tree.sh --frame-subsampling-factor 3 \
--leftmost-questions-truncate $leftmost_questions_truncate \
--context-opts "--context-width=2 --central-position=1" \
--cmd "$train_cmd" 7000 data/$train_set $lang $ali_dir $treedir
fi
if [ $stage -le 12 ]; then
echo "$0: creating neural net configs using the xconfig parser";
num_targets=$(tree-info $treedir/tree |grep num-pdfs|awk '{print $2}')
learning_rate_factor=$(echo "print 0.5/$xent_regularize" | python)
mkdir -p $dir/configs
cat <<EOF > $dir/configs/network.xconfig
input dim=100 name=ivector
input dim=40 name=input
# please note that it is important to have input layer with the name=input
# as the layer immediately preceding the fixed-affine-layer to enable
# the use of short notation for the descriptor
fixed-affine-layer name=lda input=Append(-2,-1,0,1,2,ReplaceIndex(ivector, t, 0)) affine-transform-file=$dir/configs/lda.mat
# the first splicing is moved before the lda layer, so no splicing here
relu-renorm-layer name=tdnn1 dim=1024
relu-renorm-layer name=tdnn2 input=Append(-1,0,1) dim=1024
relu-renorm-layer name=tdnn3 input=Append(-1,0,1) dim=1024
# check steps/libs/nnet3/xconfig/lstm.py for the other options and defaults
lstmp-layer name=lstm1 cell-dim=1024 recurrent-projection-dim=256 non-recurrent-projection-dim=256 delay=-3 dropout-proportion=0.0 dropout-per-frame=true
relu-renorm-layer name=tdnn4 input=Append(-3,0,3) dim=1024
relu-renorm-layer name=tdnn5 input=Append(-3,0,3) dim=1024
lstmp-layer name=lstm2 cell-dim=1024 recurrent-projection-dim=256 non-recurrent-projection-dim=256 delay=-3 dropout-proportion=0.0 dropout-per-frame=true
relu-renorm-layer name=tdnn6 input=Append(-3,0,3) dim=1024
relu-renorm-layer name=tdnn7 input=Append(-3,0,3) dim=1024
lstmp-layer name=lstm3 cell-dim=1024 recurrent-projection-dim=256 non-recurrent-projection-dim=256 delay=-3 dropout-proportion=0.0 dropout-per-frame=true
## adding the layers for chain branch
output-layer name=output input=lstm3 output-delay=$label_delay include-log-softmax=false dim=$num_targets max-change=1.5
# adding the layers for xent branch
# This block prints the configs for a separate output that will be
# trained with a cross-entropy objective in the 'chain' models... this
# has the effect of regularizing the hidden parts of the model. we use
# 0.5 / args.xent_regularize as the learning rate factor- the factor of
# 0.5 / args.xent_regularize is suitable as it means the xent
# final-layer learns at a rate independent of the regularization
# constant; and the 0.5 was tuned so as to make the relative progress
# similar in the xent and regular final layers.
output-layer name=output-xent input=lstm3 output-delay=$label_delay dim=$num_targets learning-rate-factor=$learning_rate_factor max-change=1.5
EOF
steps/nnet3/xconfig_to_configs.py --xconfig-file $dir/configs/network.xconfig --config-dir $dir/configs/
fi
if [ $stage -le 13 ]; then
if [[ $(hostname -f) == *.clsp.jhu.edu ]] && [ ! -d $dir/egs/storage ]; then
utils/create_split_dir.pl \
/export/b0{5,6,7,8}/$USER/kaldi-data/egs/swbd-$(date +'%m_%d_%H_%M')/s5c/$dir/egs/storage $dir/egs/storage
fi
steps/nnet3/chain/train.py --stage $train_stage \
--cmd "$decode_cmd" \
--feat.online-ivector-dir exp/nnet3/ivectors_${train_set} \
--feat.cmvn-opts "--norm-means=false --norm-vars=false" \
--chain.xent-regularize $xent_regularize \
--chain.leaky-hmm-coefficient 0.1 \
--chain.l2-regularize 0.00005 \
--chain.apply-deriv-weights false \
--chain.lm-opts="--num-extra-lm-states=2000" \
--trainer.num-chunk-per-minibatch 64 \
--trainer.frames-per-iter 1200000 \
--trainer.max-param-change 2.0 \
--trainer.num-epochs 4 \
--trainer.optimization.shrink-value 0.99 \
--trainer.optimization.num-jobs-initial 3 \
--trainer.optimization.num-jobs-final 16 \
--trainer.optimization.initial-effective-lrate 0.001 \
--trainer.optimization.final-effective-lrate 0.0001 \
--trainer.optimization.momentum 0.0 \
--trainer.deriv-truncate-margin 8 \
--egs.stage $get_egs_stage \
--egs.opts "--frames-overlap-per-eg 0" \
--egs.chunk-width $chunk_width \
--egs.chunk-left-context $chunk_left_context \
--egs.chunk-right-context $chunk_right_context \
--trainer.dropout-schedule $dropout_schedule \
--egs.dir "$common_egs_dir" \
--cleanup.remove-egs $remove_egs \
--feat-dir data/${train_set}_hires \
--tree-dir $treedir \
--lat-dir exp/tri4_lats_nodup$suffix \
--dir $dir || exit 1;
fi
if [ $stage -le 14 ]; then
# Note: it might appear that this $lang directory is mismatched, and it is as
# far as the 'topo' is concerned, but this script doesn't read the 'topo' from
# the lang directory.
utils/mkgraph.sh --self-loop-scale 1.0 data/lang_sw1_tg $dir $dir/graph_sw1_tg
fi
decode_suff=sw1_tg
graph_dir=$dir/graph_sw1_tg
if [ $stage -le 15 ]; then
[ -z $extra_left_context ] && extra_left_context=$chunk_left_context;
[ -z $extra_right_context ] && extra_right_context=$chunk_right_context;
[ -z $frames_per_chunk ] && frames_per_chunk=$chunk_width;
iter_opts=
if [ ! -z $decode_iter ]; then
iter_opts=" --iter $decode_iter "
fi
for decode_set in train_dev eval2000; do
(
steps/nnet3/decode.sh --acwt 1.0 --post-decode-acwt 10.0 \
--nj 50 --cmd "$decode_cmd" $iter_opts \
--extra-left-context $extra_left_context \
--extra-right-context $extra_right_context \
--frames-per-chunk "$frames_per_chunk" \
--online-ivector-dir exp/nnet3/ivectors_${decode_set} \
$graph_dir data/${decode_set}_hires \
$dir/decode_${decode_set}${decode_dir_affix:+_$decode_dir_affix}_${decode_suff} || exit 1;
if $has_fisher; then
steps/lmrescore_const_arpa.sh --cmd "$decode_cmd" \
data/lang_sw1_{tg,fsh_fg} data/${decode_set}_hires \
$dir/decode_${decode_set}${decode_dir_affix:+_$decode_dir_affix}_sw1_{tg,fsh_fg} || exit 1;
fi
) &
done
fi
wait;
exit 0;
|
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03403073+2429143.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03405126+2335544.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03413958+2345471.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03415366+2327287.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03415868+2342263.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03420383+2442454.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03422154+2439527.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03422760+2502492.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03424189+2411583.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03432662+2459395.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03433660+2327141.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03433692+2423382.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03434796+2503115.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03434860+2332218.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03435214+2450297.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03435569+2425350.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03440509+2529017.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03442628+2435229.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03442801+2410176.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03443541+2400049.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03443742+2508161.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03445017+2454401.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03445896+2323202.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03451199+2435102.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03452219+2328182.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03452349+2451029.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03452957+2345379.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03453022+2418455.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03453903+2513279.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03453941+2345154.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03454245+2503255.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03454407+2404268.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03454894+2351103.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03455048+2352262.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03460381+2527108.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03460525+2258540.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03460649+2434027.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03460652+2350204.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03460750+2422278.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03460777+2452005.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03460989+2440251.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03461175+2437203.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03461287+2403158.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03462047+2447077.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03462778+2335337.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03462863+2445324.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03463118+2407025.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03463288+2318192.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03463533+2324422.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03463591+2358013.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03463727+2420367.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03463777+2444517.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03463888+2431132.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03463939+2401469.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03464027+2455517.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03464831+2418060.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03464921+2436001.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03465260+2338433.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03465709+2315024.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03470678+2342546.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03471353+2342515.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03471481+2522186.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03471806+2423268.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03471814+2402115.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03472083+2505124.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03473368+2441032.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03473521+2532383.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03473801+2328050.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03474098+2255480.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03475973+2443528.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03481018+2300041.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03481099+2330253.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03481729+2430159.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03482277+2358212.fits
wget --no-parent http://data.sdss3.org/sas/dr10/apogee/spectro/redux/r3/s3/a3/v304/4259/aspcapStar-v304-2M03482604+2514411.fits
|
use std::fs::File;
use std::io::{BufRead, BufReader};
fn parse_file(file_path: &str) -> Result<(Vec<(i32, i32)>, Vec<(usize, usize)>), String> {
let file = File::open(file_path).map_err(|e| format!("Error opening file: {}", e))?;
let reader = BufReader::new(file);
let mut points = Vec::new();
let mut folds = Vec::new();
let mut parse_folds = false;
for line in reader.lines() {
let line = line.map_err(|e| format!("Error reading line: {}", e))?;
if line.is_empty() {
parse_folds = true;
continue;
}
let values: Vec<&str> = line.split(',').collect();
if values.len() != 2 {
return Err("Invalid format: each line should contain two comma-separated values".to_string());
}
let x: i32 = values[0].parse().map_err(|e| format!("Error parsing x coordinate: {}", e))?;
let y: i32 = values[1].parse().map_err(|e| format!("Error parsing y coordinate: {}", e))?;
if parse_folds {
folds.push((x as usize, y as usize));
} else {
points.push((x, y));
}
}
if parse_folds && points.is_empty() {
return Err("No points found before folds section".to_string());
}
Ok((points, folds))
} |
#!/usr/bin/env bash
#
# Copyright (c) Dell Inc., or its subsidiaries. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Capture from camera, blur faces, and write to Pravega.
# The OpenCV faceblur element uses the CPU so the video frames must be transferred between the GPU and CPU.
# Prerequisite: sudo apt-get install gstreamer1.0-opencv
set -ex
ROOT_DIR=$(readlink -f $(dirname $0)/../..)
pushd ${ROOT_DIR}
ls -lh ${ROOT_DIR}/target/debug/*.so
export GST_PLUGIN_PATH=${ROOT_DIR}/target/debug:${GST_PLUGIN_PATH}
export GST_DEBUG=pravegasink:DEBUG,INFO
export RUST_BACKTRACE=1
PRAVEGA_STREAM=${PRAVEGA_STREAM:-camera9}
PRAVEGA_CONTROLLER_URI=${PRAVEGA_CONTROLLER_URI:-192.168.1.123:9090}
FPS=15
BITRATE_KILOBYTES_PER_SEC=1000
BITRATE_BITS_PER_SEC=$(( 8000 * ${BITRATE_KILOBYTES_PER_SEC} ))
gst-launch-1.0 \
-v \
--eos-on-shutdown \
nvarguscamerasrc \
! "video/x-raw(memory:NVMM),width=1280,height=720,framerate=${FPS}/1,format=NV12" \
! nvvidconv flip-method=2 \
! nvv4l2h264enc maxperf-enable=1 preset-level=1 control-rate=1 bitrate=${BITRATE_BITS_PER_SEC} \
! mpegtsmux \
! pravegasink stream=examples/${PRAVEGA_STREAM} controller=${PRAVEGA_CONTROLLER_URI} timestamp-mode=realtime-clock \
|& tee /tmp/camera-to-pravega-no-blur.log
|
<reponame>difo23/heroeapp
import React from 'react'
import { HeroList } from '../heroes/HeroList'
export const MarvelScreen = () => {
return (
<div>
<h1>Marvel Screen</h1>
<hr />
<HeroList publisher="Marvel Comics" />
</div>
)
}
|
import { Component, OnInit } from "@angular/core";
import { NgRedux, select } from "@angular-redux/store";
import { Observable } from "rxjs";
import * as NotificationActions from "@actions/notification-container.actions";
import { AppState } from "@store/app.state";
import { NotificationContainer } from "@interfaces/notification-container.interface";
@Component({
selector: "notification-component",
templateUrl: "./notification.component.html"
})
export class NotificationComponent implements OnInit {
@select("notificationContainer") notificationContainer$: Observable<NotificationContainer>;
notificationContainer: NotificationContainer;
constructor(private ngRedux: NgRedux<AppState>) { }
ngOnInit() {
this.notificationContainer$.subscribe(
(notificationContainer: NotificationContainer) => (this.notificationContainer = notificationContainer)
);
}
dismiss(id: string) {
let notificationContainerActions: NotificationActions.Actions = new NotificationActions.CRUDNotificationContainer(this.notificationContainer);
notificationContainerActions.removeNotification(id);
this.ngRedux.dispatch({ type: notificationContainerActions.type, payload: notificationContainerActions.payload });
}
}
|
import h5py
import os
def loadWeightsPartial(model, weights_path, n_layers):
f = h5py.File(weights_path)
for k in range(f.attrs['nb_layers']):
if k >= n_layers:
break
g = f['layer_{}'.format(k)]
weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])]
model.layers[k].set_weights(weights)
f.close()
|
import java.util.List;
class TestRunner {
void runTests(List<TestCase> testCases) {
for (TestCase testCase : testCases) {
try {
testCase.runTest();
} catch (AssertionError e) {
System.out.println("Test failed: " + testCase.name);
return; // Stop immediately on test failure
}
}
}
} |
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var ListNode_1 = __importDefault(require("./ListNode"));
var root = new ListNode_1.default(1);
root.InsertNode(4);
root.InsertNode(3);
root.InsertNode(2);
root.InsertNode(5);
root.InsertNode(2);
root.Print();
function partition(head, x) {
if (head === null)
return null;
var parent = null;
var next = null;
var tmp = head;
while (tmp !== null) {
if (tmp.val < x) {
if (parent === null) {
parent = new ListNode_1.default(tmp.val);
next = parent;
}
else {
next.next = new ListNode_1.default(tmp.val);
next = next.next;
}
}
tmp = tmp.next;
}
tmp = head;
while (tmp !== null) {
if (tmp.val >= x) {
if (parent === null) {
parent = new ListNode_1.default(tmp.val);
next = parent;
}
else {
next.next = new ListNode_1.default(tmp.val);
next = next.next;
}
}
tmp = tmp.next;
}
return parent;
}
;
partition(root, 3).Print();
|
#! /bin/bash
timestamp="$(date +'%Y%m%d-%H%M%S')"
db="stitchv${timestamp}SET4.db"
dbzip="stitchv${timestamp}SET4db.zip"
log="log${timestamp}.txt"
#keep track of current time
curr_time=$(date +%s)
echo $(date) > $log
sbt stitcher/"runMain ncats.stitcher.impl.SRSJsonEntityFactory $db \"name=G-SRS, July 2018\" cache=data/hash.db ../stitcher-rawinputs/files/dump-public-2018-07-19.gsrs"
echo 'gsrs:' $(( ($(date +%s) - $curr_time )/60 )) 'min' >> $log
sbt stitcher/"runMain ncats.stitcher.impl.DrugBankXmlEntityFactory $db \"name=DrugBank, July 2018\" cache=data/hash.db ../stitcher-rawinputs/files/drugbank_all_full_database.xml.zip"
echo 'DrugBank:' $(( ($(date +%s) - $curr_time )/60 )) 'min' >> $log
sbt stitcher/"runMain ncats.stitcher.impl.PharmManuEncyl3rdEntityFactory $db \"name=Pharmaceutical Manufacturing Encyclopedia (Third Edition)\" ../stitcher-rawinputs/files/PharmManuEncycl3rdEd.json"
echo 'PharmManuEncycl:' $(( ($(date +%s) - $curr_time )/60 )) 'min' >> $log
sbt stitcher/"runMain ncats.stitcher.impl.LineMoleculeEntityFactory $db data/withdrawn.conf"
echo 'Withdrawn:' $(( ($(date +%s) - $curr_time )/60 )) 'min' >> $log
# these add additional data for event calculator
sbt stitcher/"runMain ncats.stitcher.impl.MapEntityFactory $db data/dailymedrx.conf"
echo 'DailyMedRx:' $(( ($(date +%s) - $curr_time )/60 )) 'min' >> $log
sbt stitcher/"runMain ncats.stitcher.impl.MapEntityFactory $db data/dailymedrem.conf"
echo 'DailyMedRem:' $(( ($(date +%s) - $curr_time )/60 )) 'min' >> $log
sbt stitcher/"runMain ncats.stitcher.impl.MapEntityFactory $db data/dailymedotc.conf"
echo 'DailyMedOTC:' $(( ($(date +%s) - $curr_time )/60 )) 'min' >> $log
sbt stitcher/"runMain ncats.stitcher.impl.MapEntityFactory $db data/ob.conf"
echo 'OB:' $(( ($(date +%s) - $curr_time )/60 )) 'min' >> $log
sbt stitcher/"runMain ncats.stitcher.impl.MapEntityFactory $db data/ct.conf"
echo 'CT:' $(( ($(date +%s) - $curr_time )/60 )) 'min' >> $log
# now the stitching...
sbt stitcher/"runMain ncats.stitcher.tools.CompoundStitcher $db 1"
echo 'Stitching:' $(( ($(date +%s) - $curr_time )/60 )) 'min' >> $log
# calculate events
sbt stitcher/"runMain ncats.stitcher.calculators.EventCalculator $db 1"
echo 'EventCalculator:' $(( ($(date +%s) - $curr_time )/60 )) 'min' >> $log
echo $(date) >> $log
#zip up the directory
zip -r $dbzip $db
|
const cheerio = require('cheerio');
const path = require('path');
const childProcess = require('child_process');
const fs = require('fs');
const mockReadFileSync = jest.spyOn(fs, 'readFileSync');
const mockExec = jest.spyOn(childProcess, 'exec').mockImplementation(() => ({
stdin: { write: jest.fn() },
on: jest.fn(),
stderr: { on: jest.fn() },
}),
);
const plantumlPlugin = require('../../../../src/plugins/default/markbind-plugin-plantuml');
const mockFolderPath = path.join(__dirname, '_plantuml');
const mockConfig = {
outputPath: mockFolderPath,
baseUrl: '',
rootPath: mockFolderPath,
};
test('processNode should modify inline puml node correctly', () => {
const expectedPicSrc = '/a31b4068deea63d65d1259b4d54bcc79.png';
const [pumlNode] = cheerio.parseHTML('<puml width=300>\n@startuml\n'
+ 'alice -> bob ++ : hello\n'
+ 'bob -> bob ++ : self call\n'
+ '@enduml\n</puml>', true);
plantumlPlugin.processNode({}, pumlNode, mockConfig);
expect(mockExec).toHaveBeenCalled();
expect(pumlNode.type).toEqual('tag');
expect(pumlNode.name).toEqual('pic');
expect(pumlNode.attribs.width).toEqual('300');
expect(pumlNode.attribs.src).toEqual(expectedPicSrc);
},
);
test('processNode should modify inline puml node (with name) correctly', () => {
const expectedPicSrc = '/alice.png';
const [pumlNode] = cheerio.parseHTML('<puml name="alice">\n@startuml\n'
+ 'alice -> bob ++ : hello\n'
+ 'bob -> bob ++ : self call\n'
+ '@enduml\n</puml>', true);
plantumlPlugin.processNode({}, pumlNode, mockConfig);
expect(mockExec).toHaveBeenCalled();
expect(pumlNode.type).toEqual('tag');
expect(pumlNode.name).toEqual('pic');
expect(pumlNode.attribs.src).toEqual(expectedPicSrc);
},
);
test('processNode should modify puml node (with src) correctly', () => {
const expectedPicSrc = 'activity.png';
const [pumlNode] = cheerio.parseHTML('<puml src="activity.puml" />', true);
plantumlPlugin.processNode({}, pumlNode, mockConfig);
expect(mockReadFileSync).toHaveBeenCalled();
expect(pumlNode.type).toEqual('tag');
expect(pumlNode.name).toEqual('pic');
expect(pumlNode.attribs.src).toEqual(expectedPicSrc);
},
);
test('processNode should not modify non-puml node', () => {
const divNode = cheerio.parseHTML('<div>HTML</div>', true)[0];
const copy = { ...divNode };
plantumlPlugin.processNode({}, divNode);
expect(divNode).toEqual(copy);
},
);
|
#!/bin/bash
set -e
set -x
gvt restore
rm -rf vendor/k8s.io/apiextensions-apiserver/vendor/k8s.io/apiserver/pkg/util/feature/
appname="sidecar-injector"
rm -rf $appname
BUILD_PATH=$(cd $(dirname $0);pwd)
echo $BUILD_PATH
cd $BUILD_PATH
CGO_ENABLED=0 GO_EXTLINK_ENABLED=0 go build --ldflags '-s -w -extldflags "-static"' -a -o $appname
cp $appname build/; cd $BUILD_PATH/build
bash -x build_image.sh
|
package wire
import (
"testing"
)
func TestTreeBaseReq_Encoding(t *testing.T) {
treeBaseReq := &TreeBaseReq{
Name: "testname.",
}
testMessageEncoding(t, "tree_base_req", treeBaseReq, &TreeBaseReq{})
}
|
<reponame>jayjfadd/yahoo-fantasy-custom<filename>app/util/fantasysports/lib/framework/fantasy.js
var Q = require("q"),
_ = require("underscore"),
FantasyRequest = require("./fantasyRequest");
function FantasySports(auth) {
this.defaults = {
apiRoot: "http://fantasysports.yahooapis.com/fantasy/v2/"
};
this.auth = auth;
}
FantasySports.prototype.options = function(opts) {
this.config = _.extend(this.defaults, opts);
this.auth.config = this.config;
};
FantasySports.prototype.startAuth = function(req, res) {
this.auth.beginAuthentication(req, res);
};
FantasySports.prototype.endAuth = function(req, res) {
this.auth.endAuthentication(req, res);
};
FantasySports.prototype.request = function(req, res) {
var request = new FantasyRequest(this.auth, req, res);
return request;
};
exports = module.exports = FantasySports;
|
<filename>src/main/java/com/filippov/data/validation/tool/controller/validation/InputValidator.java
/*
* Copyright 2018-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.filippov.data.validation.tool.controller.validation;
import com.filippov.data.validation.tool.dto.cache.CacheRequestDto;
import com.filippov.data.validation.tool.dto.workspace.WorkspaceDto;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ResponseStatusException;
public class InputValidator {
private boolean validateWorkspaceId;
private boolean validateWorkspaceDto;
private boolean validateTablePairId;
private boolean validateColumnPairId;
private boolean validateCacheRequestDto;
private boolean validateOffset;
private boolean validateLimit;
private String workspaceId;
private WorkspaceDto workspaceDto;
private String tablePairId;
private String columnPairId;
private CacheRequestDto cacheRequestDto;
private Integer offset;
private Integer limit;
private InputValidator() {
}
public static InputValidator builder() {
return new InputValidator();
}
public InputValidator withWorkspaceId(String workspaceId) {
this.validateWorkspaceId = true;
this.workspaceId = workspaceId;
return this;
}
public InputValidator withWorkspaceDto(WorkspaceDto workspaceDto) {
this.validateWorkspaceDto = true;
this.workspaceDto = workspaceDto;
return this;
}
public InputValidator withTablePairId(String tablePairId) {
this.validateTablePairId = true;
this.tablePairId = tablePairId;
return this;
}
public InputValidator withColumnPairId(String columnPairId) {
this.validateColumnPairId = true;
this.columnPairId = columnPairId;
return this;
}
public InputValidator withCacheRequestDto(CacheRequestDto cacheRequestDto) {
this.validateCacheRequestDto = true;
this.cacheRequestDto = cacheRequestDto;
return this;
}
public InputValidator withOffset(Integer offset) {
this.validateOffset = true;
this.offset = offset;
return this;
}
public InputValidator withLimit(Integer limit) {
this.validateLimit = true;
this.limit = limit;
return this;
}
public void validate() {
final StringBuilder sb = new StringBuilder();
if (validateWorkspaceId
&& (workspaceId == null || StringUtils.isEmpty(workspaceId))) {
sb.append("workspaceId is incorrect");
}
if (validateWorkspaceDto) {
if (workspaceDto == null) {
append(sb, "workspace is null");
} else {
if (StringUtils.isEmpty(workspaceDto.getName())) {
append(sb, "workspace name is incorrect");
}
if (workspaceDto.getLeft() == null) {
append(sb, "left datasource definition is null");
} else {
if (workspaceDto.getLeft().getDatasourceType() == null) {
append(sb, "incorrect left datasource type");
}
if (workspaceDto.getLeft().getMaxConnections() == null || workspaceDto.getLeft().getMaxConnections() <= 0) {
append(sb, "incorrect left datasource max connections property");
}
}
if (workspaceDto.getRight() == null) {
append(sb, "right datasource definition is null");
} else {
if (workspaceDto.getRight().getDatasourceType() == null) {
append(sb, "incorrect right datasource type");
}
if (workspaceDto.getRight().getMaxConnections() == null || workspaceDto.getRight().getMaxConnections() <= 0) {
append(sb, "incorrect right datasource max connections property");
}
}
}
}
if (validateTablePairId
&& (tablePairId == null || StringUtils.isEmpty(tablePairId))) {
append(sb, "incorrect table pair id");
}
if (validateColumnPairId
&& (columnPairId == null || StringUtils.isEmpty(columnPairId))) {
append(sb, "incorrect column pair id");
}
if (validateCacheRequestDto) {
if (cacheRequestDto == null) {
append(sb, "cache request is null");
} else if (cacheRequestDto.getCacheFetchingCommand() == null) {
append(sb, "incorrect caching command in cache request");
}
}
if (validateOffset
&& (offset == null || offset < 0)) {
append(sb, "incorrect offset");
}
if (validateLimit
&& (limit == null || limit < 0)) {
append(sb, "incorrect limit");
}
if (sb.length() != 0) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Incorrect input: " + sb.toString());
}
}
private void append(StringBuilder sb, String message) {
if (sb.length() != 0) {
sb.append("; ");
}
sb.append(message);
}
}
|
var AppListener = require('../lib/AppManager').AppListener;
var util = require('util');
util.inherits(MyAppListener, AppListener);
function MyAppListener(){
this.priority = 1;
}
MyAppListener.prototype.onStart = function(next){
console.log("My App Start ");
console.log(this);
next();
};
var singleton = new MyAppListener();
module.exports = singleton; |
#!/bin/bash
PATH=/bin:/usr/bin:/usr/local/bin:/usr/sbin
. pip-deps/bin/activate
pip install nose
pip install coverage
pip install pylint
pip install jinja2==2.6
pip install sphinx
pip install sphinx_bootstrap_theme
pip install webob
pip install virtual_env/libs/mysql-connector
pip install sqlalchemy
pip install mock
pip install uwsgi
pip install "pycrypto>=2.6"
|
<filename>src/main/java/com/atico/erp/core/ui/components/GridSecondaryText.java
package com.atico.erp.core.ui.components;
import com.vaadin.flow.component.html.Span;
public class GridSecondaryText extends Span {
public GridSecondaryText(String text) {
super(text);
getStyle().set("font-size", "var(--lumo-font-size-m)");
getStyle().set("color", "var(--lumo-secondary-text-color)");
getStyle().set("margin-top", "0");
getStyle().set("margin-bottom", "0");
}
}
|
#!/bin/sh
DIR="$( cd "$(dirname "$0")" && pwd )"
source $DIR/sample-env.sh
# check for ~/.smac-running-env and then check that
# processes are running before doing this. Then the
# expose ports stuff in the readme should work
SMAC_OPTS="-DtempMiniDir=/smac-tmp"
SMAC_OPTS="${SMAC_OPTS} -DinstanceName=${ACCUMULO_INSTANCE}"
SMAC_OPTS="${SMAC_OPTS} -DrootPassword=${ACCUMULO_ROOT_PASS}"
SMAC_OPTS="${SMAC_OPTS} -DnumTservers=${ACCUMULO_NUM_TSERVERS}"
SMAC_OPTS="${SMAC_OPTS} -DinitScript=${ACCUMULO_INIT_SCRIPT}"
SMAC_OPTS="${SMAC_OPTS} -DsetJDWP=${ACCUMULO_JDWP}"
SMAC_OPTS="${SMAC_OPTS} -DstartShell=${ACCUMULO_START_SHELL}"
SMAC_OPTS="${SMAC_OPTS} -DshutdownPort=${ACCUMULO_SHUTDOWN_PORT}"
SMAC_OPTS="${SMAC_OPTS} -Dlog4jConfig=${LOG4J_CONFIG}"
SMAC_OPTS="${SMAC_OPTS} -DmonitorPort=${ACCUMULO_MONITOR_PORT}"
if [ -n "${TSERV_CLIENTPORT}" ]; then
SMAC_OPTS="${SMAC_OPTS} -DtserverClientPort=${TSERV_CLIENTPORT}"
fi
if [ -n $EXISTING_ZOOKEEPERS ]; then
SMAC_OPTS="${SMAC_OPTS} -DexistingZookeepers=${EXISTING_ZOOKEEPERS}"
else
SMAC_OPTS="${SMAC_OPTS} -DzookeeperPort=${ZOOKEEPER_PORT}"
fi
SMAC_JAR=$(ls /downloads/standalone*.jar | head -1)
java $SMAC_OPTS -jar $SMAC_JAR
|
#!/bin/bash
cd `dirname $0`
npm run serve
|
//
// HierarchyScrollView.h
// TreeViewer
//
// Created by <NAME> on 1/11/15.
// Copyright (c) 2015 Inova. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TreeViewer.h"
@interface HierarchyScrollView : UIScrollView
// init the scroll view that contains the treeview.
- (id)initWithFrame:(CGRect)frame andWithRoot:(id<TreeViewerDelegate>)root;
@end
|
# Use powerline
USE_POWERLINE="true"
export GPG_TTY=$(tty)
# Source manjaro-zsh-configuration
if [[ -e /usr/share/zsh/manjaro-zsh-config ]]; then
source /usr/share/zsh/manjaro-zsh-config
fi
# Use manjaro zsh prompt
if [[ -e /usr/share/zsh/manjaro-zsh-prompt ]]; then
source /usr/share/zsh/manjaro-zsh-prompt
fi
|
<reponame>beverloo/draw
const browsers = [
'> 1%',
'last 3 versions',
'ios > 8',
'not ie < 10',
];
const node = 'current';
const getCommonConfig = (targets = {}) => [
[
'@babel/env',
{
targets,
useBuiltIns: 'usage',
corejs: {
version: 2,
},
}
],
'@babel/react',
];
const config = (api) => {
api.cache(true);
const isWebpack = process.env.IS_WEBPACK === 'true';
const plugins = [
['@babel/plugin-proposal-decorators', { legacy: true }],
'@babel/plugin-proposal-class-properties',
];
if (isWebpack) plugins.push('react-hot-loader/babel');
return {
presets: getCommonConfig(isWebpack ? { browsers } : { node }),
plugins,
};
};
module.exports = config;
|
<filename>5-websites/lambda-prep/_Resources/Precourse-master/Precourse-master/Lesson04-JS-I/homework/homework.js<gh_stars>0
//In these first 6 questions, replace `null` with the answer
//create a string variable, it can contain anything
const newString = null ;
//create a number variable, it an be any number
const newNum = null ;
//create a boolean variable
const newBool = null ;
//solve the following math problem
const newSubtract = 10 - null === 5;
//Solve the following math problem
const newMultiply = 10 * null === 40 ;
//Solve the following math problem:
const newModulo = 21 % 5 === null ;
//In the next 22 problems you will compete the function. All of your code will go inside of the function braces.
//Make sure you use return when the prompt asks you to.
//hint: console.log() will NOT work.
//Do not change any of the function names
function returnString(str) {
//simply return the string provided: str
}
function add(x, y) {
// x and y are numbers
// add x and y together and return the value
// code here
}
function subtract(x, y) {
// subtract y from x and return the value
// code here
}
function multiply(x, y) {
// multiply x by y and return the value
// code here
}
function divide(x, y) {
// divide x by y and return the value
// code here
}
function areEqual(x, y) {
// return true if x and y are the same
// otherwise return false
// code here
}
function areSameLength(str1, str2) {
// return true if the two strings have the same length
// otherwise return false
// code here
}
function lessThanNinety(num) {
// return true if the function argument: num , is less than ninety
// otherwise return false
// code here
}
function greaterThanFifty(num) {
// return true if num is greater than fifty
// otherwise return false
// code here
}
function getRemainder(x, y) {
// return the remainder from dividing x by y
// code here
}
function isEven(num) {
// return true if num is even
// otherwise return false
// code here
}
function isOdd(num) {
// return true if num is odd
// otherwise return false
// code here
}
function square(num) {
// square num and return the new value
// hint: NOT square root!
// code here
}
function cube(num) {
// cube num and return the new value
// code here
}
function raiseToPower(num, exponent) {
// raise num to whatever power is passed in as exponent
// code here
}
function roundNumber(num) {
// round num and return it
// code here
}
function roundUp(num) {
// round num up and return it
// code here
}
function addExclamationPoint(str) {
// add an exclamation point to the end of str and return the new string
// 'hello world' -> 'hello world!'
// code here
}
function combineNames(firstName, lastName) {
// return firstName and lastName combined as one string and separated by a space.
// 'Lambda', 'School' -> 'Lambda School'
// code here
}
function getGreeting(name) {
// Take the name string and concatenate other strings onto it so it takes the following form:
// 'Sam' -> 'Hello Sam!'
// code here
}
// The next three questions will have you implement math area formulas.
// If you can't remember these area formulas then head over to Google.
function getRectangleArea(length, width) {
// return the area of the rectangle by using length and width
// code here
}
function getTriangleArea(base, height) {
// return the area of the triangle by using base and height
// code here
}
// Do not modify code below this line.
// --------------------------------
module.exports = {
newString,
newNum,
newBool,
newSubtract,
newMultiply,
newModulo,
returnString,
areSameLength,
areEqual,
lessThanNinety,
greaterThanFifty,
add,
subtract,
divide,
multiply,
getRemainder,
isEven,
isOdd,
square,
cube,
raiseToPower,
roundNumber,
roundUp,
addExclamationPoint,
combineNames,
getGreeting,
getRectangleArea,
getTriangleArea,
};
|
#!/bin/bash
# Define the public IP address of the VM
vm1a_public_ip="192.168.1.100" # Replace with the actual public IP address
# Execute the SSH command to establish a connection to the VM
outputSSH=$(ssh -o BatchMode=yes -o ConnectTimeout=5 user@$vm1a_public_ip echo "SSH connection successful" 2> /dev/null)
# Print the captured output surrounded by asterisks
echo "***"
echo "Test 4 - from Internet to VM1B public IP ${vm1a_public_ip}"
echo $outputSSH
echo "***" |
import shutil
from os import path
def copy_file(source_path, destination_dir):
try:
# Check if the source file exists
if not path.exists(source_path):
print("Source file does not exist.")
return
# Check if the destination directory exists
if not path.exists(destination_dir):
print("Destination directory does not exist.")
return
# Extract the file name from the source path
file_name = path.basename(source_path)
# Construct the destination file path
destination_path = path.join(destination_dir, file_name)
# Copy the file to the destination directory
shutil.copy2(source_path, destination_path)
print(f"File '{file_name}' copied to '{destination_dir}' successfully.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
source_file_path = "/path/to/source/file.txt"
destination_directory = "/path/to/destination/directory"
copy_file(source_file_path, destination_directory) |
import UIKit
class ViewManager {
private let parentView: UIView
init(parentView: UIView) {
self.parentView = parentView
}
func addView(view: UIView, withConstraints: Bool) {
parentView.addSubview(view)
if withConstraints {
view.translatesAutoresizingMaskIntoConstraints = false
view.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true
view.widthAnchor.constraint(equalTo: parentView.widthAnchor, multiplier: 1.0 / CGFloat(parentView.subviews.count)).isActive = true
if let previousView = parentView.subviews.dropLast().last {
view.leadingAnchor.constraint(equalTo: previousView.trailingAnchor).isActive = true
} else {
view.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true
}
}
}
func removeView(view: UIView) {
view.removeFromSuperview()
}
func arrangeViewsHorizontally(views: [UIView]) {
for (index, view) in views.enumerated() {
parentView.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true
view.widthAnchor.constraint(equalTo: parentView.widthAnchor, multiplier: 1.0 / CGFloat(views.count)).isActive = true
if index > 0 {
let previousView = views[index - 1]
view.leadingAnchor.constraint(equalTo: previousView.trailingAnchor).isActive = true
} else {
view.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true
}
}
}
func arrangeViewsVertically(views: [UIView]) {
for (index, view) in views.enumerated() {
parentView.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true
view.heightAnchor.constraint(equalTo: parentView.heightAnchor, multiplier: 1.0 / CGFloat(views.count)).isActive = true
if index > 0 {
let previousView = views[index - 1]
view.topAnchor.constraint(equalTo: previousView.bottomAnchor).isActive = true
} else {
view.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true
}
}
}
} |
# Create a neural network model with 2 hidden layers of 10 neurons each
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(2,)),
tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(3, activation='softmax')
]) |
describe Fastlane::Actions::CarthageCacheFtpsAction do
describe '#run' do
it 'prints a message' do
expect(true)
end
end
end
|
<filename>homeassistant/components/gpslogger/device_tracker.py
"""
Support for the GPSLogger platform.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.gpslogger/
"""
import logging
from homeassistant.components.device_tracker import DOMAIN as \
DEVICE_TRACKER_DOMAIN
from homeassistant.components.gpslogger import DOMAIN as GPSLOGGER_DOMAIN, \
TRACKER_UPDATE
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.typing import HomeAssistantType
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['gpslogger']
DATA_KEY = '{}.{}'.format(GPSLOGGER_DOMAIN, DEVICE_TRACKER_DOMAIN)
async def async_setup_entry(hass: HomeAssistantType, entry, async_see):
"""Configure a dispatcher connection based on a config entry."""
async def _set_location(device, gps_location, battery, accuracy, attrs):
"""Fire HA event to set location."""
await async_see(
dev_id=device,
gps=gps_location,
battery=battery,
gps_accuracy=accuracy,
attributes=attrs
)
hass.data[DATA_KEY] = async_dispatcher_connect(
hass, TRACKER_UPDATE, _set_location
)
return True
async def async_unload_entry(hass: HomeAssistantType, entry):
"""Unload the config entry and remove the dispatcher connection."""
hass.data[DATA_KEY]()
return True
|
<reponame>Alex-Diez/java-tdd-Katas
package kata.joins;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class HashJoin<K extends Comparable<K>, V>
implements InnerJoin<K, V> {
private static final Function<JoinType, Boolean> PREDICATE = (j) -> j == JoinType.INNER;
@Override
public List<Triple<K, V, V>> innerJoin(List<Pair<K, V>> left, List<Pair<K, V>> right) {
return join(left, right, PREDICATE, JoinType.INNER);
}
public List<Triple<K, V, V>> leftJoin(List<Pair<K, V>> left, List<Pair<K, V>> right) {
return join(left, right, PREDICATE, JoinType.OUTER);
}
private Map<K, V> createHash(List<Pair<K, V>> data) {
return data.stream().collect(Collectors.toMap((kvPair -> kvPair.getKey()), (p -> p.getValue())));
}
private List<Triple<K, V, V>> join(List<Pair<K, V>> left, List<Pair<K, V>> right, Function<JoinType, Boolean> mapPredicate, JoinType joinType) {
Map<K, V> hash = createHash(right);
return left.stream()
.map(l -> {
V r = null;
if (mapPredicate.apply(joinType) || hash.containsKey(l.getKey())) {
r = hash.get(l.getKey());
}
return new ImmutableTriple<>(l.getKey(), l.getValue(), r);
}
).collect(Collectors.toList());
}
}
|
<filename>js/mixins/program.js
import Program from '../components/Program.vue';
export default {
props: ['id', 'options'],
components: {
Program
},
} |
def total_cost(items, prices, quantities):
cost = 0
for item, price, quantity in zip(items, prices, quantities):
cost += price * quantity
return cost
clothes_price = 26.30
clothes_quantity = 5
shoes_price = 33.45
shoes_quantity = 3
items = ['clothes', 'shoes']
prices = [clothes_price, shoes_price]
quantities =[clothes_quantity, shoes_quantity]
total_cost = total_cost(items, prices, quantities)
print(total_cost) |
/*
* MIT License
*
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.jamsimulator.jams.utils;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class CollectionUtils {
@SuppressWarnings("unchecked")
public static <T, K> Map<T, K> deepCopy(Map<T, K> original) {
Map<T, K> map = new HashMap<>();
original.forEach((key, value) -> {
if (value instanceof List) {
map.put(key, (K) deepCopy((List<?>) value));
} else if (value instanceof Map) {
map.put(key, (K) deepCopy((Map<?, ?>) value));
} else map.put(key, value);
});
return map;
}
@SuppressWarnings("unchecked")
public static <T> List<T> deepCopy(List<T> original) {
List<T> list = new LinkedList<>();
original.forEach(value -> {
if (value instanceof List) {
list.add((T) deepCopy((List<?>) value));
} else if (value instanceof Map) {
list.add((T) deepCopy((Map<?, ?>) value));
} else list.add(value);
});
return list;
}
}
|
<filename>open-sphere-plugins/wms/src/main/java/io/opensphere/wms/sld/event/SldChangeListener.java
package io.opensphere.wms.sld.event;
/**
* Styled layer descriptor change listener.
*
* @see SldChangeEvent
*/
public interface SldChangeListener
{
/**
* Invoked when sld is created.
*
* @param evt the evt
*/
void sldCreated(SldChangeEvent evt);
/**
* Invoked when sld is deleted.
*
* @param evt the evt
*/
void sldDeleted(SldChangeEvent evt);
}
|
<reponame>chlds/util
/* **** Notes
Display events.
//*/
# define CALEND
# define CAR
# include "../../../incl/config.h"
signed(__cdecl cals_display_events_r_r(time_t(*prev),cals_event_t(*argp))) {
auto cals_event_t *ev;
auto struct tm *tp;
auto signed char *b;
auto time_t t;
auto signed i,r;
auto signed short wk,di,mo,yr;
auto signed short hr;
auto signed short cols;
auto signed short colors;
auto signed short flag;
auto rect_t rect;
auto signed delay = (0x00);
auto signed char sym[] = {
('\n'),
(0x00),
};
if(!prev) return(0x00);
if(!argp) return(0x00);
// update day of the week for periodic events
if(CALS_PERIODIC&(R(flag,*argp))) {
t = (R(t,*argp));
tp = localtime(&t);
if(!tp) return(0x00);
*(CALS_WK+(R(date,*argp))) = (R(tm_wday,*tp));
*(CALS_DI+(R(date,*argp))) = (R(tm_mday,*tp));
}
yr = (*(CALS_YR+(R(date,*argp))));
mo = (*(CALS_MO+(R(date,*argp))));
di = (*(CALS_DI+(R(date,*argp))));
wk = (*(CALS_WK+(R(date,*argp))));
AND(flag,0x00);
t = (*prev);
*prev = (R(t,*argp));
if(cals_event_in_the_day(t,argp)) OR(flag,0x01);
// display only once on duplicate days
// column of the left
if(!flag) printf(" %2d %s ",*(CALS_DI+(R(date,*argp))),*(CAPS_DAYOFTHEWK+(*(CALS_WK+(R(date,*argp))))));
else printf("\t");
colors = (R(colors,*argp));
if(CALS_APERIODIC&(R(periodic,*argp))) AND(colors,0xFF);
if(colors) {
if(!(color_text(0xFF&(colors),0xFF&(colors>>(0x08))))) {
if(DBG) printf("%s \n","<< Error at fn. color_text()");
}}
// also
if(CALS_TIME_ALLDAY&(R(flag,*argp))) printf("%s ","All-day");
if(!(CALS_TIME_ALLDAY&(R(flag,*argp)))) {
hr = (*(CALS_HR+(R(time,*argp))));
b = ("%2d:%02d ");
if(CALS_MERIDIEM&(R(flag,*argp))) {
b = ("%2d:%02dam ");
if(!(hr<(12))) b = ("%2d:%02dpm ");
hr = (hr%(12));
}
printf(b,hr,*(CALS_MN+(R(time,*argp))));
}
if(colors) {
if(!(color_text(COLOR_RESET,COLOR_BG_RESET))) {
if(DBG) printf("%s \n","<< Error at fn. color_text()");
}}
// column of the right
b = (R(b,*argp));
// r = cli_outs(b);
if(!(rect_beta(CLI_IN,CLI_RULE,&rect))) return(0x00);
cols = (*(CLI_BASE+(R(right,rect))));
cols = (cols+(0x01+(~(0x03*(0x08)))));
r = cals_output(delay,colors,cols,sym,b);
if(!r) return(0x00);
if(DBG) {
printf("[");
printf("%d-%s-%d ",*(CALS_YR+(R(date,*argp))),*(MON+(*(CALS_MO+(R(date,*argp))))),*(CALS_DI+(R(date,*argp))));
printf("%s ",*(DAYOFTHEWK+(*(CALS_WK+(R(date,*argp))))));
printf("%2d:%02d:%02d",*(CALS_HR+(R(time,*argp))),*(CALS_MN+(R(time,*argp))),*(CALS_SM+(R(time,*argp))));
printf("] ");
}
// if(!(cli_es(CTRL_K))) return(0x00);
if(DBG) {
t = (R(t,*argp));
printf("[t: %lld] ",t);
tp = localtime(&t);
if(!tp) return(0x00);
printf("[%d-%s-%d %s ",1900+(R(tm_year,*tp)),*(MON+(R(tm_mon,*tp))),R(tm_mday,*tp),*(DAYOFTHEWK+(R(tm_wday,*tp))));
printf("%d:%02d:%02d] ",R(tm_hour,*tp),R(tm_min,*tp),R(tm_sec,*tp));
}
return(0x01);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.