blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 332 | content_id stringlengths 40 40 | detected_licenses listlengths 0 50 | license_type stringclasses 2
values | repo_name stringlengths 7 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 557
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 77.7k | fork_events_count int64 0 48k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 82
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 7 5.41M | extension stringclasses 11
values | content stringlengths 7 5.41M | authors listlengths 1 1 | author stringlengths 0 161 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7b59259bebfbeb88fa411ac3f760887b5f3580bf | 9ce413bb13af9e596146d1269479c1a5a41f949d | /src/control/Misc/Bite.java | 651934b0f297f4e98d36f39f5ba1d6b01ecbf4d6 | [] | no_license | RedEyedMars/TheFount | 2fef1e9901967b69065bb54933e92eaafc1e5c32 | ee8fd80ce23fbc319cfb299a29e2b0a5db21a152 | refs/heads/master | 2021-01-22T22:56:46.967542 | 2012-12-21T09:04:08 | 2012-12-21T09:04:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,132 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package control.Misc;
import java.util.ArrayList;
import java.util.Collection;
/**
*
* @author Geoff
*/
public class Bite{
byte[] mb;
public static Bite[] psbMvs=new Bite[]{new Bite(new byte[]{0,-1}),new Bite(new byte[]{-1,0}),new Bite(new byte[]{0,1}),new Bite(new byte[]{1,0})};
public Bite(byte[]b){
mb=b;
}
public Bite(Byte[]b){
mb=new byte[b.length];
for(int m=0;m<b.length;m++){
mb[m]=b[m];
}
}
public byte[] add(int i){
byte[] ret=new byte[mb.length];
for(int m=0;m<mb.length;m++){
ret[m]=(byte)(mb[m]+i);
}
return ret;
}
public byte[] add(byte[] i){
byte[] ret=new byte[mb.length];
ret[0]=(byte)(mb[0]+i[0]);
ret[2]=(byte)(mb[2]+i[1]);
return ret;
}
public byte[] mul(int i){
byte[] ret=new byte[mb.length];
for(int m=0;m<mb.length;m++){
ret[m]=(byte)(mb[m]*i);
}
return ret;
}
public byte[] get(){
return mb;
}
public Byte[] teg(){
Byte[] ret=new Byte[mb.length];
for(int m=0;m<mb.length;m++){
ret[m]=(Byte)(mb[m]);
}
return ret;
}
public boolean equals(Object O){
byte[] ob=((Bite)O).mb;
//System.out.println(ob[0]+"=="+mb[0]+"&&"+ob[1]+"=="+mb[1]);
return ob[0]==mb[0]&&ob[1]==mb[1];
}
public static ArrayList<Byte[]> toArray(Collection<Bite> bs){
ArrayList<Byte[]> B=new ArrayList<Byte[]>(bs.size());
for(Bite b:bs){
B.add(b.teg());
}
return B;
}
public String toString(){
String s=new String();
for(Byte b:mb){
s+=b+", ";
}
return s;
}
}
| [
"greg_estouffey@hotmail.com"
] | greg_estouffey@hotmail.com |
6fce09c4689405679719deb50a122bc81bddb361 | e836ea6b9279f5e668602a435bde1cf7048f33e2 | /src/main/java/ru/job4j/email/EmailNotification.java | c7245d0b73abade3191a622a89041fc8b0c86dfc | [] | no_license | k-r-3/job4j_threads | 41e8b657a3a0dc72e5c87645a50eb8f071845352 | 345e5ebed0624eeb9d5e714e1c5ecb8a652365a7 | refs/heads/master | 2023-06-10T10:43:40.746942 | 2021-07-06T11:56:12 | 2021-07-06T11:56:12 | 375,966,332 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,013 | java | package ru.job4j.email;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class EmailNotification {
private final ExecutorService pool = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors()
);
public void emailTo(User user) {
pool.submit(() -> {
String subject = String.format("Notification %s to email %s",
user.getUserName(), user.getEmail());
String body = String.format("Add a new event to %s", user.getUserName());
send(subject, body, user.getEmail());
});
}
public void send(String subject, String body, String email) {
}
public void close() {
pool.shutdown();
while (!pool.isTerminated()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
}
| [
"rke19922802@gmail.com"
] | rke19922802@gmail.com |
3bf10c7aaa2fa2b0cfe39c6e504df5c51bbc7cc4 | f86938ea6307bf6d1d89a07b5b5f9e360673d9b8 | /CodeComment_Data/Code_Jam/train/Standing_Ovation/S/R2015QA.java | 5eab1554662db95e55867a22a6c9fdc7e7a22c19 | [] | no_license | yxh-y/code_comment_generation | 8367b355195a8828a27aac92b3c738564587d36f | 2c7bec36dd0c397eb51ee5bd77c94fa9689575fa | refs/heads/master | 2021-09-28T18:52:40.660282 | 2018-11-19T14:54:56 | 2018-11-19T14:54:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 959 | java | package methodEmbedding.Standing_Ovation.S.LYD840;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
public class R2015QA {
public final static String IN_FILE = "test/R2015QA.in";
public final static String OUT_FILE = "test/R2015QA.out";
private static Scanner IN;
public static void main(String[] args) throws Exception {
InputStream in = new FileInputStream(IN_FILE);
PrintWriter out = new PrintWriter(new FileWriter(OUT_FILE));
IN = new Scanner(in);
int T = IN.nextInt();
IN.nextLine();
for (int t = 1; t <= T; t++) {
int s = IN.nextInt();
char[] S = IN.next().toCharArray();
int m = 0;
int tm = S[0] - '0';
for (int i = 1; i <= s; i++) {
int mm = S[i] - '0';
if (tm < i) {
m += i - tm;
tm += i - tm;
}
tm += mm;
}
out.println("Case #" + t + ": " + m);
}
out.flush();
out.close();
}
}
| [
"liangyuding@sjtu.edu.cn"
] | liangyuding@sjtu.edu.cn |
56ac6d2aabf2281bcbba2591a75840d6be5576f4 | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /java/neo4j/2017/12/LabelScanReader.java | 26826b1fa7554f6360aa31552952de3fb0b5d78d | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | Java | false | false | 1,630 | java | /*
* Copyright (c) 2002-2017 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.storageengine.api.schema;
import org.neo4j.collection.primitive.PrimitiveLongResourceIterator;
import org.neo4j.graphdb.Resource;
/**
* Reader of a label scan store which contains label-->nodes mappings.
*/
public interface LabelScanReader extends Resource
{
/**
* @param labelId label token id.
* @return node ids with the given {@code labelId}.
*/
PrimitiveLongResourceIterator nodesWithLabel( int labelId );
/**
* @param labelIds label token ids.
* @return node ids with any of the given label ids.
*/
PrimitiveLongResourceIterator nodesWithAnyOfLabels( int... labelIds );
/**
* @param labelIds label token ids.
* @return node ids with all of the given label ids.
*/
PrimitiveLongResourceIterator nodesWithAllLabels( int... labelIds );
}
| [
"rodrigosoaresilva@gmail.com"
] | rodrigosoaresilva@gmail.com |
4ce77f396d5b0044b0d3a9f46ba39454f117a860 | f242f5f57355897138f62f9103e04037a382a2f4 | /src/main/java/repositories/TodoRepository.java | b65068a1aef7ef85d3adc2dcdd9eff4d774f2c4d | [] | no_license | lesniewskii/ToDo | 4769161665a51a65ceb511fb516057c33623f62f | 2c444378ef454ade9ff2adfaf74074ce159e17ef | refs/heads/master | 2020-03-12T09:29:04.495816 | 2018-04-24T06:15:29 | 2018-04-24T06:15:29 | 120,769,782 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 291 | java | package repositories;
import models.Todo;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
/**
* Created by Adrian on 8/17/2017.
*/
@Repository
public interface TodoRepository extends MongoRepository<Todo, String>{
}
| [
"adijos126@gmail.com"
] | adijos126@gmail.com |
1bb1c5e485328510d31fe4a076f5c18a9a9a0a6f | a0aeb8b474ab2131a0520e5e13b3e8048c0e4c46 | /src/main/java/com/depromeet/boiledegg/common/utils/random/Digit.java | cf213907938f3937e787e1654f042a8bddd333b4 | [] | no_license | depromeet/7th-final-team10-server | 496ef2b7e6d32d8c0925e4d8e1535aa73d1e6b4d | 5d3cf42e6cd5f08b5f8f7cc1e81261840cc6ecb4 | refs/heads/master | 2020-12-09T02:29:22.585558 | 2020-02-22T04:47:23 | 2020-02-22T04:47:23 | 233,163,422 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 660 | java | package com.depromeet.boiledegg.common.utils.random;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode
public final class Digit {
static final int MIN = 0;
static final int MAX = 9;
private final int value;
private Digit(final int value) {
validate(value);
this.value = value;
}
private void validate(final int value) {
if (MIN > value || value > MAX) {
throw new IllegalArgumentException();
}
}
public static Digit valueOf(final int value) {
return new Digit(value);
}
@Override
public String toString() {
return String.valueOf(value);
}
}
| [
"jaeyeonling@gmail.com"
] | jaeyeonling@gmail.com |
36a0c58502e47587c21fd56c3f8adc8aa0258904 | 29b71940edd98b7e016fcdfee832200ed7803568 | /coumbaD/Exo/Exemple12/src/com/projet/inter/Personne.java | 53577b35d4d0859eeee3a6a5190122806d1b6107 | [] | no_license | manelBHM/java | 257771a08eb49f9003d25fdbdc5b5fe0794f3682 | a5e5e1e91ca5b709360bd2348d357e29a6c24e03 | refs/heads/master | 2022-12-25T07:27:29.668413 | 2019-06-04T08:05:53 | 2019-06-04T08:05:53 | 158,882,973 | 0 | 5 | null | 2022-12-16T00:54:49 | 2018-11-23T22:26:13 | HTML | UTF-8 | Java | false | false | 963 | java | package com.projet.inter;
import java.util.Date;
public class Personne {
private int id;
private String nom;
private String prenom;
private Date dateNais;
private double salaire;
private Profil profil;
public Personne(int id,String nom, String prenom, Date dateNais, double salaire, Profil profil) {
this.setId(id);
this.nom = nom;
this.prenom = prenom;
this.dateNais = dateNais;
this.salaire = salaire;
this.profil = profil;
}
public void afficher() {
System.out.println(" Je suis "+ profil.libelle +""+ nom+ " " +prenom+" je suis né le " + dateNais+ " mon salaire mensuel est de : "+ salaire + " Euros ");
}
public double calculerSalaire() {
if(profil.libelle.equals("DG")) {
salaire += salaire*0.20;
}
else if (profil.libelle.equals("EM")){
salaire=salaire*0.10;
}
return salaire;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}}
| [
"coumba.doucoure@hotmail.fr"
] | coumba.doucoure@hotmail.fr |
59df4b63a05bcc6d91a95f010ff4b2e9c34947bc | 0cd407f6a73c21bbeb52958665fc2872bd25e83b | /java/tasks/welcome-to.java | 3771ea88a42a176d9f71dd489fb73413a17dfe7b | [] | no_license | ikenticus/blogcode | 178c6d99e7805490fbe95417d6e28d1f64b0ce9d | 550b57c46284bb2e47ac23b3984792f3e68d73ea | refs/heads/master | 2023-07-05T09:00:55.780386 | 2023-06-30T02:08:10 | 2023-06-30T02:08:10 | 1,432,663 | 4 | 3 | null | 2023-01-05T17:26:25 | 2011-03-02T22:12:14 | Python | UTF-8 | Java | false | false | 338 | java | // Easy
// https://www.hackerrank.com/challenges/welcome-to-java/problem
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Print output to STDOUT. Your class should be named Solution. */
System.out.println("Hello, World.");
System.out.println("Hello, Java.");
}
}
| [
"ikenticus@gmail.com"
] | ikenticus@gmail.com |
9ef59ba911f5956b20ac52102adaa3931ecdaf15 | b8dfd3c3d0b3fdd54a2cc13149ab3c20bdd67547 | /src/main/java/com/service/impl/BookServiceImpl.java | 899fee7b04e8525f5cf3bce9efd05269e4ccbe2d | [] | no_license | hachieu/LibrarySystem | 589bff52b0ab409cb159d5110012a26600d87c5b | 8ec795d25336958208de692d736958d213cf2e6b | refs/heads/master | 2023-06-25T02:38:51.874591 | 2021-06-07T15:48:29 | 2021-06-07T15:48:29 | 372,874,201 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,781 | java | package com.service.impl;
import com.service.BookService;
import com.domain.Book;
import com.repository.BookRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
/**
* Service Implementation for managing {@link Book}.
*/
@Service
@Transactional
public class BookServiceImpl implements BookService {
private final Logger log = LoggerFactory.getLogger(BookServiceImpl.class);
private final BookRepository bookRepository;
public BookServiceImpl(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
@Override
public Book save(Book book) {
log.debug("Request to save Book : {}", book);
if (book.getId() == null) {
book.setDateCreate(LocalDate.now());
Optional<Book> bookBarCode = bookRepository.findByBookBarCode(book.getBookBarCode());
if (bookBarCode.isPresent()) {
return null;
}
} else {
Optional<Book> BookCaseOptional = bookRepository.findById(book.getId());
book.setDateCreate(BookCaseOptional.get().getDateCreate());
}
book.setDateUpdate(LocalDate.now());
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
book.setUserCreate(authentication.getName());
return bookRepository.save(book);
}
@Override
@Transactional(readOnly = true)
public Page<Book> findAll(Pageable pageable) {
log.debug("Request to get all Books");
return bookRepository.findAll(pageable);
}
@Override
@Transactional(readOnly = true)
public Optional<Book> findOne(Long id) {
log.debug("Request to get Book : {}", id);
return bookRepository.findById(id);
}
@Override
public void delete(Long id) {
log.debug("Request to delete Book : {}", id);
bookRepository.deleteById(id);
}
@Override
public Book findByBookBarCodeAndStatus(String bookBarCode, Integer status) {
Optional<Book> book = bookRepository.findByBookBarCodeAndStatus(bookBarCode, status);
if (book.isPresent()) {
return book.get();
}
return null;
}
@Override
public List<Book> findByBorrowBook(Long id) {
List<Book> books = bookRepository.findByBorrowBook(id);
return books;
}
}
| [
"havanchieu0908@gmail.com"
] | havanchieu0908@gmail.com |
c54efa40b7bea5f8622b2719155e6e450c8958f8 | 9644b214529a5865665173d0405e3e0e81bbc86a | /app/src/main/java/com/example/frederick/journal_app_alc/MainActivity.java | 8f9076a6629bcef0de9c95991986e86c8191205c | [] | no_license | fkmawuli/Journal-App-ALC | e1281115aa610ec86412f4cb236920b39e3fcb09 | ce11ad7209b11f7e7fc8fd2d57196f4b843944ac | refs/heads/master | 2020-03-21T12:25:53.994449 | 2018-06-26T11:27:48 | 2018-06-26T11:27:48 | 138,551,850 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 350 | java | package com.example.frederick.journal_app_alc;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| [
"fkmawuli@gmail.com"
] | fkmawuli@gmail.com |
52678497ae077344131eb82582431c5940c0e261 | 23b1cc8daea9214aa7735fabf9ea6b12da93c3e9 | /beans/src/test/java/fr/univtln/dosso_boudfor/mini_projet_d35/BeansTest.java | 70167ea463bc533a80b03de09c18d8cf8d6390d6 | [] | no_license | saadBoudfor/Mini_projet_D35 | b0a05a1658ce232a54a8587ed945d7cdaddd4808 | d8fda90f3299cd3245027ce6692311bccfdbf1d8 | refs/heads/master | 2021-01-10T04:34:38.336551 | 2016-02-15T23:11:50 | 2016-02-15T23:11:50 | 51,792,303 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 163 | java | package fr.univtln.dosso_boudfor.mini_projet_d35;
/**
* Created by yssouf on 24/12/15.
* @author Dosso
* @author Boudfor
*/
public class BeansTest {
}
| [
"sboudfor@gmail.com"
] | sboudfor@gmail.com |
2b98dfeaad35c524d8508d781120341e39032d59 | 0c878f3b11155f93eabd74faead8281c65aa87c8 | /Web Storage/src/storage/controller/AddStorageElementServlet.java | d435ffe6e206e9c2e2fbc21d8b8f9919da60761a | [] | no_license | yevheniiKravtsov/WebStorage | 20346b251ed7ab70d1743f34a41e2c7e486c30f5 | 633a39d5036f291a3b3de3f5ebcd7477e76f5507 | refs/heads/master | 2022-12-20T10:23:57.427283 | 2020-10-01T11:22:57 | 2020-10-01T11:22:57 | 300,246,710 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,362 | java | package storage.controller;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import storage.DBmanger.ComponentDB;
import storage.DBmanger.StorageDB;
import storage.DBmanger.StorageElementDB;
import storage.entity.Component;
import storage.entity.Storage;
import storage.entity.StorageElement;
/**
* Servlet implementation class AddStorageElementServlet
*/
@WebServlet("/addStorageElement")
public class AddStorageElementServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ArrayList<Storage> storageList = StorageDB.select();
ArrayList<Component> componentList = ComponentDB.select();
request.setAttribute("storageList", storageList);
request.setAttribute("componentList", componentList);
getServletContext().getRequestDispatcher("/addStorageElement.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
Timestamp time = Timestamp.valueOf(LocalDateTime.now());
int numberOfComponents=Integer.valueOf(request.getParameter("numberOfComponents"));
double price = Double.valueOf(request.getParameter("price"));
int componentId = Integer.valueOf(request.getParameter("componentId"));
Component component = ComponentDB.selectOne(componentId);
int storageId=Integer.valueOf(request.getParameter("storageId"));
Storage storage = StorageDB.selectOne(storageId);
StorageElement storageElement= new StorageElement(time, numberOfComponents, price, component, storage);
StorageElementDB.insert(storageElement);
response.sendRedirect(request.getContextPath()+"/main");
}
catch(Exception ex) {
getServletContext().getRequestDispatcher("/addStorageElement.jsp").forward(request, response);
}
}
}
| [
"[y.k.kravtsov96@gmail.com]"
] | [y.k.kravtsov96@gmail.com] |
f495a1e4d0ad02efd30602ca7dd9dce556738f52 | 0a275ec4a9ec8845812e1ef67e7c0f3fb7872699 | /src/main/java/com/drepair/controller/WebsetCotroller.java | 2fa86eb4cb8876497f7abbedbf7c526809aa46a9 | [] | no_license | SongMin90/drepair | 6bf617b90231f449acc27de606eb61eafe735ee1 | 6bdbdaabbab3b3d24a5f0a5431913ec0c84a8c2f | refs/heads/master | 2021-01-23T16:07:36.902077 | 2017-09-30T04:08:39 | 2017-09-30T04:08:48 | 101,524,306 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,018 | java | package com.drepair.controller;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.alibaba.fastjson.JSON;
import com.drepair.po.SqlCustom;
import com.drepair.po.webset.Setting;
import com.drepair.service.SqlService;
import com.drepair.utils.DateTime;
import com.drepair.utils.FileHelper;
import com.drepair.utils.MySQLDatabase;
/**
* 网站设置Cotroller
* @author SongM
* @date 2017年8月30日 上午8:29:17
*/
@Controller
@RequestMapping("webset")
public class WebsetCotroller {
/**
* 报修客户端信息
* @param request
* @return
*/
@RequestMapping(value="getBaoxiuInfo", method={RequestMethod.GET})
public @ResponseBody Map<String, Object> getBaoxiuInfo(HttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>();
double version = Double.parseDouble(read(request).getVersion_baoxiu());
String updateInfo = read(request).getUpdateInfo_baoxiu();
map.put("version", version);
map.put("updateInfo", updateInfo);
return map;
}
/**
* 抢修修客户端信息
* @param request
* @return
*/
@RequestMapping(value="getQiangxiuInfo", method={RequestMethod.GET})
public @ResponseBody Map<String, Object> getQiangxiuInfo(HttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>();
double version = Double.parseDouble(read(request).getVersion_qiangxiu());
String updateInfo = read(request).getUpdateInfo_qiangxiu();
map.put("version", version);
map.put("updateInfo", updateInfo);
return map;
}
/**
* 报修客户端版本
* @param request
* @return
*/
public static String version_baoxiu(HttpServletRequest request) {
return read(request).getVersion_baoxiu();
}
/**
* 报修客户端更新信息
* @param request
* @return
*/
public static String updateInfo_baoxiu(HttpServletRequest request) {
return read(request).getUpdateInfo_baoxiu();
}
/**
* 抢修客户端版本
* @param request
* @return
*/
public static String version_qiangxiu(HttpServletRequest request) {
return read(request).getVersion_qiangxiu();
}
/**
* 抢修客户端更新信息
* @param request
* @return
*/
public static String updateInfo_qiangxiu(HttpServletRequest request) {
return read(request).getUpdateInfo_qiangxiu();
}
/**
* 后台管理导航栏颜色
* @param request
* @return
*/
public static String topbarColor(HttpServletRequest request) {
return read(request).getTopbarColor();
}
/**
* 网站名称
* @param request
* @return
*/
public static String webName(HttpServletRequest request) {
return read(request).getWebName();
}
/**
* 图片存放路径
* @param request
* @return
*/
public static String imgPath(HttpServletRequest request) {
return read(request).getImgPath();
}
@Autowired
private SqlService sqlService;
/**
* 跳转至设置界面
* @param model
* @return
*/
@RequestMapping("setting")
public String setting(HttpServletRequest request, Model model, Integer nowPage, Integer size) {
// 将配置文件的内容发送到页面
Setting setting = read(request);
model.addAttribute("version_baoxiu", setting.getVersion_baoxiu());
model.addAttribute("version_qiangxiu", setting.getVersion_qiangxiu());
model.addAttribute("updateInfo_web", setting.getUpdateInfo_web());
model.addAttribute("web_path", setting.getWeb_path());
model.addAttribute("apkPath", setting.getApkPath());
model.addAttribute("cookieSaveTime", setting.getCookieSaveTime());
model.addAttribute("webName", setting.getWebName());
model.addAttribute("sqlBackupPath", setting.getSqlBackupPath());
model.addAttribute("sqlBackupTime", setting.getSqlBackupTime());
model.addAttribute("isStart_sqlBackup", setting.getIsStart_sqlBackup());
model.addAttribute("imgPath", setting.getImgPath());
model.addAttribute("topbarColor", setting.getTopbarColor());
model.addAttribute("apiState", setting.getApiState());
// 取到数据库的所有备份文件
// 如果当前页为null,默认设为1
if(nowPage == null) {
nowPage = 1;
}
// 如果每页显示大小为null,默认设为10
if(size == null) {
size = 10;
}
try {
Integer allCount = sqlService.findAllCount(); // 取到所有记录数
// 计算出总页数
Integer pageCount = allCount / size;
if((allCount % size) != 0) {
pageCount++;
}
// 分页根据ID降序查询所有sql记录
List<SqlCustom> sqlList = sqlService.findAll(nowPage * size - size, size);
model.addAttribute("sqlList", sqlList);// 将查到的所有sql发送到页面
model.addAttribute("pageCount", pageCount); // 将总页数发送到页面
model.addAttribute("nowPage", nowPage); // 将当前页发送到页面
model.addAttribute("size", size); // 将每页显示大小发送到页面
} catch (Exception e) {
e.printStackTrace();
}
return "../WEB-INF/jsp/webset";
}
/**
* 报修客户端更新版本
* @param attr
* @param file_baoxiu
* @param updateVersion_baoxiu
* @param updateInfo_baoxiu
* @return
*/
@RequestMapping(value="updateBaoxiu", method={RequestMethod.POST})
public String updateBaoxiu(HttpServletRequest request, RedirectAttributes attr, MultipartFile file_baoxiu, String updateVersion_baoxiu, String updateInfo_baoxiu) {
Setting setting = read(request);
// 判断文件夹是否存在,不存在就创建
if(!(new File(setting.getApkPath())).exists()) {
(new File(setting.getApkPath())).mkdir();
}
// 更新文件
try {
setting.setVersion_baoxiu(updateVersion_baoxiu); // 更新版本号
setting.setUpdateInfo_baoxiu(updateInfo_baoxiu); // 更新内容设置
save(setting, request); // 储存
file_baoxiu.transferTo(new File(setting.getApkPath() + "Baoxiu.apk")); // 复制文件
attr.addFlashAttribute("message", "提交更新成功!");
} catch (IOException e) {
attr.addFlashAttribute("message", "服务器出错啦!");
e.printStackTrace();
}
return "redirect:setting";
}
/**
* 抢修客户端更新版本
* @param attr
* @param file_qiangxiu
* @param updateVersion_qiangxiu
* @param updateInfo_qiangxiu
* @return
*/
@RequestMapping(value="updateQiangxiu", method={RequestMethod.POST})
public String updateQiangxiu(HttpServletRequest request, RedirectAttributes attr, MultipartFile file_qiangxiu, String updateVersion_qiangxiu, String updateInfo_qiangxiu) {
Setting setting = read(request);
// 判断文件夹是否存在,不存在就创建
if(!(new File(setting.getApkPath())).exists()) {
(new File(setting.getApkPath())).mkdir();
}
// 更新文件
try {
setting.setVersion_qiangxiu(updateVersion_qiangxiu); // 更新版本号
setting.setUpdateInfo_qiangxiu(updateInfo_qiangxiu); // 更新内容设置
save(setting, request); // 储存
file_qiangxiu.transferTo(new File(setting.getApkPath() + "Qiangxiu.apk")); // 复制文件
attr.addFlashAttribute("message", "提交更新成功!");
} catch (IOException e) {
attr.addFlashAttribute("message", "服务器出错啦!");
e.printStackTrace();
}
return "redirect:setting";
}
/**
* 更新网站
* @param attr
* @param file_web
* @param updateInfo_web
* @return
*/
@RequestMapping(value="updateWeb", method={RequestMethod.POST})
public String updateWeb(HttpServletRequest request, RedirectAttributes attr, MultipartFile file_web, String updateInfo_web) {
Setting setting = read(request);
try {
setting.setUpdateInfo_web(updateInfo_web); // 设置更新内容
save(setting, request); // 储存
file_web.transferTo(new File(setting.getWeb_path())); // 复制文件
Thread.sleep(1000 * 30); // 休眠30秒
attr.addFlashAttribute("message", "提交更新成功!");
} catch (Exception e) {
attr.addFlashAttribute("message", "服务器出错啦!");
e.printStackTrace();
}
return "redirect:setting";
}
/**
* 设置网站信息
* @param attr
* @param webName
* @param cookieSaveTime
* @param web_path
* @return
*/
@RequestMapping(value="setWebInfo", method={RequestMethod.POST})
public String setWebInfo(HttpServletRequest request, RedirectAttributes attr, String webName, int cookieSaveTime, String web_path, String topbarColor) {
try {
// 设置网站信息
Setting setting = read(request);
setting.setTopbarColor(topbarColor);
setting.setWebName(webName);
setting.setCookieSaveTime(cookieSaveTime);
setting.setWeb_path(web_path);
// 储存网站信息
save(setting, request);
attr.addFlashAttribute("message", "保存成功!");
} catch (Exception e) {
attr.addFlashAttribute("message", "服务器出错啦!");
e.printStackTrace();
}
return "redirect:setting";
}
/**
* 数据库定时备份
* @param attr
* @param sqlBackupPath
* @param sqlBackupTime
* @return
*/
@RequestMapping(value="sqlBackup", method={RequestMethod.POST})
public String sqlBackup(HttpServletRequest request, RedirectAttributes attr, final String sqlBackupPath, final int sqlBackupTime) {
Setting setting = read(request);
try {
setting.setSqlBackupPath(sqlBackupPath); // 设置备份地址
setting.setSqlBackupTime(sqlBackupTime); // 设置备份定时
// 判断文件夹是否存在,不存在就创建
if(!(new File(sqlBackupPath)).exists()) {
(new File(sqlBackupPath)).mkdir();
}
// 实例线程
SqlBackupThread thread = new SqlBackupThread(sqlBackupPath, sqlBackupTime, sqlService);
// 判断是启动还是停止
if(setting.getIsStart_sqlBackup().equals("off")) {
// 开启定时备份
setting.setIsStart_sqlBackup("on");
save(setting, request); // 储存
thread.start(); // 启动线程
attr.addFlashAttribute("message", "启动成功!");
} else {
// 关闭定时备份
setting.setIsStart_sqlBackup("off");
save(setting, request); // 储存
// 停止线程
thread.exit(true);
thread.join();
attr.addFlashAttribute("message", "停止成功!");
}
} catch (Exception e) {
attr.addFlashAttribute("message", "服务器出错啦!");
e.printStackTrace();
}
return "redirect:setting";
}
/**
* api设置
* @param request
* @param attr
* @return
*/
@RequestMapping(value="api", method={RequestMethod.POST})
public String api(HttpServletRequest request, RedirectAttributes attr) {
try {
Setting setting = read(request);
String apiState = setting.getApiState();
if(apiState.equals("on")) {
setting.setApiState("off");
attr.addFlashAttribute("message", "停用成功!");
} else {
setting.setApiState("on");
attr.addFlashAttribute("message", "启用成功!");
}
save(setting, request);
} catch (Exception e) {
attr.addFlashAttribute("message", "服务器出错啦!");
e.printStackTrace();
}
return "redirect:setting";
}
/**
* 储存网站信息
* @param setting
* @param request
*/
private void save(Setting setting, HttpServletRequest request) {
String path = "/usr/drepair/set/webset.json";
Object json = JSON.toJSON(setting);
FileHelper.writeUTF8(path, json.toString());
}
/**
* 读取网站信息
* @param request
* @return
*/
public static Setting read(HttpServletRequest request) {
String path = "/usr/drepair/set/webset.json";
String json = FileHelper.readUTF8(path);
return JSON.parseObject(json, Setting.class);
}
}
/**
* 数据库定时备份
* @author SongM
* @date 2017年9月25日 下午3:39:16
*/
class SqlBackupThread extends Thread {
private volatile boolean flag = false;
private int time;
private String sqlBackupPath;
private SqlService sqlService;
public SqlBackupThread(String sqlBackupPath, int time, SqlService sqlService) {
this.time = time;
this.sqlBackupPath = sqlBackupPath;
this.sqlService = sqlService;
}
public void exit(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
while(!flag) {
try {
// 延迟时间
Thread.sleep(time * 1000);
// 设置备份的sql名字
String saveName = DateTime.getDate() + "_" + DateTime.getTime() + ".sql";
// 物理位置储存
new MySQLDatabase().exportDatabaseTool("127.0.0.1", "root", "sa", sqlBackupPath, saveName, "drepair");
// 数据库添加一条记录
SqlCustom sqlCustom = new SqlCustom();
sqlCustom.setSqlPath(saveName);
sqlService.save(sqlCustom);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| [
"13037232106@163.com"
] | 13037232106@163.com |
c5edc1229ca3a51fed4f54f8f7d420fe9982248b | 018a303cb948b87c5191f623efac9e7afb5197c6 | /java/Entities/EntityState.java | 577523885e8524f165a718ce70646e5c2ded01ba | [
"MIT"
] | permissive | benfarhner/gnomebrew | 41beb375ee4b656c19c3e45ab90d29cead5b8a0a | b3ee26b8d8644f0ac2f3e45b6f7f8efcc897fdef | refs/heads/master | 2021-01-01T18:29:13.873934 | 2013-11-13T18:03:25 | 2013-11-13T18:03:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,697 | java | /*
EntityState.java
Represents a single state of an Entity with unique properties.
*/
import java.util.HashSet;
public class EntityState
{
/*
* Properties
*/
private int id;
protected String description;
protected HashSet<Entity.Attribute> attributes;
/*
* Constructors
*/
public EntityState(int id)
{
this(id, "");
}
public EntityState(int id, String description)
{
this.id = id;
this.description = description;
attributes = new HashSet<Entity.Attribute>();
}
public EntityState(EntityState copy)
{
id = copy.id;
description = copy.description;
attributes = new HashSet<Entity.Attribute>(copy.attributes);
}
/*
* Accessors
*/
public int getID()
{
return id;
}
public String getDescription()
{
return description;
}
public boolean hasAttribute(Entity.Attribute attribute)
{
return attributes.contains(attribute);
}
/*
* Mutators
*/
public void addAttribute(Entity.Attribute attribute)
{
attributes.add(attribute);
}
/*
* Public Methods
*/
public boolean equals(Object other)
{
if (other == this)
{
return true;
}
if (!(other instanceof EntityState))
{
return false;
}
return id == ((EntityState)other).id;
}
public int hashCode()
{
return id;
}
public int compareTo(EntityState other)
{
return id - other.id;
}
}
| [
"ben@farhner.com"
] | ben@farhner.com |
81d82ef0ff1c516428be4ad20a8bba89b6b37c82 | 2c267b231f277a4b042fc5a07d7d20e2a378acd1 | /Thread/src/com/training/ReadInfo.java | 06c00d6cd1b386d3b0af39071f0e8d21678a62c6 | [] | no_license | vishaka27/EclipsePractice | 6a83b999dda888fc4db65868227c3d29bb288608 | 8b9527de6df6a54313e33725c37ee31dcee3669b | refs/heads/master | 2021-01-19T05:44:26.795088 | 2016-06-29T11:24:02 | 2016-06-29T11:24:02 | 62,034,605 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 799 | java | /**
*
*/
package com.training;
import java.io.IOException;
/**
* @author vnaga1
*
*/
public class ReadInfo extends Thread {
public void run(){
if(this.isInterrupted())
{
System.out.println("Interrupted");
}
System.out.println("Reading");
try {
System.in.read();
Thread t = new Thread() {
public void run(){
System.out.println("Sleeping for 200 milli sec");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
t.join();
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Finished Reading");
}
}
| [
"vish@gmail.com"
] | vish@gmail.com |
e6f93d63cbfaade3c78c6804f6fc41461589d9cd | 6c307005ba708fcfedab9180e70035481447f5c0 | /Module4/10_Session_cookie/thuc_hanh/views_counting/src/test/java/com/views_counting/ViewCountingApplicationTests.java | 6df79f4715ee55a28e21afb0c051be8e9f18b344 | [] | no_license | baongoc093254/C1020G1-LePhuocThanhCao | 37b233daff22015300da9c86b7517b7ea141aed0 | 89ecd6a52b236cd59988e90bc44e2867a1e5851b | refs/heads/main | 2023-04-09T17:16:42.112164 | 2021-04-03T23:45:57 | 2021-04-03T23:45:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 225 | java | package com.views_counting;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ViewCountingApplicationTests {
@Test
void contextLoads() {
}
}
| [
"hathaykhongbanghayhat18@gmail.com"
] | hathaykhongbanghayhat18@gmail.com |
88eb9ffa33852dc72f075c28bea20756aae9ba63 | 0853a6eeb1708fb475014782050eb35a36fb4ef7 | /src/main/java/project/Traffic_type.java | bb776f16d6a551e04cec831cc420fb57a0e8c13c | [] | no_license | michalbarczyk/moral-dilema-detector | 400a3a2c183babfa987a788a6b0c13001e9941e7 | 701401d5a6748b681340ba3f956b6d016d0f2299 | refs/heads/master | 2022-11-15T22:58:56.441639 | 2020-06-29T13:32:25 | 2020-06-29T13:32:25 | 277,850,652 | 0 | 0 | null | 2020-07-07T15:13:41 | 2020-07-07T15:13:40 | null | UTF-8 | Java | false | false | 2,738 | java | package project;
import java.net.URI;
import java.util.Collection;
import javax.xml.datatype.XMLGregorianCalendar;
import org.protege.owl.codegeneration.WrappedIndividual;
import org.semanticweb.owlapi.model.OWLNamedIndividual;
import org.semanticweb.owlapi.model.OWLOntology;
/**
*
* <p>
* Generated by Protege (http://protege.stanford.edu). <br>
* Source Class: Traffic_type <br>
* @version generated on Mon Jun 29 13:39:07 CEST 2020 by kamsz
*/
public interface Traffic_type extends Traffic_code {
/* ***************************************************
* Property http://webprotege.stanford.edu/traffic_code_has
*/
/**
* Gets all property values for the traffic_code_has property.<p>
*
* @returns a collection of values for the traffic_code_has property.
*/
Collection<? extends Traffic_type> getTraffic_code_has();
/**
* Checks if the class has a traffic_code_has property value.<p>
*
* @return true if there is a traffic_code_has property value.
*/
boolean hasTraffic_code_has();
/**
* Adds a traffic_code_has property value.<p>
*
* @param newTraffic_code_has the traffic_code_has property value to be added
*/
void addTraffic_code_has(Traffic_type newTraffic_code_has);
/**
* Removes a traffic_code_has property value.<p>
*
* @param oldTraffic_code_has the traffic_code_has property value to be removed.
*/
void removeTraffic_code_has(Traffic_type oldTraffic_code_has);
/* ***************************************************
* Property http://webprotege.stanford.edu/traffic_type_is
*/
/**
* Gets all property values for the traffic_type_is property.<p>
*
* @returns a collection of values for the traffic_type_is property.
*/
Collection<? extends Left_hand_traffic> getTraffic_type_is();
/**
* Checks if the class has a traffic_type_is property value.<p>
*
* @return true if there is a traffic_type_is property value.
*/
boolean hasTraffic_type_is();
/**
* Adds a traffic_type_is property value.<p>
*
* @param newTraffic_type_is the traffic_type_is property value to be added
*/
void addTraffic_type_is(Left_hand_traffic newTraffic_type_is);
/**
* Removes a traffic_type_is property value.<p>
*
* @param oldTraffic_type_is the traffic_type_is property value to be removed.
*/
void removeTraffic_type_is(Left_hand_traffic oldTraffic_type_is);
/* ***************************************************
* Common interfaces
*/
OWLNamedIndividual getOwlIndividual();
OWLOntology getOwlOntology();
void delete();
}
| [
"kamsza@onet.pl"
] | kamsza@onet.pl |
f965f379bbe57dd233e05999ba04318a636b8a85 | 60ca7216bb02425588ddb873811ad3715fa89a77 | /org.knopflerfish.eclipse.core.ui/src/org/knopflerfish/eclipse/core/ui/assist/BuildPathCompletionProposal.java | a77c1d6e5af80f1aa6d2c1b1b2b6c3a93c118994 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | knopflerfish/eclipse.knopflerfish.org | 3dede1d8f02bcfebc9792530810df4e46a37b145 | 59a5b1ff05465e5bdb1f438db134a7c895865673 | refs/heads/master | 2021-01-10T08:29:06.926311 | 2017-09-11T22:46:44 | 2017-09-11T22:46:44 | 47,396,810 | 0 | 0 | null | null | null | null | ISO-8859-2 | Java | false | false | 5,662 | java | /*
* Copyright (c) 2003-2010, KNOPFLERFISH project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the KNOPFLERFISH project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.knopflerfish.eclipse.core.ui.assist;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.ui.ISharedImages;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.knopflerfish.eclipse.core.project.BuildPath;
import org.knopflerfish.eclipse.core.project.BundleProject;
import org.knopflerfish.eclipse.core.project.classpath.FrameworkContainer;
import org.knopflerfish.eclipse.core.ui.OsgiUiPlugin;
import org.osgi.framework.Version;
/**
* @author Anders Rimén, Makewave
* @see http://www.makewave.com/
*/
public class BuildPathCompletionProposal implements IJavaCompletionProposal {
private final BundleProject bundleProject;
private final BuildPath buildPath;
public BuildPathCompletionProposal(BundleProject bundleProject,
BuildPath buildPath)
{
this.bundleProject = bundleProject;
this.buildPath = buildPath;
this.buildPath.getPackageDescription().setVersion(Version.emptyVersion);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jdt.ui.text.java.IJavaCompletionProposal#getRelevance()
*/
public int getRelevance()
{
if (buildPath.getContainerPath().toString()
.equals(FrameworkContainer.CONTAINER_PATH)) {
return 20;
}
return 10;
}
/****************************************************************************
* org.eclipse.jface.text.contentassist.ICompletionProposal methods
***************************************************************************/
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.text.contentassist.ICompletionProposal#apply(org.eclipse
* .jface.text.IDocument)
*/
public void apply(IDocument document)
{
try {
bundleProject.addBuildPath(buildPath, true);
} catch (CoreException e) {
OsgiUiPlugin.log(e.getStatus());
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.text.contentassist.ICompletionProposal#getSelection(org
* .eclipse.jface.text.IDocument)
*/
public Point getSelection(IDocument document)
{
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#
* getAdditionalProposalInfo()
*/
public String getAdditionalProposalInfo()
{
StringBuffer info = new StringBuffer();
info.append("The package ");
info.append(buildPath.getPackageDescription().getPackageName());
info.append(" will be added to this projects classpath and also added to the");
info.append(" Import-Package header in the bundle manifest");
return info.toString();
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.text.contentassist.ICompletionProposal#getDisplayString()
*/
public String getDisplayString()
{
StringBuffer info = new StringBuffer("Import package ");
info.append(buildPath.getPackageDescription().getPackageName());
if (buildPath.getContainerPath().toString()
.equals(FrameworkContainer.CONTAINER_PATH)) {
info.append(" from framework");
} else {
info.append(" from bundle ");
info.append(buildPath.getBundleIdentity().getSymbolicName()
.getSymbolicName());
}
return info.toString();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#getImage()
*/
public Image getImage()
{
return JavaUI.getSharedImages().getImage(
ISharedImages.IMG_OBJS_EXTERNAL_ARCHIVE);
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jface.text.contentassist.ICompletionProposal#getContextInformation
* ()
*/
public IContextInformation getContextInformation()
{
return null;
}
}
| [
"ar@6b03482b-4ef8-0310-878d-8b81e9ef6eed"
] | ar@6b03482b-4ef8-0310-878d-8b81e9ef6eed |
9642e0bfc19cea6ef07daf5cde77b9031c46ec57 | b1c23163a1ceb913ea66f7a409993e64eecbb2a0 | /src/main/java/com/exploringcn/reactive/exceptionhandling/ExceptionHandlingExample.java | 74e0210473689a520631b413901e988995b3176e | [] | no_license | exploringcn21/exploring-java-reactive | 363f460fd1593e0e34b50e80b0925127d669cffe | ea8ea3ef69e83ed2ed601ce5f84ee2d20eee1f19 | refs/heads/master | 2023-08-01T04:10:33.404532 | 2021-09-15T22:19:10 | 2021-09-15T22:19:10 | 399,209,922 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,197 | java | package com.exploringcn.reactive.exceptionhandling;
import reactor.core.publisher.Flux;
public class ExceptionHandlingExample {
public Flux<Integer> exceptionFluxDemo(){
return Flux.just(1,4,2,0,5,3)
.map(integer -> 60/integer)
.log();
}
// useful in cases where a fallback value is needed while processing a flux of elements
public Flux<Integer> demoOnErrorReturn(){
return Flux.just(1,4,2,0,5,3)
.map(integer -> 60/integer)
.onErrorReturn(60) // catch exception & provide a single fallback value
.log();
}
public Flux<Integer> demoOnErrorResumeConditionalRecovery(){
Flux<Integer> recoveryFluxOption1 = Flux.just(100,101,102);
Flux<Integer> recoveryFluxOption2 = Flux.just(200,201,202);
return Flux.just(1,4,2,0,5,3)
.map(integer -> 60/integer)
.onErrorResume(e -> {
if (e instanceof ArithmeticException)
return recoveryFluxOption1;
else
return recoveryFluxOption2;
})
.log();
}
public Flux<Integer> demoOnErrorContinue(){
return Flux.just(1,4,2,0,5,3)
.map(integer -> 60/integer)
.onErrorContinue((ex, item) -> System.out.println("Element " + item + " caused the exception: " + ex.getMessage()))
.log();
}
public Flux<String> demoOnErrorMap(){
return Flux.just("apple", "mango", "capsicum", "strawberry", "tulip", "pear")
.map(fruit -> {
if (fruit.equals("capsicum"))
throw new IllegalStateException("No vegetables can be processed");
if (fruit.equals("tulip"))
throw new IllegalStateException("No flowers can be processed");
return fruit.toUpperCase();
})
.onErrorMap(ex -> {
System.err.println(ex.getMessage());
return new RuntimeException(ex.getMessage());
})
.log();
}
}
| [
"exploringcn21@gmail.com"
] | exploringcn21@gmail.com |
5687ae09cc75d7e59bf3342655d88a99db40bdab | 4093236855e0a21b0a5d0699cfa1dc93bb667f0f | /OONumericalMethodsAsGiven/Java/DhbIterations/IterativeProcess.java | ba0663b49946eae84d0d2ce32d9ec174feb1430f | [] | no_license | SquareBracketAssociates/ArchiveOONumericalMethods | 2a29f1c2434f7a4bc14d3b5d0c2f4273cc9ccf8d | 0bb4ce7aa50478af8a66cf9327f1d6130ee56eb7 | refs/heads/master | 2020-12-24T13:21:15.590684 | 2015-02-05T12:46:40 | 2015-02-05T12:46:40 | 29,548,727 | 8 | 11 | null | null | null | null | UTF-8 | Java | false | false | 3,135 | java | \begin{verbatim}
package DhbIterations;
import DhbFunctionEvaluation.DhbMath;
/**
* An iterative process is a general structure managing iterations.
*
* @author Didier H. Besset
*/
public abstract class IterativeProcess
{
/**
* Number of iterations performed.
*/
private int iterations;
/**
* Maximum allowed number of iterations.
*/
private int maximumIterations = 50;
/**
* Desired precision.
*/
private double desiredPrecision = DhbMath.defaultNumericalPrecision();
/**
* Achieved precision.
*/
private double precision;
/**
* Generic constructor.
*/
public IterativeProcess() {
}
/**
* Performs the iterative process.
* Note: this method does not return anything because Java does not
* allow mixing double, int, or objects
*/
public void evaluate()
{
iterations = 0;
initializeIterations();
while ( iterations++ < maximumIterations )
{
precision = evaluateIteration();
if ( hasConverged() )
break;
}
finalizeIterations();
}
/**
* Evaluate the result of the current interation.
* @return the estimated precision of the result.
*/
abstract public double evaluateIteration();
/**
* Perform eventual clean-up operations
* (mustbe implement by subclass when needed).
*/
public void finalizeIterations ( )
{
}
/**
* Returns the desired precision.
*/
public double getDesiredPrecision( )
{
return desiredPrecision;
}
/**
* Returns the number of iterations performed.
*/
public int getIterations()
{
return iterations;
}
/**
* Returns the maximum allowed number of iterations.
*/
public int getMaximumIterations( )
{
return maximumIterations;
}
/**
* Returns the attained precision.
*/
public double getPrecision()
{
return precision;
}
/**
* Check to see if the result has been attained.
* @return boolean
*/
public boolean hasConverged()
{
return precision < desiredPrecision;
}
/**
* Initializes internal parameters to start the iterative process.
*/
public void initializeIterations()
{
}
/**
* @return double
* @param epsilon double
* @param x double
*/
public double relativePrecision( double epsilon, double x)
{
return x > DhbMath.defaultNumericalPrecision()
? epsilon / x: epsilon;
}
/**
* Defines the desired precision.
*/
public void setDesiredPrecision( double prec )
throws IllegalArgumentException
{
if ( prec <= 0 )
throw new IllegalArgumentException
( "Non-positive precision: "+prec);
desiredPrecision = prec;
}
/**
* Defines the maximum allowed number of iterations.
*/
public void setMaximumIterations( int maxIter)
throws IllegalArgumentException
{
if ( maxIter < 1 )
throw new IllegalArgumentException
( "Non-positive maximum iteration: "+maxIter);
maximumIterations = maxIter;
}
}
\end{verbatim} | [
"stephane.ducasse@inria.fr"
] | stephane.ducasse@inria.fr |
cd864638be816f30c9ec42916ffd4e5025c25d79 | 367f06b7929571b8a1297f03e648be0d339175bc | /src/main/java/home/spring/ioc/exercises/third/MessagingManager.java | fe812db8710a807d5b108065d565c0be7c15d81c | [] | no_license | chuongnn/spring-ioc-exercises | 62d52b0c20c24ce67afecfe27d926275d2281e71 | 8f67b50232103ec8365398361fdb3062389a2a58 | refs/heads/master | 2021-01-10T13:38:41.272518 | 2015-12-31T09:50:37 | 2015-12-31T09:50:37 | 48,739,008 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 436 | java | package home.spring.ioc.exercises.third;
public class MessagingManager extends Bean {
private CacheManager cacheManager;
private DatabaseManager databaseManager;
public MessagingManager(int lifeCyclePhase, CacheManager cacheManager, DatabaseManager databaseManager) {
super(lifeCyclePhase, MessagingManager.class);
this.cacheManager = cacheManager;
this.databaseManager = databaseManager;
}
}
| [
"chuong.nguyen@chuongs-MacBook-Pro.local"
] | chuong.nguyen@chuongs-MacBook-Pro.local |
a7627adc840361afdf913f9c9937e2374a3d9542 | 7d21aa88a852811bcb1378786aab3c1778edd031 | /src/main/java/com/sadman/medicalinventory/model/Sale.java | 28327f49a46e1894741289971a7fd3235ba17d72 | [
"MIT"
] | permissive | imran110219/Medical-Inventory | dbd7599b8513e6351e37ec9a940ece72a94808af | 05b49fb280f120c734f13a1b4cd5a057043c843f | refs/heads/develop | 2023-06-27T08:36:00.199644 | 2021-08-02T17:34:13 | 2021-08-02T17:34:13 | 328,570,967 | 1 | 1 | null | 2021-08-02T17:35:43 | 2021-01-11T06:36:42 | JavaScript | UTF-8 | Java | false | false | 854 | java | package com.sadman.medicalinventory.model;
import lombok.*;
import javax.persistence.*;
import java.util.Date;
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "sale")
public class Sale {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne(cascade = CascadeType.MERGE)
@JoinColumn(name = "sale_invoice_id")
private SaleInvoice saleInvoice;
@OneToOne(cascade = CascadeType.MERGE)
@JoinColumn(name = "stock_id")
private Stock stock;
@Column(name = "discount")
private double discount;
@Column(name = "quantity")
private double quantity;
@Column(name = "unit_price")
private double unitPrice;
@Column(name = "total")
private double total;
@Column(name = "datetime", insertable=false)
private Date date;
}
| [
"imran110219@gmail.com"
] | imran110219@gmail.com |
aadefc4f8923e41b70613bde34294e503151bc28 | dc7926be32ed8a3daa8a8064715146f91dda1f5a | /ArrayGeeks/src/arrayGeeks/Q8.java | 48121076d6cb3c0c5890afe6fa5af336585431be | [] | no_license | alarya/JavaDataStructures | f7bc969c5f8afe47c2b10c044272000447de7a4d | 40bb9c4a63b0c126f0660b197579e1eb6adf7b89 | refs/heads/master | 2016-08-12T06:59:55.738337 | 2015-05-28T22:55:36 | 2015-05-28T22:55:36 | 36,469,143 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,580 | java | /*
* Median of two sorted arrays
*
* There are 2 sorted arrays A and B of size n each. Write an algorithm to find the median
* of the array obtained after merging the above 2 arrays(i.e. array of length 2n).
* The complexity should be O(log(n))
*/
package arrayGeeks;
public class Q8 {
public static int getMedian1(int[] arr1, int[] arr2){
if(arr1.length == 0)
return arr2[(arr2.length-1)/2 ];
if(arr2.length == 0)
return arr1[(arr1.length-1) /2];
int mid = ((arr1.length-1) + (arr2.length-1)) / 2 ;
int[] mergeArray = new int[arr1.length + arr2.length];
int i = 0, j = 0, k = 0 ;
while(i < arr1.length && j < arr2.length){
if(arr1[i] < arr2[j])
{
mergeArray[k++] = arr1[i++];
}
else
mergeArray[k++] = arr2[j++];
}
return mergeArray[mid];
}
public static int getMedian2(int[] arr1, int[] arr2, int low1, int high1, int low2, int high2)
{
int mid1 = low1 + high1 ;
int mid2 = low2 + high2 ;
if(high1 - low1 == 1)
return
if(arr1[mid1] < arr2[mid2])
{
return getMedian2(arr1,arr2,mid1+1,high1,low2 * 2, mid2);
}
else
return getMedian2(arr1,arr2,low1,mid1-1,mid2+1,high2);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr1[] = {1, 12, 15, 26, 38};
int arr2[] = {2, 13, 17, 30, 45};
System.out.println("Result: " + getMedian1(arr1,arr2));
int arr3[] = {1, 2, 4, 5, 6};
int arr4[] = {7, 8, 9};
System.out.println("Result: " + getMedian1(arr3,arr4));
}
}
| [
"buntyalok06@gmail.com"
] | buntyalok06@gmail.com |
21519da9da34e224f7d2b4b8fce0475645bcb333 | e49cdc708624373dde60bb3cc6b3af5d78625538 | /java/bw.zqgame.com/com/zqgame/mappers/VotingDao.java | ff6833b9e975488258708fddaeb65b053300932a | [] | no_license | panguixiang/zqgame-springmvc-maven | 5e90387286604d506cb71e9853867f96b6195c02 | 60eca334ac98b61979af591f10a9d666978c2e45 | refs/heads/master | 2016-09-05T10:02:33.832125 | 2015-03-10T07:35:45 | 2015-03-10T07:35:45 | 31,944,158 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 540 | java | package com.zqgame.mappers;
import org.apache.ibatis.annotations.Param;
import com.zqgame.models.Voting;
/**
* 新闻评价Mapper
* @author panguixiang
*
*/
public interface VotingDao {
/**
* 添加新闻评价
* @param voting
*/
public void save(@Param("voting") Voting voting);
/**
* 修改新闻评价
* @param voting
*/
public void update(@Param("voting") Voting voting);
/**
* 根据新闻Id查询此新闻评价信息
* @param artId
*/
public Voting getVotingByArtId(@Param("artId") Long artId);
}
| [
"yuanleike@163.com"
] | yuanleike@163.com |
90feabf479756cf83f7815fae732f7f2f454b8e9 | dab945db8541c30011771caf8ddb63ec8c683618 | /src/com/osp/ide/internal/ui/MakePackageDialog.java | eaf185fadd047624cf7c29fcf1e45b2a2bc3e65b | [] | no_license | romanm11/bada-SDK-1.0.0-com.osp.ide | feb25cd9727e5f746cf618c752f933ca4a4ab61c | cd051d031310457a90eb558212b6c93b62b4dbf0 | refs/heads/master | 2020-04-06T04:20:24.837952 | 2010-10-27T18:46:27 | 2010-10-27T18:46:27 | 1,132,307 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 44,101 | java | package com.osp.ide.internal.ui;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.core.settings.model.ICConfigurationDescription;
import org.eclipse.cdt.core.settings.model.ICProjectDescription;
import org.eclipse.cdt.managedbuilder.core.IConfiguration;
import org.eclipse.cdt.managedbuilder.core.IManagedBuildInfo;
import org.eclipse.cdt.managedbuilder.core.ITool;
import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager;
import org.eclipse.cdt.managedbuilder.macros.BuildMacroException;
import org.eclipse.cdt.managedbuilder.macros.IBuildMacroProvider;
import org.eclipse.cdt.utils.ui.controls.ControlFactory;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text; //import org.eclipse.ui.internal.ide.dialogs.ResourceTreeAndListGroup;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.ide.DialogUtil;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import com.osp.ide.IConstants;
import com.osp.ide.core.AppXmlStore;
import com.osp.ide.core.badaNature;
import com.osp.ide.utils.FileUtil;
public class MakePackageDialog extends TitleAreaDialog {
IContainer fContainer;
protected IProject fProject = null;
protected boolean noContentOnPage = false;
protected IConfiguration[] cfgDescs = null;
private IConfiguration currentConfig = null;
private String buildTargetName = "";
private String buildTargetExt = "";
// private String targetExePath="";
private ResourceTreeAndListGroup resourceGroup;
protected Combo configSelector;
protected Text textOutFolder;
protected Text textPkgName;
// protected Button checkSecurity;
Button makeButton = null;
boolean makeButtonEnabled = false;
IFolder folderIcon = null;
String libExt = IConstants.EXT_SO;
PackageData packageData;
MakePackageHelper helper;
String outFilePath;
boolean bFileCheckError = false;
String fileCheckErrorMag = "";
Composite parent;
static int MANIFEST_CHECK_TRUE = 0; // manifest.xml 파일 서버와 동일
static int MANIFEST_CHECK_FALSE = 1; // manifest.xml 파일 서버와 다름
static int MANIFEST_CHECK_OFFLINE = 2; // manifest.xml 파일 서버와 연결이 않됨
static int MANIFEST_CHECK_NOTFOUND = 3; // manifest.xml 동일한 id를 서버에서 찾을 수 없음
static int MANIFEST_CHECK_USERCANCEL = 4;// User cancel
static final String ERR_MSG_MANIFEST_CHECK_FALSE = "Invalid Manifest file.";
static final String ERR_MSG_MANIFEST_CHECK_OFFLINE = "Server Off-line.";
static final String ERR_MSG_MANIFEST_CHECK_NOTFOUND = "Id Not Found.";
static final String ERR_MSG_MANIFEST_CHECK_USERCANCEL = "User Cancel.";
public Combo getConfigSelector() {
return configSelector;
}
protected class CheckManifestOperaton implements IRunnableWithProgress {
IProject project;
String surl;
int result = MANIFEST_CHECK_OFFLINE;
public CheckManifestOperaton(String sUrl) {
this.surl = sUrl;
}
public int getResult() {
return result;
}
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
// TODO Auto-generated method stub
monitor.beginTask("Check Manifest...", -1);
URL url;
try {
url = new URL(surl);
URLConnection conn = url.openConnection();
HttpURLConnection hurl = (HttpURLConnection) conn;
hurl.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
hurl.setRequestMethod("POST");
hurl.setDoOutput(true);
hurl.setDoInput(true);
hurl.setUseCaches(false);
hurl.setDefaultUseCaches(false);
boolean flag = false; // 서버가 접속이 되었는지 되지 않았는지 체크합니다.
String cookie = null; // 서버에서 받은 답의0번 헤더를 가져옵니다.
String bufferline = null; // 서버에서 받은 답변을 buffer에서 한줄 씩 가져오기 위한
// 문자열입니다.
String manifestvalid = ""; // 서버에서 받은 답변의 바디 부분을 모은 문자열입니다.
String onlinecheck = ""; // 현재 서버가 접속이 되었는지 되지 않았는지 체크하기 위해 0번
// 헤더의
// 토큰을 하나씩 비교하기 위한 문자열입니다.
cookie = conn.getHeaderField(0);
StringTokenizer stk = new StringTokenizer(cookie, " "); // 가져온
// 0번
// 헤더의
// 토큰을
// " "
// 으로
// 구분합니다.
while (stk.hasMoreElements()) {
String str1 = stk.nextToken();
if (str1.equals("200")) {
flag = !flag;
}
}
BufferedReader in = new BufferedReader(new InputStreamReader(
hurl.getInputStream()));
while ((bufferline = in.readLine()) != null) {
manifestvalid = manifestvalid.concat(bufferline);
}
// System.out.println(str2); // 받아온 문서의 내용 테스트 용입니다.
// System.out.println(flag);
if (flag == false) { // 서버의 응답이 200이 아닌 경우입니다.
result = MANIFEST_CHECK_OFFLINE;
monitor.done();
return;
} else if (manifestvalid.equals("true")) { // 서버가 접속 되어 있으며
// manifest.xml이 서버와
// 동일한 경우
result = MANIFEST_CHECK_TRUE;
monitor.done();
return;
} else if (manifestvalid.equals("false")) { // 서버도 접속 되지 않고
// manifest.xml도 서버와
// 다른 경우
result = MANIFEST_CHECK_FALSE;
monitor.done();
return;
} else if (manifestvalid.equals("NotFound")) { // 서버에서 동일한 id의
// manifest.xml을
// 찾을 수 없는 경우
result = MANIFEST_CHECK_NOTFOUND;
monitor.done();
return;
}
// 받아오는 헤더의 정보가 아닌 바디의 정보가
// true/false의 값으로 넘어오기 때문에 더이상
// 헤더는 필요 없습니다.
// boolean flag = false; // 문자열을 비교하여 바로 true/false를 반환 합니다.
// String cookie = null;
// String str3 = "";
// cookie = conn.getHeaderField(0);
// StringTokenizer stk = new StringTokenizer(cookie, " ");
// while(stk.hasMoreElements())
// {
// String str1 = stk.nextToken();
// if(str1.equals("200")){
// flag = !flag;
// }
// }
// System.out.println(cookie); // 0번 헤더 내용 출력
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
} catch (Exception e) {
}
if (monitor.isCanceled())
result = MANIFEST_CHECK_USERCANCEL;
else
result = MANIFEST_CHECK_OFFLINE; // 페이지가 존재하지 않는 경우입니다.
// 위의 try/catch문에서 NullPointExeption이 불려옵니다.
// 때문에 Exception을 통해서 try문을 무시하게 됩니다.
monitor.done();
}
}
public MakePackageDialog(Shell parentShell, IContainer container) {
super(parentShell);
// TODO Auto-generated constructor stub
fContainer = container;
helper = new MakePackageHelper(container);
packageData = new PackageData();
// helper.setPackageData(packageData);
}
public void create() {
// TODO Auto-generated method stub
setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE);
super.create();
if (noContentOnPage)
getShell().setSize(450, 400);
updateWidgetEnablements();
}
@Override
protected void configureShell(Shell newShell) {
// TODO Auto-generated method stub
super.configureShell(newShell);
newShell.setText("Make Package");
}
protected Control createDialogArea(Composite parent) {
this.parent = parent;
Composite composite = (Composite) super.createDialogArea(parent);
((GridLayout) composite.getLayout()).numColumns = 1;
Composite compArea = new Composite(composite, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
layout.marginHeight = 10;
layout.verticalSpacing = 10;
compArea.setLayout(layout);
compArea.setLayoutData(new GridData(GridData.FILL_BOTH));
String s = null;
if (!checkElement()) {
s = "This element not a project";
} else {
fProject = getProject();
if (!isBadaProject(fProject))
s = "This project is not a bada project"; //$NON-NLS-1$
// if( !isManifestFileValid(fProject))
// // 서버가 접속 되어있으며 manifest.xml이 다른 경우
// if(fileCheckErrorMag.equals("Invalid Manifest file."))
// s = "This project manifest file is invalid."; //$NON-NLS-1$
// // 서버가 접속이 되어있지 않은 경우
// else
// s = "This server Off-Line.";
}
if (s == null) {
contentForConfiguration(compArea);
createWidgets(compArea);
setOutputFolder();
initConfigurations();
return composite;
}
// no contents
Label label = new Label(compArea, SWT.LEFT);
label.setText(s);
label.setFont(compArea.getFont());
noContentOnPage = true;
return composite;
}
protected void createButtonsForButtonBar(Composite parent) {
// create OK and Cancel buttons by default
super.createButtonsForButtonBar(parent);
makeButton = getButton(IDialogConstants.OK_ID);
makeButton.setText("&Make");
setMakeButton(makeButtonEnabled);
Button closeButton = getButton(IDialogConstants.CANCEL_ID);
closeButton.setText("Cancel");
setTitle("Select files to package");
}
protected void createWidgets(Composite parent) {
Composite treeComposite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
treeComposite.setLayout(layout);
treeComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label label_tree = new Label(treeComposite, SWT.NONE);
label_tree.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
label_tree
.setText("Select the folders and files to include in the bada application package.");
createResourcesGroup(treeComposite);
createTreeButtonsGroup(treeComposite);
Composite folderComposite = new Composite(parent, SWT.NONE);
layout = new GridLayout(3, false);
folderComposite.setLayout(layout);
folderComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label label_pkgName = new Label(folderComposite, SWT.NONE);
label_pkgName.setLayoutData(new GridData());
label_pkgName.setText("Package name:");
textPkgName = new Text(folderComposite, SWT.BORDER);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
textPkgName.setLayoutData(gd);
textPkgName.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
updateWidgetEnablements();
}
});
Label label_folder = new Label(folderComposite, SWT.NONE);
label_folder.setLayoutData(new GridData());
label_folder.setText("Output folder:");
textOutFolder = new Text(folderComposite, SWT.BORDER);
textOutFolder.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
textOutFolder.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
outFolderChanged();
}
});
Button changeButton = new Button(folderComposite, SWT.PUSH);
changeButton.setText("Browse...");
changeButton.setLayoutData(new GridData());
changeButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
handleOutDirButtonPressed();
}
});
// checkSecurity = new Button(folderComposite, SWT.CHECK);
// checkSecurity.setText("Check the application's security violation");
// gd = new GridData(GridData.FILL_HORIZONTAL);
// gd.horizontalSpan = 3;
// checkSecurity.setLayoutData(gd);
Label labelSep = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL
| SWT.LINE_DOT);
;
labelSep.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
}
protected void handleOutDirButtonPressed() {
DirectoryDialog dialog = new DirectoryDialog(getShell());
dialog.setMessage("Select Output Folder");
String dirName = textOutFolder.getText().trim();
if (dirName.length() > 0) {
File path = new File(dirName);
if (path.exists())
dialog.setFilterPath(new Path(dirName).toOSString());
}
String selectedDirectory = dialog.open();
if (selectedDirectory != null) {
if (!dirName.equals(selectedDirectory)) {
textOutFolder.setText(selectedDirectory);
outFolderChanged();
}
}
}
protected final void createResourcesGroup(Composite parent) {
// create the input element, which has the root resource
// as its only child
List input = new ArrayList();
if (fProject != null) {
// input.add(fProject);
IFolder folder = fProject.getFolder(IConstants.DIR_HOME);
if (folder != null && folder.exists())
input.add(folder);
folder = fProject.getFolder(IConstants.DIR_RESOURCE);
if (folder != null && folder.exists())
input.add(folder);
}
this.resourceGroup = new ResourceTreeAndListGroup(parent, input,
getResourceProvider(IResource.FOLDER), WorkbenchLabelProvider
.getDecoratingWorkbenchLabelProvider(),
getResourceProvider(IResource.FILE), WorkbenchLabelProvider
.getDecoratingWorkbenchLabelProvider(), SWT.NONE,
DialogUtil.inRegularFontMode(parent));
ICheckStateListener listener = new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
updateWidgetEnablements();
}
};
this.resourceGroup.addCheckStateListener(listener);
}
protected final void createTreeButtonsGroup(Composite parent) {
Font font = parent.getFont();
// top level group
Composite buttonComposite = new Composite(parent, SWT.NONE);
buttonComposite.setFont(parent.getFont());
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.makeColumnsEqualWidth = true;
buttonComposite.setLayout(layout);
buttonComposite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL
| GridData.HORIZONTAL_ALIGN_FILL));
Button selectButton = createTreeButton(buttonComposite,
IDialogConstants.SELECT_ALL_ID, "&Select All", false);
SelectionListener listener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
resourceGroup.setAllSelections(true);
}
};
selectButton.addSelectionListener(listener);
selectButton.setFont(font);
setButtonLayoutData(selectButton);
Button deselectButton = createTreeButton(buttonComposite,
IDialogConstants.DESELECT_ALL_ID, "&Deselect All", false);
listener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
resourceGroup.setAllSelections(false);
}
};
deselectButton.addSelectionListener(listener);
deselectButton.setFont(font);
setButtonLayoutData(deselectButton);
}
protected Button createTreeButton(Composite parent, int id, String label,
boolean defaultButton) {
// increment the number of columns in the button bar
((GridLayout) parent.getLayout()).numColumns++;
Button button = new Button(parent, SWT.PUSH);
GridData buttonData = new GridData(GridData.FILL_HORIZONTAL);
button.setLayoutData(buttonData);
button.setData(Integer.valueOf(id));
button.setText(label);
button.setFont(parent.getFont());
if (defaultButton) {
Shell shell = parent.getShell();
if (shell != null) {
shell.setDefaultButton(button);
}
button.setFocus();
}
button.setFont(parent.getFont());
setButtonLayoutData(button);
return button;
}
private ITreeContentProvider getResourceProvider(final int resourceType) {
return new WorkbenchContentProvider() {
public Object[] getChildren(Object o) {
if (o instanceof IContainer) {
IResource[] members = null;
try {
members = ((IContainer) o).members();
} catch (CoreException e) {
// just return an empty set of children
return new Object[0];
}
// filter out the desired resource types
ArrayList results = new ArrayList();
if (o instanceof IProject) {
for (int i = 0; i < members.length; i++) {
// And the test bits with the resource types to see
// if they are what we want
if ((members[i].getType() & resourceType) > 0) {
String name = members[i].getName();
if (!name.startsWith(IConstants.DOT)
&& !name
.equals(IConstants.APP_XML_FILE)
&& !name
.equals(IConstants.MANIFEST_FILE))
results.add(members[i]);
}
}
} else {
if (o instanceof IFolder) {
if (((IFolder) o).getName().equals(
IConstants.DIR_HOME)) {
for (int i = 0; i < members.length; i++) {
// And the test bits with the resource types
// to see if they are what we want
if ((members[i].getType() & resourceType) > 0) {
if (!members[i].getName().startsWith(
IConstants.DOT)
&& !IConstants.DIR_SHARE
.equals(members[i]
.getName()
.toLowerCase(
Locale
.getDefault())))
results.add(members[i]);
}
}
return results.toArray();
}
}
for (int i = 0; i < members.length; i++) {
// And the test bits with the resource types to see
// if they are what we want
if ((members[i].getType() & resourceType) > 0) {
if (!members[i].getName().startsWith(
IConstants.DOT))
results.add(members[i]);
}
}
}
return results.toArray();
}
// input element case
if (o instanceof ArrayList) {
return ((ArrayList) o).toArray();
}
return new Object[0];
}
};
}
protected boolean checkElement() {
boolean isProject = false;
IResource internalElement = null;
IAdaptable el = fContainer;
if (el instanceof ICElement)
internalElement = ((ICElement) el).getResource();
else if (el instanceof IResource)
internalElement = (IResource) el;
if (internalElement == null)
return false;
if (internalElement.getProject() != null)
isProject = true;
else
isProject = false;
return isProject;
}
public IProject getProject() {
/*
* Object element = fContainer; if (element != null) { if (element
* instanceof IProject) { IResource f = (IResource) element; return
* f.getProject(); } else if (element instanceof ICProject) return
* ((ICProject)element).getProject(); } return null;
*/
IResource internalElement = null;
IAdaptable el = fContainer;
if (el instanceof ICElement)
internalElement = ((ICElement) el).getResource();
else if (el instanceof IResource)
internalElement = (IResource) el;
if (internalElement == null)
return null;
return internalElement.getProject();
}
public boolean isCDTPrj(IProject p) {
ICProjectDescription prjd = CoreModel.getDefault()
.getProjectDescription(p, false);
if (prjd == null)
return false;
ICConfigurationDescription[] cfgs = prjd.getConfigurations();
return (cfgs != null && cfgs.length > 0);
}
public boolean isBadaProject(IProject p) {
ICProjectDescription prjd = CoreModel.getDefault()
.getProjectDescription(p, false);
if (prjd == null)
return false;
ICConfigurationDescription[] cfgs = prjd.getConfigurations();
boolean flag = (cfgs != null && cfgs.length > 0);
if (flag) {
try {
flag = p.hasNature(badaNature.OSP_NATURE_ID);
} catch (CoreException e) {
// TODO Auto-generated catch block
flag = false;
}
}
return flag;
}
protected void contentForConfiguration(Composite composite) {
// Add a config selection area
Group configGroup = ControlFactory.createGroup(composite, "", 1);
GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.grabExcessHorizontalSpace = true;
gd.widthHint = 150;
configGroup.setLayoutData(gd);
configGroup.setLayout(new GridLayout(3, false));
Label configLabel = new Label(configGroup, SWT.NONE);
configLabel.setText("Configuration:"); //$NON-NLS-1$
configLabel.setLayoutData(new GridData(GridData.BEGINNING));
configSelector = new Combo(configGroup, SWT.READ_ONLY | SWT.DROP_DOWN);
configSelector.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
handleConfigSelection();
}
});
gd = new GridData(GridData.FILL_BOTH);
configSelector.setLayoutData(gd);
}
public void handleConfigSelectionRTL() {
handleConfigSelection();
}
private void handleConfigSelection() {
// If there is nothing in config selection widget just bail
if (configSelector.getItemCount() == 0)
return;
int selectionIndex = configSelector.getSelectionIndex();
if (selectionIndex == -1)
return;
String strName = cfgDescs[selectionIndex].getName();
if (strName.equals(IConstants.CONFIG_SIMUAL_DEBUG_NAME)) {
// checkSecurity.setEnabled(false);
libExt = IConstants.EXT_DLL;
} else {
// checkSecurity.setEnabled(true);
libExt = IConstants.EXT_SO;
}
cfgChanged(cfgDescs[selectionIndex]);
}
private void initConfigurations() {
IProject prj = getProject();
// Do nothing in case of Preferences page.
if (prj == null)
return;
// Do not re-read if list already created by another page
IConfiguration defCfg = null;
IManagedBuildInfo info = ManagedBuildManager.getBuildInfo(prj);
cfgDescs = info.getManagedProject().getConfigurations();
if (cfgDescs == null || cfgDescs.length == 0)
return;
defCfg = info.getDefaultConfiguration();
buildTargetName = info.getBuildArtifactName();
// Get its extension
buildTargetExt = info.getBuildArtifactExtension();
try {
// try to resolve the build macros in the target extension
buildTargetExt = ManagedBuildManager.getBuildMacroProvider()
.resolveValueToMakefileFormat(buildTargetExt,
"", //$NON-NLS-1$
" ", //$NON-NLS-1$
IBuildMacroProvider.CONTEXT_CONFIGURATION,
info.getDefaultConfiguration());
} catch (BuildMacroException e) {
e.printStackTrace();
}
try {
// try to resolve the build macros in the target name
String resolved = ManagedBuildManager.getBuildMacroProvider()
.resolveValueToMakefileFormat(buildTargetName,
"", //$NON-NLS-1$
" ", //$NON-NLS-1$
IBuildMacroProvider.CONTEXT_CONFIGURATION,
info.getDefaultConfiguration());
if (resolved != null && (resolved = resolved.trim()).length() > 0)
buildTargetName = resolved;
} catch (BuildMacroException e) {
e.printStackTrace();
}
// Clear and replace the contents of the selector widget
configSelector.removeAll();
int currIdx = 0;
for (int i = 0; i < cfgDescs.length; ++i) {
configSelector.add(cfgDescs[i].getName());
if (defCfg != null
&& defCfg.getName().equals(cfgDescs[i].getName()))
currIdx = i;
}
configSelector.select(currIdx);
handleConfigSelection();
}
protected void cfgChanged(IConfiguration config) {
currentConfig = config;
setDefaultSelect();
setPackageName();
checkFiles();
}
public String checkFilesRTL() {
checkFiles();
IFile exeFile = packageData.getExeFile();
IFile appXml = packageData.getAppXml();
if (fileCheckErrorMag.equals("")) {
if (exeFile == null) {
return "Exe File Not Found";
} else if (appXml == null) {
return "App File Not Found";
}
} else {
return fileCheckErrorMag;
}
return null;
}
public String getFileCheckErrorMsg() {
return fileCheckErrorMag;
}
private void checkFiles() {
bFileCheckError = false;
fileCheckErrorMag = "";
IFile exeFile = packageData.getExeFile();
IFile appXml = packageData.getAppXml();
if (exeFile != null && appXml != null) {
String fileName = exeFile.getName();
fileName = fileName.substring(0, fileName.length() - 4); // remove
// .exe
AppXmlStore xmlManager = new AppXmlStore(appXml);
xmlManager.loadXML();
if (!xmlManager.getEntry().equals(fileName)) {
bFileCheckError = true;
fileCheckErrorMag = "The name of the project executable binary is not identical with the value of the <Entry> field in application.xml.";
return;
}
if (fProject == null)
return;
String iconName = xmlManager.getIconMainMenu();
if (iconName != null && iconName.length() > 0) {
IFile iconFile = fProject.getFile(IConstants.DIR_ICON
+ IConstants.FILE_SEP_FSLASH + iconName);
if (iconFile == null || !iconFile.exists()) {
bFileCheckError = true;
fileCheckErrorMag = "Cannot find the "
+ iconName
+ " image specified in the <MainMenu> field in application.xml.";
return;
}
}
iconName = xmlManager.getIconLaunchImage();
if (iconName != null && iconName.length() > 0) {
IFile iconFile = fProject.getFile(IConstants.DIR_ICON
+ IConstants.FILE_SEP_FSLASH + iconName);
if (iconFile == null || !iconFile.exists()) {
bFileCheckError = true;
fileCheckErrorMag = "Cannot find the "
+ iconName
+ " image specified in the <LaunchImage> field in application.xml.";
return;
}
}
iconName = xmlManager.getIconQuickPanel();
if (iconName != null && iconName.length() > 0) {
IFile iconFile = fProject.getFile(IConstants.DIR_ICON
+ IConstants.FILE_SEP_FSLASH + iconName);
if (iconFile == null || !iconFile.exists()) {
bFileCheckError = true;
fileCheckErrorMag = "Cannot find the "
+ iconName
+ " image specified in the <QuickPanel> field in application.xml.";
return;
}
}
iconName = xmlManager.getIconSetting();
if (iconName != null && iconName.length() > 0) {
IFile iconFile = fProject.getFile(IConstants.DIR_ICON
+ IConstants.FILE_SEP_FSLASH + iconName);
if (iconFile == null || !iconFile.exists()) {
bFileCheckError = true;
fileCheckErrorMag = "Cannot find the "
+ iconName
+ " image specified in the <Setting> field in application.xml.";
return;
}
}
iconName = xmlManager.getIconTicker();
if (iconName != null && iconName.length() > 0) {
IFile iconFile = fProject.getFile(IConstants.DIR_ICON
+ IConstants.FILE_SEP_FSLASH + iconName);
if (iconFile == null || !iconFile.exists()) {
bFileCheckError = true;
fileCheckErrorMag = "Cannot find the "
+ iconName
+ " image specified in the <Ticker> field in application.xml.";
return;
}
}
}
updateWidgetEnablements();
}
private void setPackageName() {
if (fProject != null) {
textPkgName.setText(fProject.getName() + "_"
+ configSelector.getText());
}
}
private void setOutputFolder() {
if (fProject != null) {
textOutFolder.setText(fProject.getLocation().toString());
}
}
public void setDefaultSelectRTL() {
setDefaultSelect();
}
private void setDefaultSelect() {
resourceGroup.setAllSelections(false);
packageData.clear();
if (noContentOnPage == false && fProject != null
&& currentConfig != null) {
List selectedResources = new ArrayList();
IFile file = fProject.getFile(IConstants.APP_XML_FILE);
if (file != null) {
if (!file.exists())
file = null;
}
packageData.setAppXml(file);
file = fProject.getFile(IConstants.MANIFEST_FILE);
if (file != null) {
if (!file.exists())
file = null;
}
packageData.setManifestXml(file);
ITool targetTool = currentConfig.calculateTargetTool();
String outputPrefix = "";
if (targetTool != null) {
outputPrefix = targetTool.getOutputPrefix();
}
String targetName = buildTargetName;
if (buildTargetExt.length() > 0)
targetName += "." + buildTargetExt;
String targetFilePath = outputPrefix + IConstants.PREFIX_CONFIG_DIR
+ currentConfig.getName() + IConstants.FILE_SEP_FSLASH
+ targetName;
// targetExePath =
// fProject.getLocation().makeAbsolute().toOSString() +
// IConstants.FILE_SEP_BSLASH + outputPrefix +
// IConstants.PREFIX_CONFIG_DIR + currentConfig.getName();
packageData.setBuildDirectory(fProject.getFolder(outputPrefix
+ IConstants.PREFIX_CONFIG_DIR + currentConfig.getName()));
// packageData.setBuildDirectory(fProject.getFolder(outputPrefix));
// check exe File
file = fProject.getFile(targetFilePath);
if (file != null) {
if (!file.exists())
file = null;
}
packageData.setExeFile(file);
// check rbin
IFolder folder = fProject.getFolder(IConstants.DIR_RESOURCE);
if (folder != null && folder.exists())
selectedResources.add(folder);
// folder = fProject.getFolder(IConstants.DIR_ICON);
// if( folder != null && folder.exists() )
// selectedResources.add(folder);
folder = fProject.getFolder(IConstants.DIR_HOME);
if (folder != null && folder.exists())
selectedResources.add(folder);
folderIcon = fProject.getFolder(IConstants.DIR_ICON);
if (folderIcon == null || !folderIcon.exists())
folderIcon = null;
setSelect(selectedResources);
} else {
updateWidgetEnablements();
}
}
protected void updateWidgetEnablements() {
setMakeButton(false);
if (bFileCheckError) {
setErrorMessage(fileCheckErrorMag);
return;
}
if (packageData.getAppXml() == null) {
setErrorMessage("The project does not have an applicationl.xml file.");
return;
}
if (packageData.getExeFile() == null) {
setErrorMessage("The project does not have an .exe file.");
return;
}
if (packageData.getManifestXml() == null) {
setErrorMessage("The project does not have a manifest.xml file.");
return;
}
if (textPkgName.getText().trim().length() <= 0) {
setErrorMessage("You must define a name for the package."); //$NON-NLS-1$
return;
}
String outFolderPath = textOutFolder.getText().trim();
if (outFolderPath.length() == 0) {
setErrorMessage("You must define an output folder for the package."); //$NON-NLS-1$
return;
}
if (outFolderPath.equals(".") || outFolderPath.equals("..")) { //$NON-NLS-1$ //$NON-NLS-2$
setErrorMessage("You must define an output folder for the package."); //$NON-NLS-1$
return;
}
IPath binOutFolderPath = new Path(outFolderPath);
if (!binOutFolderPath.toFile().exists()) {
setErrorMessage("The output folder does not exist. Create or redefine the folder."); //$NON-NLS-1$
return;
}
setErrorMessage(null);
setMakeButton(true);
}
protected void outFolderChanged() {
updateWidgetEnablements();
}
private void setMakeButton(boolean enabled) {
if (makeButton != null)
makeButton.setEnabled(enabled);
else
makeButtonEnabled = enabled;
}
protected void setSelect(List sel) {
if (resourceGroup == null)
return;
resourceGroup.setAllSelections(false);
Iterator it = sel.iterator();
while (it.hasNext()) {
IResource currentResource = (IResource) it.next();
if (currentResource.getType() == IResource.FILE) {
this.resourceGroup.initialCheckListItem(currentResource);
} else {
this.resourceGroup.initialCheckTreeItem(currentResource);
}
}
updateWidgetEnablements();
}
@Override
protected void okPressed() {
// TODO Auto-generated method stub
String s = null;
if (!isManifestFileValid(fProject)) {
// 서버가 접속 되어있으며 manifest.xml이 다른 경우
if (fileCheckErrorMag.equals(ERR_MSG_MANIFEST_CHECK_FALSE)) {
s = "The project manifest file is not identical with the manifest file created for the application in bada Developers."; //$NON-NLS-1$
MessageDialog.openInformation(parent.getShell(), "Error", s);
return;
// 서버가 접속이 되어있지 않은 경우
} else if (fileCheckErrorMag
.equals(ERR_MSG_MANIFEST_CHECK_NOTFOUND)) {
s = "Cannot find the project manifest file in bada Developers.";
MessageDialog.openInformation(parent.getShell(), "Error", s);
return;
} else if (fileCheckErrorMag
.equals(ERR_MSG_MANIFEST_CHECK_USERCANCEL)) {
// s = "Cancelled.";
// MessageDialog.openInformation(parent.getShell(), "Error", s);
return;
} else {
s = "The manifest file cannot be validated due to a network problem.";
}
}
// if(s != null)
// noContentOnPage = true;
//
// if( noContentOnPage ){
// System.out.println(s);
// // this.cancelPressed();
// }
PressOK(s, null);
}
public void PressOK(String s, String path) {
List items = resourceGroup.getAllCheckedItems();
if (folderIcon != null) {
items.add(folderIcon);
}
packageData.setExportResources(items);
String outFileName = textPkgName.getText().trim();
if (!outFileName.toLowerCase(Locale.getDefault()).endsWith(
IConstants.EXT_PACKAGE))
outFileName += IConstants.EXT_PACKAGE;
if (path != null)
outFilePath = path + IConstants.FILE_SEP_BSLASH + outFileName;
else
outFilePath = textOutFolder.getText().trim()
+ IConstants.FILE_SEP_BSLASH + outFileName;
if (path == null)
if ((new File(outFilePath).exists())) {
if (!MessageDialog.openConfirm(getShell(),
"Confirm File Overwrite", "Package file " + outFileName
+ " exists. Do you want to overwrite?")) {
return;
}
}
// boolean isSecurityChecked = checkSecurity.getSelection();
// if
// (currentConfig.getName().equals(IConstants.CONFIG_SIMUAL_DEBUG_NAME))
// isSecurityChecked = false;
packageData.setProject(fProject);
packageData.setConfigName(currentConfig.getName());
// packageData.setCheckSecurity(isSecurityChecked);
setLibaryList();
if (helper.executeExportOperation(new PackageArchiveExportOperation(null,
outFilePath, packageData))) {
if (s != null)
MessageDialog.openInformation(parent.getShell(), "Error", s);
super.okPressed();
}
}
public String getoutFilePath() {
return outFilePath;
}
private void setLibaryList() {
List list = new ArrayList<IFile>();
IFolder folder = fProject.getFolder(IConstants.DIR_LIB);
if (folder != null && folder.exists()) {
IResource[] members = null;
try {
members = folder.members();
} catch (CoreException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
if (members != null) {
for (int i = 0; i < members.length; i++) {
// And the test bits with the resource types to see if they
// are what we want
if ((members[i].getType() & IResource.FILE) > 0) {
if (members[i].getName().toLowerCase(
Locale.getDefault()).endsWith(libExt)) {
list.add(members[i]);
}
}
}
}
}
packageData.setLibraryList(list);
}
protected boolean executeExportOperation(PackageArchiveExportOperation op) {
op.setUseCompression(true);
try {
new ProgressMonitorDialog(getShell()).run(false, true, op);
} catch (InterruptedException e) {
return false;
} catch (InvocationTargetException e) {
MessageDialog.openError(getShell(), "Internal Error for Export", e
.getTargetException().getMessage());
return false;
}
IStatus status = op.getStatus();
if (!status.isOK()) {
ErrorDialog.openError(getShell(), "Export error", null, // no
// special
// message
status);
return false;
}
if (fProject != null) {
try {
fProject.refreshLocal(IResource.DEPTH_ONE, null);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}
private boolean isManifestFileValid(IProject prj) {
IFile maniFile = prj.getFile(IConstants.MANIFEST_FILE);
if (!maniFile.exists()) {
bFileCheckError = true;
fileCheckErrorMag = "Manifest file does not exist.";
}
String url = "http://developer.bada.com/apis/tools/sdk/compareManifest.do?xml="
+ URLEncoder.encode(FileUtil.loadFromFile(maniFile
.getLocation().toOSString()));
// 서버가 접속 되었으나 manifest.xml이 동일하지 않은 경우
int result = getContents(url);
if (result == MANIFEST_CHECK_FALSE) {
bFileCheckError = true;
fileCheckErrorMag = ERR_MSG_MANIFEST_CHECK_FALSE;
return false;
// 서버가 접속 되어있지 않은 경우
} else if (result == MANIFEST_CHECK_OFFLINE) {
bFileCheckError = true;
fileCheckErrorMag = ERR_MSG_MANIFEST_CHECK_OFFLINE;
return false;
} else if (result == MANIFEST_CHECK_NOTFOUND) {
bFileCheckError = true;
fileCheckErrorMag = ERR_MSG_MANIFEST_CHECK_NOTFOUND;
return false;
} else if (result == MANIFEST_CHECK_USERCANCEL) {
bFileCheckError = true;
fileCheckErrorMag = ERR_MSG_MANIFEST_CHECK_USERCANCEL;
return false;
}
return true;
}
private Display getStandardDisplay() {
Display display = Display.getCurrent();
if (display == null) {
display = Display.getDefault();
}
return display;
}
private int getContents(String surl) {
final CheckManifestOperaton oper = new CheckManifestOperaton(surl);
getStandardDisplay().syncExec(new Runnable() {
public void run() {
IWorkbenchWindow window = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow();
if (window != null) {
ProgressMonitorDialog dialog = new ProgressMonitorDialog(
window.getShell());
try {
dialog.run(true, true, oper);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
return oper.getResult();
}
/*
* private int getContents(String surl){
*
* URL url; try { url = new URL(surl); URLConnection conn =
* url.openConnection(); HttpURLConnection hurl = (HttpURLConnection) conn;
* hurl.setRequestProperty("Content-Type",
* "application/x-www-form-urlencoded"); hurl.setRequestMethod("POST");
* hurl.setDoOutput(true); hurl.setDoInput(true); hurl.setUseCaches(false);
* hurl.setDefaultUseCaches(false); boolean flag = false; // 서버가 접속이 되었는지 되지
* 않았는지 체크합니다. String cookie = null; // 서버에서 받은 답의0번 헤더를 가져옵니다. String
* bufferline = null; // 서버에서 받은 답변을 buffer에서 한줄 씩 가져오기 위한 문자열입니다. String
* manifestvalid = ""; // 서버에서 받은 답변의 바디 부분을 모은 문자열입니다. String onlinecheck =
* ""; // 현재 서버가 접속이 되었는지 되지 않았는지 체크하기 위해 0번 헤더의 // 토큰을 하나씩 비교하기 위한 문자열입니다.
* cookie = conn.getHeaderField(0); StringTokenizer stk = new
* StringTokenizer(cookie, " "); // 가져온 0번 헤더의 토큰을 " " 으로 구분합니다.
* while(stk.hasMoreElements()) { String str1 = stk.nextToken();
* if(str1.equals("200")){ flag = !flag; } } BufferedReader in = new
* BufferedReader(new InputStreamReader(hurl.getInputStream()));
* while((bufferline = in.readLine()) != null){ manifestvalid =
* manifestvalid.concat(bufferline); } // System.out.println(str2); // 받아온
* 문서의 내용 테스트 용입니다. // System.out.println(flag); if(flag == false){ // 서버의
* 응답이 200이 아닌 경우입니다. return MANIFEST_CHECK_OFFLINE; }else
* if(manifestvalid.equals("true")){ // 서버가 접속 되어 있으며 manifest.xml이 서버와 동일한
* 경우 return MANIFEST_CHECK_TRUE; }else if(manifestvalid.equals("false")){
* // 서버도 접속 되지 않고 manifest.xml도 서버와 다른 경우 return MANIFEST_CHECK_FALSE;
* }else if(manifestvalid.equals("NotFound")){ // 서버에서 동일한 id의 manifest.xml을
* 찾을 수 없는 경우 return MANIFEST_CHECK_NOTFOUND; } // 받아오는 헤더의 정보가 아닌 바디의 정보가
* // true/false의 값으로 넘어오기 때문에 더이상 // 헤더는 필요 없습니다. // boolean flag = false;
* // 문자열을 비교하여 바로 true/false를 반환 합니다. // String cookie = null; // String
* str3 = ""; // cookie = conn.getHeaderField(0); // StringTokenizer stk =
* new StringTokenizer(cookie, " "); // while(stk.hasMoreElements()) // { //
* String str1 = stk.nextToken(); // if(str1.equals("200")){ // flag =
* !flag; // } // } // System.out.println(cookie); // 0번 헤더 내용 출력 } catch
* (MalformedURLException e1) { // TODO Auto-generated catch block
* e1.printStackTrace(); } catch (IOException e) { } catch (Exception e){ }
* return MANIFEST_CHECK_OFFLINE; // 페이지가 존재하지 않는 경우입니다. // 위의 try/catch문에서
* NullPointExeption이 불려옵니다. // 때문에 Exception을 통해서 try문을 무시하게 됩니다. }
*/
}
| [
"rom@garay.(none)"
] | rom@garay.(none) |
dd26296080f7839319bd6baf3290daa597acbc07 | 76beeafa6ad463e9a952a8466589f05407ca0b1e | /taotao-common/src/main/java/com/kun/common/utils/IDUtils.java | dfa382f2b442b833291d7141f0d38fe6bbb61d7e | [] | no_license | wangchuankun1/taotao-SSM | 15e0d92c09ae5e37afa4de32860a17399efe0538 | 0480cf0daaf585cc9e8950fff8dcd2d0f6ec190e | refs/heads/master | 2022-12-24T14:37:17.437670 | 2019-07-03T12:13:33 | 2019-07-03T12:13:33 | 195,040,390 | 0 | 0 | null | 2022-12-16T05:00:54 | 2019-07-03T11:28:52 | JavaScript | UTF-8 | Java | false | false | 1,191 | java | package com.kun.common.utils;
import java.util.Random;
/**
* 各种id生成策略
* <p>Title: IDUtils</p>
* <p>Description: </p>
* <p>Company: www.itcast.com</p>
* @author 入云龙
* @date 2015年7月22日下午2:32:10
* @version 1.0
*/
public class IDUtils {
/**
* 图片名生成
*/
public static String genImageName() {
//取当前时间的长整形值包含毫秒
long millis = System.currentTimeMillis();
//long millis = System.nanoTime();
//加上三位随机数
Random random = new Random();
int end3 = random.nextInt(999);
//如果不足三位前面补0
String str = millis + String.format("%03d", end3);
return str;
}
/**
* 商品id生成
*/
public static long genItemId() {
//取当前时间的长整形值包含毫秒
long millis = System.currentTimeMillis();
//long millis = System.nanoTime();
//加上两位随机数
Random random = new Random();
int end2 = random.nextInt(99);
//如果不足两位前面补0
String str = millis + String.format("%02d", end2);
long id = new Long(str);
return id;
}
public static void main(String[] args) {
for(int i=0;i< 100;i++)
System.out.println(genItemId());
}
}
| [
"657129804@qq.com"
] | 657129804@qq.com |
fd169f56023dc97c4346fcf11a9e239305436d1d | e49c3901d4a13216505a272799d184656fc1ee4a | /app/src/main/java/com/example/ar_pc/projectr/model/bahanMakananItem.java | 6e79c814ede176041a4aa9eadb51e5def9834c5a | [] | no_license | alldoraafi/ProjectR | 40b104652e4e0094b88a2e2a5c3d87b338e50ddf | 539d157839ee99dcdd2b2382e85ed0836fbf8e1a | refs/heads/master | 2021-08-22T11:12:54.598547 | 2017-11-30T02:58:46 | 2017-11-30T02:58:46 | 112,413,435 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 385 | java | package com.example.ar_pc.projectr.model;
/**
* Created by AR-PC on 11/30/2017.
*/
public class bahanMakananItem {
private String nama;
private int jumlah;
public bahanMakananItem() {
}
public bahanMakananItem(String nama, int jumlah) {
this.nama = nama;
this.jumlah = jumlah;
}
public String getNama() {
return nama;
}
}
| [
"alldoraafi@gmail.com"
] | alldoraafi@gmail.com |
c0075c26c243dd1032918610b0191c6e2fe56f75 | e56e5863b8cb49692cae552131ee9b565f1dcdd8 | /edu/Design/Behavioral/Visitor/Visitor.java | ae0b7e49c13de51a3e61d7d41c4dd442a6cf89dd | [] | no_license | jufangqi/JvavSE | bc9000ca68459667f0e3ded5be6923552392cc93 | 4bab8153bb9ae215b9ff1280b8ce925339be84e4 | refs/heads/master | 2021-01-20T02:41:52.400717 | 2016-06-26T09:44:29 | 2016-06-26T09:44:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 150 | java | package edu.Design.Behavioral.Visitor;
/**
* Created by 存 on 2016/6/12.
*/
public interface Visitor {
public void visit(Subject subject);
}
| [
"丁存"
] | 丁存 |
99dbebdb776853c10514dae93b7c6fe83b6432db | af31eafcdd36da986f07bf259bd3a4d3e8fc10b3 | /src/main/java/com/midai/springboot/mybatis/JdbcProperties.java | 4fbac9157017562ebdd1b12bc634f3a14cec1db6 | [] | no_license | ChenXun1989/spring-boot-starter-mybatis | c4c32fbf471431630290dab2faf7039a0273d22f | 38144ab098119895314fc0e9b7b09fb959483e67 | refs/heads/master | 2020-07-23T19:29:35.670019 | 2016-08-19T06:00:58 | 2016-08-19T06:00:58 | 66,055,735 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,477 | java | /**
* Project Name:demo-dubbo-provider
* File Name:JdbcProperties.java
* Package Name:com.midai.springboot.mybatis
* Date:2016年7月27日下午9:27:09
* Copyright (c) 2016, www midaigroup com Technology Co., Ltd. All Rights Reserved.
*
*/
package com.midai.springboot.mybatis;
import java.sql.SQLException;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* ClassName:JdbcProperties <br/>
* Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON. <br/>
* Date: 2016年7月27日 下午9:27:09 <br/>
*
* @author 陈勋
* @version
* @since JDK 1.7
* @see
*/
@Data
@ConfigurationProperties(prefix = JdbcProperties.JDBC_PREFIX)
public class JdbcProperties {
public static final String JDBC_PREFIX = "jdbc";
private String url;
private String username;
private String password;
private int initialSize = 0;
private int maxActive = 20;
private int minIdle = 0;
private int maxWait = 60000;
private boolean poolPreparedStatements = true;
private int maxPoolPreparedStatementPerConnectionSize = 33;
private boolean testOnBorrow = false;
private boolean testOnReturn = false;
private boolean testWhileIdle = true;
private int timeBetweenEvictionRunsMillis = 60000;
private int minEvictableIdleTimeMillis = 25200000;
private boolean removeAbandoned = true;
private int removeAbandonedTimeout = 1800;
private boolean logAbandoned = true;
private String validationQuery;
}
| [
"576481228@qq.com"
] | 576481228@qq.com |
ee53837d114c7b779babe9c74783e19f6c0720bc | c56875ab84597f75ae7c18cc7d0934c7f74f7ed7 | /linjiashop-core/src/main/java/cn/enilu/flash/service/shop/OrderService.java | b3f3a32d8f02a8ece3919f8bae5404586da7bca9 | [
"MIT"
] | permissive | ls9527/linjiashop | 4e662d5bf196dce9e34fbef102a777bfb23fc970 | d7362e43868d036685e2429763952a2522762d1d | refs/heads/master | 2022-11-25T18:48:53.373047 | 2020-07-25T13:24:40 | 2020-07-25T13:24:40 | 282,122,227 | 1 | 0 | MIT | 2020-07-24T04:25:25 | 2020-07-24T04:25:24 | null | UTF-8 | Java | false | false | 4,373 | java | package cn.enilu.flash.service.shop;
import cn.enilu.flash.bean.entity.shop.Order;
import cn.enilu.flash.bean.entity.shop.OrderItem;
import cn.enilu.flash.bean.entity.shop.OrderLog;
import cn.enilu.flash.bean.enumeration.shop.OrderEnum;
import cn.enilu.flash.bean.vo.query.SearchFilter;
import cn.enilu.flash.dao.shop.OrderItemRepository;
import cn.enilu.flash.dao.shop.OrderLogRepository;
import cn.enilu.flash.dao.shop.OrderRepository;
import cn.enilu.flash.security.JwtUtil;
import cn.enilu.flash.service.BaseService;
import cn.enilu.flash.utils.DateUtil;
import cn.enilu.flash.utils.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
public class OrderService extends BaseService<Order, Long, OrderRepository> {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private OrderItemRepository orderItemRepository;
@Autowired
private OrderLogRepository orderLogRepository;
/**
* 获取唯一订单号
* 时间戳+随机数<br>
* 建议生产环境使用redis获取唯一订单号
*
* @return
*/
public String getOrderSn() {
return DateUtil.getAllTime() + RandomUtil.getRandomNumber(6);
}
public void save(Order order, List<OrderItem> itemList) {
order.setOrderSn(getOrderSn());
insert(order);
for(OrderItem item:itemList){
item.setIdOrder(order.getId());
}
orderItemRepository.saveAll(itemList);
OrderLog orderLog = new OrderLog();
orderLog.setIdOrder(order.getId());
orderLog.setDescript("生成订单");
orderLogRepository.save(orderLog);
}
public void updateOrder(Order order){
update(order);
}
/**
* 用户取消订单
* @param orderSn
*/
public void cancel(String orderSn) {
Order order = getByOrderSn(orderSn);
order.setStatus(OrderEnum.OrderStatusEnum.CANCEL.getId());
String descript = "用户取消订单";
saveOrderLog(order,descript);;
updateOrder(order);
}
public Order getByOrderSn(String orderSn) {
return get(SearchFilter.build("orderSn", SearchFilter.Operator.EQ,orderSn));
}
/**
* 确认收货
* @param orderSn
*/
public Order confirmReceive(String orderSn) {
Order order = getByOrderSn(orderSn);
order.setStatus(OrderEnum.OrderStatusEnum.FINISHED.getId());
String descript = "客户确认收货";
saveOrderLog(order,descript);
updateOrder(order);
return order;
}
public void startPay(Order order){
order.setPayStatus(OrderEnum.PayStatusEnum.PAYING.getId());
saveOrderLog(order,"客户发起支付");
updateOrder(order);
}
private void saveOrderLog(Order order,String descript){
OrderLog orderLog = new OrderLog();
orderLog.setIdOrder(order.getId());
orderLog.setDescript(descript);
orderLogRepository.save(orderLog);
}
/**
* 管理员添加备注信息
* @param order
* @param message
*/
public void addComment(Order order, String message) {
order.setAdminMessage(message);
update(order);
OrderLog orderLog = new OrderLog();
orderLog.setIdOrder(order.getId());
orderLog.setDescript("管理员("+ JwtUtil.getUsername() +")添加备注:"+message);
orderLogRepository.save(orderLog);
}
/**
* 支付成功,更新订单数据
* @param order
* @param payType
*/
public void paySuccess(Order order,String payType) {
order.setPayTime(new Date());
order.setPayStatus(OrderEnum.PayStatusEnum.UN_SEND.getId());
order.setStatus(OrderEnum.OrderStatusEnum.UN_SEND.getId());
order.setRealPrice(order.getTotalPrice());
order.setPayType(payType);
updateOrder(order);
String descript = "用户付款成功";
saveOrderLog(order,descript);
}
public void send(Order order) {
String descript = "管理员("+JwtUtil.getUsername()+")已发货";
updateOrder(order);
saveOrderLog(order,descript);
}
}
| [
"eniluzt@qq.com"
] | eniluzt@qq.com |
a9393414b66562fdc3c3a1a2b0232d7493320649 | cb4ba5492743f12f2e327b93ee464a40ad89e43a | /app/src/main/java/com/example/apkersan2/adapter/PengaduanAdapter.java | 403bb1a121afd1fdd97bbc623f7280c08f809007 | [] | no_license | ekosooo/ApkersanApp | 2ab95ee4ef7157daa14da7ca86e0f41618d653b3 | c3bc3217d78264d40812a37e3761cbd6466f68da | refs/heads/master | 2020-08-29T16:18:16.323616 | 2019-11-27T03:44:21 | 2019-11-27T03:44:21 | 218,088,773 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,233 | java | package com.example.apkersan2.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.apkersan2.DetailActivity;
import com.example.apkersan2.R;
import com.example.apkersan2.model.DataPengaduan;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class PengaduanAdapter extends RecyclerView.Adapter<PengaduanAdapter.PengaduanHolder> {
List<DataPengaduan> PengaduanList;
Context context;
String ticket_number, kasus_nama, bentuk_kekerasan, korban_nama, waktu_kejadian, status_pengaduan, alamat_kejadian, kronologi, tindak_lanjut, bukti;
public PengaduanAdapter(Context context, List<DataPengaduan> listPengaduan){
this.context = context;
this.PengaduanList = listPengaduan;
}
@NonNull
@Override
public PengaduanHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_pengaduan, parent, false);
final PengaduanHolder pengaduanHolder = new PengaduanHolder(view);
return pengaduanHolder;
}
@Override
public void onBindViewHolder(PengaduanHolder holder, int position){
final DataPengaduan pengaduanItem = PengaduanList.get(position);
holder.TvNoTiket.setText(pengaduanItem.getTicketNumber());
holder.TvNamaKorban.setText(pengaduanItem.getKorbanNama());
holder.TvStatusPengaduan.setText(pengaduanItem.getStatusPengaduan());
holder.TvKasus.setText(pengaduanItem.getKasusNama());
holder.ItemClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, DetailActivity.class);
ticket_number = pengaduanItem.getTicketNumber();
korban_nama = pengaduanItem.getKorbanNama();
kasus_nama = pengaduanItem.getKasusNama();
bentuk_kekerasan = pengaduanItem.getKekerasanNama();
waktu_kejadian = pengaduanItem.getWaktuKejadian();
alamat_kejadian = pengaduanItem.getAlamatKejadian();
kronologi = pengaduanItem.getKronologi();
status_pengaduan = pengaduanItem.getStatusPengaduan();
tindak_lanjut = pengaduanItem.getTindakLanjut();
bukti = pengaduanItem.getBukti();
intent.putExtra("tiket", ticket_number);
intent.putExtra("korban", korban_nama);
intent.putExtra("kasus", kasus_nama);
intent.putExtra("kekerasan", bentuk_kekerasan);
intent.putExtra("waktu", waktu_kejadian);
intent.putExtra("alamat", alamat_kejadian);
intent.putExtra("kronologi", kronologi);
intent.putExtra("status", status_pengaduan);
intent.putExtra("tindak", tindak_lanjut);
intent.putExtra("bukti", bukti);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount(){
return PengaduanList.size();
}
public class PengaduanHolder extends RecyclerView.ViewHolder{
public TextView TvNoTiket, TvNamaKorban, TvStatusPengaduan, TvKasus;
public CardView ItemClick;
public PengaduanHolder(@NonNull View itemView){
super(itemView);
TvNoTiket = itemView.findViewById(R.id.GetTvTiket);
TvNamaKorban = itemView.findViewById(R.id.GetTvNamaKorban);
TvStatusPengaduan = itemView.findViewById(R.id.GetTvStatusPengaduan);
TvKasus = itemView.findViewById(R.id.GetTvKasusNama);
ItemClick = itemView.findViewById(R.id.item);
ButterKnife.bind(this, itemView);
}
}
}
| [
"ekoalfnt@gmail.com"
] | ekoalfnt@gmail.com |
d832d31f8a01666f15da0d3bcf21516ea7076c95 | 06dd0a25857857e7089559aa1a9d95e2b63f69c8 | /src/main/java/cn/com/esrichina/ServerMonitor/domain/Timeperiods.java | 6f374738388ddd5b1eef6863c3f78cc5ea389462 | [] | no_license | javaWD/ServerMonitor | 8116c71acbbf6376a47dd38b388b6dade539a18f | 47ef30ca418e9f71898490c2a0a98ccc655d8ea1 | refs/heads/master | 2020-11-28T07:07:08.176873 | 2016-08-27T09:07:09 | 2016-08-27T09:07:09 | 66,256,071 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,825 | java | package cn.com.esrichina.ServerMonitor.domain;
// Generated 2016-8-18 11:14:22 by Hibernate Tools 4.0.0
import java.util.HashSet;
import java.util.Set;
/**
* Timeperiods generated by hbm2java
*/
public class Timeperiods implements java.io.Serializable {
private long timeperiodid;
private int timeperiodType;
private int every;
private int month;
private int dayofweek;
private int day;
private int startTime;
private int period;
private int startDate;
private Set maintenancesWindowses = new HashSet(0);
public Timeperiods() {
}
public Timeperiods(long timeperiodid, int timeperiodType, int every,
int month, int dayofweek, int day, int startTime, int period,
int startDate) {
this.timeperiodid = timeperiodid;
this.timeperiodType = timeperiodType;
this.every = every;
this.month = month;
this.dayofweek = dayofweek;
this.day = day;
this.startTime = startTime;
this.period = period;
this.startDate = startDate;
}
public Timeperiods(long timeperiodid, int timeperiodType, int every,
int month, int dayofweek, int day, int startTime, int period,
int startDate, Set maintenancesWindowses) {
this.timeperiodid = timeperiodid;
this.timeperiodType = timeperiodType;
this.every = every;
this.month = month;
this.dayofweek = dayofweek;
this.day = day;
this.startTime = startTime;
this.period = period;
this.startDate = startDate;
this.maintenancesWindowses = maintenancesWindowses;
}
public long getTimeperiodid() {
return this.timeperiodid;
}
public void setTimeperiodid(long timeperiodid) {
this.timeperiodid = timeperiodid;
}
public int getTimeperiodType() {
return this.timeperiodType;
}
public void setTimeperiodType(int timeperiodType) {
this.timeperiodType = timeperiodType;
}
public int getEvery() {
return this.every;
}
public void setEvery(int every) {
this.every = every;
}
public int getMonth() {
return this.month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDayofweek() {
return this.dayofweek;
}
public void setDayofweek(int dayofweek) {
this.dayofweek = dayofweek;
}
public int getDay() {
return this.day;
}
public void setDay(int day) {
this.day = day;
}
public int getStartTime() {
return this.startTime;
}
public void setStartTime(int startTime) {
this.startTime = startTime;
}
public int getPeriod() {
return this.period;
}
public void setPeriod(int period) {
this.period = period;
}
public int getStartDate() {
return this.startDate;
}
public void setStartDate(int startDate) {
this.startDate = startDate;
}
public Set getMaintenancesWindowses() {
return this.maintenancesWindowses;
}
public void setMaintenancesWindowses(Set maintenancesWindowses) {
this.maintenancesWindowses = maintenancesWindowses;
}
}
| [
"drudgery@live.com"
] | drudgery@live.com |
c9486a556063e4247e5c33a1bff6e1af55d27776 | a6fcc58f04231290c00bddf265736f3bf940a8e0 | /src/main/java/cl/duoc/dej/tienda/service/PedidoService.java | 6e43947a4ba917b134b3de8360fd7e1508dc8d3e | [] | no_license | juangriffin/prueba3hierberia | 637446ca3e333248089e7e5970f1d1d41a84932b | da7c68e533a78e102bba3f1689b569040cc76fc3 | refs/heads/master | 2021-08-22T08:41:30.052135 | 2017-11-29T19:30:11 | 2017-11-29T19:30:11 | 112,518,275 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,499 | java | package cl.duoc.dej.tienda.service;
import cl.duoc.dej.tienda.entity.Pedido;
import cl.duoc.dej.tienda.exception.PedidoNoEncontradoException;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
@Stateless
public class PedidoService implements Serializable {
static final long serialVersionUID = 66L;
@PersistenceContext
private EntityManager em;
Logger logger = Logger.getLogger(this.getClass().getSimpleName());
public Pedido crearPedido(Pedido pedido) {
em.persist(pedido);
return pedido;
}
public Pedido getPedidoById(Long id) {
return em.find(Pedido.class, id);
}
public List<Pedido> getPedidos() {
TypedQuery<Pedido> query = em.createQuery("SELECT p FROM Pedido p", Pedido.class);
return query.getResultList();
}
public void eliminarPedido(Long pedidoId) throws PedidoNoEncontradoException {
Pedido p = getPedidoById(pedidoId);
if (p == null) {
String mensajeException = String.format("Pedido con ID %s no encontrado para ser eliminado", pedidoId);
logger.log(Level.SEVERE, mensajeException);
throw new PedidoNoEncontradoException(mensajeException);
}
em.remove(p);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
1697a673a9a41329c62cceb27abadcf906c00986 | 6826e00925044a43e6175c7e5e0fe755e02b2e69 | /Email_crypt/unifiedEmail/src/main/java/com/indeema/mail/browse/SelectedConversationsActionMenu.java | 19efd686edc8f8604836c52fe64f04f4276d973d | [] | no_license | nazarcybulskij/DefaultEmail-OpenKeyChain | 6e7fa5125221c218e3b08c2c918554da68dd265d | 415ee83155a73725ba7bb768554e7813a8c6114c | refs/heads/master | 2016-09-11T02:53:17.425139 | 2015-03-08T20:54:20 | 2015-03-08T20:54:20 | 31,715,869 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 24,944 | java | /*
* Copyright (C) 2010 Google Inc.
* Licensed to The Android Open Source Project.
*
* 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.indeema.mail.browse;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.indeema.mail.R;
import com.indeema.mail.analytics.Analytics;
import com.indeema.mail.providers.Account;
import com.indeema.mail.providers.AccountObserver;
import com.indeema.mail.providers.Conversation;
import com.indeema.mail.providers.Folder;
import com.indeema.mail.providers.MailAppProvider;
import com.indeema.mail.providers.Settings;
import com.indeema.mail.providers.UIProvider;
import com.indeema.mail.ui.ControllableActivity;
import com.indeema.mail.ui.ConversationListCallbacks;
import com.indeema.mail.ui.ConversationSelectionSet;
import com.indeema.mail.ui.ConversationSetObserver;
import com.indeema.mail.ui.ConversationUpdater;
import com.indeema.mail.ui.DestructiveAction;
import com.indeema.mail.ui.FolderOperation;
import com.indeema.mail.ui.FolderSelectionDialog;
import com.indeema.mail.ui.MailActionBarView;
import com.indeema.mail.utils.LogTag;
import com.indeema.mail.utils.LogUtils;
import com.indeema.mail.utils.Utils;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import java.util.Collection;
import java.util.List;
/**
* A component that displays a custom view for an {@code ActionBar}'s {@code
* ContextMode} specific to operating on a set of conversations.
*/
public class SelectedConversationsActionMenu implements ActionMode.Callback,
ConversationSetObserver {
private static final String LOG_TAG = LogTag.getLogTag();
/**
* The set of conversations to display the menu for.
*/
protected final ConversationSelectionSet mSelectionSet;
private final ControllableActivity mActivity;
private final ConversationListCallbacks mListController;
/**
* Context of the activity. A dialog requires the context of an activity rather than the global
* root context of the process. So mContext = mActivity.getApplicationContext() will fail.
*/
private final Context mContext;
@VisibleForTesting
private ActionMode mActionMode;
private boolean mActivated = false;
private Menu mMenu;
/** Object that can update conversation state on our behalf. */
private final ConversationUpdater mUpdater;
private Account mAccount;
private final Folder mFolder;
private AccountObserver mAccountObserver;
public SelectedConversationsActionMenu(
ControllableActivity activity, ConversationSelectionSet selectionSet, Folder folder) {
mActivity = activity;
mListController = activity.getListHandler();
mSelectionSet = selectionSet;
mAccountObserver = new AccountObserver() {
@Override
public void onChanged(Account newAccount) {
mAccount = newAccount;
}
};
mAccount = mAccountObserver.initialize(activity.getAccountController());
mFolder = folder;
mContext = mActivity.getActivityContext();
mUpdater = activity.getConversationUpdater();
FolderSelectionDialog.setDialogDismissed();
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
boolean handled = true;
// If the user taps a new menu item, commit any existing destructive actions.
mListController.commitDestructiveActions(true);
final int itemId = item.getItemId();
Analytics.getInstance().sendMenuItemEvent(Analytics.EVENT_CATEGORY_MENU_ITEM, itemId,
"cab_mode", 0);
if (itemId == R.id.delete) {
LogUtils.i(LOG_TAG, "Delete selected from CAB menu");
performDestructiveAction(R.id.delete);
} else if (itemId == R.id.discard_drafts) {
performDestructiveAction(R.id.discard_drafts);
} else if (itemId == R.id.archive) {
LogUtils.i(LOG_TAG, "Archive selected from CAB menu");
performDestructiveAction(R.id.archive);
} else if (itemId == R.id.remove_folder) {
destroy(R.id.remove_folder, mSelectionSet.values(),
mUpdater.getDeferredRemoveFolder(mSelectionSet.values(), mFolder, true,
true, true));
} else if (itemId == R.id.mute) {
destroy(R.id.mute, mSelectionSet.values(), mUpdater.getBatchAction(R.id.mute));
} else if (itemId == R.id.report_spam) {
destroy(R.id.report_spam, mSelectionSet.values(),
mUpdater.getBatchAction(R.id.report_spam));
} else if (itemId == R.id.mark_not_spam) {
// Currently, since spam messages are only shown in list with other spam messages,
// marking a message not as spam is a destructive action
destroy (R.id.mark_not_spam,
mSelectionSet.values(), mUpdater.getBatchAction(R.id.mark_not_spam)) ;
} else if (itemId == R.id.report_phishing) {
destroy(R.id.report_phishing,
mSelectionSet.values(), mUpdater.getBatchAction(R.id.report_phishing));
} else if (itemId == R.id.read) {
markConversationsRead(true);
} else if (itemId == R.id.unread) {
markConversationsRead(false);
} else if (itemId == R.id.star) {
starConversations(true);
} else if (itemId == R.id.remove_star) {
if (mFolder.isType(UIProvider.FolderType.STARRED)) {
LogUtils.d(LOG_TAG, "We are in a starred folder, removing the star");
performDestructiveAction(R.id.remove_star);
} else {
LogUtils.d(LOG_TAG, "Not in a starred folder.");
starConversations(false);
}
} else if (itemId == R.id.move_to || itemId == R.id.change_folders) {
boolean cantMove = false;
Account acct = mAccount;
// Special handling for virtual folders
if (mFolder.supportsCapability(UIProvider.FolderCapabilities.IS_VIRTUAL)) {
Uri accountUri = null;
for (Conversation conv: mSelectionSet.values()) {
if (accountUri == null) {
accountUri = conv.accountUri;
} else if (!accountUri.equals(conv.accountUri)) {
// Tell the user why we can't do this
Toast.makeText(mContext, R.string.cant_move_or_change_labels,
Toast.LENGTH_LONG).show();
cantMove = true;
return handled;
}
}
if (!cantMove) {
// Get the actual account here, so that we display its folders in the dialog
acct = MailAppProvider.getAccountFromAccountUri(accountUri);
}
}
if (!cantMove) {
final FolderSelectionDialog dialog = FolderSelectionDialog.getInstance(
mContext, acct, mUpdater, mSelectionSet.values(), true, mFolder,
item.getItemId() == R.id.move_to);
if (dialog != null) {
dialog.show();
}
}
} else if (itemId == R.id.move_to_inbox) {
new AsyncTask<Void, Void, Folder>() {
@Override
protected Folder doInBackground(final Void... params) {
// Get the "move to" inbox
return Utils.getFolder(mContext, mAccount.settings.moveToInbox,
true /* allowHidden */);
}
@Override
protected void onPostExecute(final Folder moveToInbox) {
final List<FolderOperation> ops = Lists.newArrayListWithCapacity(1);
// Add inbox
ops.add(new FolderOperation(moveToInbox, true));
mUpdater.assignFolder(ops, mSelectionSet.values(), true,
true /* showUndo */, false /* isMoveTo */);
}
}.execute((Void[]) null);
} else if (itemId == R.id.mark_important) {
markConversationsImportant(true);
} else if (itemId == R.id.mark_not_important) {
if (mFolder.supportsCapability(UIProvider.FolderCapabilities.ONLY_IMPORTANT)) {
performDestructiveAction(R.id.mark_not_important);
} else {
markConversationsImportant(false);
}
} else {
handled = false;
}
return handled;
}
/**
* Clear the selection and perform related UI changes to keep the state consistent.
*/
private void clearSelection() {
mSelectionSet.clear();
}
/**
* Update the underlying list adapter and redraw the menus if necessary.
*/
private void updateSelection() {
mUpdater.refreshConversationList();
if (mActionMode != null) {
// Calling mActivity.invalidateOptionsMenu doesn't have the correct behavior, since
// the action mode is not refreshed when activity's options menu is invalidated.
// Since we need to refresh our own menu, it is easy to call onPrepareActionMode
// directly.
onPrepareActionMode(mActionMode, mActionMode.getMenu());
}
}
private void performDestructiveAction(final int action) {
final Collection<Conversation> conversations = mSelectionSet.values();
final Settings settings = mAccount.settings;
final boolean showDialog;
// no confirmation dialog by default unless user preference or common sense dictates one
if (action == R.id.discard_drafts) {
// drafts are lost forever, so always confirm
showDialog = true;
} else if (settings != null && (action == R.id.archive || action == R.id.delete)) {
showDialog = (action == R.id.delete) ? settings.confirmDelete : settings.confirmArchive;
} else {
showDialog = false;
}
if (showDialog) {
mUpdater.makeDialogListener(action, true /* fromSelectedSet */);
final int resId;
if (action == R.id.delete) {
resId = R.plurals.confirm_delete_conversation;
} else if (action == R.id.discard_drafts) {
resId = R.plurals.confirm_discard_drafts_conversation;
} else {
resId = R.plurals.confirm_archive_conversation;
}
final CharSequence message = Utils.formatPlural(mContext, resId, conversations.size());
final ConfirmDialogFragment c = ConfirmDialogFragment.newInstance(message);
c.displayDialog(mActivity.getFragmentManager());
} else {
// No need to show the dialog, just make a destructive action and destroy the
// selected set immediately.
// TODO(viki): Stop using the deferred action here. Use the registered action.
destroy(action, conversations, mUpdater.getDeferredBatchAction(action));
}
}
/**
* Destroy these conversations through the conversation updater
* @param actionId the ID of the action: R.id.archive, R.id.delete, ...
* @param target conversations to destroy
* @param action the action that performs the destruction
*/
private void destroy(int actionId, final Collection<Conversation> target,
final DestructiveAction action) {
LogUtils.i(LOG_TAG, "About to remove %d converations", target.size());
mUpdater.delete(actionId, target, action, true);
}
/**
* Marks the read state of currently selected conversations (<b>and</b> the backing storage)
* to the value provided here.
* @param read is true if the conversations are to be marked as read, false if they are to be
* marked unread.
*/
private void markConversationsRead(boolean read) {
final Collection<Conversation> targets = mSelectionSet.values();
// The conversations are marked read but not viewed.
mUpdater.markConversationsRead(targets, read, false);
updateSelection();
}
/**
* Marks the important state of currently selected conversations (<b>and</b> the backing
* storage) to the value provided here.
* @param important is true if the conversations are to be marked as important, false if they
* are to be marked not important.
*/
private void markConversationsImportant(boolean important) {
final Collection<Conversation> target = mSelectionSet.values();
final int priority = important ? UIProvider.ConversationPriority.HIGH
: UIProvider.ConversationPriority.LOW;
mUpdater.updateConversation(target, UIProvider.ConversationColumns.PRIORITY, priority);
// Update the conversations in the selection too.
for (final Conversation c : target) {
c.priority = priority;
}
updateSelection();
}
/**
* Marks the selected conversations with the star setting provided here.
* @param star true if you want all the conversations to have stars, false if you want to remove
* stars from all conversations
*/
private void starConversations(boolean star) {
final Collection<Conversation> target = mSelectionSet.values();
mUpdater.updateConversation(target, UIProvider.ConversationColumns.STARRED, star);
// Update the conversations in the selection too.
for (final Conversation c : target) {
c.starred = star;
}
updateSelection();
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mSelectionSet.addObserver(this);
final MenuInflater inflater = mActivity.getMenuInflater();
inflater.inflate(R.menu.conversation_list_selection_actions_menu, menu);
mActionMode = mode;
mMenu = menu;
updateCount();
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// Update the actionbar to select operations available on the current conversation.
final Collection<Conversation> conversations = mSelectionSet.values();
boolean showStar = false;
boolean showMarkUnread = false;
boolean showMarkImportant = false;
boolean showMarkNotSpam = false;
boolean showMarkAsPhishing = false;
for (Conversation conversation : conversations) {
if (!conversation.starred) {
showStar = true;
}
if (conversation.read) {
showMarkUnread = true;
}
if (!conversation.isImportant()) {
showMarkImportant = true;
}
if (conversation.spam) {
showMarkNotSpam = true;
}
if (!conversation.phishing) {
showMarkAsPhishing = true;
}
if (showStar && showMarkUnread && showMarkImportant && showMarkNotSpam &&
showMarkAsPhishing) {
break;
}
}
final MenuItem star = menu.findItem(R.id.star);
star.setVisible(showStar);
final MenuItem unstar = menu.findItem(R.id.remove_star);
unstar.setVisible(!showStar);
final MenuItem read = menu.findItem(R.id.read);
read.setVisible(!showMarkUnread);
final MenuItem unread = menu.findItem(R.id.unread);
unread.setVisible(showMarkUnread);
// We only ever show one of:
// 1) remove folder
// 2) archive
// 3) If we show neither archive or remove folder, then show a disabled
// archive icon if the setting for that is true.
final MenuItem removeFolder = menu.findItem(R.id.remove_folder);
final MenuItem moveTo = menu.findItem(R.id.move_to);
final MenuItem moveToInbox = menu.findItem(R.id.move_to_inbox);
final boolean showRemoveFolder = mFolder != null && mFolder.isType(UIProvider.FolderType.DEFAULT)
&& mFolder.supportsCapability(UIProvider.FolderCapabilities.CAN_ACCEPT_MOVED_MESSAGES)
&& !mFolder.isProviderFolder()
&& mAccount.supportsCapability(UIProvider.AccountCapabilities.ARCHIVE);
final boolean showMoveTo = mFolder != null
&& mFolder.supportsCapability(UIProvider.FolderCapabilities.ALLOWS_REMOVE_CONVERSATION);
final boolean showMoveToInbox = mFolder != null
&& mFolder.supportsCapability(UIProvider.FolderCapabilities.ALLOWS_MOVE_TO_INBOX);
removeFolder.setVisible(showRemoveFolder);
moveTo.setVisible(showMoveTo);
moveToInbox.setVisible(showMoveToInbox);
if (mFolder != null && showRemoveFolder) {
removeFolder.setTitle(mActivity.getActivityContext().getString(R.string.remove_folder,
mFolder.name));
}
final MenuItem archive = menu.findItem(R.id.archive);
final boolean accountSupportsArchive =
mAccount.supportsCapability(UIProvider.AccountCapabilities.ARCHIVE);
boolean showArchive = accountSupportsArchive
&& mFolder.supportsCapability(UIProvider.FolderCapabilities.ARCHIVE);
if (archive == null) {
showArchive = false;
} else {
archive.setVisible(showArchive);
}
// We may want to reshow the archive menu item, but only if the account supports archiving
if (!showArchive && accountSupportsArchive) {
if (!showRemoveFolder &&
Utils.shouldShowDisabledArchiveIcon(mActivity.getActivityContext())) {
archive.setEnabled(false);
archive.setVisible(true);
}
}
final MenuItem spam = menu.findItem(R.id.report_spam);
spam.setVisible(!showMarkNotSpam
&& mAccount.supportsCapability(UIProvider.AccountCapabilities.REPORT_SPAM)
&& mFolder.supportsCapability(UIProvider.FolderCapabilities.REPORT_SPAM));
final MenuItem notSpam = menu.findItem(R.id.mark_not_spam);
notSpam.setVisible(showMarkNotSpam &&
mAccount.supportsCapability(UIProvider.AccountCapabilities.REPORT_SPAM) &&
mFolder.supportsCapability(UIProvider.FolderCapabilities.MARK_NOT_SPAM));
final MenuItem phishing = menu.findItem(R.id.report_phishing);
phishing.setVisible(showMarkAsPhishing &&
mAccount.supportsCapability(UIProvider.AccountCapabilities.REPORT_PHISHING) &&
mFolder.supportsCapability(UIProvider.FolderCapabilities.REPORT_PHISHING));
final MenuItem mute = menu.findItem(R.id.mute);
if (mute != null) {
mute.setVisible(mAccount.supportsCapability(UIProvider.AccountCapabilities.MUTE)
&& (mFolder != null && mFolder.isInbox()));
}
final MenuItem markImportant = menu.findItem(R.id.mark_important);
markImportant.setVisible(showMarkImportant
&& mAccount.supportsCapability(UIProvider.AccountCapabilities.MARK_IMPORTANT));
final MenuItem markNotImportant = menu.findItem(R.id.mark_not_important);
markNotImportant.setVisible(!showMarkImportant
&& mAccount.supportsCapability(UIProvider.AccountCapabilities.MARK_IMPORTANT));
final boolean showDelete = mFolder != null
&& mFolder.supportsCapability(UIProvider.FolderCapabilities.DELETE);
final MenuItem trash = menu.findItem(R.id.delete);
trash.setVisible(showDelete);
// We only want to show the discard drafts menu item if we are not showing the delete menu
// item, and the current folder is a draft folder and the account supports discarding
// drafts for a conversation
final boolean showDiscardDrafts = !showDelete && mFolder != null && mFolder.isDraft() &&
mAccount.supportsCapability(UIProvider.AccountCapabilities.DISCARD_CONVERSATION_DRAFTS);
final MenuItem discardDrafts = menu.findItem(R.id.discard_drafts);
if (discardDrafts != null) {
discardDrafts.setVisible(showDiscardDrafts);
}
MailActionBarView.reorderMenu(mContext, mAccount, menu,
mContext.getResources().getInteger(R.integer.actionbar_max_items));
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
// The action mode may have been destroyed due to this menu being deactivated, in which
// case resources need not be cleaned up. However, if it was destroyed while this menu is
// active, that implies the user hit "Done" in the top right, and resources need cleaning.
if (mActivated) {
destroy();
// Only commit destructive actions if the user actually pressed
// done; otherwise, this was handled when we toggled conversation
// selection state.
mActivity.getListHandler().commitDestructiveActions(true);
}
mMenu = null;
}
@Override
public void onSetPopulated(ConversationSelectionSet set) {
// Noop. This object can only exist while the set is non-empty.
}
@Override
public void onSetEmpty() {
LogUtils.d(LOG_TAG, "onSetEmpty called.");
destroy();
}
@Override
public void onSetChanged(ConversationSelectionSet set) {
// If the set is empty, the menu buttons are invalid and most like the menu will be cleaned
// up. Avoid making any changes to stop flickering ("Add Star" -> "Remove Star") just
// before hiding the menu.
if (set.isEmpty()) {
return;
}
updateCount();
}
/**
* Updates the visible count of how many conversations are selected.
*/
private void updateCount() {
if (mActionMode != null) {
mActionMode.setTitle(mContext.getString(R.string.num_selected, mSelectionSet.size()));
}
}
/**
* Activates and shows this menu (essentially starting an {@link android.view.ActionMode}) if the selected
* set is non-empty.
*/
public void activate() {
if (mSelectionSet.isEmpty()) {
return;
}
mListController.onCabModeEntered();
mActivated = true;
if (mActionMode == null) {
mActivity.startActionMode(this);
}
}
/**
* De-activates and hides the menu (essentially disabling the {@link android.view.ActionMode}), but maintains
* the selection conversation set, and internally updates state as necessary.
*/
public void deactivate() {
mListController.onCabModeExited();
if (mActionMode != null) {
mActivated = false;
mActionMode.finish();
}
}
@VisibleForTesting
public boolean isActivated() {
return mActivated;
}
/**
* Destroys and cleans up the resources associated with this menu.
*/
private void destroy() {
deactivate();
mSelectionSet.removeObserver(this);
clearSelection();
mUpdater.refreshConversationList();
if (mAccountObserver != null) {
mAccountObserver.unregisterAndDestroy();
mAccountObserver = null;
}
}
/**
* Disable the selected conversations menu item associated with a command
* id.
*/
public void disableCommand(int id) {
enableMenuItem(id, false);
}
/**
* Enable the selected conversations menu item associated with a command
* id.
*/
public void enableCommand(int id) {
enableMenuItem(id, true);
}
private void enableMenuItem(int id, boolean enable) {
if (mActivated) {
MenuItem item = mMenu.findItem(id);
if (item != null) {
item.setEnabled(enable);
}
}
}
}
| [
"nazar.cybulskij@optigra-soft.com"
] | nazar.cybulskij@optigra-soft.com |
8111ab476d6c21fc63ec97b4f0240f613ca1e11b | 30bd7991ace10e2568e3ce4558e2929147437a25 | /OSource/Android Play/Android_Projects/maps/src/com/example/mapdemo/StreetViewPanoramaEventsDemoActivity.java | 4bdcc85c810aa088bf0830a7abd1179cf4f86b10 | [] | no_license | Mundhey/Engineering-Stuff | 8c478d922f00e4cc5ae755ec645e36d59cdc8535 | 4f770c58ffbe9d62994467165c482919f2bf7cf8 | refs/heads/master | 2021-01-17T07:41:20.055909 | 2016-07-26T02:32:46 | 2016-07-26T02:32:46 | 27,905,966 | 2 | 1 | null | null | null | null | UTF-8 | Java | false | false | 5,022 | java | /*
* Copyright (C) 2012 The Android Open Source Project
*
* 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.example.mapdemo;
import com.google.android.gms.maps.OnStreetViewPanoramaReadyCallback;
import com.google.android.gms.maps.StreetViewPanorama;
import com.google.android.gms.maps.StreetViewPanorama.OnStreetViewPanoramaCameraChangeListener;
import com.google.android.gms.maps.StreetViewPanorama.OnStreetViewPanoramaChangeListener;
import com.google.android.gms.maps.StreetViewPanorama.OnStreetViewPanoramaClickListener;
import com.google.android.gms.maps.SupportStreetViewPanoramaFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.StreetViewPanoramaCamera;
import com.google.android.gms.maps.model.StreetViewPanoramaLocation;
import com.google.android.gms.maps.model.StreetViewPanoramaOrientation;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
/**
* This shows how to listen to some {@link StreetViewPanorama} events.
*/
public class StreetViewPanoramaEventsDemoActivity extends FragmentActivity
implements OnStreetViewPanoramaChangeListener, OnStreetViewPanoramaCameraChangeListener,
OnStreetViewPanoramaClickListener {
// George St, Sydney
private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689);
private StreetViewPanorama mStreetViewPanorama;
private TextView mPanoChangeTimesTextView;
private TextView mPanoCameraChangeTextView;
private TextView mPanoClickTextView;
private int mPanoChangeTimes = 0;
private int mPanoCameraChangeTimes = 0;
private int mPanoClickTimes = 0;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.street_view_panorama_events_demo);
mPanoChangeTimesTextView = (TextView) findViewById(R.id.change_pano);
mPanoCameraChangeTextView = (TextView) findViewById(R.id.change_camera);
mPanoClickTextView = (TextView) findViewById(R.id.click_pano);
SupportStreetViewPanoramaFragment streetViewPanoramaFragment =
(SupportStreetViewPanoramaFragment)
getSupportFragmentManager().findFragmentById(R.id.streetviewpanorama);
streetViewPanoramaFragment.getStreetViewPanoramaAsync(
new OnStreetViewPanoramaReadyCallback() {
@Override
public void onStreetViewPanoramaReady(StreetViewPanorama panorama) {
mStreetViewPanorama = panorama;
mStreetViewPanorama.setOnStreetViewPanoramaChangeListener(
StreetViewPanoramaEventsDemoActivity.this);
mStreetViewPanorama.setOnStreetViewPanoramaCameraChangeListener(
StreetViewPanoramaEventsDemoActivity.this);
mStreetViewPanorama.setOnStreetViewPanoramaClickListener(
StreetViewPanoramaEventsDemoActivity.this);
// Only set the panorama to SYDNEY on startup (when no panoramas have been
// loaded which is when the savedInstanceState is null).
if (savedInstanceState == null) {
mStreetViewPanorama.setPosition(SYDNEY);
}
}
});
}
@Override
public void onStreetViewPanoramaChange(StreetViewPanoramaLocation location) {
if (location != null) {
mPanoChangeTimesTextView.setText("Times panorama changed=" + ++mPanoChangeTimes);
}
}
@Override
public void onStreetViewPanoramaCameraChange(StreetViewPanoramaCamera camera) {
mPanoCameraChangeTextView.setText("Times camera changed=" + ++mPanoCameraChangeTimes);
}
@Override
public void onStreetViewPanoramaClick(StreetViewPanoramaOrientation orientation) {
Point point = mStreetViewPanorama.orientationToPoint(orientation);
if (point != null) {
mPanoClickTimes++;
mPanoClickTextView.setText(
"Times clicked=" + mPanoClickTimes);
mStreetViewPanorama.animateTo(
new StreetViewPanoramaCamera.Builder()
.orientation(orientation)
.zoom(mStreetViewPanorama.getPanoramaCamera().zoom)
.build(), 1000);
}
}
}
| [
"mundheyrohan@gmail.com"
] | mundheyrohan@gmail.com |
653e02578e2b33a30cca2ce3f0e741d51ba83a58 | 382f9eabf1df350b41a6950c2f35470b1d290e3c | /src/com/snake/field/Field.java | c2f0533bb777c6fcf492bca80b1365519cc5df2f | [] | no_license | x0152/Snake | 60c3c57d691f13c1203423dc2f56734d04d18edf | 96fdbe3396da750ac33740f60a72850acbb16050 | refs/heads/master | 2021-07-10T09:56:16.326856 | 2020-06-30T21:12:07 | 2020-06-30T21:12:07 | 158,110,496 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 902 | java | package com.snake.field;
import com.snake.Const;
import com.snake.field.cell.Cell;
import com.snake.field.cell.CellFood;
import com.snake.field.cell.EmpatyCell;
/**
* Created by x0152 on 11.07.16.
*/
public class Field {
public Field(){
cells = new Cell[(int)Const.HORIZONTAL_COUNT_CELLS]
[(int)Const.VERTICAL_COUNT_CELLS];
for(int i = 0; i < Const.HORIZONTAL_COUNT_CELLS; ++i){
for(int j = 0; j < Const.VERTICAL_COUNT_CELLS; ++j){
cells[i][j] = new EmpatyCell();
}
}
}
public Cell[][] GetCells(){
return this.cells;
}
public void Clear(){
for(int i = 0; i < Const.HORIZONTAL_COUNT_CELLS; ++i){
for(int j = 0; j < Const.VERTICAL_COUNT_CELLS; ++j){
cells[i][j] = new EmpatyCell();
}
}
}
private Cell[][] cells;
}
| [
"egorevdomashenko@mail.ru"
] | egorevdomashenko@mail.ru |
0723e0d58eac3fedaa843494310d95c99193d173 | 1aef6c82b3fc969abe7c5fc577563a19748d0921 | /app/src/main/java/com/proximate/evaluacion/network/DataItem.java | c05730e6fd7594eebef3827e8e830c43401ed400 | [] | no_license | G1L21088/ProximateEv | 44df8851f4f41219ec302f49e279fea257c07f66 | e87e544beacc8b486f9a515cc774ce8a083049b0 | refs/heads/master | 2021-08-31T18:02:48.080792 | 2017-12-22T09:08:16 | 2017-12-22T09:08:16 | 115,066,904 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,285 | java | package com.proximate.evaluacion.network;
import java.util.List;
import com.google.gson.annotations.SerializedName;
public class DataItem{
@SerializedName("apellidos")
private String apellidos;
@SerializedName("eliminado")
private int eliminado;
@SerializedName("documentos_abrev")
private String documentosAbrev;
@SerializedName("correo")
private String correo;
@SerializedName("numero_documento")
private String numeroDocumento;
@SerializedName("documentos_id")
private int documentosId;
@SerializedName("documentos_label")
private String documentosLabel;
@SerializedName("estados_usuarios_label")
private String estadosUsuariosLabel;
@SerializedName("id")
private int id;
@SerializedName("ultima_sesion")
private String ultimaSesion;
@SerializedName("secciones")
private List<SeccionesItem> secciones;
@SerializedName("nombres")
private String nombres;
public void setApellidos(String apellidos){
this.apellidos = apellidos;
}
public String getApellidos(){
return apellidos;
}
public void setEliminado(int eliminado){
this.eliminado = eliminado;
}
public int getEliminado(){
return eliminado;
}
public void setDocumentosAbrev(String documentosAbrev){
this.documentosAbrev = documentosAbrev;
}
public String getDocumentosAbrev(){
return documentosAbrev;
}
public void setCorreo(String correo){
this.correo = correo;
}
public String getCorreo(){
return correo;
}
public void setNumeroDocumento(String numeroDocumento){
this.numeroDocumento = numeroDocumento;
}
public String getNumeroDocumento(){
return numeroDocumento;
}
public void setDocumentosId(int documentosId){
this.documentosId = documentosId;
}
public int getDocumentosId(){
return documentosId;
}
public void setDocumentosLabel(String documentosLabel){
this.documentosLabel = documentosLabel;
}
public String getDocumentosLabel(){
return documentosLabel;
}
public void setEstadosUsuariosLabel(String estadosUsuariosLabel){
this.estadosUsuariosLabel = estadosUsuariosLabel;
}
public String getEstadosUsuariosLabel(){
return estadosUsuariosLabel;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setUltimaSesion(String ultimaSesion){
this.ultimaSesion = ultimaSesion;
}
public String getUltimaSesion(){
return ultimaSesion;
}
public void setSecciones(List<SeccionesItem> secciones){
this.secciones = secciones;
}
public List<SeccionesItem> getSecciones(){
return secciones;
}
public void setNombres(String nombres){
this.nombres = nombres;
}
public String getNombres(){
return nombres;
}
@Override
public String toString(){
return
"DataItem{" +
"apellidos = '" + apellidos + '\'' +
",eliminado = '" + eliminado + '\'' +
",documentos_abrev = '" + documentosAbrev + '\'' +
",correo = '" + correo + '\'' +
",numero_documento = '" + numeroDocumento + '\'' +
",documentos_id = '" + documentosId + '\'' +
",documentos_label = '" + documentosLabel + '\'' +
",estados_usuarios_label = '" + estadosUsuariosLabel + '\'' +
",id = '" + id + '\'' +
",ultima_sesion = '" + ultimaSesion + '\'' +
",secciones = '" + secciones + '\'' +
",nombres = '" + nombres + '\'' +
"}";
}
} | [
"gilsantaella@gmail.com"
] | gilsantaella@gmail.com |
c5f24ebc55f1f22b87ae1b6d13cf56ff4423530c | d0bd68dc668748b7b4e5ad2947ff59fa1cef49f0 | /DesignPattern/src/main/java/com/peng/designpattern/proxy/staticproxy/ITeacherDao.java | c61b17aaee7577f5bfb2cc8580fca204e64d2df0 | [] | no_license | HJPeng97/repo2 | 1118193ce95c529e8734b554ed4bb5de7b4fb035 | ae59087ac577cfd0f0c12161a3ec9931fe3d689a | refs/heads/master | 2023-01-03T10:08:33.041476 | 2020-10-31T10:22:23 | 2020-10-31T10:22:23 | 308,802,287 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 195 | java | package com.peng.designpattern.proxy.staticproxy;
/**
* 接口,让目标对象(被代理的对象)和代理对象都实现该接口
*/
public interface ITeacherDao {
void teach();
}
| [
"1062314744@qq.com"
] | 1062314744@qq.com |
f3be0a489b53c4ede986f82b0259d948f9841ce6 | 0161530667749dee49e35415e88af237dd0acb71 | /demo/src/main/java/com/example/entities/concretes/ImageForCv.java | f29b65381d8698f108d43851742a88a28ea87ce5 | [
"MIT"
] | permissive | sebakir/HrmsProject | bc3270d7e8e5aa962549d28999b552a7864da08b | d7431c1e504445dd80b1cb95bea0e91ec319737b | refs/heads/master | 2023-07-14T12:18:49.881972 | 2021-08-23T19:30:04 | 2021-08-23T19:30:04 | 370,149,823 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 685 | java | package com.example.entities.concretes;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Data
@Table(name = "cv_images")
@NoArgsConstructor
@AllArgsConstructor
public class ImageForCv extends Base {
@Column(name = "url")
private String url;
@OneToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "jobseeker_id", referencedColumnName = "user_id")
private Jobseeker jobseeker;
}
| [
"seckin.bakir07@gmail.com"
] | seckin.bakir07@gmail.com |
98bc4a78920379eb21949ba841a4cacecc2f4603 | 7b4f2fd333b304d54f776d143b8d7c9d1025910c | /src/main/java/happe/marco/petclinic/bootstrap/DataLoader.java | 2136fc64f1fb0951bc2a90abcd8cf5945aee168a | [] | no_license | Entremetier/pet-clinic | 75b476ba7b9ecbed374c60ae00132611c29aaa12 | f0715ca1ac58e1f71ea1e075f5a21956b2ff8537 | refs/heads/master | 2021-02-10T00:42:58.018945 | 2020-05-23T09:56:33 | 2020-05-23T09:56:33 | 244,339,021 | 0 | 0 | null | 2020-05-06T16:24:56 | 2020-03-02T10:08:39 | Java | UTF-8 | Java | false | false | 4,475 | java | package happe.marco.petclinic.bootstrap;
import happe.marco.petclinic.model.*;
import happe.marco.petclinic.services.*;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
@Component
public class DataLoader implements CommandLineRunner {
private final OwnerService ownerService;
private final VetService vetService;
private final PetTypeService petTypeService;
private final SpecialtyService specialtyService;
private final VisitService visitService;
public DataLoader(OwnerService ownerService, VetService vetService, PetTypeService petTypeService,
SpecialtyService specialtyService, VisitService visitService) {
this.ownerService = ownerService;
this.vetService = vetService;
this.petTypeService = petTypeService;
this.specialtyService = specialtyService;
this.visitService = visitService;
}
@Override
public void run(String... args) throws Exception {
int count = petTypeService.findAll().size();
if (count == 0) {
loadData();
}
}
//beim persistieren von Daten muss die Methode aufgerufen werden, da sonst die Daten immer wieder in die Datenbank
//geschrieben werden, darum mit der if abfrage sicherstellen das die daten noch nicht in der db sind
//wenn count 0 ist wird die methode aufgerufen, sonst nicht
private void loadData() {
PetType dog = new PetType();
dog.setName("Dog");
PetType savedDogPetType = petTypeService.save(dog);
PetType cat = new PetType();
cat.setName("Cat");
PetType savedCatPetType = petTypeService.save(cat);
Speciality radiology = new Speciality();
radiology.setDescription("Radiology");
Speciality savedRadiology = specialtyService.save(radiology);
Speciality surgery = new Speciality();
surgery.setDescription("Surgery");
Speciality savedSurgery = specialtyService.save(surgery);
Speciality dentistry = new Speciality();
dentistry.setDescription("Dentistry");
Speciality savedDentistry = specialtyService.save(dentistry);
//mit dieser Zeile wird ein objekt erstellt
Owner.builder().firstName("Marco").lastName("Happe").address("Zuhause").city("Wien").telephone("555987").build();
Owner owner1 = new Owner();
owner1.setFirstName("Bart");
owner1.setLastName("Simpson");
owner1.setAddress("742 Evergreen Terrace");
owner1.setCity("Springfield");
owner1.setTelephone("9395550113");
Pet bartsPet = new Pet();
bartsPet.setPetType(savedDogPetType);
bartsPet.setOwner(owner1);
bartsPet.setBirthDate(LocalDate.now());
bartsPet.setName("Santas Little Helper");
owner1.getPets().add(bartsPet);
ownerService.save(owner1);
Owner owner2 = new Owner();
owner2.setFirstName("Lisa");
owner2.setLastName("Simpson");
owner2.setAddress("742 Evergreen Terrace");
owner2.setCity("Springfield");
owner2.setTelephone("9395550113");
Pet lisasPet = new Pet();
lisasPet.setPetType(savedCatPetType);
lisasPet.setOwner(owner2);
lisasPet.setBirthDate(LocalDate.now());
lisasPet.setName("Snowball II");
owner2.getPets().add(lisasPet);
ownerService.save(owner2);
Visit knechtRuprecht = new Visit();
knechtRuprecht.setPet(bartsPet);
knechtRuprecht.setDate(LocalDate.now());
knechtRuprecht.setDescription("Broken Leg");
visitService.save(knechtRuprecht);
Visit snowBallVisitOne = new Visit();
snowBallVisitOne.setPet(lisasPet);
snowBallVisitOne.setDate(LocalDate.now());
snowBallVisitOne.setDescription("Sneezy Kitten");
visitService.save(snowBallVisitOne);
System.out.println("Loaded Owners....");
Vet vet1 = new Vet();
vet1.setFirstName("Dr. Nick");
vet1.setLastName("Rivera");
vet1.getSpecialties().add(savedSurgery);
vet1.getSpecialties().add(savedDentistry);
vetService.save(vet1);
Vet vet2 = new Vet();
vet2.setFirstName("Dr. Julius");
vet2.setLastName("Hibbert");
vet2.getSpecialties().add(savedRadiology);
vetService.save(vet2);
System.out.println("Loaded Vets....");
}
}
| [
"marco.happe@icloud.com"
] | marco.happe@icloud.com |
4a0747c2a44788261130ca0821f3b4e66a54f15f | 35ccfeb4c2258ca13e6498ee00abd527773720b9 | /app/src/main/java/com/example/aditya/blynkv2/PlottingActivity.java | b292d898acf0f75eecd6d693d9f933d8639f3cbd | [] | no_license | AdityaIndoori/HridayaWifi | 63fb485d734a47a4d7d607d29ba1e41172721c6e | 5746db6beaf2c3ac3b8f4a42d1e8ec43531a360a | refs/heads/master | 2020-07-10T09:16:56.427424 | 2016-09-17T14:11:19 | 2016-09-17T14:11:19 | 68,455,187 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,853 | java | package com.example.aditya.blynkv2;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class PlottingActivity extends AppCompatActivity {
public static TextView valueText;
public static Button plotButton;
public static LineGraphSeries<DataPoint> mSeries1;
public static double graph2LastXValue;
public static double timeInterval,numberOfValues;
public static boolean clickStatus;
private static boolean connectionStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plotting);
//---mapping all the objects,Initialising Values
valueText=(TextView)findViewById(R.id.valueText);
plotButton=(Button)findViewById(R.id.plotButton);
GraphView graph = (GraphView) findViewById(R.id.graph);
mSeries1 = new LineGraphSeries<DataPoint>();
int xMax=10;
timeInterval=250*0.001;//ms
numberOfValues=xMax/timeInterval;
graph2LastXValue=0;
clickStatus=false;
//---GraphView parameters-----------
graph.addSeries(mSeries1);
graph.getViewport().setXAxisBoundsManual(true);;
graph.getViewport().setMinX(0);
graph.getViewport().setMaxX(xMax);
graph.getGridLabelRenderer().setGridColor(Color.GREEN);
graph.getGridLabelRenderer().setHorizontalLabelsColor(Color.WHITE);
graph.getGridLabelRenderer().setVerticalLabelsColor(Color.WHITE);
mSeries1.setColor(Color.GREEN);
//-------MISC--------------
plotButton.setText("Start Plotting");
valueText.setText("");
}
//initially since we have not clicked, clickStatus = false
public void plotClick(View view){
if (!clickStatus){
clickStatus=true;//to indicate we have clicked it
keepOnExec();
}
else{
clickStatus=false;
}
}
public class httppart extends AsyncTask<Void,Void,String>{
@Override
protected String doInBackground(Void... params) {
if (clickStatus)
{
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are available at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String forecast_url = "http://blynk-cloud.com/" + "4707453111104dea98a1118249b7de34" + "/pin/v1";
//final String isConnected_url="http://blynk-cloud.com/" + "4707453111104dea98a1118249b7de34" + "/isHardwareConnected";
Uri builtURi = Uri.parse(forecast_url).buildUpon().build();
//Uri builtURi2 = Uri.parse(isConnected_url).buildUpon().build();
Log.v("URL", "URL is: " + builtURi.toString());
//Log.v("URL2","URL2 is: "+ builtURi2.toString());
URL url = new URL(builtURi.toString());
//URL url2= new URL(builtURi2.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
forecastJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
forecastJsonStr = null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
forecastJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
Log.v("Tag", "Forecast JSON String" + forecastJsonStr);
//-------------MyPart Starts-------------
if (forecastJsonStr!=null){
String substr = null;
int i = 0;
i = forecastJsonStr.length();
substr = forecastJsonStr.substring(2, i - 3);
Log.v("PlotDoIn","The substring in Background is: "+substr);
return substr;
}
else
return null;
}
else
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//----MainCode of OnPost-----
if (result!=null)//implies we did get an output number
{
double ddata = Double.parseDouble(result);
Log.v("PlotOnPostExecute", ""+ddata);
valueText.setText(""+ddata);
mSeries1.appendData(new DataPoint(graph2LastXValue, ddata), true, (int) numberOfValues);
graph2LastXValue+=timeInterval;
plotButton.setText("Stop Plotting");
}
else{
plotButton.setText("Start Plotting");
}
}
}
public void keepOnExec(){
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
httppart httppartObj = new httppart();
httppartObj.execute();
handler.postDelayed(this,50);
}
},50);
}
} | [
"Aditya Indoori"
] | Aditya Indoori |
ea460a0af2ab884ecf6063405f5571b271b8f7d6 | 22ff5bc18a5cafd239c2621d09667e74c86edd03 | /app/src/main/java/com/hbdiye/newlechuangsmart/activity/InfraredActivity.java | 53c3c5da32fcaccb5c0ef71d08eb352c33f7cad7 | [] | no_license | a1019421612/NewLeChuang | dda9e42b6fd7e7ef80bae8c89c897a838acf215f | d542db2a656ae6221574a8bae36622a01c033834 | refs/heads/master | 2021-07-19T02:28:13.360372 | 2019-01-30T02:17:11 | 2019-01-30T02:17:11 | 150,920,488 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,341 | java | package com.hbdiye.newlechuangsmart.activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.coder.zzq.smartshow.toast.SmartToast;
import com.google.gson.Gson;
import com.hbdiye.newlechuangsmart.R;
import com.hbdiye.newlechuangsmart.adapter.InfraredAdapter;
import com.hbdiye.newlechuangsmart.bean.InfraredBean;
import com.hbdiye.newlechuangsmart.global.InterfaceManager;
import com.hbdiye.newlechuangsmart.view.SceneDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import static com.hbdiye.newlechuangsmart.global.InterfaceManager.HWGETREMOTE;
/**
*
*/
public class InfraredActivity extends BaseActivity {
@BindView(R.id.rv_infrared)
RecyclerView rvInfrared;
private InfraredAdapter adapter;
private List<InfraredBean.Remote_list> mList = new ArrayList<>();
private boolean editStatus = false;//编辑状态标志,默认false
private SceneDialog sceneDialog;
private String uuid = "";
@Override
protected void initData() {
getInfraredList();
}
private void getInfraredList() {
OkHttpUtils
.post()
.url(InterfaceManager.getInstance().getURL(HWGETREMOTE))
.addParams("app_id", InterfaceManager.APPID)
.addParams("app_type", InterfaceManager.APPKEY)
.build()
.execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
SmartToast.show("网络连接出错");
}
@Override
public void onResponse(String response, int id) {
if (TextUtils.isEmpty(response)) {
return;
}
InfraredBean infraredBean = new Gson().fromJson(response, InfraredBean.class);
if (infraredBean.success) {
if (mList.size() > 0) {
mList.clear();
}
List<InfraredBean.Remote_list> remote_list = infraredBean.remote_list;
mList.addAll(remote_list);
adapter.notifyDataSetChanged();
}
}
});
}
@Override
protected String getTitleName() {
return "遥控中心";
}
@Override
protected void initView() {
ivBaseEdit.setVisibility(View.VISIBLE);
ivBaseAdd.setVisibility(View.VISIBLE);
ivBaseAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// startActivityForResult(new Intent(InfraredActivity.this, ZuWangActivity.class), 100);
}
});
ivBaseEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (editStatus) {
ivBaseEdit.setImageResource(R.drawable.bianji2);
adapter.sceneStatusChange(editStatus);
editStatus = false;
} else {
ivBaseEdit.setImageResource(R.drawable.duigou);
adapter.sceneStatusChange(editStatus);
editStatus = true;
}
}
});
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
rvInfrared.setLayoutManager(manager);
adapter = new InfraredAdapter(mList);
rvInfrared.setAdapter(adapter);
handlerClicker();
}
private void handlerClicker() {
adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
String uuid = mList.get(position).uuid;
ArrayList<InfraredBean.Remote_list.Ir_list> ir_list = (ArrayList<InfraredBean.Remote_list.Ir_list>) mList.get(position).ir_list;
// startActivity(new Intent(InfraredActivity.this, RemoteDeviceListActivity.class)
// .putExtra("uuid", uuid)
// .putExtra("ir_list",ir_list)
// );
}
});
adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
@Override
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
InfraredBean.Remote_list remote_list = mList.get(position);
uuid = remote_list.uuid;
switch (view.getId()) {
case R.id.ll_scene_item_del:
AlertDialog.Builder builder = new AlertDialog.Builder(InfraredActivity.this);
builder.setMessage("确认删除遥控中心?");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
delRemote();
}
});
builder.setNegativeButton("取消", null);
builder.show();
break;
case R.id.ll_scene_item_edt:
sceneDialog = new SceneDialog(InfraredActivity.this, R.style.MyDialogStyle, dailogClicer, "遥控中心名称");
sceneDialog.setCanceledOnTouchOutside(true);
sceneDialog.show();
break;
}
}
});
}
private void delRemote() {
OkHttpUtils
.post()
.url(InterfaceManager.getInstance().getURL(InterfaceManager.DELREMOTE))
.addParams("app_id", InterfaceManager.APPID)
.addParams("app_type", InterfaceManager.APPKEY)
.addParams("uuid", uuid)
.build()
.execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
SmartToast.show("网络连接错误");
}
@Override
public void onResponse(String response, int id) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
String info = jsonObject.getString("info");
SmartToast.show(info);
if (success) {
getInfraredList();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public View.OnClickListener dailogClicer = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.app_cancle_tv:
sceneDialog.dismiss();
break;
case R.id.app_sure_tv:
String remoteName = sceneDialog.getSceneName();
if (TextUtils.isEmpty(remoteName)) {
SmartToast.show("遥控中心名称不能为空");
} else {
editremote(remoteName);
}
break;
}
}
};
private void editremote(String name) {
OkHttpUtils
.post()
.url(InterfaceManager.getInstance().getURL(InterfaceManager.EDITREMOTE))
.addParams("app_id", InterfaceManager.APPID)
.addParams("app_type", InterfaceManager.APPKEY)
.addParams("name", name)
.addParams("uuid", uuid)
.build()
.execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
SmartToast.show("网络连接错误");
}
@Override
public void onResponse(String response, int id) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
String info = jsonObject.getString("info");
SmartToast.show(info);
if (sceneDialog != null) {
sceneDialog.dismiss();
}
if (success) {
getInfraredList();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
@Override
protected int getLayoutID() {
return R.layout.activity_infrared;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
ButterKnife.bind(this);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 100) {
getInfraredList();
}
}
}
| [
"zhaochong@xzcysoft.com"
] | zhaochong@xzcysoft.com |
a26e673fb9ea28f2008d7e0016968ef7ff701e96 | 44a5aa7a85189383ac3ca7395d57a0648a25e842 | /java/duplicateZeros.java | 3b1e88a90ab63e23eee8d5dafbb454defd9a93fd | [] | no_license | ny5462/LeetCodeProblems | 3f38043e16de1079c883b336d4037eb89b47c4b3 | 466feefcdaa484d58086a4d5cd4dea2484477e1a | refs/heads/main | 2023-01-23T09:13:59.030705 | 2020-12-04T21:54:59 | 2020-12-04T21:54:59 | 318,643,407 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 359 | java | /** program to duplicate zeros in a position next next to it.
TC-O(n)
**/
class Solution{
public void duplicateZeros(int [] arr){
StringBuilder sb=new StringBuilder();
for(int i=0;i<arr.length;i++){
sb.append(arr[i]);
if(arr[i]==0){
sb.append(0);
}
}
for(int i=0;i<arr.length;i++){
arr[i]=Character.getNumericValue(sb.charAt(i));
}
}
| [
"nickkanakian7@gmail.com"
] | nickkanakian7@gmail.com |
fb48dc04412267e47e77d5328a0df2ea7843e031 | 33dd9dff76072ea1b4014c618c8ad365ac477e07 | /shop/WEB-INF/src/cn/shop/base/util/ImgUtil.java | cd129efc91b9dfa7ad26786fb42dc741faa13f55 | [] | no_license | gaoshaozhen/workspace | 8d04d690568ffbe01f6d3025c0deebf41d2a6991 | 313a84d78ee25a517c9e2fa8b0285b5a4a99709e | refs/heads/master | 2020-07-14T01:22:26.326546 | 2017-05-20T11:49:43 | 2017-05-20T11:49:43 | 66,636,679 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 178 | java | package cn.shop.base.util;
import java.awt.image.BufferedImage;
public class ImgUtil
{
public static BufferedImage getImg(String imgId)
{
return null;
}
}
| [
"2456071896@qq.com"
] | 2456071896@qq.com |
87ed8e263dfdba3f35d421adddab14aa851d5f70 | ff0c33ccd3bbb8a080041fbdbb79e29989691747 | /jdk.internal.vm.compiler/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/memory/WriteNode.java | 9f8f671b3a970963a408a9b52b5500b2af21b460 | [] | no_license | jiecai58/jdk15 | 7d0f2e518e3f6669eb9ebb804f3c89bbfb2b51f0 | b04691a72e51947df1b25c31175071f011cb9bbe | refs/heads/main | 2023-02-25T00:30:30.407901 | 2021-01-29T04:48:33 | 2021-01-29T04:48:33 | 330,704,930 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,075 | java | /*
* Copyright (c) 2011, 2020, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package org.graalvm.compiler.nodes.memory;
import org.graalvm.compiler.core.common.LIRKind;
import org.graalvm.compiler.core.common.type.Stamp;
import org.graalvm.compiler.graph.Node;
import org.graalvm.compiler.graph.NodeClass;
import org.graalvm.compiler.graph.spi.Canonicalizable;
import org.graalvm.compiler.graph.spi.CanonicalizerTool;
import org.graalvm.compiler.nodeinfo.NodeInfo;
import org.graalvm.compiler.nodes.NodeView;
import org.graalvm.compiler.nodes.ValueNode;
import org.graalvm.compiler.nodes.memory.address.AddressNode;
import org.graalvm.compiler.nodes.spi.NodeLIRBuilderTool;
import jdk.internal.vm.compiler.word.LocationIdentity;
/**
* Writes a given {@linkplain #value() value} a {@linkplain FixedAccessNode memory location}.
*/
@NodeInfo(nameTemplate = "Write#{p#location/s}")
public class WriteNode extends AbstractWriteNode implements LIRLowerableAccess, Canonicalizable {
public static final NodeClass<WriteNode> TYPE = NodeClass.create(WriteNode.class);
public WriteNode(AddressNode address, LocationIdentity location, ValueNode value, BarrierType barrierType) {
super(TYPE, address, location, value, barrierType);
}
protected WriteNode(NodeClass<? extends WriteNode> c, AddressNode address, LocationIdentity location, ValueNode value, BarrierType barrierType) {
super(c, address, location, value, barrierType);
}
@Override
public void generate(NodeLIRBuilderTool gen) {
LIRKind writeKind = gen.getLIRGeneratorTool().getLIRKind(value().stamp(NodeView.DEFAULT));
gen.getLIRGeneratorTool().getArithmetic().emitStore(writeKind, gen.operand(address), gen.operand(value()), gen.state(this));
}
@Override
public Stamp getAccessStamp(NodeView view) {
return value().stamp(view);
}
@Override
public boolean canNullCheck() {
return true;
}
@Override
public boolean hasSideEffect() {
/*
* Writes to newly allocated objects don't have a visible side-effect to the interpreter
*/
if (getLocationIdentity().equals(LocationIdentity.INIT_LOCATION)) {
return false;
}
return super.hasSideEffect();
}
@Override
public Node canonical(CanonicalizerTool tool) {
if (tool.canonicalizeReads() && hasExactlyOneUsage() && next() instanceof WriteNode) {
WriteNode write = (WriteNode) next();
if (write.lastLocationAccess == this && write.getAddress() == getAddress() && getAccessStamp(NodeView.DEFAULT).isCompatible(write.getAccessStamp(NodeView.DEFAULT))) {
write.setLastLocationAccess(getLastLocationAccess());
return write;
}
}
return this;
}
@Override
public LocationIdentity getKilledLocationIdentity() {
return getLocationIdentity();
}
}
| [
"caijie2@tuhu.cn"
] | caijie2@tuhu.cn |
3e4f72416b96cea04cb21b70535a5467a2ac2ba9 | 6138af219efc3a8f31060e30ebc532ffcbad1768 | /astrogrid/adql2/adqlbase/src/java/org/astrogrid/adql/Node.java | 949ca65669931b462857ab007dac37deefe29670 | [] | no_license | Javastro/astrogrid-legacy | dd794b7867a4ac650d1a84bdef05dfcd135b8bb6 | 51bdbec04bacfc3bcc3af6a896e8c7f603059cd5 | refs/heads/main | 2023-06-26T10:23:01.083788 | 2021-07-30T11:17:12 | 2021-07-30T11:17:12 | 391,028,616 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,386 | java | /* Generated By: AdqlStoX.jjt,v 1.15 2006/10/02 09&JJTree: Do not edit this line. Node.java */
package org.astrogrid.adql;
import org.apache.xmlbeans.XmlObject ;
/* All AST nodes must implement this interface. It provides basic
machinery for constructing the parent and child relationships
between nodes. */
public interface Node {
/** This method is called after the node has been made the current
node. It indicates that child nodes can now be added to it. */
public void jjtOpen();
/** This method is called after all the child nodes have been
added. */
public void jjtClose();
/** This pair of methods are used to inform the node of its
parent. */
public void jjtSetParent(Node n);
public Node jjtGetParent();
/** This method tells the node to add its argument to the node's
list of children. */
public void jjtAddChild(Node n, int i);
/** This method returns a child node. The children are numbered
from zero, left to right. */
public Node jjtGetChild(int i);
/** Return the number of children the node has. */
public int jjtGetNumChildren();
/** Return the generated object. */
public Object getGeneratedObject() ;
/** Builds the generated object out of the passed XmlObject. */
public void buildXmlTree( XmlObject xo ) ;
/** Builds the generated object. */
public void buildXmlTree() ;
}
| [
"Jeff.Lusted@astrogrid.org"
] | Jeff.Lusted@astrogrid.org |
2dac41d81a9e066ad05edb6fcc8a1cd987dd140e | 4da2697f3614499d7e881de870fe6d18ff0c39b9 | /GPSRouting/src/com/bean/People.java | b394d9b38966085f34c1ccacd071f026784471e3 | [] | no_license | cugIE/GPSRouting | 13d6f12a42eac2b25034154b493159798e6b0d2a | 9dafce490826d3d2193c3e266a5bb2b001c8b783 | refs/heads/master | 2021-04-22T12:40:57.472516 | 2017-03-09T00:44:19 | 2017-03-09T00:44:19 | 54,687,722 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,138 | java | package com.bean;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.util.DB;
//人员信息
public class People {
private String id;
private String username;
private String name;
private String password;
private String code;
private String peopRemark;
private String branchId;
private String teamId;
private int generId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPeopRemark() {
return peopRemark;
}
public void setPeopRemark(String peopRemark) {
this.peopRemark = peopRemark;
}
public String getBranchId() {
return branchId;
}
public void setBranchId(String branchId) {
this.branchId = branchId;
}
public String getTeamId() {
return teamId;
}
public void setTeamId(String team_id) {
this.teamId = team_id;
}
public int getGenerId() {
return generId;
}
public void setGenerId(int generId) {
this.generId = generId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public boolean checkIs(String username)
throws Exception {
boolean b = true;
Connection conn = DB.getConn();
String sql = "select * from people where people_username = '"+ username +"'";
Statement stmt = DB.getStatement(conn);
//根据sql语句获取查询结果
ResultSet rs = DB.getResultSet(stmt, sql);
try {
if (rs.next()) {
throw new Exception("用户已存在");
} else {
b = false;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
DB.close(rs);
DB.close(stmt);
DB.close(conn);
}
return b;
}
}
| [
"553446164@qq.com"
] | 553446164@qq.com |
a39926485cd0ee1b33336f036428ab78d881e2d5 | 8a64c5b82ace9f3d1f0c3c01fa464496a374e6de | /CanyonBunny-android/src/com/gamerald/canyonbunny/MainActivity.java | 6426fe97a8cf6bfc5fc1ad0cff8d921d9565c2d8 | [
"Apache-2.0"
] | permissive | andgeno/canyon-bunny | 55669de5129abcc1cb45f824118b5fdb64f870e4 | becf102a2d0f07a2edb5c290c286bb48eac7fca9 | refs/heads/master | 2021-01-19T11:21:31.573009 | 2016-06-15T12:43:21 | 2016-06-15T12:43:21 | 61,207,296 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,362 | java | /*******************************************************************************
* Copyright 2013 Andreas Oehlke
*
* 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.gamerald.canyonbunny;
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.packtpub.libgdx.canyonbunny.CanyonBunnyMain;
public class MainActivity extends AndroidApplication {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
cfg.useGL20 = true;
initialize(new CanyonBunnyMain(), cfg);
}
} | [
"andreas.oehlke@gamerald.com"
] | andreas.oehlke@gamerald.com |
377e4d6a123890a5070161171693599bb5855101 | d23a5cc28a593bac5ca786b80fb9159892241f59 | /masterdataservice/src/main/java/com/beans/leaveapp/leavetype/service/LeaveTypeNotFound.java | cab3e914f6f21e49da4bd04e130c561f707beafe | [] | no_license | kinmengBGM/bgmhrm | 45aefcb6eecb3f852d6b5f821467605dbe9c709f | ca63bb4990205c4283227139d0bfd0d5e9808728 | refs/heads/master | 2021-01-23T07:03:49.226721 | 2015-05-26T09:47:25 | 2015-05-26T09:47:25 | 20,989,048 | 1 | 3 | null | null | null | null | UTF-8 | Java | false | false | 107 | java | package com.beans.leaveapp.leavetype.service;
public class LeaveTypeNotFound extends Throwable {
}
| [
"kinmeng.chan@beans.com.my"
] | kinmeng.chan@beans.com.my |
b8b6ed27fd140099e6979fd7680cba2ce9ba7682 | ac7ae7ae1b587c69f10a429adcc6562faf4bc7e4 | /app/src/main/java/edu/buffalo/cse/cse486586/groupmessenger2/GroupMessengerActivity.java | c6e34413cb3402f4f6306994a9c4ef69fbb9c9fe | [] | no_license | AhutGupta/GroupMessenger | 20455c0184364e517ff768c7163adac4f0c18677 | 5e06afd93a49525d78572a1d77470f51b590e6b0 | refs/heads/master | 2021-01-01T05:43:45.693509 | 2016-05-19T23:49:59 | 2016-05-19T23:49:59 | 59,250,848 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 20,481 | java | package edu.buffalo.cse.cse486586.groupmessenger2;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.Buffer;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
/**
* GroupMessengerActivity is the main Activity for the assignment.
*
*/
public class GroupMessengerActivity extends Activity {
static final String TAG = GroupMessengerActivity.class.getSimpleName();
static final int SERVER_PORT = 10000;
static final String[] ports = {"11108", "11112", "11116", "11120", "11124" };
static int count = 0;
static int maxcount = 0;
static int msgcount = 1;
static int file_count = 0;
static boolean tflag = true;
static int myPort;
static boolean failure = false;
static boolean Qflag = true;
static int failed_avd = 5;
static final String New_Msg = "First_Contact";
static final String Proposed_Seq = "Proposed_Sequence_Number";
static final String Agreed_Seq = "Agreed_Sequence_Number";
static final String Fail = "FAILURE";
Hashtable<Integer, Proposed> table = new Hashtable();
private Uri providerUri;
public int PortMapping(int port){
switch (port){
case 11108:
return 0;
case 11112:
return 1;
case 11116:
return 2;
case 11120:
return 3;
case 11124:
return 4;
}
return 5;
}
public int maxseq(int a, int b){
if (a>b)
return a+1;
else
return b+1;
}
public void AnnounceFail(int a){
Message fail_msg = new Message();
fail_msg.type = Fail;
fail_msg.fail_avd = a;
for (int i = 0; i < 5; i++) {
try {
if(i==a){
continue;
}
Socket socket = new Socket(InetAddress.getByAddress(new byte[]{10, 0, 2, 2}), Integer.parseInt(ports[i]));
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
output.writeObject(fail_msg);
output.flush();
output.close();
socket.close();
} catch (UnknownHostException e) {
Log.e(TAG, "Fail Broadcast UnknownHostException");
} catch (IOException e) {
Log.e(TAG, "Fail Broadcast socket IOException");
} catch (Exception e) {
Log.e(TAG, "Fail Broadcast Exception");
}
}
}
public class Proposed{
public int count=0;
public float seq;
public int avdlist[] = {0,0,0,0,0};
}
public PriorityQueue <Message> MsgQueue = new PriorityQueue();
private Uri buildUri(String scheme, String authority) {
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.authority(authority);
uriBuilder.scheme(scheme);
return uriBuilder.build();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_messenger);
TelephonyManager tel = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
String portStr = tel.getLine1Number().substring(tel.getLine1Number().length() - 4);
myPort = (Integer.parseInt(portStr) * 2);
msgcount = msgcount + PortMapping(myPort)*100;
providerUri = buildUri("content", "edu.buffalo.cse.cse486586.groupmessenger2.provider");
/*
* TODO: Use the TextView to display your messages. Though there is no grading component
* on how you display the messages, if you implement it, it'll make your debugging easier.
*/
try {
ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
new ServerTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, serverSocket);
} catch (IOException e) {
Log.e(TAG, "Can't create a ServerSocket");
return;
}
final TextView tv = (TextView) findViewById(R.id.textView1);
tv.setMovementMethod(new ScrollingMovementMethod());
findViewById(R.id.button1).setOnClickListener(
new OnPTestClickListener(tv, getContentResolver()));
findViewById(R.id.button4).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final EditText editText = (EditText) findViewById(R.id.editText1);
String msg = editText.getText().toString() + "\n";
editText.setText("");
final TextView localtv = (TextView) findViewById(R.id.textView1);
localtv.append("\t" + msg + "\n");
Message msgObject = new Message();
msgObject.type = New_Msg;
msgObject.senderId = PortMapping(myPort);
msgObject.uniqueId = msgcount++;
msgObject.text = msg;
Log.e(TAG, "I am the sender, my new message unique id : "+msgObject.uniqueId +", text: "+msgObject.text);
new ClientTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, msgObject);
return;
}
});
}
private class ServerTask extends AsyncTask<ServerSocket, String, Void> {
@Override
protected Void doInBackground(ServerSocket... sockets) {
ServerSocket serverSocket = sockets[0];
TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String portStr = tel.getLine1Number().substring(tel.getLine1Number().length() - 4);
final int myPort = (Integer.parseInt(portStr) * 2);
int port = PortMapping(myPort);
Socket socket;
while (true) {
try {
socket = serverSocket.accept();
BufferedInputStream bin = new BufferedInputStream(socket.getInputStream());
ObjectInputStream input = new ObjectInputStream(bin);
Message msg = (Message)input.readObject();
input.close();
bin.close();
socket.close();
if(msg.type.equals(Fail)){
Log.e(TAG, "In ServerTask. I got a Failure broadcast.....");
failure = true;
failed_avd = msg.fail_avd;
}
if(msg.type.equals(New_Msg)){
Log.e(TAG, "In Server. new_msg");
//Publish progres- Add to priority Q with proposed seq no.
publishProgress(msg.type, msg.text, msg.senderId+"", msg.uniqueId+"");
}
else if(msg.type.equals(Proposed_Seq)){
Log.e(TAG, "In server. Proposed_seq");
//Publish progress. and add proposed seq to hashtable.
publishProgress(msg.type, msg.text, msg.proposedby+"", msg.uniqueId+"", msg.seqno+"", msg.senderId+"");
}
else if(msg.type.equals(Agreed_Seq)){
Log.e(TAG, "In server. Agreed Seq...");
publishProgress(msg.type, msg.uniqueId+"", msg.seqno+"", msg.maxagreed+"");
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
protected void onProgressUpdate(String... strings) {
/*
* The following code displays what is received in doInBackground().
*/
if(failure) {
Set msg_set = table.entrySet();
Iterator Tableiterator = msg_set.iterator();
while (Tableiterator.hasNext()) {
Map.Entry msg_proposals = (Map.Entry) Tableiterator.next();
Proposed Pmsg = (Proposed) msg_proposals.getValue();
if (Pmsg.count == 4 && Pmsg.avdlist[failed_avd] == 0) {
Message temp_msg = new Message();
temp_msg.uniqueId = (Integer) msg_proposals.getKey();
temp_msg.seqno = ((Proposed) msg_proposals.getValue()).seq;
temp_msg.type = Agreed_Seq;
temp_msg.maxagreed = maxseq(temp_msg.seqno.intValue(), maxcount) - 1;
Tableiterator.remove();
Log.e(TAG, "In ServerTask. I am sending agreed seq no: " + temp_msg.seqno + " for unique id: " + temp_msg.uniqueId);
new ClientTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, temp_msg);
}
}
}
//Remove msgs in the Q, sent by failed AVD
if(failure) {
Iterator MsgQiterator = MsgQueue.iterator();
while (MsgQiterator.hasNext()) {
Message message = (Message) MsgQiterator.next();
if (message.senderId == failed_avd) {
MsgQueue.remove((message));
Log.e(TAG, "Removed message from Msg Queue. For crashed AVD- " + message.senderId);
}
}
}
String status = strings[0];
if(status.equals(New_Msg)){
//Create a new msg object, with proposed seq no. Send it to client and add to Q
int proposed_seq = maxseq(count, maxcount);
Message proposed = new Message();
proposed.type = Proposed_Seq;
proposed.text = strings[1];
proposed.senderId = Integer.parseInt(strings[2]);
proposed.uniqueId = Integer.parseInt((strings[3]));
proposed.seqno = proposed_seq + PortMapping(myPort)*0.1f;
if(proposed.senderId!=failed_avd){
MsgQueue.add(proposed);
count++;
Log.e(TAG, "Added Message to the Queue and proposed seq..."+proposed);
}
new ClientTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, proposed);
}
else if(status.equals(Proposed_Seq)){
Log.e(TAG, "In onProgressUpdate. Proposed_Seq...");
//Add to hashtale and check if we have 5(or 4) entries. Decide on agreed seq no. if we do
int key = Integer.parseInt(strings[3]);
Float seq = Float.parseFloat(strings[4]);
int sender = Integer.parseInt(strings[2]);
int original_sender = Integer.parseInt(strings[5]);
int count=0;
if(!table.containsKey(key)){
Proposed proposed_msg = new Proposed();
proposed_msg.count=1;
count = proposed_msg.count;
proposed_msg.seq = seq;
proposed_msg.avdlist[sender] = 1;
table.put(key, proposed_msg);
Log.e(TAG, "First Hashtable entry for UID: " + key + " Count: "+proposed_msg.count+"For sender: "+sender + " Failure: " + failure);
}
else{
Proposed proposed_seq = table.get(key);
if (proposed_seq.avdlist[sender]==0){
proposed_seq.avdlist[sender]=1;
proposed_seq.count+=1;
if(seq>proposed_seq.seq){
proposed_seq.seq = seq;
}
else{
seq = proposed_seq.seq;
}
table.put(key, proposed_seq);
Log.e(TAG, "Later Hashtable entry for UID: " + key + " Count: "+ proposed_seq.count + " Max Seq: " + seq+ "Faliure: "+failure);
}
count = proposed_seq.count;
}
Log.e(TAG, "Count after insert: "+ count+" For sender: "+sender+ "Faliure: "+failure);
//Check if count is 5 or 4
boolean is_it = false;
Proposed proposed_seq = table.get(key);
if((failure && count==4 && proposed_seq.avdlist[failed_avd] == 0) || count == 5){
is_it = true;
}
if(is_it){
Message finalmsg = new Message();
finalmsg.type = Agreed_Seq;
finalmsg.seqno = seq;
finalmsg.uniqueId = key;
finalmsg.maxagreed = maxseq(seq.intValue(), maxcount)-1;
table.remove(key);
Log.e(TAG, "In onProgressUpdate. I am sending agreed seq no: "+finalmsg.seqno+" for unique id: "+finalmsg.uniqueId);
new ClientTask().executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, finalmsg);
}
}
else if(status.equals(Agreed_Seq)){
int uid = Integer.parseInt(strings[1]);
float seq_final = Float.parseFloat(strings[2]);
int maxrecvd = Integer.parseInt(strings[3]);
if(maxcount<maxrecvd){
maxcount = maxrecvd;
}
Log.e(TAG, "In onProgressUpdate. Agreed_seq...unique id is :"+uid+" agreed seq is :"+seq_final+" & maxAgreed for grp is :"+maxcount);
Iterator Qiterator = MsgQueue.iterator();
while(Qiterator.hasNext()){
Message message = (Message) Qiterator.next();
if(message.uniqueId == uid){
Log.e(TAG, "Added msg back to Q with correct priority...");
MsgQueue.remove(message);
message.seqno = seq_final;
message.deliverable = true;
MsgQueue.add(message);
Log.e(TAG, "---------Updated msg in Q. "+message);
break;
}
}
Log.e(TAG, "++++++++++Length of Q at this point = "+MsgQueue.size());
while(!MsgQueue.isEmpty()) {
Log.e(TAG, "&&&&&&&&&&&&&&&Now inside the while loop for Q. status= "+MsgQueue.peek().deliverable);
Log.e(TAG, "The message at head: "+MsgQueue.peek());
if (MsgQueue.peek().deliverable) {
Log.e(TAG, "*********Now I should write to the content provider************");
String final_msg = MsgQueue.poll().text;
TextView localtv = (TextView) findViewById(R.id.textView1);
localtv.append("\t" + final_msg + "\n");
ContentValues keyValueToInsert = new ContentValues();
String sequence = Integer.toString(file_count++);
keyValueToInsert.put("key", sequence);
keyValueToInsert.put("value", final_msg);
Uri newUri = getContentResolver().insert(
providerUri,
keyValueToInsert
);
} else {
break;
}
}
}
//Add to Content provider finally
return;
}
}
private class ClientTask extends AsyncTask<Message, Void, Void> {
@Override
protected Void doInBackground(Message... msgs) {
Message msg = msgs[0];
if(msg.type.equals(New_Msg)) {
Log.e(TAG, "In client task.... New_msg");
for (int i = 0; i < 5; i++) {
try {
if(i==failed_avd){
continue;
}
Socket socket = new Socket(InetAddress.getByAddress(new byte[]{10, 0, 2, 2}), Integer.parseInt(ports[i]));
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
output.writeObject(msg);
output.flush();
output.close();
socket.close();
} catch (UnknownHostException e) {
Log.e(TAG, "ClientTask UnknownHostException");
} catch (IOException e) {
Log.e(TAG, "ClientTask socket IOException");
if(!failure){
AnnounceFail(i);
}
} catch (Exception e) {
Log.e(TAG, "Parent Exception");
}
}
}
else if(msg.type.equals(Proposed_Seq) && (msg.senderId != failed_avd) ){
Log.e(TAG, "In Client task.. Proposed_seq");
msg.proposedby = PortMapping(myPort);
try{
Socket socket = new Socket(InetAddress.getByAddress(new byte[]{10, 0, 2, 2}),
Integer.parseInt(ports[msg.senderId]));
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
output.writeObject(msg);
output.flush();
output.close();
socket.close();
} catch (UnknownHostException e) {
Log.e(TAG, "ClientTask UnknownHostException");
} catch (IOException e) {
Log.e(TAG, "ClientTask socket IOException");
if(!failure){
AnnounceFail(msg.senderId);
}
} catch (Exception e) {
Log.e(TAG, "Parent Exception");
}
}
else if(msg.type.equals(Agreed_Seq)){
Log.e(TAG, "In client task. Agreed_seq.........");
for (int i = 0; i < 5; i++) {
try{
if(i==failed_avd){
continue;
}
Socket socket = new Socket(InetAddress.getByAddress(new byte[]{10, 0, 2, 2}),
Integer.parseInt(ports[i]));
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
output.writeObject(msg);
output.flush();
output.close();
socket.close();
} catch (UnknownHostException e) {
Log.e(TAG, "ClientTask UnknownHostException");
} catch (IOException e) {
Log.e(TAG, "ClientTask socket IOException");
if(!failure){
AnnounceFail(i);
}
} catch (Exception e) {
Log.e(TAG, "Parent Exception");
}
}
}
return null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_group_messenger, menu);
return true;
}
} | [
"ahutgupt@buffalo.edu"
] | ahutgupt@buffalo.edu |
d32c6b0a11557f8c7d3358feba5cc83b40d2ac1a | e7bb9bef20a33f23cb759c1b3d092e63cac497ee | /app/src/main/java/com/mohit/stockstracker/AddTicker.java | a178e634dfa097e8b599cbf5c0e3ad4d68adb3f3 | [] | no_license | AngadDtu/Stocker | 68543991f5c04a03be4e8097f5f4acfd1d1749a3 | 1a01ed4d25fb4771a005327d746ee6c6c6af653e | refs/heads/master | 2021-01-21T04:19:44.457669 | 2016-08-23T08:37:00 | 2016-08-23T08:37:00 | 50,863,477 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,119 | java | package com.mohit.stockstracker;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.AutoCompleteTextView;
import java.util.ArrayList;
/**
* Created by Mohit on 26-04-2015.
*/
public class AddTicker extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.addticker);
Intent i = getIntent();
Bundle b = i.getExtras();
ArrayList<TickerStockExchange> list = b.getParcelableArrayList("listoftickers");
AutoCompleteTextView textView = (AutoCompleteTextView)findViewById(R.id.addNewEditText);
textView.setThreshold(1);
DialogArrayAdapter d = new DialogArrayAdapter(getApplicationContext(),
android.R.layout.simple_dropdown_item_1line,list);
textView.setAdapter(d);
d.notifyDataSetChanged();
}
}
| [
"angad.dtu2012@gmail.com"
] | angad.dtu2012@gmail.com |
d79c1e6df1a425080543c8cc8a7eae86d6468645 | 2f3412474d4b749596ff2d30669016861ea54307 | /app/src/main/java/in/goodiebag/example/n/bean/Bean.java | cfcb853531810d746c88d8b40ac706d3cf7400c7 | [
"MIT"
] | permissive | slimCai/GitTest | e4182339229db1298d5bf27dfba7d9f7e76a244f | 6927c05d7ebe7a449dfe1b0a7b317bdf6cf8ad8b | refs/heads/master | 2021-09-08T22:23:53.936169 | 2018-03-12T12:19:19 | 2018-03-12T12:19:19 | 124,881,390 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 416 | java | package in.goodiebag.example.n.bean;
import android.graphics.Bitmap;
/**
* Created by wuhang on 17/3/15.
*/
public class Bean {
private String mFirtLine;
public Bean() {
}
public Bean(String firtLine) {
mFirtLine = firtLine;
}
public String getFirtLine() {
return mFirtLine;
}
public void setFirtLine(String firtLine) {
mFirtLine = firtLine;
}
}
| [
"532363674@qq.com"
] | 532363674@qq.com |
bcd246a19c4866854e8309037f39d81f3ca9d462 | 7ee6175ff7795a2ed80e33906bf638419098cf2b | /PrimeAndReverse.java | dc8f18232fc474ef1193665ee2fcd96139b1beba | [] | no_license | Clowen3094/Assignment6.1 | 052b12b52e268dca13a75e05672b9cb2c5abf30b | ff5b8b39a02cdb939fc7f274f726b0bef19e2dd0 | refs/heads/master | 2021-01-21T22:01:24.981474 | 2017-06-22T18:38:28 | 2017-06-22T18:38:28 | 95,145,529 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,036 | java | //a program Declare and initialize an integer array of size 10. Fill it with only prime numbers. (step-1) Create another integer array of size 10 and copy the values of first array into second array in the reverse order and print them. (step-2)
public class PrimeAndReverse {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Declaring both array of size 10 and initialized primeArray with prime numbers
int primeArray[] = {2,3,5,7,11,13,17,19,23,29};
int reverseArray[] = new int[10];
System.out.println("Elements in array is :");
//Displaying the prime elements in arrayPrime
for(int i=0;i<10;i++)
System.out.print("\t"+primeArray[i]);
//reversing prime numbers in reverseArray
for(int i=0,j=9 ; i<10 && j>=0 ;i++,j--){
reverseArray[i]=primeArray[j];
}
//Displaying reversed array prime elements
System.out.println("\nElements after getting reversed :");
for(int i=0;i<10;i++)
{
System.out.print("\t"+reverseArray[i]);
}
}
} | [
"noreply@github.com"
] | noreply@github.com |
e52ea87a0c70b7929da01d1dc134444f9ce1d056 | 61325fcac199024e36b42954d881655e54309ea1 | /src/draft/qcs/stock_garbage_ok.java | 02e5c13fe4e105d52fbd1654845cd9909a8ef3c8 | [] | no_license | RainerJava/erp-6 | 89376f75988d4662d8116da0b474565a3d992e1d | 5697a68876dc5dd2a1e54fb0a7b940e5beb34d6d | refs/heads/master | 2021-01-16T22:46:07.322118 | 2013-05-10T17:23:54 | 2013-05-10T17:23:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,073 | java | package draft.qcs;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import include.nseer_db.*;
import include.nseer_cookie.*;
import java.io.*;
import java.util.*;
import com.jspsmart.upload.*;
import include.nseer_cookie.counter;
public class stock_garbage_ok extends HttpServlet{
public synchronized void service(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{
HttpSession dbSession=request.getSession();
JspFactory _jspxFactory=JspFactory.getDefaultFactory();
PageContext pageContext = _jspxFactory.getPageContext(this,request,response,"",true,8192,true);
ServletContext dbApplication=dbSession.getServletContext();
try{
//实例化
HttpSession session=request.getSession();
ServletContext context=session.getServletContext();
String path=context.getRealPath("/");
counter count=new counter(dbApplication);
SmartUpload mySmartUpload=new SmartUpload();
mySmartUpload.setCharset("UTF-8");
nseer_db_backup1 qcs_db = new nseer_db_backup1(dbApplication);
if(qcs_db.conn((String)dbSession.getAttribute("unit_db_name"))){
mySmartUpload.initialize(pageContext);
String file_type=getFileLength.getFileType((String)session.getAttribute("unit_db_name"));
long d=getFileLength.getFileLength((String)session.getAttribute("unit_db_name"));
mySmartUpload.setMaxFileSize(d);
mySmartUpload.setAllowedFilesList(file_type);
try{
mySmartUpload.upload();
String qcs_id = mySmartUpload.getRequest().getParameter("qcs_id");
String config_id = mySmartUpload.getRequest().getParameter("config_id");
String[] item = mySmartUpload.getRequest().getParameterValues("item");
if(item!=null){
String[] file_name=new String[mySmartUpload.getFiles().getCount()];
String[] not_change=new String[mySmartUpload.getFiles().getCount()];
java.util.Date now = new java.util.Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
String time=formatter.format(now);
String standard_id = mySmartUpload.getRequest().getParameter("standard_id");
String sqla="select attachment1 from qcs_stock where qcs_id='"+qcs_id+"' and (check_tag='5' or check_tag='9')";
ResultSet rs=qcs_db.executeQuery(sqla);
if(!rs.next()){
response.sendRedirect("draft/qcs/stock_ok.jsp?finished_tag=3");
}else{
String[] attachment=mySmartUpload.getRequest().getParameterValues("attachment");
String[] delete_file_name=new String[0];
if(attachment!=null){
delete_file_name=new String[attachment.length];
for(int i=0;i<attachment.length;i++){
delete_file_name[i]=rs.getString(attachment[i]);
}
}
for(int i=0;i<mySmartUpload.getFiles().getCount();i++){
com.jspsmart.upload.SmartFile file = mySmartUpload.getFiles().getFile(i);
if (file.isMissing()){
file_name[i]="";
int q=i+1;
String field_name="attachment"+q;
if(!rs.getString(field_name).equals("")) not_change[i]="yes";
continue;
}
int filenum=count.read((String)dbSession.getAttribute("unit_db_name"),"qcsAttachmentcount");
count.write((String)dbSession.getAttribute("unit_db_name"),"qcsAttachmentcount",filenum);
file_name[i]=filenum+file.getFileName();
file.saveAs(path+"qcs/file_attachments/" + filenum+file.getFileName());
}
String apply_id = mySmartUpload.getRequest().getParameter("apply_id");
String product_id = mySmartUpload.getRequest().getParameter("product_id");
String product_name = mySmartUpload.getRequest().getParameter("product_name");
String qcs_amount = mySmartUpload.getRequest().getParameter("qcs_amount");
String qcs_time = mySmartUpload.getRequest().getParameter("qcs_time");
String quality_way = mySmartUpload.getRequest().getParameter("quality_way");
String quality_solution = mySmartUpload.getRequest().getParameter("quality_solution");
String sampling_standard = mySmartUpload.getRequest().getParameter("sampling_standard");
String sampling_amount = mySmartUpload.getRequest().getParameter("sampling_amount");
String accept = mySmartUpload.getRequest().getParameter("accept");
String reject = mySmartUpload.getRequest().getParameter("reject");
String qualified = mySmartUpload.getRequest().getParameter("qualified");
String unqualified = mySmartUpload.getRequest().getParameter("unqualified");
String qcs_result = mySmartUpload.getRequest().getParameter("qcs_result");
String register = mySmartUpload.getRequest().getParameter("register");
String checker_id = mySmartUpload.getRequest().getParameter("checker_id");
String register_time = mySmartUpload.getRequest().getParameter("register_time");
String bodyab = new String(mySmartUpload.getRequest().getParameter("remark").getBytes("UTF-8"),"UTF-8");
String remark=exchange.toHtml(bodyab);
sqla = "update qcs_stock set apply_id='"+apply_id+"',product_id='"+product_id+"',product_name='"+product_name+"',qcs_amount='"+qcs_amount+"',qcs_time='"+qcs_time+"',quality_way='"+quality_way+"',quality_solution='"+quality_solution+"',sampling_standard='"+sampling_standard+"',sampling_amount='"+sampling_amount+"',accept='"+accept+"',reject='"+reject+"',qualified='"+qualified+"',unqualified='"+unqualified+"',checker_id='"+checker_id+"',qcs_result='"+qcs_result+"',register='"+register+"',register_time='"+register_time+"',remark='"+remark+"',check_tag='2'";
String sqlb = " where qcs_id='"+qcs_id+"'" ;
if(attachment!=null){
for(int i=0;i<attachment.length;i++){
sqla=sqla+","+attachment[i]+"=''";
java.io.File file=new java.io.File(path+"qcs/file_attachments/"+delete_file_name[i]);
file.delete();
}
}
for(int i=0;i<mySmartUpload.getFiles().getCount();i++){
if(not_change[i]!=null&¬_change[i].equals("yes")) continue;
int p=i+1;
sqla=sqla+",attachment"+p+"='"+file_name[i]+"'";
}
String sql=sqla+sqlb;
qcs_db.executeUpdate(sql) ;
sql="delete from qcs_stock_details where qcs_id='"+qcs_id+"'";
qcs_db.executeUpdate(sql);
String[] default_basis = mySmartUpload.getRequest().getParameterValues("default_basis");
String[] ready_basis = mySmartUpload.getRequest().getParameterValues("ready_basis");
String[] quality_method = mySmartUpload.getRequest().getParameterValues("quality_method");
String[] analyse_method = mySmartUpload.getRequest().getParameterValues("analyse_method");
String[] standard_value = mySmartUpload.getRequest().getParameterValues("standard_value");
String[] standard_max = mySmartUpload.getRequest().getParameterValues("standard_max");
String[] standard_min = mySmartUpload.getRequest().getParameterValues("standard_min");
String[] quality_value = mySmartUpload.getRequest().getParameterValues("quality_value");
String[] sampling_amount_d = mySmartUpload.getRequest().getParameterValues("sampling_amount_d");
String[] qualified_d = mySmartUpload.getRequest().getParameterValues("qualified_d");
String[] unqualified_d = mySmartUpload.getRequest().getParameterValues("unqualified_d");
String[] quality_result = mySmartUpload.getRequest().getParameterValues("quality_result");
String[] unqualified_reason = mySmartUpload.getRequest().getParameterValues("unqualified_reason");
for(int i=0;i<item.length;i++){
if(!item[i].equals("")){
sql="insert into qcs_stock_details(qcs_id,item,default_basis,ready_basis,quality_method,analyse_method,standard_value,standard_max,standard_min,quality_value,sampling_amount_d,qualified_d,unqualified_d,quality_result,unqualified_reason,details_number) values('"+qcs_id+"','"+item[i]+"','"+default_basis[i]+"','"+ready_basis[i]+"','"+quality_method[i]+"','"+analyse_method[i]+"','"+standard_value[i]+"','"+standard_max[i]+"','"+standard_min[i]+"','"+quality_value[i]+"','"+sampling_amount_d[i]+"','"+qualified_d[i]+"','"+unqualified_d[i]+"','"+quality_result[i]+"','"+unqualified_reason[i]+"','"+i+"')";
qcs_db.executeUpdate(sql);
}
}
response.sendRedirect("draft/qcs/stock_ok.jsp?finished_tag=2");
}
qcs_db.commit();
qcs_db.close();
}else{
response.sendRedirect("draft/qcs/stock_ok.jsp?finished_tag=7");
}
}catch(Exception ex){
response.sendRedirect("draft/qcs/stock_ok.jsp?finished_tag=6");
}
}else{
response.sendRedirect("error_conn.htm");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
| [
"joooohnli@gmail.com"
] | joooohnli@gmail.com |
48ac5c29d0a25e1503e206af52ca0f0d9aa59696 | 84862218b4b680d5f258dbcf59792bd6d18d10a0 | /app/src/main/java/greyson/demo/datepicker/languages/EN.java | 4d2e4bf40ee3ebfddc660e6e6df7a4206162a6e1 | [] | no_license | yufeilong92/DatePicker | 1f6e85ee8be753592a95b93e4562c8d3888cca0e | 825b91144a2c35c0b5891cdfb938dc594b08b9ed | refs/heads/master | 2022-12-25T07:30:51.532967 | 2020-01-12T09:08:50 | 2020-01-12T09:09:07 | 303,257,289 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 996 | java | package greyson.demo.datepicker.languages;
import java.util.Locale;
/**
* 英文的默认实现类
* 如果你想实现更多的语言请参考Language{@link DPLManager}
* <p>
* The implementation class of english.
* You can refer to Language{@link DPLManager} if you want to define more language.
*
* @author AigeStudio 2015-03-28
*/
public class EN extends DPLManager {
public EN(Locale locale) {
this.mLocale = locale;
}
@Override
public String[] titleMonth() {
return new String[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
}
@Override
public String titleEnsure() {
return "Ok";
}
@Override
public String titleBC() {
return "B.C.";
}
@Override
public String[] titleWeek() {
return new String[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
}
@Override
public String getDateFormatStr() {
return "MMM d, yyyy";
}
}
| [
"guoguishen@nightstation.cn"
] | guoguishen@nightstation.cn |
190aee09b3788a58a66ed85ed651e105b9a702d8 | 9dc489766abcc57c15837106ea1deb421e8f4974 | /AfternoonRacesRemote/Monitors/ControlCenter/package-info.java | e6a794844f5f71fbf06e7ef9a98734a1226de60a | [] | no_license | franciscommcunha/Distributed-Systems-2018 | 69b436153573ba1ef5a42e00c380350467740891 | 0e69cc88257e6298f38e8e95ab62517a60afe6fc | refs/heads/master | 2020-04-03T02:44:28.621266 | 2018-10-27T13:27:54 | 2018-10-27T13:27:54 | 154,965,527 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 225 | java | /**
* Package that contains the ControlCenter class and associated classes to make ControlCenter class as server
* - ControlCenter.java
* - ControlCenterServer.java
*/
package AfternoonRacesRemote.Monitors.ControlCenter;
| [
"franciscomiguelcunha@ua.pt"
] | franciscomiguelcunha@ua.pt |
915e3b6c10e18b3f62d16ed0d917169a31cd1aa7 | 50300b90025d5b5aabee9a603a64d87b1277f741 | /src/test/java/io/renren/service/DataSourceTestService.java | 7a43f181bb50a75e3455d035888c90314c22e842 | [
"Apache-2.0"
] | permissive | ygg404/htsys | 2e62c5f40827b575b1802ccdcdc027ab4fe7e3b2 | 228085f1bd0e686475f8f0fa5acee2f2ee330253 | refs/heads/master | 2022-07-27T11:11:36.759931 | 2021-02-25T08:49:26 | 2021-02-25T08:49:26 | 277,976,137 | 3 | 1 | Apache-2.0 | 2022-07-06T20:53:02 | 2020-07-08T03:04:41 | JavaScript | UTF-8 | Java | false | false | 1,382 | java | /**
*
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.renren.service;
import io.renren.datasources.DataSourceNames;
import io.renren.datasources.annotation.DataSource;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 测试多数据源
*
* @author Mark sunlightcs@gmail.com
* @since 3.1.0 2018-01-28
*/
@Service
public class DataSourceTestService {
@Autowired
private SysUserService sysUserService;
public SysUserEntity queryUser(Long userId){
return sysUserService.selectById(userId);
}
@DataSource(name = DataSourceNames.SECOND)
public SysUserEntity queryUser2(Long userId){
return sysUserService.selectById(userId);
}
}
| [
"2279834998@qq.com"
] | 2279834998@qq.com |
0da51801884ebd921d997098c043395ec79ad5d4 | 6f0d43d812a408a6a36481c4390718a574a4e194 | /app/src/main/java/com/xx/demoproject/demofactory/mvp/bean/UserBean.java | 8efa55f37efedad877d31d828edd3bde0fa867e3 | [] | no_license | xinlingforever/demofactory | e19fd7300884c2a7b6e0fef1434a3af949bd140a | 3d91fcf65fb9384c0ac83323fb54b9cf81dc9832 | refs/heads/master | 2020-05-21T22:50:07.655250 | 2017-02-14T06:42:44 | 2017-02-14T06:42:44 | 65,566,744 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 512 | java | package com.xx.demoproject.demofactory.mvp.bean;
/**
* Created by xuxin on 2017/1/28.
*/
public class UserBean {
private String mUserFirstName;
private String mUserLastName;
public UserBean(String userFirstName, String userLastName) {
this.mUserFirstName = userFirstName;
this.mUserLastName = userLastName;
}
public String getUserFirstName() {
return this.mUserFirstName;
}
public String getUserLastName() {
return this.mUserLastName;
}
}
| [
"xuxin@xuxins-MacBook-Pro.local"
] | xuxin@xuxins-MacBook-Pro.local |
9e4583a03e283d27ddd081db5c831994348a9709 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/34/34_296020b226d1c8400b67b4d64d8202e0c1f29f40/Session/34_296020b226d1c8400b67b4d64d8202e0c1f29f40_Session_t.java | d7df09afebfd08a2e3d4804c5139092584a7f817 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 33,926 | java | /*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.internal.ccvs.core.client;
import java.io.*;
import java.util.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.eclipse.core.runtime.*;
import org.eclipse.team.internal.ccvs.core.*;
import org.eclipse.team.internal.ccvs.core.client.Command.GlobalOption;
import org.eclipse.team.internal.ccvs.core.client.Command.QuietOption;
import org.eclipse.team.internal.ccvs.core.connection.CVSRepositoryLocation;
import org.eclipse.team.internal.ccvs.core.connection.Connection;
import org.eclipse.team.internal.ccvs.core.syncinfo.NotifyInfo;
import org.eclipse.team.internal.ccvs.core.syncinfo.ResourceSyncInfo;
import org.eclipse.team.internal.ccvs.core.util.*;
import org.eclipse.team.internal.core.streams.*;
/**
* Maintains CVS communication state for the lifetime of a connection
* to a remote repository. This class covers the initialization, use,
* and eventual shutdown of a dialogue between a CVS client and a
* remote server. This dialogue may be monitored through the use of
* a console.
*
* Initially the Session is in a CLOSED state during which communication
* with the server cannot take place. Once OPENED, any number of commands
* may be issued serially to the server, one at a time. When finished, the
* Session MUST be CLOSED once again to prevent eventual local and/or
* remote resource exhaustion. The session can either be discarded, or
* re-opened for use with the same server though no state is persisted from
* previous connections except for console attributes.
*
* CVSExceptions are thrown only as a result of unrecoverable errors. Once
* this happens, commands must no longer be issued to the server. If the
* Session is in the OPEN state, it is still the responsibility of the
* caller to CLOSE it before moving on.
*/
public class Session {
public static final String CURRENT_LOCAL_FOLDER = "."; //$NON-NLS-1$
public static final String CURRENT_REMOTE_FOLDER = ""; //$NON-NLS-1$
public static final String SERVER_SEPARATOR = "/"; //$NON-NLS-1$
// default file transfer buffer size (in bytes)
private static final int TRANSFER_BUFFER_SIZE = 8192;
// update progress bar in increments of this size (in bytes)
// no incremental progress shown for files smaller than this size
private static final int TRANSFER_PROGRESS_INCREMENT = 32768;
private static final boolean IS_CRLF_PLATFORM = Arrays.equals(
System.getProperty("line.separator").getBytes(), new byte[] { '\r', '\n' }); //$NON-NLS-1$
private CVSRepositoryLocation location;
private ICVSFolder localRoot;
private boolean outputToConsole;
private Connection connection = null;
private String validRequests = null;
private Date modTime = null;
private boolean noLocalChanges = false;
private boolean createBackups = true;
private int compressionLevel = 0;
private List expansions;
private Collection /* of ICVSFile */ textTransferOverrideSet = null;
// state need to indicate whether
private boolean ignoringLocalChanges = false;
// The resource bundle key that provides the file sending message
private String sendFileTitleKey;
private Map responseHandlers;
/**
* Creates a new CVS session, initially in the CLOSED state.
* By default, command output is directed to the console.
*
* @param location the CVS repository location used for this session
* @param localRoot represents the current working directory of the client
*/
public Session(ICVSRepositoryLocation location, ICVSFolder localRoot) {
this(location, localRoot, true);
}
/**
* Creates a new CVS session, initially in the CLOSED state.
*
* @param location the CVS repository location used for this session
* @param localRoot represents the current working directory of the client
* @param outputToConsole if true, command output is directed to the console
*/
public Session(ICVSRepositoryLocation location, ICVSFolder localRoot, boolean outputToConsole) {
this.location = (CVSRepositoryLocation) location;
this.localRoot = localRoot;
this.outputToConsole = outputToConsole;
}
/*
* Add a module expansion receivered from the server.
* This is only used by the ModuleExpansionsHandler
*/
protected void addModuleExpansion(String expansion) {
expansions.add(expansion);
}
/*
* Add a module expansion receivered from the server.
* This is only used by the ExpandModules command
*/
protected void resetModuleExpansion() {
if (expansions == null)
expansions = new ArrayList();
else
expansions.clear();
}
/**
* Opens, authenticates and initializes a connection to the server specified
* for the remote location.
*
* @param monitor the progress monitor
* @throws IllegalStateException if the Session is not in the CLOSED state
*/
public void open(IProgressMonitor monitor) throws CVSException {
open(monitor, true /* write access*/);
}
public void open(IProgressMonitor monitor, boolean writeAccess) throws CVSException {
if (connection != null) throw new IllegalStateException();
monitor = Policy.monitorFor(monitor);
monitor.beginTask(null, 100);
boolean opened = false;
try {
connection = getLocationForConnection(writeAccess).openConnection(Policy.subMonitorFor(monitor, 50));
// If we're connected to a CVSNT server or we don't know the platform,
// accept MT. Otherwise don't.
boolean useMT = ! (location.getServerPlatform() == CVSRepositoryLocation.CVS_SERVER);
if ( ! useMT) {
removeResponseHandler("MT"); //$NON-NLS-1$
}
// tell the server the names of the responses we can handle
connection.writeLine("Valid-responses " + makeResponseList()); //$NON-NLS-1$
// Flush in order to recieve the valid requests
connection.flush();
// ask for the set of valid requests
IStatus status = Request.VALID_REQUESTS.execute(this, Policy.subMonitorFor(monitor, 40));
if (!status.isOK()) {
throw new CVSException(status);
}
// set the root directory on the server for this connection
connection.writeLine("Root " + getRepositoryRoot()); //$NON-NLS-1$
// enable compression
compressionLevel = CVSProviderPlugin.getPlugin().getCompressionLevel();
if (compressionLevel != 0 && isValidRequest("gzip-file-contents")) { //$NON-NLS-1$
// Enable the use of CVS 1.8 per-file compression mechanism.
// The newer Gzip-stream request seems to be problematic due to Java's
// GZIPInputStream tendency to block on read() rather than to return a
// partially filled buffer. The latter option would be better since it
// can make more effective use of the code dictionary, if it can be made
// to work...
connection.writeLine("gzip-file-contents " + Integer.toString(compressionLevel)); //$NON-NLS-1$
} else {
compressionLevel = 0;
}
// get the server platform if it is unknown
if (CVSProviderPlugin.getPlugin().isDetermineVersionEnabled() && location.getServerPlatform() == CVSRepositoryLocation.UNDETERMINED_PLATFORM) {
Command.VERSION.execute(this, location, Policy.subMonitorFor(monitor, 10));
}
opened = true;
} finally {
if (connection != null && ! opened) {
close();
}
monitor.done();
}
}
/*
* Return the location to be used for this connection
*/
private CVSRepositoryLocation getLocationForConnection(boolean writeAccess) {
return location;
}
/**
* Closes a connection to the server.
*
* @throws IllegalStateException if the Session is not in the OPEN state
*/
public void close() {
if (connection != null) {
connection.close();
connection = null;
validRequests = null;
}
}
/**
* Determines if the server supports the specified request.
*
* @param request the request string to verify
* @return true iff the request is supported
*/
public boolean isValidRequest(String request) {
return (validRequests == null) ||
(validRequests.indexOf(" " + request + " ") != -1); //$NON-NLS-1$ //$NON-NLS-2$
}
public boolean isCVSNT() {
if (location.getServerPlatform() == CVSRepositoryLocation.UNDETERMINED_PLATFORM) {
return location.getRootDirectory().indexOf(':') == 1;
} else {
return location.getServerPlatform() == CVSRepositoryLocation.CVSNT_SERVER;
}
}
/**
* Returns the local root folder for this session.
* <p>
* Generally speaking, specifies the "current working directory" at
* the time of invocation of an equivalent CVS command-line client.
* </p>
*
* @return the local root folder
*/
public ICVSFolder getLocalRoot() {
return localRoot;
}
/**
* Return the list of module expansions communicated from the server.
*
* The modules expansions are typically a directory path of length 1
* but can be of greater length on occasion.
*/
public String[] getModuleExpansions() {
if (expansions == null) return new String[0];
return (String[]) expansions.toArray(new String[expansions.size()]);
}
/**
* Returns the repository root folder for this session.
* <p>
* Specifies the unqualified path to the CVS repository root folder
* on the server.
* </p>
*
* @return the repository root folder
*/
public String getRepositoryRoot() {
return location.getRootDirectory();
}
/**
* Returns an object representing the CVS repository location for this session.
*
* @return the CVS repository location
*/
public ICVSRepositoryLocation getCVSRepositoryLocation() {
return location;
}
/**
* Receives a line of text minus the newline from the server.
*
* @return the line of text
*/
public String readLine() throws CVSException {
return connection.readLine();
}
/**
* Sends a line of text followed by a newline to the server.
*
* @param line the line of text
*/
public void writeLine(String line) throws CVSException {
connection.writeLine(line);
}
/**
* Sends an argument to the server.
* <p>e.g. sendArgument("Hello\nWorld\n Hello World") sends:
* <pre>
* Argument Hello \n
* Argumentx World \n
* Argumentx Hello World \n
* </pre></p>
*
* @param arg the argument to send
*/
public void sendArgument(String arg) throws CVSException {
connection.write("Argument "); //$NON-NLS-1$
int oldPos = 0;
for (;;) {
int pos = arg.indexOf('\n', oldPos);
if (pos == -1) break;
connection.writeLine(stripTrainingCR(arg.substring(oldPos, pos)));
connection.write("Argumentx "); //$NON-NLS-1$
oldPos = pos + 1;
}
connection.writeLine(stripTrainingCR(arg.substring(oldPos)));
}
/*
* Remove any trailing CR from the string
*/
private String stripTrainingCR(String string) {
if (string.endsWith("\r")) { //$NON-NLS-1$
return string.substring(0, string.length() - 1);
}
return string;
}
/**
* Sends a request to the server and flushes any output buffers.
*
* @param requestId the string associated with the request to be executed
*/
public void sendRequest(String requestId) throws CVSException {
connection.writeLine(requestId);
connection.flush();
}
/**
* Sends an Is-modified request to the server without the file contents.
* <p>e.g. if a file called "local_file" was modified, sends:
* <pre>
* Is-modified local_file \n
* </pre></p><p>
* This request is an optimized form of the Modified request and may not
* be supported by all servers. Hence, if it is not supported, a Modified
* request is sent instead along with the file's contents. According to
* the CVS protocol specification, this request is only safe for use with
* some forms of: admin, annotate, diff, editors, log, watch-add, watch-off,
* watch-on, watch-remove, and watchers.<br>
* It may be possible to use this for: add, export, remove and status.<br>
* Do not use with co, ci, history, init, import, release, rdiff, rtag, or update.
* </p><p>
* Note: The most recent Directory request must have specified the file's
* parent folder.
* </p>
*
* @param file the file that was modified
* @see #sendModified
*/
public void sendIsModified(ICVSFile file, boolean isBinary, IProgressMonitor monitor)
throws CVSException {
if (isValidRequest("Is-modified")) { //$NON-NLS-1$
connection.writeLine("Is-modified " + file.getName()); //$NON-NLS-1$
} else {
sendModified(file, isBinary, monitor);
}
}
/**
* Sends a Static-directory request to the server.
* <p>
* Indicates that the directory specified in the most recent Directory request
* is static. No new files will be checked out into this directory unless
* explicitly requested.
* </p>
*/
public void sendStaticDirectory() throws CVSException {
connection.writeLine("Static-directory"); //$NON-NLS-1$
}
/**
* Sends a Directory request to the server with a constructed path.
* <p>
* It may be necessary at times to guess the remote path of a directory since
* it does not exist yet. In this case we construct a remote path based on the
* local path by prepending the local path with the repository root. This may
* not work in the presence of modules, so only use it for creating new projects.
* </p><p>
* Note: A CVS repository root can end with a trailing slash. The CVS server
* expects that the repository root sent contain this extra slash. Including
* the foward slash in addition to the absolute remote path makes for a string
* containing two consecutive slashes (e.g. /home/cvs/repo//projecta/a.txt).
* This is valid in the CVS protocol.
* </p>
*/
public void sendConstructedDirectory(String localDir) throws CVSException {
sendDirectory(localDir, getRepositoryRoot() + "/" + localDir); //$NON-NLS-1$
}
/**
* Sends a Directory request to the server.
* <p>e.g. sendDirectory("local_dir", "remote_dir") sends:
* <pre>
* Directory local_dir
* repository_root/remote_dir
* </pre></p>
*
* @param localDir the path of the local directory relative to localRoot
* @param remoteDir the path of the remote directory relative to repositoryRoot
*/
public void sendDirectory(String localDir, String remoteDir) throws CVSException {
if (localDir.length() == 0) localDir = "."; //$NON-NLS-1$
connection.writeLine("Directory " + localDir); //$NON-NLS-1$
connection.writeLine(remoteDir);
}
/**
* Sends a Directory request for the localRoot.
*/
public void sendLocalRootDirectory() throws CVSException {
sendDirectory(".", localRoot.getRemoteLocation(localRoot)); //$NON-NLS-1$
}
/**
* Sends a Directory request for the localRoot with a constructed path.
* <p>
* Use this when creating a new project that does not exist in the repository.
* </p>
* @see #sendConstructedDirectory
*/
public void sendConstructedRootDirectory() throws CVSException {
sendConstructedDirectory(""); //$NON-NLS-1$
}
/**
* Sends an Entry request to the server.
* <p>
* Indicates that a file is managed (but it may not exist locally). Sends
* the file's entry line to the server to indicate the version that was
* previously checked out.
* </p><p>
* Note: The most recent Directory request must have specified the file's
* parent folder.
* </p>
*
* @param entryLine the formatted entry line of the managed file.
*/
public void sendEntry(byte[] syncBytes, String serverTimestamp) throws CVSException {
connection.write("Entry "); //$NON-NLS-1$
if (serverTimestamp == null) {
serverTimestamp = ""; //$NON-NLS-1$
}
int start = Util.getOffsetOfDelimeter(syncBytes, (byte)'/', 0, 3);
if (start == -1) {
// something is wrong with the entry line so just send it as is
// and let the server report the error.
connection.writeLine(new String(syncBytes));
return;
}
int end = Util.getOffsetOfDelimeter(syncBytes, (byte)'/', start + 1, 1);
if (end == -1) {
// something is wrong with the entry line so just send it as is
// and let the server report the error.
connection.writeLine(new String(syncBytes));
return;
}
connection.write(new String(syncBytes, 0, start + 1));
connection.write(serverTimestamp);
connection.writeLine(new String(syncBytes, end, syncBytes.length - end));
}
/**
* Sends a global options to the server.
* <p>e.g. sendGlobalOption("-n") sends:
* <pre>
* Global_option -n \n
* </pre></p>
*
* @param option the global option to send
*/
public void sendGlobalOption(String option) throws CVSException {
connection.writeLine("Global_option " + option); //$NON-NLS-1$
}
/**
* Sends an Unchanged request to the server.
* <p>e.g. if a file called "local_file" was not modified, sends:
* <pre>
* Unchanged local_file \n
* </pre></p><p>
* Note: The most recent Directory request must have specified the file's
* parent folder.
* </p>
*
* @param file the file that was not modified
*/
public void sendUnchanged(ICVSFile file) throws CVSException {
connection.writeLine("Unchanged " + file.getName()); //$NON-NLS-1$
}
/**
* Sends the Notify request to the server
*/
public void sendNotify(ICVSFolder parent, NotifyInfo info)
throws CVSException {
String filename = info.getName();
connection.writeLine("Notify " + filename); //$NON-NLS-1$
connection.writeLine(info.getServerLine(parent));
}
/**
* Sends a Questionable request to the server.
* <p>
* Indicates that a file exists locally but is unmanaged. Asks the server
* whether or not the file should be ignored in subsequent CVS operations.
* The reply to the request occurs in the form of special M-type message
* responses prefixed with '?' when the next command is executed.
* </p><p>
* Note: The most recent Directory request must have specified the file's
* parent folder.
* </p>
*
* @param resource the local file or folder
*/
public void sendQuestionable(ICVSResource resource) throws CVSException {
connection.writeLine("Questionable " + resource.getName()); //$NON-NLS-1$
}
/**
* Sends a Sticky tag request to the server.
* <p>
* Indicates that the directory specified in the most recent Directory request
* has a sticky tag or date, and sends the tag's contents.
* </p>
*
* @param tag the sticky tag associated with the directory
*/
public void sendSticky(String tag) throws CVSException {
connection.writeLine("Sticky " + tag); //$NON-NLS-1$
}
/**
* Sends a Modified request to the server along with the file contents.
* <p>e.g. if a file called "local_file" was modified, sends:
* <pre>
* Modified local_file \n
* file_permissions \n
* file_size \n
* [... file_contents ...]
* </pre></p><p>
* Under some circumstances, Is-modified may be used in place of this request.<br>
* Do not use with history, init, import, rdiff, release, rtag, or update.
* </p><p>
* Note: The most recent Directory request must have specified the file's
* parent folder.
* </p>
*
* @param file the file that was modified
* @param isBinary if true the file is sent without translating line delimiters
* @param monitor the progress monitor
* @see #sendIsModified
*/
public void sendModified(ICVSFile file, boolean isBinary, IProgressMonitor monitor)
throws CVSException {
sendModified(file, isBinary, true, monitor);
}
public void sendModified(ICVSFile file, boolean isBinary, boolean sendBinary, IProgressMonitor monitor)
throws CVSException {
String filename = file.getName();
connection.writeLine("Modified " + filename); //$NON-NLS-1$
// send the default permissions for now
connection.writeLine(ResourceSyncInfo.getDefaultPermissions());
sendFile(file, isBinary, sendBinary, monitor);
}
/**
* Sends a file to the remote CVS server, possibly translating line delimiters.
* <p>
* Line termination sequences are automatically converted to linefeeds only
* (required by the CVS specification) when sending non-binary files. This
* may alter the actual size and contents of the file that is sent.
* </p><p>
* Note: Non-binary files must be small enough to fit in available memory.
* </p>
* @param file the file to be sent
* @param isBinary is true if the file should be sent without translation
* @param monitor the progress monitor
*/
public void sendFile(ICVSFile file, boolean isBinary, IProgressMonitor monitor) throws CVSException {
sendFile(file, isBinary, true, monitor);
}
public void sendFile(ICVSStorage file, boolean isBinary, boolean sendBinary, IProgressMonitor monitor) throws CVSException {
// check overrides
if (textTransferOverrideSet != null &&
textTransferOverrideSet.contains(file)) isBinary = false;
// update progress monitor
final String title = Policy.bind(getSendFileTitleKey(), new Object[]{ Util.toTruncatedPath(file, localRoot, 3) }); //$NON-NLS-1$
monitor.subTask(Policy.bind("Session.transferNoSize", title)); //$NON-NLS-1$
try {
InputStream in = null;
long length;
try {
if (isBinary && !sendBinary) {
byte[] bytes = "hello".getBytes(); //$NON-NLS-1$
sendUncompressedBytes(new ByteArrayInputStream(bytes), bytes.length);
return;
}
if (compressionLevel == 0) {
in = file.getContents();
if (!isBinary && IS_CRLF_PLATFORM){
// uncompressed text
byte[] buffer = new byte[TRANSFER_BUFFER_SIZE];
in = new CRLFtoLFInputStream(in);
ByteCountOutputStream counter = new ByteCountOutputStream();
try {
for (int count; (count = in.read(buffer)) != -1;) counter.write(buffer, 0, count);
} finally {
counter.close();
}
in.close();
length = counter.getSize();
in = new CRLFtoLFInputStream(file.getContents());
} else {
// uncompressed binary
length = file.getSize();
}
in = new ProgressMonitorInputStream(in, length, TRANSFER_PROGRESS_INCREMENT, monitor) {
protected void updateMonitor(long bytesRead, long bytesTotal, IProgressMonitor monitor) {
if (bytesRead == 0) return;
Assert.isTrue(bytesRead <= bytesTotal);
monitor.subTask(Policy.bind("Session.transfer", //$NON-NLS-1$
new Object[] { title, Long.toString(bytesRead >> 10), Long.toString(bytesTotal >> 10) }));
}
};
sendUncompressedBytes(in, length);
} else {
monitor.subTask(Policy.bind("Session.calculatingCompressedSize", Util.toTruncatedPath(file, localRoot, 3))); //$NON-NLS-1$
in = file.getContents();
byte[] buffer = new byte[TRANSFER_BUFFER_SIZE];
ByteCountOutputStream counter = new ByteCountOutputStream();
OutputStream zout = new GZIPOutputStream(counter);
if (!isBinary && IS_CRLF_PLATFORM) in = new CRLFtoLFInputStream(in);
try {
for (int count; (count = in.read(buffer)) != -1;) zout.write(buffer, 0, count);
} finally {
zout.close();
}
in.close();
in = file.getContents();
in = new ProgressMonitorInputStream(in, file.getSize(), TRANSFER_PROGRESS_INCREMENT, monitor) {
protected void updateMonitor(long bytesRead, long bytesTotal, IProgressMonitor monitor) {
if (bytesRead == 0) return;
Assert.isTrue(bytesRead <= bytesTotal);
monitor.subTask(Policy.bind("Session.transfer", //$NON-NLS-1$
new Object[] { title, Long.toString(bytesRead >> 10), Long.toString(bytesTotal >> 10) }));
}
};
if (!isBinary && IS_CRLF_PLATFORM) in = new CRLFtoLFInputStream(in);
sendCompressedBytes(in, counter.getSize());
}
} finally {
if (in != null) in.close();
}
} catch (IOException e) {
throw CVSException.wrapException(e);
}
}
/*
* Send the contents of the input stream to CVS.
* Length must equal the number of bytes that will be transferred
* across the wire, that is, the compressed file size.
*/
private void sendCompressedBytes(InputStream in, long length) throws IOException, CVSException {
String sizeLine = "z" + Long.toString(length); //$NON-NLS-1$
writeLine(sizeLine);
OutputStream out = connection.getOutputStream();
GZIPOutputStream zo = new GZIPOutputStream(out);
byte[] buffer = new byte[TRANSFER_BUFFER_SIZE];
for (int count;
(count = in.read(buffer)) != -1;)
zo.write(buffer, 0, count);
zo.finish();
}
/*
* Send the contents of the input stream to CVS.
* Length must equal the number of bytes that will be transferred
* across the wire.
*/
private void sendUncompressedBytes(InputStream in, long length) throws IOException, CVSException {
OutputStream out = connection.getOutputStream();
String sizeLine = Long.toString(length);
writeLine(sizeLine);
byte[] buffer = new byte[TRANSFER_BUFFER_SIZE];
for (int count; (count = in.read(buffer)) != -1;) out.write(buffer, 0, count);
}
/**
* Receives a file from the remote CVS server, possibly translating line delimiters.
* <p>
* Line termination sequences are automatically converted to platform format
* only when receiving non-binary files. This may alter the actual size and
* contents of the file that is received.
* </p><p>
* Translation is performed on-the-fly, so the file need not fit in available memory.
* </p>
* @param file the file to be received
* @param isBinary is true if the file should be received without translation
* @param responseType one of the ICVSFile updated types (UPDATED, CREATED, MERGED, UPDATE_EXISTING)
* indicating what repsonse type provided the file contents
* @param monitor the progress monitor
*/
public void receiveFile(ICVSStorage file, boolean isBinary, int responseType, IProgressMonitor monitor)
throws CVSException {
// check overrides
if (textTransferOverrideSet != null &&
textTransferOverrideSet.contains(file)) isBinary = false;
// update progress monitor
final String title = Policy.bind("Session.receiving", new Object[]{ Util.toTruncatedPath(file, localRoot, 3) }); //$NON-NLS-1$
monitor.subTask(Policy.bind("Session.transferNoSize", title)); //$NON-NLS-1$
// get the file size from the server
long size;
boolean compressed = false;
try {
String sizeLine = readLine();
if (sizeLine.charAt(0) == 'z') {
compressed = true;
sizeLine = sizeLine.substring(1);
}
size = Long.parseLong(sizeLine, 10);
} catch (NumberFormatException e) {
throw new CVSException(Policy.bind("Session.badInt"), e); //$NON-NLS-1$
}
// create an input stream that spans the next 'size' bytes from the connection
InputStream in = new SizeConstrainedInputStream(connection.getInputStream(), size, true /*discardOnClose*/);
// setup progress monitoring
in = new ProgressMonitorInputStream(in, size, TRANSFER_PROGRESS_INCREMENT, monitor) {
protected void updateMonitor(long bytesRead, long bytesTotal, IProgressMonitor monitor) {
if (bytesRead == 0) return;
monitor.subTask(Policy.bind("Session.transfer", //$NON-NLS-1$
new Object[] { title, Long.toString(bytesRead >> 10), Long.toString(bytesTotal >> 10) }));
}
};
// if compression enabled, decompress on the fly
if (compressed) {
try {
in = new GZIPInputStream(in);
} catch (IOException e) {
throw CVSException.wrapException(e);
}
}
// if not binary, translate line delimiters on the fly
if (! isBinary) {
// switch from LF to CRLF if appropriate
if (IS_CRLF_PLATFORM && CVSProviderPlugin.getPlugin().isUsePlatformLineend()) {
// auto-correct for CRLF line-ends that come from the server
in = new CRLFtoLFInputStream(in);
// convert LF to CRLF
in = new LFtoCRLFInputStream(in);
} else {
// be nice and warn about text files that contain CRLF
in = new CRLFDetectInputStream(in, file);
}
}
// write the file locally
file.setContents(in, responseType, true, new NullProgressMonitor());
}
/**
* Stores the value of the last Mod-time response encountered.
* Valid only for the duration of a single CVS command.
*/
void setModTime(Date modTime) {
this.modTime = modTime;
}
/**
* Returns the stored value of the last Mod-time response,
* or null if there was none while processing the current command.
*/
Date getModTime() {
return modTime;
}
/**
* Stores true if the -n global option was specified for the current command.
* Valid only for the duration of a single CVS command.
*/
void setNoLocalChanges(boolean noLocalChanges) {
this.noLocalChanges = noLocalChanges;
}
/**
* Returns true if the -n global option was specified for the current command,
* false otherwise.
*/
boolean isNoLocalChanges() {
return noLocalChanges;
}
/**
* Callback hook for the ValidRequestsHandler to specify the set of valid
* requests for this session.
*/
void setValidRequests(String validRequests) {
this.validRequests = " " + validRequests + " "; //$NON-NLS-1$ //$NON-NLS-2$
}
boolean isOutputToConsole() {
return outputToConsole;
}
/**
* Stores a flag as to whether .# files will be created. (Default is true)
* @param createBackups if true, creates .# files at the server's request
*/
void setCreateBackups(boolean createBackups) {
this.createBackups = createBackups;
}
/**
* Returns a flag as to whether .# files will be created.
*/
boolean isCreateBackups() {
return createBackups;
}
/**
* Gets the sendFileTitleKey.
* @return Returns a String
*/
String getSendFileTitleKey() {
if (sendFileTitleKey == null)
return "Session.sending"; //$NON-NLS-1$
return sendFileTitleKey;
}
/**
* Sets the sendFileTitleKey.
* @param sendFileTitleKey The sendFileTitleKey to set
*/
public void setSendFileTitleKey(String sendFileTitleKey) {
this.sendFileTitleKey = sendFileTitleKey;
}
/**
* Remembers a set of files that must be transferred as 'text'
* regardless of what the isBinary parameter to sendFile() is.
*
* @param textTransferOverrideSet the set of ICVSFiles to override, or null if none
*/
public void setTextTransferOverride(Collection textTransferOverrideSet) {
this.textTransferOverrideSet = textTransferOverrideSet;
}
/**
* Filter the provided global options using parameters set on this session
* or globally. The session may add global options that correspond to user
* preferences or remove those that contradict requirements for this
* particular session.
*
* @param globalOptions the global options, read-only
* @return the filtered global options
*/
protected GlobalOption[] filterGlobalOptions(GlobalOption[] globalOptions) {
if (! Command.DO_NOT_CHANGE.isElementOf(globalOptions)) {
// Get the user preference for verbosity
QuietOption quietOption = CVSProviderPlugin.getPlugin().getQuietness();
if (quietOption != null) {
globalOptions = quietOption.addToEnd(globalOptions);
}
// Get the user preference for read-only
if (CVSProviderPlugin.getPlugin().getPluginPreferences().getBoolean(CVSProviderPlugin.READ_ONLY)) {
if (!Command.MAKE_READ_ONLY.isElementOf(globalOptions)) {
globalOptions = Command.MAKE_READ_ONLY.addToEnd(globalOptions);
}
}
}
return globalOptions;
}
/**
* Method setIgnoringLocalChanges.
* @param b
*/
protected void setIgnoringLocalChanges(boolean b) {
ignoringLocalChanges = b;
}
/**
* Returns the ignoringLocalChanges.
* @return boolean
*/
protected boolean isIgnoringLocalChanges() {
return ignoringLocalChanges;
}
/*
* Get the response handler map to be used for this session. The map is created by making a copy of the global
* reponse handler map.
*/
protected Map getReponseHandlers() {
if (responseHandlers == null) {
responseHandlers = Request.getReponseHandlerMap();
}
return responseHandlers;
}
/*
* Makes a list of all valid responses; for initializing a session.
* @return a space-delimited list of all valid response strings
*/
private String makeResponseList() {
StringBuffer result = new StringBuffer("ok error M E"); //$NON-NLS-1$
Iterator elements = getReponseHandlers().keySet().iterator();
while (elements.hasNext()) {
result.append(' ');
result.append((String) elements.next());
}
return result.toString();
}
public void registerResponseHandler(ResponseHandler handler) {
getReponseHandlers().put(handler.getResponseID(), handler);
}
public void removeResponseHandler(String responseID) {
getReponseHandlers().remove(responseID);
}
public ResponseHandler getResponseHandler(String responseID) {
return (ResponseHandler)getReponseHandlers().get(responseID);
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
c3a727908b896be0553bfe85032def2665460ecc | dd53ac6bc61c67b41874ec4c8e83829926bc1696 | /src/s3/client/presentation/View.java | f6920ed860653f2d2d7d8fcdb9687ceeb5920ffc | [] | no_license | cluePrints/gwt-snake | 8b24667036b80b6ea9505a22d556d3509f7def99 | 09cc07eb850e156cb658454f90448db1e0af07c0 | refs/heads/master | 2020-04-08T19:13:50.179929 | 2011-12-24T13:41:46 | 2011-12-24T13:41:46 | 3,044,826 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 395 | java | package s3.client.presentation;
import java.util.Collection;
import s3.client.domain.CellContent;
import s3.client.domain.Position;
public interface View {
void renderSegments(Collection<Position> segments, CellContent type);
void renderMaxScore(int score);
void renderCurrentScore(int score);
void updatePlaygroundSize(int horizontalCells, int verticalCells);
void clearPlayground();
} | [
"clueprints@gmail.com"
] | clueprints@gmail.com |
8cacdabc753122ce444c3b73e00df1f9eb6ba735 | 96b799235c56481e130b09276a9c14769d606a44 | /app/src/main/java/me/tivanov/cardocr/Helper/Misc.java | 76f3a851ed5513288b51dac2e1c5feb275e31740 | [] | no_license | tivanov/AndroidCardOcr | cc89c3f43e02ab3815aa2d68bf71bc999dc1724c | 5d207606b15f21380c52c8ef52129f473744a0b8 | refs/heads/master | 2021-01-19T22:09:18.400200 | 2019-03-22T20:23:13 | 2019-03-22T20:23:13 | 76,108,920 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,980 | java | package me.tivanov.cardocr.Helper;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import static org.opencv.core.Core.FILLED;
import static org.opencv.core.Core.countNonZero;
import static org.opencv.core.CvType.CV_8UC1;
import static org.opencv.imgproc.Imgproc.adaptiveThreshold;
import static org.opencv.imgproc.Imgproc.boundingRect;
import static org.opencv.imgproc.Imgproc.cvtColor;
import static org.opencv.imgproc.Imgproc.drawContours;
import static org.opencv.imgproc.Imgproc.findContours;
import static org.opencv.imgproc.Imgproc.getStructuringElement;
import static org.opencv.imgproc.Imgproc.morphologyEx;
import static org.opencv.imgproc.Imgproc.threshold;
public class Misc {
public static int THRESH_TYPE_NORMAL = 1;
public static int THRESH_TYPE_ADAPTIVE = 2;
public static String saveToInternalStorage(String fileName, Bitmap bitmapImage, Context ctx){
ContextWrapper cw = new ContextWrapper(ctx.getApplicationContext());
// path to /data/data/cardocr/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
public static Bitmap loadImageFromStorage(String fileName, String path)
{
try {
File f=new File(path, fileName);
return BitmapFactory.decodeStream(new FileInputStream(f));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
return null;
}
public static boolean deleteImageFromStorage(String fileName, String path)
{
try {
File f=new File(path, fileName);
return f.delete();
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
public static Mat preProcessImage (int thresh, int threshType, Mat mRgba, Session session) {
Mat image = new Mat();
Mat mGray = new Mat();
//convert to grayscale
cvtColor(mRgba, mGray, Imgproc.COLOR_RGBA2GRAY);
//Apply thresholding
if (thresh == Misc.THRESH_TYPE_ADAPTIVE) //ADAPTIVE
adaptiveThreshold(mGray, image, 255, threshType, Imgproc.THRESH_BINARY, session.getBlockSize(), session.getConst());
else if (thresh == Misc.THRESH_TYPE_NORMAL) //NORMAL
Imgproc.threshold(mGray, image,session.getThreshold(), session.getMaxVal(), threshType + Imgproc.THRESH_OTSU);
return image;
}
public static Mat preProcessImage (int thresh, int threshType, Mat mRgba, Map<String, String> params) {
Mat image = new Mat();
Mat mGray = new Mat();
//convert to grayscale
cvtColor(mRgba, mGray, Imgproc.COLOR_RGBA2GRAY);
//Apply thresholding
if (thresh == Misc.THRESH_TYPE_ADAPTIVE) //ADAPTIVE
adaptiveThreshold(mGray, image, 255, threshType, Imgproc.THRESH_BINARY, Integer.parseInt(params.get("blockSize")), Double.parseDouble(params.get("const")));
else if (thresh == Misc.THRESH_TYPE_NORMAL) //NORMAL
Imgproc.threshold(mGray, image,Double.parseDouble(params.get("threshold")), Double.parseDouble(params.get("maxVal")), threshType + Imgproc.THRESH_OTSU);
return image;
}
public static ArrayList<Rect> filteredRects(ArrayList<Rect> source) {
ArrayList<Rect> dest = new ArrayList<>();
boolean flag;
for (Rect r1 : source) {
flag = true;
for (Rect r2 : source)
if (r1 != r2 && r2.contains(r1.tl()) && r2.contains(r1.br()))
flag = false;
if (flag) dest.add(r1);
}
return dest;
}
public static void savePublicImage(Bitmap bmp, String fileName) {
String sdCardPath = Environment.getExternalStorageDirectory().getPath();
if (!sdCardPath.endsWith("/"))
sdCardPath = sdCardPath + "/";
File myDir=new File(sdCardPath+"OCRImages");
myDir.mkdirs();
File file = new File (myDir, fileName);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void savePublicImage(Mat mat, String fileName) {
Bitmap bmp = Bitmap.createBitmap(mat.cols(), mat.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mat, bmp);
savePublicImage(bmp, fileName);
}
public static ArrayList<Rect> findText(Mat original, boolean saveSteps) {
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
Scalar contourColor = new Scalar(255, 255, 255);
Mat gray = new Mat();
cvtColor(original, gray, Imgproc.COLOR_BGR2GRAY);
// 1) morphological gradient
Mat grad = new Mat();
Mat morphKernel = getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(3, 3));
if (saveSteps) savePublicImage(morphKernel, n + "_0-Morph_kernel.jpg");
morphologyEx(gray, grad, Imgproc.MORPH_GRADIENT, morphKernel);
if (saveSteps) savePublicImage(grad, n + "_1-Morph_gradient.jpg");
// 2) binarize
Mat bw = new Mat();
threshold(grad, bw, 0.0, 255.0, Imgproc.THRESH_OTSU);
if (saveSteps) savePublicImage(bw, n + "_2-Binarized_gradient.jpg");
// 3) connect horizontally oriented regions
Mat connected = new Mat();
morphKernel = getStructuringElement(Imgproc.MORPH_RECT, new Size(9, 1));
morphologyEx(bw, connected, Imgproc.MORPH_CLOSE, morphKernel);
if (saveSteps) savePublicImage(connected, n + "_3-Connected_horiz_regions.jpg");
// 4) find contours
Mat mask = Mat.zeros(bw.size(), CV_8UC1);
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat();
findContours(connected, contours, hierarchy, Imgproc.RETR_CCOMP, Imgproc.CHAIN_APPROX_SIMPLE, new Point(0, 0));
// 5) filter contours
Rect rect;
ArrayList<Rect> textRects = new ArrayList<>();
for(int idx = 0; idx < contours.size(); idx++)
{
rect = boundingRect(contours.get(idx));
Mat maskROI = new Mat(mask, rect);
// fill the contour
drawContours(mask, contours, idx, contourColor, FILLED);
// ratio of non-zero pixels in the filled region
double r = (double)countNonZero(maskROI)/(rect.width*rect.height);
if (r > .45 && (rect.height > 8 && rect.width > 8))
textRects.add(rect);
// rectangle(original, rect.tl(), rect.br(), new Scalar(0, 255, 0), 2);
}
if (saveSteps) savePublicImage(mask, n + "_4-Final_contours.jpg");
return filteredRects(textRects);
}
public static ArrayList<Rect> findText(Mat original) {
Scalar contourColor = new Scalar(255, 255, 255);
Mat gray = new Mat();
cvtColor(original, gray, Imgproc.COLOR_BGR2GRAY);
// 1) morphological gradient
Mat grad = new Mat();
Mat morphKernel = getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(3, 3));
morphologyEx(gray, grad, Imgproc.MORPH_GRADIENT, morphKernel);
// 2) binarize
Mat bw = new Mat();
threshold(grad, bw, 0.0, 255.0, Imgproc.THRESH_OTSU);
// 3) connect horizontally oriented regions
Mat connected = new Mat();
morphKernel = getStructuringElement(Imgproc.MORPH_RECT, new Size(9, 1));
morphologyEx(bw, connected, Imgproc.MORPH_CLOSE, morphKernel);
// 4) find contours
Mat mask = Mat.zeros(bw.size(), CV_8UC1);
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat();
findContours(connected, contours, hierarchy, Imgproc.RETR_CCOMP, Imgproc.CHAIN_APPROX_SIMPLE, new Point(0, 0));
// 5) filter contours
Rect currentRect;
Mat maskROI;
ArrayList<Rect> textRects = new ArrayList<>();
for(int idx = 0; idx < contours.size(); idx++)
{
currentRect = boundingRect(contours.get(idx));
maskROI = new Mat(mask, currentRect);
// fill the contour
drawContours(mask, contours, idx, contourColor, FILLED);
// ratio of non-zero pixels in the filled region
double r = (double)countNonZero(maskROI)/(currentRect.width*currentRect.height);
if (r > .45 && (currentRect.height > 8 && currentRect.width > 8))
textRects.add(currentRect);
}
return filteredRects(textRects);
}
}
| [
"tome_ivanov@windowslive.com"
] | tome_ivanov@windowslive.com |
9d951d0249b13c9343f77125cc444f1263a9641a | f5c0348b01577682dffa3cc59211a829e37ee601 | /com/google/ads/as.java | 80a59f225f690ce5c5a5ab2b088ebab7cb1b431e | [] | no_license | ashutoshsingh2250/digital-diary | 5a22ebbc18794811ba9d90e0eaaa5ac4fca71f9c | 51652b83c525b8ce075b7acd0e91f9d6c1c372c5 | refs/heads/master | 2020-03-11T18:46:16.927972 | 2018-04-19T09:18:34 | 2018-04-19T09:18:34 | 130,187,654 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 368 | java | package com.google.ads;
import android.net.Uri;
public class as
{
public static final Uri a = Uri.parse("content://com.google.plus.platform/token");
public static final String[] b = { "drt" };
}
/* Location: C:\Users\Yash\Desktop\apk to src\dex2jar-0.0.9.15\classes_dex2jar.jar
* Qualified Name: com.google.ads.as
* JD-Core Version: 0.6.0
*/ | [
"ashutoshsingh2250@gmail.com"
] | ashutoshsingh2250@gmail.com |
d540e28ace3cda658c4936c89300aa94fbc0c629 | 2ce5f23ad11de35ade051341594f4432f385a1e3 | /src/main/java/org/citizeninn/webdemo/controller/AccountController.java | 8506f4aac3a442cf178570c74a36140b157678b5 | [] | no_license | CitizenInn/webdemo | 9fa1de446893af1056746da2edb0b93cd3d7888b | f51b74851467c7db2c59005e5b87cf38c78dcd52 | refs/heads/master | 2020-04-06T10:34:39.521546 | 2012-12-16T17:45:56 | 2012-12-16T17:45:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,027 | java | package org.citizeninn.webdemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping(value = "/account", method = RequestMethod.GET)
public ModelAndView findAllAccounts() throws Exception {
ModelAndView mav = new ModelAndView();
mav.setViewName("account");
mav.addObject("someText", "Listing all accounts!");
return mav;
}
@RequestMapping(value = "/{accountId}", method = RequestMethod.GET)
public ModelAndView findAccount(@PathVariable int accountId, Model model) {
ModelAndView mav = new ModelAndView();
mav.setViewName("account");
mav.addObject("someText",
String.format("Showing account %d", accountId));
return mav;
}
} | [
"borys86@gmail.com"
] | borys86@gmail.com |
c4ecd440326e34e64b2e84a93641f40fa62b0c9b | f9d1340f5a9eff10d0d2b1981f228ef8d09832eb | /src/com/tuzhi/activiti/filter/LoginFilter.java | 38573859aec4269709cdf4ff23ef0f760191e96b | [] | no_license | codeZDC/activiti | 9fbe24d6cde209eed3c710078f710ff664b16d03 | dc3fc67721920e0afa2da0f186fba658fe736f8d | refs/heads/master | 2020-03-12T21:45:16.637507 | 2018-04-26T06:29:55 | 2018-04-26T06:29:55 | 130,834,237 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,662 | java | package com.tuzhi.activiti.filter;
import java.awt.image.RescaleOp;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import com.tuzhi.activiti.domain.User;
import com.tuzhi.activiti.util.Contants;
/**
* 登录过滤器
* @author codeZ
* @date 2018年4月20日 下午4:12:06
*
*/
public class LoginFilter implements Filter {
private FilterConfig config;
@Override
public void destroy() {
System.out.println("loginFilter 即将销毁!");
}
@Override
public void doFilter(ServletRequest req , ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
//不需要过滤的内容
String[] excludes = config.getInitParameter("excludeUrl").split(",");
if(isExcludes(excludes,request.getRequestURI())){
chain.doFilter(request, response);
return;
}
User user =
(User)request.getSession().getAttribute(Contants.SESSION_USER);
if(user==null)
request.getRequestDispatcher("/login.jsp").forward(request, response);
else
chain.doFilter(request, response);
}
//是否是过滤url
private boolean isExcludes(String[] excludes, String url) {
for (String string : excludes) {
if(url.contains(string))
return true;
}
return false;
}
@Override
public void init(FilterConfig arg0) throws ServletException {
config = arg0;
System.out.println("loginFilter 初始化成功!");
}
}
| [
"1184081087@qq.com"
] | 1184081087@qq.com |
3d324e9e80c7091a800310ef96a89ec7d5e7af96 | 51de03ecef5b62ecf6af33cbb6481b54c61a3d83 | /src/main/java/org/diveintojee/foobarquix/FooBarQix.java | 076cfa1c044bec03b972ddcc32b6b069df3427d4 | [] | no_license | lgueye/foobarqix | 111ea5ea7f6166c39d260e62160def2c87e8f388 | 941df69e3eca1a72409406a1d6cfc2ce02d5aa50 | refs/heads/master | 2021-01-22T03:08:49.442112 | 2011-12-09T14:46:58 | 2011-12-09T14:46:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,253 | java | /*
*
*/
package org.diveintojee.foobarquix;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.lang3.StringUtils;
/**
* @author louis.gueye@gmail.com
*/
public class FooBarQix {
public static void main(final String[] args) {
for (int index = 1; index < 101; index++) {
System.out.println(new FooBarQix(index));
}
}
private final int input;
private final StringBuilder output = new StringBuilder();
private static Map<Integer, String> encodings;
static {
encodings = new TreeMap<Integer, String>();
encodings.put(3, "Foo");
encodings.put(5, "Bar");
encodings.put(7, "Qix");
}
/**
* @param i
*/
public FooBarQix(final int i) {
input = i;
}
/**
* @return
*/
public FooBarQix applyContainsRule() {
if (!checkPreconditions())
return this;
final String inputAsString = String.valueOf(input);
for (int i = 0; i < inputAsString.length(); i++) {
final char digit = inputAsString.charAt(i);
final String digitAsString = String.valueOf(digit);
final Integer key = Integer.valueOf(digitAsString);
if (encodings.keySet().contains(key)) {
output.append(encodings.get(key));
}
}
return this;
}
/**
* @return
*/
public FooBarQix applyDivisibleRule() {
if (!checkPreconditions())
return this;
for (final Integer key : encodings.keySet()) {
if (input % key == 0) {
output.append(encodings.get(key));
}
}
return this;
}
/**
* @return
*/
public String build() {
if (StringUtils.isEmpty(output.toString()))
return String.valueOf(input);
return output.toString();
}
private boolean checkPreconditions() {
if (input < 1 || input > 100)
return false;
return true;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return applyDivisibleRule().applyContainsRule().build();
}
}
| [
"louis.gueye@gmail.com"
] | louis.gueye@gmail.com |
d76c46c3986a34e8b54ab879f0929676c1b0a99c | 0126c023399ae6fd8a8e3e5e0f57e81a16901c95 | /app/src/main/java/com/example/sumit/loginregistration/Welcome.java | e97340d280c52d7cb3c5a861cd27e949257845db | [] | no_license | Soumikn/LoginRegistration | 7dd475041c1088f86c9243c27e4c15d8ae9dc1ef | c476f40f5100e241b0e862da35f243c28cfd210a | refs/heads/master | 2020-03-30T00:39:37.057937 | 2017-05-22T06:04:38 | 2017-05-22T06:04:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 346 | java | package com.example.sumit.loginregistration;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class Welcome extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
}
}
| [
"sumit12rds@gmail.com"
] | sumit12rds@gmail.com |
878b124e87e0c3c2c3cc34257d6c436f90198957 | 3d723e17c6e701a6d1359547fe00ac9a947a3231 | /gmall-manage-service/src/main/java/com/atguigu/gmall/manage/service/impl/SkuInfoServiceImpl.java | 2ac367101a947bdeff9c32e0be85660e35e8aaa0 | [] | no_license | xiaoshuaiq/gmall0416 | 76b04933dff820411a19450fdc0ef36e0e18f0e8 | 3e95fe5c20cee0af649f09565bd0343cf7aa11ac | refs/heads/master | 2020-03-27T00:43:06.569206 | 2018-08-29T00:53:20 | 2018-08-29T00:53:31 | 145,648,755 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,422 | java | package com.atguigu.gmall.manage.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.gmall.bean.*;
import com.atguigu.gmall.manage.mapper.*;
import com.atguigu.gmall.service.SkuInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* @author xiaos
* @create 2018-08-28 19:12
*/
@Service
public class SkuInfoServiceImpl implements SkuInfoService {
@Autowired
private SpuImageMapper spuImageMapper;
@Autowired
private SkuInfoMapper skuInfoMapper;
@Autowired
private SkuImageMapper skuImageMapper;
@Autowired
private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
@Autowired
private SkuAttrValueMapper skuAttrValueMapper;
@Override
public List<SpuImage> getSpuImage(String spuId) {
SpuImage spuImage = new SpuImage();
spuImage.setSpuId(spuId);
return spuImageMapper.select(spuImage);
}
@Override
public void saveSku(SkuInfo skuInfo) {
// 插入skuInfo
if (skuInfo.getId()==null || skuInfo.getId().length()==0){
skuInfo.setId(null);
skuInfoMapper.insertSelective(skuInfo);
}else {
skuInfoMapper.updateByPrimaryKeySelective(skuInfo);
}
// 删除skuImg
SkuImage skuImage = new SkuImage();
skuImage.setSkuId(skuInfo.getId());
skuImageMapper.delete(skuImage);
// 插入
List<SkuImage> skuImageList = skuInfo.getSkuImageList();
if (skuImageList!=null && skuImageList.size()>0){
for (SkuImage image : skuImageList) {
if (image.getId()!=null && image.getId().length()==0){
image.setId(null);
}
// skuId
image.setSkuId(skuInfo.getId());
skuImageMapper.insertSelective(image);
}
}
// sku_sale_attr_value
SkuSaleAttrValue skuSaleAttrValue = new SkuSaleAttrValue();
skuSaleAttrValue.setSkuId(skuInfo.getId());
skuSaleAttrValueMapper.delete(skuSaleAttrValue);
// 插入数据
List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
if (skuSaleAttrValueList!=null && skuSaleAttrValueList.size()>0){
for (SkuSaleAttrValue saleAttrValue : skuSaleAttrValueList) {
if (saleAttrValue.getId()!=null && saleAttrValue.getId().length()==0){
saleAttrValue.setId(null);
}
// skuId
saleAttrValue.setSkuId(skuInfo.getId());
skuSaleAttrValueMapper.insertSelective(saleAttrValue);
}
}
// sku_attr_value
SkuAttrValue skuAttrValue = new SkuAttrValue();
skuAttrValue.setSkuId(skuInfo.getId());
skuAttrValueMapper.delete(skuAttrValue);
// 插入数据
List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
if (skuAttrValueList!=null && skuAttrValueList.size()>0){
for (SkuAttrValue attrValue : skuAttrValueList) {
if (attrValue.getId()!=null && attrValue.getId().length()==0){
attrValue.setId(null);
}
// skuId
attrValue.setSkuId(skuInfo.getId());
skuAttrValueMapper.insertSelective(attrValue);
}
}
}
}
| [
"1543010660@qq.com"
] | 1543010660@qq.com |
45d0b7cf4cd24fdb49a94efabc8e41d549252a43 | 37c11a7fa33e0461dc2c19ffdbd0c50014553b15 | /app_patient/src/main/java/com/kmwlyy/patient/kdoctor/permission/PermissionManager.java | 87aa3ccc9d6f7feb19683563df9641460dfba034 | [] | no_license | SetAdapter/KMYYAPP | 5010d4e8a3dd60240236db15b34696bb443914b7 | 57eeba04cb5ae57911d1fa47ef4b2320eb1f9cbf | refs/heads/master | 2020-04-23T13:56:33.078507 | 2019-02-18T04:39:40 | 2019-02-18T04:39:40 | 171,215,008 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 4,099 | java | package com.kmwlyy.patient.kdoctor.permission;
import android.annotation.TargetApi;
import android.os.Build;
import android.provider.Settings;
import android.util.SparseArray;
import java.util.Arrays;
import java.util.List;
/**
* Created by lyy on 2016/4/11.
* 权限管理工具类
*/
@TargetApi(Build.VERSION_CODES.M)
public class PermissionManager implements OnPermissionCallback {
private static final String TAG = "PermissionManager";
private PermissionUtil mPu;
private SparseArray<OnPermissionCallback> mCallbacks = new SparseArray<>();
private static volatile PermissionManager INSTANCE = null;
private static final Object LOCK = new Object();
public static PermissionManager getInstance() {
if (INSTANCE == null) {
synchronized (LOCK) {
INSTANCE = new PermissionManager();
}
}
return INSTANCE;
}
private PermissionManager() {
mPu = PermissionUtil.getInstance();
}
/**
* 申请悬浮框权限
*
* @param obj obj 只能是Activity、Fragment 的子类及其衍生类
*/
public void requestAlertWindowPermission(Object obj, OnPermissionCallback callback) {
int hashCode = Arrays.hashCode(new String[]{Settings.ACTION_MANAGE_OVERLAY_PERMISSION});
registerCallback(callback, hashCode);
mPu.requestAlertWindowPermission(obj);
}
/**
* 申请修改系统设置权限
*
* @param obj obj 只能是Activity、Fragment 的子类及其衍生类
*/
public void requestWriteSettingPermission(Object obj, OnPermissionCallback callback) {
int hashCode = Arrays.hashCode(new String[]{Settings.ACTION_MANAGE_WRITE_SETTINGS});
registerCallback(callback, hashCode);
mPu.requestWriteSetting(obj);
}
/**
* 申请权限
*
* @param obj Activity || Fragment
* @param permission
*/
public void requestPermission(Object obj, OnPermissionCallback callback, String... permission) {
requestPermission(obj, callback, "", registerCallback(obj, callback, permission));
}
/**
* 申请权限
*
* @param obj Activity || Fragment
* @param hint 如果框对话框包含“不再询问”选择框的时候的提示用语。
* @param permission
*/
private void requestPermission(Object obj, OnPermissionCallback callback, String hint, String... permission) {
mPu.requestPermission(obj, 0, hint, registerCallback(obj, callback, permission));
}
private void registerCallback(OnPermissionCallback callback, int hashCode) {
OnPermissionCallback c = mCallbacks.get(hashCode);
if (c == null) {
mCallbacks.append(hashCode, callback);
}
}
private String[] registerCallback(Object obj, OnPermissionCallback callback, String... permission) {
List<String> list = mPu.checkPermission(obj, permission);
if (list == null || list.size() == 0) {
return null;
}
String[] denyPermission = mPu.list2Array(list);
int hashCode = Arrays.hashCode(denyPermission);
OnPermissionCallback c = mCallbacks.get(hashCode);
if (c == null) {
mCallbacks.append(hashCode, callback);
}
return denyPermission;
}
@Override
public void onSuccess(String... permissions) {
int hashCode = Arrays.hashCode(permissions);
OnPermissionCallback c = mCallbacks.get(hashCode);
if (c != null) {
c.onSuccess(permissions);
mCallbacks.remove(hashCode);
}
}
@Override
public void onFail(String... permissions) {
int hashCode = Arrays.hashCode(permissions);
OnPermissionCallback c = mCallbacks.get(hashCode);
if (c != null) {
c.onFail(permissions);
mCallbacks.remove(hashCode);
}
}
}
| [
"383411934@qq.com"
] | 383411934@qq.com |
9ec2d57ce21ef764c326586499c48637d868c687 | 2fa16b8c5339265f5cae4f4b1c80f6af030996a7 | /jif-gui/src/main/java/edu/mbl/jif/gui/table/sortTable/BevelArrowIcon.java | 3bbbd99a1da47a99515b9f7135c8f59347be162f | [] | no_license | amitabhverma/jif-experimental | e2c5a354c1e431ea36035f136cd6f71a265ab6fc | f3854b7a877e4a242884e0b84349be7d15a9013c | refs/heads/master | 2021-01-17T06:08:39.490610 | 2016-01-26T19:46:42 | 2016-01-26T19:46:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,769 | java | /* (swing1.1) */
package edu.mbl.jif.gui.table.sortTable;
import java.awt.*;
import javax.swing.*;
/**
* @version 1.0 02/26/99
*/
public class BevelArrowIcon implements Icon {
public static final int UP = 0; // direction
public static final int DOWN = 1;
private static final int DEFAULT_SIZE = 11;
private Color edge1;
private Color edge2;
private Color fill;
private int size;
private int direction;
public BevelArrowIcon(int direction, boolean isRaisedView, boolean isPressedView) {
if (isRaisedView) {
if (isPressedView) {
init( UIManager.getColor("controlLtHighlight"),
UIManager.getColor("controlDkShadow"),
UIManager.getColor("controlShadow"),
DEFAULT_SIZE, direction);
} else {
init( UIManager.getColor("controlHighlight"),
UIManager.getColor("controlShadow"),
UIManager.getColor("control"),
DEFAULT_SIZE, direction);
}
} else {
if (isPressedView) {
init( UIManager.getColor("controlDkShadow"),
UIManager.getColor("controlLtHighlight"),
UIManager.getColor("controlShadow"),
DEFAULT_SIZE, direction);
} else {
init( UIManager.getColor("controlShadow"),
UIManager.getColor("controlHighlight"),
UIManager.getColor("control"),
DEFAULT_SIZE, direction);
}
}
}
public BevelArrowIcon(Color edge1, Color edge2, Color fill,
int size, int direction) {
init(edge1, edge2, fill, size, direction);
}
public void paintIcon(Component c, Graphics g, int x, int y) {
switch (direction) {
case DOWN: drawDownArrow(g, x, y); break;
case UP: drawUpArrow(g, x, y); break;
}
}
public int getIconWidth() {
return size;
}
public int getIconHeight() {
return size;
}
private void init(Color edge1, Color edge2, Color fill,
int size, int direction) {
this.edge1 = edge1;
this.edge2 = edge2;
this.fill = fill;
this.size = size;
this.direction = direction;
}
private void drawDownArrow(Graphics g, int xo, int yo) {
g.setColor(edge1);
g.drawLine(xo, yo, xo+size-1, yo);
g.drawLine(xo, yo+1, xo+size-3, yo+1);
g.setColor(edge2);
g.drawLine(xo+size-2, yo+1, xo+size-1, yo+1);
int x = xo+1;
int y = yo+2;
int dx = size-6;
while (y+1 < yo+size) {
g.setColor(edge1);
g.drawLine(x, y, x+1, y);
g.drawLine(x, y+1, x+1, y+1);
if (0 < dx) {
g.setColor(fill);
g.drawLine(x+2, y, x+1+dx, y);
g.drawLine(x+2, y+1, x+1+dx, y+1);
}
g.setColor(edge2);
g.drawLine(x+dx+2, y, x+dx+3, y);
g.drawLine(x+dx+2, y+1, x+dx+3, y+1);
x += 1;
y += 2;
dx -= 2;
}
g.setColor(edge1);
g.drawLine(xo+(size/2), yo+size-1, xo+(size/2), yo+size-1);
}
private void drawUpArrow(Graphics g, int xo, int yo) {
g.setColor(edge1);
int x = xo+(size/2);
g.drawLine(x, yo, x, yo);
x--;
int y = yo+1;
int dx = 0;
while (y+3 < yo+size) {
g.setColor(edge1);
g.drawLine(x, y, x+1, y);
g.drawLine(x, y+1, x+1, y+1);
if (0 < dx) {
g.setColor(fill);
g.drawLine(x+2, y, x+1+dx, y);
g.drawLine(x+2, y+1, x+1+dx, y+1);
}
g.setColor(edge2);
g.drawLine(x+dx+2, y, x+dx+3, y);
g.drawLine(x+dx+2, y+1, x+dx+3, y+1);
x -= 1;
y += 2;
dx += 2;
}
g.setColor(edge1);
g.drawLine(xo, yo+size-3, xo+1, yo+size-3);
g.setColor(edge2);
g.drawLine(xo+2, yo+size-2, xo+size-1, yo+size-2);
g.drawLine(xo, yo+size-1, xo+size, yo+size-1);
}
}
| [
"gharris@mbl.edu"
] | gharris@mbl.edu |
665b6e62b81f448de1557c9f745810c2b4fe4874 | 9ecd786a2d010ddbfd79e35c251b7f7d0b4b3d7b | /codegen/src/main/java/org/seasar/doma/gradle/codegen/util/ResourceUtil.java | 1bb374e7dbc2fcefbe04bddffd6e91d24e5105fd | [
"Apache-2.0"
] | permissive | domaframework/doma-codegen-plugin | db560c6b444f6e9730e36445b2b657729fb5a4cf | 145f8ccf3be3c2255ad4e53c1886954644a650dc | refs/heads/master | 2023-09-01T00:52:09.845591 | 2023-08-17T11:25:05 | 2023-08-17T13:35:58 | 252,963,822 | 17 | 2 | Apache-2.0 | 2023-09-04T14:35:16 | 2020-04-04T10:09:22 | Java | UTF-8 | Java | false | false | 2,004 | java | package org.seasar.doma.gradle.codegen.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import org.seasar.doma.gradle.codegen.exception.CodeGenException;
import org.seasar.doma.gradle.codegen.message.Message;
public final class ResourceUtil {
public static URL getResource(String path) {
AssertionUtil.assertNotNull(path);
URL result = ResourceUtil.class.getResource("/" + path);
if (result != null) {
return result;
}
ClassLoader loader = Thread.currentThread().getContextClassLoader();
if (loader == null) {
return null;
}
return loader.getResource(path);
}
public static InputStream getResourceAsStream(String path) {
AssertionUtil.assertNotNull(path);
URL url = getResource(path);
try {
return url != null ? url.openStream() : null;
} catch (IOException e) {
return null;
}
}
public static String getResourceAsString(String path) {
AssertionUtil.assertNotNull(path);
AssertionUtil.assertTrue(path.length() > 0);
InputStream inputStream = getResourceAsStream(path);
if (inputStream == null) {
return null;
}
return IOUtil.readAsString(inputStream);
}
public static File getResourceAsFile(String path) {
AssertionUtil.assertNotNull(path);
URL url = getResource(path);
if (url == null) {
return null;
}
return getFile(url);
}
protected static File getFile(URL url) {
AssertionUtil.assertNotNull(url);
File file = new File(getFileName(url));
if (file.exists()) {
return file;
}
return null;
}
protected static String getFileName(URL url) {
AssertionUtil.assertNotNull(url);
String s = url.getFile();
try {
return URLDecoder.decode(s, "UTF-8");
} catch (final UnsupportedEncodingException e) {
throw new CodeGenException(Message.DOMAGEN9001, e, e);
}
}
}
| [
"toshihiro.nakamura@gmail.com"
] | toshihiro.nakamura@gmail.com |
62c4cacb201abdb7ac1f7e109986de2be88a5019 | c3396b249163c8abca698488d5c2cfead221cdf1 | /spring-boot/src/main/java/br/com/vvezani/listavip/model/Convidado.java | 684f2e2430acbf9b8a9ddffc69c1079d34710513 | [] | no_license | vitorvezani/alura-projects | d4e4b9414ca78c01a0385133fab67a7058bb32c1 | fdcde11eb8dd03000f3eb515e16bc9426ca3381f | refs/heads/master | 2020-03-12T19:01:08.364871 | 2018-04-24T00:43:37 | 2018-04-24T00:43:37 | 80,059,974 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 892 | java | package br.com.vvezani.listavip.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity(name = "convidado")
public class Convidado {
@Id
@GeneratedValue
private Long id;
private String nome;
private String email;
private String telefone;
public Convidado(String nome, String email, String telefone) {
this.nome = nome;
this.email = email;
this.telefone = telefone;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
}
| [
"vitor.vezani@gmail.com"
] | vitor.vezani@gmail.com |
d6894c3dde4ea3e64768517490c1e92a36974723 | 717b8038e8a7bfe38bd76eaee539a91b6b4d1af0 | /app/src/main/java/com/example/leehyehyun/myapplication/MainActivity.java | b6a14dbe0993f57fff828c772000a9865b32b441 | [] | no_license | leehyehyun/MyFitness-Android | 37285988739a0141b58587437c7ee13b64c371b4 | a05cee4b00a2ade17a23f82534cfb8409be4f1a4 | refs/heads/master | 2020-04-13T03:29:31.570097 | 2019-01-05T05:02:26 | 2019-01-05T05:02:26 | 162,933,384 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,769 | java | package com.example.leehyehyun.myapplication;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.Serializable;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final int ADDED_CHALLENGE = 126;
private ListView list_view;
private TextView btnDelete;
private MainListAdapter mainListAdapter;
private ArrayList<Challenge> arrChallenge;
// private ArrayList<WorkOut> arrSelectedWorkout;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu2, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_more:
return true;
case R.id.workout_start:
if(mainListAdapter.getSelectedChallenges().size() == 0){
Toast.makeText(MainActivity.this, "챌린지를 선택해주세요.", Toast.LENGTH_SHORT).show();
return true;
}
Intent intent = new Intent(MainActivity.this, WorkOutListActivity.class);
Bundle args = new Bundle();
args.putSerializable("arr_workout_list", getWorkouts_ofSelectedChallenge());
intent.putExtra("bundle",args);
startActivity(intent);
// finish();
return true;
case R.id.add_challenge:
Intent intent2 = new Intent(MainActivity.this, AddChallengeActivity.class);
startActivityForResult(intent2, ADDED_CHALLENGE);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list_view = findViewById(R.id.list_view);
btnDelete = findViewById(R.id.btn_delete);
mainListAdapter = new MainListAdapter();
showChallengeList();
if(GlobalValue.isAdmin){
btnDelete.setVisibility(View.VISIBLE);
}else{
btnDelete.setVisibility(View.GONE);
}
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DBHelper mDBHelper = DBHelper.getInstance(getApplicationContext());
mDBHelper.deleteChallenge(mainListAdapter.getSelectedChallenges());
showChallengeList();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == ADDED_CHALLENGE && resultCode == RESULT_OK && data != null){
String challengeName = data.getStringExtra("challenge_name");
ArrayList<WorkOut> arrWorkout = (ArrayList<WorkOut>)data.getSerializableExtra("arr_workout");
// db에 추가하려는 챌린지 정보 넣기
addChallenge_inDB(challengeName, arrWorkout);
// 챌린지 리스트 갱신
showChallengeList();
}
}
private void addChallenge_inDB(String challengeName, ArrayList<WorkOut> arrWorkOut){
DBHelper mDBHelper = DBHelper.getInstance(getApplicationContext());
// challenge 테이블에 먼저 챌린지 추가하기
mDBHelper.insertChallenge(challengeName);
// challenge 테이블에 마지막 추가된 챌린지id 읽어오기
int challenge_id = mDBHelper.getLastInsertId_challengeTable();
Log.v("is-", "challenge table last insert id : "+challenge_id);
// workout 테이블에 운동이름, 이미지경로, 챌린지id 넣어서 추가하기
mDBHelper.insertWorkout(arrWorkOut, challenge_id);
}
private void getChallenge_inDB(){
DBHelper mDBHelper = DBHelper.getInstance(getApplicationContext());
arrChallenge = mDBHelper.getArrChallenge();
}
private void showChallengeList(){
// 초기화 (챌린지 추가시, 중복으로 추가됨 방지)
mainListAdapter.clearArrChallenge();
// db에 저장된 챌린지 가져와서 리스트에 노출시키기
getChallenge_inDB();
mainListAdapter.setChallengeList(arrChallenge);
list_view.setAdapter(mainListAdapter);
}
// 선택된 챌린지에 해당하는 workout 을 array에 넣기
private ArrayList<WorkOut> getWorkouts_ofSelectedChallenge(){
ArrayList<WorkOut> arrSelectedWorkout = new ArrayList<>();
ArrayList<Challenge> arrSelectedChallenge = mainListAdapter.getSelectedChallenges();
for (int i = 0 ; i < arrSelectedChallenge.size() ; i++){
arrSelectedWorkout.addAll(arrSelectedChallenge.get(i).getArrWorkOut());
}
return arrSelectedWorkout;
}
@Override
protected void onPause() {
super.onPause();
unselectedList();
}
private void unselectedList(){
mainListAdapter.clearSelectedChallenges();
for(int i = 0 ; i < mainListAdapter.getCount() ; i++){
mainListAdapter.getItem(i).setChecked(false);
}
mainListAdapter.notifyDataSetChanged();
}
}
| [
"hyehyun6403@naver.com"
] | hyehyun6403@naver.com |
b93b9ff03d4c41e713cdfc5f0932dc3aeebc5577 | 22a1fc5089f79bea8a222d24b1dba17bb4539ec1 | /src/main/java/com/imoooc/controller/SellerOrderController.java | 0f5388ff4cd6762303f2e8944e0228543c3e917e | [] | no_license | liuchunbo24/springboot-wechat | e47a974c8b1e795117430ddbeb4914215c97e1ee | f6c0915f30fd09f215913e821f7e6dbf782e6d30 | refs/heads/master | 2020-07-03T00:39:44.851153 | 2019-08-13T09:20:03 | 2019-08-13T09:20:03 | 201,728,715 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,860 | java | package com.imoooc.controller;
import com.imoooc.dto.OrderDTO;
import com.imoooc.enums.ResultEnum;
import com.imoooc.exception.SellException;
import com.imoooc.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
/**
* 卖家端订单
* Created by LCB
* 2019/7/7 13:57
*/
@Controller
@RequestMapping("/seller/order")
@Slf4j
public class SellerOrderController {
@Autowired
private OrderService orderService;
/**
* 订单列表
* @param page 第几页 ,从1页开始
* @param size 一页有多少人条数据
* @return
*/
@GetMapping("/list")
public ModelAndView list(@RequestParam(value = "page",defaultValue = "1") Integer page,
@RequestParam(value = "size",defaultValue = "10") Integer size,
Map<String,Object> map){
PageRequest request=new PageRequest(page-1,size);
Page<OrderDTO> orderDTOPage=orderService.findList(request);
map.put("orderDTOPage",orderDTOPage);
map.put("currentPage",page);
map.put("size",size);
return new ModelAndView("order/list",map);
}
/**
* 取消订单
* @param orderId
* @return
*/
@GetMapping("/cancel")
public ModelAndView cancel(@RequestParam("orderId") String orderId,
Map<String ,Object> map){
try {
OrderDTO orderDTO = orderService.findOne(orderId);
orderService.cancel(orderDTO);
}catch (SellException e){
log.error("【卖家端取消订单】发生异常{}",e);
map.put("msg", e.getMessage());
map.put("url", "/sell/seller/order/list");
return new ModelAndView("common/error", map);
}
map.put("msg", ResultEnum.ODERR_CANCEL_SUCCESS.getMessage());
map.put("url", "/sell/seller/order/list");
return new ModelAndView("common/success");
}
/**
* 订单详情
* @param orderId
* @param map
* @return
*/
@GetMapping("/detail")
public ModelAndView detail(@RequestParam("orderId") String orderId,
Map<String ,Object> map){
OrderDTO orderDTO=new OrderDTO();
try{
orderDTO=orderService.findOne(orderId);
}catch (SellException e){
log.error("【卖家端订单详情】发生异常{}",e);
map.put("msg", e.getMessage());
map.put("url", "/sell/seller/order/list");
return new ModelAndView("common/error", map);
}
map.put("orderDTO",orderDTO);
return new ModelAndView("order/detail", map);
}
@GetMapping("/finsh")
public ModelAndView finshed(@RequestParam("orderId") String orderId,
Map<String ,Object> map){
try {
OrderDTO orderDTO = orderService.findOne(orderId);
orderService.finish(orderDTO);
}catch (SellException e){
log.error("【卖家端完结订单】发生异常{}",e);
map.put("msg", e.getMessage());
map.put("url", "/sell/seller/order/list");
return new ModelAndView("common/error", map);
}
map.put("msg", ResultEnum.ODERR_FINSH_SUCCESS.getMessage());
map.put("url", "/sell/seller/order/list");
return new ModelAndView("common/success", map);
}
}
| [
"980168687@qq.com"
] | 980168687@qq.com |
6e5ae4f4bd9366171040a11c20d90ee1bd847787 | c474b03758be154e43758220e47b3403eb7fc1fc | /apk/decompiled/com.tinder_2018-07-26_source_from_JADX/sources/com/tinder/data/meta/p226a/C12968h.java | 0bc3779e74fa36e5df5c734a4021073d382bb1e3 | [] | no_license | EstebanDalelR/tinderAnalysis | f80fe1f43b3b9dba283b5db1781189a0dd592c24 | 941e2c634c40e5dbf5585c6876ef33f2a578b65c | refs/heads/master | 2020-04-04T09:03:32.659099 | 2018-11-23T20:41:28 | 2018-11-23T20:41:28 | 155,805,042 | 0 | 0 | null | 2018-11-18T16:02:45 | 2018-11-02T02:44:34 | null | UTF-8 | Java | false | false | 627 | java | package com.tinder.data.meta.p226a;
import dagger.internal.Factory;
/* renamed from: com.tinder.data.meta.a.h */
public final class C12968h implements Factory<C10846g> {
/* renamed from: a */
private static final C12968h f41532a = new C12968h();
public /* synthetic */ Object get() {
return m50712a();
}
/* renamed from: a */
public C10846g m50712a() {
return C12968h.m50710b();
}
/* renamed from: b */
public static C10846g m50710b() {
return new C10846g();
}
/* renamed from: c */
public static C12968h m50711c() {
return f41532a;
}
}
| [
"jdguzmans@hotmail.com"
] | jdguzmans@hotmail.com |
026b465c37239070d1847f5b48e30976a4662beb | 18c70f2a4f73a9db9975280a545066c9e4d9898e | /mirror-composite/composite-api/src/main/java/com/aspire/mirror/composite/service/cmdb/index/ItCloudScreenValidateAPI.java | 72865916ec17c3af647a258b94c6c8f4f90817cf | [] | no_license | iu28igvc9o0/cmdb_aspire | 1fe5d8607fdacc436b8a733f0ea44446f431dfa8 | 793eb6344c4468fe4c61c230df51fc44f7d8357b | refs/heads/master | 2023-08-11T03:54:45.820508 | 2021-09-18T01:47:25 | 2021-09-18T01:47:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,855 | java | package com.aspire.mirror.composite.service.cmdb.index;
import com.alibaba.fastjson.JSONObject;
import com.aspire.ums.cmdb.index.payload.ItCloudScreenExportRequest;
import com.aspire.ums.cmdb.index.payload.ItCloudScreenValidateRequest;
import com.aspire.ums.cmdb.index.payload.ScreenValidate;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
/**
* @ClassName ItCloudScreenValidateAPI
* @Description 大屏数据校验对外暴露的接口层
* @Author luowenbo
* @Date 2020/5/6 17:21
* @Version 1.0
*/
@RequestMapping("${version}/cmdb/index/overview")
public interface ItCloudScreenValidateAPI {
/*
* 验证数据完整性和准确性
* */
@RequestMapping(value = "/validate", method = RequestMethod.POST)
@ApiOperation(value = "验证数据完整性和准确性", notes = "验证数据完整性和准确性", tags = {"CMDB Index Overview API"})
@ApiResponses(value = {@ApiResponse(code = 200, message = "查询成功", response = JSONObject.class),
@ApiResponse(code = 500, message = "内部错误")})
JSONObject validate(@RequestBody ItCloudScreenValidateRequest req);
/*
* 查询,按照新增时间列出前5条
* */
@RequestMapping(value = "/validate/list", method = RequestMethod.POST)
@ApiOperation(value = "查询,按照新增时间列出前5条", notes = "查询,按照新增时间列出前5条", tags = {"CMDB Index Overview API"})
@ApiResponses(value = {@ApiResponse(code = 200, message = "查询成功", response = List.class),
@ApiResponse(code = 500, message = "内部错误")})
List<ScreenValidate> listAll();
/*
* 导出数据的生成
* */
@RequestMapping(value = "/excel/create", method = RequestMethod.POST)
@ApiOperation(value = "导出数据的生成", notes = "导出数据的生成", tags = {"CMDB Index Overview API"})
@ApiResponses(value = {@ApiResponse(code = 200, message = "查询成功", response = List.class),
@ApiResponse(code = 500, message = "内部错误")})
JSONObject createExcel(@RequestBody ItCloudScreenExportRequest req);
/*
* 数据下载
* */
@RequestMapping(value = "/excel/export", method = RequestMethod.POST)
@ApiOperation(value = "数据下载", notes = "数据下载", tags = {"CMDB Index Overview API"})
@ApiResponses(value = {@ApiResponse(code = 200, message = "查询成功", response = List.class),
@ApiResponse(code = 500, message = "内部错误")})
JSONObject exportExcel(@RequestBody ItCloudScreenExportRequest req);
}
| [
"jiangxuwen7515@163.com"
] | jiangxuwen7515@163.com |
0315a7fd6b29e50dae42b68efbacb37f14ed2eaa | ce11afab8fddca1fbde7d28c0b5ff6d30709038e | /src/com/kilotrees/dao/advtodayresultdao.java | 4dcbb97e257eeb2fcbbd8d3bdaa5f8d55ba9dcce | [] | no_license | LT877677447/CloudContrl | 92ae6144b58396ac3f9f72b9b2bc9d906d809b76 | 14272d96a6e80b6f2e3dba881c425a9742d53138 | refs/heads/master | 2020-05-20T20:14:47.117382 | 2019-10-24T16:28:20 | 2019-10-24T16:28:20 | 185,739,586 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,010 | java | package com.kilotrees.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import com.kilotrees.model.po.advtodayresult;
import com.kilotrees.services.ErrorLog_service;
public class advtodayresultdao {
private static Logger log = Logger.getLogger(advtodayresultdao.class);
/**select * from tb_advtodayresult where datediff(dd,result_time,getdate()) = 0
* 服务启动时需要把今天所有执行结果信息收集起来,这个表作为中间表,方便后台查询,在服务器重启时计算新增还有多少没有完成,
* 这里没有统计广告每个设备打开次数,对于每个广告第天打开次数,实际上可以通过新增和留存日志表查到每天任务执行情况
* .
* @return
*/
public static synchronized HashMap<String,advtodayresult> getAdvTodayResultSet()
{
HashMap<String,advtodayresult> list = new HashMap<String,advtodayresult>();
String sql = "select * from tb_advtodayresult where datediff(dd,result_time,getdate()) = 0";
Connection con = connectionmgr.getInstance().getConnection();
PreparedStatement ps = null;
try{
ps = con.prepareStatement(sql);
//String todayStr = DateUtil.getDateBeginString(new java.util.Date());
//ps.setString(1, todayStr);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
advtodayresult ar = new advtodayresult();
ar.setTid(rs.getInt("tid"));
ar.setAdvid(rs.getInt("advid"));
ar.setIsremain(rs.getInt("isremain"));
ar.setNewuser_success_count(rs.getInt("newuser_success_count"));
ar.setNewuser_err_count(rs.getInt("newuser_err_count"));
ar.setNewuser_success_opentcount(rs.getInt("newuser_success_opentcount"));
ar.setNewuser_err_opentcount(rs.getInt("newuser_err_opentcount"));
//
ar.setRemain_olduser_success_count(rs.getInt("remain_olduser_success_count"));
ar.setRemain_newuser_success_count(rs.getInt("remain_newuser_success_count"));
ar.setRemain_olduser_success_opentcount(rs.getInt("remain_olduser_success_opentcount"));
ar.setRemain_newuser_success_opentcount(rs.getInt("remain_newuser_success_opentcount"));
ar.setRemain_err_opentcount(rs.getInt("remain_err_opentcount"));
java.util.Date d = new java.util.Date(rs.getTimestamp("result_time").getTime());
ar.setResult_time(d);
list.put(ar.getKey(),ar);
}
rs.close();
}catch(Exception e)
{
ErrorLog_service.system_errlog(e);
log.error(e.getMessage(),e);
}
finally
{
connectionmgr.getInstance().closeConnection(con,ps);
}
return list;
}
/**
* 这里可能有每天跨度问题,这里由服务器控制好时间逻辑
*/
public static synchronized void updateAdvTodayResult(advtodayresult rs)
{
Connection con = connectionmgr.getInstance().getConnection();
String sql = "update tb_advtodayresult set "
+ "newuser_success_count=?,newuser_err_count=?,newuser_success_opentcount=?,"
+ "newuser_err_opentcount=?,remain_olduser_success_count=?,remain_newuser_success_count=?,"
+ "remain_olduser_success_opentcount=?,remain_newuser_success_opentcount=?,remain_err_opentcount=?,"
+ "result_time=? "
+ "where tid=?";
//log.info(sql);
PreparedStatement ps = null;
try{
ps = con.prepareStatement(sql);
ps.setInt(1, rs.getNewuser_success_count());
ps.setInt(2, rs.getNewuser_err_count());
ps.setInt(3, rs.getNewuser_success_opentcount());
ps.setInt(4, rs.getNewuser_err_opentcount());
//
ps.setInt(5, rs.getRemain_olduser_success_count());
ps.setInt(6, rs.getRemain_newuser_success_count());
ps.setInt(7, rs.getRemain_olduser_success_opentcount());
ps.setInt(8, rs.getRemain_newuser_success_opentcount());
ps.setInt(9, rs.getRemain_err_opentcount());
java.sql.Timestamp t = new java.sql.Timestamp(rs.getResult_time().getTime());
ps.setTimestamp(10, t);
ps.setInt(11, rs.getTid());
//ps.get
ps.execute();
}catch(Exception e)
{
ErrorLog_service.system_errlog(e);
log.error(e.getMessage(),e);
}
finally
{
connectionmgr.getInstance().closeConnection(con,ps);
}
}
public static synchronized void newAdvTodayResult(advtodayresult ar)
{
Connection con = connectionmgr.getInstance().getConnection();
String sql = "insert into tb_advtodayresult values(?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement ps = null;
try{
ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
ps.setInt(1, (int)ar.getAdvid());
ps.setInt(2, (int)ar.getIsremain());
ps.setInt(3, ar.getNewuser_success_count());
ps.setInt(4, ar.getNewuser_err_count());
ps.setInt(5, ar.getNewuser_success_opentcount());
ps.setInt(6, ar.getNewuser_err_opentcount());
//
ps.setInt(7, ar.getRemain_olduser_success_count());
ps.setInt(8, ar.getRemain_newuser_success_count());
ps.setInt(9, ar.getRemain_olduser_success_opentcount());
ps.setInt(10, ar.getRemain_newuser_success_opentcount());
ps.setInt(11, ar.getRemain_err_opentcount());
java.sql.Timestamp t = new java.sql.Timestamp(ar.getResult_time().getTime());
ps.setTimestamp(12, t);
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if(rs.next())
ar.setTid(rs.getInt(1));
rs.close();
}catch(Exception e)
{
ErrorLog_service.system_errlog(e);
e.printStackTrace();
}
finally
{
connectionmgr.getInstance().closeConnection(con,ps);
}
}
public static void main(String[] argvs)
{
HashMap<Integer,String> h = new HashMap<Integer,String>();
h.put(1, "s1");
h.put(3, "s3");
h.put(4, "s4");
h.put(2, "s2");
List<String> sl = new ArrayList<String>();
sl.addAll(h.values());
for(int i = 0; i < sl.size(); i++)
System.out.println(sl.get(i));
System.out.println("----");
for(String s : h.values())
System.out.println(s);
//System.out.println(udate.toString());
}
}
| [
"877677447@qq.com"
] | 877677447@qq.com |
8122c7160902b0faeaac887533b2f2087259a397 | 23e74f033a0a8a74fb818f358d9490b05b67fb03 | /src/br/com/mpssolutions/bookmarkapp/backgroundjobs/WebPageDownloaderTask.java | b254515b89d60cbcc0e57ddfae3709076ff0367a | [
"MIT"
] | permissive | Mathsphysis/bookmarks-app | a1df01fe8c66d269600e97e841974f46765e1189 | dedfcbdee65e715b8f3e9b56a4c4406ffa232a31 | refs/heads/main | 2023-01-02T01:05:55.504124 | 2020-10-20T07:43:00 | 2020-10-20T07:43:00 | 303,154,055 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,596 | java | package br.com.mpssolutions.bookmarkapp.backgroundjobs;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import br.com.mpssolutions.bookmarkapp.dao.BookmarkDao;
import br.com.mpssolutions.bookmarkapp.entities.WebLink;
import br.com.mpssolutions.bookmarkapp.entities.WebLink.DownloadStatus;
import br.com.mpssolutions.bookmarkapp.util.HttpConnect;
import br.com.mpssolutions.bookmarkapp.util.IOUtil;
public class WebPageDownloaderTask implements Runnable {
private static BookmarkDao dao = new BookmarkDao();
private static final long TIME_FRAME = 300000000; // 3 seconds
private boolean downloadAll = false;
ExecutorService downloadExecutor = Executors.newFixedThreadPool(5);
private static class Downloader<T extends WebLink> implements Callable<T> {
private T webLink;
public Downloader(T webLink) {
this.webLink = webLink;
}
public T call() {
try {
if (!webLink.getUrl().endsWith(".pdf")) {
webLink.setDownloadStatus(DownloadStatus.FAILED);
String htmlPage = HttpConnect.download(webLink.getUrl());
webLink.setHtmlPage(htmlPage);
webLink.setDownloadStatus(DownloadStatus.SUCCESS);
} else {
webLink.setDownloadStatus(DownloadStatus.NOT_ELIGIBLE);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return webLink;
}
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
List<WebLink> webLinks = getWebLinks();
if (webLinks.size() > 0) {
download(webLinks);
} else {
System.out.println("No new Web Links to download!");
}
try {
TimeUnit.SECONDS.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
downloadExecutor.shutdown();
}
private void download(List<WebLink> webLinks) {
List<Downloader<WebLink>> tasks = getTasks(webLinks);
List<Future<WebLink>> futures = new ArrayList<>();
try {
futures = downloadExecutor.invokeAll(tasks, TIME_FRAME, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (Future<WebLink> future : futures) {
try {
if (!future.isCancelled()) {
WebLink webLink = future.get();
String webPage = webLink.getHtmlPage();
if (webPage != null) {
IOUtil.write(webPage, webLink.getId());
webLink.setDownloadStatus(WebLink.DownloadStatus.SUCCESS);
System.out.println("Download Success: " + webLink.getUrl());
} else {
System.out.println("Webpage not downloaded!");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
private List<Downloader<WebLink>> getTasks(List<WebLink> webLinks) {
List<Downloader<WebLink>> tasks = new ArrayList<>();
for (WebLink webLink : webLinks) {
tasks.add(new Downloader<WebLink>(webLink));
}
return tasks;
}
private List<WebLink> getWebLinks() {
List<WebLink> webLinks = null;
if (downloadAll) {
webLinks = dao.getAllWebLinks();
downloadAll = false;
} else {
webLinks = dao.getWebLinks(WebLink.DownloadStatus.NOT_ATTEMPTED);
}
return webLinks;
}
public WebPageDownloaderTask(boolean downloadAll) {
this.downloadAll = downloadAll;
}
}
| [
"smathsphysis@gmail.com"
] | smathsphysis@gmail.com |
3d9ff0a8dace731c96f34ea1e17ed710dd0188d4 | 0de3d7b27e4a7df87f8ce2c07357705acb1d01b2 | /java/src/kr/ac/kopo/day05/HandPhone.java | 369f6b5b8eac5397a193b0de1499e17a527e14ce | [] | no_license | kimhyeju-a/kopo_java | 1192c398d947e4791fd420cd210f79de19e510a9 | 9081c78d6c68ba665b4c39952ad2fe635fd6f75e | refs/heads/master | 2021-06-12T20:51:38.348563 | 2020-06-11T15:00:30 | 2020-06-11T15:00:30 | 254,394,400 | 0 | 0 | null | 2020-05-21T00:22:13 | 2020-04-09T14:29:42 | Java | UTF-8 | Java | false | false | 104 | java | package kr.ac.kopo.day05;
public class HandPhone {
String phone;
String name;
String company;
}
| [
"hyeju.aa@gmail.com"
] | hyeju.aa@gmail.com |
4d740724791f2589e793b214c99b0bdedc977403 | 2dbb7d55055b5165435e252ecb4fb79e428cf9ec | /app/src/main/java/com/android/mig/mjsongs/models/Song.java | 4967e2a8239d97b797c99cd4998203cb8b992249 | [] | no_license | msaenz424/MJ-Songs | 290b34a2bbe38c446f58270452b77e8d48bfa572 | e3429ff41f8e5d5047b8e5318e9885d2d9268cc0 | refs/heads/master | 2021-07-18T00:01:59.354161 | 2017-07-28T19:15:49 | 2017-07-28T19:15:49 | 108,619,148 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,230 | java | package com.android.mig.mjsongs.models;
import android.os.Parcel;
import android.os.Parcelable;
public class Song implements Parcelable{
private String mCollectionName;
private String mTrackName;
private String mPreviewUrl;
private String mArtworkUrl;
private double mTrackPrice;
private String mReleaseDate;
private String mPrimaryGenreName;
public Song(String collectionName, String trackName, String previewUrl, String artworkUrl, double trackPrice, String releaseDate, String primaryGenreName ){
this.mCollectionName = collectionName;
this.mTrackName = trackName;
this.mPreviewUrl = previewUrl;
this.mArtworkUrl = artworkUrl;
this.mPreviewUrl = previewUrl;
this.mArtworkUrl = artworkUrl;
this.mTrackPrice = trackPrice;
this.mReleaseDate = releaseDate;
this.mPrimaryGenreName = primaryGenreName;
}
protected Song(Parcel in) {
mCollectionName = in.readString();
mTrackName = in.readString();
mPreviewUrl = in.readString();
mArtworkUrl = in.readString();
mTrackPrice = in.readDouble();
mReleaseDate = in.readString();
mPrimaryGenreName = in.readString();
}
public static final Creator<Song> CREATOR = new Creator<Song>() {
@Override
public Song createFromParcel(Parcel in) {
return new Song(in);
}
@Override
public Song[] newArray(int size) {
return new Song[size];
}
};
public String getCollectionName() {
return mCollectionName;
}
public void setCollectionName(String mCollectionName) {
this.mCollectionName = mCollectionName;
}
public String getTrackName() {
return mTrackName;
}
public void setTrackName(String mTrackName) {
this.mTrackName = mTrackName;
}
public String getPreviewUrl() {
return mPreviewUrl;
}
public void setPreviewUrl(String mPreviewUrl) {
this.mPreviewUrl = mPreviewUrl;
}
public String getArtworkUrl() {
return mArtworkUrl;
}
public void setArtworkUrl(String mArtworkUrl) {
this.mArtworkUrl = mArtworkUrl;
}
public double getTrackPrice() {
return mTrackPrice;
}
public void setTrackPrice(double mTrackPrice) {
this.mTrackPrice = mTrackPrice;
}
public String getReleaseDate() {
return mReleaseDate;
}
public void setReleaseDate(String mReleaseDate) {
this.mReleaseDate = mReleaseDate;
}
public String getPrimaryGenreName() {
return mPrimaryGenreName;
}
public void setPrimaryGenreName(String mPrimaryGenreName) {
this.mPrimaryGenreName = mPrimaryGenreName;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(mCollectionName);
parcel.writeString(mTrackName);
parcel.writeString(mPreviewUrl);
parcel.writeString(mArtworkUrl);
parcel.writeDouble(mTrackPrice);
parcel.writeString(mReleaseDate);
parcel.writeString(mPrimaryGenreName);
}
}
| [
"msaenz424@gmail.com"
] | msaenz424@gmail.com |
8c5869aa0f8a941598d5ffb2a5ea14aa7af8e89a | a9a221b42922ec3f77fc5d565ffbbf3e87d662ed | /src/Practice_03_10_2021/MovieDuration.java | 11f363196fdb6d209fcd537f3c3c793ad5bb6a79 | [] | no_license | Sabinacunningham/java-programming | 30d87525ec45ced934bc4f42ec2ede2abd15c241 | 4ca872dba9f80ec8af97d299db58ff6a1fba3ca0 | refs/heads/master | 2023-05-06T23:58:04.920088 | 2021-06-02T19:58:27 | 2021-06-02T19:58:27 | 373,280,941 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 560 | java | package Practice_03_10_2021;
import java.util.Scanner;
public class MovieDuration {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Next the length of the movie");
double movieLength = input.nextDouble();
double price = 0;
if (movieLength ==1) {
price = 8.99;
System.out.println("Price: " + price);
if (movieLength == 1.5) {
price = 10.50;
System.out.println("price = " + price);
}
}
}
}
| [
"isakeevas@gmail.com"
] | isakeevas@gmail.com |
ead24deabafce025c797686b62d8c3e7d0efa8f3 | f54a38426da718c184ef680706b9cd2141ad6b98 | /app/src/main/java/com/globe3/tno/g3_lite_mobile/utils/BitmapUtility.java | 86cc9e40ace42f6fe07581f5cadeadf4b2110b19 | [] | no_license | Globe3HuyLV/lite-globe3-mobile-android | a2f257fcdf1274c3d4d7f46de21917844df464e3 | 5303a636900b019d165682cb72173dac6c28cace | refs/heads/master | 2021-01-19T03:42:29.344088 | 2017-03-09T07:11:45 | 2017-03-09T07:11:50 | 84,409,907 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 5,372 | java | package com.globe3.tno.g3_lite_mobile.utils;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.TypedValue;
import com.frosquivel.magicalcamera.MagicalCamera;
import com.frosquivel.magicalcamera.Utilities.ConvertSimpleImage;
import java.io.ByteArrayOutputStream;
public class BitmapUtility {
public static Bitmap decodeBitmap(Resources res, Bitmap bitmap, int dpWidth, int dpHeight) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitmapBytes = stream.toByteArray();
float px_width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpWidth, res.getDisplayMetrics());
float px_height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpHeight, res.getDisplayMetrics());
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length, options);
options.inSampleSize = calculateInSampleSize(options, (int) px_width, (int) px_height);
options.inJustDecodeBounds = false;
Bitmap bitmap_raw = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length, options);
int new_size = bitmap_raw.getWidth() < bitmap_raw.getHeight() ? bitmap_raw.getWidth() : bitmap_raw.getHeight();
Matrix matrix = new Matrix();
if (bitmap_raw.getWidth() > bitmap_raw.getHeight()) {
matrix.postRotate(90);
}
return Bitmap.createBitmap(bitmap_raw, 0, 0, new_size, new_size, matrix, true);
}
public static Bitmap decodeBitmap(Resources res, byte[] bitmapBytes, int dpWidth, int dpHeight) {
float px_width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpWidth, res.getDisplayMetrics());
float px_height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpHeight, res.getDisplayMetrics());
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length, options);
options.inSampleSize = calculateInSampleSize(options, (int) px_width, (int) px_height);
options.inJustDecodeBounds = false;
Bitmap bitmap_raw = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length, options);
int new_size = bitmap_raw.getWidth() < bitmap_raw.getHeight() ? bitmap_raw.getWidth() : bitmap_raw.getHeight();
Matrix matrix = new Matrix();
if (bitmap_raw.getWidth() > bitmap_raw.getHeight()) {
matrix.postRotate(90);
}
return Bitmap.createBitmap(bitmap_raw, 0, 0, new_size, new_size, matrix, true);
}
public static Bitmap decodeBitmap(Resources res, int resId, int dpWidth, int dpHeight) {
float px_width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpWidth, res.getDisplayMetrics());
float px_height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpHeight, res.getDisplayMetrics());
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
options.inSampleSize = calculateInSampleSize(options, (int) px_width, (int) px_height);
options.inJustDecodeBounds = false;
Bitmap bitmap_raw = BitmapFactory.decodeResource(res, resId, options);
int new_size = bitmap_raw.getWidth() < bitmap_raw.getHeight() ? bitmap_raw.getWidth() : bitmap_raw.getHeight();
Matrix matrix = new Matrix();
if (bitmap_raw.getWidth() > bitmap_raw.getHeight()) {
matrix.postRotate(90);
}
return Bitmap.createBitmap(bitmap_raw, 0, 0, new_size, new_size, matrix, true);
}
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static byte[] encodeBitmapToByte(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
return stream.toByteArray();
}
public static Bitmap flipBitmap(Bitmap bitmap) {
Matrix matrix = new Matrix();
matrix.preScale(-1, 1);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
}
public static Bitmap decodeByteToBitMapRotate(byte[] arr) {
Bitmap bitmap = ConvertSimpleImage.bytesToBitmap(arr, MagicalCamera.JPEG);
Matrix matrix = new Matrix();
matrix.postRotate(-90);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
}
}
| [
"vanhuy.le@globe3.com"
] | vanhuy.le@globe3.com |
a3ac56d87a09c210de22131d54ef21e7092f0182 | ee8b4a8e4e9e8688321bd34cd15fed7e281b6ee2 | /app-common/src/main/java/com/eryansky/modules/sys/service/DictionaryService.java | 79bed57379a6ad856d2f29d4f0a1dba304131ce8 | [] | no_license | eryanwcp/ec | 245086ade1242ed22b489d1cbcfada5bf69b17db | 298a0a03d5958f71ad815eed46d6a012871a0ed0 | refs/heads/master | 2023-08-14T06:19:47.354602 | 2023-08-14T01:54:08 | 2023-08-14T01:54:08 | 166,914,136 | 10 | 4 | null | 2023-06-21T00:21:57 | 2019-01-22T02:35:26 | JavaScript | UTF-8 | Java | false | false | 3,446 | java | /**
* Copyright (c) 2012-2022 https://www.eryansky.com
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.eryansky.modules.sys.service;
import com.eryansky.common.orm.Page;
import com.eryansky.common.orm.model.Parameter;
import com.eryansky.common.utils.StringUtils;
import com.eryansky.common.utils.collections.Collections3;
import com.eryansky.core.orm.mybatis.service.CrudService;
import com.eryansky.modules.sys.dao.DictionaryDao;
import com.eryansky.modules.sys.mapper.Dictionary;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 数据字典管理
*
* @author Eryan
* @date 2015-09-27
*/
@Service
public class DictionaryService extends CrudService<DictionaryDao, Dictionary> {
@Override
public void save(Dictionary entity) {
super.save(entity);
}
@Override
public void delete(Dictionary entity) {
super.delete(entity);
}
public void deleteByIds(List<String> ids) {
if (Collections3.isNotEmpty(ids)) {
for (String id : ids) {
delete(new Dictionary(id));
}
}
}
@Override
public Page<Dictionary> findPage(Page<Dictionary> page, Dictionary entity) {
entity.setEntityPage(page);
page.setResult(dao.findList(entity));
return page;
}
/**
* 根据编码查找
*
* @param code
* @return
*/
public Dictionary getByCode(String code) {
if (StringUtils.isBlank(code)) {
return null;
}
code = StringUtils.strip(code);// 去除两边空格
Dictionary dictionary = new Dictionary();
dictionary.setCode(code);
return dao.getByCode(dictionary);
}
/**
* 检查分组下是否有数据
*
* @param groupId
* @param name
* @return
*/
public Dictionary getByGroupCode_Name(String groupId, String name) {
Dictionary group = new Dictionary();
group.setId(groupId);
Dictionary dictionary = new Dictionary();
dictionary.setName(name);
dictionary.setGroup(group);
return dao.getBy(dictionary);
}
/**
* 查找第一级所属有数据
*
* @return
*/
public List<Dictionary> findParents() {
return dao.findParents(new Dictionary());
}
/**
* 根据编码查找子级数据
*
* @param groupId
* @return
*/
public List<Dictionary> findChilds(String groupId) {
Dictionary dictionary = new Dictionary(groupId);
return dao.findChilds(dictionary);
}
/**
* 查找排序最大值
*
* @return
*/
public Integer getMaxSort() {
Integer max = dao.getMaxSort(new Dictionary());
if (max == null) {
max = 0;
}
return max;
}
/**
* 自定义SQL查询
*
* @param whereSQL
* @return
*/
public List<Dictionary> findByWhereSQL(String whereSQL) {
Parameter parameter = Parameter.newParameter();
parameter.put("whereSQL", whereSQL);
return dao.findByWhereSQL(parameter);
}
/**
* 自定义SQL查询
*
* @param sql
* @return
*/
public List<Dictionary> findBySql(String sql) {
Parameter parameter = Parameter.newParameter();
parameter.put("sql", sql);
return dao.findBySql(parameter);
}
}
| [
"eryanwcp@gmail.com"
] | eryanwcp@gmail.com |
6ec484747db6f377d1babf84c5386802e916168f | 25653cbc420b3e108bb12958b94a2a9c55bfa779 | /20210106/src/MyDoubleLinkedList.java | b17ffac15749902628630e00b675f288da24ada1 | [] | no_license | fengchen98/JavaSE | e5ac4bad644ebaf9fbbafb60977d8d9f05a0c7e7 | b4fa709dc0c2f09051fc37f1108fa667e8ecf120 | refs/heads/master | 2023-03-20T08:05:25.893038 | 2021-03-17T15:08:39 | 2021-03-17T15:08:39 | 324,927,846 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,377 | java | /**
* @Author:FC
* @Date:2021/1/8
* @Time:20:29
* @Content:
*/
class ListNode1{
public int val;
public ListNode1 prev;
public ListNode1 next;
public ListNode1(int val) {
this.val = val;
}
}
public class MyDoubleLinkedList {
public ListNode1 head=new ListNode1(-1);
public ListNode1 last;
public void display(){
ListNode1 cur=head.next;
while (cur!=null){
System.out.print(cur.val+" ");
cur=cur.next;
}
System.out.println();
}
public void addFirst(int val){
ListNode1 node=new ListNode1(val);
if (this.head.next==null){
node.prev=head;
head.next=node;
last=node;
return;
}
head.next.prev=node;
node.next=head.next;
head.next=node;
node.prev=head;
}
public void addLast(int val){
ListNode1 node=new ListNode1(val);
if (this.head.next==null){
node.prev=head;
head.next=node;
last=node;
return;
}
last.next=node;
node.prev=last;
last=node;
}
public int size() {
ListNode1 cur = this.head.next;
int count = 0;
while (cur != null) {
count ++;
cur = cur.next;
}
return count;
}
public void addIndex(int index,int val){
ListNode1 node=new ListNode1(val);
if (index<0||index>size()){
return;
}
if (index==0){
addFirst(val);
return;
}
if (index==size()){
addLast(val);
return;
}
ListNode1 cur=head.next;
while (index!=0){
cur=cur.next;
index--;
}
node.next=cur;
node.prev=cur.prev;
node.prev.next=node;
cur.prev=cur;
}
public boolean contains(int key){
ListNode1 cur=this.head.next;
while (cur!=null){
if (cur.val==key){
return true;
}
cur=cur.next;
}
return false;
}
public ListNode1 findNode(int key){
ListNode1 cur=this.head.next;
while (cur!=null){
if (cur.val==key){
return cur;
}
cur=cur.next;
}
return null;
}
public void remove(int key) {
ListNode1 cur = this.head.next;
if (last.val == key) {
last = last.prev;
last.next = null;
return;
}
while (cur.next != null) {
if (cur.val == key) {
cur.prev.next = cur.next;
cur.next.prev = cur.prev;
return;
}
cur = cur.next;
}
}
public void removeAllKey(int key){
ListNode1 cur = this.head.next;
if (last.val == key) {
last = last.prev;
last.next = null;
}
while (cur.next != null) {
if (cur.val == key) {
cur.prev.next = cur.next;
cur.next.prev = cur.prev;
}
cur = cur.next;
}
}
public void clear(){
this.head.next=null;
this.last=null;
}
}
| [
"249841036@qq.com"
] | 249841036@qq.com |
71bbebcdcd6e4943406718e46036637fe431db65 | a3eb2a9b1ae8d52e3cb007ab1efb114994fe610f | /src/test/java/stepdefs/PetTypesStepDefs.java | 36a865c152f1b7def2d593955b45045540a0c1ff | [] | no_license | scarlatam/Final_Homework_Scarlat_AnaMaria | 80cee47c6ed7669e7db9796fa118edb322a5a31c | 090b0678e7e41245a023252bbcff9dfa0f25c959 | refs/heads/master | 2020-04-03T16:09:38.571919 | 2018-11-02T09:22:30 | 2018-11-02T09:22:30 | 155,393,492 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,098 | java | package stepdefs;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class PetTypesStepDefs {
WebDriver webDriver;
private WebElement title;
private WebElement petType;
private WebElement addPet;
private WebElement namePet;
private WebElement savePet;
private WebElement home;
private WebElement updatePet;
@Given("^I open Pet Types page$")
public void iOpenPetTypesPage() {
webDriver = new ChromeDriver();
webDriver.get("http://bhdtest.endava.com/petclinic/welcome");
webDriver.manage().window().maximize();
webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
petType = webDriver.findElement(By.xpath("//a[span][contains(.,'Pet Types')]"));
petType.click();
}
@When("^I perform POST request to pettypes$")
public void iPerformPOSTRequestToPettypes() {
petType = webDriver.findElement(By.xpath("//a[span][contains(.,'Pet Types')]"));
petType.click();
addPet = webDriver.findElement(By.xpath("//button[text()[contains(.,'Add')]]"));
addPet.click();
namePet = webDriver.findElement(By.id("name"));
namePet.sendKeys("Pet 3");
savePet = webDriver.findElement(By.xpath("//button[text()[contains(.,'Save')]]"));
savePet.click();
}
@Then("^I click on Home$")
public void iClickOnHome() throws InterruptedException{
Thread.sleep(1500);
home = webDriver.findElement(By.xpath("//button[text()[contains(.,'Home')]]"));
home.click();
}
@Given("^I am on Pet Type page$")
public void iAmOnPetTypePage() {
webDriver = new ChromeDriver();
webDriver.get("http://bhdtest.endava.com/petclinic/welcome");
webDriver.manage().window().maximize();
webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
petType = webDriver.findElement(By.xpath("//a[span][contains(.,'Pet Types')]"));
petType.click();
}
@When("^I edit the new pet type$")
public void iEditTheNewPetType() {
title = webDriver.findElement(By.xpath("//a[contains(.,'Pet Types')]"));
title.click();
webDriver.get("http://bhdtest.endava.com/petclinic/pettypes/4/edit");
webDriver.findElement(By.id("name")).clear();
webDriver.findElement(By.id("name")).sendKeys("Porumbita");
updatePet = webDriver.findElement(By.xpath("//button[text()[contains(.,'Update')]]"));
updatePet.click();
}
@Then("^I go on Home Page$")
public void iGoOnHomePage() throws InterruptedException{
title = webDriver.findElement(By.xpath("//a[span] [contains(.,'Pet Types')]"));
title.click();
Thread.sleep(1500);
home = webDriver.findElement(By.xpath("//button[text()[contains(.,'Home')]]"));
home.click();
}
}
| [
"scarlat_am@yahoo.com"
] | scarlat_am@yahoo.com |
22825ea2015c6f27431835c623e0e52a13ef1677 | 1335f65d2e5a4493272e9f508a12473c85b9da4c | /test/com/triniforce/server/plugins/kernel/BasicServerCorePluginTest.java | 42b285ea27cb2d5d92af0fe6a7114fd8e962bcde | [] | no_license | ProjectKaiser/tf-server-toolkit | 66d5ef48c737b1340d5b3d5d903156185ec00b3e | 15c121aa9807d4721e3d373d81f6b4b6a6846eca | refs/heads/master | 2023-04-18T08:30:30.663998 | 2023-04-11T13:25:38 | 2023-04-11T13:25:38 | 42,588,018 | 1 | 8 | null | 2022-05-31T13:02:16 | 2015-09-16T13:13:43 | Java | UTF-8 | Java | false | false | 935 | java | /*
* Copyright(C) Triniforce
* All Rights Reserved.
*
*/
package com.triniforce.server.plugins.kernel;
import com.triniforce.db.test.BasicServerTestCase;
import com.triniforce.server.plugins.kernel.ep.srv_ev.PKEPServerEvents;
import com.triniforce.server.srvapi.ITaskExecutors;
import com.triniforce.server.srvapi.IBasicServer.Mode;
import com.triniforce.server.srvapi.ITimedLock2;
import com.triniforce.utils.ApiStack;
public class BasicServerCorePluginTest extends BasicServerTestCase {
@Override
public void test() throws Exception {
//test interfaces
getServer().enterMode(Mode.Running);
try{
ApiStack.getInterface(ITaskExecutors.class);
ApiStack.getInterface(ITimedLock2.class);
getServer().getExtensionPoint(PKEPServerEvents.class);
}finally{
getServer().leaveMode();
}
}
}
| [
"maxim.ge@0957a958-f1c7-11dd-ac65-f74f249cfaac"
] | maxim.ge@0957a958-f1c7-11dd-ac65-f74f249cfaac |
915624c50c523f57dc212c611325f7c03fc42f18 | ccda29ebd3b47cd33e5bc3adb885b4d90631da80 | /Produto/src/Servlet/Cadastro.java | 325b8fd6f33900d93cb445fb1d31345023e4917a | [] | no_license | gabriellacrystina/workspaceWeb | 924591f517c298763c7b314c91bc93ae35cf6526 | 2c172be3f84b52c692e2b05ced4cc0f44015adf6 | refs/heads/master | 2016-09-06T08:07:30.115100 | 2015-09-24T19:46:32 | 2015-09-24T19:46:32 | 42,543,751 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,865 | java | package Servlet;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import PrAula24082015.Produto;
/**
* Servlet implementation class Cadastro
*/
@WebServlet("/Cadastro")
public class Cadastro extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Cadastro() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String aux;
Produto p = new Produto();
HttpSession sessao = request.getSession();
ArrayList<Produto> lista;
lista = (ArrayList<Produto>)sessao.getAttribute("lista");
if(lista == null){
lista = new ArrayList<Produto>();
sessao.setAttribute("lista", lista);
}
aux = request.getParameter("codigo");
p.setCodigo(Integer.parseInt(aux));
aux = request.getParameter("valor");
p.setValor(Double.parseDouble(aux));
aux = request.getParameter("descricao");
p.setDescricao(aux);
aux = request.getParameter("fornecedor");
p.setFornecedor(aux);
lista.add(p);
request.getRequestDispatcher("Cadastro.jsp").forward(request, response);
}
}
| [
"gabriellacrystina@gmail.com"
] | gabriellacrystina@gmail.com |
8509b75af75fd113c60b842ed2d543fceae3f18c | 0c4a69f27b8c6672f831822eb4829e34f5468730 | /src/main/java/lukaur/grant_management_system/app/web/projects/repositories/TaskRepository.java | 38fb702ea7fc41fde722cbf110e8db115d81d9f7 | [] | no_license | LukaUr/Grant_Management_System | b64c547153aac5f6f79b97964ba1734debc14c33 | 3be2a818c319a15ac0b2a06e057b62cae7349a2c | refs/heads/master | 2023-03-19T09:26:53.804117 | 2020-10-05T09:08:16 | 2020-10-05T09:08:16 | 288,548,460 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 342 | java | package lukaur.grant_management_system.app.web.projects.repositories;
import lukaur.grant_management_system.app.web.model.project.timetable.Task;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TaskRepository extends JpaRepository<Task, Long> {
}
| [
"lukau@o2.pl"
] | lukau@o2.pl |
7e4a213722ac67c619ffe71bfe694fa41a60f169 | d3fe19e79066e188ba8fbedc7c9f7c3392b54c40 | /src/seleniumfirst/FirstSafari.java | 1c77c63fb4360fca02c1ead4b21db756f638b980 | [] | no_license | Bir-Eda/SeleniumFirst | 061c881feaec197c375a368edcdfcbda472c6b66 | 673d9ed828d81735172f78a4d2ee7991981ee849 | refs/heads/master | 2023-03-12T14:44:15.379030 | 2021-03-09T04:12:37 | 2021-03-09T04:12:37 | 345,878,326 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 379 | java | package seleniumfirst;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.safari.SafariDriver;
public class FirstSafari {
public static void main(String[] args) {
System.out.println("driver location is:"+System.getProperty("webdriver.safari.driver"));
WebDriver driver1=new SafariDriver();
driver1.get("https://facebook.com");
}
}
| [
"60522150+Bir-Eda@users.noreply.github.com"
] | 60522150+Bir-Eda@users.noreply.github.com |
9088c6183516fd3d6cf73000bb36e35796c95821 | e0f736c789060351fe2b5711d4aaa7eb61a7164b | /src/main/java/org/example/patterns/command/LightOnCommand.java | d1ffb97c66fe577460ec7ee4484233e273b2c13d | [] | no_license | StasGrigoryev/headfirst-patterns | 37e854200dfd76761f5e910a6c7cbdf5d9436818 | b5acb5fcaa469b9598775c8770f86f43f4541d7c | refs/heads/master | 2023-03-10T00:07:52.468980 | 2021-02-25T23:06:46 | 2021-02-25T23:06:46 | 328,373,473 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 260 | java | package org.example.patterns.command;
public class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
}
| [
"stasilius2009@gmail.com"
] | stasilius2009@gmail.com |
7cb99462391d62bfeecfc4242e3da9ff422e1cca | b68b36b74fa20e29fd95b5c8be3e71ba6b4bc7df | /vtnrsc/virtualport/AllowedAddressPairTest.java | d052d74ec7fe9e28368136393a6094d29ea38e51 | [] | no_license | kuangrewawa/vtnrsctest | 6879fd919f0d19bfd681bad2d2dd9153dcdad0ea | 4745047a85809159d1d04ca0dc30d2a0b0c1d2f3 | refs/heads/master | 2021-01-10T08:01:48.103504 | 2015-10-27T11:05:28 | 2015-10-27T11:05:28 | 45,035,107 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,355 | java | /*
* Copyright 2015 Open Networking Laboratory
*
* 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.onosproject.app.vtnrsc.virtualport;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;
import org.junit.Test;
import org.onlab.packet.IpAddress;
import org.onlab.packet.MacAddress;
import org.onosproject.app.vtnrsc.AllowedAddressPair;
import com.google.common.testing.EqualsTester;
/**
* Unit tests for AllowedAddressPair class.
*/
public class AllowedAddressPairTest {
final IpAddress ip1 = IpAddress.valueOf("192.168.0.1");
final IpAddress ip2 = IpAddress.valueOf("192.168.0.2");
final MacAddress mac1 = MacAddress.valueOf("fa:16:3e:76:83:88");
final MacAddress mac2 = MacAddress.valueOf("aa:16:3e:76:83:88");
/**
* Checks that the AllowedAddressPair class is immutable.
*/
@Test
public void testImmutability() {
assertThatClassIsImmutable(AllowedAddressPair.class);
}
/**
* Checks the operation of equals().
*/
@Test
public void testEquals() {
new EqualsTester().addEqualityGroup(AllowedAddressPair.allowedAddressPair(ip1, mac1))
.addEqualityGroup(AllowedAddressPair.allowedAddressPair(ip2, mac2)).testEquals();
}
/**
* Checks the construction of a AllowedAddressPair object.
*/
@Test
public void testConstruction() {
AllowedAddressPair allowedAddressPair = AllowedAddressPair.allowedAddressPair(ip1, mac1);
assertThat(ip1, is(notNullValue()));
assertThat(ip1, is(allowedAddressPair.ip()));
assertThat(mac1, is(notNullValue()));
assertThat(mac1, is(allowedAddressPair.mac()));
}
}
| [
"xuzhang.xuzhang@huawei.com"
] | xuzhang.xuzhang@huawei.com |
88ccd5cef2c8f54a6b5d08bc924322279bd326bf | 7734838ab379f2d7e8afa0fe5deba956f7559b8e | /src/main/java/com/araz/controller/AdminController.java | e4b5f2fc2641d396fca57f35427c0d944e415725 | [] | no_license | Araz1998/deliveryOfGoodsBadalov | 1103494b145606dde35e7e566c69349388a83e78 | 1090436d121152555dfdc69b9b361ecae585543b | refs/heads/master | 2023-03-14T01:59:20.112326 | 2021-03-01T14:52:16 | 2021-03-01T14:52:16 | 340,728,220 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,950 | java | package com.araz.controller;
import com.araz.dao.OrderDAO;
import com.araz.dao.UserDAO;
import com.araz.entity.Order;
import com.araz.service.OrderService;
import com.araz.service.UserService;
import com.araz.util.SendEmail;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* Controller for admin
*
*/
public class AdminController extends HttpServlet {
private OrderDAO orderDAO;
private UserDAO userDAO;
private UserService userService;
private OrderService orderService;
private SendEmail sendEmail;
@Override
public void init() throws ServletException {
orderDAO = new OrderDAO();
orderService = new OrderService(orderDAO);
sendEmail = new SendEmail("email", "passwor");
userDAO = new UserDAO();
userService = new UserService(userDAO);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getServletPath();
try {
switch (action) {
case "/admit":
admitOrder(req, resp);
break;
case "/delete":
deleteOrder(req, resp);
break;
default:
listOrder(req, resp);
break;
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
/**
* This method return list of order from db, by pagination
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
private void listOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String paramPage = req.getParameter("page");
String paramPageSize = req.getParameter("pageSize");
int page = Integer.parseInt(paramPage);
int pageSize = Integer.parseInt(paramPageSize);
List<Order> orderList = orderService.getAllOrdersByLimit(page, pageSize);
int usersNumber = orderService.getOrdersNumber();
int maxPage = (int) Math.ceil((double) usersNumber / pageSize);
req.setAttribute("orderList", orderList);
req.setAttribute("page", page);
req.setAttribute("pageSize", pageSize);
req.setAttribute("maxPage", maxPage);
req.getRequestDispatcher("/view/admin.jsp").forward(req, resp);
}
/**
* This method admit user order by id: send email for user, with code.
* This code is used to pay for the order.
* @param req
* @param resp
* @throws IOException
* @throws ServletException
*/
private void admitOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
int id = Integer.parseInt(req.getParameter("id"));
orderService.admitUserOrder(id);
Order order = orderService.getOrderById(id);
String email = userService.getUserEmail(id);
System.out.println("HASF from ADMIN - " + order.hashCode());
int code = sendEmail.send(order, email);
orderService.insertCodeToOrder(code, id);
resp.sendRedirect("/admin?pageSize=2&page=1");
}
/**
* This method delete order by order's id
* @param req
* @param resp
* @throws IOException
*/
private void deleteOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException {
int id = Integer.parseInt(req.getParameter("id"));
orderService.deleteOrder(id);
resp.sendRedirect("/admin?pageSize=2&page=1");
}
}
| [
"33088732+Araz1998@users.noreply.github.com"
] | 33088732+Araz1998@users.noreply.github.com |
5881982c472580eaf247122ee93c1d854fa63336 | c765561286c370c43df5b5634714a851e77cc92f | /smoothchart/src/main/java/com/hymane/smoothchart/DensityUtils.java | 880d57d513bb3d4d86627712d3a9890fae2d7e55 | [
"Apache-2.0"
] | permissive | hymanme/SmoothChartView | b6774a79541ccb394de166733411bffd98d03bee | 2ff4333dbbad663d8bf23efd821b2e18fd3ce131 | refs/heads/master | 2021-01-19T10:34:12.667767 | 2017-04-11T02:19:06 | 2017-04-11T02:19:06 | 87,876,665 | 18 | 3 | null | null | null | null | UTF-8 | Java | false | false | 1,511 | java | package com.hymane.smoothchart;
import android.content.Context;
import android.util.TypedValue;
/**
* Author :hymanme
* Email :hymanme@163.com
* Create at 2016/3/7 0007
* Description:
*/
public class DensityUtils {
private DensityUtils() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* dp转px
*
* @param context
* @param dpVal
* @return
*/
public static int dp2px(Context context, float dpVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpVal, context.getResources().getDisplayMetrics());
}
/**
* sp转px
*
* @param context
* @param spVal
* @return
*/
public static int sp2px(Context context, float spVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spVal, context.getResources().getDisplayMetrics());
}
/**
* px转dp
*
* @param context
* @param pxVal
* @return
*/
public static float px2dp(Context context, float pxVal) {
final float scale = context.getResources().getDisplayMetrics().density;
return (pxVal / scale);
}
/**
* px转sp
*
* @param context
* @param pxVal
* @return
*/
public static float px2sp(Context context, float pxVal) {
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}
}
| [
"hymanme@163.com"
] | hymanme@163.com |
19a0ab52569d052982daec194719e193f866cfc9 | f4eaf2e121bc6238c16a788767f4836505f954b0 | /src/java/edu/psu/citeseerx/loaders/ExternalMetadataLoader.java | fc8cb1e3173ef2d264d02b81b3aa2cda1f5a7015 | [
"Apache-2.0"
] | permissive | SeerLabs/CiteSeerX | 5abd92bb16e0275ef3a91c29790c59ea04527e4d | 49ecb503fb1ced8e2c2e94c3e100e5d4dc410ea6 | refs/heads/master | 2021-04-12T03:53:59.996465 | 2019-11-25T18:29:20 | 2019-11-25T18:29:20 | 11,351,492 | 114 | 53 | NOASSERTION | 2019-11-25T18:29:21 | 2013-07-11T19:51:28 | HTML | UTF-8 | Java | false | false | 1,987 | java | /*
* Copyright 2007 Penn State University
* 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 edu.psu.citeseerx.loaders;
import java.io.IOException;
import org.springframework.beans.factory.ListableBeanFactory;
import edu.psu.citeseerx.updates.external.metadata.ACMMetadataUpdater;
import edu.psu.citeseerx.updates.external.metadata.CiteulikeMetadataUpdater;
import edu.psu.citeseerx.updates.external.metadata.DBLPMetadataUpdater;
/**
* Loads the MetadataUpdaters in order to update the custom copy of external
* metadata.
* Currently, it handles DBLP and CiteULike
* @author Juan Pablo Fernandez Ramirez
* @version $Rev$ $Date$
*/
public class ExternalMetadataLoader {
/**
* @param args
*/
public static void main(String[] args) throws IOException {
ListableBeanFactory factory = ContextReader.loadContext();
DBLPMetadataUpdater dblpUpdater =
(DBLPMetadataUpdater)factory.getBean("dblpUpdateManager");
CiteulikeMetadataUpdater citeulikeUpdater =
(CiteulikeMetadataUpdater)factory.getBean("citeulikeUpdateManager");
ACMMetadataUpdater acmUpdater =
(ACMMetadataUpdater)factory.getBean("acmUpdateManager");
try {
dblpUpdater.updateDBLP();
citeulikeUpdater.updateCiteulike();
acmUpdater.updateACM();
} catch (Exception e) {
e.printStackTrace();
}
} //- main
} //- class DBLPExternalMetaDataLoader
| [
"kwilliams@psu.edu"
] | kwilliams@psu.edu |
5678ebad735bc7c0545b66a34afc4b0aeaf70417 | efcc816fbe01d84a3bc9388955cc8adcb317e4bf | /common/src/main/java/com/zzh/userstate/impl/RedisUserStatusServiceImpl.java | e892077e23c257199e0eb1825459a3aa294aeab4 | [] | no_license | zhedouyourenyong/IM | c2447053afd01ff1f8d514e942afbccbc790067a | bb5cedd195f4cbaea108ca2c3f83cecab8427f4b | refs/heads/master | 2022-10-10T22:57:12.105099 | 2020-02-22T12:55:20 | 2020-02-22T12:55:20 | 229,436,894 | 1 | 0 | null | 2022-10-04T23:55:04 | 2019-12-21T14:11:44 | Java | UTF-8 | Java | false | false | 1,558 | java | package com.zzh.userstate.impl;
import com.zzh.constant.RedisKey;
import com.zzh.userstate.UserStatusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Objects;
@Slf4j
@Service
public class RedisUserStatusServiceImpl implements UserStatusService
{
private StringRedisTemplate redisTemplate;
@Autowired
public RedisUserStatusServiceImpl(StringRedisTemplate redisTemplate)
{
this.redisTemplate = redisTemplate;
}
@Override
public Long saveUserLoginStatus(String userId)
{
try
{
return redisTemplate.opsForSet().add(RedisKey.LOGIN_STATUS_PREFIX, userId);
} catch (Exception e)
{
log.error(e.getMessage(), e);
return null;
}
}
@Override
public Boolean checkUserLoginStatus(String userId)
{
try
{
return redisTemplate.opsForSet().isMember(RedisKey.LOGIN_STATUS_PREFIX, userId);
} catch (Exception e)
{
log.error(e.getMessage(), e);
return null;
}
}
@Override
public Long removeUserLoginStatus(String userId)
{
try
{
return redisTemplate.opsForSet().remove(RedisKey.LOGIN_STATUS_PREFIX, userId);
} catch (Exception e)
{
log.error(e.getMessage(), e);
return null;
}
}
}
| [
"1124212685@qq.com"
] | 1124212685@qq.com |
57e82739b2f53db96036c5b94171b9b0254eed93 | 9783f49b7291da63adf15b9ea2267e5299b20103 | /code/get.java | 0baca1a1e4416fd40f7286aa54e750767d098d67 | [] | no_license | saurabhmalkar/DavisBase | a3badc332ac7fd75cff9de63cf479c89a622b4d3 | 6972565206a1ed39384c9aa6b0da8b50d97287cf | refs/heads/master | 2020-03-21T04:25:59.357138 | 2018-06-21T02:11:21 | 2018-06-21T02:11:21 | 138,107,964 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 572 | java | import java.io.RandomAccessFile;
public class get{
public static int page_size = 512;
public static byte get_type_of_page(RandomAccessFile file, int page)
{
byte type=0x05;
try {
file.seek((page-1)*page_size);
type = file.readByte();
} catch (Exception e) {
System.out.println(e);
}
return type;
}
public static boolean hasRowId(RandomAccessFile file, int page, int rowid)
{
int[] keys = Btree.get_key_array(file, page);
for(int i : keys)
if(rowid == i)
return true;
return false;
}
public static void main(String[] args){}
} | [
"saurabhmalkar@users.noreply.github.com"
] | saurabhmalkar@users.noreply.github.com |
2c1f0f9aadf25ef961aa3851246cf0501849027b | 8bcbf676c8fd28b6686f90c18eca8bf501244ed8 | /src/main/java/com/example/onlineshopapp/user/Status.java | 7cd55d23772aa90120a34c11e5cd2be08b692f09 | [] | no_license | RaQu04/OnlineShopApp | 6f3005360374d0350b4b98dc2c18c95feea536b4 | 990d6a85c547a44533d369cd6991c5040444911a | refs/heads/dev | 2023-02-26T01:56:44.621655 | 2021-02-07T10:38:39 | 2021-02-07T10:38:39 | 332,188,337 | 0 | 0 | null | 2021-02-07T10:38:40 | 2021-01-23T10:57:16 | TypeScript | UTF-8 | Java | false | false | 94 | java | package com.example.onlineshopapp.user;
public enum Status {
ACTIVE, INACTIVE, BLOCKED
}
| [
"lukasz.er17@gmail.com"
] | lukasz.er17@gmail.com |
937310f4c18cf46ae1f3ff3d5f3c271d15e49f47 | 10615d5bae1900788766b2264b0131f56f7314a8 | /OpenGlWrapper/fbos/Attachment.java | 44aa41d1888c5b91274808af99c4d2a2e7b88717 | [
"Unlicense"
] | permissive | TheThinMatrix/LowPolyWater | f12e12c2a36133f9d9e1ba54e8afe57637e45b7a | a202218f19ad226f14910b0e96f18bdba9475efd | refs/heads/master | 2021-08-10T08:32:13.317261 | 2017-11-12T11:26:59 | 2017-11-12T11:26:59 | 110,422,068 | 53 | 11 | null | null | null | null | UTF-8 | Java | false | false | 1,603 | java | package fbos;
/**
* Represents an FBO attachment.
*
* @author Karl
*
*/
public abstract class Attachment {
private int bufferId;
private boolean isDepthAttach = false;
public int getBufferId() {
return bufferId;
}
/**
* Creates the attachment by initializing the necessary storage, and then
* attaches it to the FBO. This method also needs to set the bufferId after
* the storage has been initialized.
*
* @param attachment
* - The type of attachment, e.g. GL_COLOR_ATTACHMENT0, or
* GL_DEPTH_ATTACHMENT, etc.
* @param width
* - The width of the FBO in pixels
* @param height
* - The height of the FBO in pixels
* @param samples
* - The number of samples that this FBO uses (for
* multisampling). This is 0 if multisampling is not used.
*/
public abstract void init(int attachment, int width, int height, int samples);
public abstract void delete();
/**
* Sets the ID of the storage being used for this attachment.
*
* @param id
* - The ID of either the texture or the render buffer being used
* for this attachment.
*/
protected void setBufferId(int id) {
this.bufferId = id;
}
/**
* Indicate that this attachment is a depth buffer attachment.
*/
protected void setAsDepthAttachment() {
this.isDepthAttach = true;
}
/**
* @return True if this attachment is being used as a depth attachment.
*/
protected boolean isDepthAttachment() {
return isDepthAttach;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
6184d4b4a886ad6c17c97a3460fdafa83be1ef40 | 2d8c9c2e5adcbc2980fb2beae80968481e9f55bb | /src/Constants.java | fda1380acdb159018a6e45f64f37bb1490f643a6 | [] | no_license | rachna928/ServerConsolidationusingCloudsim | 5cd171c4178bb07c1a3476e290dc1683d7bee592 | f5f858b601493d4c8e5e3a8c45416535ffb960d2 | refs/heads/master | 2023-02-20T21:08:15.457015 | 2021-01-11T15:54:49 | 2021-01-11T15:54:49 | 328,253,098 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,103 | java |
import org.cloudbus.cloudsim.power.models.PowerModel;
import org.cloudbus.cloudsim.power.models.PowerModelSpecPowerHpProLiantMl110G4Xeon3040;
import org.cloudbus.cloudsim.power.models.PowerModelSpecPowerHpProLiantMl110G5Xeon3075;
public class Constants {
public final static boolean ENABLE_OUTPUT = true;
public final static boolean OUTPUT_CSV = false;
public final static double SCHEDULING_INTERVAL = 300;
public final static double SIMULATION_LIMIT = 24 * 60 * 60;
public final static int CLOUDLET_LENGTH = 2500 * (int) SIMULATION_LIMIT;
public final static int CLOUDLET_PES = 1;
/*
* VM instance types:
* High-Memory Extra Large Instance: 3.25 EC2 Compute Units, 8.55 GB // too much MIPS
* High-CPU Medium Instance: 2.5 EC2 Compute Units, 0.85 GB
* Extra Large Instance: 2 EC2 Compute Units, 3.75 GB
* Small Instance: 1 EC2 Compute Unit, 1.7 GB
* Micro Instance: 0.5 EC2 Compute Unit, 0.633 GB
* We decrease the memory size two times to enable oversubscription
*
*/
public final static int VM_TYPES = 4;
public final static int[] VM_MIPS = { 2500, 2000, 1000, 500 };
public final static int[] VM_PES = { 1, 1, 1, 1 };
public final static int[] VM_RAM = { 870, 1740, 1740, 613 };
public final static int VM_BW = 100000; // 100 Mbit/s
public final static int VM_SIZE = 2500; // 2.5 GB
/*
* Host types:
* HP ProLiant ML110 G4 (1 x [Xeon 3040 1860 MHz, 2 cores], 4GB)
* HP ProLiant ML110 G5 (1 x [Xeon 3075 2660 MHz, 2 cores], 4GB)
* We increase the memory size to enable over-subscription (x4)
*/
public final static int HOST_TYPES = 2;
public final static int[] HOST_MIPS = { 1860, 2660 };
public final static int[] HOST_PES = { 2, 2 };
public final static int[] HOST_RAM = { 4096, 4096 };
public final static int HOST_BW = 1000000; // 1 Gbit/s
public final static int HOST_STORAGE = 1000000; // 1 GB
public final static PowerModel[] HOST_POWER = {
new PowerModelSpecPowerHpProLiantMl110G4Xeon3040(),
new PowerModelSpecPowerHpProLiantMl110G5Xeon3075()
};
} | [
"rachna.kulal2809@gmail.com"
] | rachna.kulal2809@gmail.com |
75b498c3da8925d350245aa1bf1003570677a7db | c081877cb822404d00a364e18a59fd891d620513 | /src/java/newmemberspackage/newmembers1.java | e043050c52381a9be629c84c96a76d4a969db27a | [] | no_license | phurku/java_detail_record | d047790e9ee22cfaea91522865eaa084333f94f2 | 6444dcaaef9c6de678c0c3dbe744496a5251cc9a | refs/heads/master | 2020-04-21T00:07:03.519612 | 2019-02-14T05:56:10 | 2019-02-14T05:56:10 | 169,187,043 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,022 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package newmemberspackage;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Phurkima
*/
@WebServlet(name = "newmembers1", urlPatterns = {"/newmembers1"})
public class newmembers1 extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet newmembers1</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet newmembers1 at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| [
"phurku2017@gmail.com"
] | phurku2017@gmail.com |
e35059921f47154dcefe6b381e1a7ca32727c114 | 1efa1222f11138615e80291ff4f0e8f6312e0004 | /app/src/androidTest/java/com/dissertation/watchingyou/ExampleInstrumentedTest.java | 4e8d6f738cd2f2ee969d391cdc5f620a6aed08b0 | [] | no_license | sudeep16/WatchingYou | 9fbbd23f330a9450bdb4c33f7236845b74216fa1 | 60f65daee093c30af51769063a4d97aca57ec562 | refs/heads/master | 2023-01-01T02:37:34.993973 | 2020-10-10T14:17:09 | 2020-10-10T14:17:09 | 299,891,525 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 770 | java | package com.dissertation.watchingyou;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.dissertation.watchingyou", appContext.getPackageName());
}
} | [
"srshakya5@gmail.com"
] | srshakya5@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.