language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 380 | 2.53125 | 3 |
[] |
no_license
|
# 此函数不应被前端调用,如有后端需要,其中权限问题将由后端依据实际情况完善
def create_user(cursor, db, usr, password):
sql1 = "create user \"{}\" with password '{}'".format(usr, password)
cursor.execute(sql1)
sql2 = "grant all privileges on database {} to \"{}\"".format(db, usr)
cursor.execute(sql2)
return cursor.rowcount
|
Java
|
UTF-8
| 287 | 2.09375 | 2 |
[] |
no_license
|
package mk.ukim.finki.wp.lab.service;
import mk.ukim.finki.wp.lab.model.Teacher;
import java.util.List;
import java.util.Optional;
public interface TeacherService {
List<Teacher> findAll();
Teacher findById(Long id);
Optional<Teacher> save(String name, String surname);
}
|
Java
|
UTF-8
| 4,356 | 1.789063 | 2 |
[] |
no_license
|
package com.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import io.cucumber.java.en.Then;
public class SpicejetFlightPage {
WebDriver driver;
By BookFlight = By.xpath("//*[@id=\"content-change\"]/div[2]");//Click on Flights Icon
By clickingflights = By.xpath("//*[@id=\"buttons\"]/div/div/ul/li[1]/a");
By clickRoundTrip =By.xpath("//input[@id='ctl00_mainContent_rbtnl_Trip_1']");////input[@id='ctl00_mainContent_rbtnl_Trip_1'];
By clickFromDepartCityDropdown = By.xpath("//input[@id='ctl00_mainContent_ddl_originStation1_CTXT']");
By clickDepartCity = By.xpath("//a[contains(text(),'Bengaluru (BLR)')]");
By clickArrivalCity = By.xpath("//body[1]/form[1]/div[4]/div[2]/div[1]/div[5]/div[2]/div[2]/div[2]/div[3]/div[1]/div[3]/div[1]/div[2]/div[2]/div[1]/table[1]/tbody[1]/tr[2]/td[2]/div[3]/div[1]/div[1]/ul[3]/li[9]/a[1]");
By clickDepartDate = By.xpath("//body[1]/div[2]/div[1]/table[1]/tbody[1]/tr[4]/td[5]/a[1]");
By closewindowwrongreturndate = By.xpath("//span[@id='spclearDate']");
By clickReturnDateCalendar=By.cssSelector("#ctl00_mainContent_view_date2"); //By.xpath("//input[@id='date_picker_id_2']");
By selectnextmonth = By.xpath("//span[contains(text(),'January')]");
By clickReturnDate = By.linkText("12");
By clickPassengersDropdown = By.cssSelector("#divpaxinfo");//By.xpath("/html[1]/body[1]/form[1]/div[4]/div[2]/div[1]/div[5]/div[2]/div[2]/div[2]/div[3]/div[1]/div[6]/div[2]']");
By clickAdult = By.xpath("//select[@id='ctl00_mainContent_ddl_Adult']");
//By selectChild = //select[@id='ctl00_mainContent_ddl_Child']
//By selectInfant = //select[@id='ctl00_mainContent_ddl_Infant']
By ClickCurrencyDropdown = By.xpath("//select[@id='ctl00_mainContent_DropDownListCurrency']");
By selectCurrency = By.xpath("//option[contains(text(),'INR')]");
By clickSearch = By.xpath("//input[@id='ctl00_mainContent_btn_FindFlights']");
By clickVerifyingFareDetails = By.xpath("//body/div[15]/form[1]/div[4]/div[1]/div[2]/div[1]/div[1]/span[2]");
By ClickContinuebutton = By.xpath("//*[@id=\"continue-to-contact-page\"]");
public SpicejetFlightPage(WebDriver driver) {
this.driver = driver;
//PageFactory.initElements(driver, this);
}
public void bookingFlights(WebDriver driver) {
driver.findElement(clickingflights).click();
}
public void click_Round_Trip(WebDriver driver) {
driver.findElement(clickRoundTrip).click();
}
public void click_From_Depart_City_Dropdown(WebDriver driver) {
driver.findElement(clickFromDepartCityDropdown).click();
}
public void click_Depart_City(WebDriver driver) {
driver.findElement(clickDepartCity).click();
}
// public void click_To_Arrival_City_Dropdown(WebDriver driver) {
// driver.findElement(clickToArrivalCityDropdown).click();
// }
public void click_Arrival_City(WebDriver driver) {
driver.findElement(clickArrivalCity).click();
}
public void click_Depart_Date(WebDriver driver) {
driver.findElement(clickDepartDate).click();
}
public void select_next_month(WebDriver driver) {
driver.findElement(selectnextmonth).click();
}
public void click_Return_Date(WebDriver driver) {
driver.findElement(clickReturnDate).click();
}
public void click_Return_Date_Calendar(WebDriver driver) {
driver.findElement(clickReturnDateCalendar).click();
}
public void close_window_wrong_returndate(WebDriver driver) {
driver.findElement(closewindowwrongreturndate).click();
}
public void click_Passengers_Dropdown(WebDriver driver) {
driver.findElement(clickPassengersDropdown).click();
}
public void click_Adult(WebDriver driver) {
driver.findElement(clickAdult).click();
}
public void Click_Currency_Dropdown(WebDriver driver) {
driver.findElement(ClickCurrencyDropdown).click();
}
public void select_Currency(WebDriver driver) {
driver.findElement(selectCurrency).click();
}
public void click_Search(WebDriver driver) {
driver.findElement(clickSearch).click();
}
public void click_Verifying_Fare_Details(WebDriver driver) {
driver.findElement(clickVerifyingFareDetails).click();
}
public void Click_Continue_button(WebDriver driver) {
driver.findElement(ClickContinuebutton).click();
}
// //public void close_the_browser(WebDriver driver) {
// public void close_the_browser() {
// tearDown();
// // driver.quit();
// }
}
|
TypeScript
|
UTF-8
| 245 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
import _ from 'lodash';
import * as Types from '../types/graphql';
export const formatAddress = ({street, building}: Pick<Types.Poi, 'street' | 'building'>) =>
[_.get(street, 'name'), building]
.filter(Boolean)
.join(', ');
|
Java
|
UTF-8
| 23,313 | 1.726563 | 2 |
[] |
no_license
|
package sk.insomnia.rowingRace.ui.controller;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.text.Text;
import javafx.util.Callback;
import javafx.util.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sk.insomnia.rowingRace.communication.PMOperations;
import sk.insomnia.rowingRace.constants.RowingRaceCodeTables;
import sk.insomnia.rowingRace.dto.DtoUtils;
import sk.insomnia.rowingRace.dto.RaceYearDto;
import sk.insomnia.rowingRace.exceptions.RowingRaceException;
import sk.insomnia.rowingRace.listeners.DataChangeObserver;
import sk.insomnia.rowingRace.listeners.RaceListener;
import sk.insomnia.rowingRace.listeners.TeamsListener;
import sk.insomnia.rowingRace.remote.PMDataHandler;
import sk.insomnia.rowingRace.so.Performance;
import sk.insomnia.rowingRace.so.PerformanceParameter;
import sk.insomnia.rowingRace.so.Performances;
import sk.insomnia.rowingRace.so.RaceRound;
import sk.insomnia.rowingRace.so.Racer;
import sk.insomnia.rowingRace.so.RacerInterval;
import sk.insomnia.rowingRace.so.RowingRace;
import sk.insomnia.rowingRace.so.Team;
import sk.insomnia.rowingRace.timer.TimeDisplay;
import sk.insomnia.tools.exceptionUtils.ExceptionUtils;
import sk.insomnia.tools.timeUtil.RowingRaceTimeUtil;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* Created by bobek on 6/26/2014.
*/
public class RaceViewController extends AbstractController implements TeamsListener, TimeDisplay, RaceListener {
private static final Logger logger = LoggerFactory.getLogger(RaceViewController.class);
@FXML
private Label rowingCadenceLabel;
@FXML
private Label lbRowingPaceTime;
@FXML
private ComboBox<RaceYearDto> cbRaceRaceYear;
@FXML
private ComboBox<RaceRound> cbRaceRaceRound;
@FXML
private ComboBox<Team> cbRaceTeam;
@FXML
private Label lblRaceDisciplineDescription;
@FXML
private Label lblWorkStatus;
@FXML
private Label lblDeviceConnected;
@FXML
private Label lblWorkoutDistance;
@FXML
private Label lblRowingTime;
@FXML
private Button btnSavePerformance;
@FXML
private Button bntStartRace;
@FXML
private TableView<RacerInterval> raceIntervalsTable;
@FXML
private TableColumn<RacerInterval, String> ritIntervalNumber;
@FXML
private TableColumn<RacerInterval, Racer> ritRacer;
@FXML
private TableColumn<RacerInterval, String> ritTime;
private final PMDataHandler remote = new PMDataHandler();
private int workState = -1;
private int deviceCount = 0;
private boolean raceRunning = false;
private int raceDistance;
private int relaySplit;
private boolean raceOnDistance = true;
private int relayRounds = 0;
private Performances performances;
private Performance performance;
private final ObservableList<Racer> teamMembers = FXCollections.observableArrayList();
private RowingRace rowingRace;
private static final int maxRacersInRace = 4;
private static final int minRacersInRace = 4;
private final ObservableList<RacerInterval> _intervalsData = FXCollections.observableArrayList();
@FXML
private void initialize() {
DataChangeObserver.registerTeamsListener(this);
DataChangeObserver.registerRaceListener(this);
cbRaceRaceRound.getItems().clear();
cbRaceTeam.getItems().clear();
try {
this.connectivityWatcher.setCycleCount(Timeline.INDEFINITE);
this.connectivityWatcher.play();
} catch (Exception e) {
this.connectivityWatcher.stop();
}
}
private void initRaceIntervalTable() {
raceIntervalsTable.setItems(_intervalsData);
raceIntervalsTable.setPlaceholder(new Text(resourceBundle.getString("NO_DATA_IN_TABLE")));
ritIntervalNumber.setCellValueFactory(new PropertyValueFactory<RacerInterval, String>("intervalNumber"));
ritRacer.setCellValueFactory(new PropertyValueFactory<RacerInterval, Racer>("fullName"));
ritRacer.setEditable(true);
ritRacer.setCellFactory(new Callback<TableColumn<RacerInterval, Racer>, TableCell<RacerInterval, Racer>>() {
@Override
public TableCell<RacerInterval, Racer> call(
TableColumn<RacerInterval, Racer> arg0) {
ComboBoxTableCell cb = new ComboBoxTableCell<RacerInterval, Racer>();
cb.getItems().addAll(teamMembers);
return cb;
}
;
});
ritRacer.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<RacerInterval, Racer>>() {
@Override
public void handle(TableColumn.CellEditEvent<RacerInterval, Racer> t) {
t.getTableView().getItems().get(t.getTablePosition().getRow()).setRacer(t.getNewValue());
}
});
ritTime.setCellValueFactory(new PropertyValueFactory<RacerInterval, String>("time"));
raceIntervalsTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
}
@Override
public void initLocale(Locale locale) {
this.locale = locale;
}
@Override
public void initResourceBundle(ResourceBundle resourceBundle) {
this.resourceBundle = resourceBundle;
initRaceIntervalTable();
}
@Override
public void onTeamsChange(List<Team> teamList) {
this.cbRaceTeam.getItems().clear();
this.cbRaceTeam.getItems().addAll(teamList);
}
@Override
public void initializeFormData() {
setupPerformance();
}
@FXML
private void handleCbRaceYearAction() {
cbRaceRaceRound.getItems().clear();
if (cbRaceRaceYear.getValue() != null &&
cbRaceRaceYear.getValue().getRounds() != null) {
List<RaceRound> rounds = new ArrayList<RaceRound>();
Calendar today = GregorianCalendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
for (RaceRound rr : cbRaceRaceYear.getValue().getRounds()) {
if (rr.getBegin().getTime() <= today.getTime().getTime() && rr.getEnd().getTime() >= today.getTime().getTime()) {
rounds.add(rr);
}
}
cbRaceRaceRound.getItems().addAll(rounds);
}
}
@FXML
private void handleRaceRound() {
if (cbRaceRaceRound.getValue() != null) {
lblRaceDisciplineDescription.setText(cbRaceRaceRound.getValue().getDescription());
}
}
@FXML
private void handleRaceTeamAction() {
if (cbRaceTeam.getValue() == null) {
String errorMessage = resourceBundle.getString("ERR_NO_TEAMS");
displayErrorMessage(errorMessage,
resourceBundle.getString("INFO_CORRECT_FIELDS"),
resourceBundle.getString("INFO_CORRECT_FIELDS_TITLE"));
} else if (cbRaceTeam.getValue().getId() == null) {
String errorMessage = resourceBundle.getString("ERR_TEAM_NOT_REGISTERED");
displayErrorMessage(errorMessage,
resourceBundle.getString("ERR_TEAM_NOT_REGISTERED_MSG"),
resourceBundle.getString("ERR_TEAM_NOT_REGISTERED"));
} else if (cbRaceTeam.getValue().getRacers() == null
|| cbRaceTeam.getValue().getRacers().size() <= 0) {
String errorMessage = resourceBundle.getString("ERR_NO_RACERS_IN_ORGANIZATION");
displayErrorMessage(errorMessage,
resourceBundle.getString("INFO_CORRECT_FIELDS"),
resourceBundle.getString("INFO_CORRECT_FIELDS_TITLE"));
} else if (
cbRaceRaceRound.getValue() == null
|| cbRaceRaceRound.getValue().getDiscipline() == null
|| cbRaceRaceRound.getValue().getDiscipline().getIntervals() == null) {
String errorMessage = resourceBundle.getString("ERR_DISCIPLINE_INTERVALS_EMTPY");
displayErrorMessage(errorMessage,
resourceBundle.getString("INFO_CORRECT_FIELDS"),
resourceBundle.getString("INFO_CORRECT_FIELDS_TITLE"));
} else {
boolean performanceToSave = false;
this.teamMembers.clear();
this.teamMembers.addAll(cbRaceTeam.getValue().getRacers());
refreshRaceIntervalsTable();
}
}
private void refreshRaceIntervalsTable() {
if (this.cbRaceTeam.getValue().getRacers().size() < 4) {
Object[] params = {RowingRaceCodeTables.CT_COUNTRIES};
String errorMessage = MessageFormat.format(resourceBundle.getString("ERR_MINIMUM_TEAM_MEMBERS"), this.minRacersInRace) + "\n";
displayErrorMessage(errorMessage,
resourceBundle.getString("INFO_ACTION_NOT_ALLOWED"),
resourceBundle.getString("INFO_ACTION_NOT_ALLOWED_TITLE"));
return;
}
raceIntervalsTable.getItems().clear();
if (cbRaceRaceRound.getValue().getDiscipline().getIntervals() != null
&& this.cbRaceTeam.getValue().getRacers() != null) {
if (cbRaceRaceRound.getValue().getDiscipline().getIntervals().size() == 1) {
relayRounds = cbRaceRaceRound.getValue().getDiscipline().getIntervals().get(0).getWorkoutValue() / cbRaceRaceRound.getValue().getDiscipline().getIntervals().get(0).getRelaySplitValue();
this.raceDistance = cbRaceRaceRound.getValue().getDiscipline().getIntervals().get(0).getWorkoutValue();
this.relaySplit = cbRaceRaceRound.getValue().getDiscipline().getIntervals().get(0).getRelaySplitValue();
if (cbRaceRaceRound.getValue().getDiscipline().getIntervals().get(0).getDimension().getAcronym().equals("DIM_TIME")) {
this.raceOnDistance = false;
}
} else {
relayRounds = cbRaceRaceRound.getValue().getDiscipline().getIntervals().size();
}
for (int i = 0; i < relayRounds; i++) {
RacerInterval _ri = new RacerInterval();
_ri.setIntervalNumber(i + 1);
_ri.setRacer(cbRaceTeam.getValue().getRacers().get(i % maxRacersInRace));
this._intervalsData.add(_ri);
}
raceIntervalsTable.layout();
}
}
@FXML
private void handleSavePerformance() {
if (performances == null || performances.getPerformances() == null) {
String saved = this.resourceBundle.getString("NO_PERFORMANCE_TO_SAVE");
displayInfoMessage(saved, saved, saved);
return;
}
boolean saveSuccess = true;
for (Performance p : performances.getPerformances()) {
try {
dataProcessor.saveOrUpdatePerformance(p);
performances.getPerformances().remove(p);
} catch (RowingRaceException e) {
logger.error("Error saving performance.", e);
String notSaved = this.resourceBundle.getString("INFO_PERFORMANCE_NOT_SAVED");
String[] args = {Integer.toString(performance.getFinalDistance()), RowingRaceTimeUtil.formatRowingTime(performance.getFinalTime())};
displayInfoMessage(MessageFormat.format(this.resourceBundle.getString("PERFORMANCE_DETAIL"), args), notSaved, notSaved);
saveSuccess = false;
}
}
if (saveSuccess) {
try {
fileService.deletePerformance();
} catch (IOException e) {
logger.debug(ExceptionUtils.exceptionAsString(e));
}
String saved = this.resourceBundle.getString("INFO_PERFORMANCE_SAVED_DB");
displayInfoMessage(saved, saved, saved);
} else {
try {
fileService.saveOrUpdate(performances);
String saved = this.resourceBundle.getString("INFO_PERFORMANCE_SAVED_FS");
displayInfoMessage(saved, saved, saved);
} catch (IOException e) {
logger.error("Can't write performance data to file after attempt to store it in database.");
}
}
}
private void setupPerformance() {
try {
logger.info("going to load performances from file");
this.performances = fileService.loadPerformance();
} catch (IOException e) {
logger.info("error while loading performance data from file : " + ExceptionUtils.exceptionAsString(e));
}
if (this.performances == null) {
this.performances = new Performances();
logger.info("Loading performance data from file failed, instantiating new ");
btnSavePerformance.setDisable(true);
} else {
btnSavePerformance.setDisable(false);
}
lblDeviceConnected.setText(resourceBundle.getString("label.pm.disconnected"));
}
@Override
public void showTime(String time) {
this.lbRowingPaceTime.setText(time);
}
@FXML
private void handleRaceStartStop() {
if (raceRunning) {
this.performanceWatcher.stop();
this.workState = -1;
this.remote.callResetCmd();
this.remote.callGoReadyCmd();
} else {
this.remote.callResetCmd();
this.remote.callGoReadyCmd();
}
if (deviceCount <= 0) {
deviceCount = remote.connectToDevice();
}
if (deviceCount > 0) {
this.raceRunning = true;
PMOperations.setWorkout(this.remote, cbRaceRaceRound.getValue().getDiscipline());
// only while one rowing machine is supposed to be used
this.remote.setPort(0);
this.performanceWatcher.setCycleCount(Timeline.INDEFINITE);
this.performanceWatcher.play();
}
refreshRaceIntervalsTable();
}
Timeline connectivityWatcher = new Timeline(new KeyFrame(Duration.millis(1000), new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
deviceCount = 0;
try {
deviceCount = remote.connectToDevice();
} catch (Exception e) {
logger.error("Can't connect to device, cause : ",e);
connectivityWatcher.stop();
}
if (deviceCount > 0) {
lblDeviceConnected.setText(resourceBundle.getString("label.pm.connected"));
} else {
lblDeviceConnected.setText(resourceBundle.getString("label.pm.disconnected"));
}
}
}));
Timeline performanceWatcher = new Timeline(new KeyFrame(Duration.millis(500), new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
if (deviceCount > 0) {
double speed = PMOperations.getSpeed(remote);
lbRowingPaceTime.setText(MessageFormat.format(resourceBundle.getString("label.actualRowingTime"), RowingRaceTimeUtil.rowingSpeedAsParams(speed)));
int cadence = PMOperations.getCadence(remote);
String[] props = {Integer.toString(cadence)};
rowingCadenceLabel.setText(MessageFormat.format(resourceBundle.getString("label.cadence"), props));
double seconds = PMOperations.getDataGetWorkTime(remote);
int sekundy = (int) ((seconds / 100) % 60);
lblRowingTime.setText(MessageFormat.format(resourceBundle.getString("label.rowingTime"), RowingRaceTimeUtil.formatRowingTime(seconds)));
int newWorkState = PMOperations.getWorkoutState(remote);
if (newWorkState != workState) {
workState = newWorkState;
lblWorkStatus.setText(resourceBundle.getString("workState." + newWorkState));
}
logger.debug("workstate : " + workState);
int distance = 0;
try {
distance = PMOperations.intArrayToInt(PMOperations.getDataGetWorkDistance(remote));
} catch (Exception e) {
logger.debug(" something bad happen during distance calculations : " + ExceptionUtils.exceptionAsString(e));
}
String[] wrkDistanceProps = {distance / 10 + " m / " + raceDistance + " m"};
lblWorkoutDistance.setText(MessageFormat.format(resourceBundle.getString("label.workoutDistance"), wrkDistanceProps));
if (workState == 1) {
if (performance == null) {
performance = new Performance();
performance.setTeam(cbRaceTeam.getValue());
logger.debug("performance created");
}
if (performance.getParameters() == null) {
performance.setParameters(new ArrayList<PerformanceParameter>());
}
try {
if (raceIntervalsTable.getSelectionModel().getSelectedIndex() < 0) {
raceIntervalsTable.getSelectionModel().select(0);
logger.debug("setting raceIntervalsTable's selection model to 0");
}
int currSplit = raceIntervalsTable.getSelectionModel().getSelectedIndex();
int workout = 0;
if (raceOnDistance) {
workout = distance / 10;
} else {
workout = (int) (seconds / 100);
}
int splitShift = ((raceDistance - workout) / relaySplit);
if (splitShift > currSplit) {
currSplit++;
if (raceIntervalsTable.getSelectionModel().getSelectedItem() == null) {
raceIntervalsTable.getSelectionModel().select(0);
}
raceIntervalsTable.getSelectionModel().getSelectedItem().setDistance(new Long(distance));
raceIntervalsTable.getSelectionModel().getSelectedItem().setTime(RowingRaceTimeUtil.formatRowingTime(seconds));
// posun sa na dalsie
raceIntervalsTable.getSelectionModel().select(currSplit);
raceIntervalsTable.getColumns().get(2).setVisible(false);
raceIntervalsTable.getColumns().get(2).setVisible(true);
}
} catch (Exception e) {
logger.debug("racer shift gone bad :" + ExceptionUtils.exceptionAsString(e));
}
if (sekundy % 3 == 0) {
PerformanceParameter performanceParam = new PerformanceParameter();
performanceParam.setCadence(cadence);
performanceParam.setSpeed(speed);
performanceParam.setTime(seconds);
performanceParam.setRacedBy(raceIntervalsTable.getSelectionModel().getSelectedItem().getRacer());
logger.debug("performance parameters, added racer : " + raceIntervalsTable.getSelectionModel().getSelectedItem().getRacer().getFullName());
performance.getParameters().add(performanceParam);
logger.debug("performance parameters added at : " + sekundy);
}
}
if (performance != null && (workState == 10 || workState == 12)) {
if (distance == 0) {
distance = raceDistance;
}
performance.setFinalDistance(distance);
performance.setDate(new Date());
performance.setFinalTime(seconds);
performance.setRaceRound(cbRaceRaceRound.getValue());
logger.debug("performance watcher going down");
performanceWatcher.stop();
logger.debug("performance watcher is down");
btnSavePerformance.setDisable(false);
/*
try {
logger.debug("connected, going to write data to DB");
dataProcessor.saveOrUpdatePerformance(performance);
logger.debug("data writen to DB");
} catch (RowingRaceException e) {
logger.debug("Error saving performance data to database.", e);
}
*/
if (performances.getPerformances() == null) {
performances.setPerformances(new ArrayList<Performance>());
}
performances.getPerformances().add(performance);
try {
logger.debug("save performance data to file");
fileService.saveOrUpdate(performances);
} catch (Exception e) {
logger.debug("save performance data to file failed : " + ExceptionUtils.exceptionAsString(e));
}
performance = null;
}
} else {
logger.info("No performance, or wrong workState ");
}
}
}));
@Override
public void onRaceSelected(RowingRace race) {
this.rowingRace = race;
setRaceYears();
}
private void setRaceYears() {
this.cbRaceRaceYear.getItems().clear();
List<RaceYearDto> raceYearDtos = DtoUtils.raceYearsToDtos(this.rowingRace.getRaceYears(), this.locale.getLanguage());
this.cbRaceRaceYear.getItems().addAll(raceYearDtos);
}
}
|
C++
|
UTF-8
| 742 | 3.59375 | 4 |
[] |
no_license
|
/*
File Name: 169MajorityElement.cpp
Xiaolong Zhang
Question:
Given an array of size n, find the majority element.
The majority element is the element that appears more
than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the
majority element always exist in the array.
++++++++++++++++++++++++++++++++++++++
Solution:
Conteract different elements, so that only the majority
element survives.
*/
class Solution {
public:
int majorityElement(std::vector<int> &num) {
int count = 1;
int majIndex = 0;
for (int i = 1; i < num.size(); i++){
if (num[majIndex] == num[i])
count++;
else
count--;
if (count == 0){
majIndex = i;
count = 1;
}
}
return num[majIndex];
}
};
|
Java
|
UTF-8
| 903 | 2.53125 | 3 |
[] |
no_license
|
package NutriaDao;
import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.support.ConnectionSource;
import java.io.FileInputStream;
import java.util.Properties;
/**
*
* @author Ariel
*/
public class DbConnection {
private ConnectionSource conn;
public DbConnection() {
try {
Properties prop = new Properties();
prop.load(new FileInputStream("config.properties"));
Class.forName("org.sqlite.JDBC");
conn = new JdbcConnectionSource(prop.getProperty("db.string"));
}
catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
public ConnectionSource getConnection() {
return this.conn;
}
}
|
JavaScript
|
UTF-8
| 943 | 2.71875 | 3 |
[] |
no_license
|
// load the things we need
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// define the schema for our user model
var userSchema = mongoose.Schema({
local : {
username : String,
password : String,
},
currentClass : String,
classes: [
{
className: String,
classAverage: Number,
numStudents: Number,
studentList: [
{
studentName: String,
age: Number,
gender: String,
classAverage: Number
}
]
}
]
});
// generating a hash
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
// create the model for users and expose it to our app
module.exports = mongoose.model('User', userSchema);
|
Shell
|
UTF-8
| 2,135 | 3.609375 | 4 |
[] |
no_license
|
#!/bin/sh
MAIN_EXE='xyipk'
base_path=$(dirname $0)
cd ${base_path}
ulimit -c ulimited
SOFTMODE=`fw_printenv xl_softmode | awk -F "=" '{print $2}'`
stop_app ()
{
ps | grep xyipk_daemon | grep -v grep | awk '{print $1}' | xargs kill -9
killall xyipkd
killall ${MAIN_EXE}
}
start_app ()
{
cd ${base_path}
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${base_path}/lib
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/thunder/lib
rm ${base_path}/xyipkd
sh ${base_path}/xyipk_daemon.sh &
}
# mounting '/app' dir of rootfs to '/dev/data'
mount_app_dir()
{
mount_dev="/dev/data"
mount_info=`mount | grep '/dev/data'`
if [ -z "$mount_info" ]; then
mount $mount_dev /app
# fail to mount,supposed to format
if [ $? -ne 0 ]; then
mkfs.ext4 -F $mount_dev
mkdir -p /tmp/app
mount $mount_dev /tmp/app
if [ $? -eq 0 ]; then
while true
do
mkdir -p /app/lost\+found/
cp -rf /app/* /tmp/app
sync
diff -r /app /tmp/app
[ $? -eq 0 ] && break
touch /tmp/loopcopy.app
sleep 1
done
umount $mount_dev
mount $mount_dev /app
fi
else
# mount success,do copy-action guarantee
if [ "$SOFTMODE" = "factory" ]; then
mkdir -p /tmp/system
mount /dev/system /tmp/system
diff -r /app /tmp/system/app
if [ $? -ne 0 ]; then
cp -rf /tmp/system/app/* /app
sync
touch /tmp/repair.app
fi
umount /tmp/system
fi
fi
return 1
fi
return 0
}
# boot every app in dirs named templated 'miner.<$name>.ipk' under '/app/system'
start_plugin_app ()
{
plugin_dirs=`ls /app/system | grep miner | grep -v miner.xyipkmng.ipk`
for plugin_dir in $plugin_dirs
do
[ -e /app/system/$plugin_dir/start.sh ] && (sh /app/system/$plugin_dir/start.sh >/dev/null 2>/dev/null &)
sleep 1
done
}
[ -d /tmp/.opkg_ipk ] || mkdir /tmp/.opkg_ipk
stop_app
mount_app_dir
# don't bootup plugins when factory mode
[ "$SOFTMODE" = "factory" ] && exit 1
start_app
sleep 1
start_plugin_app
exit 0
|
C++
|
UTF-8
| 7,023 | 2.859375 | 3 |
[] |
no_license
|
/**
* bn40.cpp for Clique3
* Copyright (C) 2018, Gu Jun
*
* This file is part of Clique3.
* Clique3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
* Clique3 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Clique3. If not, see <http://www.gnu.org/licenses/>.
**/
#include "bn40.h"
#include <iostream>
#include <string>
using namespace std;
bn40::bn40(size_t len){
this->_len = len;
this->_ele = new size_t[len];
for(size_t i=0; i < len; i++){
this->_ele[i] = 0;
}
}
bn40::~bn40(){
delete[] this->_ele;
}
size_t bn40::bits(){
this->shrink();
size_t v = 0x40 * this->_len ;
size_t tmp = 0x8000000000000000;
size_t p = this->_ele[this->_len - 1];
while(((p & tmp) == 0) && (v > 0)){
tmp = tmp >> 1;
v--;
}
return v;
}
bn40* bn40::leftpush(size_t bits){
size_t i = bits % 0x40;
size_t o = bits / 0x40;
bn40* r;
if(i == 0){
r = new bn40(this->_len + o);
for(size_t index=0; index < this->_len; index++){
r->addat(index + o, this->_ele[index]);
}
}else{
r = new bn40(this->_len + o + 1);
size_t remain = 0x40 - i;
for(size_t index=0; index < this->_len; index++){
r->addat(index + o, this->_ele[index] << i);
r->addat(index + o + 1, this->_ele[index] >> remain);
}
}
r->shrink();
return r;
}
void bn40::addat(size_t p, size_t v){
size_t val = this->_ele[p];
size_t sum = val + v;
this->_ele[p] = sum;
if(sum < val){
this->addat(p + 1, 1);
}
}
void bn40::subat(size_t p, size_t v){
size_t val = this->_ele[p];
size_t out = val - v;
this->_ele[p] = out;
if(out > val){
this->subat(p + 1, 1);
}
}
void bn40::shrink(){
size_t index = this->_len - 1;
while(index > 0){
if(this->_ele[index] == 0){
index--;
}else{
break;
}
}
this->_len = index + 1;
}
int cmp(bn40* a, bn40* b){
int r = 0; /*by default a == b*/
a->shrink();
b->shrink();
if(a->_len > b->_len){
return 1;
}
if(a->_len < b->_len){
return -1;
}
size_t index = a->_len - 1;
while((a->_ele[index] == b->_ele[index]) && (index > 0)){
index--;
}
if(a->_ele[index] > b->_ele[index]){
return 1;
}
if(a->_ele[index] < b->_ele[index]){
return -1;
}
return r;
}
bn40* add(bn40* a, bn40* b){
a->shrink();
b->shrink();
size_t len = a->_len;
if( len < b->_len){
len = b->_len;
}
len += 1;
bn40* r = new bn40(len);
int index = 0;
for(; index < a->_len; index++){
r->addat(index, a->_ele[index]);
}
index = 0;
for(; index < b->_len; index++){
r->addat(index, b->_ele[index]);
}
r->shrink();
return r;
}
bn40* sub(bn40* a, bn40* b){
a->shrink();
b->shrink();
bn40* r = new bn40(a->_len);
int index = 0;
for(; index < a->_len; index++){
r->addat(index, a->_ele[index]);
}
index = 0;
for(; index < b->_len; index++){
r->subat(index, b->_ele[index]);
}
r->shrink();
return r;
}
bn40* mul(bn40* a, bn40* b){
a->shrink();
b->shrink();
size_t len = a->_len + b->_len;
bn40* r = new bn40(len);
size_t ia = 0;
size_t ib = 0;
size_t index = 0;
for( ia = 0; ia < a->_len; ia++){
size_t aright = a->_ele[ia] & _bits20;
size_t aleft = a->_ele[ia] >> 0x20;
for(ib = 0; ib < b->_len; ib++){
size_t bright = b->_ele[ib] & _bits20;
size_t bleft = b->_ele[ib] >> 0x20;
index = ia + ib;
r->addat(index, aright * bright);
r->addat(index + 1, aleft * bleft);
size_t val1 = aleft * bright;
r->addat(index, val1 << 0x20);
r->addat(index + 1, val1 >> 0x20);
size_t val2 = aright * bleft;
r->addat(index, val2 << 0x20);
r->addat(index + 1, val2 >> 0x20);
}
}
r->shrink();
return r;
}
bn40* bn40::clone(){
this->shrink();
bn40* r = new bn40(this->_len);
size_t i = 0;
for(; i < this->_len; i++){
r->_ele[i] = this->_ele[i];
}
return r;
}
bn40* mod(bn40* a, bn40* b){
/*if a < b*/
if(cmp(a,b) < 0){
bn40* r = a->clone();
return r;
}
int diff = a->bits() - b->bits();
if(diff < 0){
cout<<"logic error, diff = "<<diff<<endl;
}
if( diff == 0){
bn40* tmp = sub(a, b);
bn40* r = mod(tmp, b);
delete tmp;
return r;
}else{
bn40* nb = b->leftpush(diff);
bn40* nb1 = b->leftpush(diff - 1);
bn40* tmp;
if(cmp(a, nb) >= 0){
tmp = sub(a, nb);
}else{
tmp = sub(a, nb1);
}
bn40* r = mod(tmp, b);
delete tmp;
delete nb;
delete nb1;
return r;
}
}
bn40* npmod(bn40* a, bn40* b, bn40* c){
a->shrink();
b->shrink();
c->shrink();
size_t bbits = b->bits();
bn40* ar[bbits];
ar[0] = mod(a,c);
size_t index = 1;
/* cout<<"L247"<<endl;*/
for(index = 1; index < bbits; index++){
bn40* m = mul(ar[index - 1], ar[index - 1]);
/* cout<<"L222 index="<<index<<endl;*/
bn40* tmp = mod(m, c);
/* cout<<"L224 index="<<index<<endl;*/
ar[index] = tmp;
delete m;
}
/* cout<<"L254"<<endl;*/
bn40* r = new bn40(1);
r->addat(0,1);
for(size_t index = 0; index < bbits; index++){
size_t v_1 = 1;
size_t o = index / 0x40;
size_t i = index % 0x40;
size_t v = v_1 << i;
if((b->_ele[o] & v) != 0){
bn40* tmp = mul(r, ar[index]);
delete r;
r = mod(tmp, c);
delete tmp;
}
}
for(size_t index = 0; index < bbits; index++){
delete ar[index];
}
return r;
}
bn40* mersenne(size_t n){
size_t len = n/64 + 1;
size_t pos = n%64;
bn40* r = new bn40(len);
size_t v_1 = 1;
v_1 <<= pos;
r->addat(len - 1, v_1);
r->subat(0, 1);
return r;
}
string* bn40::tohex(){
size_t chars = (this->_len) << 4;
size_t f = 0xf;
string* str = new string();
for(size_t i = 0 ; i < chars; i++){
int o_index = i / 0x10;
int i_index = i % 0x10;
size_t v = *(this->_ele + o_index);
size_t a = (v >> (i_index*4))& f;
char tc;
if(a <= 9){
tc = '0' + a;
}else {
tc = 'a' + a - 10;
}
*str += tc;
}
return str;
}
bn40* fromhex(string* str){
size_t len = str->length();
size_t length = len >> 4;
if((len % 0x10) !=0){
length++;
}
bn40* r = new bn40(length);
for(size_t i = 0 ; i < len ; i++){
size_t o_index = i / 0x10;
size_t i_index = i % 0x10;
char c = *(str->c_str() + i);
size_t v;
if((c >='0') && (c<='9')){
v = c - '0';
}
if((c >= 'a') && (c <= 'f')){
v = c - 'a' + 0xa;
}
v <<= (i_index * 4);
r->addat(o_index, v);
}
return r;
}
void bn40::print(){
this->shrink();
string* s = this->tohex();
cout<<"^^"<< *s <<"$$"<<endl;
delete s;
}
|
Java
|
UTF-8
| 3,327 | 2.09375 | 2 |
[] |
no_license
|
package com.bec.merchantmanager.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bec.merchantmanager.R;
import com.bec.merchantmanager.Utils.AppUtils;
import com.bec.merchantmanager.base.BECFragment;
import com.bec.merchantmanager.bean.TabMenus;
import butterknife.Bind;
/**
* Created by admin on 2017/10/10.
*/
public abstract class BECTabFragment extends BECFragment implements TabLayout.OnTabSelectedListener {
@Bind(R.id.tab_menu) TabLayout mTabMenu;
protected int mCurrentPosition = 0;
private View rootView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_bec_tab, container, false);
return rootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mTabMenu.setOnTabSelectedListener(this);
mTabMenu.setSelectedTabIndicatorColor(getIndicatorColor());
for (int i = 0; i < getTabMenu().length; i++) {
mTabMenu.addTab(mTabMenu.newTab().setCustomView(getTabView(i)));
}
if (mTabMenu.getTabCount() > 3){
mTabMenu.setTabMode(TabLayout.MODE_SCROLLABLE);
}else {
mTabMenu.setTabMode(TabLayout.MODE_FIXED);
}
setSelectedTab(mCurrentPosition);
getChildFragmentManager().beginTransaction().add(R.id.fl_content, getTabMenu()[mCurrentPosition].mFragment).commit();
}
protected void setSelectedTab(int position) {
mTabMenu.getTabAt(position).select();
switchFragment(position);
}
private void switchFragment(int position) {
if (position == mCurrentPosition) {
return;
}
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
Fragment to = getTabMenu()[position].mFragment;
Fragment from = getTabMenu()[mCurrentPosition].mFragment;
mCurrentPosition = position;
if (!to.isAdded()) { // 先判断是否被add过
transaction.hide(from).add(R.id.fl_content, to).commit(); // 隐藏当前的fragment,add下一个到Activity中
} else {
transaction.hide(from).show(to).commit(); // 隐藏当前的fragment,显示下一个
}
}
protected int getIndicatorColor() {
return getResources().getColor(R.color.becPrimaryBlue);
}
protected View getTabView(int position) {
return AppUtils.getCustomTextTabView(getActivity(), getTabMenu()[position].name);
}
@Override
protected boolean isBindEventBus() {
return false;
}
@Override
public void onTabSelected(TabLayout.Tab tab) {
setSelectedTab(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
protected abstract TabMenus[] getTabMenu();
}
|
Java
|
UTF-8
| 557 | 1.867188 | 2 |
[] |
no_license
|
package com.yumu.hexie.model.commonsupport.info;
import javax.persistence.Entity;
import com.yumu.hexie.model.BaseModel;
@Entity
public class ProductRule extends BaseModel {
/**
*
*/
private static final long serialVersionUID = -7072087262127364609L;
private long productId;
private long ruleId;
public long getProductId() {
return productId;
}
public void setProductId(long productId) {
this.productId = productId;
}
public long getRuleId() {
return ruleId;
}
public void setRuleId(long ruleId) {
this.ruleId = ruleId;
}
}
|
Java
|
UTF-8
| 386 | 3.046875 | 3 |
[] |
no_license
|
package academy.everyonecodes.java.week6.set2.exercise2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class IntegersLeftShifter {
public List<Integer> shiftOne(List<Integer> numbers) {
List<Integer> numbersMutable = new ArrayList<>(numbers);
Collections.rotate(numbersMutable, -1);
return numbersMutable;
}
}
|
Shell
|
UTF-8
| 2,471 | 4.28125 | 4 |
[] |
no_license
|
#!/bin/bash
# replaygain.sh - A wrapper for mp3gain
# Homepage: https://github.com/rucker/scripts
# Author: Rick Ucker
#
# Run this script to add mp3gain values to mp3 files in a directory
# and its subdirectories. Both album mode and track mode are supported.
#
# Dependencies:
# mp3gain (http://mp3gain.sourceforge.net/)
thisScript=$(basename $(readlink -nf $0))
usage="Usage: $thisScript directory [options]"
date=$(eval date +%Y%m%d)
workingDir=""
thisScriptDir="$(dirname $(readlink -f "$0"))/"
mp3LogFile=$thisScriptDir/logs/mp3gain-$date.tsv
flacLogFile=$thisScriptDir/logs/metaflac-$date.log
errLogFile=$thisScriptDir/logs/mp3gain-$date.err.log
mp3gainOpts="-T -k -o "
mp3NamePattern="*.mp3"
metaflacOpts="--add-replay-gain"
flacNamePattern="*.flac"
findOpts="-type d -print0"
while [[ $# > 0 ]]
do
arg="$1"
if [[ -d $arg ]]
then
workingDir="$(readlink -f $arg)"
else
mp3gainOpts=$mp3gainOpts$arg
fi
shift
done
show_usage() {
echo $usage
echo "Use -h or --help for full list of options."
}
show_full_options() {
echo $usage
echo "Options:"
echo "-a Album mode (mp3gain). Treat all files in a given directory as tracks from the same album and apply album gain to all of them."
echo "-r Track mode (mp3gain). Apply track leveling to each individual file."
echo $'\nEither -a or -r is required, but both cannot be used together.'
}
if [[ $mp3gainOpts =~ .*(-h|help).* ]]
then
show_full_options
exit 1
elif ! [[ $mp3gainOpts =~ .*(-a|-r).* ]]
then
show_usage
exit 1
elif [[ $mp3gainOpts =~ .*-a.* ]] && [[ $mp3gainOpts =~ .*-r.* ]]
then
show_usage
exit 1
fi
if [[ $workingDir == "" ]]
then
show_usage
exit 1
fi
process_dir() {
echo "Processing replaygain for mp3 files in "$@""
cd "$@"
if ls $mp3NamePattern 1> /dev/null 2>&1; then
mp3gain $mp3gainOpts $mp3NamePattern >> $mp3LogFile 2>> $errLogFile
elif ls $flacNamePattern 1> /dev/null 2>&1
then
metaflac $metaflacOpts $flacNamePattern >> $flacLogFile 2>> $errLogFile
metaflac --list $flacNamePattern | grep REPLAYGAIN>> $flacLogFile 2>> $errLogFile
else
echo "No matching files in this directory."
fi
}
if [[ $mp3gainOpts =~ .*-a.* ]]
then
echo "Using album mode for each subdirectory of $workingDir"
find $workingDir/* $findOpts | while read -d $'\0' -r dir
do
process_dir "$dir"
done
process_dir $workingDir
else
echo "Using track mode for all tracks in $workingDir"
process_dir "$workingDir"
fi
|
Java
|
UTF-8
| 629 | 2.3125 | 2 |
[] |
no_license
|
package Servlets;
import Controller.Agent;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetAgent extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String nic = request.getParameter("nic");
out.write(new Agent().getAgent(nic));
}
}
|
Markdown
|
UTF-8
| 926 | 2.75 | 3 |
[] |
no_license
|
# Async HTTP Sample
This is a sample project to check the potential integration of async HTTP client into an existing non reactive Spring Boot application.
We wanted to check whether an async HTTP client behaves in a production-like environment, having callbacks writing to a database.
It is actually as simple as with a sync HTTP client.
The workflow of this app is :
1. `MovieController.getById`
2. Checks whether we have a record of movie in `MovieRepository.findByImdbId`
3. If there is, return a `CompletableFuture.completedFuture` of the `movie`
4. If not, call `http://www.omdbapi.com/` asynchronously and let Spring handle the result using a registered `MovieHandler`
In the 4th point, we can see the interesting point is that while we are calling the HTTP actions, we can do some other computation, as the CPU is completely free.
You can test using :
```
curl 'http://localhost:8080/tt3896180' --compressed
```
|
Python
|
UTF-8
| 2,957 | 2.71875 | 3 |
[
"Apache-2.0"
] |
permissive
|
import erdos
import numpy as np
from pylot.prediction.messages import PredictionMessage
from pylot.prediction.obstacle_prediction import ObstaclePrediction
from pylot.utils import Location, Rotation, Transform
class LinearPredictorOperator(erdos.Operator):
"""Operator that takes in past (x,y) locations of agents, and fits a linear
model to these locations.
"""
def __init__(self,
tracking_stream,
linear_prediction_stream,
name,
flags,
log_file_name=None):
"""Initializes the LinearPredictor Operator."""
tracking_stream.add_callback(self.generate_predicted_trajectories,
[linear_prediction_stream])
self._logger = erdos.utils.setup_logging(name, log_file_name)
self._flags = flags
@staticmethod
def connect(tracking_stream):
linear_prediction_stream = erdos.WriteStream()
return [linear_prediction_stream]
def generate_predicted_trajectories(self, msg, linear_prediction_stream):
self._logger.debug('@{}: received trajectories message'.format(
msg.timestamp))
obstacle_predictions_list = []
for obstacle in msg.obstacle_trajectories:
# Time step matrices used in regression.
num_steps = min(self._flags.prediction_num_past_steps,
len(obstacle.trajectory))
ts = np.zeros((num_steps, 2))
future_ts = np.zeros((self._flags.prediction_num_future_steps, 2))
for t in range(num_steps):
ts[t][0] = -t
ts[t][1] = 1
for i in range(self._flags.prediction_num_future_steps):
future_ts[i][0] = i + 1
future_ts[i][1] = 1
xy = np.zeros((num_steps, 2))
for t in range(num_steps):
# t-th most recent step
transform = obstacle.trajectory[-(t + 1)]
xy[t][0] = transform.location.x
xy[t][1] = transform.location.y
linear_model_params = np.linalg.lstsq(ts, xy)[0]
# Predict future steps and convert to list of locations.
predict_array = np.matmul(future_ts, linear_model_params)
predictions = []
for t in range(self._flags.prediction_num_future_steps):
predictions.append(
Transform(location=Location(x=predict_array[t][0],
y=predict_array[t][1]),
rotation=Rotation()))
obstacle_predictions_list.append(
ObstaclePrediction(
obstacle.label,
obstacle.id,
1.0, # probability
predictions))
linear_prediction_stream.send(
PredictionMessage(msg.timestamp, obstacle_predictions_list))
|
TypeScript
|
UTF-8
| 512 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
import { Injectable, HttpService } from '@nestjs/common';
import { Weather } from './interfaces/weather.interface';
@Injectable()
export class WeatherService {
constructor(private httpService: HttpService) {}
async getWeather(): Promise<Weather> {
const weather = await this.httpService.get('https://api.openweathermap.org/data/2.5/onecall' +
'?lat=47.222531&lon=39.718705&exclude=minutely,hourly&appid=da58e8be9d2780499a34927e283b3378&units=metric').toPromise();
return weather.data;
}
}
|
Python
|
UTF-8
| 224 | 2.8125 | 3 |
[] |
no_license
|
import pygame
import settings
class Camera:
def __init__(self):
# This is the viewing Area, also known as the Screen Size
self.camera = pygame.Rect(0, 0, settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT)
|
Python
|
UTF-8
| 265 | 3.5 | 4 |
[] |
no_license
|
"""
project euler 1
by: Nir
Multiples of 3 and 5
"""
def sum_and_div_35(to=int(input("add ur num"))):
result = 0
for i in range(1, to):
if i % 3 == 0 or i % 5 == 0:
result += i
return result
print(sum_and_div_35())
|
Java
|
UTF-8
| 767 | 2.859375 | 3 |
[] |
no_license
|
package ru.netology;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
private static final String HOST = "localhost";
private static final int PORT = Server.SERVER_PORT;
public static void main(String[] args) throws IOException {
try (Socket clientSocket = new Socket(HOST, PORT);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
out.println("Username");
String resp = in.readLine();
System.out.println(resp);
}
}
}
|
C++
|
UTF-8
| 730 | 2.5625 | 3 |
[] |
no_license
|
#ifdef __APPLE__
#include <OpenCL/cl.hpp>
#else
#include <CL/cl.hpp>
#endif
#include "cl_tools.hpp"
#include <iostream>
#include <tuple>
int main()
{
// To execute the program, we need context and device.
auto [program, context, device] = program_builder("../kernels/helloworld.cl");
char buff[16];
cl::Buffer mem_buff(context, CL_MEM_WRITE_ONLY | CL_MEM_HOST_READ_ONLY, sizeof(buff));
cl::Kernel kernel(program, "HelloWorld");
kernel.setArg(0, mem_buff); // A kernel is from a function(program). And it needs memory(mem_buff).
cl::CommandQueue queue(context, device);
queue.enqueueTask(kernel);
queue.enqueueReadBuffer(mem_buff, CL_TRUE, 0, sizeof(buff), buff);
std::cout << buff;
}
|
JavaScript
|
UTF-8
| 7,350 | 2.921875 | 3 |
[] |
no_license
|
var y=document.getElementById('text-content');
function ahah(url, target) {
document.getElementById(target).innerHTML = ' Fetching data...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url, target) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
} else {
document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
function load(name, div) {
ahah(name,div);
return false;
}
var bisiesto=0;
var l_anho=0;
var l_mes=0;
function llenarMes(){
var htmlMes="<option>- Mes -</option>";
for(var i=1;i<=12;i++){
htmlMes+="<option value="+i+">"+numMes(i)+"</option>";
}
document.getElementById("mes").innerHTML = htmlMes;
}
function numMes(i){
switch (i){
case 1: return "Enero"; break;
case 2: return "Febrero"; break;
case 3: return "Marzo"; break;
case 4: return "Abril"; break;
case 5: return "Mayo"; break;
case 6: return "Junio"; break;
case 7: return "Julio"; break;
case 8: return "Agosto"; break;
case 9: return "Septiembre"; break;
case 10: return "Octubre"; break;
case 11: return "Noviembre"; break;
default: return "Diciembre"; break;
}
}
function ajustarFeb(anho){
l_anho=anho;
if (anho % 4 != 0) {
bisiesto=0;
} else if (anho % 400 == 0) {
bisiesto=1;
} else if (anho % 100 == 0) {
bisiesto=0;
} else {
bisiesto=1;
}
}
function llenarDias(mes){
l_mes=mes;
ajustarFeb(l_anho);
var i=1;
var top=0;
var dias_txt="<option> - Día - </option>";
if ((mes==1)||(mes==3)||(mes==5)||(mes==7)||(mes==8)||(mes==10)||(mes==12)){
top=31;
}else if((mes==2)&&(bisiesto==1)){
top=29;
}else if((mes==2)&&(bisiesto==0)){
top=28;
}else{
top=30;
}
for(i=1;i<=top;i++){
dias_txt+="<option>"+i+"</option>";
}
document.getElementById("dia").innerHTML = dias_txt;
}
function llenarAnhos(){
var i = 0;
var fecha = new Date();
anhos_txt="<option> - Año - </option>";
for(i=fecha.getFullYear();i>fecha.getFullYear()-5;i--){
anhos_txt+="<option value=\""+i+"\">"+i+"</option>";
}
document.getElementById("ano").innerHTML = anhos_txt;
}
function validateForm(){
var ret = true
var x;
x=document.forms.agregarCliente.nombre;
if (x.value==null || x.value==""){
x.style.backgroundColor="#FFFF99";
document.getElementById("lnombre").className="invalid";
ret = false;
} else{
x.style.backgroundColor="#FFFFFF";
document.getElementById("lnombre").className="valid";
}
x=document.forms.agregarCliente.apellido;
if (x.value==null || x.value==""){
x.style.backgroundColor="#FFFF99";
document.getElementById("lapellido").className="invalid";
ret = false;
} else{
x.style.backgroundColor="#FFFFFF";
document.getElementById("lapellido").className="valid";
}
x=document.forms.agregarCliente.dia;
if (x.value =="escoger"){
document.getElementById("lfechaNacimiento").className="invalid";
ret = false;
}else{
x.style.backgroundColor="#FFFFFF";
document.getElementById("lfechaNacimiento").className="valid";
}
x=document.forms.agregarCliente.correo;
if (x.value==null|| x.value==""){
x.style.backgroundColor="#FFFF99";
document.getElementById("lcorreo").className="invalid";
ret = false;
}else{
x.style.backgroundColor="#FFFFFF";
document.getElementById("lcorreo").className="valid";
}
x=document.forms.agregarCliente.direccion;
if (x.value==null || x.value==""){
x.style.backgroundColor="#FFFF99";
document.getElementById("ldireccion").className="invalid";
ret = false;
}else{
x.style.backgroundColor="#FFFFFF";
document.getElementById("ldireccion").className="valid";
}
x=document.forms.agregarCliente.colonia;
if (x.value==null || x.value==""){
x.style.backgroundColor="#FFFF99";
document.getElementById("lcolonia").className="invalid";
ret = false;
}else{
x.style.backgroundColor="#FFFFFF";
document.getElementById("lcolonia").className="valid";
}
x=document.forms.agregarCliente.cp;
if (x.value==null || x.value==""){
x.style.backgroundColor="#FFFF99";
document.getElementById("lcp").className="invalid";
ret = false;
}
else
if (isNaN(parseInt(x.value))){
x.style.backgroundColor="#FFFF99";
document.getElementById("lcp").className="invalid";
document.getElementById("scp").innerHTML="Introducir números";
ret = false;
}else{
x.style.backgroundColor="#FFFFFF";
document.getElementById("lcp").className="valid";
document.getElementById("scp").innerHTML="";
}
x=document.forms.agregarCliente.ciudad;
if (x.value==null || x.value==""){
x.style.backgroundColor="#FFFF99";
document.getElementById("lciudad").className="invalid";
ret = false;
}else{
x.style.backgroundColor="#FFFFFF";
document.getElementById("lciudad").className="valid";
}
x=document.forms.agregarCliente.estado;
if (x.value =="escoger"){
document.getElementById("lestado").className="invalid";
ret = false;
}else{
document.getElementById("lestado").className="valid";
}
x=document.forms.agregarCliente.telefono;
if (x.value==null || x.value==""){
x.style.backgroundColor="#FFFF99";
document.getElementById("ltelefono").className="invalid";
ret = false;
}
else
if (isNaN(parseInt(x.value))){
x.style.backgroundColor="#FFFF99";
document.getElementById("ltelefono").className="invalid";
document.getElementById("stelefono").innerHTML="Introducir números";
ret = false;
}
else
if (x.value<9999999){
x.style.backgroundColor="#FFFF99";
document.getElementById("ltelefono").className="invalid";
document.getElementById("stelefono").innerHTML="Mínimo 8 digitos";
ret = false;
}else{
x.style.backgroundColor="#FFFFFF";
document.getElementById("ltelefono").className="valid";
document.getElementById("stelefono").innerHTML="";
}
return ret;
}
|
Java
|
UTF-8
| 934 | 2.921875 | 3 |
[] |
no_license
|
package com.hyxy.viary;
public class DiaryItem {
private int year;//年份
private int month;//月份
private int day;//日期
private String diaryContent;//日记内容
public DiaryItem(int year, int month, int day, String content){
this.year=year;
this.month=month;
this.day=day;
this.diaryContent=content;
}
public int getYear(){
return this.year;
}
public void setYear(int year){
this.year = year;
}
public int getMonth(){
return this.month;
}
public void setMonth(int month){
this.month = month;
}
public int getDay(){
return this.day;
}
public void setDay(int day){
this.day = day;
}
public String getDiaryContent(){
return this.diaryContent;
}
public void setDiaryContent(String diaryContent){
this.diaryContent = diaryContent;
}
}
|
C
|
UTF-8
| 1,227 | 3.765625 | 4 |
[] |
no_license
|
/*
CH-230-A
a7p4.c
Erlisa Kulla
e.kulla@jacobs-university.de
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
//capitalizing all letters
char* upper(char* str) {
int i;
for (i = 0; str[i]; i++)
str[i] = toupper(str[i]);
return str;
}
//converting to lower case
char* lower(char* str) {
int i;
for (i = 0; str[i]; i++)
str[i] = tolower(str[i]);
return str;
}
//revering the cases
char* reverse(char* str) {
int i;
for (i = 0; str[i]; i++) {
if(islower(str[i]))
str[i] = toupper(str[i]);
else if(isupper(str[i]))
str[i] = tolower(str[i]);
}
return str;
}
//quitting the program
char* quit() {
exit(0);
}
//creating array of function pointers
char* (*Case[4])(char* myStr) = {upper, lower, reverse, quit};
int main() {
char str[150], arr[150], copyStr[150];
int n;
fgets(str, sizeof(str), stdin);
strcpy(copyStr, str);
//looping for user input
while(1) {
fgets(arr, sizeof(arr), stdin);//command numbers
sscanf(arr, "%d", &n);
strcpy(copyStr, str);
printf("%s", (*Case[n - 1])(copyStr));
}
return 0;
}
|
Python
|
UTF-8
| 2,135 | 2.796875 | 3 |
[] |
no_license
|
import numpy as np
from sklearn.base import ClassifierMixin, BaseEstimator
from keras.layers import Dense, Input, Add, Concatenate
from keras.models import Model
from keras.optimizers import Adam
from keras.wrappers.scikit_learn import KerasClassifier
from constants import *
class BaselineClassifierTitanic(BaseEstimator, ClassifierMixin):
def __init__(self, column_to_use_as_predictor=SEX_MALE):
self.column_to_use_as_predictor = column_to_use_as_predictor
def fit(self, X, y):
return self
def predict(self, X):
return 1 - X[self.column_to_use_as_predictor]
class TitanicNNClassifier(BaseEstimator, ClassifierMixin):
@staticmethod
def _create_model(input_len):
k_in = Input(shape=(input_len, ))
dense_1_1 = Dense(units=input_len)(k_in)
add_1_1 = Add()([k_in, dense_1_1])
dense_2_1 = Dense(units=input_len)(add_1_1)
add_2_1 = Add()([dense_1_1, dense_2_1])
dense_3_1 = Dense(units=5)(add_2_1)
dense_1_2 = Dense(units=input_len)(k_in)
add_1_2 = Add()([k_in, dense_1_2])
dense_2_2 = Dense(units=input_len)(add_1_2)
add_2_2 = Add()([dense_1_2, dense_2_2])
dense_3_2 = Dense(units=5)(add_2_2)
concat_4 = Add()([dense_3_1, dense_3_2])
dense_4 = Dense(5)(concat_4)
dense_5 = Dense(1, activation="sigmoid")(dense_4)
model = Model(inputs=k_in, outputs=dense_5)
return model
def __init__(self):
self.input_len = None
self.optimizer = None
self.loss = None
def compile(self, optimizer=Adam(), loss="mse"):
self.optimizer = optimizer
self.loss = loss
self.model.compile(optimizer=optimizer, loss=loss)
def fit(self, X, y, batch_size=None, epochs=10, verbose=0, **kwargs):
self.input_len = np.shape(X)[1]
self.model = self._create_model(self.input_len)
self.compile()
self.model.fit(X, y, batch_size=batch_size, epochs=epochs, verbose=verbose, **kwargs)
def predict(self, X):
predictions = self.model.predict(X)
return predictions > 0.5
|
Python
|
UTF-8
| 2,011 | 3.53125 | 4 |
[] |
no_license
|
# 세그먼트 트리
# https://upcount.tistory.com/12
import sys
# 세그먼트 트리 생성
def init(node, start ,end):
# node가 leaf node인 경우 배열의 원소 값 반환.
if start == end:
tree[node] = arr[start]
return tree[node]
# 재귀 함수를 이용하여 왼쪽/오른쪽 자식 트리를 만들고 합을 저장.
else:
mid = (start + end) // 2
tree[node] = init(node * 2, start, mid) + init(node * 2 + 1, mid + 1, end)
return tree[node]
# 구간합 구하기
# node가 담당하는 구간 [start, end]
# 합을 구해야하는 구간 [left, right]
def subNum(node, start, end, left, right):
if end < left or right < start:
return 0
# 구해야 하는 합의 범위는 [left, right] 인데, [start, end]는 그 범위에 모두 포함되고
# node 자식도 모두 포함되기 때문에 더 이상의 연산 호출은 비효율적임.
if left <= start and end <= right:
return tree[node]
# 왼쪽 자식과 오른쪽 자식을 루트로 하는 트리에서 다시 탐색을 시작해야 한다.
mid = (start + end) // 2
return subNum(node*2, start ,mid, left, right) + subNum(node*2 + 1, mid+1, end, left, right)
def update(node, start, end, index, diff):
if index < start or end < index:
return
tree[node] += diff
# 리프노드가 아닌 경우 자식 노드도 값을 변경해야 함.
if start != end:
mid = (start + end) // 2
update(node * 2, start, mid, index, diff)
update(node * 2 + 1, mid + 1, end, index, diff)
n, m, k = map(int, sys.stdin.readline().rstrip().split())
arr = [int(sys.stdin.readline().rstrip()) for _ in range(n)]
tree = [0] * 4000000
init(1, 0, n-1)
for _ in range(m+k):
a, b, c = map(int, sys.stdin.readline().rstrip().split())
if a == 1:
b = b-1
diff = c - arr[b]
arr[b] = c
update(1, 0, n-1, b, diff)
else:
print(subNum(1, 0, n-1, b-1, c-1))
|
C#
|
UTF-8
| 1,320 | 3.359375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SmartPacMan
{
/// <summary>
/// Main charatcer class in game. Controlled by user.
/// </summary>
public class Pacman : Character
{
public Pacman()
{
state = PacmanState.Closed;
lastMove = Pathfinder.Direction.Right;
}
/*********************************************************************/
/* Class Types */
/*********************************************************************/
/// <summary>
/// Pacman's current state. Basically varies between open and closed mouth.
/// </summary>
public enum PacmanState
{
Open,
Closed
};
/*********************************************************************/
/* Class Variables */
/*********************************************************************/
public PacmanState state { get; set; }
/*********************************************************************/
/* Class Methods */
/*********************************************************************/
/// <summary>
/// Inverts Pacman's current state.
/// </summary>
public void switchState()
{
if (state == PacmanState.Open)
state = PacmanState.Closed;
else
state = PacmanState.Open;
}
}
}
|
Java
|
UTF-8
| 100,794 | 1.5625 | 2 |
[] |
no_license
|
// $Id: RGroupTool.java 3864 2009-12-18 22:09:45Z nguyenda $
package gov.nih.ncgc.rgroup;
import chemaxon.formats.MolImporter;
import chemaxon.marvin.beans.MViewPane;
import chemaxon.struc.MolAtom;
import chemaxon.struc.Molecule;
import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
import com.jidesoft.swing.CheckBoxList;
import com.jidesoft.swing.JideTabbedPane;
import gov.nih.ncgc.descriptor.TopologicalIndices;
import gov.nih.ncgc.model.DataSeq;
import gov.nih.ncgc.search.SearchParams;
import gov.nih.ncgc.util.MolFpFactory;
import gov.nih.ncgc.util.MolStandardizer;
import gov.nih.ncgc.util.DummySSLSocketFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;
import org.jdesktop.swingworker.SwingWorker;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.DefaultXYDataset;
import javax.imageio.ImageIO;
import javax.jnlp.FileContents;
import javax.jnlp.FileOpenService;
import javax.jnlp.FileSaveService;
import javax.jnlp.ServiceManager;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.plaf.UIResource;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.net.*;
import javax.net.ssl.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class RGroupTool extends JFrame
implements PropertyChangeListener,
ListSelectionListener,
ActionListener {
static final Logger logger = Logger.getLogger(RGroupTool.class.getName());
static final Border EMPTY = BorderFactory.createEmptyBorder(1,1,1,1);
static boolean UnsignedWebstart = false;
static final ImageIcon BACK_ICON =
new ImageIcon (RGroupTool.class.getResource
("/resources/arrow-180-medium.png"));
static final ImageIcon FORWARD_ICON =
new ImageIcon (RGroupTool.class.getResource
("/resources/arrow-000-medium.png"));
static final ImageIcon OPEN_ICON =
new ImageIcon (RGroupTool.class.getResource
("/resources/folder-open.png"));
static final ImageIcon COMPOUND_ICON =
new ImageIcon (RGroupTool.class.getResource
("/resources/pccompound_small.png"));
static final Icon PLUS_ICON = new ImageIcon
(RGroupTool.class.getResource("/resources/icons/add_obj.gif"));
/**
* content tab
*/
static final int REFERENCE_TAB = 0;
static final int COMPOUND_TAB = 1;
static final int RGROUP_TAB = 2;
static final int PUBCHEM_TAB = 3;
/**
* navigation tab
*/
static final int SCAFFOLD_TAB = 0;
static final int NETWORK_TAB = 1;
static final int SINGLETON_TAB = 2;
JFileChooser chooser;
JTable scaffoldTab;
JTable instanceTab;
JLabel scaffoldLabel;
JTable rgroupTab;
JTable singletonTab;
JTabbedPane contentTab;
JProgressBar progress;
MViewPane mview;
JTextField statusField;
JPopupMenu popup;
JButton extBtn;
RGroupNetwork network;
RGroupDocsPane docsPane;
RGroupPubChemPane pubchemPane;
JideTabbedPane navtab;
JButton navBackBtn, navForwardBtn;
JTextField searchField;
StructureSearchDialog _strucSearchDialog;
CheckBoxList propCheckBoxList;
JDialog propDialog;
Map<String, Class> props = new TreeMap<String, Class>();
String activityDataFileName = null;
RGroupWebResources webservice;
/**
* history stack
*/
LinkedList<RGroupGenerator> history = new LinkedList<RGroupGenerator>();
LinkedList<RGroupGenerator> forward = new LinkedList<RGroupGenerator>();
//there's got to be a better way to do this.
Map<Integer,Integer> columnPreviousWidth = new HashMap<Integer,Integer>();
class TabControl extends JPanel implements UIResource, ActionListener {
JButton addBtn;
TabControl () {
//setOpaque (true);
setLayout (new GridLayout (1, 1));
addBtn = new JButton (PLUS_ICON);
addBtn.setMargin(new Insets (0, 0, 0, 0));
addBtn.setRolloverEnabled(true);
addBtn.setFocusPainted(false);
addBtn.setBorderPainted(false);
addBtn.setToolTipText("Search for scaffolds in new dataset");
addBtn.addActionListener(this);
addBtn.setBackground(getBackground());
add (addBtn);
}
public void actionPerformed (ActionEvent e) {
RGroupGenerator rgroup = getRGroup ();
if (rgroup == null || rgroup.getScaffoldCount() == 0) {
JOptionPane.showMessageDialog
(RGroupTool.this, "No reference scaffold(s) have "
+"been generated.", "Error",JOptionPane.ERROR_MESSAGE);
return;
}
if (UnsignedWebstart) {
try {
FileOpenService fos =
(FileOpenService)ServiceManager.lookup
("javax.jnlp.FileOpenService");
FileContents contents = fos.openFileDialog
(".", new String[]{"sdf","mol","smi","smiles",
"cml","sd"});
if (!contents.canRead()) {
throw new Exception ("Can't open file");
}
new SearchRGroup (rgroup.getRGroupTables(),
contents).execute();
}
catch (Exception ex) {
JOptionPane.showMessageDialog
(RGroupTool.this, "Your Java Webstart doesn't have "
+"proper permission to open files.",
"Fatal Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
chooser.setDialogTitle("Please select input file");
if (JFileChooser.APPROVE_OPTION ==
chooser.showOpenDialog(RGroupTool.this)) {
File file = chooser.getSelectedFile();
new SearchRGroup (rgroup.getRGroupTables(),
file).execute();
}
}
}
}
class ExtendScaffold extends SwingWorker<RGroupTable, String> {
RGroupTable tab;
ExtendScaffold (RGroupTable tab) {
this.tab = tab;
}
@Override
protected RGroupTable doInBackground () {
publish ("Extending scaffold... ");
return getRGroup().extendScaffold(tab);
}
@Override
protected void process (String... mesg) {
for (String m : mesg) {
statusField.setText(m);
}
}
@Override
protected void done () {
try {
RGroupTable tab = get ();
if (tab != null) {
updateProperties ();
((AbstractTableModel)scaffoldTab.getModel())
.fireTableDataChanged();
for (int i = 1; i < contentTab.getTabCount(); ++i) {
SearchRGroup srg = (SearchRGroup)
((JComponent)contentTab.getComponentAt(i))
.getClientProperty("rgroup.search");
srg.addScaffold(tab);
}
JOptionPane.showMessageDialog
(RGroupTool.this, "New scaffold added!", "Message",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog
(RGroupTool.this,
"Unable to extend this scaffold any further!",
"Message", JOptionPane.INFORMATION_MESSAGE);
}
statusField.setText(null);
}
catch (Exception ex) {
JOptionPane.showMessageDialog
(RGroupTool.this, ex, "Exception",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
}
class RGroupWorker extends SwingWorker<Throwable, String> {
Object[] argv;
RGroupWorker (String... argv) {
this.argv = new Object[argv.length];
for (int i = 0; i < argv.length; ++i) {
this.argv[i] = argv[i];
}
}
RGroupWorker (File... files) {
this.argv = new Object[files.length];
for (int i = 0; i < files.length; ++i) {
argv[i] = files[i].getPath();
}
}
RGroupWorker (URL... urls) {
this.argv = new Object[urls.length];
for (int i = 0; i < urls.length; ++i) {
argv[i] = urls[i];
}
}
RGroupWorker (FileContents... files) {
this.argv = new Object[files.length];
for (int i = 0; i < files.length; ++i) {
argv[i] = files[i];
}
}
void checkProps (Molecule mol) {
for (int i = 0; i < mol.getPropertyCount(); ++i){
String key = mol.getPropertyKey(i);
if (key == null) {
continue;
}
Object val = mol.getPropertyObject(key);
Class clazz = props.get(key);
if (clazz == null) {
try {
double x = Double.parseDouble(val.toString());
if (Math.rint(x) == x) {
props.put(key, Long.class);
}
else {
props.put(key, Double.class);
}
}
catch (NumberFormatException ex) {
props.put(key, String.class);
}
}
else if (clazz == Double.class) {
try {
Double.parseDouble(val.toString());
}
catch (NumberFormatException ex) {
props.put(key, String.class);
}
}
else if (clazz == Long.class) {
try {
double x = Double.parseDouble(val.toString());
if (Math.rint(x) != x) {
props.put(key, Double.class);
}
}
catch (NumberFormatException ex) {
props.put(key, String.class);
}
}
else if (clazz == String.class) {
}
}
}
InputStream getInputStream (Object input) throws Exception {
if (input instanceof FileContents) {
return ((FileContents)input).getInputStream();
}
else if (input instanceof File) {
return new FileInputStream ((File)input);
}
else if (input instanceof URL) {
URL url = (URL)input;
URLConnection con = url.openConnection();
if ("https".equals(url.getProtocol())) {
((HttpsURLConnection)con)
.setSSLSocketFactory(new DummySSLSocketFactory ());
}
return con.getInputStream();
}
else { // assume String
return new FileInputStream ((String)input);
}
}
@Override
protected Throwable doInBackground () {
//props.clear();
((DefaultListModel)propCheckBoxList.getModel()).clear();
try {
publish ("Searching for scaffolds...");
progress.setIndeterminate(true);
int cnt = 0;
for (Object file : argv) {
MolImporter mi = new MolImporter (getInputStream (file));
//mi.setGrabbingEnabled(true);
Molecule last = null;
try {
for (Molecule mol; (mol = mi.read()) != null; ) {
publish ("Searching for scaffolds..."
+String.format("%1$5d %2$s",
++cnt, mol.getName()));
getRGroup().add(mol);
last = mol;
checkProps (mol);
}
mi.close();
getRGroup().setName(getName (file));
}
catch (Exception ex) {
logger.log(Level.WARNING,
"Can't parse molecule: "
+mi.getGrabbedMoleculeString(), ex);
}
}
/*
publish (rgroup.getFragmentCount()
+ " possible scaffold(s) generated...");
*/
SwingUtilities.invokeLater(new Runnable () {
public void run () {
progress.setIndeterminate(false);
}
});
getRGroup().run();
publish ("Done!");
}
catch (Exception ex) {
return ex;
}
return null;
}
@Override
protected void process (String... mesg) {
for (String m : mesg) {
statusField.setText(m);
}
}
String getName (Object input) throws IOException {
if (input instanceof FileContents) {
return ((FileContents)input).getName();
}
else if (input instanceof File) {
return ((File)input).getName();
}
else if (input instanceof URL) {
return ((URL)input).getFile();
}
return input.toString();
}
@Override
protected void done() {
try {
Throwable t = get();
if (t != null) {
JOptionPane.showMessageDialog
(RGroupTool.this, t.getMessage(),
"Fatal Exception", JOptionPane.ERROR_MESSAGE);
t.printStackTrace();
statusField.setText(t.getMessage());
return;
}
for (Map.Entry<String, Class> e : props.entrySet()) {
System.out.println
(e.getKey() + " => " + e.getValue());
((DefaultListModel)propCheckBoxList
.getModel()).addElement(e.getKey());
}
propCheckBoxList.selectAll();
statusField.setText(null);
contentTab.setTitleAt(RGROUP_TAB, "R-group");
updateRGroup ();
progress.setValue(0);
progress.setString(null);
progress.setStringPainted(false);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
class SearchRGroup extends SwingWorker<Throwable, String>
implements DataSeq<Molecule> {
RGroupTable[] rgroups;
Object file;
Vector<Molecule> molseq = new Vector<Molecule>();
Map<RGroupTable, RGroupTable> rgmap =
new HashMap<RGroupTable, RGroupTable>();
DefaultTableModel singletons = new DefaultTableModel
(new Object[]{"ID", "Structure"}, 0) {
public Class getColumnClass (int col) {
if (col == 0) return String.class;
return Molecule.class;
}
};
SearchRGroup (RGroupTable[] rgroups, Object file) {
this.rgroups = rgroups;
this.file = file;
}
/**
* DataSeq interface
*/
public int size () { return molseq.size(); }
public Molecule get (int index) { return molseq.get(index); }
public Object getFile () { return file; }
public RGroupTable getRGroupTable (RGroupTable scaffold) {
return rgmap.get(scaffold);
}
public TableModel getSingletons () { return singletons; }
public String getName () {
if (UnsignedWebstart) {
try {
return ((FileContents)file).getName() ;
}
catch (IOException ex) {
ex.printStackTrace();
}
}
else {
return ((File)file).getName();
}
return null;
}
public RGroupTable addScaffold (RGroupTable scaffold) throws Exception {
RGroupTable rg = RGroupSolver.solve
(scaffold.getScaffold().cloneMolecule(), this, null);
if (rg != null) {
rgmap.put(scaffold, rg);
}
logger.info(getName ()+": scaffold "
+ scaffold.getScaffold().toFormat("cxsmarts:q")
+ "..."
+ (rg != null ? rg.getRowCount() : 0));
return rg;
}
@Override
protected Throwable doInBackground () {
try {
progress.setIndeterminate(true);
publish ("Generating r-groups for "+getName()+"...");
MolImporter mi = new MolImporter
(UnsignedWebstart ? ((FileContents)file).getInputStream()
: new FileInputStream ((File)file));
Molecule last = null;
try {
MolStandardizer molstd = new MolStandardizer ();
Set<Molecule> singles = new HashSet<Molecule>();
for (Molecule mol; (mol = mi.read()) != null; ) {
try {
molstd.standardize(mol);
publish ("Generating r-groups for "
+ getName ()+"..."+mol.getName());
}
catch (Exception ex) {
logger.log(Level.WARNING,
"Can't standardize "+mol.getName(),
ex);
}
molseq.add(mol);
singles.add(mol);
last = mol;
}
mi.close();
for (int i = 0; i < rgroups.length; ++i) {
RGroupTable rg = addScaffold (rgroups[i]);
if (rg != null) {
for (int j = 0; j < rg.rows.length; ++j) {
singles.remove(molseq.get(rg.rows[j]));
}
}
publish (getName()
+": searching for scaffold " +(i+1) +"..."
+ (rg != null ? rg.getRowCount():0));
}
for (Molecule mol : singles) {
singletons.addRow(new Object[]{mol.getName(), mol});
}
}
catch (Exception ex) {
logger.log(Level.WARNING,
"Can't parse molecule; last molecule "
+"parsed is "
+ (last != null
?last.getName() :"null"), ex);
}
}
catch (Exception ex) {
return ex;
}
return null;
}
@Override
protected void process (String... mesg) {
for (String m : mesg) {
statusField.setText(m);
}
}
@Override
protected void done() {
try {
Throwable t = get();
if (t != null) {
JOptionPane.showMessageDialog
(RGroupTool.this, t.getMessage(),
"Fatal Exception", JOptionPane.ERROR_MESSAGE);
t.printStackTrace();
statusField.setText(t.getMessage());
}
else {
statusField.setText(null);
EventQueue.invokeLater(new Runnable () {
public void run () {
addSearchRGroup (SearchRGroup.this);
}
});
}
progress.setIndeterminate(false);
progress.setValue(0);
progress.setString(null);
progress.setStringPainted(false);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
class AddScaffold extends SwingWorker<RGroupTable, String> {
Molecule scaffold;
AddScaffold (Molecule scaffold) {
this.scaffold = scaffold;
}
@Override
protected RGroupTable doInBackground () {
// don't prune
RGroupTable rtab = getRGroup().generate(scaffold, false);
if (rtab != null) {
updateProperties ();
// generate new scaffold for the rest of the dataset
for (int i = 1; i < contentTab.getTabCount(); ++i) {
SearchRGroup srg = (SearchRGroup)
((JComponent)contentTab.getComponentAt(i))
.getClientProperty("rgroup.search");
if (srg != null) {
try {
srg.addScaffold(rtab);
} catch (Exception e) {
}
}
}
}
return rtab;
}
@Override
protected void process (String... mesg) {
for (String m : mesg) {
statusField.setText(m);
}
}
@Override
protected void done () {
try {
RGroupTable tab = get ();
if (tab != null) {
((AbstractTableModel)scaffoldTab.getModel())
.fireTableDataChanged();
JOptionPane.showMessageDialog
(RGroupTool.this, "New scaffold added!", "Message",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog
(RGroupTool.this,
"No scaffold added because scaffold either\n"
+"already exists or is redundant!",
"Message", JOptionPane.INFORMATION_MESSAGE);
}
statusField.setText(null);
}
catch (Exception ex) {
JOptionPane.showMessageDialog
(RGroupTool.this, ex, "Exception",
JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
}
class CRCCellRenderer implements TableCellRenderer {
ChartPanel chart;
XYPlot xyplot;
JPanel empty;
java.awt.Shape shape;
public CRCCellRenderer () {
chart = new ChartPanel
(ChartFactory.createScatterPlot
(null, null, null, null, PlotOrientation.HORIZONTAL,
false, false, false));
chart.getChart().setBackgroundPaint(null);
chart.setOpaque(false);
chart.setBackground (new Color (0, 0, 0, 0));
chart.setDoubleBuffered(false);
//chart.getChart().setBorderPaint(Color.white);
chart.getChart().getPlot().setBackgroundAlpha(.0f);
xyplot = chart.getChart().getXYPlot();
xyplot.setRangeGridlinesVisible(false);
xyplot.setOutlineVisible(false);
//xyplot.setDomainCrosshairVisible(false);
xyplot.setDomainGridlinesVisible(false);
xyplot.setRangeZeroBaselineVisible(false);
xyplot.setDomainZeroBaselineVisible(false);
XYItemRenderer renderer = new XYLineAndShapeRenderer ();
/*
for (int i = 0; i < CURVE_COLOR.length; ++i) {
renderer.setSeriesPaint(i, CURVE_COLOR[i]);
}
*/
xyplot.setRenderer(renderer);
shape = new java.awt.geom.Ellipse2D.Double(0., 0., 4., 4.);
empty = new JPanel ();
empty.setBackground(Color.white);
}
public Component getTableCellRendererComponent
(JTable table, Object value, boolean selected, boolean focus,
int row, int col) {
if (value == null) {
empty.setBackground(selected ? table.getSelectionBackground()
: table.getBackground());
return empty;
}
/*
chart.getChart().setBackgroundPaint
(selected ? table.getSelectionBackground()
: table.getBackground());
*/
RGroupTable.CRC[] crc = (RGroupTable.CRC[])value;
//xyplot.getDomainAxis().setVisible(table.getRowHeight() >= 100);
int width = table.getColumnModel().getColumn(col)
.getPreferredWidth();
//xyplot.getRangeAxis().setVisible(width >= 100);
DefaultXYDataset dataset = new DefaultXYDataset();
XYLineAndShapeRenderer renderer =
(XYLineAndShapeRenderer)xyplot.getRenderer();
for (int i = 0; i < crc.length; ++i) {
double[][] xy = crc[i].xy();
int series = dataset.getSeriesCount();
renderer.setSeriesShapesVisible(series, true);
renderer.setSeriesLinesVisible(series, false);
renderer.setSeriesShape(series, shape);
double[][] yx = new double[2][];
yx[0] = xy[1];
yx[1] = xy[0];
dataset.addSeries("raw-"+i, yx);
series = dataset.getSeriesCount();
renderer.setSeriesShapesVisible(series, false);
renderer.setSeriesLinesVisible(series, true);
xy = crc[i].hillfit();
if (xy != null) {
yx = new double[2][];
yx[0] = xy[1];
yx[1] = xy[0];
dataset.addSeries("fit-"+i, yx);
}
xyplot.setDataset(dataset);
}
return chart;
}
}
class InstanceTableModel extends AbstractTableModel {
Map<String, Class> types = new HashMap<String, Class>();
ArrayList<String> columns = new ArrayList<String>();
RGroupGenerator rgen;
InstanceTableModel () {
}
InstanceTableModel (RGroupGenerator rgen, Map<String, Class> types) {
setProperties (types);
setRGroupGenerator (rgen);
}
public void setRGroupGenerator (RGroupGenerator rgen) {
this.rgen = rgen;
fireTableDataChanged ();
}
public void setProperties (Map<String, Class> types) {
columns.clear();
this.types.clear();
this.types.put("Molecule", Molecule.class);
columns.add("Molecule");
for (Map.Entry<String, Class> e : types.entrySet()) {
columns.add(e.getKey());
this.types.put(e.getKey(), e.getValue());
}
fireTableStructureChanged ();
}
public int getColumnCount () { return columns.size(); }
public int getRowCount () { return rgen != null ? rgen.size() : 0; }
public Class getColumnClass (int col) {
return types.get(columns.get(col));
}
public String getColumnName (int col) { return columns.get(col); }
public Object getValueAt (int row, int col) {
Molecule mol = rgen.get(row);
if (mol != null) {
if (col == 0) return mol;
String prop = columns.get(col);
Class cls = types.get(prop);
String value = mol.getProperty(prop);
if (value != null) {
if (cls == Long.class) {
return Float.parseFloat(value);
}
if (Double.class == cls) {
return Double.parseDouble(value);
}
return value;
}
}
return null;
}
public boolean isCellEditable (int r, int c) {
return getColumnClass (c) == Molecule.class;
}
public void setValueAt (int row, int col, Object value) {
if (col != 0 || value == null) return;
Molecule mol = rgen.get(row);
mol.clear();
((Molecule)value).clonecopy(mol);
}
}
class ScaffoldTableModel extends AbstractTableModel {
Map<String, Class> types = new HashMap<String, Class>();
ArrayList<String> columns = new ArrayList<String>();
Map<String, Map<RGroupTable, ScaffoldData>> values =
new TreeMap<String, Map<RGroupTable, ScaffoldData>>();
ArrayList<RGroupTable> rgs = new ArrayList<RGroupTable>();
public ScaffoldTableModel () {
types.put("Scaffold", Molecule.class);
columns.add("Scaffold");
types.put("Scaffold Score", Double.class);
columns.add("Scaffold Score");
types.put("Complexity", Integer.class);
columns.add("Complexity");
types.put("Count", Integer.class);
columns.add("Count");
}
public ScaffoldTableModel (Map<String, Class> types) {
this.types.put("Scaffold", Molecule.class);
columns.add("Scaffold");
this.types.put("Scaffold Score", Double.class);
columns.add("Scaffold Score");
this.types.put("Complexity", Integer.class);
columns.add("Complexity");
this.types.put("Count", Integer.class);
columns.add("Count");
addProperties (types);
}
public void addProperties (Map<String, Class> types) {
for (Map.Entry<String, Class> e : types.entrySet()) {
if (e.getValue() == Double.class) {
Class c = this.types.put(e.getKey(), ScaffoldData.class);
if (c == null) {
columns.add(e.getKey());
}
}
}
/*
for (String s : columns) {
System.out.println(s + " => " + this.types.get(s));
}
*/
fireTableStructureChanged ();
}
public void removeProperties (Collection<String> props) {
for (String s : props) {
Class c = types.remove(s);
if (c != null) {
columns.remove(s);
}
}
fireTableStructureChanged ();
}
public void setScaffolds (RGroupTable... scaffolds) {
rgs.clear();
if (scaffolds != null && scaffolds.length > 0) {
for (RGroupTable rg : scaffolds) {
rgs.add(rg);
}
}
fireTableDataChanged ();
}
public void update () {
fireTableDataChanged ();
}
public RGroupTable getScaffold (int r) {
return rgs.isEmpty() ? getRGroup().getRGroupTable(r) : rgs.get(r);
}
public boolean isCellEditable (int r, int c) {
return getColumnClass (c) == Molecule.class;
}
public Class getColumnClass (int c) {
return types.get(columns.get(c));
}
public String getColumnName (int c) { return columns.get(c); }
public int getColumnCount () { return columns.size(); }
public int getRowCount () {
return rgs.isEmpty()
? getRGroup().getScaffoldCount() : rgs.size();
}
public Object getValueAt (int row, int col) {
RGroupTable rtab = getScaffold (row);
if (col == 0) {
try {
return rtab.getScaffold();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
if (col == 1) {
return rtab.getScaffoldScore();
}
if (col == 2) {
return rtab.getScaffoldComplexity();
}
if (col == 3) {
return rtab.getRowCount();
}
String prop = columns.get(col);
Map<RGroupTable, ScaffoldData> rows = values.get(prop);
if (rows == null) {
rows = new HashMap<RGroupTable, ScaffoldData>();
values.put(prop, rows);
}
ScaffoldData data = rows.get(rtab);
if (data == null) {
rows.put(rtab, data = new ScaffoldData (prop, rtab));
}
return data;
}
}
public RGroupTool () {
this (null);
}
public RGroupTool (RGroupWebResources web) {
if (web == null) {
try {
URL url = new URL ("https://tripod.nih.gov/chembl/version");
HttpsURLConnection con =
(HttpsURLConnection)url.openConnection();
con.setSSLSocketFactory(new DummySSLSocketFactory ());
BufferedReader br = new BufferedReader
(new InputStreamReader (con.getInputStream()));
web = new RGroupWebResources
("https://tripod.nih.gov", br.readLine());
}
catch (Exception ex) {
ex.printStackTrace();
logger.warning("Can't retrieve chembl version; use default");
web = new RGroupWebResources
("https://tripod.nih.gov", "chembl-v23");
}
logger.info("## Using "+web.getBase());
}
webservice = web;
initGUI ();
}
void initGUI () {
if (!UnsignedWebstart) {
chooser = new JFileChooser (".");
chooser.setMultiSelectionEnabled(true);
}
propCheckBoxList = new CheckBoxList ();
propCheckBoxList.setCheckBoxEnabled(true);
propCheckBoxList.setClickInCheckBoxOnly(true);
propCheckBoxList.setModel(new DefaultListModel ());
propDialog = new JDialog (this, true);
propDialog.setTitle("Add/remove data columns");
{ JPanel pane = new JPanel (new BorderLayout (5, 0));
pane.add(new JScrollPane (propCheckBoxList));
JPanel bp = new JPanel (new GridLayout (1, 2));
((GridLayout)bp.getLayout()).setHgap(5);
JButton btn;
bp.add(btn = new JButton ("OK"));
btn.addActionListener(new ActionListener () {
public void actionPerformed (ActionEvent e) {
updateProperties ();
propDialog.setVisible(false);
}
});
bp.add(btn = new JButton ("Cancel"));
btn.addActionListener(new ActionListener () {
public void actionPerformed (ActionEvent e) {
propDialog.setVisible(false);
}
});
JPanel bpp = new JPanel ();
bpp.setBorder(BorderFactory.createTitledBorder(""));
bpp.add(bp);
pane.add(bpp, BorderLayout.SOUTH);
propDialog.getContentPane().add(pane);
propDialog.pack();
propDialog.setSize(400, 500);
}
popup = new JPopupMenu ();
JMenuItem item = new JMenuItem ("Extend");
item.setToolTipText("Extend (if at all possible) selected scaffold");
item.addActionListener(this);
popup.add(item);
popup.add(item = new JMenuItem ("Dump"));
item.addActionListener(new ActionListener () {
public void actionPerformed (ActionEvent e) {
RGroupTable rtab = getSelectedScaffold ();
if (rtab != null)
dumpXml (System.out, rtab);
}
});
setJMenuBar (createMenuBar ());
JPanel pane = new JPanel (new BorderLayout (0, 0));
pane.setBorder(EMPTY);
JSplitPane split = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT);
split.setDividerSize(7);
split.setResizeWeight(.35);
split.setLeftComponent(createNavPane ());
split.setRightComponent(createContentPane ());
pane.add(split);
pane.add(createToolBar (), BorderLayout.NORTH);
pane.add(createStatusPane (), BorderLayout.SOUTH);
setTitle ("NCGC Scaffold Hopper ["+webservice.getBase()+"]");
getContentPane().add(pane);
pack ();
setDefaultCloseOperation (EXIT_ON_CLOSE);
}
void updateProperties () {
Object[] selected = propCheckBoxList.getCheckBoxListSelectedValues();
Set<String> remove = new HashSet<String>();
remove.addAll(props.keySet());
for (Object keep : selected) {
remove.remove((String)keep);
}
for (RGroupTable rtab : getRGroup().getRGroupTables()) {
rtab.removeProperties(remove);
}
((ScaffoldTableModel)scaffoldTab.getModel())
.removeProperties(remove);
Map<String, Class> keep = new TreeMap<String, Class>();
for (Object obj : selected) {
String s = (String)obj;
keep.put(s, props.get(s));
}
for (RGroupTable rtab : getRGroup().getRGroupTables()) {
rtab.addProperties(keep);
}
((ScaffoldTableModel)scaffoldTab.getModel()).addProperties(keep);
}
Component createStatusPane () {
JPanel pane = new JPanel (new BorderLayout (5, 0));
pane.setBorder(BorderFactory.createCompoundBorder
(BorderFactory.createEtchedBorder(),
BorderFactory.createEmptyBorder(1,1,1,1)));
JSlider slider = new JSlider (50, 200, 100);
//slider.setPreferredSize(new Dimension (100, 20));
slider.addChangeListener(new ChangeListener () {
public void stateChanged (ChangeEvent e) {
JSlider slider = (JSlider)e.getSource();
scaffoldTab.setRowHeight(slider.getValue());
rgroupTab.setRowHeight(slider.getValue());
instanceTab.setRowHeight(slider.getValue());
//pubchemPane.setRowHeight(slider.getValue());
}
});
pane.add(slider, BorderLayout.WEST);
statusField = new JTextField ();
statusField.setEditable(false);
pane.add(statusField);
progress = new JProgressBar (0, 100);
progress.setBorderPainted(true);
progress.setStringPainted(false);
pane.add(progress, BorderLayout.EAST);
return pane;
}
Component createContentPane () {
JideTabbedPane tab = new JideTabbedPane ();
tab.setShowCloseButton(true);
tab.setShowCloseButtonOnTab(true);
tab.addChangeListener(new ChangeListener () {
public void stateChanged (ChangeEvent e) {
//logger.info("contentTab changed");
}
});
tab.addTab("References", createDocsPane ()); // REFERENCE_TAB
tab.addTab("Compounds", createInstancesPane ()); // COMPOUND_TAB
tab.addTab("R-group", createRGroupPane ()); // RGROUP_TAB
//tab.addTab("PubChem", createPubChemPane ());
tab.setTabLeadingComponent(new TabControl ());
tab.setTabClosableAt(0, false); // first tab can't be closed!
tab.setTabClosableAt(1, false);
tab.setTabClosableAt(2, false);
//tab.setTabClosableAt(3, false);
JPanel pane = new JPanel (new BorderLayout (0, 5));
pane.setBorder(EMPTY);
pane.add(tab);
contentTab = tab;
return pane;
}
Component createNavPane () {
JPanel pane = new JPanel (new BorderLayout (0, 5));
pane.setBorder(EMPTY);
scaffoldTab = createTable ();
//scaffoldTab.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
scaffoldTab.getSelectionModel()
.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scaffoldTab.getSelectionModel().addListSelectionListener(this);
scaffoldTab.addMouseListener(new MouseAdapter () {
public void mouseClicked (MouseEvent e) {
if (e.isPopupTrigger()) {
triggerPopup (e);
}
}
public void mousePressed (MouseEvent e) {
if (e.isPopupTrigger()) {
triggerPopup (e);
}
}
void triggerPopup (MouseEvent e) {
popup.show(scaffoldTab, e.getX(), e.getY());
}
});
JSplitPane split = new JSplitPane (JSplitPane.VERTICAL_SPLIT);
split.setDividerSize(7);
split.setResizeWeight(.75);
split.setOneTouchExpandable(true);
JPanel scafpane = new JPanel (new BorderLayout (0, 3));
scaffoldLabel = new JLabel
("<html><b>List of scaffolds", JLabel.CENTER);
scaffoldTab.addPropertyChangeListener(this);
scafpane.add(scaffoldLabel, BorderLayout.NORTH);
scafpane.add(new JScrollPane (scaffoldTab));
split.setTopComponent(scafpane);
split.setBottomComponent(createMViewPane ());
navtab = new JideTabbedPane ();
JPanel sp = new JPanel (new BorderLayout (0, 1));
sp.add(split);
navtab.addTab("Scaffold", sp); // SCAFFOLD_TAB
navtab.addTab("Network", network = new RGroupNetwork ());// NETWORK_TAB
navtab.addTab("Singleton", createSingletonPane ());// SINGLETON_TAB
network.addPropertyChangeListener(this);
pane.add(navtab);
JPanel bp = new JPanel (new GridLayout (1, 3));
((GridLayout)bp.getLayout()).setHgap(2);
JButton btn = new JButton ("Add");
btn.addActionListener(this);
btn.setToolTipText("Add new scaffold");
bp.add(btn);
btn = new JButton ("Sort");
btn.addActionListener(this);
btn.setToolTipText
("Sort the scaffolds relative to the reference structure");
bp.add(btn);
btn = new JButton ("Extend");
btn.addActionListener(this);
btn.setToolTipText
("Extend the selected scaffold (if possible)");
bp.add(btn);
extBtn = btn;
JPanel bp2 = new JPanel ();
bp2.add(bp);
sp.add(bp2, BorderLayout.SOUTH);
return pane;
}
public void sortSimilar(JTable jtab, final Molecule ref, int column) {
TableModel tm = jtab.getModel();
if (tm.getColumnClass(column).isAssignableFrom(Molecule.class)) {
TableRowSorter trs = new TableRowSorter(tm);
final MolFpFactory fpFact = MolFpFactory.getInstance();
trs.setComparator(column, new Comparator<Molecule>() {
public int compare
(Molecule a, Molecule b) {
double simA = fpFact.tanimotoSim
(ref, a);
double simB = fpFact.tanimotoSim
(ref, b);
int d = 0;
if (simA > simB) d = -1;
else if (simA < simB) d = 1;
if (d == 0) {
d = b.getAtomCount() - a.getAtomCount();
}
if (d == 0) {
d = b.getBondCount() - a.getBondCount();
}
if (d == 0) {
d = (int)Math.signum(b.getMass() - a.getMass());
}
return d;
}
});
jtab.setRowSorter(trs);
trs.toggleSortOrder(column);
}
}
public void actionPerformed (ActionEvent e) {
if (e.getSource() instanceof JMenuItem) {
JMenuItem item = (JMenuItem)e.getSource();
RGroupTable rtab = getSelectedScaffold ();
if (rtab != null) {
new ExtendScaffold (rtab).execute();
}
}
else {
String cmd = e.getActionCommand();
if (cmd.equalsIgnoreCase("sort")) {
Molecule scaffold = mview.getM(0);
if (scaffold != null) {
sortSimilar(scaffoldTab,scaffold,0);
//rgroup.sort(scaffold);
//((AbstractTableModel)scaffoldTab.getModel()).fireTableDataChanged();
}
}
else if (cmd.equalsIgnoreCase("add")) {
if (mview.getSelectedIndex() < 0) {
JOptionPane.showMessageDialog
(RGroupTool.this,
"There is nothing to add!", "Message",
JOptionPane.INFORMATION_MESSAGE);
return;
}
mview.applyRotationMatrices();
Molecule scaffold = mview.getM(0);
logger.info("Adding user-defined scaffold... "
+scaffold.toFormat("cxsmarts"));
statusField.setText("Adding user-defined scaffold...");
new AddScaffold(scaffold.cloneMolecule()).execute();
}
else if (cmd.equalsIgnoreCase("extend")) {
RGroupTable rtab = getSelectedScaffold ();
if (rtab == null) {
JOptionPane.showMessageDialog
(RGroupTool.this,
"Please select a scaffold to extend", "Message",
JOptionPane.INFORMATION_MESSAGE);
}
else if (!rtab.isExtensible()) {
JOptionPane.showMessageDialog
(RGroupTool.this,
"Sorry, this scaffold can't be "
+"extended any further!", "Message",
JOptionPane.INFORMATION_MESSAGE);
}
else {
new ExtendScaffold (rtab).execute();
}
}
else if (cmd.equalsIgnoreCase("search")) {
JTextField field = (JTextField)e.getSource();
String text = field.getText();
if (text != null && text.length() > 0) {
doSearch (text.trim());
}
else {
JOptionPane.showMessageDialog
(this, "No search terms specified!",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
else if (cmd.equalsIgnoreCase("open")) {
openFile ();
}
else if (cmd.equalsIgnoreCase("go-back")) {
goBack ();
}
else if (cmd.equalsIgnoreCase("go-forward")) {
goForward ();
}
else if (cmd.equalsIgnoreCase("structure-search")) {
getStructureSearchDialog().setVisible(true);
}
else {
logger.log(Level.WARNING, "unknown command: " + cmd);
}
}
}
void updateRGroup () {
updateRGroup (getRGroup ());
}
void updateRGroup (RGroupGenerator rgroup) {
instanceTab.setModel
(new InstanceTableModel (rgroup, props));
scaffoldTab.setModel(new ScaffoldTableModel (props));
//addMolecularSorter(scaffoldTab);
//addMolecularSorter(instanceTab);
for (RGroupTable rtab : rgroup.getRGroupTables()) {
rtab.addProperties(props);
}
network.setRGroups(rgroup.getRGroupTables());
scaffoldLabel.setText("<html><b>"+rgroup.getName());
DefaultTableModel model = new DefaultTableModel
(new Object[]{"ID", "Structure"}, 0) {
public Class getColumnClass (int col) {
if (col == 0) return String.class;
return Molecule.class;
}
};
Enumeration<Molecule> singleton = rgroup.getSingletons();
while (singleton.hasMoreElements()) {
Molecule m = singleton.nextElement();
model.addRow(new Object[]{m.getName(), m});
}
singletonTab.setModel(model);
navtab.setTitleAt(SINGLETON_TAB, "Singletons ("
+rgroup.getSingletonCount()+")");
navtab.setTitleAt(SCAFFOLD_TAB, "Scaffolds ("
+rgroup.getScaffoldCount()+")");
// now regenerate all datasets
Vector files = new Vector ();
for (int i = contentTab.getTabCount(); --i > 0;) {
final JComponent c = (JComponent)contentTab.getComponentAt(i);
SearchRGroup rg = (SearchRGroup)c.getClientProperty
("rgroup.search");
if (rg != null) {
files.add(rg.getFile());
contentTab.remove(i);
}
if (i == COMPOUND_TAB) {
contentTab.setTitleAt
(i, "Compounds ("+rgroup.size()+")");
}
}
for (Object file : files) {
new SearchRGroup (rgroup.getRGroupTables(),
file).execute();
}
}
public void valueChanged (ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
// scaffold selection
RGroupTable rtab = getSelectedScaffold ();
if (rtab != null)
showRGroupTable (rtab);
}
void showRGroupTable (final RGroupTable rtab) {
contentTab.setTitleAt(RGROUP_TAB, "R-group ("+rtab.getRowCount()+")");
rgroupTab.setModel(rtab);
//addMolecularSorter(rgroupTab);
Enumeration<TableColumn> tcI=rgroupTab.getColumnModel().getColumns();
for(TableColumn tc=null;tcI.hasMoreElements();){
tc=tcI.nextElement();
int mindex=tc.getModelIndex();
if(rtab.isVisible(mindex)){
if(tc.getWidth()>0){
columnPreviousWidth.put(mindex,tc.getWidth());
tc.setMinWidth(0);
tc.setPreferredWidth(0);
tc.setResizable(false);
}
}
else {
if(tc.getWidth()<=0){
Integer restoreWidth=columnPreviousWidth.get(mindex);
tc.setResizable(true);
tc.setMinWidth(5);
tc.setPreferredWidth(restoreWidth);
}
}
}
rgroupTab.getTableHeader().repaint();
EventQueue.invokeLater(new Runnable () {
public void run () {
// clear all previous highlighting
for (int i = 0; i < getRGroup().size(); ++i) {
Molecule m = getRGroup().get(i);
for (MolAtom a : m.getAtomArray()) {
a.setSetSeq(0);
}
}
// do alignment and highlighting
rtab.align();
// repaint the two tables
rgroupTab.repaint();
instanceTab.repaint();
}
});
// select the rest of the table
for (int i = 1; i < contentTab.getTabCount(); ++i) {
JComponent c = (JComponent)contentTab.getComponentAt(i);
JPanel pane = (JPanel)c.getClientProperty("rgroup.pane");
final JTable tab = (JTable)c.getClientProperty("rgroup.table");
//addMolecularSorter(tab);
SearchRGroup rg = (SearchRGroup)
c.getClientProperty("rgroup.search");
if (rg != null) {
final RGroupTable rt = rg.getRGroupTable(rtab);
if (rt != null) {
contentTab.setTitleAt
(i, rg.getName()+" ("+rt.getRowCount()+")");
tab.setModel(rt);
((CardLayout)pane.getLayout()).show(pane, "rgroup.data");
EventQueue.invokeLater(new Runnable () {
public void run () {
rt.align();
tab.repaint();
}
});
}
else {
contentTab.setTitleAt(i, rg.getName());
((CardLayout)pane.getLayout()).show(pane, "rgroup.empty");
}
}
}
extBtn.setEnabled(rtab.isExtensible());
for (int i = 0; i < popup.getComponentCount(); ++i) {
Component c = popup.getComponent(i);
if (c instanceof JMenuItem) {
JMenuItem item = (JMenuItem)c;
if (item.getText().equalsIgnoreCase("extend")) {
item.setEnabled(rtab.isExtensible());
}
}
}
Molecule scaffold = rtab.getScaffold();
if (scaffold != null) {
mview.setM(0, scaffold);
}
contentTab.setTitleAt(REFERENCE_TAB, "References...");
docsPane.search(rtab.getCore());
//contentTab.setTitleAt(PUBCHEM_TAB, "PubChem...");
//pubchemPane.search(rtab.getCore());
}
void dumpXml (PrintStream ps, RGroupTable rtab) {
ps.println("<?xml version=\"1.0\"?>");
ps.println("<rgroup-radial>");
ps.println("</rgroup-radial>");
}
protected StructureSearchDialog getStructureSearchDialog () {
if (_strucSearchDialog == null) {
_strucSearchDialog = new StructureSearchDialog (this) {
protected void search (Molecule query,
SearchParams params) {
contentTab.setTitleAt(REFERENCE_TAB, "References...");
docsPane.search(query, params);
}
};
Dimension s0 = getSize ();
Dimension s1 = _strucSearchDialog.getSize();
_strucSearchDialog.setLocation
(getX() + (s0.width - s1.width)/2,
getY() + (s0.height - s1.height)/2);
}
return _strucSearchDialog;
}
protected Component createMViewPane () {
JPanel pane = new JPanel (new BorderLayout (0, 2));
pane.add(new JLabel ("Double-click to edit scaffold", JLabel.CENTER),
BorderLayout.NORTH);
mview = new MViewPane ();
/*
mview.getVisibleCellComponent(0)
.addMouseMotionListener(new MouseMotionAdapter () {
public void mouseDragged (MouseEvent e) {
System.out.println
("mouse dragged: " + e.getX() + " " + e.getY());
}
});
*/
mview.getVisibleCellComponent(0)
.addMouseListener(new MouseAdapter () {
public void mouseReleased (MouseEvent e) {
updateSelectedScaffold ();
}
});
mview.addPropertyChangeListener(this);
mview.addActionListener(new ActionListener () {
public void actionPerformed (ActionEvent e) {
System.out.println(e.getActionCommand());
}
});
mview.setEditable(2);
pane.add(mview);
return pane;
}
void updateSelectedScaffold () {
Molecule m = mview.getM(0);
if (m == null) return;
mview.applyRotationMatrices();
RGroupTable rtab = getSelectedScaffold ();
if (rtab != null) {
Molecule core = rtab.getCore();
Molecule scaffold = rtab.getScaffold();
}
//System.out.println("scaffold: " + scaffold + " edited: " + m);
}
RGroupTable getSelectedScaffold() {
int row = scaffoldTab.getSelectedRow();
return row < 0 ? null
: ((ScaffoldTableModel) scaffoldTab.getModel()).getScaffold(scaffoldTab.convertRowIndexToModel(row));
}
protected JTable createTable() {
JTable tab = new RTable();
tab.setDefaultRenderer(RGroupTable.CRC.class,
new CRCCellRenderer());
return tab;
}
Component createRGroupPane () {
JPanel pane = new JPanel (new BorderLayout ());
/*
pane.setBorder(BorderFactory.createCompoundBorder
(BorderFactory.createTitledBorder("R-group"), EMPTY));
*/
pane.setBorder(EMPTY);
rgroupTab = createTable ();
pane.add(new JScrollPane (rgroupTab));
return pane;
}
Component createInstancesPane () {
JPanel pane = new JPanel (new BorderLayout ());
/*
pane.setBorder(BorderFactory.createCompoundBorder
(BorderFactory.createTitledBorder("R-group"), EMPTY));
*/
pane.setBorder(EMPTY);
instanceTab = createTable ();
instanceTab.getSelectionModel()
.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
instanceTab.getSelectionModel().addListSelectionListener
(new ListSelectionListener () {
public void valueChanged (ListSelectionEvent e) {
// this is in view coordinate; if sorting is available
// the row should be converted into model's
// coordinate!
ScaffoldTableModel model =
(ScaffoldTableModel)scaffoldTab.getModel();
int row = instanceTab.getSelectedRow();
row= (row < 0)?-1:instanceTab.convertRowIndexToModel(row);
if (row >= 0) {
RGroupTable[] rgs =
getRGroup().getRGroupTablesFor(row);
model.setScaffolds(rgs);
}
else {
model.setScaffolds((RGroupTable[])null); // clear
}
}
});
pane.add(new JScrollPane (instanceTab));
//addMolecularSorter(instanceTab);
return pane;
}
Component createDocsPane () {
docsPane = new RGroupDocsPane ();
docsPane.setWS(webservice);
docsPane.addPropertyChangeListener(this);
return docsPane;
}
Component createSingletonPane () {
JPanel pane = new JPanel (new BorderLayout ());
singletonTab = createTable ();
pane.add(new JScrollPane (singletonTab));
return pane;
}
Component createPubChemPane () {
pubchemPane = new RGroupPubChemPane ();
pubchemPane.addPropertyChangeListener(this);
return pubchemPane;
}
void makeRGroupStats() throws IOException {
// read in data
BufferedReader reader = new BufferedReader(new FileReader(activityDataFileName));
HashMap<String, Double> activity = new HashMap<String, Double>();
String line;
while ((line = reader.readLine()) != null) {
String[] toks = line.trim().split(",");
activity.put(toks[0], Double.parseDouble(toks[1]));
}
System.out.println("Loaded activity data from " + activityDataFileName);
System.out.println("Will process " + getRGroup().getScaffoldCount() + " scaffolds");
int nskip = 0;
for (int i = 0; i < getRGroup().getScaffoldCount(); i++) {
RGroupTable rtab = getRGroup().getRGroupTable(i);
double ratio = (double) rtab.getRGroupCount() / rtab.getRowCount();
if (ratio >= 1) {
// System.out.println("Won't fit model for scaffold " + (i + 1) + " (ratio = " + ratio + ")");
nskip++;
continue;
}
Molecule[] members = rtab.getMembers();
int ndesc = 2;
double[][] x = new double[rtab.getRowCount()][rtab.getRGroupCount() * ndesc];
double[] y = new double[rtab.getRowCount()];
String[] molids = new String[rtab.getRowCount()];
for (int row = 0; row < rtab.getRowCount(); row++) {
Molecule[] groups = rtab.getRGroups(row);
// get molecule id for this row
String moleculeId = members[row].getName();
molids[row] = moleculeId;
y[row] = activity.get(moleculeId);
// generate descriptors
for (int col = 0; col < rtab.getRGroupCount(); col += ndesc) {
Molecule m = groups[col];
if (i == 11) System.out.println("m = " + m);
if (m != null) {
TopologicalIndices ti = new TopologicalIndices(m);
x[row][col + 0] = ti.TIkierflex();
x[row][col + 1] = m.getAtomCount();
} else {
for (int j = 0; j < ndesc; j++)
x[row][col + j] = 0.0;
}
}
System.out.println();
}
// dump x, y for testing purposes
dumpRGroupDesc("scaf" + i + ".csv", molids, y, x);
// fit model
}
System.out.println("Processed = "
+ (getRGroup().getScaffoldCount() - nskip)
+ " scaffolds, skipped " + nskip);
}
void addSearchRGroup (SearchRGroup rgroup) {
JPanel rgpane = new JPanel (new BorderLayout ());
rgpane.setBorder(EMPTY);
final JTable rgtab = createTable ();
rgpane.add(new JScrollPane (rgtab));
JPanel spane = new JPanel (new BorderLayout ());
JTable stab = createTable ();
stab.setModel(rgroup.getSingletons());
spane.add(new JScrollPane (stab));
spane.setBorder(BorderFactory.createCompoundBorder
(BorderFactory.createTitledBorder
("Singletons" + (stab.getRowCount() == 0 ? ""
: (" ("+stab.getRowCount()+")"))),
EMPTY));
JPanel pane = new JPanel (new CardLayout ());
pane.add(rgpane, "rgroup.data");
JPanel empty = new JPanel (new BorderLayout ());
empty.add(new JLabel ("<html><b>This scaffold is not in data set "
+ rgroup.getName(), JLabel.CENTER));
pane.add(empty, "rgroup.empty");
JSplitPane split = new JSplitPane (JSplitPane.VERTICAL_SPLIT);
split.setDividerSize(7);
split.setOneTouchExpandable(true);
split.setTopComponent(pane);
split.setBottomComponent(spane);
split.setResizeWeight(.75);
split.putClientProperty("rgroup.table", rgtab);
split.putClientProperty("rgroup.search", rgroup);
split.putClientProperty("rgroup.pane", pane);
contentTab.addTab(rgroup.getName(), split);
RGroupTable rtab = getSelectedScaffold ();
if (rtab != null) {
final RGroupTable tab = rgroup.getRGroupTable(rtab);
if (tab != null) {
rgtab.setModel(tab);
contentTab.setTitleAt
(contentTab.getTabCount()-1, rgroup.getName()
+" ("+tab.getRowCount()+")");
EventQueue.invokeLater(new Runnable () {
public void run () {
tab.align();
rgtab.repaint();
}
});
}
else {
((CardLayout)pane.getLayout()).show(pane, "rgroup.empty");
}
}
}
protected JToolBar createToolBar () {
JToolBar toolbar = new JToolBar ();
JButton btn = new JButton (BACK_ICON);
btn.setBorderPainted(false);
btn.setContentAreaFilled(false);
btn.setRolloverEnabled(true);
btn.setToolTipText("Go to previous dataset");
btn.setActionCommand("go-back");
btn.addActionListener(this);
btn.setEnabled(false);
navBackBtn = btn;
toolbar.add(btn);
btn = new JButton (FORWARD_ICON);
btn.setBorderPainted(false);
btn.setContentAreaFilled(false);
btn.setRolloverEnabled(true);
btn.setToolTipText("Go to next dataset");
btn.setActionCommand("go-forward");
btn.addActionListener(this);
btn.setEnabled(false);
navForwardBtn = btn;
toolbar.add(btn);
btn = new JButton (OPEN_ICON);
btn.setBorderPainted(false);
btn.setContentAreaFilled(false);
btn.setRolloverEnabled(true);
btn.setToolTipText("Open dataset");
btn.setActionCommand("open");
btn.addActionListener(this);
toolbar.add(btn);
btn = new JButton (COMPOUND_ICON);
btn.setBorderPainted(false);
btn.setContentAreaFilled(false);
btn.setRolloverEnabled(true);
btn.setToolTipText("Structure search references");
btn.setActionCommand("structure-search");
btn.addActionListener(this);
toolbar.add(btn);
toolbar.addSeparator();
toolbar.add(new JLabel ("Search: "));
searchField = new JTextField (30);
searchField.setToolTipText
("Enter search terms (e.g., clk4, pde4 inhibitor)");
searchField.setActionCommand("search");
searchField.addActionListener(this);
toolbar.add(searchField);
return toolbar;
}
protected JMenuBar createMenuBar () {
JMenuBar menubar = new JMenuBar ();
JMenu menu;
JMenuItem item;
menubar.add(menu = new JMenu ("File"));
JMenu open = new JMenu ("Open");
menu.add(open);
open.add(item = new JMenuItem ("File"));
item.setToolTipText("Open input file to generate scaffolds");
item.addActionListener(new ActionListener () {
public void actionPerformed (ActionEvent e) {
openFile ();
}
});
open.add(item = new JMenuItem ("URL"));
item.setToolTipText("Open input stream from a URL");
item.addActionListener(new ActionListener () {
public void actionPerformed (ActionEvent e) {
openURL ();
}
});
open.add(item = new JMenuItem ("DOI/PubMed"));
item.setToolTipText("Open input from DOI/PubMed references");
item.addActionListener(new ActionListener () {
public void actionPerformed (ActionEvent e) {
openWS ();
}
});
menu.addSeparator();
JMenu exportDataMenu = new JMenu("Export dataset");
JMenuItem exportJsonMenuItem = new JMenuItem("JSON");
JMenuItem exportTabMenuItem = new JMenuItem("TSV");
exportDataMenu.add(exportJsonMenuItem);
exportDataMenu.add(exportTabMenuItem);
menu.add(exportDataMenu);
exportJsonMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exportDatasetAsJSON();
}
});
exportTabMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exportDatasetAsTSV();
}
});
menu.add(item = new JMenuItem ("Export image"));
item.addActionListener(new ActionListener () {
public void actionPerformed (ActionEvent e) {
exportImage ();
}
});
menu.addSeparator();
menu.add(item = new JMenuItem ("Quit"));
item.addActionListener(new ActionListener () {
public void actionPerformed (ActionEvent e) {
quit ();
}
});
menubar.add(menu = new JMenu ("Options"));
menu.add(item = new JMenuItem ("Add/remove data columns"));
item.addActionListener(new ActionListener () {
public void actionPerformed (ActionEvent e) {
propDialog.setVisible(true);
}
});
menubar.add(menu = new JMenu ("Help"));
menu.add(item = new JMenuItem ("About"));
item.addActionListener(new ActionListener () {
public void actionPerformed (ActionEvent e) {
about ();
}
});
return menubar;
}
void about () {
JOptionPane.showMessageDialog
(this, "NCGC Scaffold Hopper, 2017\n"
+"Please send questions and/or comments to\n"
+"nguyenda@mail.nih.gov and tyler.peryea@nih.gov",
"About", JOptionPane.INFORMATION_MESSAGE);
}
void newRGroupGenerator (RGroupWorker worker) {
newRGroupGenerator (false, worker);
}
void newRGroupGenerator (boolean clearHistory, RGroupWorker worker) {
if (clearHistory) {
for (RGroupGenerator rg : history) {
rg.removePropertyChangeListener(this);
}
history.clear();
for (RGroupGenerator rg : forward) {
rg.removePropertyChangeListener(this);
}
forward.clear();
navForwardBtn.setEnabled(false);
}
RGroupGenerator rgroup = new RGroupGenerator ();
rgroup.addPropertyChangeListener(this);
history.push(rgroup);
navBackBtn.setEnabled(history.size() > 1);
progress.setStringPainted(true);
worker.execute();
}
RGroupGenerator getRGroup () {
return history.peek();
}
void loadFile (String... argv) {
if (argv.length > 0) {
/*
rgroup = new RGroupGenerator ();
rgroup.addPropertyChangeListener(this);
progress.setStringPainted(true);
new RGroupWorker (argv).execute();
*/
newRGroupGenerator (true, new RGroupWorker (argv));
}
}
void loadFile (File... files) {
if (files == null || files.length == 0) {
JOptionPane.showMessageDialog
(this, "No file(s) selected!", "Error",
JOptionPane.ERROR_MESSAGE);
}
else {
/*
rgroup = new RGroupGenerator ();
rgroup.addPropertyChangeListener(this);
progress.setStringPainted(true);
new RGroupWorker (files).execute();
*/
newRGroupGenerator (true, new RGroupWorker (files));
}
}
void loadFile (FileContents... files) {
if (files == null || files.length == 0) {
JOptionPane.showMessageDialog
(this, "No file(s) selected!", "Error",
JOptionPane.ERROR_MESSAGE);
}
else {
/*
rgroup = new RGroupGenerator ();
rgroup.addPropertyChangeListener(this);
progress.setStringPainted(true);
new RGroupWorker (files).execute();
*/
newRGroupGenerator (true, new RGroupWorker (files));
}
}
private void dumpRGroupDesc(String fname, String[] molids, double[] y, double[][] x) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fname));
for (int j = 0; j < y.length; j++) {
StringBuffer sb = new StringBuffer();
if (molids != null) sb.append(molids[j] + ",");
sb.append(y[j] + ",");
for (int k = 0; k < x[0].length; k++) {
if (k != x[0].length - 1) sb.append(x[j][k] + ",");
else sb.append(x[j][k]);
}
sb.append("\n");
writer.write(sb.toString());
}
writer.close();
}
public void propertyChange (PropertyChangeEvent e) {
String name = e.getPropertyName();
//logger.info(e.getSource() + ": name="+name+" old="+e.getOldValue() + " new="+e.getNewValue());
if (name.equals("progress")) {
progress.setValue((Integer)e.getNewValue());
}
else if (name.equals("docs")) {
JsonNode[] docs = (JsonNode[])e.getNewValue();
for (int i = 0; i < contentTab.getTabCount(); ++i) {
if (i == REFERENCE_TAB) {
contentTab.setTitleAt
(i, "References"+(docs != null
? (" ("+docs.length+")") : ""));
}
}
}
else if (name.equals("pubchem")) {
contentTab.setTitleAt
(PUBCHEM_TAB, "PubChem ("+pubchemPane.getCount()+")");
}
else if (name.equals("load")) {
// we should keep a history of this
URL url = getWS().getCompoundURL(e.getNewValue()+"/pubmed");
newRGroupGenerator (false, new RGroupWorker (url));
}
else if (name.equalsIgnoreCase("majr")
|| name.equalsIgnoreCase("mh")) {
String mesh = "\""+e.getNewValue()+"\"["+name+"]";
searchField.setText(mesh);
doSearch (mesh);
}
else if (name.equalsIgnoreCase("tid")) {
URL url = getWS().getDocumentURL(e.getNewValue()+"/tid?max=100");
doLoad (url);
}
else if (name.equals("model")) {
((AbstractTableModel)scaffoldTab.getModel()).addTableModelListener
(new TableModelListener () {
public void tableChanged (TableModelEvent e) {
navtab.setTitleAt
(SCAFFOLD_TAB, "Scaffolds ("
+((TableModel)e.getSource()).getRowCount()
+")");
}
});
}
else if (name.equals("rgroup")) {
if (e.getSource() == network) {
RGroupTable rtab = (RGroupTable)e.getNewValue();
if (rtab != null) {
selectScaffold (rtab);
}
}
}
else if(name.equals("status")){
statusField.setText((String)e.getNewValue());
}
if (mview != e.getSource()) {
return;
}
/*
if (name.equals("selectedIndex")) {
mview.applyRotationMatrices();
Molecule m = mview.getM(0).cloneMolecule();
// remove the R-group...
Set<MolAtom> remove = new HashSet<MolAtom>();
for (MolAtom a : m.getAtomArray()) {
if (a.getAtno() == MolAtom.RGROUP) {
remove.add(a);
}
}
for (MolAtom a : remove) {
m.removeNode(a);
}
mview.setM(0, m);
}
*/
}
void selectScaffold (RGroupTable rtab) {
/*
* this code doesn't work when the scaffoldTab is reduced
* from the Instance selection. So to make life easy, we
* just clear the instanceTab selection.
*/
instanceTab.clearSelection();
RGroupGenerator rgroup = getRGroup ();
for (int r = 0; r < rgroup.getScaffoldCount(); ++r) {
if (rgroup.getRGroupTable(r) == rtab) {
if(r<scaffoldTab.getRowCount()&&r>=0){
int vr = scaffoldTab.convertRowIndexToView(r);
scaffoldTab.setRowSelectionInterval(vr, vr);
int scroll = vr*scaffoldTab.getRowHeight();
JScrollPane sp = (JScrollPane)
SwingUtilities.getAncestorOfClass
(JScrollPane.class, scaffoldTab);
if (sp != null) {
sp.getVerticalScrollBar().setValue(scroll);
}
logger.info(vr+"th scaffold selected!");
break;
}
}
}
}
void openURL () {
String value = JOptionPane.showInputDialog
(this, "Please enter URL", null);
if (value != null) {
try {
URL url = new URL (value);
/*
rgroup = new RGroupGenerator ();
rgroup.addPropertyChangeListener(this);
progress.setStringPainted(true);
new RGroupWorker (url).execute();
*/
newRGroupGenerator (false, new RGroupWorker (url));
}
catch (Exception ex) {
JOptionPane.showMessageDialog
(this, "Bad URL "+value, "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
void openWS () {
String value = JOptionPane.showInputDialog
(this, "Please enter DOIs and/or PubMed IDs", null);
if (value != null) {
String[] toks = value.split("[\\s]+");
ArrayList<URL> urls = new ArrayList<URL>();
for (String t : toks) {
if (t.startsWith("10.")) {
urls.add(getWS().getCompoundURL(t+"/doi"));
}
else {
urls.add(getWS().getCompoundURL(t+"/pubmed"));
}
}
if (urls.isEmpty()) {
JOptionPane.showMessageDialog
(this, "No valid DOI/PubMed IDs specified!", "Error",
JOptionPane.ERROR_MESSAGE);
}
else {
newRGroupGenerator (true, new RGroupWorker
(urls.toArray(new URL[0])));
}
}
}
void doSearch (String query) {
logger.info("## Searching for \""+query+"\"...");
contentTab.setTitleAt(REFERENCE_TAB, "References...");
docsPane.search(query);
}
void doLoad (URL url) {
logger.info("## Loading "+url+"...");
contentTab.setTitleAt(REFERENCE_TAB, "References...");
docsPane.load(url);
}
void goBack () {
forward.push(history.pop());
docsPane.push();
navBackBtn.setEnabled(history.size() > 1);
navForwardBtn.setEnabled(true);
updateRGroup ();
}
void goForward () {
history.push(forward.pop());
docsPane.pop();
navBackBtn.setEnabled(true);
navForwardBtn.setEnabled(!forward.isEmpty());
updateRGroup ();
}
void openFile () {
if (UnsignedWebstart) {
try {
FileOpenService fos = (FileOpenService)ServiceManager.lookup
("javax.jnlp.FileOpenService");
FileContents[] files = fos.openMultiFileDialog
(".", new String[]{"sdf","mol","smi","smiles",
"cml","sd"});
loadFile (files);
}
catch (Exception ex) {
JOptionPane.showMessageDialog
(RGroupTool.this, "Your Java Webstart doesn't have "
+"proper permission to open files.",
"Fatal Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
chooser.setDialogTitle("Please select input file(s)");
if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) {
loadFile (chooser.getSelectedFiles());
}
}
}
RGroupWebResources getWS () { return webservice; }
void quit () {
System.exit(0);
}
private JsonNode _addMembersToScaffold(RGroupTable rgt, ObjectNode scaffoldNode, ObjectMapper mapper) {
ArrayNode mols = mapper.createArrayNode();
// add the rgroup labels to the scaffold node
ArrayNode labels = mapper.createArrayNode();
for (int i = 0; i < rgt.getRGroupCount(); i++) labels.add(rgt.getRGroupLabel(i));
scaffoldNode.put("rgroupLabels", labels);
// molecules for this r-group table
for (int idx = 0; idx < rgt.rows.length; idx++) {
int serial = rgt.rows[idx];
ObjectNode molnode = mapper.createObjectNode();
Molecule m = rgt.molseq.get(serial);
molnode.put("id", m.getName());
molnode.put("smiles", m.toFormat("cxsmiles"));
// r-groups for this molecule
ArrayNode rgroupNodes = mapper.createArrayNode();
Molecule[] rgroups = rgt.rgroups[idx];
for (int rpos = 0; rpos < rgroups.length; rpos++) {
String label = rgt.getRGroupLabel(rpos);
Molecule rgm = rgroups[rpos];
if (rgm != null) {
ObjectNode tmp = mapper.createObjectNode();
tmp.put(label, rgm.toFormat("cxsmiles"));
rgroupNodes.add(tmp);
}
}
molnode.put("rgroups", rgroupNodes);
mols.add(molnode);
}
return mols;
}
void exportDatasetAsTSV() {
RGroupGenerator rgen = getRGroup();
if (scaffoldTab.getModel() == null || scaffoldTab.getModel() instanceof DefaultTableModel) return;
ScaffoldTableModel model = (ScaffoldTableModel) scaffoldTab.getModel();
StringBuilder sb = new StringBuilder();
StringBuilder rsb = new StringBuilder();
int RGROUP_MAX = 21;
RGroupTable selectedScaffold = getSelectedScaffold();
if (selectedScaffold != null) {
} else {
String delim = "";
// set up header
sb.append(delim).append("ScaffoldId");
delim = "\t";
sb.append(delim).append("Structure");
// add in R-group labels
sb.append(delim).append("RgroupLabels");
for (int col = 1; col < model.getColumnCount(); col++) {
Object data = model.getValueAt(0, col);
String colName = model.getColumnName(col);
if (data instanceof ScaffoldData) {
sb.append(delim).append(colName).append(delim).append(colName+"_SD");
} else sb.append(delim).append(colName);
}
sb.append("\n");
// rgroup file header
rsb.append("ScaffoldID").
append(delim).
append("MolID").
append(delim).
append("Structure");
for (int i = 1; i <= RGROUP_MAX; i++) rsb.append(delim).append("R"+i);
rsb.append("\n");
delim = "";
for (int row = 0; row < model.getRowCount(); row++) {
sb.append(delim);
delim = "\t";
Molecule scaffold = (Molecule) model.getValueAt(row, 0);
sb.append(delim).append(row);
sb.append(delim).append(scaffold.toFormat("cxsmiles"));
// get set of R? labels for this scaffold
RGroupTable rgt = rgen.getRGroupTable(row);
/*
String rlabels = IntStream.
range(0, rgt.getRGroupCount()).
mapToObj(i -> rgt.getRGroupLabel(i)).
collect(Collectors.joining(","));
sb.append(delim).append(rlabels);
*/
sb.append(delim);
for (int i = 0; i < rgt.getRGroupCount(); ++i) {
if (i > 0) sb.append(",");
sb.append(rgt.getRGroupLabel(i));
}
// get property values
for (int col = 1; col < model.getColumnCount(); col++) {
Object data = model.getValueAt(row, col);
if (data instanceof ScaffoldData) {
ScaffoldData sd = (ScaffoldData) data;
sb.append(delim).append(sd.getMean()).append(delim).append(sd.getStd());
} else {
sb.append(delim).append(data);
}
}
sb.append("\n");
// get r-group table for this scaffold. It will be written to a separate file
String rdelim = "";
for (int idx = 0; idx < rgt.rows.length; idx++) {
int serial = rgt.rows[idx];
Molecule m = rgt.molseq.get(serial);
rsb.append(rdelim).append(row);
rdelim = "\t";
rsb.append(rdelim).append(m.getName()).append(delim).append(m.toFormat("cxsmiles"));
// r-groups for this molecule
int nrg = rgt.getRGroupCount();
Molecule[] rgroups = rgt.rgroups[idx];
for (int rpos = 0; rpos < RGROUP_MAX; rpos++) {
if (rpos >= nrg)
rsb.append(delim).append("");
else {
Molecule rgm = rgroups[rpos];
if (rgm != null) rsb.append(delim).append(rgm.toFormat("cxsmiles"));
else rsb.append(delim).append("");
}
}
rsb.append("\n");
rdelim = "";
}
}
}
chooser.setDialogTitle("Please select output TSV file");
if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(this)) {
try {
File file = chooser.getSelectedFile();
FileWriter w = new FileWriter(file);
w.write(sb.toString());
w.close();
String fname = file.getParent()+ File.separator+"rgoup-"+file.getName();
w = new FileWriter(new File(fname));
w.write(rsb.toString());
w.close();
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog
(this, "Unable to export dataset as TSV", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
void exportDatasetAsJSON() {
ObjectMapper mapper = new ObjectMapper();
ArrayNode scaffoldList = mapper.createArrayNode();
RGroupGenerator rgen = getRGroup();
if (scaffoldTab.getModel() == null || scaffoldTab.getModel() instanceof DefaultTableModel) return;
ScaffoldTableModel model = (ScaffoldTableModel) scaffoldTab.getModel();
RGroupTable selectedScaffold = getSelectedScaffold();
if (selectedScaffold != null) {
ObjectNode scaffoldNode = mapper.createObjectNode();
Molecule scaffold = selectedScaffold.getScaffold();
scaffoldNode.put("scaffold",scaffold.toFormat("cxsmiles"));
scaffoldNode.put("Scaffold Score", selectedScaffold.getScaffoldScore());
scaffoldNode.put("Complexity", selectedScaffold.getScaffoldComplexity());
scaffoldNode.put("Count", selectedScaffold.getMemberCount());
scaffoldNode.put("members", _addMembersToScaffold(selectedScaffold, scaffoldNode, mapper));
scaffoldList.add(scaffoldNode);
} else {
for (int row = 0; row < model.getRowCount(); row++) {
ObjectNode scaffoldNode = mapper.createObjectNode();
Molecule scaffold = (Molecule) model.getValueAt(row, 0);
scaffoldNode.put("scaffold", scaffold.toFormat("cxsmiles"));
for (int col = 1; col < model.getColumnCount(); col++) {
Object data = model.getValueAt(row, col);
if (data instanceof ScaffoldData) {
ScaffoldData sd = (ScaffoldData) data;
ObjectNode sdNode = mapper.createObjectNode();
sdNode.put("mean", sd.getMean());
sdNode.put("sd", sd.getStd());
scaffoldNode.put(model.getColumnName(col), sdNode);
} else {
Class colClass = model.getColumnClass(col);
if (colClass.getName().contains("Integer"))
scaffoldNode.put(model.getColumnName(col), (Integer) data);
else if (colClass.getName().contains("Double"))
scaffoldNode.put(model.getColumnName(col), (Double) data);
else if (colClass.getName().contains("Float"))
scaffoldNode.put(model.getColumnName(col), (Float) data);
else if (colClass.getName().contains("Long"))
scaffoldNode.put(model.getColumnName(col), (Long) data);
else if (colClass.getName().contains("String"))
scaffoldNode.put(model.getColumnName(col), (String) data);
}
}
// Pull in r-group table for this scaffold
RGroupTable rgt = rgen.getRGroupTable(row);
JsonNode mols = _addMembersToScaffold(rgt, scaffoldNode, mapper);
scaffoldNode.put("members", mols);
scaffoldList.add(scaffoldNode);
}
}
chooser.setDialogTitle("Please select output JSON file");
if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(this)) {
try {
_dumpJson(chooser.getSelectedFile(), scaffoldList, mapper);
} catch (Exception ex) {
JOptionPane.showMessageDialog
(this, "Unable to export dataset as JSON!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// try {
// String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(scaffoldList);
// System.out.println(json);
// } catch (IOException e) {
// e.printStackTrace();
// }
}
private void _dumpJson(File out, JsonNode doc, ObjectMapper mapper) throws IOException {
mapper.writeValue(out, doc);
}
void exportImage () {
if (UnsignedWebstart) {
try {
FileSaveService fss = (FileSaveService)ServiceManager.lookup
("javax.jnlp.FileSaveService");
PipedInputStream pis = new PipedInputStream ();
final PipedOutputStream pos = new PipedOutputStream (pis);
Executors.newSingleThreadExecutor().execute(new Runnable () {
public void run () {
try {
exportViewImage (pos);
pos.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
FileContents save = fss.saveFileDialog
(null, null, pis, "scaffold.png");
if (save != null) {
System.err.println("saved image: "+save.getName());
}
}
catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog
(RGroupTool.this, "Your Java Webstart doesn't have "
+"proper permission to write files.",
"Fatal Error", JOptionPane.ERROR_MESSAGE);
}
}
else {
chooser.setDialogTitle("Please select output image file");
if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(this)) {
try {
exportViewImage (chooser.getSelectedFile());
}
catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog
(this, "Unable to export image!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
void exportViewImage (File out) throws Exception {
exportViewImage (new FileOutputStream (out));
}
void exportViewImage (OutputStream os) throws Exception {
int row = scaffoldTab.getSelectedRow();
row= (row < 0)?-1:scaffoldTab.convertRowIndexToModel(row);
if (row < 0) {
JOptionPane.showMessageDialog
(this, "No scaffold selected; no image generated!",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
int htop = mview.getHeight() + 5;
int index = contentTab.getSelectedIndex();
JTable tab = rgroupTab; // the main r-group table
if (index > 0) {
JComponent c = (JComponent)contentTab.getTabComponentAt(index);
SearchRGroup rg = (SearchRGroup)
c.getClientProperty("rgroup.search");
if (rg != null) {
RGroupTable rtab = rg.getRGroupTable(getSelectedScaffold ());
if (rtab == null) {
JOptionPane.showMessageDialog
(this, "There is no such scaffold exists in "
+ rg.getName()+"!", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
tab = (JTable)c.getClientProperty("rgroup.table");
}
else {
JOptionPane.showMessageDialog
(this, "No scaffold selected; no image generated!",
"Error", JOptionPane.ERROR_MESSAGE);
return;
}
}
int width = Math.max(mview.getWidth(), tab.getWidth());
int height = htop + tab.getHeight()
+ tab.getTableHeader().getHeight();
BufferedImage img = new BufferedImage
(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
g.setPaint(Color.white);
g.fillRect(0, 0, width, height);
int x = (width - mview.getWidth())/2;
g.translate(x, 0);
mview.paint(g);
g.translate(-x, htop);
tab.getTableHeader().paint(g);
g.translate(0, tab.getTableHeader().getHeight());
tab.paint(g);
g.dispose();
ImageIO.write(img, "png", os);
}
public static void main (final String[] argv) throws Exception {
try {
UIManager.setLookAndFeel(new Plastic3DLookAndFeel());
} catch (Exception e) {}
EventQueue.invokeLater(new Runnable () {
public void run () {
RGroupWebResources web = null;
if (argv.length == 2) {
logger.info("Web Resource: host="
+argv[0]+" context="+argv[1]);
web = new RGroupWebResources (argv[0], argv[1]);
}
RGroupTool tool = new RGroupTool (web);
tool.setSize(800, 600);
tool.setVisible(true);
if (web == null && argv.length > 0) {
tool.loadFile(argv);
}
}
});
}
public static class JnlpLaunch {
public static void main (final String[] argv) throws Exception {
UnsignedWebstart = true;
try {
UIManager.setLookAndFeel(new Plastic3DLookAndFeel());
} catch (Exception e) {}
EventQueue.invokeLater(new Runnable () {
public void run () {
RGroupTool tool = new RGroupTool ();
tool.setSize(800, 600);
tool.setVisible(true);
}
});
}
}
}
|
PHP
|
UTF-8
| 1,881 | 2.671875 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php declare(strict_types = 1);
/**
* SensorRange.php
*
* @license More in LICENSE.md
* @copyright https://www.fastybird.com
* @author Adam Kadlec <adam.kadlec@fastybird.com>
* @package FastyBird:ShellyConnector!
* @subpackage Entities
* @since 1.0.0
*
* @date 18.07.22
*/
namespace FastyBird\Connector\Shelly\Entities\API\Gen1;
use FastyBird\Connector\Shelly\Entities;
use FastyBird\Connector\Shelly\Types;
use FastyBird\Library\Metadata\Types as MetadataTypes;
use Nette;
/**
* Parsed sensor range entity
*
* @package FastyBird:ShellyConnector!
* @subpackage Entities
*
* @author Adam Kadlec <adam.kadlec@fastybird.com>
*/
final class SensorRange implements Entities\API\Entity
{
use Nette\SmartObject;
/**
* @param array<string>|array<int>|array<float>|array<int, array<int, (string|array<int, string>|null)>>|array<int, (int|null)>|array<int, (float|null)>|array<int, (MetadataTypes\SwitchPayload|string|Types\RelayPayload|null)>|null $format
*/
public function __construct(
private readonly MetadataTypes\DataType $dataType,
private readonly array|null $format,
private readonly int|float|string|null $invalid,
)
{
}
public function getDataType(): MetadataTypes\DataType
{
return $this->dataType;
}
/**
* @return array<string>|array<int>|array<float>|array<int, array<int, (string|array<int, string>|null)>>|array<int, (int|null)>|array<int, (float|null)>|array<int, (MetadataTypes\SwitchPayload|string|Types\RelayPayload|null)>|null
*/
public function getFormat(): array|null
{
return $this->format;
}
public function getInvalid(): float|int|string|null
{
return $this->invalid;
}
/**
* {@inheritDoc}
*/
public function toArray(): array
{
return [
'data_type' => $this->dataType->getValue(),
'format' => $this->getFormat(),
'invalid' => $this->getInvalid(),
];
}
}
|
JavaScript
|
UTF-8
| 827 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
'use strict';
export default class RewardList {
constructor(el) {
this.el = el;
this.newClass = 'is-new';
this.removeNewSticker = this.removeNewSticker.bind(this);
[].forEach.call(this.el.querySelectorAll('.js-reward-list-item.is-new'), item => {
item.addEventListener('mouseenter', this.onMouseEnter.bind(this, item));
});
document.body.addEventListener('BALANCE_CLOSE', this.removeNewSticker);
}
onMouseEnter(item) {
item.classList.remove(this.newClass);
}
removeNewSticker() {
[].forEach.call(this.el.querySelectorAll(`.${ this.newClass }`), item => item.classList.remove(this.newClass));
}
}
document.addEventListener('DOMContentLoaded', () => {
if (document.querySelector('.js-reward-list')) {
new RewardList(document.querySelector('.js-reward-list'));
}
})
|
C#
|
UTF-8
| 3,859 | 2.953125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net.Http;
using System.Threading.Tasks;
using BoilerController.Common.Helpers;
using BoilerController.Common.Models;
using Newtonsoft.Json;
namespace BoilerController.Common.Services
{
public class BoilerServerService
{
private readonly int _devPin;
public BoilerServerService() : this(17)
{}
public BoilerServerService(int devPin)
{
_devPin = devPin;
}
/// <summary>
/// Gets the current state of the boiler
/// </summary>
/// <returns>Status object</returns>
public async Task<Status> GetCurrentStateTask()
{
var response = await NetworkHandler.GetResponseTask("getstate?dev=" + _devPin);
if(response == null || !response.IsSuccessStatusCode)
throw new HttpRequestException("Unable to connect to server.");
var content = await response.Content.ReadAsStringAsync();
var status = JsonConvert.DeserializeObject<Status>(content);
return status;
}
/// <summary>
/// Sets the state desired state
/// </summary>
/// <param name="state">true for 'on'; false for 'off'</param>
public async Task SetStateTask(bool state)
{
await NetworkHandler.GetResponseTask("setstate?dev=" + _devPin + "&state=" + (state ? "1" : "0"));
}
/// <summary>
/// Gets the list of scheduled jobs
/// </summary>
/// <returns>Observable collection of Job objects</returns>
public async Task<ObservableCollection<Job>> GetJobsTask()
{
var response = await NetworkHandler.GetResponseTask("gettimes");
if (!response.IsSuccessStatusCode)
{
throw new UnauthorizedAccessException();
}
var job = await response.Content.ReadAsStringAsync();
// Deserialize the jobs list and updat the Jobs collection
return JsonConvert.DeserializeObject<ObservableCollection<Job>>(job);
}
/// <summary>
/// Remove a job by a given ID number
/// </summary>
/// <param name="id">Job Id number</param>
/// <returns>true if successful; false otherwise.</returns>
public async Task<bool> RemoveJobTask(int id)
{
var response = await NetworkHandler.GetResponseTask("remove?id=" + id, method: "DELETE");
return await response.Content.ReadAsStringAsync() == "OK";
}
/// <summary>
/// Creates a new job and sends request to add it to the server's schedule.
/// </summary>
/// <param name="start">Starting date and time string</param>
/// <param name="end">Ending date and time string</param>
/// <param name="type">Type of job (datetime\cron)</param>
/// <param name="days">Days for cron job</param>
public async Task SetScheduledJobTask(string start, string end, string type, IEnumerable<string> days)
{
var job = JsonConvert.SerializeObject(new Job
{
Pin = _devPin,
Start = start,
End = end,
Type = type,
DaysList = days
});
if (type == "datetime")
type = "settime";
else if (type == "cron")
type = "addcron";
// Send the request to the server and in case of success update the listview
var response = await NetworkHandler.GetResponseTask(type, job, "POST");
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException("Remote operation failed.");
}
}
}
}
|
JavaScript
|
UTF-8
| 3,856 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
const path = require('path');
const https = require('https');
const fs = require('fs');
const keyword = process.argv[2]; // 搜索的正则表达式关键字
const url = 'https://raw.githubusercontent.com/any86/any-rule/master/packages/www/src/RULES.js';
function fetchData() {
return new Promise((resolve, reject) => {
https.get(url, async res => {
// 处理返回数据
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk.trim(); });
res.on('end', () => {
try {
// 获取正则表达式数据
const arrStr = rawData.split(' = ')[1].trim();
fs.writeFile('./RULES.txt', arrStr, err => {
if (err) {
reject(err);
} else {
console.log(JSON.stringify({
items: [{
title: '本地数据已经更新完成,可重新输入关键字搜索~',
subtitle: '已完成',
icon: {
path: path.join(__dirname, './icon.png'),
},
}]
}))
resolve();
}
})
} catch (e) {
reject(e.message);
}
});
})
})
}
async function readLocalFile() {
return new Promise((resolve, reject) => {
if (fs.existsSync('./RULES.txt')) {
fs.readFile('./RULES.txt', 'utf8', (err, data) => {
if (err) reject(err)
const list = eval(data);
resolve(list);
})
} else {
resolve(null);
}
})
}
async function main() {
// 指令是 zzupdate 表示手动更新数据
if (keyword == 'zzupdate') {
console.log(JSON.stringify({
items: [{
title: '1111',
subtitle: '222',
icon: {
path: path.join(__dirname, './icon.png'),
},
}]
}))
await fetchData();
} else {
const list = await readLocalFile();
if (list == null) {
console.log(JSON.stringify({
items: [{
title: '本地数据不存在,请输入 zzupdate 命令进行更新~',
subtitle: '输入完毕重新查询',
icon: {
path: path.join(__dirname, './icon.png'),
},
arg: 'zzupdate'
}]
}))
return;
}
const result = list && list.map(ele => {
return {
title: ele.title,
subtitle: '' + ele.rule,
icon: {
path: path.join(__dirname, './icon.png'),
},
arg: '' + ele.rule,
}
}).filter(ele => {
return ele.title.indexOf(keyword) > -1;
}) || []
if (result && result.length === 0) {
console.log(JSON.stringify({
items: [{
title: '未找到符合要求的结果~',
subtitle: '请重新选择关键字,或者更新本地数据源再试试~',
icon: {
path: path.join(__dirname, './icon.png'),
},
}]
}))
} else {
console.log(JSON.stringify({
items: result
}))
}
}
}
main();
|
C
|
UTF-8
| 2,394 | 2.671875 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_condition.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gquerre <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/06/20 07:44:08 by gquerre #+# #+# */
/* Updated: 2017/10/10 05:27:11 by gquerre ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_printf.h"
int ft_doub(char *str, char c, t_env *e)
{
int i;
i = 0;
if (e->h > 1 || e->h < 0 || e->l > 1 || e->l < 0)
{
if (e->h > 1)
e->h = -1;
if (e->l > 1)
e->l = -1;
return (-1);
}
if ((c == 'h' && e->h == 1) || (c == 'l' && e->l == 1))
{
if (str[i + 1] != c)
return (-1);
else
return (2);
}
return (1);
}
void ft_condition3(char str, t_env *e)
{
if (str == 'j')
e->j += 1;
if (str == 'z')
e->z += 1;
}
void ft_condition2(char *str, t_env *e)
{
int i;
int k;
i = 0;
if (ft_precision(&str[i], e) < 0)
e->error = 1;
while (str[i] != '%' && !(ft_isdigit(str[i])))
{
ft_condition3(str[i], e);
if (str[i] == 'h')
e->h = ft_doub(&str[i], str[i], e);
if (str[i] == 'l')
e->l = ft_doub(&str[i], str[i], e);
i--;
}
k = (e->condi == '%' && str[i] == '%') ? -1 : 0;
while (str[i + k] != '%')
k--;
ft_signs(&str[i + k + 1], e);
}
int ft_condition(char *str, t_env *e, int check)
{
int i;
i = 0;
e->size_arg = 0;
if (str[i] == 's' || str[i] == 'S' || str[i] == 'd' || str[i] == 'b'
|| str[i] == 'p' || str[i] == 'O' || str[i] == 'o'
|| str[i] == 'i' || str[i] == 'D' || str[i] == '%'
|| str[i] == 'x' || str[i] == 'X' || str[i] == 'u'
|| str[i] == 'U' || str[i] == 'c' || str[i] == 'C')
{
e->condi = str[i];
if (check == 1)
{
ft_condition2(str, e);
if (e->h < 0 || e->l < 0)
return (-4);
if (e->size_arg - ft_somme_option(e) != 0)
{
return (-6);
}
}
return (1);
}
return (0);
}
|
Swift
|
UTF-8
| 802 | 3.46875 | 3 |
[] |
no_license
|
//
// Reorder.swift
// DSAlgo
//
// Created by Shilpa M on 15/06/21.
//
//1->2->3->4->nil
//Reord to
//1->4->2->3->nil
//get to middle of the list and saperate it
// 1-> 2
// 3->4
// reverse the second list
//4->3
// merge 1st and 2nd list
func reorderList(_ node : NodeL) {
if node == nil || node.next == nil {
return
}
//head of first half
var l1 : NodeL = node
//head of second half
var slow : NodeL = node
//tail of second half
var fast : NodeL = node
//tail of first half
var prev : NodeL? = nil
while fast.next != nil && fast != nil {
prev = slow
slow = slow.next!
fast = (fast.next?.next)!
}
prev!.next = nil
//var l2 = reverseLinkedList(head: slow)
//merge(l1,l2)
}
|
Python
|
UTF-8
| 596 | 2.6875 | 3 |
[
"Apache-2.0"
] |
permissive
|
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from classes.Price_Bond_Regular import PriceBondRegular
def test_px_bond_reg_one():
test = PriceBondRegular(9, 20, 6, 12, 1000)
assert round(test.calculate()) == 774, "Should be $774"
def test_px_bond_price():
sample = PriceBondRegular(5.75, 1.5, 6, 0.093691, 100)
assert round(sample.price_bond()) == 95, "Should be $95"
def test_px_bond_price():
sample = PriceBondRegular(5.75, 1.5, 12, 0.093691, 100)
assert round(sample.price_bond()) == 22, "Should be 22"
|
Python
|
UTF-8
| 579 | 3.453125 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
# @Time : 2019/11/18 15:45
# @Author : 赵金林
# @Site :
# @File : test.py
import sys
# line = sys.stdin.readline().strip()
# print(line) # 输出的字符串
#
# n = int(input())
# print(n) # 输出为数字
#
# l = list(map(int, input().split(" ")))
# print(l) # 单行输入输出为数组
if __name__ == "__main__":
data = []
while True:
line = sys.stdin.readline().strip()
if not line:
break
tmp = list(map(int, line.split(" ")))
data.append(tmp)
print(data) # 输出形式为矩阵
|
C#
|
UTF-8
| 220 | 3.09375 | 3 |
[] |
no_license
|
public static void Main()
{
C c = new C();
var a = c;
Console.WriteLine(a.GetType()); // It still is of `C` type
a.Show(); // Prints out "C.Show"
c.Show(); // Prints out "C.Show"
Console.ReadLine();
}
|
C#
|
UTF-8
| 8,718 | 3.203125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataManager;
using Scene;
namespace IO
{
class GetValue
{
public static int GetIntAnswer(string question, int min, int max)
{
string strAnswer;
int intAnswer;
string errorMessage;
StringBuilder errorMessageBldr = new StringBuilder("Please enter a number between ");
errorMessageBldr.AppendFormat("{0} and {1}", min.ToString(), max.ToString());
errorMessage = errorMessageBldr.ToString();
while (true)
{
Console.Write(String.Format("{0," + ((Console.WindowWidth / 2) + ((question.Length - 3) / 2)) + "}", question));
strAnswer = Console.ReadLine();
Int32.TryParse(strAnswer, out intAnswer);
if (intAnswer >= min && intAnswer <= max) break;
else Print.Error(errorMessage);
}
return intAnswer;
}
public static void USettingInfo()
{
string contents = "[User Information] ";
string name1 = "Name of Player 1 : ";
string name2 = "Name of Palyer 2 : ";
string stone1 = "Stone of Player 1 : ";
string stone2 = "Stone of Player 2 : ";
string question = "Who's ganna first(1/2)? ";
string userName1, userName2;
char userStone1, userStone2;
int firstPlayer;
PlayerInfo player1 = new PlayerInfo();
PlayerInfo player2 = new PlayerInfo();
Console.WriteLine(String.Format("\n\n{0," + ((Console.WindowWidth / 2) + (contents.Length / 2)) + "}", contents));
Console.WriteLine();
Console.WriteLine();
userName1 = GetName(name1);
Console.WriteLine();
userStone1 = GetStone(stone1);
Console.WriteLine();
userName2 = GetName(name2, userName1);
Console.WriteLine();
userStone2 = GetStone(stone2, userStone1);
Console.WriteLine();
Console.WriteLine();
firstPlayer = GetIntAnswer(question,1, 2);
if (firstPlayer == 1)
{
player1.Player(userName1, userStone1, 1);
player2.Player(userName2, userStone2, 2);
}
else
{
player1.Player(userName1, userStone1, 2);
player2.Player(userName2, userStone2, 1);
}
UvsUGame.Game(player1, player2);
}
public static void CSettingInfo()
{
string content1 = "[User Information] ";
string name = "Name of Player : ";
string stone = "Stone of Palyer : ";
string content2 = "[Your Oppenent] ";
string computer = "1. Idiot(I) 2. Genius(G)";
string question1 = "Who's your oppenent? ";
string question2 = "Who's ganna first(1/2)? ";
string userName;
char userStone;
int computerType;
int firstPlayer;
PlayerInfo player1 = new PlayerInfo();
PlayerInfo player2 = new PlayerInfo();
Console.WriteLine(String.Format("\n{0," + ((Console.WindowWidth / 2) + (content1.Length / 2)) + "}", content1));
Console.WriteLine();
userName = GetName(name);
Console.WriteLine();
userStone = GetStone(stone);
Console.WriteLine(String.Format("\n\n{0," + ((Console.WindowWidth / 2) + (content2.Length / 2)) + "}", content2));
Console.WriteLine(String.Format("\n{0," + ((Console.WindowWidth / 2) + (computer.Length / 2)) + "}", computer));
Console.WriteLine();
computerType = GetIntAnswer(question1, 1, 2);
Console.WriteLine();
firstPlayer = GetIntAnswer(question2, 1, 2);
if (firstPlayer == 1)
{
player1.Player(userName, userStone, 1);
if (computerType == 1) player2.Player("Idiot", 'I', 2);
else player2.Player("Genius", 'G', 2);
}
else
{
player1.Player(userName, userStone, 2);
if (computerType == 1) player2.Player("Idiot", 'I', 1);
else player2.Player("Genius", 'G', 1);
}
UvsCGame.Game(player1, player2);
}
public static string GetName(string question)
{
string name;
string errorMessage = "Please enter within 15 characters";
while (true)
{
Console.Write(String.Format("{0," + ((Console.WindowWidth / 2) + ((question.Length - 3) / 2)) + "}", question));
name = Console.ReadLine();
if (name.Length > 15 || name.Length == 0) Print.Error(errorMessage);
else break;
}
return name;
}
public static string GetName(string question, string player1)
{
string name;
string errorMessage = "Please enter within 15 characters";
string overlapErrorMessage = "Please enter a different name from Player 1";
while (true)
{
Console.Write(String.Format("{0," + ((Console.WindowWidth / 2) + ((question.Length - 3) / 2)) + "}", question));
name = Console.ReadLine();
if (name.Length > 15 || name.Length == 0) Print.Error(errorMessage);
else if (name == player1) Print.Error(overlapErrorMessage);
else break;
}
return name;
}
public static char GetStone(string question)
{
string strStone;
char charStone;
string errorMessage = "Please enter 1 character for stone";
string overlapErrormessage = "Please enter 1 character except circle character";
while (true)
{
Console.Write(String.Format("{0," + ((Console.WindowWidth / 2) + ((question.Length - 3) / 2)) + "}", question));
strStone = Console.ReadLine();
if (strStone.Length > 1 || strStone.Length == 0) Print.Error(errorMessage);
else if (strStone[0] >= '①' && strStone[0] <= '⑨') Print.Error(overlapErrormessage);
else break;
}
charStone = strStone[0];
return charStone;
}
public static char GetStone(string question, char player1)
{
string strStone;
char charStone;
string errorMessage = "Please enter 1 character for stone";
string overlapErrormessage = "Please enter 1 character except circle character";
string overlapErrormessage1 = "Please enter 1 character different from player 1's";
while (true)
{
Console.Write(String.Format("{0," + ((Console.WindowWidth / 2) + ((question.Length - 3) / 2)) + "}", question));
strStone = Console.ReadLine();
if (strStone.Length > 1 || strStone.Length == 0) Print.Error(errorMessage);
else if (strStone[0] >= '①' && strStone[0] <= '⑨') Print.Error(overlapErrormessage);
else if (strStone[0] == player1) Print.Error(overlapErrormessage1);
else break;
}
charStone = strStone[0];
return charStone;
}
public static char GetStone(string question, char idiot, char genius)
{
string strStone;
char charStone;
string errorMessage = "Please enter 1 character for stone";
string overlapErrormessage = "Please enter 1 character except circle character";
string overlapErrormessage1 = "Please enter 1 character different from computer";
while (true)
{
Console.Write(String.Format("{0," + ((Console.WindowWidth / 2) + ((question.Length - 3) / 2)) + "}", question));
strStone = Console.ReadLine();
if (strStone.Length > 1 || strStone.Length == 0) Print.Error(errorMessage);
else if (strStone[0] >= '①' && strStone[0] <= '⑨') Print.Error(overlapErrormessage);
else if (strStone[0] == idiot || strStone[0] == genius) Print.Error(overlapErrormessage1);
else break;
}
charStone = strStone[0];
return charStone;
}
}
}
|
Python
|
UTF-8
| 382 | 3.171875 | 3 |
[] |
no_license
|
#Euler Project 72
#Thinginitself
import math
fac = [0] * 10 ** 7
f = [0] * 10 ** 7
def getEulerfuc(size):
for i in xrange(2,size):
if fac[i]!=0:
tmp = i/fac[i]
if tmp%fac[i]==0:
f[i] = f[tmp]*fac[i]
else:
f[i] = f[tmp]*(fac[i]-1)
else:
f[i] = i-1
for j in xrange(i*i,size,i):
if fac[j]==0:
fac[j] = i
getEulerfuc(10 ** 6 + 1)
print sum(f)
|
Java
|
UTF-8
| 1,640 | 2.484375 | 2 |
[] |
no_license
|
package edu.sdsu.cs.ramya.ratetheinstructor;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by sarathbollepalli on 2/27/15.
*/
public class CustomAdapter extends ArrayAdapter{
private ArrayList<Comment> comments;
public CustomAdapter(Context context,ArrayList<Comment> objects) {
super(context,R.layout.comments_list_row,objects);
this.comments=objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null)
{
LayoutInflater inflater=(LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.comments_list_row,parent,false);
TextView date=(TextView)convertView.findViewById(R.id.dateTextView);
TextView comment=(TextView)convertView.findViewById(R.id.commentTextView);
comment.setText(comments.get(position).getComment());
date.setText(comments.get(position).getDate());
}
else {
TextView date=(TextView)convertView.findViewById(R.id.dateTextView);
TextView comment=(TextView)convertView.findViewById(R.id.commentTextView);
comment.setText(comments.get(position).getComment());
date.setText(comments.get(position).getDate());
}
return convertView;
}
}
|
Swift
|
UTF-8
| 4,672 | 2.765625 | 3 |
[] |
no_license
|
//
// DetailsView.swift
// ClaroChallenge
//
// Created by Andre Luis Campopiano on 26/06/2018.
// Copyright © 2018 Andre Luis Campopiano. All rights reserved.
//
import UIKit
class DetailsView: UIView {
@IBOutlet weak var bannerImage: UIImageView?
@IBOutlet weak var titleLabel: UILabel?
@IBOutlet weak var genreLabel: UILabel?
@IBOutlet weak var posterImage: UIImageView?
@IBOutlet weak var descriptionLabel: UILabel?
@IBOutlet weak var dateLabel: UILabel?
@IBOutlet weak var loadingView: UIView?
@IBOutlet weak var activityIndicator: UIActivityIndicatorView?
/// fill Screen with movie
///
/// - Parameter movie: movie object
func fillScreen(movie: Movie) {
loadBanner(url: movie.backdropPath)
loadPoster(url: movie.posterPath)
loadDate(movie.releaseDate)
loadGenres(movie.genres, runtime: movie.runtime)
if let title = movie.title {
titleLabel?.text = title
}
if let description = movie.overview {
descriptionLabel?.text = description
if description.isEmpty {
descriptionLabel?.text = LocalizableStrings.notSupportLanguage.localize()
}
descriptionLabel?.sizeToFit()
}
showLoading(false)
}
/// Show loading view
///
/// - Parameter show: show or hide
func showLoading(_ show: Bool) {
if show {
loadingView?.isHidden = false
activityIndicator?.startAnimating()
} else {
loadingView?.isHidden = true
activityIndicator?.stopAnimating()
}
}
private func loadPoster(url: String?) {
let placeholder = UIImage(named: "claquete")
self.posterImage?.image = placeholder
self.posterImage?.contentMode = .center
if let posterPath = url {
let url = URL(string: ApiProvider.posterBaseUrl + posterPath)
self.posterImage?.kf.setImage(with: url,
placeholder: placeholder,
completionHandler: { [weak self] (image, _, _, _) in
guard let _self = self else { return }
if image != nil {
_self.posterImage?.contentMode = .scaleAspectFill
}
})
}
}
private func loadBanner(url: String?) {
let placeholder = UIImage(named: "claquete")
self.bannerImage?.image = placeholder
self.bannerImage?.contentMode = .center
if let bannerPath = url {
let url = URL(string: ApiProvider.bannerBaseUrl + bannerPath)
self.bannerImage?.kf.setImage(with: url,
placeholder: placeholder,
completionHandler: { [weak self] (image, _, _, _) in
guard let _self = self else { return }
if image != nil {
_self.bannerImage?.contentMode = .scaleAspectFill
}
})
}
}
private func loadDate(_ date: String?) {
if let release = date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if let date = dateFormatter.date(from: release) {
dateFormatter.dateFormat = "yyyy"
let formatedRelease = dateFormatter.string(from: date)
dateLabel?.text = formatedRelease
}
}
}
private func loadGenres(_ genres: [Genre]?, runtime: Int?) {
var genresString = ""
var runtimeString = ""
if let genres = genres {
genresString = genres.compactMap({ (gnr) -> String? in
gnr.name
}).joined(separator: ", ")
}
if let runtime = runtime {
runtimeString = String(describing: runtime)
if runtimeString.count > 0 && genresString.count > 0 {
runtimeString = "\(runtimeString)m | "
} else if runtimeString.count > 0 {
runtimeString = "\(runtimeString)m"
}
}
self.genreLabel?.text = "\(runtimeString)\(genresString)"
}
}
|
Java
|
UTF-8
| 197 | 2.1875 | 2 |
[] |
no_license
|
package com.excepciones.Factura;
public class InsertandoFacturaException extends Exception{
public InsertandoFacturaException(){
super("Ha ocurrido un error ingresando factura");
}
}
|
SQL
|
UTF-8
| 787 | 3.53125 | 4 |
[] |
no_license
|
SELECT * FROM PRODUCT
LEFT JOIN VINYL_PRODUCT
ON VINYL_PRODUCT.VINYLPRODUCT_ID = PRODUCT.PRODUCT_ID
LEFT JOIN CD_PRODUCT
ON CD_PRODUCT.CDPRODUCT_ID = PRODUCT.PRODUCT_ID
LEFT JOIN ALBUM_MP3_PRODUCT
ON ALBUM_MP3_PRODUCT.ALBUM_MP3_PRODUCT_ID = PRODUCT.PRODUCT_ID
LEFT JOIN TRACK_MP3_PRODUCT
ON TRACK_MP3_PRODUCT.TRACK_MP3_PRODUCT_ID = PRODUCT.PRODUCT_ID
LEFT JOIN ALBUM_VINYL
ON VINYL_PRODUCT.VINYL_ID = ALBUM_VINYL.VINYL_ID
LEFT JOIN ALBUM_CD
ON CD_PRODUCT.CD_ID = ALBUM_CD.CD_ID
LEFT JOIN ALBUM_MP3
ON ALBUM_MP3_PRODUCT.MP3_ID = ALBUM_MP3.MP3_ID
LEFT JOIN TRACK_MP3
ON TRACK_MP3_PRODUCT.MP3_ID = TRACK_MP3.MP3_ID
LEFT JOIN ALBUM
ON ALBUM_CD.ALBUM_ID = ALBUM.ALBUM_ID
LEFT JOIN ALBUM_CD
AS ALBUM2 ON ALBUM_VINYL.ALBUM_ID
LEFT JOIN ALBUM
AS ALBUM3 ON ALBUM_MP3.ALBUM_ID
GROUP BY PRODUCT_ID;
|
C++
|
UTF-8
| 2,677 | 2.875 | 3 |
[] |
no_license
|
#include "PLCValueEvent.hpp"
#define PLCValueEvent_Constructor(name,littletype,valuetype) \
PLCValueEvent PLCValueEvent::name(littletype value)\
{\
union PLCValue data;\
data.valuetype = value;\
struct timeval tv;\
gettimeofday(&tv, NULL);\
struct PLCTime time = PLCValueEvent::TimevalToTime(tv);\
return PLCValueEvent(data, time);\
}\
PLCValueEvent PLCValueEvent::name(littletype value, struct PLCTime time)\
{\
union PLCValue data;\
data.valuetype = value;\
return PLCValueEvent(data, time);\
}
PLCValueEvent_Constructor(FromBool, bool, v_bool)
PLCValueEvent_Constructor(FromBit, bool, v_bool)
PLCValueEvent_Constructor(FromByte, uint_fast8_t, v_byte)
PLCValueEvent_Constructor(FromInt, int_fast32_t, v_int)
PLCValueEvent_Constructor(FromUInt, uint_fast32_t, v_uint)
PLCValueEvent_Constructor(FromLong, int_fast64_t, v_long)
PLCValueEvent_Constructor(FromULong, uint_fast64_t, v_ulong)
PLCValueEvent_Constructor(FromFloat, float, v_float)
PLCValueEvent_Constructor(FromDouble, double, v_double)
struct PLCTime PLCValueEvent::getTime() const
{
return this->time;
}
bool PLCValueEvent::isValid() const
{
return this->getTime().sec > 0;
}
struct PLCTime PLCValueEvent::TimevalToTime(struct timeval time)
{
struct PLCTime plctime{uint_fast64_t(time.tv_sec), uint_fast32_t(time.tv_usec)};
return plctime;
}
struct PLCTime PLCValueEvent::earliest(const PLCValueEvent event1, const PLCValueEvent event2)
{
return event1.getTime() | event2.getTime();
}
struct PLCTime PLCValueEvent::latest(const PLCValueEvent event1, const PLCValueEvent event2)
{
return event1.getTime() & event2.getTime();
}
bool PLCValueEvent::getBool() const { return this->data.v_bool; }
bool PLCValueEvent::getBit() const { return this->data.v_bool; }
uint_fast8_t PLCValueEvent::getByte() const { return this->data.v_byte; }
int_fast32_t PLCValueEvent::getInt() const { return this->data.v_int; }
uint_fast32_t PLCValueEvent::getUInt() const { return this->data.v_uint; }
int_fast64_t PLCValueEvent::getLong() const { return this->data.v_long; }
uint_fast64_t PLCValueEvent::getULong() const { return this->data.v_ulong; }
float PLCValueEvent::getFloat() const { return this->data.v_float; }
double PLCValueEvent::getDouble() const { return this->data.v_double; }
bool PLCValueEvent::operator ==(const PLCValueEvent &b) const { return getULong() == b.getULong(); }
bool PLCValueEvent::operator !=(const PLCValueEvent &b) const { return !(*this == b); }
PLCValueEvent::PLCValueEvent(): data(), time({0, 0}) { }
PLCValueEvent::PLCValueEvent(union PLCValue _value, struct PLCTime _time): data(_value), time(_time) { }
|
Java
|
UTF-8
| 417 | 2.40625 | 2 |
[] |
no_license
|
package top.kanetah.planH.info;
/**
* created by kane on 2017/08/11
*
* 信息报表枚举类接口
*/
public interface InfoEnumInterface {
/**
* 执行信息类的一个方法
* @param object 被执行的信息类对象
* @return 返回值
*/
Object invokeMargetMethod(Object object);
/**
* 获取枚举值
*
* @return 枚举值
*/
String getValue();
}
|
C#
|
UTF-8
| 3,309 | 3.640625 | 4 |
[] |
no_license
|
using System;
namespace LeetCodeNote.Array
{
/// <summary>
/// 1385. 两个数组间的距离值
/// https://leetcode-cn.com/problems/find-the-distance-value-between-two-arrays/
/// </summary>
public class Solution_1385
{
// method 1
// 暴力
public int FindTheDistanceValue_0(int[] arr1, int[] arr2, int d)
{
int res = 0;
foreach (var a in arr1)
{
bool isAllOk = true;
foreach (var b in arr2)
{
if (Math.Abs(a - b) <= d)
{
isAllOk = false;
break;
}
}
if (isAllOk)
{
res++;
}
}
return res;
}
// method 2
// 二分查找
public int FindTheDistanceValue_1(int[] arr1, int[] arr2, int d)
{
int res = 0;
System.Array.Sort(arr2);
foreach (var a in arr1)
{
int neiLeft = FindNeighbourLeft(arr2, a);
int neiRight = FindNeighbourRight(arr2, a);
if (neiLeft == -1 && Math.Abs(a - neiRight) > d)
{
// 找不到比a更小的,说明a就是最小的
res++;
continue;
}
if (neiRight == -1 && Math.Abs(a - neiLeft) > d)
{
// 找不到比a更大的,说明a就是最大的
res++;
continue;
}
if (Math.Abs(a - neiLeft) > d && Math.Abs(a - neiRight) > d)
{
res++;
}
}
return res;
}
public int FindNeighbourLeft(int[] arr, int k)
{
int left = 0;
int right = arr.Length - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] < k )
{
if (mid == arr.Length - 1 || arr[mid + 1] >= k )
{
return arr[mid];
}
else
{
left = mid + 1;
}
}
else
{
right = mid - 1;
}
}
return -1;
}
public int FindNeighbourRight(int[] arr, int k)
{
int left = 0;
int right = arr.Length - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] >= k)
{
if (mid == 0 || arr[mid - 1] < k)
{
return arr[mid];
}
else
{
right = mid - 1;
}
}
else
{
left = mid + 1;
}
}
return -1;
}
}
}
|
PHP
|
UTF-8
| 2,442 | 3.28125 | 3 |
[] |
no_license
|
<?php
class Database
{
private $connection;
/**
* Database constructor.
*
* Baut die Verbindung zur Datenbank auf
*/
public function __construct()
{
// MySQL-Zugangsdaten
// Hier: Automatisch auslesen aus .my.cnf. Sonst einfach von Hand eintragen
$user = get_current_user(); // Benutzer, dem diese Datei gehört!
$myCnf = parse_ini_file("/home/$user/.my.cnf");
$host = $myCnf['host'];
$user = $myCnf['user'];
$password = $myCnf['password'];
$database = $myCnf['database'];
$this->connection = new mysqli($host, $user, $password, $database);
}
/**
* Schließt die Verbindung zru Datenbank
*/
public function __destruct()
{
$this->connection->close();
}
public function addQuestion($question, $answer0, $answer1, $answer2, $solution)
{
$statement = $this->connection->prepare("INSERT INTO questions(question,answer0,answer1,answer2,solution) VALUES(?,?,?,?,?)");
$statement->bind_param("ssssi", $question, $answer0, $answer1, $answer2, $solution);
return $statement->execute();
}
public function deleteQuestions($id)
{
$statement = $this->connection->prepare("DELETE FROM questions WHERE id = ?");
$statement->bind_param("i", $id);
return $statement->execute();
}
public function editQuestions($id, $question, $answer0, $answer1, $answer2, $solution)
{
$statement = $this->connection->prepare("UPDATE questions SET question = ?, answer0 = ?, answer1 = ?, answer2 = ?, solution = ? WHERE id = ?");
$statement->bind_param("ssssii", $question, $answer0, $answer1, $answer2, $solution, $id);
return $statement->execute();
}
public function getQuestions()
{
$result = $this->connection->query("SELECT * FROM questions");
$resultArray = [];
while ($line = $result->fetch_assoc()) {
array_push($resultArray, $line);
}
$result->free();
return $resultArray;
}
public function getQuestion($id)
{
$statement = $this->connection->prepare("SELECT * FROM questions WHERE id = ?");
$statement->bind_param("i", $id);
$statement->execute();
return $statement->get_result()->fetch_assoc();
}
}
|
Markdown
|
UTF-8
| 2,256 | 3.484375 | 3 |
[] |
no_license
|
# 长期分支
----
因为 Git 使用简单的三方合并,所以就算在一段较长的时间内,反复把一个分支合并入另一个分支,也不是什 么难事。 也就是说,在整个项目开发周期的不同阶段,你可以同时拥有多个开放的分支;你可以定期地把某些 特性分支合并入其他分支中。
许多使用 Git 的开发者都喜欢使用这种方式来工作,比如只在 `master` 分支上保留完全稳定的代码——有可能仅 仅是已经发布或即将发布的代码。 他们还有一些名为 `develop` 或者 `next` 的平行分支,被用来做后续开发或者 测试稳定性——这些分支不必保持绝对稳定,但是一旦达到稳定状态,它们就可以被合并入 `master `分支了。 这 样,在确保这些已完成的特性分支(短期分支,比如之前的` iss53` 分支)能够通过所有测试,并且不会引入更 多 bug 之后,就可以合并入主干分支中,等待下一次的发布。
事实上我们刚才讨论的,是随着你的提交而不断右移的指针。 稳定分支的指针总是在提交历史中落后一大截, 而前沿分支的指针往往比较靠前。
<div align="center"> ![][image-1]
<div align="center"> Figure 26. 渐进稳定分支的线性图
通常把他们想象成流水线(work silos)可能更好理解一点,那些经过测试考验的提交会被遴选到更加稳定的流水线上去 。
<div align="center"> ![][image-2]
<div align="center"> Figure 27. 渐进稳定分支的流水线(“silo”)视图
你可以用这种方法维护不同层次的稳定性。 一些大型项目还有一个 `proposed`(建议) 或 `pu: proposed updates`(建议更新)分支,它可能因包含一些不成熟的内容而不能进入 `next` 或者 `master` 分支。 这么做的 目的是使你的分支具有不同级别的稳定性;当它们具有一定程度的稳定性后,再把它们合并入具有更高级别稳定 性的分支中。 再次强调一下,使用多个长期分支的方法并非必要,但是这么做通常很有帮助,尤其是当你在一 个非常庞大或者复杂的项目中工作时。
[image-1]: ../image/3/26.png
[image-2]: ../image/3/27.png
|
Java
|
UTF-8
| 1,432 | 2.234375 | 2 |
[] |
no_license
|
package org.molsbee.movie.model.web;
import lombok.Data;
import org.molsbee.movie.model.database.Movie;
import org.molsbee.movie.omdb.Type;
import java.util.List;
@Data
public class CreateMovieRequest {
private String title;
private String year;
private String rating;
private String releaseDate;
private String runtime;
private List<String> genres;
private String director;
private String writer;
private List<String> actors;
private String plot;
private String language;
private String country;
private String awards;
private String poster;
private String metascore;
private String imdbRating;
private String imdbVotes;
private String imdbID;
private String type;
public Movie toMovie() {
return Movie.builder()
.title(title)
.year(year)
.rating(rating)
.releaseDate(releaseDate)
.runtime(runtime)
.director(director)
.writer(writer)
.plot(plot)
.language(language)
.country(country)
.awards(awards)
.poster(poster)
.metascore(metascore)
.imdbRating(imdbRating)
.imdbVotes(imdbRating)
.imdbID(imdbID)
.type(Type.fromString(type))
.build();
}
}
|
C++
|
UTF-8
| 852 | 2.90625 | 3 |
[] |
no_license
|
#include <vector>
#include <chrono>
#include <algorithm>//修正点1
#include "number.h"
using namespace std;
using namespace std::chrono;
int main() {
auto t0 = high_resolution_clock::now();
const int N = 400000;
vector<int> primes;
#pragma omp parallel //修正点2
#pragma omp for schedule(dynamic, 1000) //修正点3
//#pragma omp parallel for schedule(dynamic, 1000)//1行にまとめてもOK
for (int n = 2; n <= N; ++n) {
if (isPrime(n)) {
#pragma omp critical//修正点4
primes.push_back(n);
}
}
cout << "素数の数:" << primes.size() << endl;
sort(primes.begin(), primes.end());//修正点5
report(primes.cbegin(), primes.cend());
auto t1 = high_resolution_clock::now();
cout << duration_cast<milliseconds>(t1 - t0).count() / 1000. << " 秒\n";
}
|
C++
|
GB18030
| 371 | 2.53125 | 3 |
[] |
no_license
|
#include"event.h"
#include"../../render/render.h"
//(뵱ǰڵĹϵ˵)
class EventMouse:public Event
{
public:
//λ
MOUSEMSG m;
//ϵвʱд
EventMouse(MOUSEMSG m);
MOUSEMSG getMouse();
Vec2 getPosition(){ return Vec2(m.x,m.y);}
static EventMouse* create(MOUSEMSG m);
};
|
C++
|
UTF-8
| 1,126 | 2.59375 | 3 |
[] |
no_license
|
//
// Created by munk on 15-02-17.
//
#ifndef CLIENT_SERVER_SOCKET_TCPSERVER_H
#define CLIENT_SERVER_SOCKET_TCPSERVER_H
#define QUEUESIZE 4
#include <iostream>
#include <netdb.h>
#include <sys/socket.h>
class TCPServer {
public:
/*!
* Setup constants
*/
TCPServer();
/*!
* Setup the server
* @return 0 on success or the standard error (-1)
*/
int initServer();
/*!
* Run in while loop, accept connections and handle the request
*/
void acceptConnection();
/*!
* Local method for getting files that can be send over the tcp connection
* @param buf Where to store the filenames
*/
size_t getFilesOnServer(char ***buf, const char location[], const struct sockaddr *dest_addr,
socklen_t dest_len, int dest_fd);
size_t sendFile(int dest_fd, const struct sockaddr *dest_addr, socklen_t dest_len, const char location[]);
private:
int serverSocket;
const char *IPAddr;
const char *PortNr;
struct addrinfo hints;
struct addrinfo *serverinfo;
};
#endif //CLIENT_SERVER_SOCKET_TCPSERVER_H
|
Markdown
|
UTF-8
| 729 | 2.734375 | 3 |
[
"Apache-2.0"
] |
permissive
|
# ams-cfn-lint-custom-rules
CFN Lint custom rules to validate CFN templates for ingestion into AWS Managed Services (AMS). The rules are used in combination with [CloudFormation Linter package](https://github.com/aws-cloudformation/cfn-python-lint) and will help you determine if your custom CloudFormation template can be ingested into an AMS managed account (using AMS Advanced).
## How to use it
1. Install AWS CloudFormation Linter using the instructions [here](https://github.com/aws-cloudformation/cfn-lint#aws-cloudformation-linter).
2. Download the rules folder in this repository and remember the path for next step.
3. Run as `cfn-lint --template your_template.yaml --append-rules your_directory_with_custom_rules`.
|
JavaScript
|
UTF-8
| 442 | 3.6875 | 4 |
[] |
no_license
|
function nome(numero1, numero2, numero3){
if(numero1>numero2){
if(numero1>numero3){
return numero1
} else{
return numero3
}
} else{
if(numero2>numero3){
return numero2
} else{
return numero3
}
}
}
var numero1= prompt();
var numero2= prompt();
var numero3= prompt();
var resposta= nome(numero1, numero2, numero3);
alert(resposta);
|
Java
|
GB18030
| 9,772 | 1.703125 | 2 |
[] |
no_license
|
package com.sino.soa.td.srv.assetretire.servlet;
import com.sino.ams.bean.OrgOptionProducer;
import com.sino.ams.newasset.constant.AssetsWebAttributes;
import com.sino.ams.system.user.dto.SfUserDTO;
import com.sino.base.constant.db.QueryConstant;
import com.sino.base.db.conn.DBManager;
import com.sino.base.dto.Request2DTO;
import com.sino.base.exception.DTOException;
import com.sino.base.exception.PoolPassivateException;
import com.sino.base.exception.TimeException;
import com.sino.base.message.Message;
import com.sino.base.util.StrUtil;
import com.sino.base.web.ServletForwarder;
import com.sino.framework.security.bean.SessionUtil;
import com.sino.framework.servlet.BaseServlet;
//import com.sino.soa.mis.srv.assetretire.srv.TransRetiredAssetDetailSrv;
import com.sino.soa.common.SrvReturnMessage;
import com.sino.soa.common.SrvType;
import com.sino.soa.common.SrvURLDefineList;
import com.sino.soa.common.SrvWebActionConstant;
import com.sino.soa.td.srv.assetretire.dto.TDSrvRetiredAssetDTO; //ʲ״̬
import com.sino.soa.util.SynLogUtil;
import com.sino.soa.util.SynUpdateDateUtils;
import com.sino.soa.util.dto.SynLogDTO;
import com.sino.soa.td.srv.assetretire.srv.TDTransRetiredAssetDetailSrv; //TD
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.datatype.DatatypeConfigurationException;
import java.io.IOException;
import java.sql.Connection;
/**
* User: wangzhipeng
* Date: 2011-10-09
* Function:ʲϢȡ_TDODI
*/
public class TDTransRetiredAssetDetailServlet extends BaseServlet {
public void performTask(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String forwardURL = "";
Message message = SessionUtil.getMessage(req);
Connection conn = null;
int count = 0;
int errerCount = 0;
long resumeTime = 0;
try {
conn = getDBConnection(req);
SfUserDTO user = (SfUserDTO) SessionUtil.getUserAccount(req);
Request2DTO req2DTO = new Request2DTO();
req2DTO.setDTOClassName(TDSrvRetiredAssetDTO.class.getName());
TDSrvRetiredAssetDTO dtoParameter = (TDSrvRetiredAssetDTO) req2DTO.getDTO(req);
String action = dtoParameter.getAct();
message = new Message();
String assetsType = StrUtil.nullToString(req.getParameter("assetsType"));
String range = assetsType.equals("TD") ? "Y" : "N";
dtoParameter.setAssetsType(assetsType);
OrgOptionProducer optProducer = new OrgOptionProducer(user, conn);
String opt = optProducer.getBookTypeCodeOption(dtoParameter.getBookTypeCode(), range);
dtoParameter.setOrgOption(opt);
if (action.equals("")) {
req.setAttribute(QueryConstant.QUERY_DTO, dtoParameter);
forwardURL = SrvURLDefineList.TD_SRV_TRANS_RETIRED_PAGE;
} /*else if (action.equals(SrvWebActionConstant.INFORSYN) && !AssetsWebAttributes.TD_ASSETS_TYPE.equals(assetsType)) { //TD
req.setAttribute(QueryConstant.QUERY_DTO, dtoParameter);
long start = System.currentTimeMillis();
SynLogDTO logDTO = null;
SynLogUtil logUtil = new SynLogUtil();
logDTO = new SynLogDTO();
logDTO.setSynType(SrvType.SRV_FA_RETIRE);
logDTO.setCreatedBy(user.getUserId());
logDTO.setSynMsg("ͬʲʼ");
logUtil.synLog(logDTO, conn);
String envCode = SynUpdateDateUtils.getEnvCode("TransRetiredAssetDetailSrv", conn); //
TransRetiredAssetDetailSrv srv = new TransRetiredAssetDetailSrv();
srv.setEnvCode(envCode);
srv.setBookTypeCode(dtoParameter.getBookTypeCode());
srv.setStartRetireDate(dtoParameter.getDateEffectiveFrom());
srv.setStartRetireDate(dtoParameter.getDateRettredFrom());
srv.setEndRetireDate(dtoParameter.getDateRettredTo());
srv.excute();
SrvReturnMessage srm = srv.getReturnMessage();
if (srm.getErrorFlag().equals("Y")) {
SynUpdateDateUtils.createLastUpdateDate(SrvType.SRV_FA_RETIRE, conn);
resumeTime = System.currentTimeMillis() - start;
logDTO = new SynLogDTO();
logDTO.setSynType(SrvType.SRV_FA_RETIRE);
logDTO.setCreatedBy(user.getUserId());
logDTO.setSynMsg("ͬʲɹ");
logUtil.synLog(logDTO, conn);
SynUpdateDateUtils.updateLastUpdateDate(SrvType.SRV_FA_RETIRE, conn);
message = new Message();
message.setMessageValue("ͬʲɹʱ" + resumeTime + "");
} else {
resumeTime = System.currentTimeMillis() - start;
logDTO = new SynLogDTO();
logDTO.setSynType(SrvType.SRV_FA_RETIRE);
logDTO.setCreatedBy(user.getUserId());
logDTO.setSynMsg("ͬʲʧܣ");
logUtil.synLog(logDTO, conn);
message = new Message();
message.setMessageValue("ͬʲʧܣʱ" + resumeTime + "");
}
forwardURL = SrvURLDefineList.SRV_TRANS_RETIRED_PAGE;
} */else if (action.equals(SrvWebActionConstant.INFORSYN) && AssetsWebAttributes.TD_ASSETS_TYPE.equals(assetsType)) { //TD
req.setAttribute(QueryConstant.QUERY_DTO, dtoParameter);
long start = System.currentTimeMillis();
SynLogDTO logDTO = null;
SynLogUtil logUtil = new SynLogUtil();
logDTO = new SynLogDTO();
logDTO.setSynType(SrvType.SRV_FA_RETIRE);
logDTO.setCreatedBy(user.getUserId());
logDTO.setSynMsg("ͬʲʼ");
logUtil.synLog(logDTO, conn);
String envCode = SynUpdateDateUtils.getEnvCode("TDTransRetiredAssetDetailSrv", conn);
// String envCode = SynUpdateDateUtils.getEnvCode("TransRetiredAssetDetailSrv", conn);
TDTransRetiredAssetDetailSrv srv = new TDTransRetiredAssetDetailSrv();
srv.setEnvCode(envCode);
srv.setBookTypeCode(dtoParameter.getBookTypeCode());
srv.setStartRetireDate(dtoParameter.getDateEffectiveFrom());
srv.setStartRetireDate(dtoParameter.getDateRettredFrom());
srv.setEndRetireDate(dtoParameter.getDateRettredTo());
srv.excute();
SrvReturnMessage srm = srv.getReturnMessage();
if (srm.getErrorFlag().equals("Y")) {
SynUpdateDateUtils.createLastUpdateDate(SrvType.SRV_FA_RETIRE, conn);
resumeTime = System.currentTimeMillis() - start;
logDTO = new SynLogDTO();
logDTO.setSynType(SrvType.SRV_FA_RETIRE);
logDTO.setCreatedBy(user.getUserId());
logDTO.setSynMsg("ͬTDʲɹ");
logUtil.synLog(logDTO, conn);
SynUpdateDateUtils.updateLastUpdateDate(SrvType.SRV_FA_RETIRE, conn);
message = new Message();
message.setMessageValue("ͬTDʲɹʱ" + resumeTime + "");
} else {
resumeTime = System.currentTimeMillis() - start;
logDTO = new SynLogDTO();
logDTO.setSynType(SrvType.SRV_FA_RETIRE);
logDTO.setCreatedBy(user.getUserId());
logDTO.setSynMsg("ͬTDʲʧܣ");
logUtil.synLog(logDTO, conn);
message = new Message();
message.setMessageValue("ͬTDʲʧܣʱ" + resumeTime + "");
}
forwardURL = SrvURLDefineList.TD_SRV_TRANS_RETIRED_PAGE;
}
} catch (PoolPassivateException ex) {
ex.printLog();
message.setMessageValue("ͬʧ");
forwardURL = SrvURLDefineList.MESSAGE_PRINT_PUB;
} catch (DTOException ex) {
ex.printLog();
message.setMessageValue("ͬʧ");
forwardURL = SrvURLDefineList.MESSAGE_PRINT_PUB;
} catch (DatatypeConfigurationException ex1) {
message.setMessageValue("ͬʧ");
forwardURL = SrvURLDefineList.MESSAGE_PRINT_PUB;
ex1.printStackTrace();
} catch (TimeException e) {
message.setMessageValue("ͬʧ");
forwardURL = SrvURLDefineList.MESSAGE_PRINT_PUB;
e.printStackTrace();
} catch (Exception e) {
message.setMessageValue("ͬʧ");
forwardURL = SrvURLDefineList.MESSAGE_PRINT_PUB;
e.printStackTrace();
} finally {
DBManager.closeDBConnection(conn);
setHandleMessage(req, message);
ServletForwarder forwarder = new ServletForwarder(req, res);
forwarder.forwardView(forwardURL);
}
}
}
|
C
|
UTF-8
| 1,145 | 3.0625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#define BUF_SIZE 300
void reverse(char *buf, int sz)
{
/* TODO: Reverse list. */
}
int is_zero(char *buf, int sz)
{
/* TODO: Check if number is zero.*/
return 0;
}
void num_div(char *num, int num_sz, char *div, int *div_sz, int *rem)
{
/* TODO: Divide num by 255. Put result to div and the remainder to rem. */
}
void encode(char *base256, int base256_sz, char *base255, int *base255_sz)
{
char *num = base256;
char *div; /* TODO: Alloc */
char *tmp;
int num_sz = base256_sz;
int div_sz;
int rem;
int tmp_sz;
int sz;
for (sz = 0; !is_zero(num, num_sz); sz++)
{
num_div(num, num_sz, div, &div_sz, &rem);
base255[sz] = rem;
/* Swap num<->div */
tmp = div; div = num; num = tmp;
tmp_sz = div_sz; div_sz = num_sz; num_sz = tmp_sz;
}
}
int main()
{
char base255[BUF_SIZE];
char base256[BUF_SIZE];
int base255_sz;
int base256_sz;
base256[0] = 121;
base256[1] = 122;
base256[2] = 142;
base256[3] = 212;
base256_sz = 4;
encode(base256, base256_sz, base255, &base255_sz);
return 0;
}
|
TypeScript
|
UTF-8
| 2,600 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
import { ThemeVariants } from '../../shared/theme';
import * as fromThemeActions from './theme.actions';
import * as fromThemeReducers from './theme.reducers';
describe(' Theme Reducers', () => {
const state = {
"themes":{
"appleTheme":{
"primary":{"baseColor":"yellow"}, "primaryAccent":{"baseColor":"yellow"}, "primaryNeutral":{"baseColor":"yellow"},
"secondary":{"baseColor":"yellow"}, "secondaryAccent":{"baseColor":"yellow"}, "secondaryNeutral":{"baseColor":"yellow"},
"success":{"baseColor":"yellow"}, "danger":{"baseColor":"yellow"},"warning":{"baseColor":"yellow"}, "info":{"baseColor":"yellow"},
"light":{"baseColor":"yellow"}, "dark":{"baseColor":"yellow"}
},
"ballTheme":{
"primary":{"baseColor":"yellow"}, "primaryAccent":{"baseColor":"yellow"}, "primaryNeutral":{"baseColor":"yellow"},
"secondary":{"baseColor":"yellow"}, "secondaryAccent":{"baseColor":"yellow"}, "secondaryNeutral":{"baseColor":"yellow"},
"success":{"baseColor":"yellow"}, "danger":{"baseColor":"yellow"},"warning":{"baseColor":"yellow"}, "info":{"baseColor":"yellow"},
"light":{"baseColor":"yellow"}, "dark":{"baseColor":"yellow"}
}
},
"currentTheme":"ballTheme"
}
it('should return the initial state', () => {
const { initialState } = fromThemeReducers;
const action = {} as any;
expect(fromThemeReducers.reducer(undefined, action))
.toBe(initialState);
});
const name = 'appleTheme';
const theme: ThemeVariants = {
"primary":{"baseColor":"yellow"}, "primaryAccent":{"baseColor":"yellow"}, "primaryNeutral":{"baseColor":"yellow"},
"secondary":{"baseColor":"yellow"}, "secondaryAccent":{"baseColor":"yellow"}, "secondaryNeutral":{"baseColor":"yellow"},
"success":{"baseColor":"yellow"}, "danger":{"baseColor":"yellow"},"warning":{"baseColor":"yellow"}, "info":{"baseColor":"yellow"},
"light":{"baseColor":"yellow"}, "dark":{"baseColor":"yellow"}
};
it('should add theme', () => {
const reducerThemesObj = fromThemeReducers.reducer(state, fromThemeActions.add( {name, theme})).themes;
const actionObj = fromThemeActions.add( {name, theme});
Object.keys(reducerThemesObj).forEach(key => {
if(key === name) {
expect(JSON.stringify( reducerThemesObj[key]) === JSON.stringify(actionObj.theme))
.toBe(true);
}
});
});
it(' should select a theme', () => {
expect( fromThemeActions.select({name}).name === fromThemeReducers.reducer(state, fromThemeActions.select({name})).currentTheme )
.toBe(true);
});
});
|
JavaScript
|
UTF-8
| 4,190 | 2.75 | 3 |
[] |
no_license
|
//Load required modules
var Pos = require('./sPos');
var Cell = require('./sCell');
var Map = require('./sMap');
var Player = require('./sPlayer');
//Configure server
var port = 4242;
var logLevel = 1;
var io = require('socket.io').listen(port);
io.set('log level',logLevel);
//Create map
var map = new Map();
var light_time = 5000;
var light = 0;
var positive = false;
var timmer;
function lightEvent()
{
clearInterval(timmer);
if(light <= 0 || light >= 1) positive = !positive;
if(positive) light += 0.1;
else light -= 0.1;
light = Math.round(light*10)/10;
io.sockets.emit('worldLight',light);
timmer = setTimeout(lightEvent,light_time);
}
timmer = setTimeout(lightEvent,light_time);
io.sockets.on('connection',function (client)
{
++map.playerCount;//count new player
if(map.playerCount > 0)
for(var key in map.cells)//send players in server
{
if(map.cells[key].player !== undefined)
{
client.emit('addPlayer',map.cells[key].player);
}
}
client.on('newPlayer',function()
{
var player = map.newPlayer(client.id);
client.emit('setPlayer',player);
client.broadcast.emit('addPlayer',player);
});
client.on('move',function (data)
{
if(data === undefined) return;
if(data.direction === undefined) return;
//var newTime = +new Date();
var cell = map.getCellPlayer(client.id);
if(cell === undefined) return;
switch(data.direction)
{
case 'up':
var upCell = map.getCellAt(new Pos(cell.player.pos.x,cell.player.pos.y-1));
if(upCell.player === undefined)
{
upCell.player = new Player(cell.player.pos.x,cell.player.pos.y-1,cell.player.id,cell.player.color);
upCell.player.life = cell.player.life;
io.sockets.emit('playerUpdate',upCell.player);
map.deleteCell(new Pos(cell.player.pos.x,cell.player.pos.y));
}
break;
case 'left':
var leftCell = map.getCellAt(new Pos(cell.player.pos.x-1,cell.player.pos.y));
if(leftCell.player === undefined)
{
leftCell.player = new Player(cell.player.pos.x-1,cell.player.pos.y,cell.player.id,cell.player.color);
leftCell.player.life = cell.player.life;
io.sockets.emit('playerUpdate',leftCell.player);
map.deleteCell(new Pos(cell.player.pos.x,cell.player.pos.y));
}
break;
case 'right':
var rightCell = map.getCellAt(new Pos(cell.player.pos.x+1,cell.player.pos.y));
if(rightCell.player === undefined)
{
rightCell.player = new Player(cell.player.pos.x+1,cell.player.pos.y,cell.player.id,cell.player.color);
rightCell.player.life = cell.player.life;
io.sockets.emit('playerUpdate',rightCell.player);
map.deleteCell(new Pos(cell.player.pos.x,cell.player.pos.y));
}
break;
case 'down':
var downCell = map.getCellAt(new Pos(cell.player.pos.x,cell.player.pos.y+1));
if(downCell.player === undefined)
{
downCell.player = new Player(cell.player.pos.x,cell.player.pos.y+1,cell.player.id,cell.player.color);
downCell.player.life = cell.player.life;
io.sockets.emit('playerUpdate',downCell.player);
map.deleteCell(new Pos(cell.player.pos.x,cell.player.pos.y));
}
break;
}
});
client.on('attack',function (){
var cell = map.getCellPlayer(client.id);
if(cell === undefined) return;
var aroundPositions = map.getAroundPositions(cell.player.pos);
//console.log(aroundPositions);
var size = Object.keys(aroundPositions).length;
for(var i = 0; i < size; ++i)
{
if(aroundPositions[i] in map.cells)
{
var enemy = map.cells[aroundPositions[i]];
enemy.player.life -= 10;
if(enemy.player.life < 0) enemy.player.life = 0;
io.sockets.emit('playerUpdate',enemy.player);
}
}
/*
for(var position in aroundPositions)
{
if(position in map.cells)
{
console.log('enemy detected');
var enemy = map.cells[position];
enemy.player.life -= 10;
io.sockets.emit('playerUpdate',enemy.player);
}
}
*/
});
client.on('disconnect',function ()
{
console.log('user disconnect');
--map.playerCount;
var cell = map.getCellPlayer(client.id);
if(cell !== undefined)
{
delete cell.player;
}
io.sockets.emit('exit',client.id);
});
});
console.log('Server: Listen clients in port: '+port);
|
Python
|
UTF-8
| 140 | 3.359375 | 3 |
[] |
no_license
|
from numpy import *
string = input("digite a string: ")
copy = ""
for i in string:
if(i != "a" and i != "A"):
copy = copy + i
print(copy)
|
Java
|
UTF-8
| 677 | 3.3125 | 3 |
[] |
no_license
|
class Student
{
// instance variable
//they came into memory when object is object
private int rollNo;
private String name;
// camel case
private String courseName;
private int marks;
// local variable
public void input(int rollNo,String name ,String courseName , int marks)
{
if (rollNo >0)
{
this.rollNo = rollNo;
}
this.name = name;
this.courseName = courseName;
if (marks >0){
this.marks = marks;
}
}
public void print()
{
System.out.println("Roll No :"+this.rollNo);
System.out.println("Name : "+this.name);
System.out.println("Course Name : "+this.courseName);
System.out.println("Marks : "+this.marks);
}
}
|
C++
|
UTF-8
| 1,468 | 3.640625 | 4 |
[] |
no_license
|
#include <iostream>
using namespace std;
void sort(int*, int);
int main(){
//Number of test cases
int t;
cin>>t;
for(int i = 0; i < t; i++){
//Order of the square matrix
int n;
cin>>n;
int elements[n*n]={0};
//Store the elements in a 1D array
for(int j = 0; j < n; j++){
for(int k = 0; k < n; k++){
cin>>elements[(n*j)+k];
}
}
//Sort the array any preferred sorting algorithm
sort(elements, n);
int matrix[n][n] = {0};
int count = 0;
int col1 = 0 ,col2 = n-1,row1 = 0,row2 = n-1;
while(count < (n*n)){
for(int j = col2; j >= col1; j--)
matrix[row2][j] = elements[count++];
for(int k = row2 - 1; k >= row1; k--)
matrix[k][col1] = elements[count++];
for(int j = col1 + 1; j <= col2; j++)
matrix[row1][j] = elements[count++];
for(int k = row1 + 1; k <= row2 - 1; k++)
matrix[k][col2] = elements[count++];
col1++;
col2--;
row1++;
row2--;
}
for(int j = 0; j < n; j++){
for(int k = 0; k < n; k++){
cout<<matrix[j][k]<<" ";
}
cout<<endl;
}
cout<<endl;
}
return 0;
}
void sort(int* array, int n){
//Bubble sort algorithm
for(int j = 0; j <n*n; j++){
for(int k = 0; k<(n*n) - 1; k++){
if(array[k] > array[k+1]){
int temp = array[k];
array[k] = array[k+1];
array[k+1] = temp;
}
}
}
}
|
TypeScript
|
UTF-8
| 513 | 2.859375 | 3 |
[] |
no_license
|
import {
GET_AUTHOR_BY_UID,
SET_ERROR_AUTHOR_BY_UID_TRUE
} from "../actions/types";
export const initialState: object = {};
export default function(
state = initialState,
action: { type: string; payload?: any }
) {
switch (action.type) {
case GET_AUTHOR_BY_UID:
return {
...state,
...action.payload
};
case SET_ERROR_AUTHOR_BY_UID_TRUE:
return {
...state,
[action.payload.uid]: { error: true }
};
default:
return state;
}
}
|
Markdown
|
UTF-8
| 1,047 | 3.328125 | 3 |
[] |
no_license
|
1913 · Query Student Enrollment Information
Write a SQL query, the condition: no matter whether the student has a student enrollment information, student needs to provide the following information based on the above two tables:
student_name,
phone,
hometown,
address
Table definition 1: students
| Column Name | Type | Explanation |
|--------------|--------------|-----------------|
| id | int unsigned | primary key |
| student_name | varchar | student's name |
| phone | varchar | student's phone |
Table definition 2: enrollments
| Column Name | Type | Explanation |
|-------------|--------------|--------------------|
| id | int unsigned | primary key |
| student_id | int unsigned | student's id |
| hometown | varchar | student's hometown |
| address | varchar | student's address |
#SQL
```
select t1.student_name, t1.phone, t2.hometown, t2.address
from students as t1 left join enrollments as t2
on t1.id = t2.student_id;
```
|
Java
|
UTF-8
| 2,181 | 1.679688 | 2 |
[] |
no_license
|
/* */ package com.bright.assetbank.application.action;
/* */
/* */ import com.bn2web.common.action.Bn2Action;
/* */ import com.bn2web.common.exception.Bn2Exception;
/* */ import com.bright.assetbank.application.constant.AssetBankConstants;
/* */ import com.bright.assetbank.application.constant.AssetBankSettings;
/* */ import com.bright.assetbank.application.form.EmailForm;
/* */ import com.bright.framework.constant.FrameworkConstants;
/* */ import com.bright.framework.service.FileStoreManager;
/* */ import java.io.File;
/* */ import javax.servlet.http.HttpServletRequest;
/* */ import javax.servlet.http.HttpServletResponse;
/* */ import org.apache.struts.action.ActionForm;
/* */ import org.apache.struts.action.ActionForward;
/* */ import org.apache.struts.action.ActionMapping;
/* */
/* */ public class ViewEmailAssetAction extends Bn2Action
/* */ implements AssetBankConstants, FrameworkConstants
/* */ {
/* */ private FileStoreManager m_fileStoreManager;
/* */
/* */ public ActionForward execute(ActionMapping a_mapping, ActionForm a_form, HttpServletRequest a_request, HttpServletResponse a_response)
/* */ throws Bn2Exception
/* */ {
/* 58 */ ActionForward afForward = a_mapping.findForward("Success");
/* 59 */ EmailForm form = (EmailForm)a_form;
/* */
/* 61 */ String sFileId = (String)a_request.getAttribute("downloadFile");
/* 62 */ long lMaxAttachmentSize = 1048576 * AssetBankSettings.getEmailAttachmentMaxSizeInMb();
/* 63 */ long lFileLength = new File(this.m_fileStoreManager.getAbsolutePath(sFileId)).length();
/* */
/* 66 */ form.setFileId(sFileId);
/* 67 */ form.setAssetIsAttachable(lFileLength <= lMaxAttachmentSize);
/* */
/* 69 */ return afForward;
/* */ }
/* */
/* */ public void setFileStoreManager(FileStoreManager a_fileStoreManager)
/* */ {
/* 74 */ this.m_fileStoreManager = a_fileStoreManager;
/* */ }
/* */ }
/* Location: C:\Users\mamatha\Desktop\com.zip
* Qualified Name: com.bright.assetbank.application.action.ViewEmailAssetAction
* JD-Core Version: 0.6.0
*/
|
Java
|
UTF-8
| 46,842 | 1.625 | 2 |
[] |
no_license
|
package instrument.analysis;
import static org.codehaus.groovy.gjit.DebugUtils.dump;
import static org.codehaus.groovy.gjit.DebugUtils.print;
import static org.codehaus.groovy.gjit.DebugUtils.println;
import static org.codehaus.groovy.gjit.DebugUtils.toggle;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.codehaus.groovy.gjit.db.ClassEntry;
import org.codehaus.groovy.gjit.db.SiteTypePersistentCache;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
import org.objectweb.asm.util.AbstractVisitor;
public class SecondTransformer extends BaseTransformer {
private ConstantPack pack;
private String[] siteNames;
private int[] localTypes;
private Integer currentSiteIndex;
private Stack<Integer> callSiteIndexStack = new Stack<Integer>();
private Map<Integer, AbstractInsnNode> callSiteInsnLocations = new HashMap<Integer, AbstractInsnNode>();
private List<Integer> unusedCallSites = new ArrayList<Integer>();
//private List<AbstractInsnNode> fixed = new ArrayList<AbstractInsnNode>();
private ClassEntry ce;
private HashMap<AbstractInsnNode, Integer> instToCallsiteIndex = new HashMap<AbstractInsnNode, Integer>();
private static final String SCRIPT_BYTECODE_ADAPTER = "org/codehaus/groovy/runtime/ScriptBytecodeAdapter";
private static final String CALL_SITE_INTERFACE = "org/codehaus/groovy/runtime/callsite/CallSite";
private static final String DEFAULT_TYPE_TRANSFORMATION = "org/codehaus/groovy/runtime/typehandling/DefaultTypeTransformation";
public SecondTransformer(String owner, MethodNode mn, ConstantPack pack, String[] siteNames) {
super(owner, mn);
this.pack = pack;
this.siteNames = siteNames;
this.localTypes = new int[mn.maxLocals];
this.interpreter = new DefUseInterpreter();// new FixableInterpreter();
try {
this.ce = SiteTypePersistentCache.v().find(owner);
} catch (Throwable e) {
DebugUtils.println("error cannot get cache entry of sitetype");
this.ce = null;
}
}
@Override
protected void preTransform() {
preTransformationOnly = true;
super.preTransform();
int i = -1;
while (true) {
i++;
if (i >= units.size())
break;
AbstractInsnNode s = units.get(i);
DebugUtils.dump(s);
if (extractCallSiteName(s)) continue;
recordUnusedCallSite(s);
if (unwrapBinOp(s)) continue;
if (eliminateBoxCastUnbox(s)) {
i--;
continue;
}
if (unwrapConst(s)) continue;
if (unwrapBooleanAndIF(s)) continue;
if (unwrapBoxOrUnbox(s)) {
i--;
continue;
}
if (unwrapCompare(s)) {
i--;
continue;
}
if (clearWrapperCast(s)) {
i--;
continue;
}
if (fixALOAD(s)) {
i--;
continue;
}
if (fixASTORE(s)) {
i--;
continue;
}
if (fixHasNext(s)) continue;
if (fixAASTORE(s)) continue;
if (fix_XRETURN(s)) {
i++;
continue;
}
if (fix_DUP(s)) {
i--;
continue;
}
if (fix_POP(s)) continue;
}
DebugUtils.println("===== pre-transformed");
relocateLocalVars();
removeUnusedCallSite();
i = -1;
DebugUtils.println("===== phase 2");
while (true) {
i++;
if (i >= units.size())
break;
AbstractInsnNode s = units.get(i);
if (correctCall(s)) {
i = units.indexOf(s);
continue;
}
if (correctSBAMethods(s)) {
i = units.indexOf(s);
continue;
}
if (fix_DUP(s)) {
i = units.indexOf(s);
continue;
}
if (fix_POP(s)) {
i = units.indexOf(s);
continue;
}
}
}
private boolean unwrapBooleanAndIF(AbstractInsnNode s) {
// GETSTATIC java/lang/Boolean.TRUE : Ljava/lang/Boolean;
// INVOKESTATIC org/codehaus/groovy/runtime/typehandling/DefaultTypeTransformation.booleanUnbox (Ljava/lang/Object;)Z
// IFEQ L15
if(s.getOpcode() != GETSTATIC) return false;
AbstractInsnNode s1 = s.getNext();
if(s1.getOpcode()==-1) s1 = s1.getNext();
if(s1.getOpcode() != INVOKESTATIC) return false;
AbstractInsnNode s2 = s1.getNext();
if(s2 instanceof JumpInsnNode == false) return false;
FieldInsnNode f = ((FieldInsnNode)s);
MethodInsnNode iv1 = (MethodInsnNode)s1;
if(f.owner.equals("java/lang/Boolean") && iv1.owner.equals(DEFAULT_TYPE_TRANSFORMATION) && iv1.name.equals("booleanUnbox")) {
if(f.name.equals("TRUE")) {
units.set(s, new InsnNode(ICONST_1));
units.remove(s1);
return true;
} else if(f.name.equals("FALSE")) {
units.set(s, new InsnNode(ICONST_0));
units.remove(s1);
return true;
}
}
return false;
}
private boolean fix_POP(AbstractInsnNode s) {
if(s.getOpcode() != POP) return false;
AbstractInsnNode p1 = s.getPrevious();
AbstractInsnNode p2 = p1.getPrevious();
// DebugUtils.dump = true;
// DebugUtils.dump(p2);
// DebugUtils.dump(p1);
// DebugUtils.dump(s);
// DebugUtils.dump = false;
if(p2.getOpcode() == DUP2_X1) {
units.set(s, new InsnNode(POP2));
return true;
} else if(p2.getOpcode() == DUP2 && getBytecodeType(p1).getSize()==2) {
units.set(s, new InsnNode(POP2));
return true;
} else if(p1.getOpcode() == DLOAD || p1.getOpcode() == LLOAD) {
units.set(s, new InsnNode(POP2));
return true;
}
return false;
}
private boolean fix_DUP(AbstractInsnNode s) {
if(s.getOpcode()==DUP || s.getOpcode()==DUP2) {
AbstractInsnNode p = s.getPrevious();
AbstractInsnNode s1 = s.getNext();
AbstractInsnNode s2 = s1.getNext();
if(s1.getOpcode() == ALOAD && s2.getOpcode() == SWAP) {
Type t = getBytecodeType(p);
if(t==null && s.getOpcode()==DUP) return false;
if((t != null && t.getSize() == 2) || s.getOpcode() == DUP2) {
units.remove(s);
units.insertBefore(s2, new InsnNode(DUP_X2));
units.insertBefore(s2, new InsnNode(POP));
units.set(s2, new InsnNode(DUP2_X1));
return true;
}
}
}
return false;
}
private boolean fix_XRETURN(AbstractInsnNode s) {
if(s.getOpcode() >= IRETURN && s.getOpcode() <= DRETURN) {
AbstractInsnNode p = s.getPrevious();
if(p.getOpcode()==ACONST_NULL) {
switch (s.getOpcode()) {
case IRETURN:
units.set(p, new InsnNode(ICONST_0));
return true;
case LRETURN:
units.set(p, new InsnNode(LCONST_0));
return true;
case FRETURN:
units.set(p, new InsnNode(FCONST_0));
return true;
case DRETURN:
units.set(p, new InsnNode(DCONST_0));
return true;
}
}
// DebugUtils.dump = true;
// DebugUtils.dump(p);
// DebugUtils.dump = false;
int opcode = getConverterOpCode(getBytecodeType(p), getBytecodeType(s));
if(opcode != 0) {
units.insertBefore(s, new InsnNode(opcode));
return true;
}
} else if(s.getOpcode() == ARETURN) {
AbstractInsnNode p = s.getPrevious();
if(p.getOpcode() == PUTFIELD) {
FieldInsnNode f = (FieldInsnNode)p;
if(f.desc.length()==1) {
switch(f.desc.charAt(0)) {
case 'I': box(p, Type.INT_TYPE); return true;
case 'L': box(p, Type.LONG_TYPE); return true;
case 'F': box(p, Type.FLOAT_TYPE); return true;
case 'D': box(p, Type.DOUBLE_TYPE); return true;
}
}
} else {
switch(p.getOpcode()) {
case ILOAD: box(p, Type.INT_TYPE); return true;
case LLOAD: box(p, Type.LONG_TYPE); return true;
case FLOAD: box(p, Type.FLOAT_TYPE); return true;
case DLOAD: box(p, Type.DOUBLE_TYPE); return true;
}
}
}
return false;
}
private void relocateLocalVars() {
int[] localIndex = new int[localTypes.length];
int j = 0;
DebugUtils.println(localTypes.length);
for (int i = 0; i < localIndex.length; i++) {
localIndex[i] = j;
if (localTypes[i] == Type.LONG || localTypes[i] == Type.DOUBLE) {
j++;
}
j++;
}
int i = -1;
while (true) {
i++;
if (i >= units.size())
break;
AbstractInsnNode s = units.get(i);
if (s instanceof VarInsnNode) {
VarInsnNode v = ((VarInsnNode) s);
v.var = localIndex[v.var];
}
}
}
@Override
protected void posttransform() {
DebugUtils.println(use.size());
}
private boolean correctSBAMethods(AbstractInsnNode s) {
if (s.getOpcode() != INVOKESTATIC)
return false;
MethodInsnNode iv = ((MethodInsnNode) s);
if (iv.owner.equals(SCRIPT_BYTECODE_ADAPTER) == false)
return false;
if (iv.name.equals("unwrap"))
return false;
DebugUtils.println(">>> === correctSBAMethods at " + s);
fixByArguments_specialCase1(iv);
unboxForCorrectCall(s);
return true;
}
private boolean correctCall(AbstractInsnNode s) {
if (s.getOpcode() != INVOKEINTERFACE)
return false;
MethodInsnNode iv = ((MethodInsnNode) s);
if (iv.owner.equals(CALL_SITE_INTERFACE) == false)
return false;
if (iv.name.startsWith("call") == false)
return false;
DebugUtils.println(">>> === correctCall");
fixByArguments_specialCase1(iv);
unboxForCorrectCall(s);
return true;
}
private void unboxForCorrectCall(AbstractInsnNode s) {
AbstractInsnNode s1 = s.getNext();
if(s1.getOpcode() == DUP) s1 = s1.getNext();
int s1_opcode = s1.getOpcode();
// TODO special case, need checking with ALOAD without SWAP
if(s1_opcode>=ILOAD && s1_opcode <= DLOAD) return;
if(s1_opcode>=ICONST_M1 && s1_opcode <= ICONST_5) return;
if(s1_opcode>=LCONST_0 && s1_opcode <= LCONST_1) return;
if(s1_opcode>=FCONST_0 && s1_opcode <= FCONST_1) return;
if(s1_opcode>=DCONST_0 && s1_opcode <= DCONST_1) return;
if(s1_opcode==LDC) return;
if(s1_opcode==GETFIELD) return;
if(s1_opcode==GETSTATIC) return;
Type t = getBytecodeType(s1);
if(t == null) {
// try again looking for sequence of ALOAD, SWAP, XX
AbstractInsnNode s2 = s1.getNext();
AbstractInsnNode s3 = s2.getNext();
if(s1_opcode==ALOAD && s2.getOpcode() == SWAP) {
t = getBytecodeType(s3);
}
}
if(t!=null) {
s1 = s.getNext(); // re-check
s1_opcode = s1.getOpcode();
unbox(s1, t);
if(s1_opcode == DUP && t.getSize()==2) {
units.set(s1, new InsnNode(DUP2));
}
}
}
private AbstractInsnNode findStartingInsn(MethodInsnNode s) {
ReverseStackDistance r = new ReverseStackDistance(s);
return r.findStartingNode();
}
private void fixByArguments_specialCase1(MethodInsnNode iv) {
//toggle();
dump(iv);
AbstractInsnNode s0 = findStartingInsn(iv);
PartialInterpreter in = new PartialInterpreter(this.node, s0, iv);
AbstractInsnNode[] useBox = in.analyse().get(iv);
Type[] argTypes = Type.getArgumentTypes(iv.desc);
if (iv.getOpcode() == INVOKESTATIC) {
for (int i = 0; i < argTypes.length; i++) {
if (useBox[i] == null)
continue;
print(" use box " + i);
dump(useBox[i]);
if (argTypes[i].getSort() == Type.OBJECT
|| argTypes[i].getSort() == Type.ARRAY) {
Type t = getBytecodeType(useBox[i]);
if (t != null) {
box(useBox[i], t);
}
}
}
} else {
for (int i = 0; i < argTypes.length; i++) {
if (useBox[i + 1] == null) continue;
print(" use box " + (i + 1));
dump(useBox[i + 1]);
if (argTypes[i].getSort() == Type.OBJECT
|| argTypes[i].getSort() == Type.ARRAY) {
Type t = getBytecodeType(useBox[i + 1]);
if (t != null) {
dump(iv);
print(", to box ");
dump(useBox[i + 1]);
box(useBox[i + 1], t);
}
}
}
}
//toggle();
}
private boolean unwrapBinOp(AbstractInsnNode s) {
if (s.getOpcode() == INVOKESTATIC) {
MethodInsnNode iv = ((MethodInsnNode) s);
if (iv.owner.equals(CALL_SITE_INTERFACE) == false)
return false;
if (iv.desc.equals(CALL_SITE_BIN_SIGNATURE) == false)
return false;
BinOp op = null;
try {
op = BinOp.valueOf(iv.name);
} catch (Exception e) {
op = null;
}
if (op == null)
return false;
AbstractInsnNode s_op2 = s.getPrevious();
AbstractInsnNode s_op1 = s_op2.getPrevious();
if (s_op1 instanceof MethodInsnNode || s_op2 instanceof MethodInsnNode ||
isString(s_op1) || isString(s_op2)) {
// use op1 as InsnNode to get its index
// use op2 as InsnNode to get its index
Integer op1_index = instToCallsiteIndex.get(s_op1);
Type op1_rtype=null;
try {
if(op1_index == null) {
op1_rtype = getBytecodeType(s_op1);
} else {
op1_rtype = Type.getType(ce.getReturnType(op1_index));
}
Integer op2_index = instToCallsiteIndex.get(s_op2);
Type op2_rtype=null;
if(op1_index == null) {
op2_rtype = getBytecodeType(s_op2);
} else {
op2_rtype = Type.getType(ce.getReturnType(op2_index));
}
// TODO dealing wtih callsite data here
} catch(Throwable e) {
DebugUtils.println("callsite entry not available: " + e.getMessage());
iv.setOpcode(INVOKEINTERFACE);
iv.name = "call";
unusedCallSites.remove(currentSiteIndex);
return true;
}
iv.setOpcode(INVOKEINTERFACE);
iv.name = "call";
unusedCallSites.remove(currentSiteIndex);
return true;
}
Type t2 = getBytecodeType(s_op2);
Type t1 = getBytecodeType(s_op1);
Type toType=t1;
Type fromType = null;
if (t1 != null && t2 != null) {
if(t1 != t2) {
AbstractInsnNode op_to_promote;
if(t1.getSort() > t2.getSort()) {
fromType = t2;
toType = t1;
op_to_promote = s_op2;
} else {
fromType = t1;
toType = t2;
op_to_promote = s_op1;
}
InsnNode converter=new InsnNode(getConverterOpCode(fromType, toType));
if(converter.getOpcode()!=NOP) {
units.insert(op_to_promote, converter);
}
}
int offset = 0;
if (toType == Type.LONG_TYPE) offset = 1;
else if (toType == Type.FLOAT_TYPE) offset = 2;
else if (toType == Type.DOUBLE_TYPE) offset = 3;
AbstractInsnNode newS = null;
switch (op) {
case minus:
newS = new InsnNode(ISUB + offset);
units.set(s, newS);
break;
case plus:
newS = new InsnNode(IADD + offset);
units.set(s, newS);
break;
case multiply:
newS = new InsnNode(IMUL + offset);
units.set(s, newS);
break;
case div:
newS = new InsnNode(IDIV + offset);
units.set(s, newS);
break;
case leftShift:
newS = new InsnNode(ISHL + offset);
units.set(s, newS);
break;
case rightShift:
newS = new InsnNode(ISHR + offset);
units.set(s, newS);
break;
}
if(toType.getSize() == 2 && newS.getNext().getOpcode()==DUP) {
units.set(newS.getNext(), new InsnNode(DUP2));
}
return true;
}
}
return false;
}
private boolean isString(AbstractInsnNode op) {
if(op.getOpcode()==LDC) {
return ((LdcInsnNode)op).cst instanceof String;
}
return false;
}
private Type getBytecodeType(AbstractInsnNode op) {
int opcode = op.getOpcode();
if (opcode == GETFIELD || opcode == GETSTATIC || opcode == PUTFIELD || opcode == PUTSTATIC) {
Type t = Type.getType(((FieldInsnNode) op).desc);
if (t.getSort() == Type.OBJECT || t.getSort() == Type.ARRAY)
return null;
return t;
}
if (opcode >= ICONST_M1 && opcode <= ICONST_5)
return Type.INT_TYPE;
if (opcode == ILOAD
|| opcode == BIPUSH
|| opcode == SIPUSH
|| opcode == IALOAD
|| opcode == IADD
|| opcode == ISUB
|| opcode == IMUL
|| opcode == IDIV
|| opcode == IRETURN
|| opcode == ISTORE
|| (opcode == LDC && ((LdcInsnNode) op).cst instanceof Integer))
return Type.INT_TYPE;
if (opcode == LLOAD
|| opcode == LCONST_0
|| opcode == LCONST_1
|| opcode == LALOAD
|| opcode == LADD
|| opcode == LSUB
|| opcode == LMUL
|| opcode == LDIV
|| opcode == LRETURN
|| opcode == LSTORE
|| (opcode == LDC && ((LdcInsnNode) op).cst instanceof Long))
return Type.LONG_TYPE;
if (opcode == FLOAD
|| opcode == FCONST_0
|| opcode == FCONST_1
|| opcode == FALOAD
|| opcode == FADD
|| opcode == FSUB
|| opcode == FMUL
|| opcode == FDIV
|| opcode == FRETURN
|| opcode == FSTORE
|| (opcode == LDC && ((LdcInsnNode) op).cst instanceof Float))
return Type.FLOAT_TYPE;
if (opcode == DLOAD
|| opcode == DCONST_0
|| opcode == DCONST_1
|| opcode == DALOAD
|| opcode == DADD
|| opcode == DSUB
|| opcode == DMUL
|| opcode == DDIV
|| opcode == DRETURN
|| opcode == DSTORE
|| (opcode == LDC && ((LdcInsnNode) op).cst instanceof Double))
return Type.DOUBLE_TYPE;
return null;
}
private void removeUnusedCallSite() {
// Set<Entry<Integer, AbstractInsnNode>> set =
// unusedCallSites.entrySet();
for (Integer index : unusedCallSites) {
AbstractInsnNode s = callSiteInsnLocations.get(index);
AbstractInsnNode s1 = s.getNext(); // LDC
AbstractInsnNode s2 = s1.getNext(); // AALOAD
DebugUtils.println(">>>> ===");
DebugUtils.println(index);
DebugUtils.println(siteNames[index]);
DebugUtils.println(AbstractVisitor.OPCODES[s.getOpcode()]);
DebugUtils.println(AbstractVisitor.OPCODES[s1.getOpcode()]);
DebugUtils.println(AbstractVisitor.OPCODES[s2.getOpcode()]);
units.remove(s);
units.remove(s1);
units.remove(s2);
}
}
private void recordUnusedCallSite(AbstractInsnNode s) {
if (s.getOpcode() != INVOKEINTERFACE)
return;
MethodInsnNode iv = (MethodInsnNode) s;
if (iv.owner.equals(CALL_SITE_INTERFACE) == false)
return;
if (iv.name.equals("call") == false)
return;
currentSiteIndex = callSiteIndexStack.pop();
instToCallsiteIndex.put(s, currentSiteIndex);
// AbstractInsnNode p2 = s.getPrevious();
// AbstractInsnNode p1 = p2.getPrevious();
if (isBinOpPrimitiveCall(s) == true) {
iv.setOpcode(INVOKESTATIC);
iv.name = siteNames[currentSiteIndex];
unusedCallSites.add(currentSiteIndex);
}
}
private boolean fixAASTORE(AbstractInsnNode s) {
if (s.getOpcode() != AASTORE)
return false;
AbstractInsnNode p = s.getPrevious();
switch (p.getOpcode()) {
case ILOAD:
case IADD:
case ISUB:
case IMUL:
case IDIV:
case ISHL:
case ISHR:
box(p, Type.INT_TYPE);
break;
case LLOAD:
case LADD:
case LSUB:
case LMUL:
case LDIV:
case LSHL:
case LSHR:
box(p, Type.LONG_TYPE);
break;
case FLOAD:
case FADD:
case FSUB:
case FMUL:
case FDIV:
box(p, Type.FLOAT_TYPE);
break;
case DLOAD:
case DADD:
case DSUB:
case DMUL:
case DDIV:
box(p, Type.DOUBLE_TYPE);
break;
}
return true;
}
// @Override
// public Action process(AbstractInsnNode s,
// Map<AbstractInsnNode, Frame> frames) {
// // if(extractCallSiteName(s)) return Action.NONE;
// // if(eliminateBoxCastUnbox(s)) return Action.REMOVE;
// // if(unwrapConst(s)) return Action.REPLACE;
// // if(unwrapBoxOrUnbox(s)) return Action.REMOVE;
// // if(unwrapBinaryPrimitiveCall(s, frames.get(s))) return
// // Action.REPLACE;
// // if(unwrapCompare(s,frames.get(s))) return Action.REMOVE;
// // if(clearWrapperCast(s)) return Action.REMOVE;
// // if(fixASTORE(s,frames.get(s))) return Action.REPLACE;
// // if(fixALOAD(s)) return Action.REPLACE;
// // if(fixHasNext(s)) return Action.REPLACE; // workaround ASM verifier
// // if(fixAASTORE(s,frames.get(s))) return Action.ADD;
// return Action.NONE;
// }
private boolean fixHasNext(AbstractInsnNode s) {
if (s.getOpcode() != INVOKEINTERFACE)
return false;
MethodInsnNode m = ((MethodInsnNode) s);
// mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Iterator", "hasNext",
// "()Z");
if (m.owner.equals("java/util/Iterator")
&& s.getPrevious().getOpcode() != CHECKCAST) {
units.insertBefore(s, new TypeInsnNode(CHECKCAST, m.owner));
return true;
}
return false;
}
// private boolean fixASTORE(AbstractInsnNode s, Frame frame) {
// if(s.getOpcode()!=ASTORE) return false;
// BasicValue top = (BasicValue)frame.getStack(frame.getStackSize()-1);
// return fixASTORE(s, top.getType());
// }
private boolean fixASTORE(AbstractInsnNode s) {
if (s.getOpcode() != ASTORE)
return false;
int sort = localTypes[((VarInsnNode) s).var];
if (sort != 0) { // special case, done fixing before
return fixASTORE(s, sort);
}
AbstractInsnNode p = s.getPrevious();
switch (p.getOpcode()) {
case ILOAD:
return fixASTORE(s, Type.INT_TYPE);
case LLOAD:
return fixASTORE(s, Type.LONG_TYPE);
case FLOAD:
return fixASTORE(s, Type.FLOAT_TYPE);
case DLOAD:
return fixASTORE(s, Type.DOUBLE_TYPE);
}
return false;
}
private boolean fixASTORE(AbstractInsnNode s, int sort) {
VarInsnNode v = (VarInsnNode) s;
Type t = null;
AbstractInsnNode p = s.getPrevious();
VarInsnNode newS;
switch (sort) {
case Type.INT:
if(p.getOpcode()==ACONST_NULL) units.set(p, new InsnNode(ICONST_0));
newS = new VarInsnNode(ISTORE, v.var);
units.set(s, newS);
localTypes[v.var] = Type.INT;
t = Type.INT_TYPE;
break;
case Type.LONG:
if(p.getOpcode()==ACONST_NULL) units.set(p, new InsnNode(LCONST_0));
newS = new VarInsnNode(LSTORE, v.var);
units.set(s, newS);
localTypes[v.var] = Type.LONG;
t = Type.LONG_TYPE;
break;
case Type.FLOAT:
if(p.getOpcode()==ACONST_NULL) units.set(p, new InsnNode(FCONST_0));
newS = new VarInsnNode(FSTORE, v.var);
units.set(s, newS);
localTypes[v.var] = Type.FLOAT;
t = Type.FLOAT_TYPE;
break;
case Type.DOUBLE:
if(p.getOpcode()==ACONST_NULL) units.set(p, new InsnNode(DCONST_0));
newS = new VarInsnNode(DSTORE, v.var);
units.set(s, newS);
localTypes[v.var] = Type.DOUBLE;
t = Type.DOUBLE_TYPE;
break;
default:
return false;
}
if (t != null) {
p = newS.getPrevious();
if (p != null) {
if (p.getOpcode() == DUP) p = p.getPrevious();
if (p instanceof MethodInsnNode) {
MethodInsnNode iv = ((MethodInsnNode) p);
if (iv.name.equals("call") && iv.desc.equals(CALL_SITE_BIN_SIGNATURE)) {
unbox(newS, t);
}
} else if(getBytecodeType(p) != getBytecodeType(newS)) {
// DebugUtils.dump = true;
// DebugUtils.dump(p);
// DebugUtils.dump(newS);
// DebugUtils.dump = false;
int converterOpcode = getConverterOpCode(getBytecodeType(p),getBytecodeType(newS));
if(converterOpcode != 0) {
InsnNode converter = new InsnNode(converterOpcode);
units.insertBefore(newS, converter);
}
}
}
}
return true;
}
private int getConverterOpCode(Type fromType, Type toType) {
if(fromType == null) return 0;
if(toType == null) return 0;
switch(fromType.getSort()) {
case Type.INT: return getConvertIntTo(toType);
case Type.LONG: return getConvertLongTo(toType);
case Type.FLOAT: return getConvertFloatTo(toType);
case Type.DOUBLE: return getConvertDoubleTo(toType);
}
return 0;
}
private int getConvertIntTo(Type toType) {
switch(toType.getSort()) {
case Type.LONG: return I2L;
case Type.FLOAT: return I2F;
case Type.DOUBLE: return I2D;
}
return 0;
}
private int getConvertLongTo(Type toType) {
switch(toType.getSort()) {
case Type.INT: return L2I;
case Type.FLOAT: return L2F;
case Type.DOUBLE: return L2D;
}
return 0;
}
private int getConvertFloatTo(Type toType) {
switch(toType.getSort()) {
case Type.INT: return F2I;
case Type.LONG: return F2L;
case Type.DOUBLE: return F2D;
}
return 0;
}
private int getConvertDoubleTo(Type toType) {
switch(toType.getSort()) {
case Type.INT: return D2I;
case Type.LONG: return D2L;
case Type.FLOAT: return D2F;
}
return 0;
}
private boolean fixASTORE(AbstractInsnNode s, Type type) {
if (type == null)
return false;
// VarInsnNode v = (VarInsnNode)s;
return fixASTORE(s, type.getSort());
}
private boolean fixALOAD(AbstractInsnNode s) {
if (s.getOpcode() != ALOAD)
return false;
VarInsnNode v = (VarInsnNode) s;
switch (localTypes[v.var]) {
case Type.INT:
units.set(s, new VarInsnNode(ILOAD, v.var));
return true;
case Type.LONG:
units.set(s, new VarInsnNode(LLOAD, v.var));
return true;
case Type.FLOAT:
units.set(s, new VarInsnNode(FLOAD, v.var));
return true;
case Type.DOUBLE:
units.set(s, new VarInsnNode(DLOAD, v.var));
return true;
default:
return false;
}
}
private void box(AbstractInsnNode source, Type t) {
String boxType = null;
String primType = null;
switch (t.getSort()) {
case Type.INT:
boxType = "java/lang/Integer";
primType = "I";
break;
case Type.LONG:
boxType = "java/lang/Long";
primType = "J";
break;
case Type.FLOAT:
boxType = "java/lang/Float";
primType = "F";
break;
case Type.DOUBLE:
boxType = "java/lang/Double";
primType = "D";
break;
default:
throw new RuntimeException("I'm trying to catch you" + t);
// break;
}
MethodInsnNode iv = new MethodInsnNode(INVOKESTATIC, boxType,
"valueOf", "(" + primType + ")L" + boxType + ";");
// if(source.getOpcode()==SWAP) source = source.getPrevious(); // work
// around for inserted SWAP,POP
// else if(source.getOpcode()==DUP2_X1) source =
// source.getNext().getNext();// POP2, POP,|
units.insert(source, iv);
}
private void unbox(AbstractInsnNode s, Type t) {
String boxType = null;
String primType = null;
String primTypeName = null;
switch (t.getSort()) {
case Type.INT:
boxType = "java/lang/Integer";
primType = "I";
primTypeName = "int";
break;
case Type.LONG:
boxType = "java/lang/Long";
primType = "J";
primTypeName = "long";
break;
case Type.FLOAT:
boxType = "java/lang/Float";
primType = "F";
primTypeName = "float";
break;
case Type.DOUBLE:
boxType = "java/lang/Double";
primType = "D";
primTypeName = "double";
break;
}
TypeInsnNode cast = new TypeInsnNode(CHECKCAST, boxType);
MethodInsnNode iv = new MethodInsnNode(INVOKEVIRTUAL, boxType,
primTypeName + "Value", "()" + primType);
AbstractInsnNode p = s.getPrevious();
if (p instanceof LabelNode) {
s = p;
}
units.insertBefore(s, cast);
units.insert(cast, iv);
}
private boolean extractCallSiteName(AbstractInsnNode s) {
if (s.getOpcode() != ALOAD)
return false;
VarInsnNode v = (VarInsnNode) s;
if (v.var != callSiteVar)
return false;
AbstractInsnNode s1 = s.getNext();
AbstractInsnNode s2 = s1.getNext();
if (s1.getOpcode() != LDC)
return false;
if (s2.getOpcode() != AALOAD)
return false;
LdcInsnNode l = (LdcInsnNode) s1;
callSiteIndexStack.push((Integer) l.cst);
callSiteInsnLocations.put((Integer) l.cst, s);
return true;
}
private boolean eliminateBoxCastUnbox(AbstractInsnNode s) {
if (s.getOpcode() != INVOKESTATIC)
return false;
AbstractInsnNode s1 = s.getNext();
if (s1 == null)
return false;
if (s1.getOpcode() != INVOKESTATIC)
return false;
AbstractInsnNode s2 = s1.getNext();
if (s2 == null)
return false;
if (s2.getOpcode() != INVOKESTATIC)
return false;
AbstractInsnNode s3 = s2.getNext();
if (s3 == null)
return false;
if (s3.getOpcode() != CHECKCAST)
return false;
AbstractInsnNode s4 = s3.getNext();
if (s4 == null)
return false;
if (s4.getOpcode() != INVOKESTATIC)
return false;
MethodInsnNode m = (MethodInsnNode) s;
MethodInsnNode m1 = (MethodInsnNode) s1;
MethodInsnNode m2 = (MethodInsnNode) s2;
MethodInsnNode m4 = (MethodInsnNode) s4;
if (m.owner.equals(DEFAULT_TYPE_TRANSFORMATION) == false)
return false;
if (m.name.equals("box") == false)
return false;
if (m1.name.startsWith("$get$$class$") == false)
return false;
if (m2.name.startsWith("castToType") == false)
return false;
if (m4.name.endsWith("Unbox") == false)
return false;
units.remove(s);
units.remove(s1);
units.remove(s2);
units.remove(s3);
units.remove(s4);
return true;
}
private boolean unwrapBoxOrUnbox(AbstractInsnNode s) {
if (s.getOpcode() != INVOKESTATIC)
return false;
MethodInsnNode m = (MethodInsnNode) s;
if (m.owner.equals(DEFAULT_TYPE_TRANSFORMATION) == false)
return false;
if (m.name.equals("box")) {
// unit_remove(s,s.getPrevious());
units.remove(s);
return true;
} else if (m.name.endsWith("Unbox")) {
// unit_remove(s,s.getPrevious());
units.remove(s);
return true;
}
return false;
}
private boolean unwrapConst(AbstractInsnNode s) {
if (s.getOpcode() != GETSTATIC)
return false;
FieldInsnNode f = (FieldInsnNode) s;
if (f.name.startsWith("$const$")) {
// special case, not unwrap
AbstractInsnNode s11 = s.getNext();
if(s11.getOpcode()==NEW && ((TypeInsnNode)s11).desc.equals("groovy/lang/Reference")) return false;
DebugUtils.println(">>> pass $const$");
DebugUtils.println(f.name);
Object constValue = pack.get(f.name);
DebugUtils.println("const type: " + constValue.getClass());
AbstractInsnNode newS = new LdcInsnNode(constValue);
if (constValue instanceof Integer) {
int c = (Integer) constValue;
if (c >= -1 && c <= 5) {
switch (c) {
case -1:
newS = new InsnNode(ICONST_M1);
break;
case 0:
newS = new InsnNode(ICONST_0);
break;
case 1:
newS = new InsnNode(ICONST_1);
break;
case 2:
newS = new InsnNode(ICONST_2);
break;
case 3:
newS = new InsnNode(ICONST_3);
break;
case 4:
newS = new InsnNode(ICONST_4);
break;
case 5:
newS = new InsnNode(ICONST_5);
break;
}
} else if (c >= -128 && c <= 127) {
newS = new IntInsnNode(BIPUSH, c);
} else if (c >= -32768 && c <= 32767) {
newS = new IntInsnNode(SIPUSH, c);
}
}
AbstractInsnNode s1 = s.getNext();
if (s1.getOpcode() == DUP)
s1 = s1.getNext(); // sometime the compiler use DUP to reuse
// TOS
units.set(s, newS);
if (s1.getOpcode() == ASTORE) {
Type type = Type.getType(constValue.getClass());
fixASTORE(s1, getPrimitiveType(type));
}
DebugUtils.println("unwrap const");
return true;
}
return false;
}
private Type getPrimitiveType(Type type) {
return getPrimitiveType(type.getDescriptor());
}
private Type getPrimitiveType(String desc) {
if (desc.charAt(0) != 'L')
desc = 'L' + desc + ';';
if (desc.equals("Ljava/lang/Integer;"))
return Type.INT_TYPE;
if (desc.equals("Ljava/lang/Long;"))
return Type.LONG_TYPE;
if (desc.equals("Ljava/lang/Float;"))
return Type.FLOAT_TYPE;
if (desc.equals("Ljava/lang/Double;"))
return Type.DOUBLE_TYPE;
return null;
}
private enum BinOp {
minus, plus, multiply, div, leftShift, rightShift
}
private static final String CALL_SITE_BIN_SIGNATURE = "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;";
private boolean isBinOpPrimitiveCall(AbstractInsnNode s) {
if (s.getOpcode() != INVOKEINTERFACE)
return false;
MethodInsnNode iv = (MethodInsnNode) s;
if (iv.owner.equals(CALL_SITE_INTERFACE) == false)
return false;
if (iv.name.equals("call") == false)
return false;
if (iv.desc.equals(CALL_SITE_BIN_SIGNATURE) == false)
return false;
String name = siteNames[currentSiteIndex];
BinOp op = null;
try {
op = BinOp.valueOf(name);
} catch (IllegalArgumentException e) {}
if (op == null) return false;
return true;
}
private boolean clearWrapperCast(AbstractInsnNode s) {
// INVOKESTATIC
// TreeNode.$get$$class$java$lang$Integer()Ljava/lang/Class;
// INVOKESTATIC
// org/codehaus/groovy/runtime/ScriptBytecodeAdapter.castToType(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
// CHECKCAST java/lang/Integer
if (s.getOpcode() != INVOKESTATIC)
return false;
MethodInsnNode m = (MethodInsnNode) s;
if (m.name.startsWith("$get$$class$java$lang$") == false)
return false;
AbstractInsnNode s1 = s.getNext();
if (s1 == null)
return false;
if (s1.getOpcode() != INVOKESTATIC)
return false;
MethodInsnNode m1 = (MethodInsnNode) s1;
if (m1.name.equals("castToType") == false)
return false;
AbstractInsnNode s2 = s1.getNext();
if (s2 == null)
return false;
if (s2.getOpcode() != CHECKCAST)
return false;
TypeInsnNode t2 = (TypeInsnNode) s2;
if (t2.desc.startsWith("java/lang") == false)
return false;
AbstractInsnNode s3 = s2.getNext();
AbstractInsnNode s4 = s3.getNext();
AbstractInsnNode s0 = s.getPrevious();
if (s0 instanceof LabelNode)
s0 = s0.getPrevious();
units.remove(s);
units.remove(s1);
units.remove(s2);
// DebugUtils.println(t2.desc);
// DebugUtils.print("clear >>>>>>> s0 : ");
// DebugUtils.dump(s0);
// DebugUtils.print("clear >>>>>>> s3 : ");
// DebugUtils.dump(s3.getNext());
if (s3.getOpcode() == ASTORE) {
if (s0 instanceof MethodInsnNode) {
// DebugUtils.println(siteNames[currentSiteIndex]);
if (isBinOpPrimitiveCall(s0) == false) {
unbox(s3, getPrimitiveType(t2.desc));
}
}
fixASTORE(s3, getPrimitiveType(t2.desc));
} else if(
s0.getOpcode() == INVOKEVIRTUAL &&
((MethodInsnNode)s0).name.equals("get") &&
((MethodInsnNode)s0).owner.equals("groovy/lang/Reference") &&
s4.getOpcode() >= IRETURN &&
s4.getOpcode() <= DRETURN) {
switch(s4.getOpcode()) {
case IRETURN: unbox(s3, Type.INT_TYPE);
break;
case LRETURN: unbox(s3, Type.LONG_TYPE);
break;
case FRETURN: unbox(s3, Type.FLOAT_TYPE);
break;
case DRETURN: unbox(s3, Type.DOUBLE_TYPE);
break;
}
}
return true;
}
private enum ComparingMethod {
compareLessThan,
compareGreaterThan,
compareLessThanEqual,
compareGreaterThanEqual
};
private boolean unwrapCompare(AbstractInsnNode s) {
if (s.getOpcode() != Opcodes.INVOKESTATIC)
return false;
MethodInsnNode m = (MethodInsnNode) s;
if (m.owner.equals(SCRIPT_BYTECODE_ADAPTER) == false)
return false;
if (m.name.startsWith("compare") == false)
return false;
if (m.desc.equals("(Ljava/lang/Object;Ljava/lang/Object;)Z") == false)
return false;
AbstractInsnNode p2 = s.getPrevious();
AbstractInsnNode p1 = p2.getPrevious();
Type t1 = getBytecodeType(p1);
Type t2 = getBytecodeType(p2);
if(t1 == null || t2 == null) return false;
Type fromType = null;
Type toType = null;
AbstractInsnNode whereToInsert = null;
Type promotedType=null;
// TODO doing type promotion
if(t1.getSort() != t2.getSort()) {
if(t1.getSort() < t2.getSort()) {
fromType = t1;
toType = t2;
whereToInsert = p1;
promotedType = t2;
} else if(t2.getSort() < t1.getSort()) {
fromType = t2;
toType = t1;
whereToInsert = p2;
promotedType = t1;
}
InsnNode converter = new InsnNode(getConverterOpCode(fromType, toType));
if(converter.getOpcode() != NOP) {
units.insert(whereToInsert, converter);
}
} else {
promotedType = t1;
}
ComparingMethod compare;
try {
compare = ComparingMethod.valueOf(m.name);
} catch (IllegalArgumentException e) {
return false;
}
switch(promotedType.getSort()) {
case Type.INT: convertCompareForInt(compare, s); break;
case Type.LONG: convertCompare(LCMP, compare, s); break;
case Type.FLOAT: convertCompare(FCMPL, compare, s); break;
case Type.DOUBLE: convertCompare(DCMPL, compare, s); break;
default: return false;
}
return true;
}
private void convertCompare(int opcode, ComparingMethod compare,
AbstractInsnNode s) {
JumpInsnNode s1 = (JumpInsnNode) s.getNext();
units.set(s, new InsnNode(opcode));
switch (compare) {
case compareGreaterThan:
units.set(s1, new JumpInsnNode(IFLE, s1.label));
break;
case compareGreaterThanEqual:
units.set(s1, new JumpInsnNode(IFLT, s1.label));
break;
case compareLessThan:
units.set(s1, new JumpInsnNode(IFGE, s1.label));
break;
case compareLessThanEqual:
units.set(s1, new JumpInsnNode(IFGT, s1.label));
break;
}
}
private void convertCompareForInt(ComparingMethod compare,
AbstractInsnNode s) {
JumpInsnNode s1 = (JumpInsnNode) s.getNext();
switch (compare) {
case compareGreaterThan:
units.set(s1, new JumpInsnNode(IF_ICMPLE, s1.label));
break;
case compareGreaterThanEqual:
units.set(s1, new JumpInsnNode(IF_ICMPLT, s1.label));
break;
case compareLessThan:
units.set(s1, new JumpInsnNode(IF_ICMPGE, s1.label));
break;
case compareLessThanEqual:
units.set(s1, new JumpInsnNode(IF_ICMPGT, s1.label));
break;
}
units.remove(s);
}
}
|
Markdown
|
UTF-8
| 189 | 2.78125 | 3 |
[] |
no_license
|
# Website-builder
A website builder to make it easier for myself and other developers to design and create simple websites that can be easily added onto and customized with HTML CSS and JS
|
C
|
UTF-8
| 1,208 | 3.109375 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<math.h>
#define N 1000000
unsigned long long int prime[N];
void primetabel()
{
int i,j,root;
for(i=2;i<=N;i++)
prime[i]=1;
prime[1]=0;
prime[0]=0;
root=sqrt(N);
for(i=2;i<=root;i++)
if(prime[i]==1)
for(j=i*i;j<=N;j+=i)
prime[j]=0;
}
int main()
{
primetabel();
unsigned long long int number,a,b,c,sum,rev,k;
while(scanf("%llu",&number)==1)
{
rev=0;
a=number;
if(number>10)
{
while(a>0)
{
k=a%10;
rev=rev*10+k;
a=a/10;
}
if(prime[number]==1)
{
if(prime[rev]==1&&rev!=number)
{
printf("%llu is emirp.\n",number);
}
else
{
printf("%llu is prime.\n",number);
}
}
else
{
printf("%llu is not prime.\n",number);
}
}
else if(prime[number]==1)
printf("%llu is prime.\n",number);
else
printf("%llu is not prime.\n",number);
}
return 0;
}
|
C#
|
UTF-8
| 526 | 3.421875 | 3 |
[] |
no_license
|
static void Main(string[] args)
{
Salutation hello = new Salutation();
hello.OtherParty = "World";
hello.GreetingDelegate = new AddressDelegate(HelloSayer);
hello.GreetingDelegate(hello.OtherParty);
Console.ReadKey();
}
public delegate void AddressDelegate(string otherParty);
private static void HelloSayer(string otherParty)
{
Console.WriteLine(string.Format("Hello, {0}!", otherParty));
}
|
Markdown
|
WINDOWS-1250
| 2,796 | 2.546875 | 3 |
[] |
no_license
|
Formats: [HTML](/news/2010/03/6/the-chilean-navy-removes-commander-mariano-rojas-head-of-the-oceanography-service-from-his-post-following-his-failure-to-warn-of-the-tsuna.html) [JSON](/news/2010/03/6/the-chilean-navy-removes-commander-mariano-rojas-head-of-the-oceanography-service-from-his-post-following-his-failure-to-warn-of-the-tsuna.json) [XML](/news/2010/03/6/the-chilean-navy-removes-commander-mariano-rojas-head-of-the-oceanography-service-from-his-post-following-his-failure-to-warn-of-the-tsuna.xml)
### [2010-03-6](/news/2010/03/6/index.md)
##### Chilean Navy
# The Chilean Navy removes Commander Mariano Rojas, head of the oceanography service, from his post following his failure to warn of the tsunami which followed the 2010 Chile earthquake.
The Chilean government announced that it removed Commander Mariano Rojas over the lack of tsunami warnings after the country's huge earthquake.
### Sources:
1. [RT](http://www.rte.ie/news/2010/0306/chile.html)
2. [The Daily Telegraph](http://www.telegraph.co.uk/news/worldnews/southamerica/chile/7380673/Chile-sacks-oceanography-chief-over-failure-to-issue-tsunami-warnings.html)
3. [The New Zealand Herald](http://www.nzherald.co.nz/world/news/article.cfm?c_id=2&objectid=10630298)
4. [The Times](http://www.timesonline.co.uk/tol/news/world/us_and_americas/article7051999.ece)
4. [Cover Image](http://i.telegraph.co.uk/multimedia/archive/01588/police-beach_1588056a.jpg)
### Related:
1. [The Chilean Navy admits failure to prevent deaths in the tsunami triggered by the recent earthquake. ](/news/2010/03/3/the-chilean-navy-admits-failure-to-prevent-deaths-in-the-tsunami-triggered-by-the-recent-earthquake.md) _Context: 2010 Chile earthquake, Chilean Navy, tsunami_
2. [A magnitude 7.6 earthquake strikes north of Honduras, resulting in tsunami warnings in the Caribbean. ](/news/2018/01/9/a-magnitude-7-6-earthquake-strikes-north-of-honduras-resulting-in-tsunami-warnings-in-the-caribbean.md) _Context: tsunami_
3. [A 7.7 magnitude earthquake strikes off Russia's Kamchatka Peninsula, west of the Alaskan Aleutian Island of Attu, in the North Pacific Ocean. No immediate reports of casualties or damage; a tsunami warning was cancelled. ](/news/2017/07/18/a-7-7-magnitude-earthquake-strikes-off-russia-s-kamchatka-peninsula-west-of-the-alaskan-aleutian-island-of-attu-in-the-north-pacific-ocean.md) _Context: tsunami_
4. [A 6.8 earthquake strikes off the coast of Mindanao, Philippines triggering tsunami warnings. ](/news/2017/04/28/a-6-8-earthquake-strikes-off-the-coast-of-mindanao-philippines-triggering-tsunami-warnings.md) _Context: tsunami_
5. [A magnitude 7.7 earthquake in Chile spurs tsunami warnings. ](/news/2016/12/25/a-magnitude-7-7-earthquake-in-chile-spurs-tsunami-warnings.md) _Context: tsunami_
|
Java
|
UTF-8
| 1,624 | 2.34375 | 2 |
[] |
no_license
|
package edu.shtanko.unarea.app.days_week_b;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import edu.shtanko.unarea.app.R;
import edu.shtanko.unarea.app.weeks.week_b.friday_lessons_week_b.*;
public class Friday extends TabActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_friday);
TabHost tabHost = getTabHost();
TabHost.TabSpec tabSpec;
tabSpec = tabHost.newTabSpec("tag1");
tabSpec.setIndicator("1");
tabSpec.setContent(new Intent(this, One.class));
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("tag2");
tabSpec.setIndicator("2");
tabSpec.setContent(new Intent(this, Two.class));
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("tag3");
tabSpec.setIndicator("3");
tabSpec.setContent(new Intent(this, Three.class));
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("tag4");
tabSpec.setIndicator("4");
tabSpec.setContent(new Intent(this, Four.class));
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("tag5");
tabSpec.setIndicator("5");
tabSpec.setContent(new Intent(this, Five.class));
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("tag6");
tabSpec.setIndicator("6");
tabSpec.setContent(new Intent(this, Six.class));
tabHost.addTab(tabSpec);
}
}
|
Markdown
|
UTF-8
| 1,323 | 3.359375 | 3 |
[] |
no_license
|
1) Learning HTML was completly new to me. I had heard of HTML, but hadn't ever learned what it was or why it was used. One of my favorite things I learned from HTML was how to embed a photo or a map. I never knew the amount of work that went into putting a picture on a website. Another things I learned about html was how to create forms and tables. Creating forms was fun for me because I see them all over the internet, even when taking tests on moodle and it was rewarding to understand what goes into those tables and forms and how to create them myself. The thing that was most difficult for me to learn was how to embed a video, at first it was hard for me to understand what the <iframe> element was and why we use it, but with week 8 and 9's assignments, I think i've gotten better at embedding.
2) I am excited to learn more about styling because it was one of my favorite parts so far. I think its fun to create backround colors, bold tables and text and see a simple webpage come together in something thats fun to look at.
3) For this week, my biggest challenge was creating the navigation from site to site. It's tricky to know if you're doing it right before uploading to your repository. To get help and create my navigation I watched the weekly video and went to the class website which helped greatly.
|
Markdown
|
UTF-8
| 2,369 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
# JMNotifyView
一行代码实现通知视图,零耦合, 适配iPhone X及以上机型
* 超强性能、零耦合
* 默认集成四种通用样式
* 高度自定义
# 版本
* 2018-01-21 初始版本
# 演示

# 如何安装
### 通过CocoaPods导入
```
pod 'JMNotifyView'
```
### 手动导入
```
直接下载工程把JMNotifyView文件夹拖入工程中即可使用
```
# 如何使用
### 1、导入头文件
```
#import "JMNotifyView.h"
```
### 2、一行代码调用(使用方式一)
```
[JMNotifyView showNotify:@"您还未实名, 是否实名?"];
```
### 3、自定义显示在view上(使用方式二)
```
[JMNotifyView showNotify:@"您还未实名, 是否实名?" showView:self.view];
```
### 4、使用系统默认自带样式(使用方式三)
```
// 使用默认自带样式
JMNotifyViewConfig *config = [JMNotifyViewConfig defaultNotifyConfig];
// 系统自带默认四种实现类型
if (sender.tag == 0) { //成功
config.backgroundColorType = JMNotifyViewBackgroundColorTypeSuccess;
} else if (sender.tag == 1) { //失败
config.backgroundColorType = JMNotifyViewBackgroundColorTypeDanger;
} else if (sender.tag == 2) { //警告
config.backgroundColorType = JMNotifyViewBackgroundColorTypeWarning;
} else if (sender.tag == 3) { //信息
config.backgroundColorType = JMNotifyViewBackgroundColorTypeInfo;
}
//显示
[JMNotifyView showNotify:@"你还未实名, 请实名, 如有问题, 请联系客服" showView:[UIApplication sharedApplication].keyWindow config:config];
```
### 5、高度自定义样式(使用方式四)
```
// 自定义配置
JMNotifyViewConfig *config = [JMNotifyViewConfig defaultNotifyConfig];
// 通知样式
config.notifyStyle = JMNotifyViewStyleFill;
// 自定义背景颜色
config.backgroundColor = [UIColor orangeColor];
// 自定义字体大小
config.textSize = 16.f;
// 自定义文字颜色
config.textColor = [UIColor blackColor];
// 自定义行间距
config.textLineSpace = 4.f;
// 自定义悬停时间
config.notifyViewWaitDuration = 2.f;
//显示
[JMNotifyView showNotify:@"你还未实名, 请实名, 如有问题, 请联系客服" showView:[UIApplication sharedApplication].keyWindow config:config];
```
# 联系我
* QQ群:856876741
* 微信号:liujunmin6980
|
Java
|
UTF-8
| 951 | 3.140625 | 3 |
[] |
no_license
|
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class PasswordGenerator_1225 {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws Exception{
String answer = "";
for(int test_case=1; test_case<=10; ++test_case) {
answer = "";
br.readLine();
String s = br.readLine();
StringTokenizer st = new StringTokenizer(s);
Queue<Integer> q = new LinkedList<Integer>();
for(int i=0; i<8; ++i) {
q.add(Integer.parseInt(st.nextToken()));
}
out:while(true) {
for(int i=1; i<=5; ++i) {
int temp = q.poll();
if(temp-i<=0) {
q.add(0);
while(!q.isEmpty()) {
answer += q.poll() + " ";
}
break out;
}
q.add(temp-i);
}
}
System.out.println("#" + test_case + " " + answer);
}
}
}
|
Python
|
UTF-8
| 2,735 | 2.640625 | 3 |
[] |
no_license
|
#sjParseJson.py
#from http://www.plugshare.com/
#import Modules
import json, string, os, codecs, sys
#banner
print "***\nWORKING WITH PLUGSHARE\nhttp://www.plugshare.com/\n\nSusan Jones\n19 July 2016\n"
print "json to CSV Parsing\n***"
#todo: hardcode the parameters
n = 0
jsonFile = r'd:\Tmp\worksite.json'
##pType = raw_input("R = Residential, C = Commercial?")
##print pType
#todo: Parse the json
json_data = open(jsonFile).read()
responses = json.loads(json_data)
n = 0
for response in responses:
n += 1
print responses['data'] ##data , links
print n
###todo: loop json Response
###if C
##if pType == 'C':
## #todo: open file for reading
## csvFile = r'd:\Tmp\all.csv'
## fs = codecs.open(csvFile, mode = 'w', encoding = 'utf8')
## #todo: write Header
## fs.write("rowNumber,name,stationsId,itype,longitude,latitude\n")
## for response in responses:
## #todo: fetch the attributes
## stationsId = response['stations'][0]['id']
## longitude = response['longitude']
## latitude = response['latitude']
## name = response['name']
## name = "\"" + name + "\""
## name = name.encode('ascii', 'replace')
## itype = response['icon_type']
## if name == "\"\"":
## name = "n/a"
## n += 1
## toWrite = str(n) + "," + name + "," + str(stationsId) + "," + itype + "," + str(longitude) + "," + str(latitude) + "\n"
## fs.write(toWrite)
## #todo: messaging
## print "\nlook at " + csvFile
## print str(n) + " records"
##
###if R
##else:
## #todo: open file for reading
## csvFile = r'd:\Tmp\allResidential.csv'
## fs = codecs.open(csvFile, mode = 'w', encoding = 'utf8')
## #todo: write Header
## fs.write("rowNumber,name,stationsId,itype,longitude,latitude\n")
## for response in responses:
## #todo: fetch the attributes
## stationsId = response['stations'][0]['id']
## longitude = response['longitude']
## latitude = response['latitude']
## name = response['name']
## name = "\"" + name + "\""
## name = name.encode('ascii', 'replace')
## itype = response['icon_type']
## if name == "\"\"":
## name = "n/a"
## n += 1
## toWrite = str(n) + "," + name + "," + str(stationsId) + "," + itype + "," + str(longitude) + "," + str(latitude) + "\n"
## fs.write(toWrite)
## #todo: messaging
## print "\nlook at " + csvFile
## print str(n) + " records"
#todo: file and object management
del responses
##fs.close()
#completed
print "\ncompleted, because Susan is very cool."
|
Java
|
UTF-8
| 5,885 | 2.1875 | 2 |
[] |
no_license
|
package com.icss.tjfx.total.structure.vo;
/**
* 总量情况结构VO
* @author lcx
*
*/
public class PriceClassVO {
private String C_CLASS;//价类编码
private String CLASS_NAME;
private String CIG_NAME;//规格名称
//产量
private String produceNum_bq;//本期
private String produceNum_tq;//同期
private String produceNum_bl;//+-量
private String produceNum_pt;//+-%
//销量
private String sellNum_bq;
private String sellNum_tq;
private String sellNum_bl;
private String sellNum_pt;
//工商库存
private String stock_bq;
private String stock_tq;
private String stock_bl;
private String stock_pt;
//在途量
private String onRoad_bq;
private String onRoad_tq;
private String onRoad_bl;
private String onRoad_pt;
//单箱销售额
private String singleSellAmount_bq;
private String singleSellAmount_tq;
private String singleSellAmount_bl;
private String singleSellAmount_pt;
//商业销售额
private String bsSellAmount_bq;
private String bsSellAmount_tq;
private String bsSellAmount_bl;
private String bsSellAmount_pt;
//卷烟税利
private String ciga_tax_bq;
private String ciga_tax_tq;
private String ciga_tax_bl;
private String ciga_tax_pt;
public String getC_CLASS() {
return C_CLASS;
}
public void setC_CLASS(String c_CLASS) {
C_CLASS = c_CLASS;
}
public String getCLASS_NAME() {
return CLASS_NAME;
}
public void setCLASS_NAME(String cLASS_NAME) {
CLASS_NAME = cLASS_NAME;
}
public String getProduceNum_bq() {
return produceNum_bq;
}
public void setProduceNum_bq(String produceNum_bq) {
this.produceNum_bq = produceNum_bq;
}
public String getProduceNum_tq() {
return produceNum_tq;
}
public void setProduceNum_tq(String produceNum_tq) {
this.produceNum_tq = produceNum_tq;
}
public String getProduceNum_bl() {
return produceNum_bl;
}
public void setProduceNum_bl(String produceNum_bl) {
this.produceNum_bl = produceNum_bl;
}
public String getProduceNum_pt() {
return produceNum_pt;
}
public void setProduceNum_pt(String produceNum_pt) {
this.produceNum_pt = produceNum_pt;
}
public String getSellNum_bq() {
return sellNum_bq;
}
public void setSellNum_bq(String sellNum_bq) {
this.sellNum_bq = sellNum_bq;
}
public String getSellNum_tq() {
return sellNum_tq;
}
public void setSellNum_tq(String sellNum_tq) {
this.sellNum_tq = sellNum_tq;
}
public String getSellNum_bl() {
return sellNum_bl;
}
public void setSellNum_bl(String sellNum_bl) {
this.sellNum_bl = sellNum_bl;
}
public String getSellNum_pt() {
return sellNum_pt;
}
public void setSellNum_pt(String sellNum_pt) {
this.sellNum_pt = sellNum_pt;
}
public String getStock_bq() {
return stock_bq;
}
public void setStock_bq(String stock_bq) {
this.stock_bq = stock_bq;
}
public String getStock_tq() {
return stock_tq;
}
public void setStock_tq(String stock_tq) {
this.stock_tq = stock_tq;
}
public String getStock_bl() {
return stock_bl;
}
public void setStock_bl(String stock_bl) {
this.stock_bl = stock_bl;
}
public String getStock_pt() {
return stock_pt;
}
public void setStock_pt(String stock_pt) {
this.stock_pt = stock_pt;
}
public String getOnRoad_bq() {
return onRoad_bq;
}
public void setOnRoad_bq(String onRoad_bq) {
this.onRoad_bq = onRoad_bq;
}
public String getOnRoad_tq() {
return onRoad_tq;
}
public void setOnRoad_tq(String onRoad_tq) {
this.onRoad_tq = onRoad_tq;
}
public String getOnRoad_bl() {
return onRoad_bl;
}
public void setOnRoad_bl(String onRoad_bl) {
this.onRoad_bl = onRoad_bl;
}
public String getOnRoad_pt() {
return onRoad_pt;
}
public void setOnRoad_pt(String onRoad_pt) {
this.onRoad_pt = onRoad_pt;
}
public String getSingleSellAmount_bq() {
return singleSellAmount_bq;
}
public void setSingleSellAmount_bq(String singleSellAmount_bq) {
this.singleSellAmount_bq = singleSellAmount_bq;
}
public String getSingleSellAmount_tq() {
return singleSellAmount_tq;
}
public void setSingleSellAmount_tq(String singleSellAmount_tq) {
this.singleSellAmount_tq = singleSellAmount_tq;
}
public String getSingleSellAmount_bl() {
return singleSellAmount_bl;
}
public void setSingleSellAmount_bl(String singleSellAmount_bl) {
this.singleSellAmount_bl = singleSellAmount_bl;
}
public String getSingleSellAmount_pt() {
return singleSellAmount_pt;
}
public void setSingleSellAmount_pt(String singleSellAmount_pt) {
this.singleSellAmount_pt = singleSellAmount_pt;
}
public String getBsSellAmount_bq() {
return bsSellAmount_bq;
}
public void setBsSellAmount_bq(String bsSellAmount_bq) {
this.bsSellAmount_bq = bsSellAmount_bq;
}
public String getBsSellAmount_tq() {
return bsSellAmount_tq;
}
public void setBsSellAmount_tq(String bsSellAmount_tq) {
this.bsSellAmount_tq = bsSellAmount_tq;
}
public String getBsSellAmount_bl() {
return bsSellAmount_bl;
}
public void setBsSellAmount_bl(String bsSellAmount_bl) {
this.bsSellAmount_bl = bsSellAmount_bl;
}
public String getBsSellAmount_pt() {
return bsSellAmount_pt;
}
public void setBsSellAmount_pt(String bsSellAmount_pt) {
this.bsSellAmount_pt = bsSellAmount_pt;
}
public String getCiga_tax_bq() {
return ciga_tax_bq;
}
public void setCiga_tax_bq(String ciga_tax_bq) {
this.ciga_tax_bq = ciga_tax_bq;
}
public String getCiga_tax_tq() {
return ciga_tax_tq;
}
public void setCiga_tax_tq(String ciga_tax_tq) {
this.ciga_tax_tq = ciga_tax_tq;
}
public String getCiga_tax_bl() {
return ciga_tax_bl;
}
public void setCiga_tax_bl(String ciga_tax_bl) {
this.ciga_tax_bl = ciga_tax_bl;
}
public String getCiga_tax_pt() {
return ciga_tax_pt;
}
public void setCiga_tax_pt(String ciga_tax_pt) {
this.ciga_tax_pt = ciga_tax_pt;
}
public String getCIG_NAME() {
return CIG_NAME;
}
public void setCIG_NAME(String cIG_NAME) {
CIG_NAME = cIG_NAME;
}
}
|
Java
|
UTF-8
| 1,540 | 3.890625 | 4 |
[
"Apache-2.0"
] |
permissive
|
package org.zongjieli.leetcode.question.daily.year2021.month9.week2;
/**
* 一个班级里有 n 个学生,编号为 0 到 n - 1
* 每个学生会依次回答问题,编号为 0 的学生先回答,,然后是编号为 1 的学生,以此类推
* 直到编号为 n - 1 的学生,然后老师会重复这个过程,重新从编号为 0 的学生开始回答问题
*
* 给一个长度为 n 且下标从 0 开始的整数数组 chalk 和一个整数 k
* 一开始粉笔盒里总共有 k 支粉笔
* 当编号为 i 的学生回答问题时,他会消耗 chalk[i] 支粉笔
* 如果剩余粉笔数量严格小于 chalk[i],那么学生 i 需要补充粉笔
*
* 请你返回需要补充粉笔的学生编号
*
* chalk.length == n
* 1 <= n <= 10^5
* 1 <= chalk[i] <= 10^5
* 1 <= k <= 10^9
*
* @author Li.zongjie
* @date 2021/9/10
* @version 1.0
*/
public class Z5FindSupplement {
public int chalkReplacer(int[] chalk, int k) {
if (k < chalk[0]){
return 0;
}
int i = 0;
while (++i < chalk.length){
if ((chalk[i] += chalk[i - 1]) > k){
return i;
}
}
k %= chalk[chalk.length - 1];
i = -1;
while (k >= chalk[++i]){ }
return i;
}
public static void main(String[] args) {
Z5FindSupplement test = new Z5FindSupplement();
System.out.println(test.chalkReplacer(new int[]{5,1,5},22));
System.out.println(test.chalkReplacer(new int[]{3,4,1,2},25));
}
}
|
Python
|
UTF-8
| 600 | 2.640625 | 3 |
[] |
no_license
|
import sklearn
import pickle
import numpy as np
from random import randint
filename = 'finalized_model.sav'
loaded_model = pickle.load(open(filename, 'rb'))
input_file = open("data_clean_imputed.csv","r")
lines = input_file.readlines()
CLASSIFICATION_TYPE = 2
NUM_PCA = 270;
X = []
for line in lines:
tokens = line.strip().split(",")
X.append(map(float, tokens[0:NUM_PCA]))
patientname="John Doe"
num=randint(0,NUM_PCA-1)
age=X[num][0]
sex=""
if(X[num][1]==0):
sex="Male"
else:
sex="Female"
height=X[num][2] #in cm
weight=X[num][3] #in kg
ypred=loaded_model.predict(X[num])
print ypred
|
Java
|
UTF-8
| 522 | 2 | 2 |
[] |
no_license
|
package main;
import edu.wpi.first.wpilibj.Talon;
import lib.joystick.XboxController;
public interface HardwareAdapter extends Constants {
//DriveTrain Talon's
public static final Talon forwardTalon = new Talon(DRIVETRAIN_TALON_FORWARD_PWM_OUT);
public static final Talon leftTalon = new Talon(DRIVETRAIN_TALON_LEFT_PWM_OUT);
public static final Talon rightTalon = new Talon(DRIVETRAIN_TALON_RIGHT_PWM_OUT);
//Joystick's
public static final XboxController xbox = new XboxController(OI_JOYSTICK_DRIVE_USB_IN);
}
|
SQL
|
UTF-8
| 1,658 | 3.671875 | 4 |
[] |
no_license
|
-- drop table nut_coffee.recipe_ingredients;
CREATE TABLE nut_coffee.recipe_ingredients
(
recipe_id bigint unsigned NOT NULL COMMENT 'id продаваемого товара',
ingredient_id bigint unsigned NOT NULL COMMENT 'id ингредиента',
measurement_unit_id bigint unsigned NOT NULL COMMENT 'id единицы измерения объема товара',
volume int unsigned NOT NULL default 1 COMMENT 'Объем ингредиента необходимый для производства товара',
constraint fk_recipe_ingredients_recipes
FOREIGN KEY (recipe_id) REFERENCES nut_coffee.recipes (Id) ON DELETE CASCADE,
constraint fk_recipes_goods
FOREIGN KEY (ingredient_id) REFERENCES nut_coffee.goods (Id) ON DELETE restrict,
constraint fk_recipes_measurement_unit
FOREIGN KEY (measurement_unit_id) REFERENCES nut_coffee.measurement_units (Id) ON DELETE restrict
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_unicode_ci
COMMENT ='Ингредиенты рецепт';
insert into nut_coffee.recipe_ingredients (recipe_id, ingredient_id, measurement_unit_id, volume)
values (1, 1, 9, 1),
(1, 12, 5, 30),
(1, 10, 5, 150),
(2, 1, 9, 1),
(2, 12, 5, 120),
(3, 1, 9, 1),
(3, 12, 5, 50),
(3, 10, 5, 200),
(4, 1, 9, 1),
(4, 12, 5, 50),
(4, 10, 5, 150),
(4, 11, 5, 30),
(5, 1, 9, 1),
(5, 12, 5, 70),
(5, 10, 5, 200),
(5, 11, 5, 30),
(6, 1, 9, 1),
(6, 12, 5, 50),
(6, 10, 5, 150),
(6, 24, 5, 30);
|
Java
|
UTF-8
| 727 | 2.84375 | 3 |
[] |
no_license
|
package domain.entity;
public class Liceu {
private final String nume;
private final String adresa;
private final String localitate;
public Liceu(String nume, String adresa, String localitate) {
this.nume = nume;
this.adresa = adresa;
this.localitate = localitate;
}
public String getNume() {
return nume;
}
public String getAdresa() {
return adresa;
}
public String getLocalitate() {
return localitate;
}
public void afisare(){
System.out.print("Nume liceu: " + nume);
System.out.print("; Adresa: " + adresa);
System.out.println("; Localitate: " + localitate);
}
}
|
Java
|
UTF-8
| 3,953 | 2.359375 | 2 |
[] |
no_license
|
package edu.uga.cs4300.logiclayer;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import edu.uga.cs4300.objectlayer.Recipe;
import edu.uga.cs4300.objectlayer.User;
import edu.uga.cs4300.persistlayer.RecipePersistImpl;
public class RecipeLogicImpl {
RecipePersistImpl userPersist;
public RecipeLogicImpl() {
userPersist = new RecipePersistImpl();
}
public int addUser(String first_name, String last_name, String username, String password, String email) {
User u = new User(first_name, last_name, username, password, email);
return userPersist.persistUser(u);
}
public User validateLogin(String username, String password) {
return userPersist.checkUser(username, password);
}
public List<Recipe> retrieveRecipes() {
return userPersist.getRecipes();
}
public int createRecipe(String recipeName, List<String> ingredients, List<String> instructions, String permission,
int user_id, InputStream fileContent, String category) {
return userPersist.addRecipeToDatabase(recipeName, ingredients, instructions, permission, user_id, fileContent, category);
}
public List<Recipe> getPopRecipes() {
return userPersist.getPopularRecipes();
}
public Recipe getRecipeById(int id) {
return userPersist.getRecipe(id);
}
public int sendNewUserInfo(String fname, String lname, String uname, String password, String email,
InputStream fileContent) {
User u = new User(fname, lname, uname, password, email);
return userPersist.persistUserProfile(u, fileContent);
}
public ArrayList<Recipe> getMyRecipes(int userID)
{
return userPersist.persistMyRecipes(userID);
}
//Calls persist layer to sort recipes by category and display them.
public List<Recipe> viewByCategory(String category) {
return userPersist.viewByCategory(category);
}
//Calls persist layer to search based on user input of category and search term.
public List<Recipe> Search(String category, String term) {
return userPersist.Search(category, term);
}
public List<Recipe> getUserRecipes(int id) {
return userPersist.getRecipesByUserId(id);
}
public User getUserInfo(int id) {
return userPersist.getInfoUser(id);
}
public Boolean checkFavorites(int recipeId, int userId) {
return userPersist.checkFavoriteRecipes(recipeId, userId);
}
public int favoriteRecipe(int recipeId, int userId) {
return userPersist.addToFavorites(recipeId, userId);
}
public User getUserByID(int userID)
{
return userPersist.getUserByID(userID);
}
public ArrayList<Recipe> getFavoriteRecipes (int userID)
{
return userPersist.getFavoriteRecipes(userID);
}
public ArrayList<Recipe> getSharedRecipes (int userID)
{
return userPersist.getSharedRecipes(userID);
}
//james--
public List<User> getFriends(int id) {
return userPersist.getFriends(id);
}
public List<User> getUsers(int id) {
return userPersist.getUsers(id);
}
public String addFriend(String friendId, int userId) throws NumberFormatException, SQLException {
return userPersist.addFriend(friendId, userId);
}
public List<User> getFriendRequests(int id) {
return userPersist.getFriendRequests(id);
}
public String acceptRequest(int userId, String friendId) {
return userPersist.acceptRequest(userId, friendId);
}
public String rejectRequest(int userId, String friendId) {
return userPersist.rejectRequest(userId, friendId);
}
//Logic layer to implement a ranking system for recipes
//Calls persist layer
public int Ranked(int id, int rank) {
System.out.println("LOGIC: RANK = " + rank);
return userPersist.UpdateRank(id, rank);
}
//Logic layer to check for duplicate username
//Calls persist layer
public boolean LogicCheckUser(String username) {
return userPersist.PersistCheckUser(username);
}
public void shareRecipe(int recipeID, int myID, int shareID)
{
userPersist.shareRecipe(recipeID, myID, shareID);
}
}
|
Markdown
|
UTF-8
| 2,148 | 2.53125 | 3 |
[] |
no_license
|
# Bouncing Line

## 원본
파일 구조와, 코드 스타일을 변경했습니다. 원본을 참고하고 싶으시면 아래 링크를 이용해주세요.
- **원작자**: Interactive Developer
- **링크**: [HTML5 Canvas Tutorial : 자바스크립트로 줄 튕기는 효과 만들기](https://www.youtube.com/watch?v=dXhAQbE8iBg&list=PLGf_tBShGSDNGHhFBT4pKFRMpiBrZJXCm&index=3)
## 개선점
### 1. 상수값 선언 분리
유지/보수가 용이하도록 상수값 선언을 별도의 config 파일로 분리시킴
### 2. 마우스 포인터 성능 개선
- 포인트 이벤트 리스너 최적화
- `pointermove` 이벤트 콜백 함수가 매번 실행되지 않도록, `pointerdown` 이벤트에서 등록되고 `pointerup` 이벤트에서 삭제되도록 수정
### 3. 줄 성능 개선
- 점과 직선의 거리 구하는 방법 단순화
- 기존 코드는 포인터와 줄 사이의 거리를 구하는 방법으로 벡터의 정사영 개념을 사용
- 직선의 방정식을 사용한 점과 직선 사이의 거리 공식으로 방법을 변경
- 포인터를 빠르게 움직이면 줄이 튕기지 않는 오류 발견
- 포인터를 빠르게 움직이면 `pointermove` 이벤트의 좌표가 감지 가능한 범위를 스킵하는 현상이 발생
- 이전 포인터 좌표를 기억하여, 현재 포인트 좌표와의 부등호가 다를 경우를 별도 처리하여 해결
- 줄 리사이징 성능 향상
- 브라우저 리사이징할 때 기존 코드는 모든 줄을 다시 만듬. 리사이징 시 기존의 줄 객체를 재활용하고 필요에 따라 새로운 객체를 추가/삭제하도록 변경
- 기존 코드에서 리사이징하면 줄 튕기는 에니메이션이 초기화되는 부자연스러움 발견. 기존 줄 객체를 재활용함으로써 라사이징 시에도 이 전의 움직임을 계속 이어나가도록 변경
### 4. 공 성능 개선
- 공의 속도가 빠를시 일부가 화면 밖으로 나가는 오류 수정
- 설정값을 통해 마우스를 이용한 포인터 이동과, 자동 이동르고 구분
|
C++
|
UTF-8
| 1,715 | 2.84375 | 3 |
[] |
no_license
|
#include "Alien.h"
#include "SpawnSystem.h"
Alien::Alien()
{
CreatePoints();
alive = false;
transform.SetVelocity(_speed, 0);
collisionFunction = std::bind(&Alien::Collide, this);
}
Alien::Alien(Player* player) : _player(player)
{
collisionFunction = std::bind(&Alien::Collide, this);
transform.SetVelocity(_speed,0);
CreatePoints();
}
Alien::~Alien()
{
}
void Alien::Reset()
{
alive = false;
_spawnSystem->AlienKilled(Time::time);
}
void Alien::CreatePoints()
{
_points = ResourceManager::getInstance()._shapes["alien"];
int alienBounds[4] = { -_alienBoundsValue, _alienBoundsValue, -_alienBoundsValue, _alienBoundsValue };
SetBoundingBox(alienBounds);
}
void Alien::Collide()
{
alive = false;
_spawnSystem->AlienKilled(Time::time);
}
void Alien::Update()
{
if (_player->alive == false)
{
return;
}
CalculateDirectionToPlayer();
transform.Move();
if (Time::time >= nextShotTime)
{
nextShotTime = Time::time + shotDelay;
Shoot();
}
}
void Alien::CalculateDirectionToPlayer()
{
Vector2 playerPos = _player->transform.GetPosition();
Vector2 currentPosition = transform.GetPosition();
directionToPlayer = (playerPos - currentPosition).Normalized();
transform.SetVelocity(directionToPlayer.x * _speed, directionToPlayer.y * _speed);
}
void Alien::Shoot()
{
Vector2 spawnLocation = transform.GetPosition();
spawnLocation.x += directionToPlayer.x * shotSpawnOffset;
spawnLocation.y += directionToPlayer.y * shotSpawnOffset;
_spawnSystem->SpawnProjectile(spawnLocation, directionToPlayer);
}
void Alien::Instantiate(Vector2 spawnPosition)
{
transform.SetPosition(spawnPosition);
alive = true;
}
void Alien::ReceivePlayer(Player* player)
{
_player = player;
}
|
Java
|
UTF-8
| 1,928 | 2.4375 | 2 |
[] |
no_license
|
package com.stackroute.musicservice.repository;
import com.stackroute.musicservice.domain.Track;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@DataJpaTest
public class TrackRepositoryTest {
@Autowired
private TrackRepository trackRepository;
private Track track;
@Before
public void setUp()
{
track = new Track();
track.setTrackID(10);
track.setTrackName("John");
track.setTrackComments("Jennygrd");
}
@After
public void tearDown(){
trackRepository.deleteAll();
}
@Test
public void testSaveTrack(){
trackRepository.save(track);
Track fetchTrack = trackRepository.findById(track.getTrackID()).get();
Assert.assertEquals(10,fetchTrack.getTrackID());
}
@Test
public void testSaveTrackFailure(){
Track testTrack = new Track(10,"John","Jennygrd");
trackRepository.save(track);
Track fetchTrack = trackRepository.findById(track.getTrackID()).get();
Assert.assertNotSame(testTrack,track);
}
@Test
public void testGetAlltrack(){
Track track = new Track(2,"faded","allenwalker");
Track track1 = new Track(1,"fade","allen");
trackRepository.save(track);
trackRepository.save(track1);
List<Track> list = (List<Track>) trackRepository.findAll();
Assert.assertEquals("faded",list.get(1).getTrackName());
}
}
|
C++
|
GB18030
| 1,616 | 3.25 | 3 |
[] |
no_license
|
// poj 1041.John's trip
// ŷ· ڽӾǵͱߵĹϵ
// references:
// http://blog.csdn.net/xymscau/article/details/6450657
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int graph[50][2000]; //[][öı] = һ
int vis[2000];
int degree[50];
int maxEdge;
int stack[2000];
int top;
void Euler(int s)
{
for(int i=1; i<=maxEdge; i++)
{
if(!vis[i] && graph[s][i])
{
vis[i] = 1;
//stack[top++] = i; //ע˴ջĻܻ
//мһ㣬ʼչŷ·һ...
Euler(graph[s][i]);
stack[top++] = i; //ŷ·ٻ
}
}
}
int main()
{
int x, y, z, s;
while(scanf("%d%d", &x, &y) != EOF && x && y)
{
memset(degree, 0, sizeof(degree));
memset(vis, 0, sizeof(vis));
memset(graph, 0, sizeof(graph));
top = 0;
maxEdge = 0;
scanf("%d", &z);
graph[x][z] = y;
graph[y][z] = x;
degree[x]++;
degree[y]++;
s = min(x, y);
maxEdge = max(maxEdge, z);
bool flag = 1;
while(scanf("%d%d", &x, &y) != EOF && x && y)
{
scanf("%d", &z);
graph[x][z] = y;
graph[y][z] = x;
degree[x]++;
degree[y]++;
maxEdge = max(maxEdge, z);
}
for(int i=1; i<45; i++)
{
if(degree[i] % 2)
flag = 0;
}
if(!flag)
{
printf("Round trip does not exist.\n");
continue;
}
Euler(s);
for(int i=0; i<top-1; i++)
printf("%d ", stack[i]);
printf("%d\n", stack[top-1]);
}
return 0;
}
|
Java
|
UTF-8
| 591 | 1.921875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package features;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.noear.solon.test.HttpTester;
import org.noear.solon.test.SolonJUnit4ClassRunner;
import org.noear.solon.test.SolonTest;
import webapp.App;
/**
* @author noear 2023/6/13 created
*/
@RunWith(SolonJUnit4ClassRunner.class)
@SolonTest(App.class)
public class GatewayTest extends HttpTester {
@Test
public void api_path() throws Exception {
String rst = path("/demo53/api2/hello/solon").get();
assert rst != null;
assert "solon".equals(rst) || rst.contains("solon");
}
}
|
JavaScript
|
UTF-8
| 4,472 | 3.71875 | 4 |
[] |
no_license
|
/**
* 格式化时间
* type:1 return 2018/05/01 01:01:01
* type:2 return 2018-05-01
* type:3 return 刚刚 xx分钟前 昨天
*/
let formatTime = (date, type = 1) => {
date = formatTimeZone(date, 0)
let year = date.getFullYear()
let month = date.getMonth() + 1
let day = date.getDate()
let hour = date.getHours()
let minute = date.getMinutes()
let second = date.getSeconds()
if (type === 1) {
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
} else if (type === 2) {
return [year, month, day].map(formatNumber).join('-')
} else {
let jm = new Date()
let Fo = jm.getTime() - date // 当前时间转化成毫秒,与返回时间对比
if (Fo <= 6e4) return '刚刚' // 小于一分钟,替换返回时间为 ‘刚刚’
let Qq = jm.getHours() * 36e5 + jm.getMinutes() * 6e4 + jm.getSeconds() * 1e3 // 当前时间距离昨天0点的时间毫秒数
if (day === jm.getDate()) { // 如果返回时间与当前时间在一天
if (Fo < 36e5) { // 且小于一小时
let bOh = Math.floor(Fo / 6e4)
return bOh + '分钟前' // 返回 ‘距离当前时间几分钟前’
} else if (hour < 12) {
return '上午' + [hour, minute].map(formatNumber).join(':') // 返回今天的上午时间
} else {
return '下午' + [hour, minute].map(formatNumber).join(':') // 返回今天的下午时间
}
} else {
if (Fo < Qq) { /* Fo < Qq + 864e5 */ // 如果当前时间差大于 当前时间距离昨天0点的时间毫秒数 则为昨天
return '昨天' + [hour, minute].map(formatNumber).join(':')
} else {
let hq = jm.getFullYear() // 当前年份
let bOg = new Date(hq, 0, 1) // 今年1月1号距离有计数年份的毫秒数
let Qq = jm.getTime() - bOg.getTime() // 当前时间距离1月1号的时间差
if (Fo < Qq) { // 当前时间与返回时间差值,小于 当前时间距离1月1号的时间差
return year + '年' + month + '月' + day + '日' + [hour, minute].map(formatNumber).join(':') // 返回 具体时间
}
// return year + '年' + month + '月' + day + '日' // 否则返回, 只返回 年 月 日
return year + '年' + month + '月' + day + '日' + [hour, minute].map(formatNumber).join(':')
}
}
}
}
/**
* 时区转换
* @param date 原时区时间
* @param offset 需要设置的时区
* @returns {Date} 转换后的时区时间
*/
let formatTimeZone = (date, offset) => {
let d = new Date(date) // 创建一个Date对象 time时间 offset 时区 中国为 8
let localTime = d.getTime()
let localOffset = d.getTimezoneOffset() * 60000 // 获得当地时间偏移的毫秒数
let utc = localTime + localOffset // utc即GMT时间
let wishTime = utc + (3600000 * offset)
return new Date(wishTime)
}
/**
* 补全 0
* @param n
* @returns {any}
*/
let formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
/**
* 时间转换 00:00
* @param duration
* @returns {string}
*/
let formatduration = duration => {
duration = new Date(duration)
return formatNumber(duration.getMinutes()) + ':' + formatNumber(duration.getSeconds())
}
/**
* 数字转分钟 70 => 01:10'
* @param second
* @returns {string}
*/
function numToTime(second) {
let mm = Math.floor(second / 60)
let ss = Math.ceil(second % 60)
let minute = mm < 10 ? ('0' + mm.toString()) : mm.toString()
let seconds = ss < 10 ? ('0' + ss.toString()) : ss.toString()
return minute + ':' + seconds + ''
}
/**
* 拓展对象
* newconfig = extend({},defaultConfig,myconfig)
*/
function extend(target) {
let sources = Array.prototype.slice.call(arguments, 1)
for (let i = 0; i < sources.length; i += 1) {
let source = sources[i]
for (let key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key]
}
}
}
return target
}
/**
* 地区转换
* @param target
* @param id
* @param area
*/
function toggleArea(target, id = [], area) {
id.forEach((item, index) => {
for (let key in area) {
if (target[item] === +key) {
target[item] = area[key]
}
}
// area.forEach((value, index) => {
// if (target[item] === +value.ID) {
// target[item] = value.name
// }
// })
})
}
export default {
formatTime,
formatduration,
numToTime,
extend,
toggleArea
}
|
Markdown
|
UTF-8
| 273 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
---
title: "Are science and spirituality the same?"
date: 2021-02-19
---
So today's topic is how when does science transform into spirituality?
Traditinal science had always told us that everything in reality is composed by particles formed by a nucleos that yields matter
|
Java
|
UTF-8
| 321 | 1.617188 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.ifinal.finalframework.dashboard.web.entity;
import java.io.Serializable;
import lombok.Data;
/**
* @author likly
* @version 1.0.0
* @since 1.0.0
*/
@Data
public class ResultMapping implements Serializable {
private String name;
private Class<?> type;
private boolean required = true;
}
|
JavaScript
|
UTF-8
| 2,533 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
$( document ).ready( function () {
// TOPHEADER
// -------------------------------------------------------------
var topNavLink = document.querySelector( '#topNavLink' );
var topHeader = document.querySelector( '#topHeader' );
topNavLink.addEventListener( 'click', function ( event ) {
event.preventDefault();
if ( topHeader.className === 'topnav' ) {
topHeader.className += ' topnav--responsive';
} else {
topHeader.className = 'topnav';
}
});
// HERO COUNTER ------------------------------------------------
var countDownDate = new Date( 'Feb 5, 2017 15:37:25' ).getTime();
var x = setInterval( function () {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor( distance / ( 1000 * 60 * 60 * 24 ));
var hours = Math.floor(( distance % ( 1000 * 60 * 60 * 24 )) / ( 1000 * 60 * 60 ));
var minutes = Math.floor(( distance % ( 1000 * 60 * 60 )) / ( 1000 * 60 ));
var seconds = Math.floor(( distance % ( 1000 * 60)) / 1000 );
if ( days < 10 ) { days = '0' + days; }
if ( hours < 10 ) { hours = '0' + hours; }
if ( minutes < 10 ) { minutes = '0' + minutes; }
if ( seconds < 10 ) { seconds = '0' + seconds; }
// Display the result in the element with id='demo'
document.getElementById( 'countdown__days' ).innerHTML = days;
document.getElementById( 'countdown__hours' ).innerHTML = hours;
document.getElementById( 'countdown__minutes' ).innerHTML = minutes;
document.getElementById( 'countdown__seconds' ).innerHTML = seconds;
// If the count down is finished, write some text
if ( distance < 0 ) {
clearInterval( x );
document.getElementById( 'countdown' ).innerHTML = 'EXPIRED';
}
}, 1000 );
// -----------------------------------------------------------------------
// ACCORDION -------------------------------------------------------------
var buttons = $( '.schedule .schedule__button' );
buttons.on( 'click', function () {
$( this ).toggleClass( 'is-active' );
$( this ).next( '.schedule__panel' ).toggleClass( 'is-show' ).siblings( '.schedule__panel' ).removeClass( 'is-show' );
});
// -----------------------------------------------------------------------
});
|
Java
|
UTF-8
| 1,553 | 2.953125 | 3 |
[] |
no_license
|
package core.java.chapter9.linkedList;
import com.sun.xml.internal.bind.v2.TODO;
import java.util.*;
/**
* @author: huakaimay
* @since: 2020-11-03
*/
public class LinkedListTest {
public static void main(String[] args) {
LinkedList<String> a = new LinkedList<>();
a.addLast("Amy");
a.addLast("Carl");
a.addLast("Erica");
LinkedList<String> b= new LinkedList<>();
b.addLast("Bob");
b.addLast("Doug");
b.addLast("Frances");
b.addLast("Gloria");
ListIterator<String> aIter = a.listIterator();
Iterator<String> bIter = b.iterator();
while (bIter.hasNext()) {
if(aIter.hasNext()) {
aIter.next();
}
aIter.add(bIter.next());
}
System.out.println(a);
bIter = b.iterator();
while (bIter.hasNext()) {
bIter.next();
if(bIter.hasNext()) {
bIter.next();
bIter.remove();
}
}
System.out.println(b);
a.removeAll(b);
System.out.println(a);
HashMap<Object, Object> hashMap = new HashMap<>();
// hashMap.put("1",1);
Collection<Object> values = hashMap.values();
for(Map.Entry<Object, Object> map : hashMap.entrySet()) {
map.getKey();
map.getValue();
hashMap.put("2",2);
}
hashMap.forEach((k, v) -> {
// TODO
System.out.println("k: " + k);
});
}
}
|
Python
|
UTF-8
| 211 | 2.984375 | 3 |
[] |
no_license
|
# coding: utf-8
# 对unicode码进行排序
import pyuca
coll = pyuca.Collator()
fruits = ['caju', 'atemoia', 'cajá', 'açaí', 'acerola']
sorted_fruits = sorted(fruits, key=coll.sort_key)
print(sorted_fruits)
|
C++
|
UTF-8
| 4,719 | 3.765625 | 4 |
[
"BSD-3-Clause"
] |
permissive
|
#pragma once
#include <stdint.h>
//
// Declaration
//
template< typename Type, uint8_t Capacity >
class Queue
{
public:
static_assert(Capacity > 0, "Attempt to create a Queue with Capacity less than 1");
static_assert(Capacity < 128, "Attempt to create a Queue with Capacity greater than 127");
using ItemType = Type;
using IndexType = uint8_t;
using IndexOfType = int8_t;
constexpr static const IndexType FirstIndex = 0;
constexpr static const IndexType LastIndex = Capacity - 1;
private:
ItemType items[Capacity];
IndexType next;
public:
Queue(void);
bool isEmpty(void) const; // O(1)
bool isFull(void) const; // O(1)
IndexType getCount(void) const; // O(1)
constexpr IndexType getCapacity(void) const; // O(1)
ItemType & peek(void); // O(1)
const ItemType & peek(void) const; // O(1)
bool enqueue(const ItemType & item); // O(1)
bool enqueue(ItemType && item); // O(1)
ItemType dequeue(void); // O(n)
void drop(void); // O(n)
void clear(void); // O(n)
bool contains(const ItemType & item) const; // O(n)
// Returns -1 if item not found
IndexOfType indexOf(const ItemType & item) const; // O(n)
ItemType & operator [] (const IndexType index); // O(1)
const ItemType & operator [] (const IndexType index) const; // O(1)
};
//
// Definition
//
template< typename Type, uint8_t Capacity >
Queue< Type, Capacity >::Queue(void)
: items(), next(0)
{
}
template< typename Type, uint8_t Capacity >
bool Queue< Type, Capacity >::isEmpty(void) const // O(1)
{
return (this->next == FirstIndex);
}
template< typename Type, uint8_t Capacity >
bool Queue< Type, Capacity >::isFull(void) const // O(1)
{
return (this->next == this->getCapacity());
}
template< typename Type, uint8_t Capacity >
typename Queue< Type, Capacity >::IndexType Queue< Type, Capacity >::getCount(void) const // O(1)
{
return this->next;
}
template< typename Type, uint8_t Capacity >
constexpr typename Queue< Type, Capacity >::IndexType Queue< Type, Capacity >::getCapacity(void) const // O(1)
{
return static_cast<IndexType>(Capacity);
}
template< typename Type, uint8_t Capacity >
typename Queue< Type, Capacity >::ItemType & Queue< Type, Capacity >::peek(void) // O(1)
{
return this->items[0];
}
template< typename Type, uint8_t Capacity >
const typename Queue< Type, Capacity >::ItemType & Queue< Type, Capacity >::peek(void) const // O(1)
{
return this->items[0];
}
template< typename Type, uint8_t Capacity >
typename Queue< Type, Capacity >::ItemType Queue< Type, Capacity >::dequeue(void) // O(n)
{
const auto result = this->items[this->next]; // ought to be std::move
--this->next;
// i + 1 == this->next at the last iteration
for(uint8_t i = 0; i < this->next; ++i)
this->items[i] = this->items[i + 1];
return result;
}
template< typename Type, uint8_t Capacity >
bool Queue< Type, Capacity >::enqueue(const typename Queue< Type, Capacity >::ItemType & item) // O(1)
{
if (this->isFull())
return false;
this->items[this->next] = item;
++this->next;
return true;
}
template< typename Type, uint8_t Capacity >
bool Queue< Type, Capacity >::enqueue(typename Queue< Type, Capacity >::ItemType && item) // O(1)
{
if (this->isFull())
return false;
this->items[this->next] = item; // ought to be std::move
++this->next;
return true;
}
template< typename Type, uint8_t Capacity >
void Queue< Type, Capacity >::drop(void) // O(1)
{
--this->next;
// i + 1 == this->next at the last iteration
for(uint8_t i = 0; i < this->next; ++i)
this->items[i] = this->items[i + 1];
this->items[this->next].~ItemType();
}
template< typename Type, uint8_t Capacity >
void Queue< Type, Capacity >::clear(void) // O(n)
{
for (IndexType i = 0; i < this->next; ++i)
(&this->items[i])->~ItemType();
this->next = 0;
}
template< typename Type, uint8_t Capacity >
bool Queue< Type, Capacity >::contains(const typename Queue< Type, Capacity >::ItemType & item) const // O(n)
{
return this->indexOf(item) != -1;
}
template< typename Type, uint8_t Capacity >
typename Queue< Type, Capacity >::IndexOfType Queue< Type, Capacity >::indexOf(const typename Queue< Type, Capacity >::ItemType & item) const // O(n)
{
for (IndexType i = 0; i < this->next; ++i)
if (this->items[i] == item)
return i;
return -1;
}
template< typename Type, uint8_t Capacity >
typename Queue< Type, Capacity >::ItemType & Queue< Type, Capacity >::operator [] (const typename Queue< Type, Capacity >::IndexType index) // O(1)
{
return this->items[index];
}
template< typename Type, uint8_t Capacity >
const typename Queue< Type, Capacity >::ItemType & Queue< Type, Capacity >::operator [] (const typename Queue< Type, Capacity >::IndexType index) const // O(1)
{
return this->items[index];
}
|
Java
|
UTF-8
| 309 | 1.75 | 2 |
[] |
no_license
|
package com.demo.nspl.restaurantlite.SMS;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface InterfaceCheckCustCreditSMS {
@GET("DeveloperApiV1/CheckCustCreditSMS")
Call<ClsCheckCustCreditSMSParams> value(@Query("CustomerCode") String CustomerCode);
}
|
Java
|
UTF-8
| 1,406 | 2.5625 | 3 |
[] |
no_license
|
package com.project.spring.app.employeeSkill;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
@Entity
@Table(name = "skill")
public class Skill {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;
@Column(name = "skillName")
private String skillName;
@NotNull
@Column(name = "description")
private String description;
public Skill() {
}
public Skill(String skillName, String description) {
super();
this.skillName = skillName;
this.description = description;
}
public Skill(int id,String skillName, String description) {
super();
this.id = id;
this.skillName = skillName;
this.description = description;
}
public String getSkillName() {
return skillName;
}
public void setSkillName(String skillName) {
this.skillName = skillName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public long getId() {
return id;
}
@Override
public String toString() {
String result = String.format("Skill[id=%d, skillName='%s', description='%s']", id, skillName, description);
return result;
}
}
|
Java
|
UTF-8
| 653 | 2.96875 | 3 |
[] |
no_license
|
package objects;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
/**
* Class for a (non-blocking) park
*/
public class Park extends Block {
/**
* Creates a new park
*
* @param pos_x X index starting at 0 (will get transformed to coordinate after level-init)
* @param pos_y Y index starting at 0 (will get transformed to coordinate after level-init)
*/
public Park(int pos_x, int pos_y) {
super(pos_x, pos_y, false);
try {
this.image = new Image("/res/img/objects/park.png");
} catch (SlickException e) {
e.printStackTrace();
}
}
}
|
C++
|
UTF-8
| 1,983 | 2.53125 | 3 |
[] |
no_license
|
#ifndef BtaCandListIterator_hh
#define BtaCandListIterator_hh
//////////////////////////////////////////////////////////////////////////
// //
// BtaCandListIterator //
// //
// Iterator class for BtaCandList //
// //
// Author List: //
// Marcel Kunze, RUB, Feb. 99 //
// Copyright (C) 1999-2001, Ruhr-University Bochum. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TObject.h"
class BtaCandidate;
class BtaCandList;
class BtaCandListIterator : public TObject {
public:
BtaCandListIterator(BtaCandList &);
// Constructor taking a corresponding list as argument. Starting at the
// first element.
BtaCandListIterator(const BtaCandListIterator &);
// Copy constructor.
~BtaCandListIterator();
BtaCandidate * next();
// Returns a pointer to the current object in the associated list, moving
// forward to the next. Returns 0 if all objects are done.
BtaCandidate * previous();
// Moves backward one step in the list and returns the object found there.
// If current object is the first in the list, no stepping is done and 0 is
// returned.
BtaCandidate * current();
// Returns a pointer to the current object in the associated list,
// without incrementing the index.
// public:
int index() const;
void rewind();
// Rewinds the iterator to the first element of the list.
void skip(int);
// Move iterator forward or backward.
void skipAll();
// Move iterator past last element.
private:
BtaCandList * l; //! Pointer to the associated list.
int i; //! Current position in the associated list.
public:
ClassDef(BtaCandListIterator,1) // Iterator for BtaCandList
};
#endif
|
Java
|
UTF-8
| 3,121 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
package de.digitalcollections.prosemirror.model.jackson.contentblocks;
import de.digitalcollections.prosemirror.model.api.contentblocks.Heading;
import de.digitalcollections.prosemirror.model.api.contentblocks.Text;
import de.digitalcollections.prosemirror.model.impl.contentblocks.HeadingImpl;
import de.digitalcollections.prosemirror.model.impl.contentblocks.TextImpl;
import de.digitalcollections.prosemirror.model.jackson.BaseProseMirrorObjectMapperTest;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class HeadingTest extends BaseProseMirrorObjectMapperTest {
@Test
public void testDefaultConstructor() throws Exception {
Heading heading = new HeadingImpl();
checkSerializeDeserialize(heading);
}
@Test
public void testWithTextContentOnly() throws Exception {
Heading heading = new HeadingImpl();
Text text = new TextImpl("Impressum");
heading.addContentBlock(text);
checkSerializeDeserialize(heading);
}
@Test
public void testWithAttributesOnly() throws Exception {
Heading heading = new HeadingImpl();
heading.addAttribute("level", 3);
checkSerializeDeserialize(heading);
}
@Test
public void testDeserializationWithEmptyContentAndEmptyAttributes() throws Exception {
String jsonString = "{\n"
+ " \"type\": \"heading\"\n"
+ " }";
Heading heading = mapper.readValue(jsonString, Heading.class);
assertThat(heading).isNotNull();
assertThat(heading.getAttributes()).isNull();
assertThat(heading.getContentBlocks()).isNull();
}
@Test
public void testDeserializationWithAttributesOnly() throws Exception {
String jsonString = "{\n"
+ " \"type\": \"heading\",\n"
+ " \"attrs\": {\n"
+ " \"level\": 3\n"
+ " }\n"
+ " },";
Heading heading = mapper.readValue(jsonString, Heading.class);
assertThat(heading).isNotNull();
assertThat(heading.getAttributes()).isNotNull();
assertThat(heading.getAttribute("level")).isEqualTo(3);
assertThat(heading.getAttribute("foo")).isNull();
}
@Test
public void testDeserializationWithAttributesAndContent() throws Exception {
String jsonString = "{\n"
+ " \"type\": \"heading\",\n"
+ " \"attrs\": {\n"
+ " \"level\": 3\n"
+ " },\n"
+ " \"content\": [\n"
+ " {\n"
+ " \"type\": \"text\",\n"
+ " \"text\": \"Impressum\"\n"
+ " }\n"
+ " ]\n"
+ " },";
Heading heading = mapper.readValue(jsonString, Heading.class);
assertThat(heading).isNotNull();
assertThat(heading.getAttributes()).isNotNull();
assertThat(heading.getAttribute("level")).isEqualTo(3);
assertThat(heading.getAttribute("foo")).isNull();
assertThat(heading.getContentBlocks()).isNotEmpty();
Text impressum = new TextImpl("Impressum");
assertThat(heading.getContentBlocks().get(0)).isEqualTo(impressum);
}
}
|
JavaScript
|
UTF-8
| 385 | 3.5 | 4 |
[] |
no_license
|
var imgUrl = null, degree = null
do {imgUrl = prompt('Enter link')} while (!imgUrl.startsWith('http'))
do {degree = prompt('Enter degree')} while (isNaN(degree))
var startDegree = 0
for ( var i = 1; i <= 5; i++) {
var img = document.createElement('img')
img.src = imgUrl
document.body.appendChild(img)
startDegree += +degree
img.style.transform = `rotate(${startDegree}deg)`
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.