hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
acbd3fb84e6b1741bb8bc95c02ea35bca0676ea3
5,166
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.registry.core.repositories; import org.apache.airavata.registry.core.utils.Committer; import org.apache.airavata.registry.core.utils.DBConstants; import org.apache.airavata.registry.core.utils.ObjectMapperSingleton; import org.dozer.Mapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import javax.persistence.Query; import java.util.ArrayList; import java.util.List; import java.util.Map; public abstract class AbstractRepository<T, E, Id> { private final static Logger logger = LoggerFactory.getLogger(AbstractRepository.class); private Class<T> thriftGenericClass; private Class<E> dbEntityGenericClass; public AbstractRepository(Class<T> thriftGenericClass, Class<E> dbEntityGenericClass) { this.thriftGenericClass = thriftGenericClass; this.dbEntityGenericClass = dbEntityGenericClass; } public T create(T t) { return update(t); } public T update(T t) { return mergeEntity(mapToEntity(t)); } protected E mapToEntity(T t) { Mapper mapper = ObjectMapperSingleton.getInstance(); return mapper.map(t, dbEntityGenericClass); } protected T mergeEntity(E entity) { Mapper mapper = ObjectMapperSingleton.getInstance(); E persistedCopy = execute(entityManager -> entityManager.merge(entity)); return mapper.map(persistedCopy, thriftGenericClass); } public boolean delete(Id id) { execute(entityManager -> { E entity = entityManager.find(dbEntityGenericClass, id); entityManager.remove(entity); return entity; }); return true; } public T get(Id id) { E entity = execute(entityManager -> entityManager .find(dbEntityGenericClass, id)); if(entity == null) return null; Mapper mapper = ObjectMapperSingleton.getInstance(); return mapper.map(entity, thriftGenericClass); } public List<T> select(String query, int offset) { List resultSet = (List) execute(entityManager -> entityManager.createQuery(query).setFirstResult(offset) .getResultList()); Mapper mapper = ObjectMapperSingleton.getInstance(); List<T> gatewayList = new ArrayList<>(); resultSet.stream().forEach(rs -> gatewayList.add(mapper.map(rs, thriftGenericClass))); return gatewayList; } public List<T> select(String query, int limit, int offset, Map<String, Object> queryParams) { int newLimit = limit < 0 ? DBConstants.SELECT_MAX_ROWS: limit; List resultSet = (List) execute(entityManager -> { Query jpaQuery = entityManager.createQuery(query); for (Map.Entry<String, Object> entry : queryParams.entrySet()) { jpaQuery.setParameter(entry.getKey(), entry.getValue()); } return jpaQuery.setFirstResult(offset).setMaxResults(newLimit).getResultList(); }); Mapper mapper = ObjectMapperSingleton.getInstance(); List<T> gatewayList = new ArrayList<>(); resultSet.stream().forEach(rs -> gatewayList.add(mapper.map(rs, thriftGenericClass))); return gatewayList; } public boolean isExists(Id id) { return get(id) != null; } public <R> R execute(Committer<EntityManager, R> committer){ EntityManager entityManager = null; try { entityManager = getEntityManager(); } catch (Exception e) { logger.error("Failed to get EntityManager", e); throw new RuntimeException("Failed to get EntityManager", e); } try { entityManager.getTransaction().begin(); R r = committer.commit(entityManager); entityManager.getTransaction().commit(); return r; } catch(Exception e) { logger.error("Failed to execute transaction", e); throw e; }finally { if (entityManager != null && entityManager.isOpen()) { if (entityManager.getTransaction().isActive()) { entityManager.getTransaction().rollback(); } entityManager.close(); } } } abstract protected EntityManager getEntityManager(); }
35.627586
112
0.660472
e82869bb504f49d9d5ef6378c4e7c7db3b7abaca
413
/** * @author YZhi * @date 2012-5-29 * @copyright 2012 haitian.com All rights reserved * @since V1.0 */ package dp.example.structure.facade.salary; /** * 奖金计算 * @author YZhi * @since 1.0 */ public class Bonus { private Attendance atte = new Attendance(); public int getBonus() { int workDays = atte.getWorkDays(); int bonus = workDays * 1000 / 30; return bonus; } }
17.956522
50
0.612591
55b2fee363fac2153d30925fefe9f4fc49ebbea6
5,652
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.studentattendance.web; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.thinkgem.jeesite.common.config.Global; import com.thinkgem.jeesite.common.mapper.JsonMapper; import com.thinkgem.jeesite.common.persistence.Page; import com.thinkgem.jeesite.common.web.BaseController; import com.thinkgem.jeesite.common.utils.StringUtils; import com.thinkgem.jeesite.modules.groupstu.entity.Groupstu; import com.thinkgem.jeesite.modules.groupstu.service.GroupstuService; import com.thinkgem.jeesite.modules.studentattendance.entity.Studentattendance; import com.thinkgem.jeesite.modules.studentattendance.service.StudentattendanceService; /** * 学生考勤信息Controller * @author lf * @version 2018-03-25 */ @Controller @RequestMapping(value = "${adminPath}/studentattendance/studentattendance") public class StudentattendanceController extends BaseController { @Autowired private StudentattendanceService studentattendanceService; @Autowired private GroupstuService groupstuService; @ModelAttribute public Studentattendance get(@RequestParam(required=false) String id) { Studentattendance entity = null; if (StringUtils.isNotBlank(id)){ entity = studentattendanceService.get(id); } if (entity == null){ entity = new Studentattendance(); } return entity; } @RequiresPermissions("studentattendance:studentattendance:view") @RequestMapping(value = {"list", ""}) public String list(Studentattendance studentattendance, HttpServletRequest request, HttpServletResponse response, Model model) { Page<Studentattendance> page = studentattendanceService.findPage(new Page<Studentattendance>(request, response), studentattendance); model.addAttribute("page", page); return "modules/studentattendance/studentattendanceList"; } @RequiresPermissions("studentattendance:studentattendance:view") @RequestMapping(value = "form") public String form(Studentattendance studentattendance, Model model) { Groupstu groupstu=new Groupstu(); groupstu.setTemp("1"); List<Groupstu> findList = groupstuService.findList(groupstu); List<Map <String,String>> sList = new ArrayList<Map <String,String>>(); for (int i = 0; i < findList.size(); i++) { Groupstu groupstu2 = findList.get(i); if(groupstu2.getGroupstudent().length()>1){ String[] stus = groupstu2.getGroupstudent().split(","); for (int a = 0; a< stus.length; a++) { Map <String,String> map =new HashMap<String,String>(); map.put("id", groupstu2.getId()); map.put("name", stus[a]); map.put("groupname", groupstu2.getGroupname()); sList.add(map); } }else{ Map <String,String> map =new HashMap<String,String>(); map.put("id", groupstu2.getId()); map.put("name", groupstu2.getGroupstudent()); map.put("groupname", groupstu2.getGroupname()); sList.add(map); } } model.addAttribute("sList", sList); model.addAttribute("studentattendance", studentattendance); return "modules/studentattendance/studentattendanceForm"; } @ResponseBody @RequestMapping(value = "save1") public String save1(Studentattendance studentattendance, Model model, RedirectAttributes redirectAttributes) { System.out.println(studentattendance.getId()+"=======ID======="); System.out.println(studentattendance.getGroupname()+"==小组名称============"); System.out.println(studentattendance.getStudent()+"=======学生======="); System.out.println(studentattendance.getMusical()+"=======乐器======="); System.out.println(studentattendance.getMback()+"=====返还日期========="); System.out.println(studentattendance.getClothing()+"=======服装======="); System.out.println(studentattendance.getCback()+"========返还日期======"); System.out.println(studentattendance.getWorktime1()+"======开始时间========"); System.out.println(studentattendance.getWorktime2()+"=======结束时间======="); System.out.println(studentattendance.getScore()+"=========分数====="); studentattendanceService.save(studentattendance); addMessage(redirectAttributes, "保存学生考勤信息成功"); return JsonMapper.toJsonString("ok"); } @RequiresPermissions("studentattendance:studentattendance:edit") @RequestMapping(value = "save") public String save(Studentattendance studentattendance, Model model, RedirectAttributes redirectAttributes) { studentattendanceService.save(studentattendance); addMessage(redirectAttributes, "保存学生考勤信息成功"); return "redirect:"+Global.getAdminPath()+"/studentattendance/studentattendance/?repage"; } @RequiresPermissions("studentattendance:studentattendance:edit") @RequestMapping(value = "delete") public String delete(Studentattendance studentattendance, RedirectAttributes redirectAttributes) { studentattendanceService.delete(studentattendance); addMessage(redirectAttributes, "删除学生考勤信息成功"); return "redirect:"+Global.getAdminPath()+"/studentattendance/studentattendance/?repage"; } }
42.818182
135
0.761323
fbf407657658f1ab2995fe15d20c2ba4dc4e3246
15,300
import java.awt.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; //import b787b /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ public class passng_details extends javax.swing.JFrame { /** * Creates new form passng_details */ String refno; String username; int logon; String name; int age; String gender; String seatno; String origin; String dest; String flightno; String date; String dep; String arr; String aircraft; String ebclass; String s_index; String fare; int i_index; int i_fare; Connection conn = null; public passng_details() { initComponents(); } public passng_details(String index, String refno, String ebclass, String s_date) throws SQLException { seatno = "10-A"; initComponents(); conn = DB_Connect.connect(); this.s_index = index; this.date = s_date; this.refno = refno; this.ebclass = ebclass; try { i_index = Integer.parseInt(index); }catch(NumberFormatException e) { Logger.getLogger(passng_details.class.getName()).log(Level.SEVERE, null, e); } try { String SQLQuery1 = "SELECT username FROM userdetails where logon = ?"; PreparedStatement pst1 = conn.prepareStatement(SQLQuery1); pst1.setInt(1, 1); ResultSet rs1 = pst1.executeQuery(); while (rs1.next()) { username = rs1.getString("username"); } String SQLQuery = "SELECT a.origin, a.dest, a.flightno , a.dep, a.arr, a.aircraft, b.efare, b.bfare\n" + "FROM public.flightdetails a,public.fare b where a.aircraft=b.aircraft and a.index = ?;"; PreparedStatement pst = conn.prepareStatement(SQLQuery); pst.setInt(1, i_index); ResultSet rs = pst.executeQuery(); while (rs.next()) { origin = rs.getString("origin"); dest = rs.getString("dest"); flightno = rs.getString("flightno"); dep = rs.getString("dep"); arr = rs.getString("arr"); aircraft = rs.getString("aircraft"); if ("Economy".equals(ebclass)) { fare = rs.getString("efare"); } else { fare = rs.getString("bfare"); } i_fare = Integer.parseInt(fare); } } catch (SQLException ex) { Logger.getLogger(show_flight.class.getName()).log(Level.SEVERE, null, ex); } jLabel4.setText(refno); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); pass_fname = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); pass_age = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); pass_gender = new javax.swing.JComboBox<>(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Passenger Details"); jLabel1.setText("Full Name :"); jLabel2.setText("Age :"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N jLabel3.setText("Booking Reference No. :"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N jLabel4.setText("jLabel4"); jLabel5.setText("Gender :"); jButton1.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N jButton1.setText("Submit"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); pass_gender.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Male", "Female", "Others" })); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(92, 92, 92) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(66, 66, 66) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE)) .addGap(38, 38, 38) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(pass_fname, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(pass_age, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(pass_gender, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(162, 162, 162) .addComponent(jButton1))) .addContainerGap(64, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(47, 47, 47) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jLabel4)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(pass_fname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(pass_age, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(pass_gender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(52, 52, 52) .addComponent(jButton1) .addContainerGap(56, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try { String insert = "INSERT INTO reservation\n" + "values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; PreparedStatement pstmt = conn.prepareStatement(insert); pstmt.setString(1, refno); pstmt.setString(2, username); pstmt.setString(3, pass_fname.getText()); pstmt.setInt(4, Integer.parseInt(pass_age.getText())); pstmt.setString(5, pass_gender.getSelectedItem().toString()); pstmt.setString(6, seatno); pstmt.setString(7, origin); pstmt.setString(8, dest); pstmt.setString(9, flightno); pstmt.setString(10, date); pstmt.setString(11, dep); pstmt.setString(12, arr); pstmt.setString(13, aircraft); pstmt.setString(14, ebclass); pstmt.setInt(15, i_index); pstmt.setInt(16, i_fare); pstmt.execute(); try { if ("B787".equals(aircraft) && "Economy".equals(ebclass)) { System.out.println("B787"); B787E model_m; model_m = new B787E(flightno, date, ebclass, refno, pass_fname.getText()); model_m.setVisible(true); model_m.setLocationRelativeTo(null); }else if ("B787".equals(aircraft) && "Business".equals(ebclass)) { System.out.println("B787"); B787B model_m; model_m = new B787B(flightno, date, ebclass, refno, pass_fname.getText()); model_m.setVisible(true); model_m.setLocationRelativeTo(null); }else if ("B777-ER".equals(aircraft) && "Economy".equals(ebclass)) { System.out.println("B777-ER"); B777_ERE model_m; model_m = new B777_ERE(flightno, date, ebclass, refno, pass_fname.getText()); model_m.setVisible(true); model_m.setLocationRelativeTo(null); }else if ("B777-ER".equals(aircraft) && "Business".equals(ebclass)) { System.out.println("B777-ER"); B777_ERB model_m; model_m = new B777_ERB(flightno, date, ebclass, refno, pass_fname.getText()); model_m.setVisible(true); model_m.setLocationRelativeTo(null); }else if ("A-319".equals(aircraft) && "Business".equals(ebclass)) { System.out.println("A319"); A319B model_m; model_m = new A319B(flightno, date, ebclass, refno, pass_fname.getText()); model_m.setVisible(true); model_m.setLocationRelativeTo(null); }else if ("A-319".equals(aircraft) && "Economy".equals(ebclass)) { System.out.println("A319"); A319E model_m; model_m = new A319E(flightno, date, ebclass, refno, pass_fname.getText()); model_m.setVisible(true); model_m.setLocationRelativeTo(null); } else if ("A-320".equals(aircraft) && "Business".equals(ebclass)) { System.out.println("A320"); B787B model_m; model_m = new B787B(flightno, date, ebclass, refno, pass_fname.getText()); model_m.setVisible(true); model_m.setLocationRelativeTo(null); } else if ("A-320".equals(aircraft) && "Economy".equals(ebclass)) { System.out.println("A320"); A320E model_m; model_m = new A320E(flightno, date, ebclass, refno, pass_fname.getText()); model_m.setVisible(true); model_m.setLocationRelativeTo(null); } } catch (SQLException ex) { Logger.getLogger(passng_details.class.getName()).log(Level.SEVERE, null, ex); } dispose(); } catch (SQLException ex) { Logger.getLogger(passng_details.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(passng_details.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(passng_details.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(passng_details.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(passng_details.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { new passng_details().setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JTextField pass_age; private javax.swing.JTextField pass_fname; private javax.swing.JComboBox<String> pass_gender; // End of variables declaration//GEN-END:variables }
46.223565
206
0.587451
b9191f7f155f07f45bdeb2eee8ca631899284352
633
package io.github.metteo.ws; import javax.xml.bind.annotation.adapters.XmlAdapter; public class Element1To2Adapter extends XmlAdapter<Element_1_0, Element_2_0> { @Override public Element_2_0 unmarshal(Element_1_0 v) throws Exception { if (v == null) { return null; } Element_2_0 result = new Element_2_0(); result.value1 = v.value1; result.value2 = v.value2; return result; } @Override public Element_1_0 marshal(Element_2_0 v) throws Exception { if (v == null) { return null; } Element_1_0 result = new Element_1_0(); result.value1 = v.value1; result.value2 = v.value2; return result; } }
21.1
78
0.71564
01d4ce09a0d5a562ab275ff41ea45f1492280d18
3,531
package net.minecraft.server; import java.util.Random; import org.bukkit.BlockChangeDelegate; // CraftBukkit public class WorldGenTaiga1 extends WorldGenerator { public WorldGenTaiga1() {} public boolean a(World world, Random random, int i, int j, int k) { // CraftBukkit start // sk: The idea is to have (our) WorldServer implement // BlockChangeDelegate and then we can implicitly cast World to // WorldServer (a safe cast, AFAIK) and no code will be broken. This // then allows plugins to catch manually-invoked generation events return this.generate((BlockChangeDelegate) world, random, i, j, k); } public boolean generate(BlockChangeDelegate world, Random random, int i, int j, int k) { // CraftBukkit end int l = random.nextInt(5) + 7; int i1 = l - random.nextInt(2) - 3; int j1 = l - i1; int k1 = 1 + random.nextInt(j1 + 1); boolean flag = true; if (j >= 1 && j + l + 1 <= 128) { int l1; int i2; int j2; int k2; int l2; for (l1 = j; l1 <= j + 1 + l && flag; ++l1) { boolean flag1 = true; if (l1 - j < i1) { l2 = 0; } else { l2 = k1; } for (i2 = i - l2; i2 <= i + l2 && flag; ++i2) { for (j2 = k - l2; j2 <= k + l2 && flag; ++j2) { if (l1 >= 0 && l1 < 128) { k2 = world.getTypeId(i2, l1, j2); if (k2 != 0 && k2 != Block.LEAVES.id) { flag = false; } } else { flag = false; } } } } if (!flag) { return false; } else { l1 = world.getTypeId(i, j - 1, k); if ((l1 == Block.GRASS.id || l1 == Block.DIRT.id) && j < 128 - l - 1) { world.setRawTypeId(i, j - 1, k, Block.DIRT.id); l2 = 0; for (i2 = j + l; i2 >= j + i1; --i2) { for (j2 = i - l2; j2 <= i + l2; ++j2) { k2 = j2 - i; for (int i3 = k - l2; i3 <= k + l2; ++i3) { int j3 = i3 - k; if ((Math.abs(k2) != l2 || Math.abs(j3) != l2 || l2 <= 0) && !Block.o[world.getTypeId(j2, i2, i3)]) { world.setRawTypeIdAndData(j2, i2, i3, Block.LEAVES.id, 1); } } } if (l2 >= 1 && i2 == j + i1 + 1) { --l2; } else if (l2 < k1) { ++l2; } } for (i2 = 0; i2 < l - 1; ++i2) { j2 = world.getTypeId(i, j + i2, k); if (j2 == 0 || j2 == Block.LEAVES.id) { world.setRawTypeIdAndData(i, j + i2, k, Block.LOG.id, 1); } } return true; } else { return false; } } } else { return false; } } }
34.281553
133
0.356839
b3b23faf3434feeeb04b5a6bed77bf66564aef33
5,286
/* * Copyright (c) 2015 Oracle and/or its affiliates. All rights reserved. This * code is released under a tri EPL/GPL/LGPL license. You can use it, * redistribute it and/or modify it under the terms of the: * * Eclipse Public License version 1.0 * GNU General Public License version 2 * GNU Lesser General Public License version 2.1 */ package org.jruby.truffle.nodes.rubinius; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.object.DynamicObject; import com.oracle.truffle.api.source.SourceSection; import com.oracle.truffle.api.utilities.ConditionProfile; import org.jruby.truffle.nodes.objects.IsTaintedNode; import org.jruby.truffle.nodes.objects.IsTaintedNodeGen; import org.jruby.truffle.nodes.objects.TaintNode; import org.jruby.truffle.nodes.objects.TaintNodeGen; import org.jruby.truffle.nodes.objectstorage.ReadHeadObjectFieldNode; import org.jruby.truffle.nodes.objectstorage.WriteHeadObjectFieldNode; import org.jruby.truffle.runtime.RubyContext; import org.jruby.truffle.runtime.layouts.Layouts; import org.jruby.truffle.runtime.object.ObjectIDOperations; /** * Rubinius primitives associated with the Ruby {@code Object} class. */ public abstract class ObjectPrimitiveNodes { @RubiniusPrimitive(name = "object_id") public abstract static class ObjectIDPrimitiveNode extends RubiniusPrimitiveNode { public ObjectIDPrimitiveNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); } public abstract Object executeObjectID(VirtualFrame frame, Object value); @Specialization(guards = "isNil(nil)") public int objectID(Object nil) { return ObjectIDOperations.NIL; } @Specialization(guards = "value") public int objectIDTrue(boolean value) { return ObjectIDOperations.TRUE; } @Specialization(guards = "!value") public int objectIDFalse(boolean value) { return ObjectIDOperations.FALSE; } @Specialization public long objectID(int value) { return ObjectIDOperations.smallFixnumToID(value); } @Specialization(rewriteOn = ArithmeticException.class) public long objectIDSmallFixnumOverflow(long value) throws ArithmeticException { return ObjectIDOperations.smallFixnumToIDOverflow(value); } @Specialization public Object objectID(long value, @Cached("createCountingProfile()") ConditionProfile smallProfile) { if (smallProfile.profile(ObjectIDOperations.isSmallFixnum(value))) { return ObjectIDOperations.smallFixnumToID(value); } else { return ObjectIDOperations.largeFixnumToID(getContext(), value); } } @Specialization public Object objectID(double value) { return ObjectIDOperations.floatToID(getContext(), value); } @Specialization public long objectID(DynamicObject object, @Cached("createReadObjectIDNode()") ReadHeadObjectFieldNode readObjectIdNode, @Cached("createWriteObjectIDNode()") WriteHeadObjectFieldNode writeObjectIdNode) { final Object id = readObjectIdNode.execute(object); if (id == nil()) { final long newId = getContext().getNextObjectID(); writeObjectIdNode.execute(object, newId); return newId; } return (long) id; } protected ReadHeadObjectFieldNode createReadObjectIDNode() { return new ReadHeadObjectFieldNode(Layouts.OBJECT_ID_IDENTIFIER); } protected WriteHeadObjectFieldNode createWriteObjectIDNode() { return new WriteHeadObjectFieldNode(Layouts.OBJECT_ID_IDENTIFIER); } } @RubiniusPrimitive(name = "object_infect", needsSelf = false) public static abstract class ObjectInfectPrimitiveNode extends RubiniusPrimitiveNode { @Child private IsTaintedNode isTaintedNode; @Child private TaintNode taintNode; public ObjectInfectPrimitiveNode(RubyContext context, SourceSection sourceSection) { super(context, sourceSection); } @Specialization public Object objectInfect(Object host, Object source) { if (isTaintedNode == null) { CompilerDirectives.transferToInterpreter(); isTaintedNode = insert(IsTaintedNodeGen.create(getContext(), getSourceSection(), null)); } if (isTaintedNode.executeIsTainted(source)) { // This lazy node allocation effectively gives us a branch profile if (taintNode == null) { CompilerDirectives.transferToInterpreter(); taintNode = insert(TaintNodeGen.create(getContext(), getSourceSection(), null)); } taintNode.executeTaint(host); } return host; } } }
37.225352
104
0.667991
103635bfc546383f4679c6f0dfc97bf31ab237f0
390
package FundamentalsJava.DataTypesAndVariablesLab; import java.util.Scanner; public class ConvertMetersToKilometers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int meters = Integer.parseInt(scanner.nextLine()); double kilometers = meters * 1.0 / 1000; System.out.printf("%.2f", kilometers); } }
22.941176
55
0.666667
1e19d05216d01dfd92492f517e8e63daf3a14f62
11,234
package org.visallo.web; import com.google.common.base.Joiner; import org.visallo.core.config.Configuration; import org.visallo.core.model.thumbnails.ThumbnailRepository; import org.visallo.core.model.properties.VisalloProperties; import org.visallo.core.model.properties.types.MetadataVisalloProperty; import org.visallo.core.model.properties.types.VisalloPropertyBase; import java.util.HashMap; import java.util.Map; public class WebConfiguration { public static final String PREFIX = Configuration.WEB_CONFIGURATION_PREFIX; public static final String THROTTLE_MESSAGING_SECONDS = PREFIX + "throttle.messaging.seconds"; public static final String CACHE_VERTEX_LRU_EXPIRATION_SECONDS = PREFIX + "cache.vertex.lru.expiration.seconds"; public static final String CACHE_VERTEX_MAX_SIZE = PREFIX + "cache.vertex.max_size"; public static final String CACHE_EDGE_LRU_EXPIRATION_SECONDS = PREFIX + "cache.edge.lru.expiration.seconds"; public static final String CACHE_EDGE_MAX_SIZE = PREFIX + "cache.edge.max_size"; public static final String VERTEX_LOAD_RELATED_MAX_BEFORE_PROMPT = PREFIX + "vertex.loadRelatedMaxBeforePrompt"; public static final String VERTEX_LOAD_RELATED_MAX_FORCE_SEARCH = PREFIX + "vertex.loadRelatedMaxForceSearch"; public static final String VERTEX_RELATIONSHIPS_MAX_PER_SECTION = PREFIX + "vertex.relationships.maxPerSection"; public static final String DETAIL_HISTORY_STACK_MAX = PREFIX + "detail.history.stack.max"; public static final String MAX_SELECTION_PARAGRAPHS_FOR_TERM_POPOVER = PREFIX + "detail.text.popover.maxSelectionParagraphs"; public static final String MAX_TEXT_LENGTH = PREFIX + "detail.text.maxTextLength"; public static final String FIELD_JUSTIFICATION_VALIDATION = PREFIX + "field.justification.validation"; public static final String SEARCH_DISABLE_WILDCARD_SEARCH = PREFIX + "search.disableWildcardSearch"; public static final String SEARCH_EXACT_MATCH = PREFIX + "search.exactMatch"; public static final String NOTIFICATIONS_LOCAL_AUTO_DISMISS_SECONDS = PREFIX + "notifications.local.autoDismissSeconds"; public static final String NOTIFICATIONS_SYSTEM_AUTO_DISMISS_SECONDS = PREFIX + "notifications.system.autoDismissSeconds"; public static final String NOTIFICATIONS_USER_AUTO_DISMISS_SECONDS = PREFIX + "notifications.user.autoDismissSeconds"; public static final String TYPEAHEAD_PROPERTIES_MAX_ITEMS = PREFIX + "typeahead.properties.maxItems"; public static final String TYPEAHEAD_CONCEPTS_MAX_ITEMS = PREFIX + "typeahead.concepts.maxItems"; public static final String TYPEAHEAD_EDGE_LABELS_MAX_ITEMS = PREFIX + "typeahead.edgeLabels.maxItems"; public static final String PROPERTIES_MULTIVALUE_DEFAULT_VISIBLE_COUNT = PREFIX + "properties.multivalue.defaultVisibleCount"; public static final String PROPERTIES_METADATA_PROPERTY_NAMES = PREFIX + "properties.metadata.propertyNames"; public static final String PROPERTIES_METADATA_PROPERTY_NAMES_DISPLAY = PREFIX + "properties.metadata.propertyNamesDisplay"; public static final String PROPERTIES_METADATA_PROPERTY_NAMES_TYPE = PREFIX + "properties.metadata.propertyNamesType"; public static final String MAP_PROVIDER = PREFIX + "map.provider"; public static final String MAP_PROVIDER_OSM_URL = PREFIX + "map.provider.osm.url"; public static final String LOGIN_SHOW_POWERED_BY = PREFIX + "login.showPoweredBy"; public static final String FORMATS_DATE_DATEDISPLAY = PREFIX + "formats.date.dateDisplay"; public static final String FORMATS_DATE_TIMEDISPLAY = PREFIX + "formats.date.timeDisplay"; public static final String FORMATS_DATE_SHOW_TIMEZONE = PREFIX + "formats.date.showTimezone"; public static final String SHOW_VERSION_COMMENTS = PREFIX + "showVersionComments"; public static final String SHOW_VISIBILITY_IN_DETAILS_PANE = PREFIX + "showVisibilityInDetailsPane"; public static final String TIMEZONE_DEFAULT_DETECT = PREFIX + "timezone.defaults.detect"; public static final String TIMEZONE_DEFAULT_TIMEZONE = PREFIX + "timezone.defaults.timezone"; public static final String DATE_DISPLAY = PREFIX + "date.default.display"; public static final PropertyMetadata PROPERTY_METADATA_SOURCE_TIMEZONE = new PropertyMetadata( "http://visallo.org#sourceTimezone", "properties.metadata.label.source_timezone", "timezone" ); public static final PropertyMetadata PROPERTY_METADATA_MODIFIED_DATE = new PropertyMetadata( VisalloProperties.MODIFIED_DATE, "properties.metadata.label.modified_date", "datetime" ); public static final PropertyMetadata PROPERTY_METADATA_MODIFIED_BY = new PropertyMetadata( VisalloProperties.MODIFIED_BY, "properties.metadata.label.modified_by", "user" ); public static final PropertyMetadata PROPERTY_METADATA_STATUS = new PropertyMetadata( "sandboxStatus", "properties.metadata.label.status", "sandboxStatus" ); public static final PropertyMetadata PROPERTY_METADATA_CONFIDENCE = new PropertyMetadata( VisalloProperties.CONFIDENCE_METADATA, "properties.metadata.label.confidence", "percent" ); public static final Map<String, String> DEFAULTS = new HashMap<>(); static { // To display exact date or relative date DEFAULTS.put(DATE_DISPLAY, "relative"); DEFAULTS.put(LOGIN_SHOW_POWERED_BY, "false"); DEFAULTS.put(SHOW_VERSION_COMMENTS, "true"); DEFAULTS.put(FORMATS_DATE_DATEDISPLAY, "YYYY-MM-DD"); DEFAULTS.put(FORMATS_DATE_TIMEDISPLAY, "HH:mm"); DEFAULTS.put(FORMATS_DATE_SHOW_TIMEZONE, "true"); DEFAULTS.put(SHOW_VISIBILITY_IN_DETAILS_PANE, "true"); DEFAULTS.put(THROTTLE_MESSAGING_SECONDS, "2"); // Local cache rules for vertices / edges (per workspace) DEFAULTS.put(CACHE_VERTEX_LRU_EXPIRATION_SECONDS, Integer.toString(10 * 60)); DEFAULTS.put(CACHE_VERTEX_MAX_SIZE, "500"); DEFAULTS.put(CACHE_EDGE_LRU_EXPIRATION_SECONDS, Integer.toString(10 * 60)); DEFAULTS.put(CACHE_EDGE_MAX_SIZE, "250"); // Load related vertices thresholds DEFAULTS.put(VERTEX_LOAD_RELATED_MAX_BEFORE_PROMPT, "50"); DEFAULTS.put(VERTEX_LOAD_RELATED_MAX_FORCE_SEARCH, "250"); DEFAULTS.put(VERTEX_RELATIONSHIPS_MAX_PER_SECTION, "5"); DEFAULTS.put(DETAIL_HISTORY_STACK_MAX, "5"); DEFAULTS.put(MAX_SELECTION_PARAGRAPHS_FOR_TERM_POPOVER, "5"); DEFAULTS.put(MAX_TEXT_LENGTH, "1500000"); DEFAULTS.put(Configuration.VIDEO_PREVIEW_FRAMES_COUNT, Integer.toString(ThumbnailRepository.DEFAULT_FRAMES_PER_PREVIEW)); // Justification field validation DEFAULTS.put(FIELD_JUSTIFICATION_VALIDATION, JustificationFieldValidation.OPTIONAL.toString()); // Search DEFAULTS.put(SEARCH_DISABLE_WILDCARD_SEARCH, "false"); DEFAULTS.put(SEARCH_EXACT_MATCH, "false"); // Notifications DEFAULTS.put(NOTIFICATIONS_LOCAL_AUTO_DISMISS_SECONDS, "2"); DEFAULTS.put(NOTIFICATIONS_SYSTEM_AUTO_DISMISS_SECONDS, "-1"); DEFAULTS.put(NOTIFICATIONS_USER_AUTO_DISMISS_SECONDS, "5"); DEFAULTS.put(TYPEAHEAD_CONCEPTS_MAX_ITEMS, "-1"); DEFAULTS.put(TYPEAHEAD_PROPERTIES_MAX_ITEMS, "-1"); DEFAULTS.put(TYPEAHEAD_EDGE_LABELS_MAX_ITEMS, "-1"); // Hide multivalue properties after this count DEFAULTS.put(PROPERTIES_MULTIVALUE_DEFAULT_VISIBLE_COUNT, "2"); // Property Metadata shown in info popover DEFAULTS.put(PROPERTIES_METADATA_PROPERTY_NAMES, Joiner.on(',').join( PROPERTY_METADATA_SOURCE_TIMEZONE.getName(), PROPERTY_METADATA_MODIFIED_DATE.getName(), PROPERTY_METADATA_MODIFIED_BY.getName(), PROPERTY_METADATA_STATUS.getName(), PROPERTY_METADATA_CONFIDENCE.getName() )); DEFAULTS.put(PROPERTIES_METADATA_PROPERTY_NAMES_DISPLAY, Joiner.on(',').join( PROPERTY_METADATA_SOURCE_TIMEZONE.getMessageKey(), PROPERTY_METADATA_MODIFIED_DATE.getMessageKey(), PROPERTY_METADATA_MODIFIED_BY.getMessageKey(), PROPERTY_METADATA_STATUS.getMessageKey(), PROPERTY_METADATA_CONFIDENCE.getMessageKey() )); DEFAULTS.put(PROPERTIES_METADATA_PROPERTY_NAMES_TYPE, Joiner.on(',').join( PROPERTY_METADATA_SOURCE_TIMEZONE.getDataType(), PROPERTY_METADATA_MODIFIED_DATE.getDataType(), PROPERTY_METADATA_MODIFIED_BY.getDataType(), PROPERTY_METADATA_STATUS.getDataType(), PROPERTY_METADATA_CONFIDENCE.getDataType() )); DEFAULTS.put(MAP_PROVIDER, MapProvider.OSM.toString()); DEFAULTS.put(MAP_PROVIDER_OSM_URL, "https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png"); } public static class PropertyMetadata { private String name; private String messageKey; private String dataType; public PropertyMetadata(VisalloPropertyBase visalloProperty, String messageKey, String dataType) { this(visalloProperty.getPropertyName(), messageKey, dataType); } public PropertyMetadata(MetadataVisalloProperty visalloProperty, String messageKey, String dataType) { this(visalloProperty.getMetadataKey(), messageKey, dataType); } public PropertyMetadata(String name, String messageKey, String dataType) { this.name = name; this.messageKey = messageKey; this.dataType = dataType; } public String getName() { return name; } public String getMessageKey() { return messageKey; } public String getDataType() { return dataType; } } public enum MapProvider { /** * @deprecated Google is not officially supported by OpenLayers, OpenStreetMap will be used. */ @Deprecated GOOGLE("google"), OSM("osm"), ARCGIS93REST("ArcGIS93Rest"); private String string; private MapProvider(String string) { this.string = string; } @Override public String toString() { return string; } } public enum JustificationFieldValidation { REQUIRED, OPTIONAL, NONE; } public static JustificationFieldValidation getJustificationFieldValidation(Configuration configuration) { return JustificationFieldValidation.valueOf(configuration.get(FIELD_JUSTIFICATION_VALIDATION, DEFAULTS.get(FIELD_JUSTIFICATION_VALIDATION))); } public static boolean justificationRequired(Configuration configuration) { return getJustificationFieldValidation(configuration).equals(JustificationFieldValidation.REQUIRED); } }
49.928889
150
0.710789
4bfbd1e660cf13cbe7920c950d191f147779b03f
1,095
package org.sag.gjfr; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class AbstractPattern { private final String patternText; private final Pattern pattern; public AbstractPattern(String patternText) { if (patternText == null) throw new IllegalArgumentException("Pattern text may not be null."); this.patternText = patternText; this.pattern = PatternUtils.newPattern(patternText); } public String getPatternText() { return patternText; } public Pattern getPattern() { return pattern; } protected Matcher getMatcher(String value) { if (!PatternUtils.isPossibleQualifiedName(value, "/")) return null; Matcher matcher = pattern.matcher(value); if (matcher.matches()) return matcher; return null; } public boolean matches(String value) { return getMatcher(value) != null; } @Override public String toString() { return getClass().getSimpleName() + "{" + pattern + ")"; } }
24.886364
80
0.635616
bbab0b69a349a4dd8fd94447eaf1c28e5e1b8a0f
2,029
package com.seu.magicfilter.filter.advance.common; import android.content.Context; import android.opengl.GLES20; import com.show.tt.R; import com.seu.magicfilter.filter.base.gpuimage.GPUImageFilter; import com.seu.magicfilter.filter.helper.MagicFilterParam; import com.seu.magicfilter.utils.OpenGLUtils; public class MagicBeautyFilter extends GPUImageFilter { private int mSingleStepOffsetLocation; private int mParamsLocation; public MagicBeautyFilter(Context context) { super(NO_FILTER_VERTEX_SHADER, ( MagicFilterParam.mGPUPower == 1 ? OpenGLUtils.readShaderFromRawResource(context, R.raw.beautify_fragment) : OpenGLUtils.readShaderFromRawResource(context, R.raw.beautify_fragment_low))); } protected void onInit() { super.onInit(); mSingleStepOffsetLocation = GLES20.glGetUniformLocation(getProgram(), "singleStepOffset"); mParamsLocation = GLES20.glGetUniformLocation(getProgram(), "params"); setBeautyLevel(5); } protected void onDestroy() { super.onDestroy(); } private void setTexelSize(final float w, final float h) { setFloatVec2(mSingleStepOffsetLocation, new float[] {2.0f / w, 2.0f / h}); } @Override public void onOutputSizeChanged(final int width, final int height) { super.onOutputSizeChanged(width, height); setTexelSize(width, height); } public void setBeautyLevel(int level){ switch (level) { case 1: setFloatVec4(mParamsLocation, new float[] {1.0f, 1.0f, 0.15f, 0.15f}); break; case 2: setFloatVec4(mParamsLocation, new float[] {0.8f, 0.9f, 0.2f, 0.2f}); break; case 3: setFloatVec4(mParamsLocation, new float[] {0.6f, 0.8f, 0.25f, 0.25f}); break; case 4: setFloatVec4(mParamsLocation, new float[] {0.4f, 0.7f, 0.38f, 0.3f}); break; case 5: setFloatVec4(mParamsLocation, new float[] {0.33f, 0.63f, 0.4f, 0.35f}); break; default: break; } } }
31.215385
99
0.675702
b3e5c5c9af8f11eca2dbff7eaf487503886f1fea
1,950
/* * #%L * joynr::java::messaging::bounceproxy::controlled-bounceproxy * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package io.joynr.messaging.bounceproxy; import com.google.inject.Inject; import com.google.inject.name.Named; /** * Convenience class to build URLs for a controlled bounce proxy. * * @author christina.strobel * */ public class ControlledBounceProxyUrl { private static final String URL_PATH_SEPARATOR = "/"; private String baseUrlForBpc; private String baseUrlForCc; @Inject public ControlledBounceProxyUrl(@Named(BounceProxyPropertyKeys.PROPERTY_BOUNCEPROXY_URL_FOR_CC) String baseUrlForCc, @Named(BounceProxyPropertyKeys.PROPERTY_BOUNCEPROXY_URL_FOR_BPC) String baseUrlForBpc) { if (!baseUrlForCc.endsWith(URL_PATH_SEPARATOR)) { this.baseUrlForCc = baseUrlForCc + URL_PATH_SEPARATOR; } else { this.baseUrlForCc = baseUrlForCc; } if (!baseUrlForBpc.endsWith(URL_PATH_SEPARATOR)) { this.baseUrlForBpc = baseUrlForBpc + URL_PATH_SEPARATOR; } else { this.baseUrlForBpc = baseUrlForBpc; } } public String getOwnUrlForClusterControllers() { return this.baseUrlForCc; } public String getOwnUrlForBounceProxyController() { return this.baseUrlForBpc; } }
30.46875
124
0.695385
b203eea431cd58a6f6217511454dfc4657eb04bd
145
package com.example.sqliteapp; public interface TodoDataSource { void getTodoNote(GetTodoNote callback); void setData(TodoNote note); }
20.714286
43
0.772414
88eedbf6f085fee61155adcfe815785029e6d2dd
958
package com.baeldung.spring.kafka.dto.document.full; import com.baeldung.spring.kafka.dto.document.dal.ResolutionExecutionTask; import com.baeldung.spring.kafka.dto.document.dal.ResolutionExecutionTaskCreateRequest; import com.baeldung.spring.kafka.dto.document.full.ProlongationRequestAcceptTaskFull; import com.baeldung.spring.kafka.dto.document.full.ReassignmentRequestAcceptTaskFull; import com.baeldung.spring.kafka.dto.document.full.ResolutionExecutionReportAcceptTaskFull; import java.util.List; import lombok.Data; @Data public class ResolutionExecutionTaskFull extends ResolutionExecutionTask { private List<ResolutionExecutionTaskCreateRequest> resolutionExecutionTaskCreateRequests; private List<ResolutionExecutionReportAcceptTaskFull> resolutionExecutionReportAcceptTasks; private List<ProlongationRequestAcceptTaskFull> prolongationRequestAcceptTasks; private List<ReassignmentRequestAcceptTaskFull> reassignmentRequestAcceptTasks; }
53.222222
93
0.882046
897476bc73b851c2506d8b730570230a4742a59d
1,213
package com.vaguehope.onosendai.notifications; import java.util.List; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.vaguehope.onosendai.config.Column; import com.vaguehope.onosendai.model.Tweet; import com.vaguehope.onosendai.util.LogWrapper; public class MarkAsReadReceiver extends BroadcastReceiver { protected static final String EXTRA_COL_ID = "col_id"; protected static final String EXTRA_UP_TO_TIME = "up_to_time"; protected static final LogWrapper LOG = new LogWrapper("MAR"); public static PendingIntent makePi (final Context context, final Column col, final List<Tweet> tweets) { if (tweets == null || tweets.size() < 1) return null; return PendingIntent.getBroadcast(context, col.getId(), new Intent(context, MarkAsReadReceiver.class) .putExtra(EXTRA_COL_ID, col.getId()) .putExtra(EXTRA_UP_TO_TIME, tweets.iterator().next().getTime()), PendingIntent.FLAG_UPDATE_CURRENT); } @Override public void onReceive (final Context context, final Intent intent) { context.startService(new Intent(context, MarkAsReadService.class).putExtras(intent.getExtras())); } }
33.694444
105
0.781533
d39bc7918fcb67e9587c6b7bd508f8fb9ce22f69
2,641
package com.digero.abcplayer.view; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.font.GlyphVector; import java.util.List; import java.util.NavigableMap; import java.util.NavigableSet; import javax.swing.JPanel; import com.digero.common.abctomidi.AbcRegion; public class HighlightAbcNotesPanel extends JPanel { private static final Font FONT = new Font(Font.MONOSPACED, Font.PLAIN, 13); private List<String> lines = null; private NavigableSet<AbcRegion> regions = null; private NavigableMap<Integer, AbcRegion> indexToRegion = null; private Dimension size = null; public HighlightAbcNotesPanel() { } private void setLinesTmp(List<String> lines) { this.lines = lines; size = null; invalidate(); repaint(); } @Override public Dimension getPreferredSize() { if (size == null) { if (lines == null) return size = new Dimension(0, 0); FontMetrics metrics = getGraphics().getFontMetrics(FONT); int width = 0; for (String line : lines) width = Math.max(width, metrics.stringWidth(line)); int height = metrics.getHeight() * lines.size(); size = new Dimension(width, height); } return size; } public void setLinesAndRegions(List<String> lines, NavigableSet<AbcRegion> regions, boolean retainScrollPosition) { repaint(); StringBuilder text = new StringBuilder(); for (int i = 0; i < lines.size(); i++) { text.append(lines.get(i)).append("\r\n"); } if (!retainScrollPosition) scrollRectToVisible(new Rectangle()); this.regions = regions; this.indexToRegion = null; update(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (lines == null) return; Graphics2D g2 = (Graphics2D) g; g2.setFont(FONT); g2.setColor(getForeground()); FontMetrics metrics = g2.getFontMetrics(); Rectangle clipRect = g2.getClipBounds(); int lineHeight = metrics.getHeight(); int leadingAndAscent = metrics.getLeading() + metrics.getAscent(); int iMin = clipRect.y / lineHeight; int iMax = Math.min(lines.size() - 1, (clipRect.y + clipRect.height) / lineHeight); for (int i = iMin; i <= iMax; i++) { GlyphVector glyphs = FONT.createGlyphVector(g2.getFontRenderContext(), lines.get(i)); g2.drawString(lines.get(i), 0, i * lineHeight + leadingAndAscent); } System.out.println("Draw " + (iMax - iMin + 1) + " lines"); } private void update() { // TODO } }
24.009091
115
0.672473
8d0769f0c551ed729a682b72d00ca24ff80e514c
2,184
package com.hui.SlidingWindow; /** * @author: shenhaizhilong * @date: 2018/11/13 10:04 * * * * 424. Longest Repeating Character Replacement * DescriptionHintsSubmissionsDiscussSolution * Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations. * * Note: * Both the string's length and k will not exceed 104. * * Example 1: * * Input: * s = "ABAB", k = 2 * * Output: * 4 * * Explanation: * Replace the two 'A's with two 'B's or vice versa. * Example 2: * * Input: * s = "AABABBA", k = 1 * * Output: * 4 * * Explanation: * Replace the one 'A' in the middle with 'B' and form "AABBBBA". * The substring "BBBB" has the longest repeating letters, which is 4. * * */ public class LongestRepeatingCharacterReplacement { public int characterReplacement(String s, int k) { int start = 0; int maxCharCount = 0; int maxSize = 0; int N = s.length(); int[] counter = new int[26]; for (int end = 0; end < N; end++) { int idx = s.charAt(end) - 'A'; counter[idx]++; if(counter[idx] > maxCharCount) { maxCharCount = counter[idx]; } // end - start +1 - maxCharCount <=k ,changing size <=k, expand the sliding window // end - start +1 <= maxCharCount +k, we want len = end - start +1 is the max, k is const, so just compute the max Char Count is ok. //end - start +1 - maxCharCount > k ,changing size > k, shrink the sliding window, while (end - start +1 - maxCharCount > k) { counter[s.charAt(start) -'A']--; start++; } if(end - start +1 > maxSize) { maxSize = end - start +1; } } return maxSize; } public static void main(String[] args) { } }
25.103448
268
0.544414
a7b7405ae827542e0ae44a3629739060fdb5fdb8
687
package com.d365lab.eatery.restaurantcustomerorchestrator.services; import com.d365lab.eatery.restaurantcustomerorchestrator.dao.RestaurantLogin; import org.javatuples.Pair; import java.util.List; public interface RestaurantOnboardingService { String generateLogin(String userName, String userGivenPassword, String restaurant_master_tenant_id, String restaurant_outlet_tenant_id, String restaurant_brand_name, String restaurant_outlet_name); List<RestaurantLogin> verifyPassword(String userName, String password); List<RestaurantLogin> logoutRestaurant(String userName); Pair<String, String> generateTenant(String restaurantBrandName, String restaurantOutletName); }
45.8
201
0.847162
7a0f6500479c10cd281a8bce4831648def008003
1,692
/* * Copyright 2007 Yusuke Yamamoto * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package twitter4j; import java.util.Date; /** * @author Yusuke Yamamoto - yusuke at mac.com * @since Twitter4J 2.2.6 */ public interface Twt { /** * returns the created_at * * @return the created_at */ Date getCreatedAt(); /** * returns the status id of the tweet * * @return the status id */ long getId(); /** * returns the text * * @return the text */ String getText(); /** * returns the source of the tweet * * @return the source of the tweet */ String getSource(); /** * Returns the in_reply_tostatus_id * * @return the in_reply_tostatus_id */ long getInReplyToStatusId(); /** * Returns the place associated with the Tweet. * * @return The place associated with the Tweet */ Place getPlace(); /** * Returns The location that this tweet refers to if available. * * @return returns The location that this tweet refers to if available (can be null) */ GeoLocation getGeoLocation(); }
22.864865
88
0.632388
715ac8bdab6670ce1cfe87f002a47be4a94e2851
4,052
package de.hbz.introx.mf.benchmarks.stream.converter; import de.hbz.introx.mf.stream.converter.JsonToElasticsearchBulkIdKeyOriginal; import de.hbz.introx.mf.stream.converter.JsonToElasticsearchBulkIdKeyPointer; import de.hbz.introx.mf.stream.converter.JsonToElasticsearchBulkIdPathFind; import de.hbz.introx.mf.stream.converter.JsonToElasticsearchBulkIdPathGet; import org.culturegraph.mf.stream.converter.JsonEncoder; import org.culturegraph.mf.stream.converter.xml.MarcXmlHandler; import org.culturegraph.mf.stream.converter.xml.XmlDecoder; import org.culturegraph.mf.stream.sink.ObjectWriter; import org.culturegraph.mf.stream.source.FileOpener; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.*; @Fork(2) @Warmup(iterations = 8) @Measurement(iterations = 8) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.SECONDS) @State(Scope.Benchmark) public class JsonToElasticsearchBulkIdBenchmark { @Param({ "baseline", "idKeyOriginal:001", "idKeyPointer:/001", "idKeyPointer:/040 /a", "idPathGet:001", "idPathGet:040 .a", "idPathFind:001", "idPathFind:040 .a" }) private String param; @Benchmark public void benchmark() { final FileOpener opener = new FileOpener(); final JsonEncoder encoder = new JsonEncoder(); opener .setReceiver(new XmlDecoder()) .setReceiver(new MarcXmlHandler()) .setReceiver(encoder); configure(encoder); opener.process(fileName("xml")); opener.closeStream(); } private void configure(final JsonEncoder encoder) { final String[] params = param.split(":", 2); switch (params[0]) { case "baseline": encoder .setReceiver(writer()); break; case "idKeyOriginal": encoder .setReceiver(new JsonToElasticsearchBulkIdKeyOriginal( bulkParam(params), "type", "name")) .setReceiver(writer()); break; case "idKeyPointer": encoder .setReceiver(new JsonToElasticsearchBulkIdKeyPointer( bulkParam(params), "type", "name", true)) .setReceiver(writer()); break; case "idPathGet": encoder .setReceiver(new JsonToElasticsearchBulkIdPathGet( bulkParam(params), "type", "name", ".")) .setReceiver(writer()); break; case "idPathFind": encoder .setReceiver(new JsonToElasticsearchBulkIdPathFind( bulkParam(params), "type", "name", ".")) .setReceiver(writer()); break; default: throw new IllegalArgumentException("Unsupported param: " + param); } } private String bulkParam(final String[] params) { if (params.length > 1) { return params[1]; } else { throw new IllegalArgumentException("Invalid param: " + param); } } private ObjectWriter<String> writer() { return new ObjectWriter<>(fileName("jsonl", true)); } private String fileName(final String extension, final boolean includeParam) { String fileName = getClass().getSimpleName().split("_")[0]; if (includeParam) { try { fileName = fileName + "-" + URLEncoder.encode( param, Charset.defaultCharset().name()); } catch (java.io.UnsupportedEncodingException e) { e.printStackTrace(); } } return fileName + "." + extension; } private String fileName(final String extension) { return fileName(extension, false); } }
33.213115
82
0.585637
42fd48fd0c2d62b8797852dd0df997b6a9293259
3,004
package com.webank.wecross.stub.fabric; import com.webank.wecross.common.FabricType; import com.webank.wecross.stub.ResourceInfo; import com.webank.wecross.utils.HashUtils; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import org.hyperledger.fabric.sdk.Peer; public class ChaincodeResource { private String name; private String chainCodeName; private String version; private long proposalWaitTime; private Collection<Peer> endorsers; private String channelName; public ChaincodeResource( String name, String chainCodeName, String version, String channelName) { this.name = name; this.chainCodeName = chainCodeName; this.version = version; this.proposalWaitTime = FabricStubConfigParser.DEFAULT_PROPOSAL_WAIT_TIME; this.endorsers = new LinkedHashSet<>(); this.channelName = channelName; } public ResourceInfo getResourceInfo() { ResourceInfo resourceInfo = new ResourceInfo(); resourceInfo.setName(name); resourceInfo.setStubType(FabricType.STUB_NAME); resourceInfo.setProperties( ResourceInfoProperty.build() .channelName(channelName) .chainCodeName(chainCodeName) .version(version) .proposalWaitTime(proposalWaitTime) .orgNames(getOrgNames()) .toMap()); resourceInfo.setChecksum(HashUtils.sha256String(chainCodeName)); return resourceInfo; } public Collection<Peer> getEndorsers() { return endorsers; } public void addEndorser(Peer endorser) { endorsers.add(endorser); } public String getName() { return name; } public String getChainCodeName() { return chainCodeName; } public String getVersion() { return version; } public long getProposalWaitTime() { return proposalWaitTime; } public String[] getOrgNames() { Set<String> orgNameSet = new HashSet<>(); for (Peer peer : endorsers) { orgNameSet.add((String) peer.getProperties().getProperty(FabricType.ORG_NAME_DEF)); } String[] orgNames = new String[] {}; orgNames = orgNameSet.toArray(orgNames); return orgNames; } @Override public String toString() { return "ChaincodeResource{" + "name='" + name + '\'' + ", chainCodeName='" + chainCodeName + '\'' + ", version='" + version + '\'' + ", proposalWaitTime=" + proposalWaitTime + ", endorsers=" + endorsers + ", channelName='" + channelName + '\'' + '}'; } }
28.339623
95
0.575233
bb63bef85a8466f96aa2bf1982fe8f585281a175
199
package org.apache.spark.util.hooks; /** * @Description : * @Author : 问天(章艺钟) * @Date : 4:19 PM 2020/4/1 * @Modified : */ public interface PreJobExecuteHook { void execute(String queue); }
16.583333
36
0.648241
078a9f52a115bf1454bf3063814178356bd58ec5
161
package com.senior_project.recipe_finder.data; import lombok.Data; import java.util.List; @Data public class SearchResults { private List<Hit> hits; }
11.5
46
0.751553
fce80f4d8f8008910265c30d98fe8df74899f402
5,064
package zemberek.examples.classification; import com.google.common.base.Splitter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.antlr.v4.runtime.Token; import zemberek.core.turkish.Turkish; import zemberek.morphology.TurkishMorphology; import zemberek.morphology.analysis.SentenceAnalysis; import zemberek.morphology.analysis.SentenceWordAnalysis; import zemberek.morphology.analysis.SingleAnalysis; import zemberek.normalization.TurkishSentenceNormalizer; import zemberek.tokenization.TurkishTokenizer; import zemberek.tokenization.antlr.TurkishLexer; public class ClassificationExampleBase { protected static TurkishMorphology morphology; protected static TurkishSentenceNormalizer normalizer; protected void generateSetWithLemmas(List<String> lines, Path lemmasPath) throws IOException { List<String> lemmas = lines .stream() .map(this::replaceWordsWithLemma) .map(this::removeNonWords) .map(s -> s.toLowerCase(Turkish.LOCALE)) .collect(Collectors.toList()); Files.write(lemmasPath, lemmas); } protected void generateSetWithSplit(List<String> lines, Path splitPath) throws IOException { List<String> lemmas = lines .stream() .map(this::splitWords) .map(this::removeNonWords) .map(s -> s.toLowerCase(Turkish.LOCALE)) .collect(Collectors.toList()); Files.write(splitPath, lemmas); } protected void generateSetTokenized(List<String> lines, Path tokenizedPath) throws IOException { List<String> tokenized = lines .stream() .map(s -> String.join(" ", TurkishTokenizer.DEFAULT.tokenizeToStrings(s))) .map(this::removeNonWords) .map(s -> s.toLowerCase(Turkish.LOCALE)) .collect(Collectors.toList()); Files.write(tokenizedPath, tokenized); } protected String splitWords(String sentence) { List<String> tokens = Splitter.on(" ").splitToList(sentence); // assume first is label. Remove label from sentence for morphological analysis. String label = tokens.get(0); tokens = tokens.subList(1, tokens.size()); sentence = String.join(" ", tokens); if (sentence.length() == 0) { return sentence; } SentenceAnalysis analysis = morphology.analyzeAndDisambiguate(sentence); List<String> res = new ArrayList<>(); // add label first. res.add(label); for (SentenceWordAnalysis e : analysis) { SingleAnalysis best = e.getBestAnalysis(); String input = e.getWordAnalysis().getInput(); if (best.isUnknown()) { res.add(input); continue; } List<String> lemmas = best.getLemmas(); String l = lemmas.get(0); if (l.length() < input.length()) { res.add(l); String substring = input.substring(l.length()); res.add("_" + substring); } else { res.add(l); } } return String.join(" ", res); } String processEnding(String input) { return input.replaceAll("[ae]", "A"). replaceAll("[ıiuü]", "I") .replaceAll("[kğ]", "K") .replaceAll("[cç]", "C") .replaceAll("[dt]", "D"); } protected String replaceWordsWithLemma(String sentence) { List<String> tokens = Splitter.on(" ").splitToList(sentence); // assume first is label. Remove label from sentence for morphological analysis. String label = tokens.get(0); tokens = tokens.subList(1, tokens.size()); sentence = String.join(" ", tokens); if (sentence.length() == 0) { return sentence; } SentenceAnalysis analysis = morphology.analyzeAndDisambiguate(sentence); List<String> res = new ArrayList<>(); // add label first. res.add(label); for (SentenceWordAnalysis e : analysis) { SingleAnalysis best = e.getBestAnalysis(); if (best.isUnknown()) { res.add(e.getWordAnalysis().getInput()); continue; } List<String> lemmas = best.getLemmas(); res.add(lemmas.get(0)); } return String.join(" ", res); } protected String removeNonWords(String sentence) { List<Token> docTokens = TurkishTokenizer.DEFAULT.tokenize(sentence); List<String> reduced = new ArrayList<>(docTokens.size()); for (Token token : docTokens) { String text = token.getText(); // skip label and ending words. if (text.startsWith("_") || text.contains("__")) { reduced.add(text); continue; } int type = token.getType(); if ( type == TurkishLexer.Mention || type == TurkishLexer.HashTag || type == TurkishLexer.URL || type == TurkishLexer.Punctuation || type == TurkishLexer.RomanNumeral || type == TurkishLexer.Time || type == TurkishLexer.UnknownWord || type == TurkishLexer.Unknown) { continue; } reduced.add(text); } return String.join(" ", reduced); } }
32.670968
98
0.649882
67919c64ffa720cc1efa7ea561ba02424404e5d5
4,486
package com.vijaya.firebase; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.AutoCompleteTextView; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; /** * A login screen that offers login via email/password. */ public class LoginActivity extends AppCompatActivity { /** * Id to identity READ_CONTACTS permission request. */ private static final int REQUEST_READ_CONTACTS = 0; /** * A dummy authentication store containing known user names and passwords. * TODO: remove after connecting to a real authentication system. */ private static final String[] DUMMY_CREDENTIALS = new String[]{ "foo@example.com:hello", "bar@example.com:world" }; private FirebaseAuth auth; // UI references. private AutoCompleteTextView mEmailView; private EditText mPasswordView; private View mProgressView; private View mLoginFormView; @Override protected void onCreate(Bundle savedInstanceState) { //Get Firebase auth instance auth = FirebaseAuth.getInstance(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Set up the login form. mEmailView = (AutoCompleteTextView) findViewById(R.id.email); mPasswordView = (EditText) findViewById(R.id.password); } /** * Attempts to sign in or register the account specified by the login form. * If there are form errors (invalid email, missing fields, etc.), the * errors are presented and no actual login attempt is made. */ public void attemptLogin(View v) { // Reset errors. mEmailView.setError(null); mPasswordView.setError(null); // Store values at the time of the login attempt. String email = mEmailView.getText().toString(); String password = mPasswordView.getText().toString(); // Check for a valid password, if the user entered one. if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) { mPasswordView.setError(getString(R.string.error_invalid_password)); } // Check for a valid email address. if (TextUtils.isEmpty(email)) { mEmailView.setError(getString(R.string.error_field_required)); } else if (!isEmailValid(email)) { mEmailView.setError(getString(R.string.error_invalid_email)); } //authenticate user auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { // there was an error Toast.makeText(LoginActivity.this, getString(R.string.auth_fail_msg), Toast.LENGTH_LONG).show(); } else { Intent intent = new Intent(LoginActivity.this, HomeActivity.class); startActivity(intent); finish(); } } }); } private boolean isEmailValid(String email) { //TODO: Replace this with your own logic return email.contains("@"); } private boolean isPasswordValid(String password) { //TODO: Replace this with your own logic return password.length() > 4; } public void redirectToSignUpPage(View v) { Intent redirect = new Intent(LoginActivity.this, SignUpActivity.class); startActivity(redirect); } public void redirectToForgotPasswordPage(View v) { Intent redirect = new Intent(LoginActivity.this, ForgotPasswordActivity.class); startActivity(redirect); } }
35.888
124
0.642443
935acaa14b33021372ae2712632a3ae0be613321
3,737
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2022, by David Gilbert and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------------- * DefaultKeyedValueDatasetTest.java * --------------------------------- * (C) Copyright 2003-2022, by David Gilbert and Contributors. * * Original Author: David Gilbert; * Contributor(s): -; * */ package org.jfree.data.general; import org.jfree.chart.TestUtils; import org.jfree.chart.internal.CloneUtils; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * Tests for the {@link DefaultKeyedValueDataset} class. */ public class DefaultKeyedValueDatasetTest { /** * Confirm that the equals method can distinguish all the required fields. */ @Test public void testEquals() { DefaultKeyedValueDataset d1 = new DefaultKeyedValueDataset("Test", 45.5); DefaultKeyedValueDataset d2 = new DefaultKeyedValueDataset("Test", 45.5); assertEquals(d1, d2); assertEquals(d2, d1); d1 = new DefaultKeyedValueDataset("Test 1", 45.5); d2 = new DefaultKeyedValueDataset("Test 2", 45.5); assertNotEquals(d1, d2); d1 = new DefaultKeyedValueDataset("Test", 45.5); d2 = new DefaultKeyedValueDataset("Test", 45.6); assertNotEquals(d1, d2); } /** * Confirm that cloning works. * @throws java.lang.CloneNotSupportedException */ @Test public void testCloning() throws CloneNotSupportedException { DefaultKeyedValueDataset d1 = new DefaultKeyedValueDataset("Test", 45.5); DefaultKeyedValueDataset d2 = (DefaultKeyedValueDataset) d1.clone(); assertNotSame(d1, d2); assertSame(d1.getClass(), d2.getClass()); assertEquals(d1, d2); } /** * Confirm that the clone is independent of the original. * @throws java.lang.CloneNotSupportedException */ @Test public void testCloneIndependence() throws CloneNotSupportedException { DefaultKeyedValueDataset d1 = new DefaultKeyedValueDataset("Key", 10.0); DefaultKeyedValueDataset d2 = CloneUtils.clone(d1); assertEquals(d1, d2); d2.updateValue(99.9); assertNotEquals(d1, d2); d2.updateValue(10.0); assertEquals(d1, d2); } /** * Serialize an instance, restore it, and check for equality. */ @Test public void testSerialization() { DefaultKeyedValueDataset d1 = new DefaultKeyedValueDataset("Test", 25.3); DefaultKeyedValueDataset d2 = TestUtils.serialised(d1); assertEquals(d1, d2); } }
33.366071
81
0.649719
513c3f16e7f63450bf7cc2d3c1c3f65618f2fc5c
8,237
/** * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org> */ package edu.lehigh.eng5m1b2016; import edu.lehigh.cse.lol.Facts; import edu.lehigh.cse.lol.Level; import edu.lehigh.cse.lol.Lol; import edu.lehigh.cse.lol.LolCallback; import edu.lehigh.cse.lol.Obstacle; import edu.lehigh.cse.lol.Physics; import edu.lehigh.cse.lol.ScreenManager; import edu.lehigh.cse.lol.Util; /** * Chooser draws the level chooser screens. Our chooser code is pretty * straightforward. However, the different screens are drawn in different ways, * to show how we can write more effective code once we are comfortable with * loops and basic geometry. */ public class Chooser implements ScreenManager { /** * This is a helper function for drawing a level button. If the level is * locked, the button isn't playable. Otherwise, the player can tap the * button to start a level. * * @param x X coordinate of the bottom left corner of the button * @param y Y coordinate of the bottom left corner of the button * @param width width of the button * @param height height of the button * @param level which level to play when the button is tapped */ static void drawLevelButton(float x, float y, float width, float height, final int level) { // figure out the last unlocked level int unlocked = Facts.getGameFact("unlocked", 1); // for each button, start by drawing an obstacle Obstacle tile = Obstacle.makeAsBox(x, y, width, height, "leveltile.png"); // if this level is unlocked, or if we are in unlocked mode, then attach // a callback and print the level number with a touchCallback, and then // put text on top of it if (level <= unlocked || Lol.getUnlockMode()) { tile.setTouchCallback(0, 0, 0, 0, false, new LolCallback() { public void onEvent() { Lol.doLevel(level); } }); Util.drawTextCentered(x + width / 2, y + height / 2, "" + level, 255, 255, 255, "arial.ttf", 56, 0); } // otherwise, just print an X else { Util.drawTextCentered(x + width / 2, y + height / 2, "X", 255, 255, 255, "arial.ttf", 56, 0); } } /** * This helper function is for drawing the button that takes us to the previous chooser screen * * @param x X coordinate of bottom left corner of the button * @param y Y coordinate of bottom left corner of the button * @param width width of the button * @param height height of the button * @param chooserLevel The chooser screen to create */ static void drawPrevButton(float x, float y, float width, float height, final int chooserLevel) { Obstacle prev = Obstacle.makeAsBox(x, y, width, height, "leftarrow.png"); prev.setTouchCallback(0, 0, 0, 0, false, new LolCallback() { public void onEvent() { Lol.doChooser(chooserLevel); } }); } /** * This helper function is for drawing the button that takes us to the next chooser screen * * @param x X coordinate of bottom left corner of the button * @param y Y coordinate of bottom left corner of the button * @param width width of the button * @param height height of the button * @param chooserLevel The chooser screen to create */ static void drawNextButton(float x, float y, float width, float height, final int chooserLevel) { Obstacle prev = Obstacle.makeAsBox(x, y, width, height, "rightarrow.png"); prev.setTouchCallback(0, 0, 0, 0, false, new LolCallback() { public void onEvent() { Lol.doChooser(chooserLevel); } }); } /** * This helper function is for drawing the button that takes us back to the splash screen * * @param x X coordinate of bottom left corner of the button * @param y Y coordinate of bottom left corner of the button * @param width width of the button * @param height height of the button */ static void drawSplashButton(float x, float y, float width, float height) { Obstacle prev = Obstacle.makeAsBox(x, y, width, height, "backarrow.png"); prev.setTouchCallback(0, 0, 0, 0, false, new LolCallback() { public void onEvent() { Lol.doSplash(); } }); } /** * Describe how to draw each level of the chooser. Our chooser will have 15 * levels per screen, so we need 7 screens. */ public void display(int which) { // screen 1: show 1-->15 // // NB: in this screen, we assume you haven't done much programming, so // we draw each button with its own line of code, and we don't use any // variables. if (which == 1) { Level.configure(48, 32); Physics.configure(0, 0); // set up background and music Util.drawPicture(0, 0, 48, 32, "HarambeArt/Platform/world map.png", 0); Util.drawPicture(8.5f, 16, 5, 5, "HarambeArt/Platform/canadian flag.png", 0); drawLevelButton(8.5f, 10, 5, 5, 1); Util.drawPicture(15f, 16, 5, 5, "HarambeArt/Platform/Detroid.png", 0); drawLevelButton(15f, 10, 5, 5, 2); Util.drawPicture(21.5f, 16, 5, 5, "HarambeArt/Platform/mexican flag.png", 0); drawLevelButton(21.5f, 10, 5, 5, 3); Util.drawPicture(28f, 16, 5, 5, "HarambeArt/Platform/japan Flag.png", 0); drawLevelButton(28f, 10, 5, 5, 4); Util.drawPicture(34.5f, 16, 5, 5, "HarambeArt/Platform/cincinatti.png", 0); drawLevelButton(34.5f, 10, 5, 5, 5); Level.setMusic("Music/BGM/BGM (Menu).ogg"); // for each button, draw an obstacle with a touchCallback, and then // put text on top of it. Our buttons are 5x5, we have 1.5 meters // between buttons, there's an 8.5 meter border on the left and // right, and there's an 11 meter border on the top // draw the navigation buttons drawSplashButton(0, 0, 5, 5); } // screen 2: show levels 16-->30 // // NB: this time, we'll use three loops to create the three rows. By // using some variables in the loops, we get the same effect as the // previous screen. The code isn't simpler yet, but it's still pretty // easy to understand. else if (which == 2) { Level.configure(48, 32); Physics.configure(0, 0); // set up background and music Util.drawPicture(0, 0, 48, 32,"HarambeArt/Platform/Final scene.png", 0); Level.setMusic("Music/BGM/Yeee(Producer song).ogg"); // draw the navigation buttons drawSplashButton(0, 28, 4, 4); } } }
41.60101
112
0.624863
decbae841aa4e3c9b7360f72c6834265da50aedc
740
package DataStructureLinkedList; public class DeleteNode_LL { /* * Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. */ // Algorithm: no prev pointer, the trick to skip next node by copying its value to current node public void deleteNode(ListNode node) { if (node == null || node.next == null) { return; } ListNode next = node.next; ListNode nextnext = next.next; node.val = next.val; node.next = nextnext; } }
32.173913
115
0.622973
73a4e1cbe6da4d8b69e9ce5780374dc53b300be9
3,181
/* * Copyright (C) 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.android_scripting.facade; import com.googlecode.android_scripting.jsonrpc.RpcReceiver; import com.googlecode.android_scripting.rpc.Rpc; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.nfc.NfcAdapter; import android.nfc.NfcManager; /** * Access NFC functions. */ public class NfcManagerFacade extends RpcReceiver { private final Service mService; private final NfcManager mNfcManager; private final NfcAdapter mNfc; private final EventFacade mEventFacade; private final IntentFilter mStateChangeFilter; private boolean mTrackingStateChange; public NfcManagerFacade(FacadeManager manager) { super(manager); mService = manager.getService(); mNfcManager = (NfcManager) mService.getSystemService(Context.NFC_SERVICE); mNfc = mNfcManager.getDefaultAdapter(); mEventFacade = manager.getReceiver(EventFacade.class); mStateChangeFilter = new IntentFilter(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED); } private final BroadcastReceiver mNfcStateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (NfcAdapter.ACTION_ADAPTER_STATE_CHANGED.equals(action)) { int nfcState = intent.getIntExtra(NfcAdapter.EXTRA_ADAPTER_STATE, NfcAdapter.STATE_OFF); if (nfcState == NfcAdapter.STATE_ON) { mEventFacade.postEvent("NfcStateOn", null); } else if (nfcState == NfcAdapter.STATE_OFF) { mEventFacade.postEvent("NfcStateOff", null); } } } }; @Rpc(description = "Check if NFC hardware is enabled.") public Boolean nfcIsEnabled() { return mNfc.isEnabled(); } @Rpc(description = "Start tracking NFC hardware state changes.") public void nfcStartTrackingStateChange() { mService.registerReceiver(mNfcStateReceiver, mStateChangeFilter); mTrackingStateChange = true; } @Rpc(description = "Stop tracking NFC hardware state changes.") public void nfcStopTrackingStateChange() { mService.unregisterReceiver(mNfcStateReceiver); mTrackingStateChange = false; } @Override public void shutdown() { if (mTrackingStateChange == true) { nfcStopTrackingStateChange(); } } }
34.576087
87
0.697265
07e7b5e707b7fd9733fb87d48bdedc8c90e597aa
3,028
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.planner.expressions.converter.converters; import org.apache.flink.annotation.Internal; import org.apache.flink.table.expressions.CallExpression; import org.apache.flink.table.expressions.Expression; import org.apache.flink.table.expressions.ValueLiteralExpression; import org.apache.flink.table.functions.BuiltInFunctionDefinitions; import org.apache.flink.table.planner.expressions.converter.CallExpressionConvertRule; import org.apache.flink.table.planner.functions.sql.FlinkSqlOperatorTable; import org.apache.calcite.rex.RexNode; import org.apache.calcite.sql.fun.SqlTrimFunction; import java.util.List; import static org.apache.flink.table.planner.expressions.converter.ExpressionConverter.extractValue; /** Conversion for {@link BuiltInFunctionDefinitions#TRIM}. */ @Internal class TrimConverter extends CustomizedConverter { @Override public RexNode convert(CallExpression call, CallExpressionConvertRule.ConvertContext context) { checkArgumentNumber(call, 4); List<Expression> children = call.getChildren(); ValueLiteralExpression removeLeadingExpr = (ValueLiteralExpression) children.get(0); Boolean removeLeading = extractValue(removeLeadingExpr, Boolean.class); ValueLiteralExpression removeTrailingExpr = (ValueLiteralExpression) children.get(1); Boolean removeTrailing = extractValue(removeTrailingExpr, Boolean.class); RexNode trimString = context.toRexNode(children.get(2)); RexNode str = context.toRexNode(children.get(3)); Enum trimMode; if (removeLeading && removeTrailing) { trimMode = SqlTrimFunction.Flag.BOTH; } else if (removeLeading) { trimMode = SqlTrimFunction.Flag.LEADING; } else if (removeTrailing) { trimMode = SqlTrimFunction.Flag.TRAILING; } else { throw new IllegalArgumentException("Unsupported trim mode."); } return context.getRelBuilder() .call( FlinkSqlOperatorTable.TRIM, context.getRelBuilder().getRexBuilder().makeFlag(trimMode), trimString, str); } }
45.19403
100
0.727873
1e3b2a47b427cd6131ca6f4cb3d333a6fc09fde7
1,106
package utitls; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Created by liang on 2016/9/18. */ public class MD5Utils { public static String encoder(String password){ StringBuffer buffer; /** * 1,信息摘要器 */ MessageDigest digest= null; try { digest = MessageDigest.getInstance("md5"); /** * 2,变成byte数组 */ byte bytes[]=digest.digest(password.getBytes()); buffer=new StringBuffer(); /** * 3,每个byte位与8个二进制数做与运算 */ for(byte b:bytes){ int number=b & 0xff; //int 类型转换为十六进制 String numberStr=Integer.toHexString(number); if(numberStr.length()==1){ buffer.append("0"); } buffer.append(numberStr); } return buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return ""; } } }
23.531915
61
0.486438
bd0a251706b840a445c94e2d13105800ae095537
2,676
// Copyright 2015-present 650 Industries. All rights reserved. package ghost; import android.view.ViewGroup; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.ViewGroupManager; import com.facebook.react.uimanager.annotations.ReactProp; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import androidx.annotation.NonNull; public class CastleBottomSheetManager extends ViewGroupManager<CastleBottomSheet> { @NonNull @Override public String getName() { return "CastleBottomSheet"; } @NonNull @Override protected CastleBottomSheet createViewInstance(@NonNull ThemedReactContext reactContext) { return new CastleBottomSheet(reactContext, reactContext.getCurrentActivity()); } @ReactProp(name = "viewId") public void setViewId(ViewGroup view, @Nullable int viewId) { ((CastleBottomSheet) view).setViewId(viewId); } @ReactProp(name = "isOpen") public void setIsOpen(ViewGroup view, @Nullable boolean isOpen) { ((CastleBottomSheet) view).setIsOpen(isOpen); } @ReactProp(name = "snapPoints") public void setSnapPoints(ViewGroup view, @Nullable ReadableArray snapPoints) { List<Integer> listSnapPoints = new ArrayList<>(); for (int i = 0; i < snapPoints.size(); i++) { listSnapPoints.add(snapPoints.getInt(i)); } ((CastleBottomSheet) view).setSnapPoints(listSnapPoints); } @ReactProp(name = "initialSnap") public void setInitialSnap(ViewGroup view, @Nullable int initialSnap) { ((CastleBottomSheet) view).setInitialSnap(initialSnap); } @ReactProp(name = "persistLastSnapWhenOpened") public void setPersistLastSnapWhenOpened(ViewGroup view, @Nullable boolean persistLastSnapWhenOpened) { ((CastleBottomSheet) view).setPersistLastSnapWhenOpened(persistLastSnapWhenOpened); } @ReactProp(name = "headerHeight") public void setHeaderHeight(ViewGroup view, @Nullable int headerHeight) { ((CastleBottomSheet) view).setHeaderHeight(headerHeight); } @ReactProp(name = "screenHeight") public void setScreenHeight(ViewGroup view, @Nullable int screenHeight) { ((CastleBottomSheet) view).setScreenHeight(screenHeight); } @ReactProp(name = "textInputHeight") public void setTextInputHeight(ViewGroup view, @Nullable int textInputHeight) { ((CastleBottomSheet) view).setTextInputHeight(textInputHeight); } /* @Override public void addView(CastleBottomSheet parent, View child, int index) { }*/ }
32.634146
107
0.721973
bdac1d8b72f611a44211f0dfa699085870050b50
3,966
package com.hjwylde.whiley.rewrite_rules.evaluator; import static com.google.common.collect.Sets.filter; import com.hjwylde.whiley.rewrite_rules.evaluator.util.Result; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.reflect.ClassPath; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * TODO: Documentation. * * @author Henry J. Wylde */ public final class Main { private static final ImmutableList<Result> WYCS_TEST_RESULTS; static { try { ImmutableList.Builder<Result> builder = ImmutableList.builder(); for (InputStream in : getResultInputStreams()) { try (InputStreamReader ir = new InputStreamReader( in); BufferedReader br = new BufferedReader(ir)) { builder.add(Result.from(br.lines())); } } WYCS_TEST_RESULTS = builder.build(); } catch (IOException e) { throw new RuntimeException(e); } } public static void main(String[] args) { Map<String, List<Double>> successResults = new HashMap<>(); Map<String, List<Double>> failResults = new HashMap<>(); for (Result result : WYCS_TEST_RESULTS) { Map<String, Double> ruleCounts = new HashMap<>( result.getNormalisedInferenceRuleCounts()); ruleCounts.putAll(result.getNormalisedReductionRuleCounts()); for (String rule : ruleCounts.keySet()) { double count = ruleCounts.get(rule); if (result.isSuccess()) { successResults.putIfAbsent(rule, new ArrayList<>()); successResults.get(rule).add(count); } else { failResults.putIfAbsent(rule, new ArrayList<>()); failResults.get(rule).add(count); } } } Path path = Paths.get("out/"); try { Files.createDirectories(path); List<String> lines = successResults.entrySet().stream().map( e -> e.getKey() + "," + Joiner.on(",").join(e.getValue())).collect( Collectors.toList()); Files.write(path.resolve("success.csv"), lines, StandardCharsets.UTF_8, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); lines = failResults.entrySet().stream().map(e -> e.getKey() + "," + Joiner.on(",").join( e.getValue())).collect(Collectors.toList()); Files.write(path.resolve("fail.csv"), lines, StandardCharsets.UTF_8, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); } catch (IOException e) { e.printStackTrace(); } } private static ImmutableList<InputStream> getResultInputStreams() throws IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Set<ClassPath.ResourceInfo> resources = ClassPath.from(classLoader).getResources(); resources = filter(resources, input -> input.getResourceName().startsWith("wycs-tests")); ImmutableList.Builder<InputStream> builder = ImmutableList.builder(); for (ClassPath.ResourceInfo resource : resources) { builder.add(classLoader.getResourceAsStream(resource.getResourceName())); } return builder.build(); } }
35.410714
100
0.624307
bbda1bc260becbb87611bf4167f31d130488ad77
4,685
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iotdb.db.consensus.statemachine.visitor; import org.apache.iotdb.common.rpc.thrift.TSStatus; import org.apache.iotdb.commons.path.PartialPath; import org.apache.iotdb.commons.utils.StatusUtils; import org.apache.iotdb.db.engine.storagegroup.DataRegion; import org.apache.iotdb.db.exception.BatchProcessException; import org.apache.iotdb.db.exception.TriggerExecutionException; import org.apache.iotdb.db.exception.WriteProcessException; import org.apache.iotdb.db.mpp.plan.planner.plan.node.PlanNode; import org.apache.iotdb.db.mpp.plan.planner.plan.node.PlanVisitor; import org.apache.iotdb.db.mpp.plan.planner.plan.node.write.DeleteDataNode; import org.apache.iotdb.db.mpp.plan.planner.plan.node.write.InsertMultiTabletsNode; import org.apache.iotdb.db.mpp.plan.planner.plan.node.write.InsertRowNode; import org.apache.iotdb.db.mpp.plan.planner.plan.node.write.InsertRowsNode; import org.apache.iotdb.db.mpp.plan.planner.plan.node.write.InsertRowsOfOneDeviceNode; import org.apache.iotdb.db.mpp.plan.planner.plan.node.write.InsertTabletNode; import org.apache.iotdb.rpc.RpcUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Arrays; public class DataExecutionVisitor extends PlanVisitor<TSStatus, DataRegion> { private static final Logger LOGGER = LoggerFactory.getLogger(DataExecutionVisitor.class); @Override public TSStatus visitPlan(PlanNode node, DataRegion context) { return null; } @Override public TSStatus visitInsertRow(InsertRowNode node, DataRegion dataRegion) { try { dataRegion.insert(node); return StatusUtils.OK; } catch (WriteProcessException | TriggerExecutionException e) { LOGGER.error("Error in executing plan node: {}", node, e); return StatusUtils.EXECUTE_STATEMENT_ERROR; } } @Override public TSStatus visitInsertTablet(InsertTabletNode node, DataRegion dataRegion) { try { dataRegion.insertTablet(node); return StatusUtils.OK; } catch (TriggerExecutionException | WriteProcessException e) { LOGGER.error("Error in executing plan node: {}", node, e); return StatusUtils.EXECUTE_STATEMENT_ERROR; } catch (BatchProcessException e) { return RpcUtils.getStatus(Arrays.asList(e.getFailingStatus())); } } @Override public TSStatus visitInsertRows(InsertRowsNode node, DataRegion dataRegion) { try { dataRegion.insert(node); return StatusUtils.OK; } catch (BatchProcessException e) { return RpcUtils.getStatus(Arrays.asList(e.getFailingStatus())); } } @Override public TSStatus visitInsertMultiTablets(InsertMultiTabletsNode node, DataRegion dataRegion) { try { dataRegion.insertTablets(node); return StatusUtils.OK; } catch (BatchProcessException e) { return RpcUtils.getStatus(Arrays.asList(e.getFailingStatus())); } } @Override public TSStatus visitInsertRowsOfOneDevice( InsertRowsOfOneDeviceNode node, DataRegion dataRegion) { try { dataRegion.insert(node); return StatusUtils.OK; } catch (WriteProcessException | TriggerExecutionException e) { LOGGER.error("Error in executing plan node: {}", node, e); return StatusUtils.EXECUTE_STATEMENT_ERROR; } catch (BatchProcessException e) { return RpcUtils.getStatus(Arrays.asList(e.getFailingStatus())); } } @Override public TSStatus visitDeleteData(DeleteDataNode node, DataRegion dataRegion) { try { for (PartialPath path : node.getPathList()) { dataRegion.deleteByDevice( path, node.getDeleteStartTime(), node.getDeleteEndTime(), Long.MAX_VALUE, null); } return StatusUtils.OK; } catch (IOException e) { LOGGER.error("Error in executing plan node: {}", node, e); return StatusUtils.EXECUTE_STATEMENT_ERROR; } } }
37.782258
95
0.747065
0ca87d4f7dfc68c8abfcf5e76d292e529af7af2f
4,712
package ru.vas.resourceservice.integration.file; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.context.IntegrationContextUtils; import org.springframework.integration.endpoint.SourcePollingChannelAdapter; import org.springframework.integration.test.context.SpringIntegrationTest; import org.springframework.kafka.support.converter.KafkaMessageHeaders; import org.springframework.kafka.test.context.EmbeddedKafka; import org.springframework.messaging.Message; import org.springframework.test.context.junit4.SpringRunner; import ru.vas.resourceservice.schedule.download.DownloadRegistryScheduler; import ru.vas.resourceservice.service.DownloadService; import ru.vas.resourceservice.service.FileService; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; @RunWith(SpringRunner.class) @SpringBootTest @SpringIntegrationTest(noAutoStartup = "fileInboundChannelAdapter") @EmbeddedKafka(partitions = 3, brokerProperties = { "listeners=PLAINTEXT://localhost:9092", "port=9092" }) class FileProcessingIntegrationFlowTest { @Autowired private SourcePollingChannelAdapter fileInboundChannelAdapter; @MockBean(name = "downloadScheduler") private DownloadRegistryScheduler downloadRegistryScheduler; @MockBean(name = "gitDownloadService") private DownloadService downloadService; @MockBean(name = IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME) private DirectChannel directChannel; @Autowired @Qualifier(value = KafkaMessageHeaders.REPLY_CHANNEL) private DirectChannel replyChannel; @SpyBean FileService fileService; @Value("${resource-service.registry.file-location}") private String tmpIn; @Value("${resource-service.registry.file-location}${resource-service.registry.processed-location}") private String tmpOut; private static final String FILE_SOURCE = "103.224.182.250 | 101.224.182.250;;;тестовое инфо 1;��-�17-079-210;2018-01-11\n" + "103.246.200.0/22;;;тестовое инфо 2;9-Restricting;2017-04-28\n" + "104.16.10.218;;;тестовое инфо 3;2-946/13;2013-06-10\n" + "104.16.c100.59;;;тестовое инфо 4;2-6-27/2016-02-12-22-��;2016-04-11"; @BeforeEach public void setUp() throws IOException { tearDown(); this.fileInboundChannelAdapter.start(); } @AfterEach public void tearDown() throws IOException { File outDir = new File(tmpOut); if (outDir.exists()) { FileUtils.cleanDirectory(outDir); } File inDir = new File(tmpIn); if (inDir.exists()) { FileUtils.cleanDirectory(inDir); } } @Test void fileReadingFlow() throws IOException, InterruptedException { //given ArgumentCaptor<Message<?>> argumentCaptor = ArgumentCaptor.forClass(Message.class); File in = new File(tmpIn, "foo"); FileOutputStream fos = new FileOutputStream(in); fos.write(FILE_SOURCE.getBytes()); fos.close(); //when in.renameTo(new File(tmpIn, "foo.csv")); Thread.sleep(5000); final Optional<Path> any = Files.walk(Paths.get(tmpOut)) .filter(Files::isRegularFile) .filter(path -> path.toFile().getName().endsWith(".tmp")) .findAny(); //then assertTrue(any.isPresent()); final Path path = any.get(); assertTrue(Files.exists(path)); Mockito.verify(fileService).renameFile(argumentCaptor.capture(), anyString()); final Message<?> message = argumentCaptor.getValue(); assertTrue(message.getPayload() instanceof List); assertEquals(((List<String>) message.getPayload()).size(), 4); } }
41.333333
106
0.72899
5b0f537457d49c3d2b3358a4ef93c5026acc2e79
11,052
package fr.itris.glips.extension.jwidget.trends.runtime.view; import java.text.*; import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import fr.itris.glips.extension.jwidget.trends.runtime.*; import fr.itris.glips.extension.jwidget.trends.runtime.configuration.*; import fr.itris.glips.extension.jwidget.trends.runtime.view.component.*; import fr.itris.glips.extension.jwidget.trends.runtime.view.component.curvesproperties.*; import fr.itris.glips.extension.jwidget.trends.runtime.view.component.dialog.*; import fr.itris.glips.library.widgets.*; /** * the class used to handle all the updates, actions and modifications * that can occur on one of the components * @author ITRIS, Jordi SUC */ public class ComponentsHandler { /** * the offset from which the curve update will be displayed */ public static final int rightOffset=20; /** * the view part */ private TrendsRuntimeView view; /** * the component that will be displayed on a svg canvas */ private JPanel trendsComponent; /** * the component displaying the curves */ private CurvesComponent curvesComponent; /** * the component displaying the scrollbar */ private HorizontalBarComponent horizontalBarComponent; /** * the component displaying a tool bar */ private ToolBarComponent toolBarComponent; /** * the curves properties component */ private CurvesPropertiesComponent curvesPropertiesComponent; /** * the current action */ private String currentAction=""; /** * the current exclusive action */ private String currentExclusiveAction=""; /** * the decimal formats */ private DecimalFormat format, exponentFormat; /** * the date pickers dialog */ private DatePickersDialog datePickersDialog; /** * the dialog that is displayed when history values are retrieved */ private WaitDialog waitDialog; /** * the constructor of the class * @param view the view part */ public ComponentsHandler(TrendsRuntimeView view){ this.view=view; //getting the configuration object TrendsConfiguration configuration=view.getController().getConfiguration(); //getting the number of decimal digits for displaying the values int decimalDigitNumber=configuration.getValuesDecimalDigitsNumber(); //computing the pattern for the decimal part of the format String decimalPattern=""; for(int i=0; i<decimalDigitNumber; i++){ decimalPattern+="#"; } //creating the decimal format DecimalFormatSymbols symbols=new DecimalFormatSymbols(); format=new DecimalFormat("#############."+decimalPattern, symbols); format.setDecimalSeparatorAlwaysShown(false); exponentFormat=new DecimalFormat("0."+decimalPattern+"E0####", symbols); exponentFormat.setDecimalSeparatorAlwaysShown(false); //creating the components trendsComponent=new JPanel(); trendsComponent.setLayout(new BorderLayout(0, 0)); JPanel centerComponent=new JPanel(); centerComponent.setLayout(new BorderLayout(0, 0)); curvesComponent=new CurvesComponent(this); centerComponent.add(curvesComponent, BorderLayout.CENTER); if(configuration.displayToolBar()){ toolBarComponent=new ToolBarComponent(this); centerComponent.add(toolBarComponent, BorderLayout.NORTH); } if(configuration.displayScrollBar()){ horizontalBarComponent=new HorizontalBarComponent(this); centerComponent.add(horizontalBarComponent, BorderLayout.SOUTH); } trendsComponent.add(centerComponent, BorderLayout.CENTER); curvesPropertiesComponent=new CurvesPropertiesComponent(this); } /** * initializes this component */ protected void initialize(){ curvesComponent.initialize(); if(toolBarComponent!=null){ toolBarComponent.initialize(); } if(horizontalBarComponent!=null){ horizontalBarComponent.initialize(); } curvesPropertiesComponent.initialize(); Point location=new Point(); if(toolBarComponent!=null){ location=new Point( toolBarComponent.getDisplayCurvesPropertiesTool().getWidth()/2, toolBarComponent.getDisplayCurvesPropertiesTool().getHeight()/2); SwingUtilities.convertPointToScreen(location, toolBarComponent.getDisplayCurvesPropertiesTool()); SwingUtilities.convertPointFromScreen(location, getView().getController().getJwidgetRuntime().getPicture().getCanvas()); } curvesPropertiesComponent.setVisible( view.getController().getConfiguration().displayCurvesLegend(), location); //creating the date pickers manager Component parent=trendsComponent.getTopLevelAncestor(); if(parent instanceof Frame){ datePickersDialog=new DatePickersDialog(view, (Frame)parent); }else if(parent instanceof JApplet){ datePickersDialog=new DatePickersDialog(view, getView().getController().getJwidgetRuntime().getPicture(). getMainDisplay().getTopLevelFrame()); }else if(parent instanceof JDialog){ datePickersDialog=new DatePickersDialog(view, (JDialog)parent); } //creating the wait dialog// //creating the cancel button ActionListener actionListener=new ActionListener(){ public void actionPerformed(ActionEvent evt) { Thread thread=new Thread(){ @Override public void run() { view.getController().getModel().setDbRequestCancelled(true); } }; thread.start(); waitDialog.setVisible(false); } }; if(parent instanceof Frame){ waitDialog=new WaitDialog((Frame)parent, actionListener); }else if(parent instanceof JDialog){ waitDialog=new WaitDialog((JDialog)parent, actionListener); } //setting the messages waitDialog.setTitleMessage(TrendsBundle.bundle.getString("historyDataLoading")); waitDialog.setMessage(TrendsBundle.bundle.getString("historyDataLoadingInfo")); waitDialog.setErrorMessage(TrendsBundle.bundle.getString("historyDataErrorLoading")); } /** * @return the curves properties component */ public CurvesPropertiesComponent getCurvesPropertiesComponent() { return curvesPropertiesComponent; } /** * disposes the handler */ public void dispose(){ datePickersDialog.disposeDialog(); waitDialog.disposeDialog(); curvesComponent.dispose(); if(horizontalBarComponent!=null){ horizontalBarComponent.dispose(); } if(toolBarComponent!=null){ toolBarComponent.dispose(); } curvesPropertiesComponent.dispose(); view=null; trendsComponent=null; curvesComponent=null; horizontalBarComponent=null; toolBarComponent=null; curvesPropertiesComponent=null; datePickersDialog=null; waitDialog=null; } /** * sets the current action * @param id the id of the action * @param deselectAll whether to deselect all the mouse action */ public void setCurrentAction(String id, boolean deselectAll){ this.currentAction=id; clearTools(true); } /** * sets the current exclusive action * @param id the id of the action */ public void setCurrentExclusiveAction(String id){ this.currentExclusiveAction=id; } /** * clearing some tools * @param deselect whether to deselect the tools */ public void clearTools(boolean deselect){ if(toolBarComponent!=null){ toolBarComponent.getCursorLineTool().clear(); toolBarComponent.getCursorCrossTool().clear(); if(deselect){ toolBarComponent.deselectMouseTools(); } } } /** * @return the current mouse action */ public String getCurrentAction() { return currentAction; } /** * @return the current exclusive action */ public String getCurrentExclusiveAction() { return currentExclusiveAction; } /** * initiates the update */ public void initiateUpdate(){ curvesComponent.initiateUpdate(); } /** * update the tag values for the give tag name * @param tagName the name of a tag * @param tagValues the map associating a time value to a tag value * @param startDate the start date of the tag values * @param endDate the end date of the tag values */ public void updateValues(String tagName, TreeMap<Long, Object> tagValues, long startDate, long endDate){ curvesComponent.updateValues(tagName, tagValues, startDate, endDate); } /** * validates all the updates that have been done, * so that the curves panel can be refreshed * @param originDate the date before which no tag value should be displayed * @param lastDate the date after which no tag value should be displayed * @param startDate the start date of the tag values * @param endDate the end date of the tag values */ public void validateUpdates(long originDate, long lastDate, long startDate, long endDate){ curvesComponent.validateUpdates(startDate, endDate); if(horizontalBarComponent!=null){ horizontalBarComponent.validateUpdates(originDate, lastDate, startDate, endDate); } } /** * updates the scroll bar given the dates when in scroll sub mode * @param firstDate the date before which no tag value should be displayed * @param lastDate the date after which no tag value should be displayed * @param startDate the start date of the tag values * @param endDate the end date of the tag values */ public void updateScrollBar(long firstDate, long lastDate, long startDate, long endDate){ if(horizontalBarComponent!=null){ horizontalBarComponent.updateScrollBar(firstDate, lastDate, startDate, endDate); } } /** * @return the view part */ public TrendsRuntimeView getView() { return view; } /** * @return the trends component */ public JPanel getTrendsComponent() { return trendsComponent; } /** * @return the curves component */ public CurvesComponent getCurvesComponent() { return curvesComponent; } /** * @return the horizontal bar component */ public HorizontalBarComponent getHorizontalBarComponent() {//TODO return horizontalBarComponent; } /** * notifies that the mode or the sub mode changed */ public void modeOrSubModeChanged() { if(toolBarComponent!=null){ toolBarComponent.modeOrSubModeChanged(); } } /** * @return the tool bar component */ public ToolBarComponent getToolBarComponent() {//TODO return toolBarComponent; } /** * @return the date pickers dialog */ public DatePickersDialog getDatePickersDialog() { return datePickersDialog; } /** * @return the wait dialog */ public WaitDialog getWaitDialog() { return waitDialog; } /** * returns the string representation of the given value * @param value a double value * @return the string representation of the given value */ public String getStringRepresentation(double value){ String str=""; double absValue=Math.abs(value); if(absValue>0 && (absValue<=view.getController().getConfiguration().getLowerLimit() || absValue>=view.getController().getConfiguration().getHigherLimit())){ str=exponentFormat.format(value); }else{ str=format.format(value); } return str; } }
24.131004
91
0.722856
5a578acc17c5b4f3c8f31cc1a060016d4517e0bd
370
package in.hocg.boot.changelog.sample.service; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; /** * Created by hocgin on 2020/8/16 * email: hocgin@gmail.com * * @author hocgin */ @Service @RequiredArgsConstructor(onConstructor = @__(@Lazy)) public class IndexService { }
20.555556
52
0.775676
d5a4e80c966d2235d28640468c985de0c5bea40c
6,242
package dao; import model.Role; import model.RoleTypeEnum; import model.User; import model.UserInfo; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Created by xzinoviou * 13/10/2018 */ public class UserDao extends Dao implements DaoUtils <User,Long,String> { public UserDao(){ super(); } public Object getEntityById(Long id) { return null; } public Object getEntityByParam(String email) { User user = null; try{ String query = "SELECT * FROM USER WHERE USER_EMAIL = ? "; preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1,email); resultSet = preparedStatement.executeQuery(); while(resultSet.next()){ user = new User(); user.setId(resultSet.getLong(1)); user.setEmail(resultSet.getString(2)); user.setPassword(resultSet.getString(3)); user.setFirstName(resultSet.getString(4)); user.setLastName(resultSet.getString(5)); user.setDate(resultSet.getDate(6)); user.setTelephone(resultSet.getString(7)); user.setAddress(resultSet.getString(8)); } closeAll(); } catch(SQLException e){ e.printStackTrace(); } return user; } public List<Role> getRoleTypes(){ List<Role> roles = new ArrayList<>(); try{ String query = "SELECT ROLE_ID,ROLE_TYPE FROM ROLE"; preparedStatement = connection.prepareStatement(query); resultSet = preparedStatement.executeQuery(); while(resultSet.next()){ Role role = new Role(); role.setId(resultSet.getLong(1)); role.setRole(resultSet.getString(2)); roles.add(role); } closeAll(); } catch(SQLException e){ e.printStackTrace(); } return roles; } public void assignRole(User user, Long roleId){ try{ String query = "INSERT INTO USER_ROLE (USER_ID,ROLE_ID) VALUES(?,?)"; preparedStatement = connection.prepareStatement(query); preparedStatement.setLong(1,user.getId()); preparedStatement.setLong(2,roleId); preparedStatement.executeUpdate(); closeAll(); } catch(SQLException e){ e.printStackTrace(); } } public Object getEntityByParams(String email,String password) { User user = null; try{ String query = "SELECT * FROM USER WHERE USER_EMAIL = ? " + "AND USER_PASSWORD = ?"; preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1,email); preparedStatement.setString(2,password); resultSet = preparedStatement.executeQuery(); while(resultSet.next()){ user = new User(); user.setId(resultSet.getLong(1)); user.setEmail(resultSet.getString(2)); user.setPassword(resultSet.getString(3)); user.setFirstName(resultSet.getString(4)); user.setLastName(resultSet.getString(5)); user.setDate(resultSet.getDate(6)); user.setTelephone(resultSet.getString(7)); user.setAddress(resultSet.getString(8)); } closeAll(); } catch(SQLException e){ e.printStackTrace(); } return user; } public List<User> getAllEntities() { return null; } public void createEntity(User user) { try{ String query = "INSERT INTO USER " + "(USER_EMAIL,USER_PASSWORD,FIRST_NAME,LAST_NAME," + "DATE_OF_BIRTH,TEL,ADDRESS) " + "VALUES(?,?,?,?,?,?,?)"; preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1,user.getEmail()); preparedStatement.setString(2,user.getPassword()); preparedStatement.setString(3,user.getFirstName()); preparedStatement.setString(4,user.getLastName()); preparedStatement.setDate(5,user.getDate()); preparedStatement.setString(6,user.getTelephone()); preparedStatement.setString(7,user.getAddress()); preparedStatement.executeUpdate(); closeAll(); } catch(SQLException e){ e.printStackTrace(); } } public void editEntity(User user) { } public void deleteEntityById(Long aLong) { } public Object getUserRole(User user){ String userRole = null; try{ String query = "SELECT ROLE.ROLE_TYPE FROM USER,USER_ROLE,ROLE WHERE USER.USER_ID=USER_ROLE.USER_ID AND " + "USER_ROLE.ROLE_ID=ROLE.ROLE_ID AND USER.USER_ID = ?"; preparedStatement = connection.prepareStatement(query); preparedStatement.setLong(1,user.getId()); resultSet = preparedStatement.executeQuery(); while(resultSet.next()){ userRole = resultSet.getString(1); } closeAll(); } catch(SQLException e){ e.printStackTrace(); } return userRole; } public Object getUserRoleByEmail(String email){ String userRole = null; try{ String query = "SELECT ROLE.ROLE_TYPE FROM USER,USER_ROLE,ROLE WHERE USER.USER_ID=USER_ROLE.USER_ID AND " + "USER_ROLE.ROLE_ID=ROLE.ROLE_ID AND USER.USER_EMAIL = ?"; preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1,email); resultSet = preparedStatement.executeQuery(); while(resultSet.next()){ userRole = resultSet.getString(1); } closeAll(); } catch(SQLException e){ e.printStackTrace(); } return userRole; } }
23.73384
119
0.563121
8c6ac5444c602ce86aca69dc68d50a7e4917716c
1,123
package com.cm.understandingJvm; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodType; import static java.lang.invoke.MethodHandles.lookup; /** * @author chengawu * @date 1/11/2019 2:22 PM */ public class InvokeVirtualTest { class GrandFather { void thinking() { System.out.println("I am grandfather"); } } class Father extends GrandFather { void thinking() { System.out.println("I am father"); } } class Son extends Father { void thinking() { try { MethodType mt = MethodType.methodType(void.class); MethodHandle mh = lookup().findSpecial(GrandFather.class, "thinking", mt, getClass()); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } public static void main(String[] args) { // InvokeVirtualTest test = new InvokeVirtualTest(); // Son son = test.Son; // (new Son()).thinking(); } }
25.522727
102
0.573464
21ba62e82c18e8e71138faaf65cf100691b51bcd
390
package com.example.android.sampleapp; import android.app.Application; import roboguice.RoboGuice; public class MySampleApplication extends Application { @Override public void onCreate() { super.onCreate(); RoboGuice.setBaseApplicationInjector(this, RoboGuice.DEFAULT_STAGE, RoboGuice.newDefaultRoboModule(this), new ApplicationModule()); } }
26
79
0.730769
88133ccfb04231a0f852c5cd98d5284c7449588a
3,312
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package javax.application.threading; import java.util.concurrent.Callable; import java.util.concurrent.CompletionStage; /** * @author Andres Almiray */ public interface ThreadingHandler { /** * True if the current thread is the UI thread. */ boolean isUIThread(); /** * Executes a code block asynchronously on the UI thread. * * @param runnable block of code that must be executed. Must not be {@code null}. */ void executeInsideUIAsync(Runnable runnable); /** * Executes a code block synchronously on the UI thread. * * @param runnable block of code that must be executed. Must not be {@code null}. */ void executeInsideUISync(Runnable runnable); /** * Executes a code block synchronously on the UI thread. * * @param callable block of code that must be executed. Must not be {@code null}. * * @return return value from the executed block. May be {@code null}. */ <R> R executeInsideUISync(Callable<R> callable); /** * Executes a code block outside of the UI thread. * The {@code runnable} will be invoked on the same thread as the caller if the caller * is already outside the UI thread. * * @param runnable block of code that must be executed. Must not be {@code null}. */ void executeOutsideUI(Runnable runnable); /** * Executes a code block on a background thread, always. * The {@code runnable} will be invoked on a different thread regardless of the thread * where the caller issued the call. * * @param runnable block of code that must be executed. Must not be {@code null}. */ void executeOutsideUIAsync(Runnable runnable); /** * Executes a code block on a background thread, always. * The {@code callable} will be invoked on a different thread regardless of the thread * where the caller issued the call. * * @param callable block of code that must be executed. Must not be {@code null}. * * @return a {@code CompletionStage} that can be used to signal the resolution or rejection of the code block. Never returns {@code null}. */ <R> CompletionStage<R> executeOutsideUIAsync(Callable<R> callable); /** * Executes a code block asynchronously on the UI thread. * * @param callable block of code that must be executed. Must not be {@code null}. * * @return a {@code CompletionStage} that can be used to signal the resolution or rejection of the code block. Never returns {@code null}. */ <R> CompletionStage<R> executeInsideUIAsync(Callable<R> callable); }
35.612903
142
0.67965
73ea0ea9ffce1d81fe61207daa9d46f5b04028e9
4,307
package cosmos.commands.perworld; import cosmos.Cosmos; import cosmos.constants.PerWorldCommands; import cosmos.statics.config.Config; import ninja.leaping.configurate.ConfigurationNode; import org.spongepowered.api.Sponge; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.util.Tuple; import org.spongepowered.api.world.World; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; public class GroupRegister { private static final Map<Tuple<PerWorldCommands, String>, Set<String>> groupMap = new HashMap<>(); public static Collection<Set<String>> collectGroups(PerWorldCommands feature) { final Set<String> collectedWorlds = new HashSet<>(); return streamEntries() .filter(entry -> entry.getKey().getFirst().equals(feature)) .filter(entry -> !collectedWorlds.contains(entry.getKey().getSecond())) .map(entry -> { collectedWorlds.add(entry.getKey().getSecond()); return entry.getValue(); }) .collect(Collectors.toSet()); } public static Optional<Set<String>> find(Tuple<PerWorldCommands, String> key) { return Optional.ofNullable(value(key)); } public static Optional<Set<String>> register(Tuple<PerWorldCommands, String> key, Set<String> value) { return Optional.ofNullable(groupMap.computeIfAbsent(key, k -> value)) .map(v -> { v.forEach(k -> { Tuple<PerWorldCommands, String> tupleK = Tuple.of(key.getFirst(), k); if (!value.contains(k)) { groupMap.remove(tupleK); } }); return groupMap.put(key, value); }); } public static void registerAll() { if (!Config.isLoaded()) { Cosmos.sendConsole(TextColors.RED, "Configuration file not loaded. No per world groups loaded !"); return; } for (final PerWorldCommands feature : PerWorldCommands.values()) { Config.getGroupNode(feature.getListenerClass()) .map(ConfigurationNode::getChildrenList) .orElse(Collections.emptyList()) .stream() .map(ConfigurationNode::getChildrenList) .map(nodes -> nodes.stream() .map(ConfigurationNode::getString) .map(worldName -> Optional.ofNullable(worldName).flatMap(Sponge.getServer()::getWorld).map(World::getName)) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toSet())) .forEach(group -> group.forEach(key -> register(Tuple.of(feature, key), group))); Config.saveGroup(feature.getListenerClass(), collectGroups(feature)); } } public static Stream<Map.Entry<Tuple<PerWorldCommands, String>, Set<String>>> streamEntries() { return groupMap.entrySet().stream(); } public static Optional<Set<String>> unregister(Tuple<PerWorldCommands, String> key) { return Optional.ofNullable(groupMap.remove(key)) .map(v -> { Set<String> value = new HashSet<>(v); value.remove(key.getSecond()); v.forEach(k -> { Tuple<PerWorldCommands, String> tupleK = Tuple.of(key.getFirst(), k); if (!tupleK.equals(key) && groupMap.containsKey(tupleK)) { if (value.size() > 1) { groupMap.put(tupleK, value); } else { groupMap.remove(tupleK); } } }); return v; }); } public static Set<String> value(Tuple<PerWorldCommands, String> key) { return groupMap.get(key); } }
38.115044
135
0.560251
2b16f2c7eb532e453462e54da49dc7660153bbf4
2,445
/* * MinIO Java SDK for Amazon S3 Compatible Cloud Storage, (C) 2015 MinIO, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.minio.messages; import java.util.Date; import org.xmlpull.v1.XmlPullParserException; import com.google.api.client.util.Key; import io.minio.DateFormat; /** * Helper class to parse Amazon AWS S3 response XML containing object item information. */ @SuppressWarnings({"SameParameterValue", "unused"}) public class Item extends XmlEntity { @Key("Key") private String objectName; @Key("LastModified") private String lastModified; @Key("ETag") private String etag; @Key("Size") private long size; @Key("StorageClass") private String storageClass; @Key("Owner") private Owner owner; private boolean isDir = false; public Item() throws XmlPullParserException { this(null, false); } /** * Constructs a new Item object with given object name and IsDir flag. */ public Item(String objectName, boolean isDir) throws XmlPullParserException { super(); this.name = "Item"; this.objectName = objectName; this.isDir = isDir; } /** * Returns object name. */ public String objectName() { return objectName; } /** * Returns last modified time of the object. */ public Date lastModified() { return DateFormat.RESPONSE_DATE_FORMAT.parseDateTime(lastModified).toDate(); } /** * Returns ETag of the object. */ public String etag() { return etag; } /** * Returns object size. */ public long objectSize() { return size; } /** * Returns storage class of the object. */ public String storageClass() { return storageClass; } /** * Returns owner object of given the object. */ public Owner owner() { return owner; } /** * Returns whether the object is a directory or not. */ public boolean isDir() { return isDir; } }
20.375
87
0.677301
792c2b8c13c50c9490c1defce615cdcc5a80abde
1,704
/* ©Copyright 2011 Cameron Morris * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.owasp.passfault; import org.junit.Test; import org.owasp.passfault.api.PatternFinder; import org.owasp.passfault.impl.FinderByPropsBuilder; import java.io.File; import java.util.Collection; import static org.junit.Assert.assertTrue; public class FinderByPropsBuilderTest { @Test public void byFile() throws Exception { System.out.println("current directory:" + new File(".").getCanonicalFile()); File file = new File("src/test/resources/wordlists"); assertTrue(file.exists()); Collection<PatternFinder> finders = new FinderByPropsBuilder(). isInMemory(false). setFileLoader(file). build(); System.out.println("Finders found " + finders); assertTrue(finders.size() > 4); } //@Test() the word lists are no longer embedded. public void byResource() throws Exception { Collection<PatternFinder> finders = new FinderByPropsBuilder(). loadDefaultWordLists(). isInMemory(true). build(); System.out.println("Finders found " + finders); assertTrue(finders.size() > 4); } }
34.77551
81
0.702465
52fa8ea8e0feef3e242a3775137df01511b60276
2,479
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; public class ProblemB { static long gcd(long a, long b) { if (b == 0) return a; else return gcd(b,a % b); } private static HashSet<Long> getFactors(long n) { HashSet<Long> factors = new HashSet<>(); for (long i = 1; i <= (long)Math.sqrt(n); i++) { if (n % i == 0) { factors.add(i); factors.add(n/i); } } return factors; } public static void main(String[] args) throws Exception { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printWriter = new PrintWriter(System.out); int K = Integer.parseInt(bufferedReader.readLine()); long[][] arr = new long[K][K]; for (int i = 0; i < K; i++) { String[] strings = bufferedReader.readLine().split(" "); for (int j = 0; j < K; j++) { arr[i][j] = Long.parseLong(strings[j]); } } long gcd = arr[0][1]; for (int i = 0; i <= 0; i++) { for (int j = 0; j < K; j++) { if (arr[i][j] == 0) { continue; } gcd = gcd(arr[i][j], gcd); } } HashSet<Long> fact = getFactors(gcd); outer : for (Long l : fact) { long newarr[] = new long[K]; newarr[0] = l; for (int i = 1; i < K; i++) { newarr[i] = arr[0][i] / l; //System.out.println(newarr[i]); } long[][] blur = new long[K][K]; for (int i = 0; i < K; i++) { for (int j = 0; j < K; j++) { if (i == j) { blur[i][j] = 0; continue; } blur[i][j] = newarr[i] * newarr[j]; } } for (int i = 0; i < K; i++) { for (int j = 0; j < K; j++) { if (arr[i][j] == blur[i][j]) { continue; } else { continue outer; } } } for (int i = 0; i < K; i++) { printWriter.print(newarr[i] + " "); } } printWriter.flush(); } }
31.782051
93
0.394514
673d253ccccf1d68d88577f18b6441c2bc0cfc99
1,632
import java.util.Scanner; import depository.Depository; import simulates.Pretense; import static java.lang.System.out; import static java.lang.System.in; public class Chiral { public fabricator.Promoter waffen = null; public static synchronized void main(String[] rationalizations) { java.lang.String bcl = ""; java.lang.String ahn = ""; java.lang.String z = ""; fabricator.Promoter arsenic = null; fabricator.Promoter emt = null; fabricator.Promoter cathode = null; fabricator.Promoter wor = null; out.print("\f"); int annex = 0; try { annex = (in.available()); } catch (Exception e) { } if (annex <= 0) { out.println("ERROR: System.in is empty, no file was passed or it is empty"); } else { double endCrop = 0, willHateful = 0; int futureDepositoryConstrain = 0; try { Scanner portable = new Scanner(in); willHateful = (portable.nextDouble()); endCrop = (portable.nextDouble()); futureDepositoryConstrain = (portable.nextInt()); } catch (Exception abe) { out.println( "ERROR: There are not enough values or the values passed are in the incorrect format"); out.println( " Values should be in the form mean (double) rng (double) storageLimit (int)"); return; } Pretense mie = new Pretense(10000000, willHateful, endCrop); Depository.layEntrepotRestrain(futureDepositoryConstrain); mie.jump(); } } public fabricator.Promoter righ = null; public java.lang.String q = ""; public fabricator.Promoter r = null; }
30.222222
99
0.641544
e58f046f35ac710e6ff9bb636eb916030d137525
1,263
package com.igormascarenhas.amivulnerable.device; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.AllArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(path = "/api") @Api(value = "REST API - DEVICE") @CrossOrigin(origins = "*") //All domains can access it @AllArgsConstructor public class DeviceController { private final DeviceService deviceService; @GetMapping("/devices") @ApiOperation(value = "GET ALL DEVICES") public List<Device> getAllDevices() { return deviceService.getAllDevices(); } @GetMapping("/device") @ApiOperation(value = "GET DEVICE BY ID") public Device getDevice() { return deviceService.getDevice(); } @PostMapping("/device") @ApiOperation(value = "REGISTER A NEW DEVICE") public void registerNewDevice(@RequestBody Device device) { deviceService.addNewDevice(device); } @DeleteMapping(path = "/device/{deviceId}") @ApiOperation(value = "DELETE A DEVICE") public void deleteDevice(@PathVariable("deviceId") Long id) { deviceService.deleteDevice(id); } }
28.704545
65
0.716548
904e12ce0f17b02b396ca544034ad52f9ca83948
2,939
/* * Copyright 2013 Nicolas Morel * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.treblereel.gwt.yaml.api; import com.amihaiemil.eoyaml.YamlMapping; import org.treblereel.gwt.yaml.api.exception.YAMLDeserializationException; import org.treblereel.gwt.yaml.api.stream.YAMLReader; /** * Base class for all the deserializer. It handles null values and exceptions. The rest is delegated to implementations. * @author Nicolas Morel * @version $Id: $ */ public abstract class YAMLDeserializer<T> { /** * Deserializes a YAML input into an object. * @param yaml {@link YamlMapping} used to read the YAML input * @param key {@link String} the key * @param ctx Context for the full deserialization process * @return the deserialized object * @throws YAMLDeserializationException if an error occurs during the deserialization */ public T deserialize(YamlMapping yaml, String key, YAMLDeserializationContext ctx) throws YAMLDeserializationException { return deserialize(yaml, key, ctx, ctx.defaultParameters()); } /** * Deserializes a JSON input into an object. * @param yaml {@link YamlMapping} used to read the YAML input * @param key {@link String} the key * @param ctx Context for the full deserialization process * @param params Parameters for this deserialization * @return the deserialized object * @throws YAMLDeserializationException if an error occurs during the deserialization */ public T deserialize(YamlMapping yaml, String key, YAMLDeserializationContext ctx, YAMLDeserializerParameters params) throws YAMLDeserializationException { return doDeserialize(yaml, key, ctx, params); } /** * Deserializes a non-null JSON input into an object. * @param yaml {@link YamlMapping} used to read the YAML input * @param key {@link String} the key * @param ctx Context for the full deserialization process * @param params Parameters for this deserialization * @return the deserialized object */ public T doDeserialize(YamlMapping yaml, String key, YAMLDeserializationContext ctx, YAMLDeserializerParameters params) { throw new Error("Unsupported operation"); } public T doDeserialize(String value, YAMLDeserializationContext ctx, YAMLDeserializerParameters params) { throw new Error("Unsupported operation"); } }
40.819444
128
0.727458
121ec757ab66770c74617a4f8e2a537d1789feaa
1,913
package com.fy.sysadmin.dao; import com.fy.sysadmin.model.SysUser; import org.apache.ibatis.annotations.*; import java.util.List; @Mapper public interface UserDao { @Select("select * from sys_user t where t.username = #{username}") SysUser getUser(String username); @Select("select count(*) from sys_user t ") Long countAllUsers(); @Select("select * from sys_user t order by t.id limit #{startPosition},#{limit}") List<SysUser> getAllUsersByPage(@Param("startPosition")Integer startPosition, @Param("limit")Integer limit); @Select("select * from sys_user t where t.telephone = #{telephone}") SysUser getUserByPhone(String telephone); @Select("select * from sys_user t where t.email = #{email}") SysUser getUserByEmail(String email); @Options(useGeneratedKeys = true, keyProperty = "id") @Insert("insert into sys_user(username, password, nickname, headImgUrl, phone, telephone, email, birthday, sex, status, createTime, updateTime) values(#{username}, #{password}, #{nickname}, #{headImgUrl}, #{phone}, #{telephone}, #{email}, #{birthday}, #{sex}, #{status}, now(), now())") int save(SysUser user); @Select("select * from sys_user t where t.id = #{id}") SysUser getById(Long id); int updateUser(SysUser user); @Delete("delete from sys_user where id = #{id}") int deleteUser(Long id); @Select("select count(*) from sys_user t where t.username like '%${username}%'") Long getUserByFuzzyUserName(@Param("username") String username); @Select("select * from sys_user t where t.username like '%${username}%' limit #{startPosition},#{limit}") List<SysUser> getUserByFuzzyUserNamePage(@Param("username") String username,@Param("startPosition")Integer startPosition,@Param("limit")Integer limit); @Update("update sys_user t set t.password = #{password} where t.id = #{id}") int changePassword(@Param("id") Long id, @Param("password") String password); }
40.702128
290
0.70988
3ef94333f2034bd116128c723047cbcc55b0a62b
2,838
package io.jpotts18.android_mvp.domain; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.orhanobut.logger.AndroidLogAdapter; import com.orhanobut.logger.FormatStrategy; import com.orhanobut.logger.Logger; import com.orhanobut.logger.PrettyFormatStrategy; import butterknife.ButterKnife; import io.jpotts18.android_mvp.R; /** * Created by John on 10/17/2017. */ public class BaseActivity extends AppCompatActivity { static final String TAG = BaseActivity.class.getName(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initLogger(TAG); Logger.i("onCreate"); if (savedInstanceState != null) { } } public void initLogger(String TAG) { Logger.clearLogAdapters(); FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder() .showThreadInfo(false) // (Optional) Whether to show thread info or not. Default true .methodCount(2) // (Optional) How many method line to show. Default 2 .methodOffset(2) // (Optional) Skips some method invokes in stack trace. Default 5 .tag(TAG) // (Optional) Custom tag for each log. Default PRETTY_LOGGER .build(); Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy)); } @Override protected void onStart() { super.onStart(); } @Override protected void onDestroy() { super.onDestroy(); } @Override protected void onStop() { super.onStop(); } @Override protected void onResume() { super.onResume(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); } protected void setupToolbar(final String title) { setupToolbar(title, false); } protected Toolbar getToolbar() { return (Toolbar) findViewById(R.id.main_toolbar); } protected void setupToolbar(final String title, final boolean enableUpNavigation) { final Toolbar toolbar = getToolbar(); if (toolbar == null) { return; } toolbar.setTitleTextAppearance(this, R.style.AppTheme); toolbar.setTitle(title); setSupportActionBar(toolbar); if (enableUpNavigation) { toolbar.setNavigationIcon(R.drawable.ic_action_name); } } @Override public void setContentView(int layoutResID) { super.setContentView(layoutResID); ButterKnife.setDebug(true); ButterKnife.bind(this); } }
27.553398
105
0.659972
2ab4a941a2e56cd2e98af9be49c8f0d85575d62b
486
package com.fandou.learning.netty.core.chapter5.rpc.consumer; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class RpcConsumerTest { @Test void sayHello() { RpcConsumer consumer = new RpcConsumer(); consumer.sayHello(); } @Test void calc() { RpcConsumer consumer = new RpcConsumer(); int result = consumer.calc("(12/4) + (8/2 * (20 - 5)) + (2 + 2)"); assertEquals(67,result); } }
23.142857
74
0.619342
86b2e86aa71a7dcd46625ba25e12cfc369e353a9
5,099
/***************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. ****************************************************************/ package org.apache.cayenne.access.util; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.cayenne.CayenneException; import org.apache.cayenne.access.OperationObserver; import org.apache.cayenne.access.ResultIterator; import org.apache.cayenne.query.Query; import org.apache.cayenne.util.Util; /** * Simple implementation of OperationObserver interface. Useful as a superclass of other * implementations of OperationObserver. This implementation only tracks transaction * events and exceptions. * <p> * <i>This operation observer is unsafe to use in application, since it doesn't rethrow * the exceptions immediately, and may cause the database to hang.</i> * </p> * */ public class DefaultOperationObserver implements OperationObserver { protected List<Throwable> globalExceptions = new ArrayList<Throwable>(); protected Map<Query, Throwable> queryExceptions = new HashMap<Query, Throwable>(); /** * Prints the information about query and global exceptions. */ public void printExceptions(PrintWriter out) { if (globalExceptions.size() > 0) { if (globalExceptions.size() == 1) { out.println("Global Exception:"); } else { out.println("Global Exceptions:"); } for (final Throwable th : globalExceptions) { th.printStackTrace(out); } } if (queryExceptions.size() > 0) { if (queryExceptions.size() == 1) { out.println("Query Exception:"); } else { out.println("Query Exceptions:"); } for (final Query query : queryExceptions.keySet()) { Throwable th = queryExceptions.get(query); th.printStackTrace(out); } } } /** Returns a list of global exceptions that occured during data operation run. */ public List<Throwable> getGlobalExceptions() { return globalExceptions; } /** Returns a list of exceptions that occured during data operation run by query. */ public Map<Query, Throwable> getQueryExceptions() { return queryExceptions; } /** * Returns <code>true</code> if at least one exception was registered during query * execution. */ public boolean hasExceptions() { return globalExceptions.size() > 0 || queryExceptions.size() > 0; } public void nextCount(Query query, int resultCount) { } public void nextBatchCount(Query query, int[] resultCount) { } public void nextRows(Query query, List<?> dataRows) { // noop } /** * Closes ResultIterator without reading its data. If you implement a custom subclass, * only call super if closing the iterator is what you need. */ public void nextRows(Query query, ResultIterator it) { if (it != null) { try { it.close(); } catch (CayenneException ex) { // don't throw here.... nextQueryException(query, ex); } } } /** * Closes ResultIterator without reading its data. If you implement a custom subclass, * only call super if closing the iterator is what you need. * * @since 3.0 */ public void nextGeneratedRows(Query query, ResultIterator keysIterator) { if (keysIterator != null) { try { keysIterator.close(); } catch (CayenneException ex) { // don't throw here.... nextQueryException(query, ex); } } } public void nextQueryException(Query query, Exception ex) { queryExceptions.put(query, Util.unwindException(ex)); } public void nextGlobalException(Exception ex) { globalExceptions.add(Util.unwindException(ex)); } /** * Returns <code>false</code>. */ public boolean isIteratedResult() { return false; } }
32.069182
90
0.612865
2bc6bbf608ad5d3f94ab21532b4e178047580c41
11,216
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.appservice.samples; import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appservice.models.PricingTier; import com.azure.resourcemanager.appservice.models.WebApp; import com.azure.resourcemanager.authorization.models.ServicePrincipal; import com.azure.resourcemanager.containerregistry.models.AccessKeyType; import com.azure.resourcemanager.containerregistry.models.Registry; import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; import com.azure.resourcemanager.cosmos.models.CosmosDBAccount; import com.azure.resourcemanager.keyvault.models.SecretPermissions; import com.azure.resourcemanager.keyvault.models.Vault; import com.azure.resourcemanager.samples.DockerUtils; import com.azure.resourcemanager.samples.Utils; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.PullImageResultCallback; import com.github.dockerjava.api.model.AuthConfig; import com.github.dockerjava.core.command.PushImageResultCallback; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; /** * Azure App Service basic sample for managing web apps. * - Create a Cosmos DB with credentials stored in a Key Vault * - Create a web app which interacts with the Cosmos DB by first * reading the secrets from the Key Vault. * * The source code of the web app is located at * https://github.com/Microsoft/todo-app-java-on-azure/tree/keyvault-secrets */ public final class ManageLinuxWebAppCosmosDbByMsi { /** * Main function which runs the actual sample. * @param azure instance of the azure client * @param clientId the client ID * @return true if sample runs successfully */ public static boolean runSample(AzureResourceManager azure, String clientId) throws IOException, InterruptedException { // New resources final Region region = Region.US_WEST; final String acrName = Utils.randomResourceName(azure, "acr", 20); final String appName = Utils.randomResourceName(azure, "webapp1-", 20); final String password = Utils.password(); final String rgName = Utils.randomResourceName(azure, "rg1NEMV_", 24); final String vaultName = Utils.randomResourceName(azure, "vault", 20); final String cosmosName = Utils.randomResourceName(azure, "cosmosdb", 20); String servicePrincipalClientId = clientId; // replace with a real service principal client id try { //============================================================ // Create a CosmosDB System.out.println("Creating a CosmosDB..."); CosmosDBAccount cosmosDBAccount = azure.cosmosDBAccounts().define(cosmosName) .withRegion(region) .withNewResourceGroup(rgName) .withDataModelSql() .withStrongConsistency() .create(); System.out.println("Created CosmosDB"); Utils.print(cosmosDBAccount); //============================================================ // Create a service principal ServicePrincipal servicePrincipal = azure.accessManagement().servicePrincipals() .define(appName) .withNewApplication() .definePasswordCredential("password") .attach() .create(); //============================================================= // If service principal client id and secret are not set via the local variables, attempt to read the service // principal client id and secret from a secondary ".azureauth" file set through an environment variable. // // If the environment variable was not set then reuse the main service principal set for running this sample. if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty()) { servicePrincipalClientId = System.getenv("AZURE_CLIENT_ID"); if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty()) { String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2"); if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty() || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION"); } servicePrincipalClientId = Utils.getSecondaryServicePrincipalClientID(envSecondaryServicePrincipal); } } //============================================================ // Create a key vault Vault vault = azure.vaults() .define(vaultName) .withRegion(region) .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(servicePrincipalClientId) .allowSecretAllPermissions() .attach() .defineAccessPolicy() .forServicePrincipal(servicePrincipal) .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) .attach() .create(); // SdkContext.sleep(10000); //============================================================ // Store Cosmos DB credentials in Key Vault vault.secrets().define("azure-documentdb-uri") .withValue(cosmosDBAccount.documentEndpoint()) .create(); vault.secrets().define("azure-documentdb-key") .withValue(cosmosDBAccount.listKeys().primaryMasterKey()) .create(); vault.secrets().define("azure-documentdb-database") .withValue("tododb") .create(); //============================================================= // Create an Azure Container Registry to store and manage private Docker container images System.out.println("Creating an Azure Container Registry"); long t1 = System.currentTimeMillis(); Registry azureRegistry = azure.containerRegistries().define(acrName) .withRegion(region) .withNewResourceGroup(rgName) .withBasicSku() .withRegistryNameAsAdminUser() .create(); long t2 = System.currentTimeMillis(); System.out.println("Created Azure Container Registry: (took " + ((t2 - t1) / 1000) + " seconds) " + azureRegistry.id()); Utils.print(azureRegistry); //============================================================= // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry RegistryCredentials acrCredentials = azureRegistry.getCredentials(); DockerClient dockerClient = DockerUtils.createDockerClient(azure, rgName, region, azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); String imageName = "tomcat:7.0-slim"; String privateRepoUrl = azureRegistry.loginServerUrl() + "/todoapp"; dockerClient.pullImageCmd(imageName) .withAuthConfig(new AuthConfig()) // anonymous .exec(new PullImageResultCallback()) .awaitCompletion(); String imageId = dockerClient.inspectImageCmd(imageName).exec().getId(); dockerClient.tagImageCmd(imageId, privateRepoUrl, "latest").exec(); dockerClient.pushImageCmd(privateRepoUrl) .exec(new PushImageResultCallback()).awaitCompletion(); //============================================================ // Create a web app with a new app service plan System.out.println("Creating web app " + appName + " in resource group " + rgName + "..."); WebApp app1 = azure.webApps() .define(appName) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName) .withNewLinuxPlan(PricingTier.STANDARD_S1) .withPrivateRegistryImage(privateRepoUrl, azureRegistry.loginServerUrl()) .withCredentials(acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) .withAppSetting("AZURE_KEYVAULT_URI", vault.vaultUri()) .withAppSetting("AZURE_KEYVAULT_CLIENT_ID", servicePrincipal.applicationId()) .withAppSetting("AZURE_KEYVAULT_CLIENT_KEY", password) .create(); System.out.println("Created web app " + app1.name()); Utils.print(app1); return true; } finally { try { System.out.println("Deleting Resource Group: " + rgName); azure.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } } /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { //============================================================= // Authenticate final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) .build(); AzureResourceManager azureResourceManager = AzureResourceManager .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); // Print selected subscription System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); runSample(azureResourceManager, ""); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
46.539419
164
0.595043
487348b031be0ad7d31267e4bf58e1589cb10d78
365
package husacct.control.task.resources; import java.util.HashMap; import org.jdom2.Document; public interface IResource { public Document load(HashMap<String, Object> dataValues); public boolean save(Document doc, HashMap<String, Object> dataValues,HashMap<String, Object> config); public boolean save(Document doc, HashMap<String, Object> dataValues); }
24.333333
102
0.786301
e39d9f11ccc612ebb7b13f69b4a645d8277dd870
1,228
package com.github.zzt93.syncer.health.export; import com.github.zzt93.syncer.config.common.HttpConnection; import com.github.zzt93.syncer.consumer.output.channel.http.HttpClientInitializer; import com.github.zzt93.syncer.consumer.output.channel.http.NettyHttpClient; import io.netty.handler.codec.http.HttpMethod; import org.junit.Before; import org.junit.Test; import java.net.UnknownHostException; public class ExportServerTest { private static final int PORT = 50000; private Thread thread; @Before public void setUp() throws Exception { thread = new Thread(() -> { try { ExportServer.init(new String[]{"--port=" + PORT}); } catch (Exception e) { e.printStackTrace(); } }); thread.start(); Thread.sleep(2000); } @Test public void init() throws UnknownHostException, InterruptedException { HttpConnection connection = new HttpConnection(); connection.setAddress("localhost"); connection.setPort(PORT); connection.setPath(ExportServer.HEALTH); NettyHttpClient nettyClient = new NettyHttpClient(connection, new HttpClientInitializer()); nettyClient.write(HttpMethod.GET, ExportServer.HEALTH, ""); System.out.println(); } }
27.288889
95
0.724756
f6fbfa1d8989a3f79ced6e43a1546435f9ec9ce8
718
package com.tjh.swivel.model.matchers; import org.apache.http.client.methods.HttpUriRequest; import org.junit.Test; import java.net.URI; import static com.tjh.swivel.model.matchers.RequestedURIPathMatcher.hasURIPath; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class RequestedURIPathMatcherTest { @Test public void matchesExpectedPath() { HttpUriRequest mockRequest = mock(HttpUriRequest.class); when(mockRequest.getURI()).thenReturn(URI.create("http://someServer/some/path")); assertThat(mockRequest, hasURIPath(equalTo("/some/path"))); } }
31.217391
89
0.770195
34423b95a10e980db900d1787f134bccb0fcc47b
1,145
package com.sixrr.inspectjs.ui; import com.intellij.openapi.ui.Messages; import com.sixrr.inspectjs.InspectionJSBundle; import javax.swing.*; import java.text.ParseException; public class RegExInputVerifier extends InputVerifier { @Override public boolean verify(JComponent input) { return true; } @Override public boolean shouldYieldFocus(JComponent input) { if (input instanceof JFormattedTextField) { final JFormattedTextField ftf = (JFormattedTextField) input; final JFormattedTextField.AbstractFormatter formatter = ftf.getFormatter(); if (formatter != null) { try { formatter.stringToValue(ftf.getText()); } catch (final ParseException e) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Messages.showErrorDialog(e.getMessage(), InspectionJSBundle.message("malformed.naming.pattern.alert")); } }); } } } return true; } }
32.714286
131
0.59214
8038ab47174433b7685559337deec3b5a2cd3086
4,159
package com.chikeandroid.debtmanager.features.iowe; import com.google.common.collect.Lists; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import com.chikeandroid.debtmanager.data.Debt; import com.chikeandroid.debtmanager.data.Person; import com.chikeandroid.debtmanager.data.PersonDebt; import com.chikeandroid.debtmanager.data.source.PersonDebtsRepository; import com.chikeandroid.debtmanager.features.iowe.loader.IOweLoader; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import java.util.UUID; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Created by Chike on 5/6/2017. * Unit tests for the implementation of {@link IOwePresenter */ public class IOwePresenterTest { private List<PersonDebt> mPersonDebts; @Mock private IOweContract.View mIOweView; @Captor private ArgumentCaptor<List> mShowDebtsArgumentCaptor; @Mock private IOweLoader mIOweLoader; @Mock private LoaderManager mLoaderManager; @Mock private PersonDebtsRepository mRepository; private IOwePresenter mIOwePresenter; @Before public void setUpOweMeDebtsPresenter() { MockitoAnnotations.initMocks(this); mIOwePresenter = new IOwePresenter(mIOweView, mRepository, mLoaderManager, mIOweLoader); Person person1 = new Person("Chike Mgbemena", "07038111534", "image_uri"); Debt debt1 = new Debt.Builder(UUID.randomUUID().toString(), person1.getPhoneNumber(), 5000.87, System.currentTimeMillis(), Debt.DEBT_TYPE_IOWE, Debt.DEBT_STATUS_PARTIAL) .dueDate(System.currentTimeMillis()) .note("school fees") .build(); PersonDebt personDebt1 = new PersonDebt(person1, debt1); Person person2 = new Person("Chinedu Mandu", "08047541254", "image_uri"); Debt debt2 = new Debt.Builder(UUID.randomUUID().toString(), person2.getPhoneNumber(), 87000.00, System.currentTimeMillis(), Debt.DEBT_TYPE_IOWE, Debt.DEBT_STATUS_PARTIAL) .dueDate(System.currentTimeMillis()) .note("note 2") .build(); PersonDebt personDebt2 = new PersonDebt(person2, debt2); Person person3 = new Person("Mary Jane", "040125789653", "image_uri"); Debt debt3 = new Debt.Builder(UUID.randomUUID().toString(), person3.getPhoneNumber(), 443420044.23, System.currentTimeMillis(), Debt.DEBT_TYPE_IOWE, Debt.DEBT_STATUS_PARTIAL) .dueDate(System.currentTimeMillis()) .note("note 3") .build(); PersonDebt personDebt3 = new PersonDebt(person3, debt3); mPersonDebts = Lists.newArrayList(personDebt1, personDebt2, personDebt3); } @Test public void shouldBeAbleToLoadAllIOweDebtsFromRepositoryAndLoadIntoView() { mIOwePresenter.onLoadFinished(mock(Loader.class), mPersonDebts); verify(mIOweView).showDebts(mShowDebtsArgumentCaptor.capture()); assertThat(mShowDebtsArgumentCaptor.getValue().size(), is(3)); } @Test public void shouldBeAbleToLoadAllIOweDebtsFromRepositoryAndShowEmptyViewIfNotAvailable() { mIOwePresenter.onLoadFinished(mock(Loader.class), new ArrayList<PersonDebt>()); verify(mIOweView).showEmptyView(); } @Test public void shouldBeAbleToShowErrorWhenIOweDebtsIsUnavailable() { mIOwePresenter.onLoadFinished(mock(Loader.class), null); verify(mIOweView).showLoadingDebtsError(); } @Test public void shouldBeAbleToDeleteIOweDebts() { mIOwePresenter.batchDeletePersonDebts(mPersonDebts, Debt.DEBT_TYPE_IOWE); verify(mRepository).batchDelete(eq(mPersonDebts), eq(Debt.DEBT_TYPE_IOWE)); } }
33.007937
107
0.705458
e44e4e2a8e0f64e3077b842d23a0e2d9568e553f
40,258
/* * Copyright (C) 2015 "IMIS-Athena R.C.", * Institute for the Management of Information Systems, part of the "Athena" * Research and Innovation Centre in Information, Communication and Knowledge Technologies. * [http://www.imis.athena-innovation.gr/] * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License */ package data; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.TableModel; import dictionary.DictionaryString; import hierarchy.Hierarchy; import hierarchy.ranges.RangeDouble; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Hashtable; import java.util.LinkedHashMap; import javax.persistence.Column; import jsoninterface.View; import java.util.Date; /** * A class managing text data * @author serafeim */ public class TXTData implements Data{ @JsonView(View.GetColumnNames.class) private String inputFile = null; private double dataSet[][] = null; private int sizeOfRows = 0; private int sizeOfCol = 0; private String delimeter = null; @JsonView(View.GetDataTypes.class) private Map <Integer,String> colNamesType = null; private CheckVariables chVar = null; private Map <Integer,String> colNamesPosition = null; private Map <Integer,DictionaryString> dictionary = null; @JsonView(View.SmallDataSet.class) private String[][] smallDataSet; @JsonView(View.DataSet.class) private ArrayList<LinkedHashMap> data; @JsonView(View.SmallDataSet.class) private String[][] typeArr; @JsonView(View.GetColumnNames.class) private String []columnNames = null; @JsonView(View.DataSet.class) private int recordsTotal; @JsonView(View.DataSet.class) private int recordsFiltered; @JsonView(View.SmallDataSet.class) private String errorMessage = null; private static final String[] formats = { "yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd HH:mm:ss", "MM/dd/yyyy HH:mm:ss", "MM/dd/yyyy'T'HH:mm:ss.SSS'Z'", "MM/dd/yyyy'T'HH:mm:ss.SSSZ", "MM/dd/yyyy'T'HH:mm:ss.SSS", "MM/dd/yyyy'T'HH:mm:ssZ", "MM/dd/yyyy'T'HH:mm:ss", "yyyy:MM:dd HH:mm:ss", "yyyy/MM/dd", "yyyy:MM:dd HH:mm:ss.SS", "dd/MM/yyyy", "dd MMM yyyy"}; public TXTData(String inputFile, String del){ recordsTotal = 0; this.smallDataSet = null; colNamesType = new TreeMap<Integer,String>(); colNamesPosition = new HashMap<Integer,String>(); chVar = new CheckVariables(); dictionary = new HashMap <Integer,DictionaryString>(); this.inputFile = inputFile; if ( del == null ){ delimeter = ","; } else{ delimeter = del; } } public double[][] getDataSet() { return dataSet; } public String getInputFile() { String delimiter = "/"; String[] temp = inputFile.split(delimiter,-1); return temp[temp.length-1]; } /** * Gets the array of the loaded dataset * @return 2-dimensional array of the loaded dataset */ /*@Override public double[][] getData() { return data; }*/ public Map<Integer, String> getColNamesType() { return colNamesType; } @Override public void setData(double[][] _dataSet) { this.dataSet = _dataSet; } /** * Gets the length of the dataset array * @return length of the dataset */ @JsonIgnore @Override public int getDataLenght() { return dataSet.length; } /** * Prints the dataset */ @Override public void print(){ int i,j; for (i = 0 ; i < dataSet.length ; i ++){ for (j = 0 ; j < dataSet[i].length ; j++){ System.out.print(dataSet[i][j]+","); } System.out.println(); } } /** * Executes a preprocessing of the dataset */ @Override public void preprocessing() { FileInputStream fstream = null; DataInputStream in = null; BufferedReader br = null; String strLine = null; String []temp = null; int i = 0; int counter = -1; try { fstream = new FileInputStream(inputFile); in = new DataInputStream(fstream); br = new BufferedReader(new InputStreamReader(in)); //counts lines of the dataset while ((strLine = br.readLine()) != null) { counter++; } //System.out.println("counter = " + counter); sizeOfRows = counter; in.close(); }catch (Exception e){ System.err.println("Error: " + e.getMessage()); } } /** * Loads dataset from file to memory */ @Override public String save(boolean[] checkColumns) { FileInputStream fstream = null; DataInputStream in = null; BufferedReader br = null; String strLine = null; String []temp = null; String []colNames = null; ArrayList<String> columns = new ArrayList<String>(); int counter = 0; int stringCount = 0; boolean FLAG = true; int counter1 = 0 ; try { fstream = new FileInputStream(inputFile); in = new DataInputStream(fstream); br = new BufferedReader(new InputStreamReader(in)); while ((strLine = br.readLine()) != null){ //do not read the fist line if (FLAG == true){ temp = strLine.split(delimeter,-1); for ( int i = 0 ; i < temp.length ; i ++){ if (checkColumns[i] == true){ columns.add(temp[i]); } } colNames = new String[columns.size()]; colNames = columns.toArray(new String[0]); this.setColumnNames(colNames); FLAG = false; dataSet = new double[sizeOfRows][columnNames.length]; } else{ temp = strLine.split(delimeter,-1); counter1 = 0; for (int i = 0; i < temp.length ; i ++ ){ if (checkColumns[i] == true){ if ( temp[i].equals("")){ } if ( colNamesType.get(counter1).contains("int") ){ if ( !temp[i].equals("")){ try { dataSet[counter][counter1] = Integer.parseInt(temp[i]); } catch (java.lang.NumberFormatException exc) { //ErrorWindow.showErrorWindow("Column : " + colNames[i] + " is chosen as integer and you have double values"); System.out.println("Column : " + colNames[i] + " is chosen as integer and you have double values"); return null; } } else{ dataSet[counter][counter1] = 2147483646; } } else if (colNamesType.get(counter1).contains("double")){ if ( !temp[i].equals("")){ dataSet[counter][counter1] = Double.parseDouble(temp[i]); } else{ dataSet[counter][counter1] = Double.NaN; } } else if (colNamesType.get(counter1).contains("date")){ DictionaryString tempDict = dictionary.get(counter1); String var = null; if ( !temp[i].equals("")){ var = temp[i]; var = this.timestampToDate(var); } else { var = "NaN"; } //transform timestamp to date //var = this.timestampToDate(var); if (var != null) { //if string is not present in the dictionary if (tempDict.containsString(var) == false){ tempDict.putIdToString(stringCount, var); tempDict.putStringToId(var,stringCount); dictionary.put(counter1, tempDict); dataSet[counter][counter1] = stringCount; stringCount++; } else{ //if string is present in the dictionary, get its id int stringId = tempDict.getStringToId(var); dataSet[counter][counter1] = stringId; } } } else{ DictionaryString tempDict = dictionary.get(counter1); String var = null; if ( !temp[i].equals("")){ var = temp[i]; } else { var = "NaN"; } //if string is not present in the dictionary if (tempDict.containsString(var) == false){ tempDict.putIdToString(stringCount, var); tempDict.putStringToId(var,stringCount); dictionary.put(counter1, tempDict); dataSet[counter][counter1] = stringCount; stringCount++; } else{ //if string is present in the dictionary, get its id int stringId = tempDict.getStringToId(var); dataSet[counter][counter1] = stringId; } } counter1++; } } counter++; } } in.close(); System.out.println("size row = " + dataSet.length + "\tsize column = " + dataSet[0].length); /*for ( int i = 0; i < dataSet.length ; i ++){ for ( int j=0; j < dataSet[i].length ; j ++ ){ System.out.print("data = " + dataSet[i][j]); } System.out.println(); }*/ }catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); return null; } return "OK"; } /** * Reads dataset from file (preprocessing and load) */ @Override public String readDataset(String[] columnTypes, boolean[] checkColumns) { SaveClmnsAndTypeOfVar(columnTypes,checkColumns); preprocessing(); String result = save(checkColumns); return result; } /** * Gets dictionary for the specified column * @param column the number of the column * @return the dictionary for the column */ @Override public DictionaryString getDictionary(Integer column){ return this.dictionary.get(column); } /** * Gets column names * @return a map with the column names by position */ @Override public Map<Integer, String> getColNamesPosition() { return colNamesPosition; } /** * Gets all dictionaries * @return a map with with the column dictionaries by position */ @Override public Map<Integer, DictionaryString> getDictionary() { return dictionary; } /** * Finds the column number of the column name specified * @param column the column name to search for * @return the column number of the given column */ @Override @JsonIgnore public int getColumnByName(String column){ for(Integer i : this.colNamesPosition.keySet()){ if(this.colNamesPosition.get(i).equals(column)){ return i; } } return -1; } /** * Sets a new dictionary for a specific column * @param column the column number * @param dict the new dictionary */ @Override public void setDictionary(Integer column, DictionaryString dict) { this.dictionary.put(column, dict); } /** * Replaces the dictionary of a column with a new one. Updates values in this * column with those taken from the new dictionary * @param column the column number * @param dict the new dictionary */ @Override public void replaceColumnDictionary(Integer column, DictionaryString dict) { DictionaryString curDict = this.dictionary.get(column); for (double[] row : dataSet) { //retrieve actual value from dictionary String columnValue = curDict.getIdToString((int)row[column]); //replace with value from new dictionary row[column] = dict.getStringToId(columnValue); } //set given dictionary as the new one setDictionary(column, dict); } @Override public void export(String file, Object [][] initialTable, Object[][] anonymizedTable, int[] qids, Map<Integer, Hierarchy> hierarchies, Map<Integer, Set<String>> suppressedValues) { System.out.println("Export in data..."); Object[][] temp = null; if ( initialTable != null ){ System.out.println("initial table"); temp = initialTable; } else{ System.out.println("anonymized table"); temp = anonymizedTable; } try { try (PrintWriter writer = new PrintWriter( file, "UTF-8")) { //TableModel model = anonymizedTable.getModel(); //int columnCount = model.getColumnCount(); //int rowCount = model.getRowCount(); //write column names /*for(int column = 0; column < temp[0].length; column++){ //if column contains ranges, split it in min/max Hierarchy h = hierarchies.get(column); if(h != null && h.getHierarchyType().equals("range")){ Object[] possibleValues = { "min-max value", "average with tolerance" }; Object selectedValue = JOptionPane.showInputDialog(null, "Choose one", "Output file format", JOptionPane.INFORMATION_MESSAGE, null, possibleValues, possibleValues[0]); System.out.println("object = " + selectedValue); if ( selectedValue.equals("min-max value")){ //writer.print(model.getColumnName(column) + "_min,"); //writer.print(model.getColumnName(column) + "_max"); } else{ } } else{ writer.print(temp[column]); } if(column != temp[column].length-1){ writer.print(","); } Hierarchy h = hierarchies.get(column-1); if(h != null && h.getHierarchyType().equals("range")){ writer.print(model.getColumnName(column) + "_min,"); writer.print(model.getColumnName(column) + "_max"); } else{ writer.print(model.getColumnName(column)); } if(column != columnCount-1){ writer.print(","); } } writer.println();*/ boolean FLAG = false; for(int i = 0 ; i < temp[0].length ; i ++){ if (FLAG == false){ writer.print(columnNames[i]); FLAG = true; } else{ writer.print(","+columnNames[i]); } } writer.println(); Object[] rowQIs = null; if(suppressedValues != null){ rowQIs = new Object[qids.length]; } //write table data for (int row = 0; row < temp.length; row++){ //if suppressed values exist if(suppressedValues != null){ //get qids of this row for(int i=0; i<qids.length; i++){ rowQIs[i] = temp[row][qids[i]]; } //check if row is suppressed if(isSuppressed(rowQIs, qids, suppressedValues)){ continue; } } //write row to file for(int column = 0; column < temp[0].length; column++){ Object value = temp[row][column]; if(value instanceof RangeDouble){ if ( colNamesType.get(column-1).equals("double")){ writer.print(((RangeDouble)value).lowerBound + ","); writer.print(((RangeDouble)value).upperBound); } else{ writer.print((((RangeDouble)value).lowerBound).intValue() + ","); writer.print((((RangeDouble)value).upperBound).intValue()); } } else{ if (!value.equals("(null)")){ writer.print(value); } } if(column != temp[column].length-1){ writer.print(","); } } writer.println(); } } } catch (FileNotFoundException | UnsupportedEncodingException ex) { //Logger.getLogger(AnonymizedDatasetPanel.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("done"); } private boolean isSuppressed(Object[] data, int[] qids, Map<Integer, Set<String>> suppressedValues){ if (suppressedValues == null) return false; Object[] checkArr = new Object[1]; //check for each and every qid if is suppressed for(int i=0; i<qids.length; i++){ Set<String> suppressed = suppressedValues.get(qids[i]); if(suppressed != null){ checkArr[0] = data[i]; if(suppressed.contains(java.util.Arrays.toString(checkArr))) return true; } } //check for all qids combined Set<String> suppressed = suppressedValues.get(-1); if(suppressed != null){ if(suppressed.contains(java.util.Arrays.toString(data))){ return true; } } return false; } @Override @JsonIgnore public String getColumnByPosition(Integer columnIndex) { return this.colNamesPosition.get(columnIndex); } @Override public void SaveClmnsAndTypeOfVar(String[] columnTypes, boolean[] checkColumns) { FileInputStream fstream = null; DataInputStream in = null; BufferedReader br = null; String strLine = null; String []temp = null; String []colNames = null; boolean FLAG = true; try { fstream = new FileInputStream(inputFile); in = new DataInputStream(fstream); br = new BufferedReader(new InputStreamReader(in)); int counter = 0 ; while ((strLine = br.readLine()) != null) { //save column names if (FLAG == true){ colNames = strLine.split(delimeter,-1); for ( int i = 0 ; i < colNames.length ; i ++){ if ( checkColumns[i] == true){ colNamesType.put(counter,null); colNamesPosition.put(counter,colNames[i]); counter++; } } FLAG = false; } } counter = 0 ; //save column types for ( int i = 0 ; i < columnTypes.length ; i ++ ){ //System.out.println("columnnnnnnnnnnnnnn = " + colNamesType.size()); if ( checkColumns[i] == true){ if (columnTypes[i].equals("int")){ colNamesType.put(counter, "int"); } else if (columnTypes[i].equals("double")){ colNamesType.put(counter, "double"); } else if (columnTypes[i].equals("date")){ colNamesType.put(counter, "date"); dictionary.put(counter, new DictionaryString()); } else{ colNamesType.put(counter, "string"); dictionary.put(counter, new DictionaryString()); } counter++; } } sizeOfCol = columnTypes.length; in.close(); }catch (Exception e){ System.err.println("Error: " + e.getMessage()); } } @JsonView(View.SmallDataSet.class) @Override public String findColumnTypes() { FileInputStream fstream = null; DataInputStream in = null; BufferedReader br = null; String strLine = null; String []temp = null; boolean FLAG = true; boolean FLAG2 = true; int counter = 0; try { fstream = new FileInputStream(inputFile); in = new DataInputStream(fstream); br = new BufferedReader(new InputStreamReader(in)); while ((strLine = br.readLine()) != null) { //escape first row if (FLAG == true){ temp = strLine.split(delimeter,-1); columnNames = new String[temp.length]; smallDataSet = new String[6][temp.length]; for ( int i = 0 ; i < temp.length ; i ++){ columnNames[i] = temp[i]; } FLAG = false; } //save column types else{ temp = strLine.split(delimeter,-1); //System.out.println("strLine = " + strLine); /*for ( int i = 0 ; i < temp.length ; i ++){ System.out.println("tempp =" + temp[i]); }*/ //System.out.println("temp len = " + temp.length + " \tcolumnNames len =" + columnNames.length); if( temp.length != columnNames.length){ System.out.println("columnNames = " + columnNames.length +"\t temp = " + temp.length ); //ErrorWindow.showErrorWindow("Parse problem.Different size between title row and data row"); this.errorMessage = "1";//"Parse problem.Different size between title row and data row" System.out.println("Parse problem.Different size between title row and data row"); return errorMessage; } if (FLAG2 == true){ for ( int i = 0 ; i < temp.length ; i ++ ){ counter = 0; if ( !temp[i].equals("")){ if (chVar.isInt(temp[i])){ smallDataSet[counter][i] = "int"; } else if (chVar.isDouble(temp[i])){ smallDataSet[counter][i] = "double"; } else if(chVar.isDate(temp[i])){ smallDataSet[counter][i] = "date"; } else{ smallDataSet[counter][i] = "string"; } } smallDataSet[++counter][i] = temp[i]; } FLAG2 = false; } //check for the next 6 records for the types else if ( counter < 6 ){ for ( int i = 0 ; i < temp.length ; i ++ ){ smallDataSet[counter][i] = temp[i]; if ( !temp[i].equals("")){ if ( smallDataSet[0][i] != null ){ if (smallDataSet[0][i].equals("int")){ if (!chVar.isInt(temp[i])){ if (chVar.isDouble(temp[i])){ smallDataSet[0][i] = "double"; } else { smallDataSet[0][i] = "string"; } } } else if(smallDataSet[0][i].equals("double")){ if (!chVar.isInt(temp[i]) && !chVar.isDouble(temp[i])){ smallDataSet[0][i] = "string"; } } } else{ if (chVar.isInt(temp[i])){ smallDataSet[0][i] = "int"; } else if (chVar.isDouble(temp[i])){ smallDataSet[0][i] = "double"; } else if(chVar.isDate(temp[i])){ smallDataSet[0][i] ="date"; } else{ smallDataSet[0][i] = "string"; } } } } counter ++; } //if record has no type, then put string else{ for (int i = 0 ; i < smallDataSet[0].length ; i ++ ){ if ( smallDataSet[0][i] == null){ smallDataSet[0][i]= "string"; } } break; } } } in.close(); }catch (Exception e){ System.err.println("Error: " + e.getMessage()); } return "Ok"; } @Override public String[][] getSmallDataSet() { return smallDataSet; } @Override public ArrayList<LinkedHashMap> getPage(int start,int length){ data = new ArrayList<LinkedHashMap>(); int counter = 0 ; LinkedHashMap linkedHashTemp = null; int max; if ( start + length <= sizeOfRows ){ max = start + length; } else{ max = sizeOfRows; } /*for ( int i = 0 ; i < dataSet.length ; i ++){ for ( int j = 0 ; j < dataSet[i].length ; j ++){ System.out.print(dataSet[i][j] +"," ); } System.out.println(); } System.out.println("Dictionary"); Dictionary d; for (Map.Entry<Integer,Dictionary> entry : dictionary.entrySet()) { System.out.println(entry.getKey()+" : "+entry.getValue()); d = entry.getValue(); System.out.println("\\\\\\"); for (Map.Entry<Integer,String> entry1 : d.getIdToString().entrySet()) { System.out.println(entry1.getKey()+" : "+entry1.getValue()); } System.out.println("End"); }*/ for ( int i = start ; i < max ; i ++){ linkedHashTemp = new LinkedHashMap<>(); for (int j = 0 ; j < colNamesType.size() ; j ++){ //System.out.println("data = " + dataSet[i][j]); if (colNamesType.get(j).equals("double")){ if (Double.isNaN(dataSet[i][j])){ linkedHashTemp.put(columnNames[j],""); } else{ Object a = dataSet[i][j]; linkedHashTemp.put(columnNames[j], dataSet[i][j]); } } else if (colNamesType.get(j).equals("int")){ if (dataSet[i][j] == 2147483646.0){ linkedHashTemp.put(columnNames[j],""); } else{ linkedHashTemp.put(columnNames[j], Integer.toString((int)dataSet[i][j])+""); } } else{ DictionaryString dict = dictionary.get(j); String str = dict.getIdToString((int)dataSet[i][j]); if (str.equals("NaN")){ linkedHashTemp.put(columnNames[j],""); } else{ linkedHashTemp.put(columnNames[j], str); } } } data.add(linkedHashTemp); counter ++; } recordsTotal = sizeOfRows; recordsFiltered = sizeOfRows; return data; } @JsonView(View.SmallDataSet.class) @Override public String[][] getTypesOfVariables(String [][]smallDataSet) { this.smallDataSet = smallDataSet; String []str = null; String []columnTypes = null; typeArr = new String[smallDataSet[0].length][]; for ( int i = 0 ; i < 1 ; i ++){ columnTypes = new String[smallDataSet[i].length]; for ( int j = 0 ; j < smallDataSet[i].length ; j ++ ){ if ( smallDataSet[i][j] != null ){ if (smallDataSet[i][j].equals("string")){ str = new String[1]; str[0] = "string"; columnTypes[j] = "string"; } else if (smallDataSet[i][j].equals("int")){ str = new String[3]; str[0] = "int"; str[1] = "string"; str[2] = "double"; columnTypes[j] = "int"; } else if (smallDataSet[i][j].equals("date")){ str = new String[2]; str[0] = "date"; str[1] = "string"; columnTypes[j] = "date"; } else { str = new String[2]; str[0] = "double"; str[1] = "string"; columnTypes[j] = "double"; } } else{ str = new String[4]; str[0] = "string"; str[1] = "int"; str[2] = "double"; str[3] = "date"; columnTypes[j] = "string"; } typeArr[j] = str; } } return typeArr; } public String[][] getTypeArr() { return typeArr; } public String[] getColumnNames() { return columnNames; } public void setColumnNames(String[] columnNames) { this.columnNames = columnNames; } public int getRecordsTotal() { return recordsTotal; } public String timestampToDate( String tmstmp){ String [] temp = null; if ( tmstmp != null ) { for (String parse : formats) { SimpleDateFormat sdf = new SimpleDateFormat(parse); //System.out.println("edwwwwwww = "); try { Date d1 = sdf.parse(tmstmp); if (sdf.parse(tmstmp) != null){ if ( parse.equals("yyyy/MM/dd")){ if ( tmstmp.contains("/")){// den mporei na dei to dd/MM/yyyy giati prwta vlepei to yyyy//MM/dd temp = tmstmp.split("/"); if (temp[0].length() <= 2){ return tmstmp; } else{ System.out.println("parse = " + parse); //System.out.println("date111111" ); SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy"); //Date date = sf.parse(tmstmp); //System.out.println("date = " + date ); System.out.println("return = " +sf.format(d1)); //System.out.println(date.); tmstmp = null; tmstmp = sf.format(d1); return tmstmp; } } } else{ System.out.println("parse = " + parse); //System.out.println("date111111" ); SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy"); //Date date = sf.parse(tmstmp); //System.out.println("date = " + date ); System.out.println("return = " +sf.format(d1)); //System.out.println(date.); tmstmp = null; tmstmp = sf.format(d1); return tmstmp; } } //System.out.println("Printing the value of " + parse); } catch (ParseException e) { } } } return null; } }
38.087039
151
0.4069
36d034333593f92e411097dbc3fe028fec4ea0a5
7,371
package lu.uni.bicslab.greenbot.android.ui.activity.itemmain; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.bumptech.glide.Glide; import java.util.List; import java.util.stream.Collectors; import lu.uni.bicslab.greenbot.android.R; import lu.uni.bicslab.greenbot.android.datamodel.IndicatorModel; import lu.uni.bicslab.greenbot.android.other.Utils; import lu.uni.bicslab.greenbot.android.ui.fragment.compare.CompareActivity; import lu.uni.bicslab.greenbot.android.datamodel.ProductModel; import lu.uni.bicslab.greenbot.android.datamodel.ProductCategoryModel; public class ProductDetailsActivity extends AppCompatActivity { String productCode; String indicatorCategoryFilter; TextView title, description, type_data, provider_data, category_data; ImageView product_image, category_icon; LinearLayout indicator_list1, indicator_list2; View indicators_section, show_more; TextView show_more_text; ImageView show_more_icon; LinearLayout similar_product_list; boolean indicatorsExpanded = false; boolean slideTransition = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_productdetails); title = findViewById(R.id.title); description = findViewById(R.id.description); type_data = findViewById(R.id.type_data); provider_data = findViewById(R.id.provider_data); category_data = findViewById(R.id.category_data); product_image = findViewById(R.id.product_image); category_icon = findViewById(R.id.category_icon); indicators_section = findViewById(R.id.indicators_section); indicator_list1 = findViewById(R.id.indicator_list1); indicator_list2 = findViewById(R.id.indicator_list2); show_more = findViewById(R.id.show_more); show_more_text = findViewById(R.id.show_more_text); show_more_icon = findViewById(R.id.show_more_icon); // Set GONE by default, make VISIBLE when at least one indicator is added show_more.setVisibility(View.GONE); show_more.setOnClickListener(v -> { indicatorsExpanded = !indicatorsExpanded; updateHiddenIndicators(); }); similar_product_list = findViewById(R.id.similar_product_list); productCode = getIntent().getExtras().getString("code"); indicatorCategoryFilter = getIntent().getExtras().getString("filter_indicator_category"); slideTransition = getIntent().getExtras().getBoolean("slide_transition", false); ProductModel product = Utils.getProductByCode(this, productCode); if (productCode == null || product == null) { Toast toast = Toast.makeText(getApplicationContext(), product == null ? R.string.product_not_found : R.string.general_error, Toast.LENGTH_SHORT); toast.show(); finish(); return; } Toolbar toolbar = findViewById(R.id.anim_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(R.string.product); setView(product); updateHiddenIndicators(); } @Override public void onBackPressed() { super.onBackPressed(); if (slideTransition) overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); menu.add(0, 0, 0, R.string.compare_button) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); if (slideTransition) overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); return true; case 0: Intent mIntent = new Intent(getApplicationContext(), CompareActivity.class); mIntent.putExtra("key_product", productCode); startActivity(mIntent); return true; } return super.onOptionsItemSelected(item); } private void updateHiddenIndicators() { if (indicatorsExpanded) { show_more_text.setText(R.string.show_less); indicator_list2.setVisibility(View.VISIBLE); show_more_icon.setRotation(90); } else { show_more_text.setText(R.string.show_more); indicator_list2.setVisibility(View.GONE); show_more_icon.setRotation(0); } } private void setView(ProductModel product) { ProductCategoryModel category = Utils.getProductCategoryByID(this, product.getCategory()); List<IndicatorModel> indicators = product.indicators.stream().filter(ind -> ind.isApplicable() && ind.sub_indicators.size() > 0).collect(Collectors.toList()); title.setText(product.getName()); description.setText(product.getDescription()); type_data.setText(product.getType()); provider_data.setText(product.getProvider()); category_data.setText(category.getName()); Glide.with(this).load(Utils.getDrawableImage(this, product.getImage_url())).error(R.drawable.ic_menu_gallery).into(product_image); Glide.with(this).load(Utils.getDrawableImage(this, category.getIcon_name())).error(R.drawable.ic_menu_gallery).into(category_icon); if (indicators.size() == 0) { indicators_section.setVisibility(View.GONE); } // Fill in indicators // If the category id matches the search filter, put in indicator_list1, else in indicator_list2 (collapsible) for (IndicatorModel ind : indicators) { View view = this.getLayoutInflater().inflate(R.layout.item_row, indicator_list1, false); ((TextView) view.findViewById(R.id.indicator_name)).setText(ind.getName()); Glide.with(this).load(Utils.getDrawableImage(this, ind.getIcon_name())).error(R.drawable.ic_menu_gallery).into((ImageView) view.findViewById(R.id.indicator_image)); if (ind.getCategory_id().equals(indicatorCategoryFilter) || indicatorCategoryFilter == null) { indicator_list1.addView(view); } else { indicator_list2.addView(view); show_more.setVisibility(View.VISIBLE); } } // Fill in similar products for (ProductModel simProduct : Utils.getProductsByType(this, product.getType())) { if (simProduct.getCode().equals(productCode)) continue; View view = this.getLayoutInflater().inflate(R.layout.item_collumn, similar_product_list, false); String catIcon = Utils.getProductCategoryByID(this, simProduct.getCategory()).getIcon_name(); ((TextView) view.findViewById(R.id.txtName)).setText(simProduct.getName()); Glide.with(this).load(Utils.getDrawableImage(this, simProduct.getImage_url())).error(R.drawable.ic_menu_gallery).into((ImageView) view.findViewById(R.id.imageview_icon)); Glide.with(this).load(Utils.getDrawableImage(this, catIcon)).error(R.drawable.ic_menu_gallery).into((ImageView) view.findViewById(R.id.imageview_origin)); view.setOnClickListener(v -> { Intent intent = new Intent(this, ProductDetailsActivity.class); intent.putExtra("code", simProduct.getCode()); intent.putExtra("filter_indicator_category", indicatorCategoryFilter); startActivity(intent); }); similar_product_list.addView(view); } } }
35.608696
173
0.763533
308b5486113fd499ec8ec545f7bbd9e5e3dd2061
3,946
package com.yuqiong.college.service.edu.controller; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest; import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse; import com.yuqiong.college.common.handler.GuliException; import com.yuqiong.college.common.utils.ConstantPropertiesUtils; import com.yuqiong.college.common.utils.InitVodCilent; import com.yuqiong.college.common.utils.ResultData; import com.yuqiong.college.service.edu.entity.Video; import com.yuqiong.college.service.edu.service.VideoService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.util.List; /** * <p> * 课程视频 前端控制器 * </p> * * @author yuqiong * @since 2021-02-13 */ @CrossOrigin @Api("课程小节") @RestController @RequestMapping("/edu/video") public class VideoController { @Autowired private VideoService videoService; @ApiOperation(value = "视频播放") @GetMapping("getPlayAuth/{id}") public ResultData getPlayAuth(@PathVariable String id) { try { //创建初始化对象 DefaultAcsClient client = InitVodCilent.initVodClient(ConstantPropertiesUtils.KEY_ID, ConstantPropertiesUtils.KEY_SECRET); //创建获取凭证request和response对象 GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest(); //向request设置视频id request.setVideoId(id); //调用方法得到凭证 GetVideoPlayAuthResponse response = client.getAcsResponse(request); String playAuth = response.getPlayAuth(); return ResultData.ok().data("playAuth", playAuth); } catch (Exception e) { throw new GuliException(20001, "获取凭证失败"); } } @ApiOperation(value = "添加小节") @PostMapping("addVideo") public ResultData addVideo(@RequestBody Video video) { boolean b = videoService.save(video); if (b == false) { return ResultData.error(); } return ResultData.ok(); } @DeleteMapping("deleterVideo/{videoId}") @ApiOperation(value = "删除小节") public ResultData deleterVideo(@PathVariable String videoId) { boolean b = videoService.removeVideoById(videoId); if (b == false) { return ResultData.error(); } return ResultData.ok(); } @PostMapping("updateVideo") @ApiOperation(value = "修改小节") public ResultData updateVideo(@RequestBody Video video) { boolean b = videoService.updateById(video); if (b == false) { return ResultData.error(); } return ResultData.ok(); } @GetMapping("getVideo/{videoId}") @ApiOperation(value = "根据id查询小节") public ResultData getVideo(@PathVariable String videoId) { Video byId = videoService.getById(videoId); return ResultData.ok().data("video", byId); } @ApiOperation(value = "上传视频") @PostMapping("uploadAlyVideo") public ResultData uploadAlyVideo(MultipartFile file) { String videoId = videoService.uploadAlyVideo(file); return ResultData.ok().data("videoId", videoId); } @DeleteMapping("deleteAliyunvod/{videoSourceId}") @ApiOperation(value = "删除视频") public ResultData deleteAliyunvod(@PathVariable String videoSourceId) { boolean b = videoService.deleteAliyunvod(videoSourceId); if (b == false) { return ResultData.error(); } return ResultData.ok(); } @ApiOperation("删除多条视频") @DeleteMapping("deleteBatch") public ResultData deleteBatch(@RequestParam("videoList") List<String> videoList) { boolean b = videoService.deleteBatch(videoList); if (b == false) { return ResultData.error(); } return ResultData.ok(); } }
32.344262
134
0.674607
8003675384ba1594067eb818398a49ffbfe32874
8,299
package org.corfudb.infrastructure; import lombok.extern.slf4j.Slf4j; import org.corfudb.runtime.CorfuRuntime; import org.corfudb.runtime.clients.BaseClient; import org.corfudb.runtime.clients.IClientRouter; import org.corfudb.runtime.exceptions.WrongEpochException; import org.corfudb.runtime.view.Layout; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Simple Polling policy. * Every node polls every other node. * <p> * Failure Condition: * Considers failure if server a node does not respond to the ping * more than 2 times in a row. * <p> * Created by zlokhandwala on 9/29/16. */ @Slf4j public class PeriodicPollPolicy implements IFailureDetectorPolicy { /** * list of layout servers that we monitor. */ private String[] historyServers = null; private IClientRouter[] historyRouters = null; /** * polling history */ private int[] historyPollFailures = null; private long[] historyPollEpochExceptions = null; private int historyPollCount = 0; private HashMap<String, Boolean> historyStatus = null; private CompletableFuture[] pollCompletableFutures = null; private final int pollTaskTimeout = 5000; /** * Failed Poll Limit. * Failed pings after which a node is considered dead. */ long failedPollLimit = 3; /** * Executes the policy once. * Checks for changes in the layout. * Then polls all the servers and updates the status. * * @param layout Current Layout */ @Override public void executePolicy(Layout layout, CorfuRuntime corfuRuntime) { String[] allServers = layout.getAllServers().stream().toArray(String[]::new); // Performs setup and checks for changes in the layout to update failure count checkForChanges(allServers, corfuRuntime); // Perform polling of all servers in historyServers pollOnce(); } /** * Checks for changes in the layout. * Fetches corfu runtime router to be able to ping a node. * * @param allServers List of all servers in teh layout * @param corfuRuntime A connected corfu runtime */ private void checkForChanges(String[] allServers, CorfuRuntime corfuRuntime) { Arrays.sort(allServers); if (historyServers == null || !Arrays.equals(historyServers, allServers)) { // Initialize the status map for the first time or if there is a change. if (historyStatus == null) { historyStatus = new HashMap<>(); } log.debug("historyServers change, length = {}", allServers.length); historyServers = allServers; historyRouters = new IClientRouter[allServers.length]; historyPollFailures = new int[allServers.length]; historyPollEpochExceptions = new long[allServers.length]; pollCompletableFutures = new CompletableFuture[allServers.length]; for (int i = 0; i < allServers.length; i++) { if (!historyStatus.containsKey(allServers[i])) { historyStatus.put(allServers[i], true); // Assume it's up until we think it isn't. } historyRouters[i] = corfuRuntime.getRouterFunction.apply(allServers[i]); historyRouters[i].start(); historyPollFailures[i] = 0; historyPollEpochExceptions[i] = -1; } historyPollCount = 0; } else { log.debug("No server list change since last poll."); } } /** * Polls all the server nodes from historyServers once. * If failure is detected it updates in the historyPollFailures. */ private void pollOnce() { // Poll servers for health. All ping activity will happen in the background. // We probably won't notice changes in this iteration; a future iteration will // eventually notice changes to historyPollFailures. for (int i = 0; i < historyRouters.length; i++) { int ii = i; // Intermediate var just for the sake of having a final for use inside the lambda below pollCompletableFutures[ii] = CompletableFuture.runAsync(() -> { try { boolean pingResult = historyRouters[ii].getClient(BaseClient.class).ping().get(); historyPollFailures[ii] = pingResult ? 0 : historyPollFailures[ii] + 1; } catch (Exception e ) { // If Wrong epoch exception is received, mark server as failed. if (e.getCause() instanceof WrongEpochException) { historyPollEpochExceptions[ii] = ((WrongEpochException) e.getCause()).getCorrectEpoch(); } log.debug("Ping failed for " + historyServers[ii] + " with " + e); historyPollFailures[ii]++; } }); } historyPollCount++; } /** * Gets the server status from the last poll. * A failure is detected after at least 2 polls. * * @return A map of failed server nodes and their status. */ @Override public PollReport getServerStatus() { Set<String> failingNodes = new HashSet<>(); HashMap<String, Long> outOfPhaseEpochNodes = new HashMap<>(); if (historyPollCount > 3) { Boolean is_up; // Simple failure detector: Is there a change in health? for (int i = 0; i < historyServers.length; i++) { // TODO: Be a bit smarter than 'more than 2 failures in a row' // Block until we complete the previous polling round. try { pollCompletableFutures[i].get(pollTaskTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { log.error("Error in polling task for server {} : {}", historyServers[i], e); pollCompletableFutures[i].cancel(true); // Assuming server is unresponsive if ping task stuck or interrupted or throws exception. historyPollFailures[i]++; } // The count remains within the interval 0 <= failureCount <= failedPollLimit(3) is_up = !(historyPollFailures[i] >= failedPollLimit); // Toggle if server was up and now not responding if (!is_up) { log.debug("Change of status: " + historyServers[i] + " " + historyStatus.get(historyServers[i]) + " -> " + is_up); failingNodes.add(historyServers[i]); historyStatus.put(historyServers[i], is_up); historyPollFailures[i]--; } else if (!historyStatus.get(historyServers[i])) { // If server was down but now responsive so wait till reaches lower watermark (0). if (historyPollFailures[i] > 0) { if (--historyPollFailures[i] == 0) { log.debug("Change of status: " + historyServers[i] + " " + historyStatus.get(historyServers[i]) + " -> " + true); historyStatus.put(historyServers[i], true); } else { // Server still down failingNodes.add(historyServers[i]); } } } if (historyPollEpochExceptions[i] != -1) { outOfPhaseEpochNodes.put(historyServers[i], historyPollEpochExceptions[i]); // Reset epoch exception value. historyPollEpochExceptions[i] = -1; } } } return new PollReport.PollReportBuilder() .setFailingNodes(failingNodes) .setOutOfPhaseEpochNodes(outOfPhaseEpochNodes) .build(); } }
41.084158
112
0.590794
6ce99fdeacc314017b6a880dbbea5223f3b09ecd
7,211
/* * Copyright &copy 2014-2016 NetApp, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * DO NOT EDIT THIS CODE BY HAND! It has been generated with jsvcgen. */ package com.solidfire.element.api; import com.solidfire.gson.Gson; import com.solidfire.core.client.Attributes; import com.solidfire.gson.annotations.SerializedName; import com.solidfire.core.annotation.Since; import com.solidfire.core.javautil.Optional; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; import java.util.Objects; /** * ListVolumeAccessGroupsRequest * ListVolumeAccessGroups enables you to return * information about the volume access groups that are * currently in the system. **/ public class ListVolumeAccessGroupsRequest implements Serializable { public static final long serialVersionUID = -7214509188999384185L; @SerializedName("startVolumeAccessGroupID") private Optional<Long> startVolumeAccessGroupID; @SerializedName("limit") private Optional<Long> limit; @SerializedName("volumeAccessGroups") private Optional<Long[]> volumeAccessGroups; // empty constructor @Since("7.0") public ListVolumeAccessGroupsRequest() {} // parameterized constructor @Since("7.0") public ListVolumeAccessGroupsRequest( Optional<Long> startVolumeAccessGroupID, Optional<Long> limit, Optional<Long[]> volumeAccessGroups ) { this.startVolumeAccessGroupID = (startVolumeAccessGroupID == null) ? Optional.<Long>empty() : startVolumeAccessGroupID; this.limit = (limit == null) ? Optional.<Long>empty() : limit; this.volumeAccessGroups = (volumeAccessGroups == null) ? Optional.<Long[]>empty() : volumeAccessGroups; } /** * The volume access group ID at which to begin the listing. If unspecified, there is no lower limit (implicitly 0). **/ public Optional<Long> getStartVolumeAccessGroupID() { return this.startVolumeAccessGroupID; } public void setStartVolumeAccessGroupID(Optional<Long> startVolumeAccessGroupID) { this.startVolumeAccessGroupID = (startVolumeAccessGroupID == null) ? Optional.<Long>empty() : startVolumeAccessGroupID; } /** * The maximum number of results to return. This can be * useful for paging. **/ public Optional<Long> getLimit() { return this.limit; } public void setLimit(Optional<Long> limit) { this.limit = (limit == null) ? Optional.<Long>empty() : limit; } /** * The list of ids of the volume access groups you wish to list **/ public Optional<Long[]> getVolumeAccessGroups() { return this.volumeAccessGroups; } public void setVolumeAccessGroups(Optional<Long[]> volumeAccessGroups) { this.volumeAccessGroups = (volumeAccessGroups == null) ? Optional.<Long[]>empty() : volumeAccessGroups; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ListVolumeAccessGroupsRequest that = (ListVolumeAccessGroupsRequest) o; return Objects.equals(startVolumeAccessGroupID, that.startVolumeAccessGroupID) && Objects.equals(limit, that.limit) && Objects.equals(volumeAccessGroups, that.volumeAccessGroups); } @Override public int hashCode() { return Objects.hash( startVolumeAccessGroupID,limit,volumeAccessGroups ); } public java.util.Map<String, Object> toMap() { java.util.Map<String, Object> map = new HashMap<>(); map.put("startVolumeAccessGroupID", startVolumeAccessGroupID); map.put("limit", limit); map.put("volumeAccessGroups", volumeAccessGroups); return map; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); Gson gson = new Gson(); sb.append( "{ " ); if(null != startVolumeAccessGroupID && startVolumeAccessGroupID.isPresent()){ sb.append(" startVolumeAccessGroupID : ").append(gson.toJson(startVolumeAccessGroupID)).append(","); } else{ sb.append(" startVolumeAccessGroupID : ").append("null").append(","); } if(null != limit && limit.isPresent()){ sb.append(" limit : ").append(gson.toJson(limit)).append(","); } else{ sb.append(" limit : ").append("null").append(","); } if(null != volumeAccessGroups && volumeAccessGroups.isPresent()){ sb.append(" volumeAccessGroups : ").append(gson.toJson(volumeAccessGroups)).append(","); } else{ sb.append(" volumeAccessGroups : ").append("null").append(","); } sb.append( " }" ); if(sb.lastIndexOf(", }") != -1) sb.deleteCharAt(sb.lastIndexOf(", }")); return sb.toString(); } public static Builder builder() { return new Builder(); } public final Builder asBuilder() { return new Builder().buildFrom(this); } public static class Builder { private Optional<Long> startVolumeAccessGroupID; private Optional<Long> limit; private Optional<Long[]> volumeAccessGroups; private Builder() { } public ListVolumeAccessGroupsRequest build() { return new ListVolumeAccessGroupsRequest ( this.startVolumeAccessGroupID, this.limit, this.volumeAccessGroups); } private ListVolumeAccessGroupsRequest.Builder buildFrom(final ListVolumeAccessGroupsRequest req) { this.startVolumeAccessGroupID = req.startVolumeAccessGroupID; this.limit = req.limit; this.volumeAccessGroups = req.volumeAccessGroups; return this; } public ListVolumeAccessGroupsRequest.Builder optionalStartVolumeAccessGroupID(final Long startVolumeAccessGroupID) { this.startVolumeAccessGroupID = (startVolumeAccessGroupID == null) ? Optional.<Long>empty() : Optional.of(startVolumeAccessGroupID); return this; } public ListVolumeAccessGroupsRequest.Builder optionalLimit(final Long limit) { this.limit = (limit == null) ? Optional.<Long>empty() : Optional.of(limit); return this; } public ListVolumeAccessGroupsRequest.Builder optionalVolumeAccessGroups(final Long[] volumeAccessGroups) { this.volumeAccessGroups = (volumeAccessGroups == null) ? Optional.<Long[]>empty() : Optional.of(volumeAccessGroups); return this; } } }
37.170103
144
0.662321
5b7c99c0c47af2e4f6d412d5677377e903b36608
664
package behavioural.observer; public interface Subject { /* * Attach an observer to this subject. * @param observer The observer to attach. */ void attach(Observer observer); /* * Detach an observer from this subject. * @param observer The observer to detach. */ void detach(Observer observer); /* * Notify all observers of a change to this subject's state. */ void notifyOservers(); /* * Get the state of this subject. */ int getState(); /* * Set the state of this subject. * @param The state to set. */ void setState(int state); }
20.121212
64
0.579819
d4e789b6b0580d4012c5f2b31a080cc73fc805cb
1,094
/** * FinalDestinationDisabledGlobalhashOverlay.java * Copyright (C)2009 Nicholas Killewald * * This file is distributed under the terms of the BSD license. * The source package should have a LICENCE file at the toplevel. */ package net.exclaimindustries.geohashdroid; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import android.graphics.drawable.Drawable; /** * The FinalDestinationDisabledGlobalhashOverlay draws a greyed-out and translucent flag * which can be tapped to change the active graticule. * * @author Nicholas Killewald */ public class FinalDestinationDisabledGlobalhashOverlay extends FinalDestinationDisabledOverlay { /** * Creates a new disabled final destination overlay. * * @param d Drawable to use as the flag * @param i Info bundle within this overlay (defines where it is) * @param parent parent MainMap which will pop up a dialog when this is tapped */ public FinalDestinationDisabledGlobalhashOverlay(Drawable d, Info i, MainMap parent) { super(d, i, parent); } }
31.257143
96
0.747715
c39edc963b2da49539c7d973bddfcbd86a3af275
4,720
package ru.majordomo.hms.personmgr.manager.impl; import lombok.RequiredArgsConstructor; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Component; import ru.majordomo.hms.personmgr.common.AccountNoticeType; import ru.majordomo.hms.personmgr.manager.AccountNoticeManager; import ru.majordomo.hms.personmgr.model.account.AccountNotice; import ru.majordomo.hms.personmgr.model.account.BirthdayAccountNotice; import ru.majordomo.hms.personmgr.model.account.DeferredPlanChangeNotice; import ru.majordomo.hms.personmgr.repository.AccountNoticeRepository; import java.time.LocalDate; import java.util.List; import java.util.Optional; @Component @RequiredArgsConstructor public class AccountNoticeManagerImpl implements AccountNoticeManager { private final AccountNoticeRepository accountNoticeRepository; private final MongoOperations mongoOperations; @Override public List<AccountNotice> findByPersonalAccountId(String personalAccountId) { return accountNoticeRepository.findByPersonalAccountId(personalAccountId); } @Override public List<AccountNotice> findByPersonalAccountIdAndType(String personalAccountId, AccountNoticeType type) { return accountNoticeRepository.findByPersonalAccountIdAndType(personalAccountId, type); } @Override public List<AccountNotice> findByPersonalAccountIdAndViewed(String personalAccountId, Boolean viewed) { return accountNoticeRepository.findByPersonalAccountIdAndViewed(personalAccountId, viewed); } @Override public List<AccountNotice> findByPersonalAccountIdAndViewedAndType(String personalAccountId, Boolean viewed, AccountNoticeType type) { return accountNoticeRepository.findByPersonalAccountIdAndViewedAndType(personalAccountId, viewed, type); } @Override public AccountNotice findByPersonalAccountIdAndId(String personalAccountId, String id) { return accountNoticeRepository.findByPersonalAccountIdAndId(personalAccountId, id); } @Override public boolean existsByPersonalAccountIdAndTypeAndViewed(String personalAccountId, AccountNoticeType type, Boolean viewed) { return accountNoticeRepository.existsByPersonalAccountIdAndTypeAndViewed(personalAccountId, type, viewed); } @Override public Optional<AccountNotice> findById(String id) { return accountNoticeRepository.findById(id); } public void save(AccountNotice accountNotice) { mongoOperations.save(accountNotice, AccountNotice.COLLECTION_NAME); // так как сохранение через accountNoticeRepository перестало работать после обновления Spring } @Override public AccountNotice insert(AccountNotice accountNotice) { return mongoOperations.insert(accountNotice); // так как сохранение через accountNoticeRepository перестало работать после обновления Spring } @Override public List<DeferredPlanChangeNotice> findDeferredPlanChangeNoticeByWasChanged(boolean wasChanged) { Query query = new Query(new Criteria("wasChanged").is(wasChanged).and("_class").is(DeferredPlanChangeNotice.class.getName())); return mongoOperations.find(query, DeferredPlanChangeNotice.class, AccountNotice.COLLECTION_NAME); } @Override public List<DeferredPlanChangeNotice> findDeferredPlanChangeNoticeByWasChangedAndWillBeChangedAfterLessThan(boolean wasChanged, LocalDate willBeChangedAfter) { Query query = new Query(new Criteria("wasChanged").is(wasChanged).and("_class").is(DeferredPlanChangeNotice.class.getName()).and("willBeChangedAfter").lt(willBeChangedAfter)); return mongoOperations.find(query, DeferredPlanChangeNotice.class, AccountNotice.COLLECTION_NAME); } @Override public List<BirthdayAccountNotice> findBirthdayAccountNoticeByPersonalAccountId(String personalAccountId) { Query query = new Query(new Criteria("personalAccountId").is(personalAccountId).and("_class").is(BirthdayAccountNotice.class.getName())); return mongoOperations.find(query, BirthdayAccountNotice.class, AccountNotice.COLLECTION_NAME); } @Override public Optional<BirthdayAccountNotice> findBirthdayAccountNoticeByPersonalAccountIdAndId(String personalAccountId, String id) { Query query = new Query(new Criteria("personalAccountId").is(personalAccountId) .and("_id").is(id) .and("_class").is(BirthdayAccountNotice.class.getName())); return Optional.ofNullable(mongoOperations.findOne(query, BirthdayAccountNotice.class, AccountNotice.COLLECTION_NAME)); } }
49.684211
183
0.797246
22bd6703ee4c98c2a3618bbe1ea1eb9c8e121519
2,856
package org.innovateuk.ifs.thread.viewmodel; import org.innovateuk.ifs.threads.resource.FinanceChecksSectionType; import org.innovateuk.ifs.user.resource.Authority; import org.innovateuk.ifs.user.resource.UserResource; import java.time.ZonedDateTime; import java.util.List; import static org.innovateuk.ifs.thread.viewmodel.ThreadState.*; import static org.innovateuk.ifs.user.resource.Role.PROJECT_FINANCE; public class ThreadViewModel { private List<ThreadPostViewModel> viewModelPosts; private FinanceChecksSectionType sectionType; private String title; private ZonedDateTime createdOn; private Long id; private Long organisationId; private Long projectId; private UserResource closedBy; private ZonedDateTime closedDate; public ThreadViewModel(List<ThreadPostViewModel> viewModelPosts, FinanceChecksSectionType sectionType, String title, ZonedDateTime createdOn, Long id, Long organisationId, Long projectId, UserResource closedBy, ZonedDateTime closedDate) { this.viewModelPosts = viewModelPosts; this.sectionType = sectionType; this.title = title; this.createdOn = createdOn; this.id = id; this.organisationId = organisationId; this.projectId = projectId; this.closedBy = closedBy; this.closedDate = closedDate; } public List<ThreadPostViewModel> getViewModelPosts() { return viewModelPosts; } public FinanceChecksSectionType getSectionType() { return sectionType; } public String getTitle() { return title; } public ZonedDateTime getCreatedOn() { return createdOn; } public Long getId() { return id; } public Long getOrganisationId() { return organisationId; } public Long getProjectId() { return projectId; } public UserResource getClosedBy() { return closedBy; } public ZonedDateTime getClosedDate() { return closedDate; } public ThreadState getState() { if (closedDate != null) { return CLOSED; } else if (isLastPostProjectFinance()) { return LAST_POST_BY_INTERNAL_USER; } return LAST_POST_BY_EXTERNAL_USER; } public boolean isClosed() { return getState().equals(CLOSED); } public boolean isLastPostByInternalUser() { return getState().equals(LAST_POST_BY_INTERNAL_USER); } public boolean isLastPostByExternalUser() { return getState().equals(LAST_POST_BY_EXTERNAL_USER); } private boolean isLastPostProjectFinance() { return viewModelPosts .get(viewModelPosts.size() -1) .author.hasAuthority(Authority.PROJECT_FINANCE); } }
27.728155
106
0.668768
9498c844292cef17964807160b76327727b4abf0
1,445
package com.test.activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.widget.TextView; import com.test.R; import com.test.presenter.SecondActivityPresenter; import com.test.presenter.SecondActivityView; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import butterknife.BindView; import butterknife.OnClick; /** * Created by roger on 2018/7/5. */ public class SecondActivity extends BaseActivity implements SecondActivityView { @BindView(R.id.tv_second) public TextView secondTextView; private SecondActivityPresenter presenter = new SecondActivityPresenter(this); private String postString; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().register(this); } @Subscribe(sticky = true) public void getDefaultBus(String str) { this.postString = str; } @OnClick(R.id.tv_second) public void secondOnClick() { presenter.updateView(postString); } @Override protected int getContentId() { return R.layout.activity_second; } @Override public void showText(String str) { toastShort(str); secondTextView.setText(str); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } }
22.936508
82
0.710727
94fcd5635a567f1e3d5050290681cb447990136c
2,122
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.streaming.connectors.activemq.internal; import org.slf4j.Logger; import javax.jms.ExceptionListener; import javax.jms.JMSException; public class AMQExceptionListener implements ExceptionListener { private final boolean logFailuresOnly; private final Logger logger; private JMSException exception; public AMQExceptionListener(Logger logger, boolean logFailuresOnly) { this.logger = logger; this.logFailuresOnly = logFailuresOnly; } @Override public void onException(JMSException e) { this.exception = e; } /** * Check if the listener received an asynchronous exception. Throws an exception if it was * received and if logFailuresOnly was set to true. Resets the state after the call * so a single exception can be thrown only once. * * @throws JMSException if exception was received and logFailuresOnly was set to true. */ public void checkErroneous() throws JMSException { if (exception == null) { return; } JMSException recordedException = exception; exception = null; if (logFailuresOnly) { logger.error("Received ActiveMQ exception", recordedException); } else { throw recordedException; } } }
34.225806
94
0.709708
1a61912d70b9df34c91ded2ccb89b693e50c6434
1,205
package com.github.vvv1559.algorithms.leetcode.lists; /* * Original text: https://leetcode.com/problems/remove-nth-node-from-end-of-list/#/description * * Given a linked list, remove the nth node from the end of list and return its head. * * For example, * * Given linked list: 1->2->3->4->5, and n = 2. * * After removing the second node from the end, the linked list becomes 1->2->3->5. * * Note: * Given n will always be valid. * Try to do this in one pass. * * */ import com.github.vvv1559.algorithms.annotations.Difficulty; import com.github.vvv1559.algorithms.annotations.Level; import com.github.vvv1559.algorithms.structures.ListNode; @Difficulty(Level.MEDIUM) class RemoveNthNodeFromEndOfList { ListNode removeNthFromEnd(ListNode head, int n) { ListNode resultHead = new ListNode(-1); resultHead.next = head; ListNode windowStart = resultHead, windowEnd = resultHead; while (n-- > 0) { windowEnd = windowEnd.next; } while ((windowEnd = windowEnd.next) != null) { windowStart = windowStart.next; } windowStart.next = windowStart.next.next; return resultHead.next; } }
25.638298
94
0.66722
f259f8505ce0acc3c2f784b72200354f6a65d561
635
package br.com.inteligenti.lavoutanovov2; import android.app.Application; import com.facebook.FacebookSdk; import com.facebook.appevents.AppEventsLogger; /** * Created by fernando on 15/12/17. */ public class LoginFacebookApp extends Application { // Location updates intervals public static int UPDATE_INTERVAL = 3000; // 3 sec public static int FATEST_INTERVAL = 3000; // 5 sec public static int DISPLACEMENT = 10; // 10 meters @Override public void onCreate() { super.onCreate(); FacebookSdk.sdkInitialize(getApplicationContext()); AppEventsLogger.activateApp(this); } }
23.518519
59
0.713386
ede82a1f7e68c9d800ea43e962732e629d41130f
745
package com.wzw.ziweishopcity.coupon.service; import com.baomidou.mybatisplus.extension.service.IService; import com.wzw.common.utils.PageUtils; import com.wzw.ziweishopcity.coupon.entity.SeckillSessionEntity; import com.wzw.ziweishopcity.coupon.entity.SeckillSkuRelationEntity; import com.wzw.ziweishopcity.coupon.entity.SkuFullReductionEntity; import java.util.List; import java.util.Map; /** * 秒杀活动场次 * * @author wangziwei * @email 937327493@qq.com * @date 2021-11-30 22:09:51 */ public interface SeckillSessionService extends IService<SeckillSessionEntity> { PageUtils queryPage(Map<String, Object> params); List<SeckillSessionEntity> getPromotion3day(); List<SeckillSkuRelationEntity> getSeckillRelation(Long id); }
27.592593
79
0.798658
2f96293264e40a1de0c5196c60c5e20fd792f7de
7,170
/******************************************************************************* * Copyright 2013 EMBL-EBI * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package htsjdk.samtools; import htsjdk.samtools.cram.lossy.PreservationPolicy; import htsjdk.samtools.cram.ref.CRAMReferenceSource; import htsjdk.samtools.cram.ref.ReferenceSource; import htsjdk.samtools.util.BufferedLineReader; import htsjdk.samtools.util.Log; import java.io.OutputStream; import java.util.List; import java.util.Set; @SuppressWarnings("UnusedDeclaration") public class CRAMFileWriter extends SAMFileWriterImpl { private CRAMContainerStreamWriter cramContainerStream; private final SAMFileHeader samFileHeader; private final String fileName; private static final Log log = Log.getInstance(CRAMFileWriter.class); /** * Create a CRAMFileWriter on an output stream. Requires input records to be presorted to match the * sort order defined by the input {@code samFileHeader}. * * @param outputStream where to write the output. Can not be null. * @param referenceSource reference source. Can not be null. * @param samFileHeader {@link SAMFileHeader} to be used. Can not be null. Sort order is determined by the sortOrder property of this arg. * @param fileName used for display in error messages * * @throws IllegalArgumentException if the {@code outputStream}, {@code referenceSource} or {@code samFileHeader} are null */ public CRAMFileWriter( final OutputStream outputStream, final CRAMReferenceSource referenceSource, final SAMFileHeader samFileHeader, final String fileName) { this(outputStream, null, referenceSource, samFileHeader, fileName); // defaults to presorted == true } /** * Create a CRAMFileWriter and optional index on output streams. Requires input records to be presorted to match the * sort order defined by the input {@code samFileHeader}. * * @param outputStream where to write the output. Can not be null. * @param indexOS where to write the output index. Can be null if no index is required. * @param referenceSource reference source * @param samFileHeader {@link SAMFileHeader} to be used. Can not be null. Sort order is determined by the sortOrder property of this arg. * @param fileName used for display in error messages * * @throws IllegalArgumentException if the {@code outputStream}, {@code referenceSource} or {@code samFileHeader} are null */ public CRAMFileWriter( final OutputStream outputStream, final OutputStream indexOS, final CRAMReferenceSource referenceSource, final SAMFileHeader samFileHeader, final String fileName) { this(outputStream, indexOS, true, referenceSource, samFileHeader, fileName); // defaults to presorted==true } /** * Create a CRAMFileWriter and optional index on output streams. * * @param outputStream where to write the output. Can not be null. * @param indexOS where to write the output index. Can be null if no index is required. * @param presorted if true records written to this writer must already be sorted in the order specified by the header * @param referenceSource reference source * @param samFileHeader {@link SAMFileHeader} to be used. Can not be null. Sort order is determined by the sortOrder property of this arg. * @param fileName used for display in error message display * * @throws IllegalArgumentException if the {@code outputStream}, {@code referenceSource} or {@code samFileHeader} are null */ public CRAMFileWriter(final OutputStream outputStream, final OutputStream indexOS, final boolean presorted, final CRAMReferenceSource referenceSource, final SAMFileHeader samFileHeader, final String fileName) { if (outputStream == null) { throw new IllegalArgumentException("CRAMWriter output stream can not be null."); } if (referenceSource == null) { throw new IllegalArgumentException("A reference is required for CRAM writers"); } if (samFileHeader == null) { throw new IllegalArgumentException("A valid SAMFileHeader is required for CRAM writers"); } this.samFileHeader = samFileHeader; this.fileName = fileName; setSortOrder(samFileHeader.getSortOrder(), presorted); cramContainerStream = new CRAMContainerStreamWriter(outputStream, indexOS, referenceSource, samFileHeader, fileName); setHeader(samFileHeader); } /** * Write an alignment record. * @param alignment must not be null and must have a valid SAMFileHeader. */ @Override protected void writeAlignment(final SAMRecord alignment) { cramContainerStream.writeAlignment(alignment); } @Override protected void writeHeader(final String textHeader) { writeHeader(new SAMTextHeaderCodec().decode(BufferedLineReader.fromString(textHeader),fileName != null ? fileName : null)); } @Override protected void writeHeader(final SAMFileHeader header) { cramContainerStream.writeHeader(header); } @Override protected void finish() { cramContainerStream.finish(true); // flush the last container and issue EOF } @Override protected String getFilename() { return fileName; } public boolean isPreserveReadNames() { return cramContainerStream.isPreserveReadNames(); } public void setPreserveReadNames(final boolean preserveReadNames) { cramContainerStream.setPreserveReadNames(preserveReadNames); } public List<PreservationPolicy> getPreservationPolicies() { return cramContainerStream.getPreservationPolicies(); } public boolean isCaptureAllTags() { return cramContainerStream.isCaptureAllTags(); } public void setCaptureAllTags(final boolean captureAllTags) { cramContainerStream.setCaptureAllTags(captureAllTags); } public Set<String> getCaptureTags() { return cramContainerStream.getCaptureTags(); } public void setCaptureTags(final Set<String> captureTags) { cramContainerStream.setCaptureTags(captureTags); } public Set<String> getIgnoreTags() { return cramContainerStream.getIgnoreTags(); } public void setIgnoreTags(final Set<String> ignoreTags) { cramContainerStream.setIgnoreTags(ignoreTags); } }
41.445087
142
0.696513
3016224213f49dcc5e88c8733b4e956f647bba5d
979
package com.dmall.bms.service.impl.menu.handler; import com.dmall.common.model.swagger.SwaggerInfo; import com.dmall.common.util.JsonUtil; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; /** * @description: * @author: created by hang.yu on 2020/5/16 16:48 */ public class PermissionTest extends BaseTest { private static final String URL = "http://dmall-framework-zuul:7010/dmall-service-impl-background/v2/api-docs"; @Autowired private RestTemplate restTemplate; @Test public void test() { ResponseEntity<String> forEntity = restTemplate.getForEntity(URL, String.class); String body = forEntity.getBody(); SwaggerInfo swagger = JsonUtil.fromJson(body, new TypeReference<SwaggerInfo>() {}); System.out.println(swagger); } }
33.758621
115
0.748723
7dcc3ce06e2b02ffced744e8c3c802c0c7bfc7fa
5,460
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.internal.runners.statements.RunAfters; import org.junit.internal.runners.statements.RunBefores; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import org.junit.runners.model.TestClass; /** * An JUnit 4 runner that also executes all JUnit3 test methods */ public class WicketJUnitRunner extends BlockJUnit4ClassRunner { /** * Construct. * * @param klass * @throws InitializationError */ public WicketJUnitRunner(Class<?> klass) throws InitializationError { super(klass); } @Override protected List<FrameworkMethod> computeTestMethods() { List<FrameworkMethod> methods = new ArrayList<FrameworkMethod>(); methods.addAll(super.computeTestMethods()); for (Method javaMethod : getTestClass().getJavaClass().getMethods()) { if (isJUnitMethod(javaMethod)) { FrameworkMethod junitMethod = new FrameworkMethod(javaMethod); methods.add(junitMethod); } } return methods; } @Override protected Statement withBefores(FrameworkMethod method, Object target, Statement statement) { List<FrameworkMethod> befores = new ArrayList<FrameworkMethod>(); befores.addAll(getTestClass().getAnnotatedMethods(Before.class)); findMethod(getTestClass(), befores, "setUp"); return befores.isEmpty() ? statement : new RunBefores(statement, befores, target); } @Override protected Statement withAfters(FrameworkMethod method, Object target, Statement statement) { List<FrameworkMethod> afters = new ArrayList<FrameworkMethod>(); afters.addAll(getTestClass().getAnnotatedMethods(After.class)); findMethod(getTestClass(), afters, "tearDown"); return afters.isEmpty() ? statement : new RunAfters(statement, afters, target); } @Override protected void validateZeroArgConstructor(List<Throwable> errors) { int ctorsNumber = getTestClass().getOnlyConstructor().getParameterTypes().length; if ((ctorsNumber == 0 || ctorsNumber == 1) == false) { String gripe = "Test class should have exactly one public zero-argument constructor"; errors.add(new Exception(gripe)); } } @Override protected Object createTest() throws Exception { Object testObject; Constructor<?> constructor = getTestClass().getOnlyConstructor(); if (constructor.getParameterTypes().length == 0) { testObject = constructor.newInstance(); } else { testObject = constructor.newInstance("junit3 test"); } return testObject; } /** * Finds a method in the hierarchy of the tested class by his name * * @param testClass * the junit class representation * @param junitMethods * the collection where to add the found method * @param methodName * the name of the method to find * @param parameterTypes * the types of the parameters of the method to find */ private void findMethod(TestClass testClass, List<FrameworkMethod> junitMethods, String methodName, Class<?>... parameterTypes) { try { Class<?> clazz = getTestClass().getJavaClass(); while (clazz != null && Object.class.equals(clazz) == false) { try { Method javaMethod = clazz.getDeclaredMethod(methodName, parameterTypes); if (javaMethod != null && Modifier.isProtected(javaMethod.getModifiers()) && (javaMethod.getReturnType().equals(Void.TYPE) || javaMethod.getReturnType() .equals(Void.class))) { javaMethod.setAccessible(true); junitMethods.add(new FrameworkMethod(javaMethod)); break; } } catch (NoSuchMethodException nsmx) { } clazz = clazz.getSuperclass(); } } catch (Exception e) { throw new RuntimeException(e); } } /** * Checks whether the passes {@code javaMethod} is JUnit 3 test method * * @param javaMethod * the method to check * @return {@code true} if the method passes all conditions to be JUnit3 method, otherwise * {@code false} */ private boolean isJUnitMethod(final Method javaMethod) { return Modifier.isPublic(javaMethod.getModifiers()) && // is not JUnit 4 test method javaMethod.getAnnotation(Test.class) == null && (Void.TYPE.equals(javaMethod.getReturnType()) || Void.class.equals(javaMethod.getReturnType())) && javaMethod.getName().startsWith("test"); } }
30
101
0.721245
a55ae5a07552a87f9d5342655cf21bebbd831191
6,476
package ch.rasc.eds.starter.service; import static ch.ralscha.extdirectspring.annotation.ExtDirectMethodType.STORE_MODIFY; import static ch.ralscha.extdirectspring.annotation.ExtDirectMethodType.STORE_READ; import java.util.List; import java.util.Locale; import javax.validation.Validator; import org.springframework.context.MessageSource; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import ch.ralscha.extdirectspring.annotation.ExtDirectMethod; import ch.ralscha.extdirectspring.bean.ExtDirectStoreResult; import ch.rasc.eds.starter.config.security.JpaUserDetails; import ch.rasc.eds.starter.config.security.RequireAnyAuthority; import ch.rasc.eds.starter.dto.UserSettings; import ch.rasc.eds.starter.entity.PersistentLogin; import ch.rasc.eds.starter.entity.QPersistentLogin; import ch.rasc.eds.starter.entity.User; import ch.rasc.eds.starter.util.JPAQueryFactory; import ch.rasc.eds.starter.util.TotpAuthUtil; import ch.rasc.eds.starter.util.ValidationMessages; import ch.rasc.eds.starter.util.ValidationMessagesResult; import ch.rasc.eds.starter.util.ValidationUtil; import eu.bitwalker.useragentutils.UserAgent; @Service @RequireAnyAuthority public class UserConfigService { private final PasswordEncoder passwordEncoder; private final JPAQueryFactory jpaQueryFactory; private final Validator validator; private final MessageSource messageSource; public UserConfigService(JPAQueryFactory jpaQueryFactory, Validator validator, PasswordEncoder passwordEncoder, MessageSource messageSource) { this.jpaQueryFactory = jpaQueryFactory; this.messageSource = messageSource; this.validator = validator; this.passwordEncoder = passwordEncoder; } @ExtDirectMethod(STORE_READ) @Transactional(readOnly = true) public ExtDirectStoreResult<UserSettings> readSettings( @AuthenticationPrincipal JpaUserDetails jpaUserDetails) { UserSettings userSettings = new UserSettings( jpaUserDetails.getUser(this.jpaQueryFactory)); return new ExtDirectStoreResult<>(userSettings); } @ExtDirectMethod @Transactional public String enable2f(@AuthenticationPrincipal JpaUserDetails jpaUserDetails) { User user = jpaUserDetails.getUser(this.jpaQueryFactory); user.setSecret(TotpAuthUtil.randomSecret()); return user.getSecret(); } @ExtDirectMethod @Transactional public void disable2f(@AuthenticationPrincipal JpaUserDetails jpaUserDetails) { User user = jpaUserDetails.getUser(this.jpaQueryFactory); user.setSecret(null); } @ExtDirectMethod(STORE_MODIFY) @Transactional public ValidationMessagesResult<UserSettings> updateSettings( UserSettings modifiedUserSettings, @AuthenticationPrincipal JpaUserDetails jpaUserDetails, Locale locale) { List<ValidationMessages> validations = ValidationUtil .validateEntity(this.validator, modifiedUserSettings); User user = jpaUserDetails.getUser(this.jpaQueryFactory); if (StringUtils.hasText(modifiedUserSettings.getNewPassword()) && validations.isEmpty()) { if (this.passwordEncoder.matches(modifiedUserSettings.getCurrentPassword(), user.getPasswordHash())) { if (modifiedUserSettings.getNewPassword() .equals(modifiedUserSettings.getNewPasswordRetype())) { user.setPasswordHash(this.passwordEncoder .encode(modifiedUserSettings.getNewPassword())); } else { for (String field : new String[] { "newPassword", "newPasswordRetype" }) { ValidationMessages error = new ValidationMessages(); error.setField(field); error.setMessage(this.messageSource .getMessage("userconfig_pwdonotmatch", null, locale)); validations.add(error); } } } else { ValidationMessages error = new ValidationMessages(); error.setField("currentPassword"); error.setMessage(this.messageSource.getMessage("userconfig_wrongpassword", null, locale)); validations.add(error); } } if (!UserService.isEmailUnique(this.jpaQueryFactory, user.getId(), modifiedUserSettings.getEmail())) { ValidationMessages validationError = new ValidationMessages(); validationError.setField("email"); validationError.setMessage( this.messageSource.getMessage("user_emailtaken", null, locale)); validations.add(validationError); } if (!UserService.isLoginNameUnique(this.jpaQueryFactory, user.getId(), modifiedUserSettings.getLoginName())) { ValidationMessages validationError = new ValidationMessages(); validationError.setField("loginName"); validationError.setMessage( this.messageSource.getMessage("user_loginnametaken", null, locale)); validations.add(validationError); } if (validations.isEmpty()) { user.setLoginName(modifiedUserSettings.getLoginName()); user.setLastName(modifiedUserSettings.getLastName()); user.setFirstName(modifiedUserSettings.getFirstName()); user.setEmail(modifiedUserSettings.getEmail()); user.setLocale(modifiedUserSettings.getLocale()); } return new ValidationMessagesResult<>(modifiedUserSettings, validations); } @ExtDirectMethod(STORE_READ) @Transactional(readOnly = true) public List<PersistentLogin> readPersistentLogins( @AuthenticationPrincipal JpaUserDetails jpaUserDetails) { List<PersistentLogin> persistentLogins = this.jpaQueryFactory .selectFrom(QPersistentLogin.persistentLogin) .where(QPersistentLogin.persistentLogin.user.id .eq(jpaUserDetails.getUserDbId())) .fetch(); persistentLogins.forEach(p -> { String ua = p.getUserAgent(); if (StringUtils.hasText(ua)) { UserAgent userAgent = UserAgent.parseUserAgentString(ua); p.setUserAgentName(userAgent.getBrowser().getGroup().getName()); p.setUserAgentVersion(userAgent.getBrowserVersion().getMajorVersion()); p.setOperatingSystem(userAgent.getOperatingSystem().getName()); } }); return persistentLogins; } @ExtDirectMethod(STORE_MODIFY) @Transactional public void destroyPersistentLogin(String series, @AuthenticationPrincipal JpaUserDetails jpaUserDetails) { this.jpaQueryFactory.delete(QPersistentLogin.persistentLogin) .where(QPersistentLogin.persistentLogin.series.eq(series) .and(QPersistentLogin.persistentLogin.user.id .eq(jpaUserDetails.getUserDbId()))) .execute(); } }
35.977778
85
0.788141
8195cda0aaaef0dcfe812b84199c088b2fbc0363
2,581
package com.xieke.admin.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.xieke.admin.mapper.TestResultMapper; import com.xieke.admin.model.TestResult; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * @author zhangyang * @date 2019/12/21 */ @Service public class TestResultService { @Resource private TestResultMapper testResultMapper; /** * 添加 * * @param testResult * @return */ public boolean insert(TestResult testResult) { return testResultMapper.insert(testResult) > 0; } /** * 删除 * * @param id * @return */ public boolean delete(Integer id) { return testResultMapper.deleteById(id) > 0; } /** * 根据主键查询 * * @param id * @return */ public TestResult get(Integer id) { return testResultMapper.selectById(id); } /** * 查询全部数据 * * @return */ public List<TestResult> findAll() { QueryWrapper<TestResult> wrapper = new QueryWrapper<>(); return testResultMapper.selectList(wrapper); } public List<TestResult> findByTestId(Integer testId) { if (testId == null) { return null; } QueryWrapper<TestResult> wrapper = new QueryWrapper<>(); LambdaQueryWrapper<TestResult> lambdaQueryWrapper = wrapper.lambda(); lambdaQueryWrapper.eq(TestResult::getTestID, testId); return testResultMapper.selectList(lambdaQueryWrapper); } public TestResult getByTestIdAndStudentId(Integer testId, Integer studentId) { if (testId == null) { return null; } if (studentId == null) { return null; } QueryWrapper<TestResult> wrapper = new QueryWrapper<>(); LambdaQueryWrapper<TestResult> lambdaQueryWrapper = wrapper.lambda(); lambdaQueryWrapper.eq(TestResult::getTestID, testId); lambdaQueryWrapper.eq(TestResult::getStudentID, studentId); return testResultMapper.selectOne(lambdaQueryWrapper); } public Boolean modScore(Integer testResultId, Integer score) { if (testResultId == null) { return false; } if (score == null) { return false; } TestResult testResult = this.get(testResultId); testResult.setScore(score); return testResultMapper.updateById(testResult) > 0; } }
26.070707
82
0.6358
a5842651274b11e5ddcc98532e061d7e7e9defda
6,878
package com.backendless.backendless_sdk; import android.content.Context; import androidx.annotation.NonNull; import com.backendless.backendless_sdk.call_handlers.BackendlessCallHandler; import com.backendless.backendless_sdk.call_handlers.CacheCallHandler; import com.backendless.backendless_sdk.call_handlers.CommerceCallHandler; import com.backendless.backendless_sdk.call_handlers.CountersCallHandler; import com.backendless.backendless_sdk.call_handlers.CustomServiceCallHandler; import com.backendless.backendless_sdk.call_handlers.DataCallHandler; import com.backendless.backendless_sdk.call_handlers.EventsCallHandler; import com.backendless.backendless_sdk.call_handlers.FilesCallHandler; import com.backendless.backendless_sdk.call_handlers.LoggingCallHandler; import com.backendless.backendless_sdk.call_handlers.MessagingCallHandler; import com.backendless.backendless_sdk.call_handlers.RtCallHandler; import com.backendless.backendless_sdk.call_handlers.UserServiceCallHandler; import com.backendless.backendless_sdk.common.FlutterBackendlessFCMService; import com.backendless.backendless_sdk.call_handlers.TestCallHandler; import com.backendless.backendless_sdk.utils.codec.BackendlessMessageCodec; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.PluginRegistry; import io.flutter.plugin.common.StandardMethodCodec; /** * BackendlessSdkPlugin */ public class BackendlessSdkPlugin implements FlutterPlugin { private MethodChannel backendlessChannel; private MethodChannel dataChannel; private MethodChannel cacheChannel; private MethodChannel commerceChannel; private MethodChannel countersChannel; private MethodChannel customServiceChannel; private MethodChannel eventsChannel; private MethodChannel filesChannel; private MethodChannel loggingChannel; private MethodChannel messagingChannel; private MethodChannel rtChannel; private MethodChannel userServiceChannel; private MethodChannel fcmServiceChannel; private MethodChannel testChannel; @SuppressWarnings("deprecation") public static void registerWith(PluginRegistry.Registrar registrar) { BackendlessSdkPlugin plugin = new BackendlessSdkPlugin(); plugin.initInstance(registrar.messenger(), registrar.context().getApplicationContext()); } @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { initInstance(binding.getBinaryMessenger(), binding.getApplicationContext()); } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { backendlessChannel.setMethodCallHandler(null); backendlessChannel = null; dataChannel.setMethodCallHandler(null); dataChannel = null; cacheChannel.setMethodCallHandler(null); cacheChannel = null; commerceChannel.setMethodCallHandler(null); commerceChannel = null; countersChannel.setMethodCallHandler(null); countersChannel = null; customServiceChannel.setMethodCallHandler(null); customServiceChannel = null; eventsChannel.setMethodCallHandler(null); eventsChannel = null; filesChannel.setMethodCallHandler(null); filesChannel = null; loggingChannel.setMethodCallHandler(null); loggingChannel = null; messagingChannel.setMethodCallHandler(null); messagingChannel = null; rtChannel.setMethodCallHandler(null); rtChannel = null; userServiceChannel.setMethodCallHandler(null); userServiceChannel = null; fcmServiceChannel.setMethodCallHandler(null); fcmServiceChannel = null; testChannel.setMethodCallHandler(null); testChannel = null; } private void initInstance(BinaryMessenger messenger, Context context) { backendlessChannel = new MethodChannel(messenger, "backendless"); backendlessChannel.setMethodCallHandler(new BackendlessCallHandler(context)); dataChannel = new MethodChannel(messenger, "backendless/data", new StandardMethodCodec(BackendlessMessageCodec.INSTANCE)); dataChannel.setMethodCallHandler(new DataCallHandler(dataChannel)); cacheChannel = new MethodChannel(messenger, "backendless/cache", new StandardMethodCodec(BackendlessMessageCodec.INSTANCE)); cacheChannel.setMethodCallHandler(new CacheCallHandler()); commerceChannel = new MethodChannel(messenger, "backendless/commerce", new StandardMethodCodec(BackendlessMessageCodec.INSTANCE)); commerceChannel.setMethodCallHandler(new CommerceCallHandler()); countersChannel = new MethodChannel(messenger, "backendless/counters"); countersChannel.setMethodCallHandler(new CountersCallHandler()); customServiceChannel = new MethodChannel(messenger, "backendless/custom_service", new StandardMethodCodec(BackendlessMessageCodec.INSTANCE)); customServiceChannel.setMethodCallHandler(new CustomServiceCallHandler()); eventsChannel = new MethodChannel(messenger, "backendless/events", new StandardMethodCodec(BackendlessMessageCodec.INSTANCE)); eventsChannel.setMethodCallHandler(new EventsCallHandler()); filesChannel = new MethodChannel(messenger, "backendless/files", new StandardMethodCodec(BackendlessMessageCodec.INSTANCE)); filesChannel.setMethodCallHandler(new FilesCallHandler(filesChannel)); loggingChannel = new MethodChannel(messenger, "backendless/logging"); loggingChannel.setMethodCallHandler(new LoggingCallHandler()); messagingChannel = new MethodChannel(messenger, "backendless/messaging", new StandardMethodCodec(BackendlessMessageCodec.INSTANCE)); messagingChannel.setMethodCallHandler(new MessagingCallHandler(messagingChannel)); rtChannel = new MethodChannel(messenger, "backendless/rt", new StandardMethodCodec(BackendlessMessageCodec.INSTANCE)); rtChannel.setMethodCallHandler(new RtCallHandler(rtChannel)); userServiceChannel = new MethodChannel(messenger, "backendless/user_service", new StandardMethodCodec(BackendlessMessageCodec.INSTANCE)); userServiceChannel.setMethodCallHandler(new UserServiceCallHandler()); fcmServiceChannel = new MethodChannel(messenger, "backendless/messaging/push"); FlutterBackendlessFCMService.setMethodChannel(fcmServiceChannel); testChannel = new MethodChannel(messenger, "backendless/test", new StandardMethodCodec(BackendlessMessageCodec.INSTANCE)); testChannel.setMethodCallHandler(new TestCallHandler()); } }
47.434483
96
0.771009
be761fb94e7e4ffceb6115184d61d03b1d82fa96
2,540
package uk.gov.hmcts.divorce.systemupdate.service.task; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import uk.gov.hmcts.ccd.sdk.api.CaseDetails; import uk.gov.hmcts.ccd.sdk.type.Document; import uk.gov.hmcts.divorce.divorcecase.model.CaseData; import uk.gov.hmcts.divorce.divorcecase.model.State; import uk.gov.hmcts.divorce.divorcecase.task.CaseTask; import uk.gov.hmcts.divorce.document.CaseDataDocumentService; import uk.gov.hmcts.divorce.document.content.CertificateOfEntitlementContent; import uk.gov.hmcts.divorce.document.model.DivorceDocument; import java.time.Clock; import java.time.LocalDateTime; import static uk.gov.hmcts.divorce.caseworker.service.task.util.FileNameUtil.formatDocumentName; import static uk.gov.hmcts.divorce.document.DocumentConstants.CERTIFICATE_OF_ENTITLEMENT_NAME; import static uk.gov.hmcts.divorce.document.DocumentConstants.CERTIFICATE_OF_ENTITLEMENT_TEMPLATE_ID; import static uk.gov.hmcts.divorce.document.model.DocumentType.CERTIFICATE_OF_ENTITLEMENT; @Component @Slf4j public class GenerateCertificateOfEntitlement implements CaseTask { @Autowired private CaseDataDocumentService caseDataDocumentService; @Autowired private CertificateOfEntitlementContent certificateOfEntitlementContent; @Autowired private Clock clock; @Override public CaseDetails<CaseData, State> apply(final CaseDetails<CaseData, State> caseDetails) { final Long caseId = caseDetails.getId(); final CaseData caseData = caseDetails.getData(); log.info("Generating certificate of entitlement pdf for CaseID: {}", caseDetails.getId()); final Document certificateOfEntitlement = caseDataDocumentService.renderDocument( certificateOfEntitlementContent.apply(caseData, caseId), caseId, CERTIFICATE_OF_ENTITLEMENT_TEMPLATE_ID, caseData.getApplicant1().getLanguagePreference(), formatDocumentName(caseId, CERTIFICATE_OF_ENTITLEMENT_NAME, LocalDateTime.now(clock)) ); final DivorceDocument coeDivorceDocument = DivorceDocument .builder() .documentLink(certificateOfEntitlement) .documentFileName(certificateOfEntitlement.getFilename()) .documentType(CERTIFICATE_OF_ENTITLEMENT) .build(); caseData.getConditionalOrder().setCertificateOfEntitlementDocument(coeDivorceDocument); return caseDetails; } }
39.6875
101
0.778346
5fd480b29259e8422fdcdf28c5e92071b2944a45
2,978
package Application.Controllers; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ResourceBundle; import Application.Constants; import Application.Model.Model; import Application.UI.AlertPopUp; import Application.UI.MainWindow; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.stage.FileChooser; public class InputSceneController implements Initializable{ private Model model; private MainWindow window; @FXML private Button browseButton; @FXML private Button convertButton; @FXML private TextField filePath; @Override public void initialize(URL arg0, ResourceBundle arg1) { window = MainWindow.getMainWindow(); model = window.getModel(); convertButton.setDisable(true); filePath.textProperty().addListener((obs, oldText, newText) -> { if(!newText.equals("")){ InputSceneController.this.convertButton.setDisable(false); } else { InputSceneController.this.convertButton.setDisable(true); } }); // This adds the enter key function to text field this.filePath.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent ke) { if (ke.getCode().equals(KeyCode.ENTER)) { InputSceneController.this.convertButtonClicked(new ActionEvent()); } } }); filePath.setPromptText(Constants.BROWSE_TEXT.getValue()); } public void convertButtonSetConvertingStatus(Boolean isConverting) { if(isConverting) { convertButton.setText(Constants.CONVERTING.getValue()); convertButton.setDisable(true); } else { convertButton.setText(Constants.CONVERT.getValue()); convertButton.setDisable(false); } } @FXML public void convertButtonClicked(ActionEvent e) { /*if you don't want to use @FXML, you can also * get the reference to the control object by using (Button) e.getSourced()*/ // This checks if the file path is valid Path path = Paths.get(this.filePath.getText()); if(!Files.exists(path)) { AlertPopUp.display(Constants.ENTER_VALID_PATH_TEXT.getValue()); } else { this.model.setInputFile(this.filePath.getText()); this.model.tellUItoDisplayPopUp(); } } @FXML public void browseButtonClicked(ActionEvent e) { FileChooser chooser = new FileChooser(); //this makes sure that only .text file is selected, no need cuz AES encrypts all files //chooser.getExtensionFilters().addAll(new ExtensionFilter("*.txt", "*.txt")); try { this.filePath.setText(chooser.showOpenDialog(null).getAbsolutePath()); }catch(NullPointerException f) { System.out.println(Constants.NO_INPUT_ERROR_MSG.getValue()); } } }
27.321101
88
0.722297
495053fc1d9dd33c3e58e996c52f575504cd59cc
9,711
/** * Copyright (C) 2005-2008 Jive Software. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.openfire.sip.calllog; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import org.jivesoftware.database.DbConnectionManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Database persistence for CallLog class and database methods for call log store * * @author Thiago Rocha Camargo */ public class CallLogDAO { private static final Logger Log = LoggerFactory.getLogger(CallLogDAO.class); final static CallFilter emptyFilter = new CallFilter("", new ArrayList<String>()); /** * Return every stored calls that matches to the SQLCondition in the interval between startIndex and endIndex * * @param filter the content of a SQL "Where" clause. * @param startIndex start index of results * @param numResults number of resultes to return * @return Collection<CallLog>; */ public static Collection<CallLog> getCalls(CallFilter filter, int startIndex, int numResults) { String sql = "SELECT * FROM ofSipPhoneLog"; sql = filter != null && !filter.getSQL().equals("") ? sql + " WHERE " + filter.getSQL() : sql; sql += " ORDER BY datetime DESC"; List<CallLog> calls = new ArrayList<CallLog>(numResults); Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = DbConnectionManager.createScrollablePreparedStatement(con, sql); int i = 1; for (String value : filter.getValues()) { pstmt.setString(i++, value); } ResultSet rs = pstmt.executeQuery(); DbConnectionManager.setFetchSize(rs, startIndex + numResults); DbConnectionManager.scrollResultSet(rs, startIndex); int count = 0; while (rs.next() && count < numResults) { calls.add(read(rs)); count++; } rs.close(); } catch (SQLException e) { Log.error(e.getMessage(), e); } finally { try { if (pstmt != null) { pstmt.close(); } } catch (Exception e) { Log.error(e.getMessage(), e); } try { if (con != null) { con.close(); } } catch (Exception e) { Log.error(e.getMessage(), e); } } return calls; } /** * Read a callLog result set and return a CallLog instance with the information of the resultSet * * @param rs ResultSet * @return CallLog */ private static CallLog read(ResultSet rs) { CallLog callLog = null; try { String username = rs.getString("username"); String numA = rs.getString("addressFrom"); String numB = rs.getString("addressTo"); long dateTime = rs.getLong("datetime"); int duration = rs.getInt("duration"); String callType = rs.getString("calltype"); if ("loss".equals(callType)) { // Backwards compatibility change callType = "missed"; } CallLog.Type type = CallLog.Type.valueOf(callType); callLog = new CallLog(username); callLog.setNumA(numA); callLog.setNumB(numB); callLog.setDateTime(dateTime); callLog.setDuration(duration); callLog.setType(type); } catch (SQLException e) { Log.error(e.getMessage(), e); } return callLog; } /** * Insert a new CallLog into the database * * @param callLog call logging * @throws SQLException */ public static void insert(CallLog callLog) throws SQLException { String sql = "INSERT INTO ofSipPhoneLog (username, addressFrom, addressTo, datetime, duration, calltype) " + " values (?, ?, ?, ?, ?, ?)"; Connection con = null; PreparedStatement psmt = null; ResultSet rs = null; try { con = DbConnectionManager.getConnection(); psmt = con.prepareStatement(sql); psmt.setString(1, callLog.getUsername()); psmt.setString(2, callLog.getNumA()); psmt.setString(3, callLog.getNumB()); psmt.setLong(4, callLog.getDateTime()); psmt.setInt(5, callLog.getDuration()); psmt.setString(6, callLog.getType().name()); psmt.executeUpdate(); } catch (SQLException e) { Log.error(e.getMessage(), e); throw new SQLException(e.getMessage()); } finally { DbConnectionManager.closeConnection(rs, psmt, con); } } /** * Gets all calls in database for the given range * * @param startIndex * @param numResults * @return Collection<CallLog> */ public static Collection<CallLog> getCalls(int startIndex, int numResults) { return getCalls(emptyFilter, startIndex, numResults); } /** * Return the number of callLog stored * * @return int number */ public static int getLogCount() { return getLogCount(emptyFilter); } /** * Return the number of store callLogs for the given SQLCondition * * @param filter call filter * @return int number */ public static int getLogCount(CallFilter filter) { int count = 0; String sql = "SELECT count(*) FROM ofSipPhoneLog"; sql = filter != null && !filter.getSQL().equals("") ? sql + " WHERE " + filter.getSQL() : sql; Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(sql); int i = 1; for (String value : filter.getValues()) { pstmt.setString(i++, value); } ResultSet rs = pstmt.executeQuery(); if (rs.next()) { count = rs.getInt(1); } rs.close(); } catch (SQLException e) { Log.error(e.getMessage(), e); } finally { try { if (pstmt != null) { pstmt.close(); } } catch (Exception e) { Log.error(e.getMessage(), e); } try { if (con != null) { con.close(); } } catch (Exception e) { Log.error(e.getMessage(), e); } } return count; } /** * Create a SQLFilter ( SQL Condition ) for CallLog entries * * @param username * @param numa * @param numb * @param callType * @param fromDate * @param uptoDate * @return String */ public static CallFilter createSQLFilter(String username, String numa, String numb, String callType, Date fromDate, Date uptoDate) { ArrayList<String> conditions = new ArrayList<String>(10); ArrayList<String> values = new ArrayList<String>(10); if (username != null && !username.trim().equals("")) { conditions.add(" username = ? "); values.add(username.trim()); } if (numa != null && !numa.trim().equals("")) { conditions.add(" addressFrom = ? "); values.add(numa.trim()); } if (numb != null && !numb.trim().equals("")) { conditions.add(" addressTo = ? "); values.add(numb.trim()); } if (fromDate != null) { conditions.add(" datetime >= ? "); values.add(String.valueOf(fromDate.getTime())); } if (uptoDate != null) { conditions.add(" datetime <= ? "); values.add(String.valueOf(uptoDate.getTime())); } if (callType != null && !callType.trim().equals("") && !callType.trim().equals("all")) { conditions.add(" calltype = ? "); values.add(callType.trim()); } StringBuilder str = new StringBuilder(); for (String aux : conditions) { if (str.length() > 0) str.append("AND"); str.append(aux); } return new CallFilter(str.toString(), values); } }
31.631922
115
0.527752
6bcc0a1166cd354501f925d903430f2c406d4836
8,240
package com.packt.cookbook.ch02_oop.g_objects; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.function.Supplier; public class ObjectsDemo { public static void main(String... args){ //compare(); //toStringWhenNull(); //checkIndex(); //requireNonNull(); //hash(); //isNull(); equal(); } private static void equal(){ String o1 = "o"; String o2 = "o"; System.out.println(Objects.equals(o1, o2)); //prints: true o1 = null; o2 = null; System.out.println(Objects.equals(o1, o2)); //prints: true Integer[] ints1 = {1,2,3}; Integer[] ints2 = {1,2,3}; System.out.println(Objects.equals(ints1, ints2)); //prints: false Integer[][] iints1 = {{1,2,3},{1,2,3}}; Integer[][] iints2 = {{1,2,3},{1,2,3}}; System.out.println(Objects.equals(iints1, iints2)); //prints: false o1 = "o"; o2 = "o"; System.out.println(Objects.deepEquals(o1, o2)); //prints: true o1 = null; o2 = null; System.out.println(Objects.deepEquals(o1, o2)); //prints: true //Integer[] ints1 = {1,2,3}; //Integer[] ints2 = {1,2,3}; System.out.println(Objects.deepEquals(ints1, ints2)); //prints: true //Integer[][] iints1 = {{1,2,3},{1,2,3}}; //Integer[][] iints2 = {{1,2,3},{1,2,3}}; System.out.println(Objects.deepEquals(iints1, iints2)); //prints: true Integer[][] iints3 = {{1,2,3},{1,3,2}}; System.out.println(Objects.deepEquals(iints1, iints3)); //prints: false //Integer[] ints1 = {1,2,3}; //Integer[] ints2 = {1,2,3}; System.out.println(Arrays.equals(ints1, ints2)); //prints: true System.out.println(Arrays.deepEquals(ints1, ints2)); //prints: true System.out.println(Arrays.equals(iints1, iints2)); //prints: false System.out.println(Arrays.deepEquals(iints1, iints2)); //prints: true } private static void isNull(){ String obj = null; System.out.println(obj == null); //prints: true System.out.println(Objects.isNull(obj)); //prints: true obj = ""; System.out.println(obj == null); //prints: false System.out.println(Objects.isNull(obj)); //prints: false obj = null; System.out.println(obj != null); //prints: false System.out.println(Objects.nonNull(obj)); //prints: false obj = ""; System.out.println(obj != null); //prints: true System.out.println(Objects.nonNull(obj)); //prints: true } private static void hash(){ System.out.println(Objects.hashCode(null)); //prints: 0 System.out.println(Objects.hashCode("abc")); //prints: 96354 System.out.println(Objects.hash(null)); //prints: 0 System.out.println(Objects.hash("abc")); //prints: 96385 String[] arr = {"abc"}; System.out.println(Objects.hash(arr)); //prints: 96385 Object[] objs = {"a", 42, "c"}; System.out.println(Objects.hash(objs)); //prints: 124409 System.out.println(Objects.hash("a", 42, "c")); //prints: 124409 } private static void requireNonNull(){ String obj = null; try { Objects.requireNonNull(obj); } catch (NullPointerException ex){ System.out.println(ex.getMessage()); //prints: null } //String obj = null; try { Objects.requireNonNull(obj, "Parameter 'obj' is null"); } catch (NullPointerException ex){ System.out.println(ex.getMessage()); //prints: Parameter 'obj' is null } //String obj = null; Supplier<String> msg1 = () -> { String msg = "Message"; return msg; }; try { Objects.requireNonNull(obj, msg1); } catch (NullPointerException ex){ System.out.println(ex.getMessage()); //prints: Message } Supplier<String> msg2 = () -> null; try { Objects.requireNonNull(obj, msg2); } catch (NullPointerException ex){ System.out.println(ex.getMessage()); //prints: null } Supplier<String> msg3 = null; try { Objects.requireNonNull(obj, msg3); } catch (NullPointerException ex){ System.out.println(ex.getMessage()); //prints: null } //String obj = null; System.out.println(Objects.requireNonNullElse(obj, "Default value")); //prints: Default value try { Objects.requireNonNullElse(obj, null); } catch (NullPointerException ex){ System.out.println(ex.getMessage()); //prints: defaultObj } //String obj = null; System.out.println(Objects.requireNonNullElseGet(obj, msg1)); //prints: Message Integer objInt = null; Supplier<Integer> msg4 = () -> { Integer val = 42; return val; }; try { System.out.println(Objects.requireNonNullElseGet(objInt, msg4)); } catch (NullPointerException ex){ System.out.println(ex.getMessage()); //prints: 42 } try { System.out.println(Objects.requireNonNullElseGet(obj, null)); } catch (NullPointerException ex){ System.out.println(ex.getMessage()); //prints: supplier } } private static void checkIndex(){ List<Integer> list = List.of(1, 2); try { Objects.checkIndex(3, list.size()); } catch (IndexOutOfBoundsException ex){ System.out.println(ex.getMessage()); //prints: Index 3 out-of-bounds for length 2 } //List<Integer> list = List.of(1, 2); try { Objects.checkFromIndexSize(1, 3, list.size()); } catch (IndexOutOfBoundsException ex){ System.out.println(ex.getMessage()); //prints: Range [1, 1 + 3) out-of-bounds for length 2 } //List<Integer> list = List.of(1, 2); try { Objects.checkFromToIndex(1, 3, list.size()); } catch (IndexOutOfBoundsException ex){ System.out.println(ex.getMessage()); //prints: Range [1, 3) out-of-bounds for length 2 } } private static void toStringWhenNull(){ System.out.println(Objects.toString("a")); //prints: a System.out.println(Objects.toString(null)); //prints: null System.out.println(Objects.toString("a", "b")); //prints: a System.out.println(Objects.toString(null, "b")); //prints: b } private static void compare(){ int res = Objects.compare("a", "c", Comparator.naturalOrder()); System.out.println(res); //prints: -2 res = Objects.compare("a", "a", Comparator.naturalOrder()); System.out.println(res); //prints: 0 res = Objects.compare("c", "a", Comparator.naturalOrder()); System.out.println(res); //prints: 2 res = Objects.compare("c", "a", Comparator.reverseOrder()); System.out.println(res); //prints: -2 res = Objects.compare(3, 5, Comparator.naturalOrder()); System.out.println(res); //prints: -1 res = Objects.compare(3, 3, Comparator.naturalOrder()); System.out.println(res); //prints: 0 res = Objects.compare(5, 3, Comparator.naturalOrder()); System.out.println(res); //prints: 1 res = Objects.compare(5, 3, Comparator.reverseOrder()); System.out.println(res); //prints: -1 res = Objects.compare("5", "3", Comparator.reverseOrder()); System.out.println(res); //prints: -2 //res = Objects.compare(null, "c", Comparator.naturalOrder()); //NullPointerException //res = Objects.compare("a", null, Comparator.naturalOrder()); //NullPointerException res = Objects.compare(null, null, Comparator.naturalOrder()); System.out.println(res); //prints: 0 } }
34.476987
103
0.559951
f7604331692248da4eb6765dd47ab157b4417f7a
3,912
package com.thinkaurelius.titan.graphdb.vertices; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.thinkaurelius.titan.diskstorage.Entry; import com.thinkaurelius.titan.diskstorage.EntryList; import com.thinkaurelius.titan.diskstorage.MyEntryList; import com.thinkaurelius.titan.diskstorage.keycolumnvalue.EdgeSliceQuery; import com.thinkaurelius.titan.diskstorage.keycolumnvalue.SliceQuery; import com.thinkaurelius.titan.graphdb.internal.ElementLifeCycle; import com.thinkaurelius.titan.graphdb.internal.InternalRelation; import com.thinkaurelius.titan.graphdb.transaction.StandardTitanTx; import com.thinkaurelius.titan.graphdb.transaction.addedrelations.AddedRelationsContainer; import com.thinkaurelius.titan.graphdb.transaction.addedrelations.ConcurrentAddedRelations; import com.thinkaurelius.titan.graphdb.transaction.addedrelations.SimpleAddedRelations; import com.thinkaurelius.titan.util.datastructures.Retriever; import org.apache.tinkerpop.gremlin.structure.Vertex; import java.util.Collection; import java.util.Collections; import java.util.List; /** * @author Matthias Broecheler (me@matthiasb.com) */ public class StandardVertex extends AbstractVertex { private byte lifecycle; private volatile AddedRelationsContainer addedRelations=AddedRelationsContainer.EMPTY; public StandardVertex(final StandardTitanTx tx, final long id, byte lifecycle) { super(tx, id); this.lifecycle=lifecycle; } public synchronized final void updateLifeCycle(ElementLifeCycle.Event event) { this.lifecycle = ElementLifeCycle.update(lifecycle,event); } @Override public void removeRelation(InternalRelation r) { if (r.isNew()) addedRelations.remove(r); else if (r.isLoaded()) updateLifeCycle(ElementLifeCycle.Event.REMOVED_RELATION); else throw new IllegalArgumentException("Unexpected relation status: " + r.isRemoved()); } @Override public boolean addRelation(InternalRelation r) { Preconditions.checkArgument(r.isNew()); if (addedRelations==AddedRelationsContainer.EMPTY) { if (tx().getConfiguration().isSingleThreaded()) { addedRelations=new SimpleAddedRelations(); } else { synchronized (this) { if (addedRelations==AddedRelationsContainer.EMPTY) addedRelations=new ConcurrentAddedRelations(); } } } if (addedRelations.add(r)) { updateLifeCycle(ElementLifeCycle.Event.ADDED_RELATION); return true; } else return false; } @Override public List<InternalRelation> getAddedRelations(Predicate<InternalRelation> query) { return addedRelations.getView(query); } @Override public EntryList loadRelations(SliceQuery query, Retriever<SliceQuery, EntryList> lookup) { return (isNew()) ? EntryList.EMPTY_LIST : lookup.get(query); } @Override public MyEntryList loadRelations(EdgeSliceQuery query, Retriever<EdgeSliceQuery, MyEntryList> lookup) { return (isNew()) ? MyEntryList.EMPTY_LIST : lookup.get(query); } @Override public boolean hasLoadedRelations(SliceQuery query) { return false; } @Override public boolean hasLoadedRelations(EdgeSliceQuery query) { return false; } @Override public boolean hasRemovedRelations() { return ElementLifeCycle.hasRemovedRelations(lifecycle); } @Override public boolean hasAddedRelations() { return ElementLifeCycle.hasAddedRelations(lifecycle); } @Override public synchronized void remove() { super.remove(); ((StandardVertex)it()).updateLifeCycle(ElementLifeCycle.Event.REMOVED); } @Override public byte getLifeCycle() { return lifecycle; } }
34.619469
107
0.722393
e65df931e8ec1267bfa237fe9af27ca51866e88b
14,647
package com.platform.service; import com.alibaba.fastjson.JSONObject; import com.aliyun.oss.common.utils.DateUtil; import com.platform.cache.J2CacheUtils; import com.platform.dao.*; import com.platform.entity.*; import com.platform.util.CommonUtil; import com.platform.utils.DateUtils; import org.apache.commons.lang.StringUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.util.*; //@Service public class ApiOrderService2 { @Autowired private ApiOrderMapper orderDao; @Autowired private ApiAddressMapper apiAddressMapper; @Autowired private ApiCartMapper apiCartMapper; @Autowired private ApiCouponMapper apiCouponMapper; @Autowired private ApiOrderMapper apiOrderMapper; @Autowired private ApiOrderGoodsMapper apiOrderGoodsMapper; @Autowired private ApiProductService productService; @Autowired private ApiGoodsService goodsService; @Autowired UserRecordSer userRecordSer; public OrderVo queryObject(Integer id) { return orderDao.queryObject(id); } public List<OrderVo> queryList(Map<String, Object> map) { return orderDao.queryList(map); } public int queryTotal(Map<String, Object> map) { return orderDao.queryTotal(map); } public void save(OrderVo order) { orderDao.save(order); } public int update(OrderVo order) { return orderDao.update(order); } public void delete(Integer id) { orderDao.delete(id); } public void deleteBatch(Integer[] ids) { orderDao.deleteBatch(ids); } @Transactional public Map<String, Object> submit(JSONObject jsonParam, UserVo loginUser) { // Map<String, Object> param = new HashMap<String, Object>(); // param.put("user_id", loginUser.getUserId()); // param.put("merchant_id", "2"); // List<CartVo> checkedGoodsList = apiCartMapper.queryList(param); // System.out.println(checkedGoodsList); // param.put("merchant_id", "1"); // checkedGoodsList = apiCartMapper.queryList(param); // System.out.println(checkedGoodsList); // param.put("merchant_id", "1"); // checkedGoodsList = apiCartMapper.queryList(param); // System.out.println(checkedGoodsList); Map<String, Object> resultObj = new HashMap<String, Object>(); // 原来couponId换成couponId和good组合的list集合 String couponGoodList = jsonParam.getString("couponGoodList"); Integer couponId = jsonParam.getInteger("couponId"); String type = jsonParam.getString("type"); String postscript = jsonParam.getString("postscript"); // 获取推荐人id String promoterId = jsonParam.getString("promoterId"); AddressVo addressVo = apiAddressMapper.queryObject(jsonParam.getInteger("addressId")); // * 获取要购买的商品 List<CartVo> checkedGoodsList = new ArrayList<>(); BigDecimal goodsTotalPrice; if (type.equals("cart")) { Map<String, Object> param = new HashMap<String, Object>(); param.put("user_id", loginUser.getUserId()); List<CartVo> mrchantList = apiCartMapper.queryMrchantGroup(param); for(CartVo vo : mrchantList) { param.put("merchant_id", vo.getMerchant_id()); checkedGoodsList = apiCartMapper.queryList(param); if (null == checkedGoodsList) { resultObj.put("errno", 400); resultObj.put("errmsg", "请选择商品"); return resultObj; } // 统计商品总价 double brokerage_percent = 0.0; BigDecimal freightPrice = BigDecimal.ZERO; BigDecimal couponPrice = new BigDecimal(0.00); goodsTotalPrice = new BigDecimal(0.00); for (CartVo cartItem : checkedGoodsList) { goodsTotalPrice = goodsTotalPrice .add(cartItem.getRetail_price().multiply(new BigDecimal(cartItem.getNumber()))); ProductVo productInfo = productService.queryObject(cartItem.getProduct_id()); if (null == productInfo || productInfo.getGoods_number() < cartItem.getNumber()) { resultObj.put("errno", 500); resultObj.put("errmsg", cartItem.getGoods_name() + "库存不足"); return resultObj; } else { productInfo.setGoods_number(productInfo.getGoods_number() - cartItem.getNumber()); productService.update(productInfo); } // 运费统计 Integer goodId = cartItem.getGoods_id(); GoodsVo goods = goodsService.queryObject(goodId); if (goods.getExtra_price() != null) { freightPrice = freightPrice .add(goods.getExtra_price().multiply(new BigDecimal(cartItem.getNumber()))); } } // 获取订单使用的优惠券 couponGoodList = "100=1152004&100=1131017&100=1152008&100=1023003"; String[] couponGoods = couponGoodList.split("&"); for (String couponGood : couponGoods) { Integer ncouponId = Integer.parseInt(couponGood.split("=")[0]); Integer goodsId = Integer.parseInt(couponGood.split("=")[1]); if (ncouponId != null && ncouponId != 0 && goodsId != null && goodsId != 0) { GoodsVo goods = goodsService.queryObject(goodsId); CouponVo couponVo = apiCouponMapper.getUserCoupon(ncouponId); // 代金券状态1可用,并且最小商品小雨订单金额 if (couponVo != null && couponVo.getCoupon_status() == 1 && couponVo.getMin_goods_amount().compareTo(goods.getRetail_price()) <= 0) { couponPrice = couponVo.getType_money(); } } } // 订单价格计算 BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice); // 订单的总价 BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice); // 减去其它支付的金额后,要实际支付的金额 OrderVo orderInfo = new OrderVo(); String all_order_id = UUID.randomUUID().toString().replaceAll("-", ""); orderInfo.setAll_order_id(all_order_id); orderInfo.setOrder_sn(CommonUtil.generateOrderNumber()); orderInfo.setUser_id(loginUser.getUserId()); // 收货地址和运费 orderInfo.setConsignee(addressVo.getUserName()); orderInfo.setMobile(addressVo.getTelNumber()); orderInfo.setCountry(addressVo.getNationalCode()); orderInfo.setProvince(addressVo.getProvinceName()); orderInfo.setCity(addressVo.getCityName()); orderInfo.setDistrict(addressVo.getCountyName()); orderInfo.setAddress(addressVo.getDetailInfo()); // 留言 orderInfo.setPostscript(postscript); // 使用的优惠券 // orderInfo.setCoupon_id(couponId); orderInfo.setCoupon_price(couponPrice.toString()); orderInfo.setAdd_time(new Date()); orderInfo.setGoods_price(goodsTotalPrice); orderInfo.setOrder_price(orderTotalPrice); orderInfo.setActual_price(actualPrice); orderInfo.setAll_price(actualPrice); orderInfo.setFreight_price(freightPrice.intValue()); // 待付款 orderInfo.setOrder_status(0); orderInfo.setShipping_status(0); orderInfo.setPay_status(0); orderInfo.setShipping_id(0); orderInfo.setShipping_fee(freightPrice); orderInfo.setIntegral(0); orderInfo.setIntegral_money(new BigDecimal(0)); if (type.equals("cart")) { orderInfo.setOrder_type("1"); } else { orderInfo.setOrder_type("4"); } // 开启事务,插入订单信息和订单商品 // 添加订单分销信息 if (StringUtils.isNotEmpty(promoterId)) { orderInfo.setPromoter_id(Integer.valueOf(promoterId)); } // 计算佣金 orderInfo.setBrokerage(orderInfo.getActual_price().multiply(new BigDecimal(brokerage_percent))); apiOrderMapper.save(orderInfo); for (CartVo goodsItem : checkedGoodsList) { OrderGoodsVo orderGoodsVo = new OrderGoodsVo(); orderGoodsVo.setOrder_id(orderInfo.getId()); orderGoodsVo.setGoods_id(goodsItem.getGoods_id()); orderGoodsVo.setGoods_sn(goodsItem.getGoods_id().toString()); orderGoodsVo.setProduct_id(goodsItem.getProduct_id()); orderGoodsVo.setGoods_name(goodsItem.getGoods_name()); orderGoodsVo.setList_pic_url(goodsItem.getList_pic_url()); orderGoodsVo.setMarket_price(goodsItem.getMarket_price()); orderGoodsVo.setRetail_price(goodsItem.getRetail_price()); orderGoodsVo.setNumber(goodsItem.getNumber()); orderGoodsVo.setGoods_specifition_name_value(goodsItem.getGoods_specifition_name_value()); orderGoodsVo.setGoods_specifition_ids(goodsItem.getGoods_specifition_ids()); if (type.equals("cart")) { couponGoodList = "123=456&567=098"; for (String couponGood : couponGoods) { Integer ncouponId = Integer.parseInt(couponGood.split("=")[0]); Integer goodsId = Integer.parseInt(couponGood.split("=")[1]); if(goodsId.intValue() == goodsItem.getGoods_id().intValue()) { orderGoodsVo.setCoupon_id(ncouponId); } } } else { orderGoodsVo.setCoupon_id(couponId); } apiOrderGoodsMapper.save(orderGoodsVo); } // 清空已购买的商品 apiCartMapper.deleteByCart(loginUser.getUserId(), 1, 1); resultObj.put("errno", 0); resultObj.put("errmsg", "订单提交成功"); // Map<String, OrderVo> orderInfoMap = new HashMap<String, OrderVo>(); orderInfoMap.put("orderInfo", orderInfo); // resultObj.put("data", orderInfoMap); // 优惠券标记已用 for (String couponGood : couponGoods) { Integer ncouponId = Integer.parseInt(couponGood.split("=")[0]); CouponVo couponVo = apiCouponMapper.queryObject(ncouponId); if (couponVo != null && couponVo.getCoupon_status() == 1) { couponVo.setCoupon_status(2); apiCouponMapper.updateUserCoupon(couponVo); } } } } else {//直接购买 double brokerage_percent = 0.0; BigDecimal freightPrice = BigDecimal.ZERO; BigDecimal couponPrice = new BigDecimal(0.00); BuyGoodsVo goodsVo = (BuyGoodsVo) J2CacheUtils.get(J2CacheUtils.SHOP_CACHE_NAME, "goods" + loginUser.getUserId()); ProductVo productInfo = productService.queryObject(goodsVo.getProductId()); // 计算订单的费用 // 商品总价 goodsTotalPrice = productInfo.getRetail_price().multiply(new BigDecimal(goodsVo.getNumber())); CartVo cartVo = new CartVo(); BeanUtils.copyProperties(productInfo, cartVo); cartVo.setNumber(goodsVo.getNumber()); cartVo.setProduct_id(goodsVo.getProductId()); checkedGoodsList.add(cartVo); if (null == productInfo || productInfo.getGoods_number() < goodsVo.getNumber()) { resultObj.put("errno", 500); resultObj.put("errmsg", goodsVo.getName() + "库存不足"); return resultObj; } else { productInfo.setGoods_number(productInfo.getGoods_number() - goodsVo.getNumber()); productService.update(productInfo); } // 运费统计 Integer goodId = goodsVo.getGoodsId(); GoodsVo goods = goodsService.queryObject(goodId); brokerage_percent = goods.getBrokerage_percent(); if (goods.getExtra_price() != null) { freightPrice = freightPrice.add(goods.getExtra_price().multiply(new BigDecimal(goodsVo.getNumber()))); } //获取订单使用的优惠券 CouponVo couponVo = null; if (couponId != null && couponId != 0) { couponVo = apiCouponMapper.getUserCoupon(couponId); if (couponVo != null && couponVo.getCoupon_status() == 1) { couponPrice = couponVo.getType_money(); } } // 订单价格计算 BigDecimal orderTotalPrice = goodsTotalPrice.add(freightPrice); // 订单的总价 BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice); // 减去其它支付的金额后,要实际支付的金额 OrderVo orderInfo = new OrderVo(); String all_order_id = UUID.randomUUID().toString().replaceAll("-", ""); orderInfo.setAll_order_id(all_order_id); orderInfo.setOrder_sn(CommonUtil.generateOrderNumber()); orderInfo.setUser_id(loginUser.getUserId()); // 收货地址和运费 orderInfo.setConsignee(addressVo.getUserName()); orderInfo.setMobile(addressVo.getTelNumber()); orderInfo.setCountry(addressVo.getNationalCode()); orderInfo.setProvince(addressVo.getProvinceName()); orderInfo.setCity(addressVo.getCityName()); orderInfo.setDistrict(addressVo.getCountyName()); orderInfo.setAddress(addressVo.getDetailInfo()); // orderInfo.setFreight_price(freightPrice.intValue()); // 留言 orderInfo.setPostscript(postscript); // 使用的优惠券 // orderInfo.setCoupon_id(couponId); orderInfo.setCoupon_price(couponPrice.toString()); orderInfo.setAdd_time(new Date()); orderInfo.setGoods_price(goodsTotalPrice); orderInfo.setOrder_price(orderTotalPrice); orderInfo.setActual_price(actualPrice); orderInfo.setAll_price(actualPrice); orderInfo.setFreight_price(actualPrice.subtract(goodsTotalPrice).intValue()); // 待付款 orderInfo.setOrder_status(0); orderInfo.setShipping_status(0); orderInfo.setPay_status(0); orderInfo.setShipping_id(0); orderInfo.setShipping_fee(freightPrice); orderInfo.setIntegral(0); orderInfo.setIntegral_money(new BigDecimal(0)); if (type.equals("cart")) { orderInfo.setOrder_type("1"); } else { orderInfo.setOrder_type("4"); } // 开启事务,插入订单信息和订单商品 // 添加订单分销信息 System.out.println("promoterId=============" + promoterId); if (StringUtils.isNotEmpty(promoterId)) { orderInfo.setPromoter_id(Integer.valueOf(promoterId)); } // 计算佣金 orderInfo.setBrokerage(orderInfo.getActual_price().multiply(new BigDecimal(brokerage_percent))); apiOrderMapper.save(orderInfo); for (CartVo goodsItem : checkedGoodsList) { OrderGoodsVo orderGoodsVo = new OrderGoodsVo(); orderGoodsVo.setOrder_id(orderInfo.getId()); orderGoodsVo.setGoods_id(goodsItem.getGoods_id()); orderGoodsVo.setGoods_sn(goodsItem.getGoods_id().toString()); orderGoodsVo.setProduct_id(goodsItem.getProduct_id()); orderGoodsVo.setGoods_name(goodsItem.getGoods_name()); orderGoodsVo.setList_pic_url(goodsItem.getList_pic_url()); orderGoodsVo.setMarket_price(goodsItem.getMarket_price()); orderGoodsVo.setRetail_price(goodsItem.getRetail_price()); orderGoodsVo.setNumber(goodsItem.getNumber()); orderGoodsVo.setGoods_specifition_name_value(goodsItem.getGoods_specifition_name_value()); orderGoodsVo.setGoods_specifition_ids(goodsItem.getGoods_specifition_ids()); orderGoodsVo.setCoupon_id(couponId); apiOrderGoodsMapper.save(orderGoodsVo); } // 清空已购买的商品 apiCartMapper.deleteByCart(loginUser.getUserId(), 1, 1); resultObj.put("errno", 0); resultObj.put("errmsg", "订单提交成功"); // Map<String, OrderVo> orderInfoMap = new HashMap<String, OrderVo>(); orderInfoMap.put("orderInfo", orderInfo); // resultObj.put("data", orderInfoMap); // 优惠券标记已用 if (couponVo != null && couponVo.getCoupon_status() == 1) { couponVo.setCoupon_status(2); apiCouponMapper.updateUserCoupon(couponVo); } } return resultObj; } public void updateStatus(OrderVo vo) { apiOrderMapper.updateStatus(vo); } public List<OrderVo> queryWaitList() { return apiOrderMapper.queryWaitList(); } public List<OrderVo> queryFxList() { return apiOrderMapper.queryFxList(); } }
35.811736
106
0.719192
f80dcb851d28861080f1831d62564b918f1d19a0
2,365
package com.rivescript;/* * Copyright (c) 2016 the original author or authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import com.rivescript.macro.ObjectHandler; import com.rivescript.util.StringUtils; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static com.rivescript.RiveScript.DEFAULT_OBJECT_NOT_FOUND_MESSAGE; /** * @author Noah Petherbridge * @author Marcel Overdijk */ public class ObjectIT extends BaseIT { @Test public void testMacroParsing() { rs = new RiveScript(); rs.setHandler("text", new MockHandler()); setUp(new String[] { "> object hello text", " Hello world!", "< object", "", "> object goodbye javascript", " return \"Goodbye\";", "< object", "", "+ hello", "- <call>hello</call>", "", "+ goodbye", "- <call>goodbye</call>" }); assertReply("Hello", "Hello world!"); assertReply("goodbye", DEFAULT_OBJECT_NOT_FOUND_MESSAGE); } private static class MockHandler implements ObjectHandler { private Map<String, String> codes = new HashMap<>(); @Override public void load(RiveScript rs, String name, String[] code) { codes.put(name, StringUtils.join(code, "\n")); } @Override public String call(RiveScript rs, String name, String[] fields) { return codes.get(name); } } }
31.118421
81
0.711628
eb50c1abc182ca3035471f742e24897ac0bb7f95
4,305
package com.valtanix.demo; import com.timgroup.statsd.NonBlockingStatsDClient; import com.timgroup.statsd.StatsDClient; import io.netty.util.internal.StringUtil; import io.vertx.core.AbstractVerticle; import io.vertx.core.Future; import io.vertx.core.http.HttpServerResponse; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.redis.RedisClient; import io.vertx.redis.RedisOptions; import com.google.common.hash.Hashing; import java.nio.charset.StandardCharsets; /** * Created by kumaran on 3/31/17. */ public class UrlShorteningVertical extends AbstractVerticle{ private final StatsDClient statsd = new NonBlockingStatsDClient("valtanix", "localhost", 8125); Router router = Router.router(vertx); RedisOptions redisConfig = new RedisOptions(); @Override public void start(Future<Void> fut) { RedisClient redis = RedisClient.create(vertx, redisConfig); System.out.println("Redis client "+redis); router.route().handler(BodyHandler.create()); router.route("/status").handler(routingContext -> { HttpServerResponse response = routingContext.response(); response.putHeader("content-type","application/json").setStatusCode(200).end("All is well!"); }); router.get("/get/:key").handler(routingContext->{ long startTime = System.currentTimeMillis(); String key = routingContext.request().getParam("key"); //Getit from post body checkForEmptiness(routingContext, key,"They Key is not found !"); redis.get(key,url -> { if(url.result()!=null) { HttpServerResponse response = routingContext.response(); response.putHeader("content-type", "application/json").setStatusCode(200) .end("The URL requested is " + url.result()); statsd.recordExecutionTimeToNow("url.shortening.expand,result=success",startTime); statsd.incrementCounter("url.shortening.expand"); }else{ HttpServerResponse response = routingContext.response(); response.putHeader("content-type", "application/json").setStatusCode(400) .end("Given Key is not found"); statsd.recordExecutionTimeToNow("url.shortening.expand,result=failure",startTime); } }); statsd.stop(); }); router.post("/put/:url").handler(routingContext -> { long startTime = System.currentTimeMillis(); String urlString = routingContext.request().getParam("url"); //Getit from post body checkForEmptiness(routingContext, urlString,"URL cannot be empty/Null"); String token = getUrlToken(urlString); redis.set(token,urlString,voidAsyncResult -> { HttpServerResponse response = routingContext.response(); response.putHeader("content-type","application/json").setStatusCode(200) .end(new StringBuilder("Successfully shortened the URL :").append(token).toString()); statsd.recordExecutionTimeToNow("url.shortening,result=success",startTime); statsd.incrementCounter("url.shortening,result=success"); }); }); vertx.createHttpServer() .requestHandler(router::accept) .listen(8081 /*config().getInteger("server.port")*/, result -> { if (result.succeeded()) { fut.complete(); } else { fut.fail(result.cause()); } }); } private void checkForEmptiness(RoutingContext routingContext, String url,String errorMsg) { if(StringUtil.isNullOrEmpty(url)){ HttpServerResponse response = routingContext.response(); response.putHeader("content-type","application/json").setStatusCode(400) .end(errorMsg); } } private String getUrlToken(final String urlString) { return String.valueOf(Hashing.murmur3_32().hashString(urlString, StandardCharsets.UTF_8)); } }
43.05
109
0.625087
9ef81ba8dbce5c148b0a55d14708c06ba1e05dd9
949
package com.alertutil.dialog; import android.app.Dialog; import android.content.Context; import android.view.View; import android.view.Window; /** * This class used for the base class of all dialogs in the application. * * @author clickapps */ public class BaseDialog extends Dialog implements View.OnClickListener { /** * Instantiates a new Base dialog. * * @param context the context */ public BaseDialog(Context context) { super(context); hideTitle(); } /** * Instantiates a new Base dialog. * * @param context the context * @param theme the theme */ public BaseDialog(Context context, int theme) { super(context, theme); hideTitle(); } @Override public void onClick(View v) { } /** * hide the dialog title */ private void hideTitle() { requestWindowFeature(Window.FEATURE_NO_TITLE); } }
18.98
72
0.622761
e7d72f9a5ab1b7179adb2d191a20a230b4a32925
3,042
package zj.custom.mybatis; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.support.JdbcUtils; import zj.custom.model.DynamicModel; import zj.custom.model.Metadata; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Map; /** * 自定义rowMapper,返回的是DynamicModel */ public class ColumnDynamicObjectRowMapper implements RowMapper<DynamicModel> { private Metadata metadata; public ColumnDynamicObjectRowMapper() { } public ColumnDynamicObjectRowMapper(Metadata m) { this.metadata = m; } @Override public DynamicModel mapRow(ResultSet rs, int rowNum) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); DynamicModel mapOfColValues = createColumnMap(columnCount); // metadata不为空的时候调用通用查询接口 if (metadata != null) { Map<String, String> code2Key = metadata.getCode2Key(); for (int i = 1; i <= columnCount; i++) { String columnCode = getColumnKey(JdbcUtils.lookupColumnName( rsmd, i)); Object obj = getColumnValue(rs, i); mapOfColValues.put(code2Key.get(columnCode), obj); } } else { for (int i = 1; i <= columnCount; i++) { String key = getColumnKey(JdbcUtils.lookupColumnName(rsmd, i)); Object obj = getColumnValue(rs, i); mapOfColValues.put(key, obj); } } return mapOfColValues; } /** * Create a Map instance to be used as column map. * <p/> * By default, a linked case-insensitive Map will be created. * * @param columnCount the column count, to be used as initial capacity for the Map * @return the new Map instance * @see org.springframework.util.LinkedCaseInsensitiveMap */ protected DynamicModel createColumnMap(int columnCount) { return new DynamicModel(columnCount); } /** * Determine the key to use for the given column in the column Map. * * @param columnName the column name as returned by the ResultSet * @return the column key to use * @see ResultSetMetaData#getColumnName */ protected String getColumnKey(String columnName) { return columnName; } /** * Retrieve a JDBC object value for the specified column. * <p/> * The default implementation uses the {@code getObject} method. * Additionally, this implementation includes a "hack" to get around Oracle * returning a non standard object for their TIMESTAMP datatype. * * @param rs is the ResultSet holding the data * @param index is the column index * @return the Object returned * @see JdbcUtils#getResultSetValue */ protected Object getColumnValue(ResultSet rs, int index) throws SQLException { return JdbcUtils.getResultSetValue(rs, index); } }
32.361702
86
0.648915
6e176c53c7afb4d1c190d615eabc2ed00daf4c53
320
package com.zxsong.mymall; import android.app.Application; import com.facebook.drawee.backends.pipeline.Fresco; /** * Created by zxsong on 2016/2/23. */ public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); Fresco.initialize(this); } }
16
52
0.684375
5f3082268143b955da8230d7ff79e5a0b6b31065
14,387
package com.myth.shishi.activity; import android.content.Context; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.MeasureSpec; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import com.myth.poetrycommon.BaseActivity; import com.myth.poetrycommon.BaseApplication; import com.myth.poetrycommon.activity.ShareEditActivity; import com.myth.poetrycommon.utils.OthersUtils; import com.myth.poetrycommon.utils.ResizeUtils; import com.myth.poetrycommon.utils.StringUtils; import com.myth.poetrycommon.view.CircleImageView; import com.myth.poetrycommon.view.TouchEffectImageView; import com.myth.shishi.R; import com.myth.shishi.db.AuthorDatabaseHelper; import com.myth.shishi.db.PoetryDatabaseHelper; import com.myth.shishi.entity.Author; import com.myth.shishi.entity.Poetry; import java.util.ArrayList; import java.util.Locale; import java.util.Random; public class PoetryActivity extends BaseActivity { private ArrayList<Poetry> mList = new ArrayList<>(); private TextView content; private Poetry poetry; private TextView title; CircleImageView shareView; private Author author; private PopupWindow menu; int[] location; private View menuView; private TouchEffectImageView more; private TextToSpeech mSpeech; private boolean mTTSEnable = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_poetry); mSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { int result = mSpeech.setLanguage(Locale.ENGLISH); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { } else { mTTSEnable = true; mSpeech.setSpeechRate(0.8f); } } } }); setBottomVisible(); mList = PoetryDatabaseHelper.getRandom200(); getRandomPoetry(); initView(); } @Override protected void onDestroy() { if (mSpeech != null) { mSpeech.stop(); mSpeech.shutdown(); } super.onDestroy(); } private int color; private void getRandomPoetry() { poetry = mList.get(new Random().nextInt(mList.size())); author = AuthorDatabaseHelper.getAuthorByName(poetry.author); color = BaseApplication.instance.getRandomColor(); } private void initView() { LinearLayout topView = (LinearLayout) findViewById(R.id.right); LayoutParams param = new LayoutParams( ResizeUtils.getInstance().dip2px(80), ResizeUtils.getInstance().dip2px( 80)); shareView = new CircleImageView(mActivity, color, R.drawable.share3_white); topView.addView(shareView, 1, param); shareView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mActivity, ShareEditActivity.class); intent.putExtra("data", poetry.toWriting()); startActivity(intent); } }); title = (TextView) findViewById(R.id.title); title.setTypeface(BaseApplication.instance.getTypeface()); title.setText(poetry.author); content = (TextView) findViewById(R.id.content); content.setTypeface(BaseApplication.instance.getTypeface()); ((TextView) findViewById(R.id.note)).setTypeface(BaseApplication.instance .getTypeface()); ((TextView) findViewById(R.id.author)).setTypeface(BaseApplication.instance .getTypeface()); title.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mActivity, AuthorPageActivity.class); author.color = color; intent.putExtra("author", author); startActivity(intent); } }); initBottomRightView(); initContentView(); } private void initBottomRightView() { ImageView view = new TouchEffectImageView(mActivity, null); view.setImageResource(R.drawable.random); view.setScaleType(ScaleType.CENTER); addBottomRightView(view); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getRandomPoetry(); refreshRandomView(); } }); more = new TouchEffectImageView(mActivity, null); more.setImageResource(R.drawable.setting); more.setScaleType(ScaleType.FIT_XY); addBottomRightView(more); more.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showMenu(); } }); } @Override protected void onPause() { super.onPause(); if (mSpeech != null) { mSpeech.stop(); } } private void refreshRandomView() { title.setText(poetry.author); setColor(); initContentView(); } private void setColor() { shareView.setColor(color); } private void initContentView() { String note = poetry.intro; ((TextView) findViewById(R.id.note)).setText(note); poetry.title = poetry.title.replaceAll("(.*)", "").trim(); poetry.poetry = poetry.poetry.replaceAll("【.*】", "").trim(); poetry.poetry = StringUtils.autoLineFeed(poetry.poetry); content.setText(poetry.poetry); ((TextView) findViewById(R.id.author)) .setText(poetry.getShowTitle() + "\n"); setTextSize(); } public void isAddTextSize(boolean add) { int size = BaseApplication.getDefaultTextSize(mActivity); if (add) { size += 2; } else { size -= 2; } BaseApplication.setDefaultTextSize(mActivity, size); setTextSize(); } public void setTextSize() { int size = BaseApplication.getDefaultTextSize(mActivity); ((TextView) findViewById(R.id.author)).setTextSize(size); content.setTextSize(size); ((TextView) findViewById(R.id.note)).setTextSize(size - 2); } private void showMenu() { if (menu == null) { LayoutInflater inflater = (LayoutInflater) mActivity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); menuView = inflater.inflate(R.layout.dialog_poetry, null); // PopupWindow定义,显示view,以及初始化长和宽 menu = new PopupWindow(menuView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true); // 必须设置,否则获得焦点后页面上其他地方点击无响应 menu.setBackgroundDrawable(new BitmapDrawable()); // 设置焦点,必须设置,否则listView无法响应 menu.setFocusable(true); // 设置点击其他地方 popupWindow消失 menu.setOutsideTouchable(true); menu.setAnimationStyle(R.style.popwindow_anim_style); // 让view可以响应菜单事件 menuView.setFocusableInTouchMode(true); menuView.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { if (menu != null) { menu.dismiss(); } return true; } return false; } }); location = new int[2]; menuView.findViewById(R.id.tv1).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { isAddTextSize(true); if (menu != null) { menu.dismiss(); } } }); menuView.findViewById(R.id.tv2).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { isAddTextSize(false); if (menu != null) { menu.dismiss(); } } }); TextView collect = (TextView) menuView.findViewById(R.id.tv3); if (PoetryDatabaseHelper.isCollect(poetry.poetry)) { collect.setText("取消收藏"); } else { collect.setText("收藏"); } collect.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { boolean isCollect = PoetryDatabaseHelper.isCollect(poetry.id); PoetryDatabaseHelper.updateCollect(poetry.id, !isCollect); if (isCollect) { Toast.makeText(mActivity, "已取消收藏", Toast.LENGTH_LONG) .show(); } else { Toast.makeText(mActivity, "已收藏", Toast.LENGTH_LONG) .show(); } if (menu != null) { menu.dismiss(); } } }); menuView.findViewById(R.id.tv4).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mActivity, PoetrySearchActivity.class); intent.putExtra("author", author); mActivity.startActivity(intent); if (menu != null) { menu.dismiss(); } } }); menuView.findViewById(R.id.tv5).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { if (menu != null) { menu.dismiss(); } OthersUtils.goBaike(mActivity, poetry.author); } }); menuView.findViewById(R.id.tv6).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { if (menu != null) { menu.dismiss(); } OthersUtils.goBaike(mActivity, poetry.title); } }); menuView.findViewById(R.id.tv7).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { OthersUtils.copy( title.getText() + "\n" + content.getText(), mActivity); Toast.makeText(mActivity, R.string.copy_text_done, Toast.LENGTH_SHORT).show(); if (menu != null) { menu.dismiss(); } } }); menuView.findViewById(R.id.tv8).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { if (mTTSEnable) { mSpeech.speak(poetry.getShowTitle().replaceAll("\\[.*\\]", "").replaceAll("(.*)", "").replaceAll("【.*】", "") + "\n" + poetry.poetry.replaceAll("[\\[\\]0-9]", "").replaceAll("【.*】", ""), TextToSpeech.QUEUE_FLUSH, null); } else { Toast.makeText(mActivity, R.string.tts_unable, Toast.LENGTH_SHORT).show(); } } }); menuView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); int popupWidth = menuView.getMeasuredWidth(); int popupHeight = menuView.getMeasuredHeight(); more.getLocationOnScreen(location); location[0] = location[0] + more.getWidth() / 2 - popupWidth / 2; location[1] = location[1] - popupHeight - ResizeUtils.getInstance().dip2px(20); menu.showAtLocation(more, Gravity.NO_GRAVITY, location[0], location[1]); // 显示在某个位置 } else { TextView collect = (TextView) menuView.findViewById(R.id.tv3); if (PoetryDatabaseHelper.isCollect(poetry.id)) { collect.setText("取消收藏"); } else { collect.setText("收藏"); } menu.showAtLocation(more, Gravity.NO_GRAVITY, location[0], location[1]); } } }
34.01182
243
0.521373
8474a1ee064c12aa847c8962c8047d38d03a5c27
249
package com.lwkandroid.lib.core.imageloader.callback; /** * 下载通用回调 * * @author LWK */ public interface ImageDownLoadCallBack<T> { void onImageDownloadStarted(); void onImageDownloadSuccess(T data); void onImageDownloadFailed(); }
15.5625
53
0.722892
ef7e0559bc4f0e60f66e916804f78b1e659703e1
3,506
package main.com.whitespell.peak.logic.endpoints.authentication; import com.google.gson.Gson; import main.com.whitespell.peak.Server; import main.com.whitespell.peak.StaticRules; import main.com.whitespell.peak.logic.EndpointHandler; import main.com.whitespell.peak.logic.RequestObject; import main.com.whitespell.peak.logic.logging.Logging; import main.com.whitespell.peak.logic.sql.StatementExecutor; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; /** * @author Cory McAn(cmcan), Whitespell LLC * 9/4/2015 */ public class GetDeviceDetails extends EndpointHandler { public static String URL_USER_ID_KEY = "userId"; @Override protected void setUserInputs() { urlInput.put(URL_USER_ID_KEY, StaticRules.InputTypes.REG_INT_REQUIRED); } private static final String RETRIEVE_DEVICE_DETAILS = "SELECT au.`device_uuid`, de.`device_type` FROM `authentication` as au INNER JOIN" + " `device` as de ON au.`device_uuid`=de.`device_uuid` WHERE au.`user_id` = ? AND `expires` != -1 AND `expires` > ? ORDER BY au.`authentication_id` DESC LIMIT 1"; @Override public void safeCall(final RequestObject context) throws IOException { final int userId = Integer.parseInt(context.getUrlVariables().get(URL_USER_ID_KEY)); /** * Retrieve the device details for this user */ try { StatementExecutor executor = new StatementExecutor(RETRIEVE_DEVICE_DETAILS); executor.execute(ps -> { ps.setInt(1, userId); ps.setLong(2, Server.getCalendar().getTimeInMillis()); ResultSet r = ps.executeQuery(); DeviceInfo d = new DeviceInfo(); if (r.next()){ d.setDeviceUUID(r.getString("device_uuid")); d.setDeviceType(r.getInt("device_type")); }else{ context.throwHttpError(this.getClass().getSimpleName(), StaticRules.ErrorCodes.COULD_NOT_RETRIEVE_DEVICE_DETAILS); return; } try { Gson g = new Gson(); String jsonDevice = g.toJson(d); context.getResponse().getWriter().write(jsonDevice); return; } catch (Exception e){ Logging.log("High", e); context.throwHttpError(this.getClass().getSimpleName(), StaticRules.ErrorCodes.UNKNOWN_SERVER_ISSUE); return; } }); } catch (SQLException e) { Logging.log("High", e); context.throwHttpError(this.getClass().getSimpleName(), StaticRules.ErrorCodes.UNKNOWN_SERVER_ISSUE); return; } } public class DeviceInfo { public String getDeviceUUID() { return deviceUUID; } public void setDeviceUUID(String deviceUUID) { this.deviceUUID = deviceUUID; } public String getDeviceName() { return deviceName; } public void setDeviceName(String deviceName) { this.deviceName = deviceName; } public int getDeviceType() { return deviceType; } public void setDeviceType(int deviceType) { this.deviceType = deviceType; } String deviceUUID = null; String deviceName = null; int deviceType = -1; } }
34.372549
173
0.604107
8890d83fce643b07440e8be4b8a04309c063cea7
4,756
/* * Copyright 2015 SIB Visions GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.sibvisions.rad.ui.javafx.ext.animation; import javafx.application.Application; import javafx.geometry.Orientation; import javafx.geometry.Pos; import javafx.scene.PerspectiveCamera; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.control.TitledPane; import javafx.scene.effect.DropShadow; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; import com.sibvisions.rad.ui.javafx.ext.panes.FXFormPane; import com.sibvisions.rad.ui.javafx.ext.panes.FXPositioningPane; public class FXAnimatorTestMain extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { Label frontLabel = new Label("This is the front."); frontLabel.setStyle("-fx-background-color: #8888CC;"); Label backLabel = new Label("This is the darkside."); backLabel.setStyle("-fx-background-color: #CC8888;"); TitledPane flippingPane = new TitledPane("Front", frontLabel); flippingPane.setPrefSize(200, 200); flippingPane.setEffect(new DropShadow()); FXPositioningPane containerPane = new FXPositioningPane(); containerPane.getChildren().add(flippingPane); ComboBox<Pos> positionComboBox = new ComboBox<>(); positionComboBox.getItems().addAll(Pos.values()); positionComboBox.valueProperty().addListener((pObservable) -> { containerPane.move(flippingPane, positionComboBox.getValue()); }); ComboBox<Orientation> orientationComboBox = new ComboBox<>(); orientationComboBox.getItems().addAll(Orientation.values()); orientationComboBox.setValue(Orientation.HORIZONTAL); CheckBox rightLeftTopDownCheckBox = new CheckBox("Right to Left/Top to Down"); rightLeftTopDownCheckBox.setSelected(true); Button flipButton = new Button("Flip"); flipButton.setOnAction((pActionEvent) -> { FXAnimator.flip(flippingPane, orientationComboBox.getValue(), rightLeftTopDownCheckBox.isSelected(), () -> { if (flippingPane.getText().equals("Front")) { flippingPane.setText("Back"); flippingPane.setContent(backLabel); } else { flippingPane.setText("Front"); flippingPane.setContent(frontLabel); } }, null); }); Slider shakeStrengthSlider = new Slider(0, 250, 100); ComboBox<Orientation> orientationShakeComboBox = new ComboBox<>(); orientationShakeComboBox.getItems().addAll(Orientation.values()); orientationShakeComboBox.setValue(Orientation.HORIZONTAL); Button shakeButton = new Button("Shake"); shakeButton.setOnAction((pActionEvent) -> { FXAnimator.shake(flippingPane, orientationShakeComboBox.getValue(), shakeStrengthSlider.getValue(), null); }); FXFormPane controlPane = new FXFormPane(); controlPane.addChild(new Label("Position of group"), controlPane.createConstraint(0, 0)); controlPane.addChild(positionComboBox, controlPane.createConstraint(1, 0)); controlPane.addChild(new Label("Flip Orientation"), controlPane.createConstraint(2, 0)); controlPane.addChild(orientationComboBox, controlPane.createConstraint(3, 0)); controlPane.addChild(rightLeftTopDownCheckBox, controlPane.createConstraint(4, 0)); controlPane.addChild(flipButton, controlPane.createConstraint(5, 0)); controlPane.addChild(new Label("Strength"), controlPane.createConstraint(0, 1)); controlPane.addChild(shakeStrengthSlider, controlPane.createConstraint(1, 1)); controlPane.addChild(orientationShakeComboBox, controlPane.createConstraint(3, 1)); controlPane.addChild(shakeButton, controlPane.createConstraint(5, 1)); BorderPane root = new BorderPane(); root.setPrefSize(640, 480); root.setCenter(containerPane); root.setTop(controlPane); BorderPane.setAlignment(root.getCenter(), Pos.CENTER); PerspectiveCamera camera = new PerspectiveCamera(); camera.setFieldOfView(60); primaryStage.setScene(new Scene(root)); primaryStage.getScene().setCamera(camera); primaryStage.setTitle("JavaFX FXAnimator Test"); primaryStage.show(); } }
36.030303
109
0.75841
a50eacbd384626642d04bd3e0baae4ec7a54776c
1,431
package practice.sets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class PossibleLists { private int[] elements; private int[] op; private List<int[]> possibleList; public PossibleLists(int[] elements) { this.elements = elements; generatePossibleList(); } private void generatePossibleList() { possibleList = new ArrayList<>(1 << elements.length); op = new int[elements.length]; possibleList.add(Arrays.copyOf(op, op.length)); boolean done = false; while (!done) { int i = 0; boolean encounterZero = false; while (!encounterZero) { if (op[i] == 0) { op[i] = 1; encounterZero = true; } else { op[i] = 0; i++; } if (i >= op.length) { encounterZero = true; done = true; } } if (!done) { possibleList.add(Arrays.copyOf(op, op.length)); } } } public void printAllPossibleLists() { List<Integer> result = new ArrayList<>(); for(int[] list : possibleList) { for (int i = 0; i < list.length; i++) { if (list[i] != 0) { result.add(elements[i]); } } System.out.println(result.toString()); result.clear(); } } public static void main(String[] args) { PossibleLists possibleLists = new PossibleLists(new int[]{1, 2, 3, 4}); possibleLists.printAllPossibleLists(); } }
20.442857
74
0.581412
be042f10a080588ed7af52ec6b2ce91a5f65b4c8
1,657
package com.sargis_ohanyan.sargapps.controles; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.scenes.scene2d.p004ui.Skin; import com.badlogic.gdx.scenes.scene2d.p004ui.Touchpad; import com.badlogic.gdx.scenes.scene2d.p004ui.Touchpad.TouchpadStyle; import com.sargis_ohanyan.sargapps.entidades.MuniecoPrincipalE; public class ControlTouchPad { private float anchoX; private MuniecoPrincipalE munieco; private float posX; private float posY; private Skin skin; private TouchpadStyle style; private Touchpad touchpad; public void iniciarTouchPadStyle() { calculosPosicionAnchoAltoPad(); this.skin = new Skin(); this.skin.add("controles/shadedLight01", new Texture("controles/shadedLight01.png")); this.style = new TouchpadStyle(); this.style.knob = this.skin.getDrawable("controles/shadedLight01"); this.touchpad = new Touchpad(10.0f, this.style); this.touchpad.getColor().f85a = 0.3f; this.touchpad.setBounds(this.posX, this.posY, this.anchoX, this.anchoX); } public Touchpad getTouchpad() { return this.touchpad; } public void setInstanceMunieco(MuniecoPrincipalE munieco2) { this.munieco = munieco2; } private void calculosPosicionAnchoAltoPad() { float ancho = (float) Gdx.graphics.getWidth(); float alto = (float) Gdx.graphics.getHeight(); this.posX = ancho / 14.0f; this.posY = alto / 6.0f; this.anchoX = ancho / 3.0f; } public void dispensar() { this.skin.dispose(); this.touchpad.clear(); } }
32.490196
93
0.687387
87c249f1c9ead1a835ecfef0d9229bed04c42a06
2,273
package ca.concordia.jsdeodorant.analysis.module.commonjs; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import com.google.javascript.jscomp.parsing.parser.trees.BinaryOperatorTree; import com.google.javascript.jscomp.parsing.parser.trees.ExpressionStatementTree; import com.google.javascript.jscomp.parsing.parser.trees.ParseTree; import ca.concordia.jsdeodorant.analysis.abstraction.AbstractIdentifier; import ca.concordia.jsdeodorant.analysis.abstraction.Export; import ca.concordia.jsdeodorant.analysis.abstraction.Module; import ca.concordia.jsdeodorant.analysis.abstraction.PlainIdentifier; import ca.concordia.jsdeodorant.analysis.decomposition.AbstractExpression; import ca.concordia.jsdeodorant.analysis.module.PackageExporter; import ca.concordia.jsdeodorant.analysis.util.IdentifierHelper; public class CommonJSExportHelper implements PackageExporter { static Logger log = Logger.getLogger(CommonJSExportHelper.class.getName()); private Module currentModule; private Set<Module> modules; public CommonJSExportHelper(Module module, Set<Module> modules) { this.currentModule = module; this.modules = modules; } public void extract(ParseTree expression) { if (expression instanceof ExpressionStatementTree) { ExpressionStatementTree expressionStatement = expression.asExpressionStatement(); if (expressionStatement.expression instanceof BinaryOperatorTree) if (checkIfLValueIsRequireStatement(expressionStatement.expression.asBinaryOperator())) { //matchModules(); return; } } } private boolean checkIfLValueIsRequireStatement(BinaryOperatorTree binaryOperator) { AbstractIdentifier lValueIdentifier = IdentifierHelper.getIdentifier(binaryOperator.left); if (lValueIdentifier instanceof PlainIdentifier) return false; if (lValueIdentifier.toString().contains("module.exports") || lValueIdentifier.asCompositeIdentifier().getLeftPart().toString().contains("exports")) { PlainIdentifier exportIdentifier = lValueIdentifier.asCompositeIdentifier().getMostRightPart(); Export export = new Export(exportIdentifier.getIdentifierName().replace("'", ""), new AbstractExpression(binaryOperator.right)); currentModule.addExport(export); return true; } return false; } }
42.092593
152
0.816982
7c0c8d60f433285b60e58cbd13e97266ea79c886
1,648
/* * Copyright 2018-2021, ranke (213539@qq.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.klw8.alita.validator.beans; import lombok.Getter; import lombok.Setter; import top.klw8.alita.validator.annotations.*; import top.klw8.alita.validator.annotations.enums.PasswordStrengthLevel; import java.util.List; import java.util.Map; /** * GroupNotEmpty 测试 * 2019/11/5 15:35 */ @Getter @Setter @GroupNotEmpty(value = "默认组里至少要有两个元素不为空", notEmptyCountMin=2) @GroupNotEmpty(value = "group2里至少要有一个元素不为空", groupName="group2") @PasswordGroup(level= PasswordStrengthLevel.VERY_STRONG) public class GroupNotEmptyTestBean { @GroupItem private String str1; @GroupItem private List<String> list1; @GroupItem private Map<String, String> map1; @GroupItem("group2") private String str2; @GroupItem("group2") private List<String> list2; @GroupItem("group2") private Map<String, String> map2; @Password(level= PasswordStrengthLevel.VERY_STRONG) private String pwd; @PasswordGroupItem private String pwd1; @PasswordGroupItem private String pwd2; }
24.969697
75
0.732403
2c1c7153cb572f97b84cf71ab093415df87a8a7d
789
public double XXX(int[] nums1, int[] nums2) { int[] merge = new int[nums1.length + nums2.length]; int i = 0, j = 0, k = 0; while (i < nums1.length && j < nums2.length) { if (nums1[i] <= nums2[j]) { merge[k++] = nums1[i++]; } else { merge[k++] = nums2[j++]; } } while(i < nums1.length) { merge[k++] = nums1[i++]; } while(j < nums2.length) { merge[k++] = nums2[j++]; } double result = 0.0; if (merge.length % 2 != 0) { result = merge[(merge.length - 1) / 2] / 1.0; } else { result = (merge[merge.length / 2 - 1] + merge[merge.length / 2]) / 2.0; } return result; }
30.346154
83
0.404309
145f4459236ab38a0c99ebbc4c417a8c695a5243
877
package easy; import java.util.Scanner; public class FirstUniqueCharacterInAString { public static void main(String[] args) { Scanner s = new Scanner(System.in); String line = s.nextLine(); System.out.println(firstUniqChar(line)); } public static int firstUniqChar(String s) { int[] letters = new int[26]; int index; for (int i = 0; i < 26; i++) letters[i] = Integer.MAX_VALUE; for (int i = 0; i < s.length(); i++) { index = s.charAt(i) - 'a'; letters[index] = (letters[index] == Integer.MAX_VALUE ? i : -1); } index = Integer.MAX_VALUE; for (int i = 0; i < 26; i++) if (letters[i] != Integer.MAX_VALUE && letters[i] != -1) index = Math.min(index, letters[i]); return (index == Integer.MAX_VALUE ? -1 : index); } }
29.233333
76
0.542759
f0f2bf20de39e20c32c84ccf77f951f3929c8ed3
270
package com.indigo.mesosprobe.mesos.beans; public class MesosClientRequest { public enum RequestType{ GET_METRICS, GET_MASTER } private RequestType type; public MesosClientRequest(RequestType type) { this.type = type; } }
16.875
49
0.666667