text
stringlengths
10
2.72M
package com.donkeymonkey.recyq.fragments; import android.graphics.Typeface; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Base64; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.donkeymonkey.recyq.R; import com.donkeymonkey.recyq.model.StoreItem; import com.donkeymonkey.recyq.model.StoreItems; import java.util.ArrayList; public class StoreItemFragment extends Fragment { private static String mStoreItemKey; private StoreItem mStoreItem = new StoreItem(); private StoreItems mStoreItems; public static StoreItemFragment newInstance(String storeItemKey) { mStoreItemKey = storeItemKey; return new StoreItemFragment(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_storeitem, container, false); mStoreItems = StoreItems.getInstance(); mStoreItem = mStoreItems.findStoreItemWithKey(mStoreItemKey); TextView storeName = (TextView) view.findViewById(R.id.storeItem_textview_store_name); ImageView imageView = (ImageView) view.findViewById(R.id.storeItem_imageview); TextView description = (TextView) view.findViewById(R.id.storeItem_textView_description); TextView detail_description = (TextView) view.findViewById(R.id.storeItem_textView_detail_description); TextView tokens = (TextView) view.findViewById(R.id.storeItem_textView_token); Button buy_button = (Button) view.findViewById(R.id.storeItem_button_buy); // Setting fonts Typeface pt_mono_font = Typeface.createFromAsset(getContext().getAssets(), "fonts/pt_mono.ttf"); Typeface pt_mono_bold_font = Typeface.createFromAsset(getContext().getAssets(), "fonts/pt_mono_bold.ttf"); Typeface volvobroad_font = Typeface.createFromAsset(getContext().getAssets(), "fonts/volvobroad.ttf"); storeName.setTypeface(volvobroad_font); description.setTypeface(pt_mono_bold_font); detail_description.setTypeface(pt_mono_font); tokens.setTypeface(pt_mono_font); buy_button.setTypeface(pt_mono_bold_font); storeName.setText(mStoreItem.getShopName()); description.setText(mStoreItem.getItemName()); detail_description.setText(mStoreItem.getDetailDescription()); if (mStoreItem.getTokenAmount() > 1) { tokens.setText(getString(R.string.storeitem_price_more, mStoreItem.getTokenAmount())); } else { tokens.setText(getString(R.string.storeitem_price_one)); } byte[] imageByteArray = Base64.decode(mStoreItem.getImageString(), Base64.DEFAULT); Glide.with(getActivity()) .load(imageByteArray) .asBitmap() .into(imageView); buy_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } }); return view; } }
package com.example.demo.model; import lombok.Data; import javax.persistence.*; @Data @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "email") private String email; @Column(name = "user_id") private String userId; }
package com.example.cursorloaderdemo; import android.app.Activity; import android.app.ListActivity; import android.app.LoaderManager.LoaderCallbacks; import android.content.Context; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.Browser; import android.support.v4.widget.SimpleCursorAdapter; import android.util.Log; import android.view.Menu; public class MainActivity extends ListActivity { private static final String TAG = "CursorLoaderDemo.MainActivity"; private SimpleCursorAdapter mAdapter; private static final Uri mUri = Browser.BOOKMARKS_URI; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String[] fromFields = new String[] { Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL }; int[] toViews = new int[] { android.R.id.text1, android.R.id.text2 }; mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, null, fromFields, toViews, 0); setListAdapter(mAdapter); // Prepare the loader: re-connects an existing one or reuses one. getLoaderManager().initLoader(0, null, new MyCallbacks(this)); } class MyCallbacks implements LoaderCallbacks<Cursor> { Context context; public MyCallbacks(Activity context) { this.context = context; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle stuff) { Log.d(TAG, "MainActivity.onCreateLoader()"); return new CursorLoader(context, // Normal CP query: url, proj, select, where, having mUri, null, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Load has finished, swap the loaded cursor into the view Log.d(TAG, "MainActivity.onLoadFinished(), count = " + data.getCount()); mAdapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { // The end of time: set the cursor to null to prevent bad ending. mAdapter.swapCursor(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.main, menu); return true; } }
package com.gbros.config; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.druid.pool.DruidDataSource; @Configuration public class DBConfig { @Autowired DBParam dBConfig;//这是个自动填充的DBParam对象 //DataSource dataSource; @Bean //把dataSource()放到spring的容器中 public DataSource dataSource() throws SQLException { DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(dBConfig.getDriverClassName()); druidDataSource.setUrl(dBConfig.getUrl()); druidDataSource.setUsername(dBConfig.getUserName()); druidDataSource.setPassword(dBConfig.getPassword()); druidDataSource.setMaxActive(dBConfig.getMaxActive()); druidDataSource.setMinIdle(dBConfig.getMinIdle()); druidDataSource.setInitialSize(dBConfig.getInitialSize()); druidDataSource.setMaxWait(dBConfig.getMaxWait()); druidDataSource.setValidationQuery(dBConfig.getValidationQuery()); druidDataSource.setTestOnBorrow(dBConfig.isTestOnBorrow()); druidDataSource.setTestOnReturn(dBConfig.isTestOnReturn()); druidDataSource.setTestWhileIdle(dBConfig.isTestWhileIdle()); druidDataSource.setTimeBetweenEvictionRunsMillis(dBConfig .getTimeBetweenEvictionRunsMillis()); druidDataSource.setMinEvictableIdleTimeMillis(dBConfig .getMinEvictableIdleTimeMillis()); druidDataSource.setRemoveAbandoned(dBConfig.isRemoveAbandoned()); druidDataSource.setRemoveAbandonedTimeout(dBConfig .getRemoveAbandonedTimeout()); druidDataSource.setLogAbandoned(dBConfig.isLogAbandoned()); druidDataSource.setFilters(dBConfig.getFilters()); return druidDataSource; } }
package fr.gpsextractor_; public class CoordonneesGpsInexistantesException extends Exception { private static final long serialVersionUID = 1L; /** * Exception pour GpsExtractor.java */ public CoordonneesGpsInexistantesException() { System.out.println("Cette image n'est pas géolocalisée"); } }
package com.springmaven.controllers; import com.springmaven.dao.HairTreatmentDAOImpl; import com.springmaven.model.HairTreatment; import com.springmaven.model.Vendor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.List; /** * Created by Gourav on 1/18/2017. */ @Controller public class HairTreatmentController { @Autowired HairTreatmentDAOImpl hairTreatmentDAO; @RequestMapping(value = "/") public ModelAndView homePage() { ModelAndView modelView = new ModelAndView("index"); return modelView; } @RequestMapping(value = "/index") public ModelAndView showindex() { ModelAndView modelView = new ModelAndView("index"); return modelView; } @RequestMapping(value = "/hairtrt") public ModelAndView showhairtreatment() { ModelAndView modelView = new ModelAndView("hair_treatment_men"); List<HairTreatment> HairTreatments; HairTreatments = hairTreatmentDAO.getAllHairtreatments(); modelView.addObject("hairTreatments", HairTreatments); return modelView; } @RequestMapping(value = "/BookHairTreatment") public ModelAndView viewbookingpagehairstyle() { ModelAndView modelView = new ModelAndView("hairstyles_booking"); return modelView; } /* ******************************** VENDOR-SIDE CODE ******************************** */ /* ################################################################ # ADD HAIR TREATMENTS DETAILS # ################################################################ */ @RequestMapping(value = "/AddHairTreatment") public ModelAndView addHairTreatmentView() { ModelAndView modelView = new ModelAndView("vendor_hairtreatment_views/vendor_AddHairTreatment"); return modelView; } @RequestMapping(value = "/addHairTreatmentForm", method = RequestMethod.POST) public ModelAndView addHairTreatmentForm(@ModelAttribute("hairtreatment") HairTreatment hairTreatment, @RequestParam("files") CommonsMultipartFile[] files, HttpServletRequest servletRequest) { ModelAndView modelView = new ModelAndView("redirect:/AddHairTreatment"); String pics[] = new String[files.length]; for (int i = 0; i < files.length; i++) { MultipartFile file = files[i]; try { byte barr[] = file.getBytes(); String orgfileName = file.getOriginalFilename(); int lastIndex = orgfileName.lastIndexOf('.'); String extension = orgfileName.substring(lastIndex, orgfileName.length()); String saloonName = hairTreatment.getVendorSaloonName(); saloonName = saloonName.replace(" ", ""); String path = servletRequest.getContextPath(); File d = new File(path + "/" + "Database"); if (!d.exists()) { boolean br = d.mkdir(); } File di = new File(d + "/" + saloonName); if (!di.exists()) { boolean br = di.mkdir(); } File di1 = new File(d + "/" + saloonName + "/hairTreatments"); if (!di1.exists()) { boolean br = di1.mkdir(); } String htName = hairTreatment.getHtName(); htName = htName.replace(" ", ""); File dir = new File(di1 + "/" + htName); if (!dir.exists()) { boolean br = dir.mkdir(); } // Create the file on server File serverFile = new File(dir + "/" + htName + "_" + (i + 1) + extension); BufferedOutputStream bout = new BufferedOutputStream( new FileOutputStream(serverFile)); bout.write(barr); bout.flush(); bout.close(); pics[i] = "/" + saloonName + "/hairTreatments/" + htName + "/" + htName + "_" + (i + 1) + extension; } catch (Exception e) { System.out.println(e); } } hairTreatment.setHtPics(pics); int i = hairTreatmentDAO.addHairTreatment(hairTreatment); if (i == 1) { modelView.setViewName("vendor_success"); modelView.addObject("service", "addHairTreatment"); } else { modelView.addObject("error", "Error occured during registration please do try again"); } return modelView; } /* #################### END ADD HAIR TREATMENTS ######################## */ /* ################################################################ # EDIT HAIR TREATMENTS # ################################################################ */ @RequestMapping(value = "/EditHairTreatmentDetails") public ModelAndView editHairstyleView(@RequestParam(value = "htId") String hId, HttpSession session) { ModelAndView modelView = new ModelAndView("vendor_hairtreatment_views/vendor_editHairTreatment"); HairTreatment hairTreatment = hairTreatmentDAO.getHairTreatmentsDetails(hId); Vendor vendor = (Vendor) session.getAttribute("vendor"); modelView.addObject("vendor", vendor); modelView.addObject("hairTreatment", hairTreatment); return modelView; } @RequestMapping(value = "/updateHairTreatmentForm", method = RequestMethod.POST) public ModelAndView updateHairTreatmentForm(@ModelAttribute("hairtreatment") HairTreatment hairTreatment, @RequestParam("files") CommonsMultipartFile[] files, HttpServletRequest servletRequest) { ModelAndView modelView = new ModelAndView("redirect:/AddHairTreatment"); String pics[] = new String[files.length]; for (int i = 0; i < files.length; i++) { MultipartFile file = files[i]; try { byte barr[] = file.getBytes(); String orgfileName = file.getOriginalFilename(); int lastIndex = orgfileName.lastIndexOf('.'); String extension = orgfileName.substring(lastIndex, orgfileName.length()); String saloonName = hairTreatment.getVendorSaloonName(); saloonName = saloonName.replace(" ", ""); String path = servletRequest.getContextPath(); File d = new File(path + "/" + "Database"); if (!d.exists()) { boolean br = d.mkdir(); } File di = new File(d + "/" + saloonName); if (!di.exists()) { boolean br = di.mkdir(); } File di1 = new File(d + "/" + saloonName + "/hairTreatments"); if (!di1.exists()) { boolean br = di1.mkdir(); } String htName = hairTreatment.getHtName(); htName = htName.replace(" ", ""); File dir = new File(di1 + "/" + htName); if (!dir.exists()) { boolean br = dir.mkdir(); } // Create the file on server File serverFile = new File(dir + "/" + htName + "_" + (i + 1) + extension); BufferedOutputStream bout = new BufferedOutputStream( new FileOutputStream(serverFile)); bout.write(barr); bout.flush(); bout.close(); pics[i] = "/" + saloonName + "/hairTreatments/" + htName + "/" + htName + "_" + (i + 1) + extension; } catch (Exception e) { System.out.println(e); } } hairTreatment.setHtPics(pics); int i = hairTreatmentDAO.updateHairTreatmentDetails(hairTreatment); if (i == 1) { modelView.setViewName("vendor_success"); modelView.addObject("service", "addHairTreatment"); } else { modelView.addObject("error", "Error occured during registration please do try again"); } return modelView; } /* #################### END OF EDIT HAIR TREATMENTS######################## */ /* ################################################################ # VIEW VENDOR HAIR TREATMENTS # ################################################################ */ @RequestMapping(value = "/ViewVendorHairTreatments") public ModelAndView viewAllVendorHairTreatmentView(HttpSession session) { ModelAndView modelView = new ModelAndView("vendor_hairtreatment_views/vendor_viewAllHairTreatment"); Vendor v = (Vendor) session.getAttribute("vendor"); List<HairTreatment> hairTreatments; if (v == null) modelView.setViewName("redirect:/VendorSignin"); else { hairTreatments = hairTreatmentDAO.getVendorHairTreatments(v.getEmail()); modelView.addObject("hairtreatments", hairTreatments); } return modelView; } /* #################### END OF VIEW HAIR TREATMENTS ######################## */ /* ################################################################ # DELETE HAIR TREATMENT # ################################################################ */ @RequestMapping(value = "/DeleteHairTreatment") public void deleteHairTreatmentView() { } /* #################### END OF DELETE HAIR TREATMENT ######################## */ /* *************************** END OF VENDOR-SIDE CODE *************************** */ }
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Jugada { public Set<Jugadita>jugaditas=new HashSet<>(); public int puntos=0; public Boolean isLine; public Jugada copy(int puntos){ Jugada n=new Jugada(); n.jugaditas=new HashSet<>(this.jugaditas); n.puntos=puntos; n.isLine=isLine; return n; } public String toString(){ String out="["; for(Jugadita j:jugaditas){ out+=j.ficha+"(x: "+j.x+" y: "+j.y+"),"; } out=out.substring(0,out.length()-1)+"]"; return out; } public int hashCode(){ return 0; } public boolean equals(Object o){ Jugada otraJugada=(Jugada)o; return otraJugada!=null&&jugaditas.equals(otraJugada.jugaditas)&&puntos==otraJugada.puntos&&isLine==otraJugada.isLine; } }
package com.dbanalyzer.commands; import com.db.persistence.scheme.BaseObject; import com.db.persistence.wsSoap.QueryRequestRemote; import com.db.persistence.wsSoap.QueryResponseRemote; import com.dbanalyzer.QuerySvcRemoteWrapper; import com.generic_tools.Pair.Pair; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.persistence.Column; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /* examples: q select m from MissionItem m */ @Component public class Query implements RunnablePayload { @Autowired private QuerySvcRemoteWrapper querySvcRemote; private List<Pair<String, String>> usage; @PostConstruct public void init() { usage = new ArrayList<>(); usage.add(new Pair<>("q","Free query")); } @Override public boolean isRelevant(String payload) { if (!payload.startsWith("q ")) return false; String[] strs = payload.split(" "); if (strs.length <= 2) return false; return true; } @Override public List<Pair<String, String>> getUsage() { return usage; } private final static String ObjID = "ObjID"; private final static String fromRevision = "From"; private final static String toRevision = "To"; private final static String Deleted = "Deleted"; private final static String Private = "Private"; private final static String Clz = "Class"; @Override public String run(String payload) { String ans = ""; try { QueryRequestRemote queryRequestRemote = new QueryRequestRemote(); String queryString = payload.substring("q ".length()); QueryResponseRemote queryResponseRemote = querySvcRemote.runNativeQuery(queryString); List<BaseObject> objectList = queryResponseRemote.getResultList(); ans += getObjectToTableString(objectList); } catch (Exception e) { // e.printStackTrace(); ans += "ERROR: " + e.getMessage() + "\n"; } return ans; } public static String getObjectToTableString(List<BaseObject> objectList) { String ans = ""; try { ans += "Total Objects: " + objectList.size() + "\n"; List<String> columns = new ArrayList(); Map<String, Integer> columnSize = new HashMap<>(); List<Map<String, Object>> allValues = new ArrayList<>(); List<Method> baseMethods = new ArrayList(Arrays.asList(BaseObject.class.getMethods())); columns.addAll(Arrays.asList(ObjID, fromRevision, toRevision, Deleted, Private, Clz)); columnSize.put(ObjID, 36); columnSize.put(fromRevision, 4); columnSize.put(toRevision, 10); columnSize.put(Deleted, 7); columnSize.put(Private, 7); columnSize.put(Clz, 7); for (BaseObject obj : objectList) { Method[] methods = obj.getClass().getMethods(); Map<String, Object> values = new HashMap<>(); //Handle base object part values.put(ObjID, obj.getKeyId().getObjId()); values.put(fromRevision, obj.getFromRevision()); values.put(toRevision, obj.getKeyId().getToRevision()); values.put(Deleted, obj.isDeleted() ? "T" : ""); values.put(Private, !obj.getKeyId().getEntityManagerCtx().equals(0) ? "T" : ""); String clzName = obj.getClass().getTypeName(); // values.put(Clz, clzName.substring(clzName.lastIndexOf(".") + 1)); values.put(Clz, obj.getClass().getSimpleName()); for (Method method : methods) { if (!method.getName().startsWith("get") && !method.getName().startsWith("is")) continue; if (method.getParameters().length != 0) continue; if (baseMethods.contains(method)) continue; String key = getKey(method); if (!columns.contains(key)) { columns.add(key); columnSize.put(key, getKeyLength(method, key)); } values.put(key, getValue(method, obj)); } allValues.add(values); } ans += "| "; for (String col : columns) { ans += String.format("%" + columnSize.get(col) + "s | ", col); } int length = ans.length() - ans.lastIndexOf('\n'); ans += "\n"; for (String s : Collections.nCopies(length - 2, "-")) ans += s; ans += "\n"; Iterator<Map<String, Object>> itr = allValues.iterator(); while (itr.hasNext()) { Map<String, Object> entry = itr.next(); ans += "| "; for (String col : columns) { if (entry.keySet().contains(col)) { Object val = entry.get(col); String stringVal = "null"; if (val != null) stringVal = val.toString(); ans += String.format("%" + columnSize.get(col) + "s | ", stringVal.substring(0, Math.min(columnSize.get(col), stringVal.length())) + ""); } else { ans += String.format("%" + columnSize.get(col) + "s | ", " "); } System.out.println(""); } ans += "\n"; } } catch (Exception e) { e.printStackTrace(); } return ans; } private static Integer getKeyLength(Method method, String key) { if (UUID.class.isAssignableFrom(method.getReturnType())) return UUID.randomUUID().toString().length(); return Math.max(5, key.length()); } private static String getKey(Method method) { String key; if (method.getName().startsWith("get")) key = method.getName().substring("get".length()); else key = method.getName().substring("is".length()); Column c = method.getAnnotation(Column.class); if (c != null && !c.name().isEmpty()) { key = c.name(); } if (Collection.class.isAssignableFrom(method.getReturnType())) { key += "[Size]"; } if (key.isEmpty()) throw new RuntimeException("Key is empty for method "+ method); return key; } private static Object getValue(Method method, Object obj) throws InvocationTargetException, IllegalAccessException { Object ret = method.invoke(obj, null); if (ret instanceof Collection) return ((Collection) ret).size(); if (ret instanceof Class) return ((Class) ret).getSimpleName(); return ret; } }
package com.example.quiz; import java.util.ArrayList; public class Quiz { private static double lastGrade = 0.0; private static double GradesSum = 0.0; private static int TestsCount = 0; public static double getLastGrade(){ return lastGrade; } public static double getGradeAverage(){ return GradesSum /(double)TestsCount; } public static double validateTest(String [] answers){ int corrects = 0; for (int i = 0; i < test.size(); i++) { Question q = test.get(i); if(q.getAnswer().equals(answers[i])) corrects++; } double grade = 100.0* (double)corrects / (double)test.size(); TestsCount++; GradesSum+=grade; lastGrade=grade; return grade; } private static ArrayList<Question> test; public static ArrayList<Question> getTest(){ if(test == null){ test = new ArrayList<>(); Question q1 = new Question("1) Um Banco de Dados é um:", "e - conjunto de dados integrados destinados a atender às necessidades de uma comunidade de usuários.", new String[]{"a - conjunto de objetos da realidade sobre os quais se deseja manter informações." ,"b - conjunto de operações sobre dados integrados destinados a modelar processos." ,"c - software que incorpora as funções de definição, recuperação e alteração de dados." ,"d - software que modela funções de definição, recuperação e alteração de dados e programas." ,"e - conjunto de dados integrados destinados a atender às necessidades de uma comunidade de usuários."}); Question q2 = new Question("2) A proteção das informações e dos sistemas das organizações requer o uso de recursos de proteção como os firewalls, utilizados para:","a - ajudar a impedir que a rede privada da empresa seja acessada sem autorização a partir da Internet." ,new String[]{"a - ajudar a impedir que a rede privada da empresa seja acessada sem autorização a partir da Internet." ,"b - liberar o uso de todos os serviços de rede somente aos usuários registrados pelo administrador da rede." ,"c - garantir que cada pacote de dados seja entregue com segurança apenas ao destinatário informado, reduzindo assim o tráfego na rede." ,"d - garantir que nenhum colaborador possa comprometer a segurança das informações da organização." ,"e - garantir que os computadores da rede não sejam infectados por malwares ou atacados por hackers."}); Question q3 = new Question("3) No sistema Operacional Windows, caso o usuário tenha excluído arquivos e venha a se arrepender,<br>" +"estes itens poderão ser restaurados da Lixeira. Na tela, basta clicar na Lixeira e o conteúdo da Lixeira será exibido.<br>" +"O usuário deverá selecionar o item a ser restaurado, então clicar no menu Arquivo e depois em Restaurar, e a restauração será feita.<br>" +"O arquivo restaurado será devolvido à(ao):", "a - Local de Origem." ,new String[]{"a - Local de Origem." ,"b - Pasta Restauração." ,"c - Barra de Tarefas." ,"d - Área de Trabalho." ,"e - Pasta Documentos."}); Question q4 = new Question("4) Sobre a memória RAM é correto afirmar", "b - É a memória principal, nela são armazenadas as informações enquanto estão sendo processadas." ,new String[]{"a - É a memória permanente do computador. Onde se instala o software e também onde é armazenado os documentos e outros arquivos." ,"b - É a memória principal, nela são armazenadas as informações enquanto estão sendo processadas." ,"c - É uma memória não volátil, isto é, os dados gravados não são perdidos quando se desliga o computador." ,"d - É a memória secundária ou memória de massa. É usada para gravar grande quantidade de dados." ,"e - É uma memória intermediária entre a memória principal e o processador."}); Question q5 = new Question("5) As funções do núcleo do Linux (escalonamento de processos, gerenciamento de memória, operações de entrada e saída, acesso ao sistema de arquivos)<br>" + "são executadas no espaço de núcleo. Uma característica do núcleo Linux é que algumas das funções podem ser compiladas e executadas como módulos,<br>" + "que são bibliotecas compiladas separadamente da parte principal do núcleo." +"Essas características fazem com que o núcleo do Linux seja classificado como:", "a - Monolítico." ,new String[]{"a - Monolítico." ,"b - Multifunções." ,"c - Distribuído." ,"d - Integrado." ,"e - Único."}); Question q6 = new Question("6) Um usuário do Google Chrome em português deseja ativar o recurso para ajudar a completar pesquisas e URLs digitados na barra de endereços do navegador.<br>" +"Para isso ele deve acessar o botão 'Personalizar e Controlar o Google Chrome' , " +"clicar na opção 'Configurações', na opção 'Mostrar configurações avançadas...'<br>" +"e clicar no quadrado que habilita esse recurso que se encontra em:", "d - Rede." ,new String[]{"a - Conteúdo da web." ,"b - Extensões." ,"c - Pesquisar." ,"d - Rede." ,"e - Privacidade."}); Question q7 = new Question("7) O cavalo de Troia (trojan)", "c - pode ser instalado por vírus, phishing ou outros programas, com a finalidade de abrir um backdoor." ,new String[]{"a - a impede que o sistema operacional se inicie ou seja executado corretamente." ,"b - aumenta o tráfego na Internet e gera um grande volume de dados de caixas postais de correio eletrônico." ,"c - pode ser instalado por vírus, phishing ou outros programas, com a finalidade de abrir um backdoor." ,"d - também é conhecido como vírus de macro, por utilizar os arquivos do MS Office." ,"e - não pode ser combatido por meio de firewall."}); Question q8 = new Question("8) Um Assistente de Gestão Escolar, por meio do Google Chrome, versão 40, em sua configuração padrão,<br>" + "acessa um site aguardando a publicação de um edital que pode ser feita a qualquer momento.<br>" +"Ao constatar que o edital ainda não está disponível, o assistente, por meio de atalho do teclado, decide atualizar a página que está sendo exibida no navegador.<br>" +"Assinale a alternativa que contém o atalho descrito no enunciado.", "b - F5." ,new String[]{"a - Ctrl + F2." ,"b - F5." ,"c - F4." ,"d - F2." ,"e - Shift + F2."}); Question q9 = new Question("9) Para prevenir que vírus se instalem nos computadores de seus usuários, o Gmail não permite que sejam enviados ou recebidos arquivos executáveis.<br>" +"Como consequência dessa política, dentre os arquivos listados abaixo, o único que poderia ser enviado por e-mail através do Gmail é:", "e - arq_e.txt." ,new String[]{"a - arq_a.pif." ,"b - arq_b.exe." ,"c - arq_c.bat." ,"d - arq_d.jar." ,"e - arq_e.txt."}); Question q10 = new Question("10) Com relação à manutenção de equipamentos de informática, assinale a opção correta.", "c - Uma maneira eficaz de fazer backup de arquivos do computador é instalar um HD externo, pela porta USB, e realizar a cópia dos arquivos normalmente." ,new String[]{"a - Para corrigir o problema do computador que apresenta a hora errada ao ser inicializado, mesmo após ter sido configurado com a hora correta, é suficiente substituir o CNIP." ,"b - Ao se instalarem monitores de LCD, é necessária a instalação de um conversor digital para se ter acesso aos padrões abertos da Internet." ,"c - Uma maneira eficaz de fazer backup de arquivos do computador é instalar um HD externo, pela porta USB, e realizar a cópia dos arquivos normalmente." ,"d - Para ampliar a capacidade de armazenamento de dados do computador, é relevante expandir os pentes de memória RAM." ,"e - A tecnologia USB provê conexão mais rápida à Internet em redes wireless."}); test.add(q1); test.add(q2); test.add(q3); test.add(q4); test.add(q5); test.add(q6); test.add(q7); test.add(q8); test.add(q9); test.add(q10); } return test; } }
/* * 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 dao; import entities.Equipo; import org.hibernate.Session; import org.hibernate.Transaction; import util.HibernateUtil; /** * * @author USUARIO */ public class EquipoDAO { public static void salvarEquipo(Equipo equipo){ Session session = HibernateUtil.getSessionFactory().openSession(); Transaction t = session.beginTransaction(); // t.begin(); session.save(equipo); t.commit(); } }
package raft.server.storage; import java.io.Closeable; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.util.zip.CRC32; /** * Author: ylgrgyq * Date: 18/6/10 */ public class LogWriterWithMmap implements Closeable { private final FileChannel workingFileChannel; private int blockOffset; private MappedByteBuffer buffer; private long bufferStartPos; LogWriterWithMmap(FileChannel workingFileChannel) throws IOException { assert workingFileChannel != null; this.workingFileChannel = workingFileChannel; this.blockOffset = 0; bufferStartPos = 0; this.buffer = workingFileChannel.map(FileChannel.MapMode.READ_WRITE, bufferStartPos, Integer.MAX_VALUE); } LogWriterWithMmap(FileChannel workingFileChannel, long writePosotion) throws IOException { assert workingFileChannel != null; workingFileChannel.position(writePosotion); this.workingFileChannel = workingFileChannel; this.blockOffset = 0; } long getPosition() { return bufferStartPos + buffer.position(); } void flush() { buffer.force(); } @Override public void close() throws IOException { long pos = bufferStartPos + buffer.position(); buffer.force(); buffer = null; workingFileChannel.truncate(pos); workingFileChannel.close(); } void append(byte[] data) throws IOException{ assert data != null; assert data.length > 0; ByteBuffer writeBuffer = ByteBuffer.wrap(data); int dataSizeRemain = writeBuffer.remaining(); boolean begin = true; while (dataSizeRemain > 0) { int blockLeft = Constant.kBlockSize - blockOffset; if (blockLeft < Constant.kHeaderSize) { paddingBlock(blockLeft); blockOffset = 0; continue; } assert Constant.kBlockSize - blockOffset - Constant.kHeaderSize >= 0; final RecordType type; final int blockForDataAvailable = blockLeft - Constant.kHeaderSize; final int fragmentSize = Math.min(blockForDataAvailable, dataSizeRemain); final boolean end = fragmentSize == dataSizeRemain; if (begin && end) { type = RecordType.kFullType; } else if (begin) { type = RecordType.kFirstType; } else if (end) { type = RecordType.kLastType; } else { type = RecordType.kMiddleType; } byte[] out = new byte[fragmentSize]; writeBuffer.get(out); writeRecord(type, out); begin = false; dataSizeRemain -= fragmentSize; } } private void paddingBlock(int blockLeft) throws IOException{ assert blockLeft >= 0 : String.format("blockLeft:%s", blockLeft); if (buffer.remaining() < blockLeft) { bufferStartPos = buffer.position(); buffer = workingFileChannel.map(FileChannel.MapMode.READ_WRITE, bufferStartPos, Integer.MAX_VALUE); } while (blockLeft > 0) { // padding with bytes array full of zero this.buffer.put((byte)0); --blockLeft; } } private void writeRecord(RecordType type, byte[] blockPayload) throws IOException { assert blockOffset + Constant.kHeaderSize + blockPayload.length <= Constant.kBlockSize; if (buffer.remaining() < Constant.kHeaderSize + blockPayload.length) { bufferStartPos = buffer.position(); buffer = workingFileChannel.map(FileChannel.MapMode.READ_WRITE, bufferStartPos, Integer.MAX_VALUE); } CRC32 checksum = new CRC32(); checksum.update(type.getCode()); checksum.update(blockPayload); buffer.putLong(checksum.getValue()); buffer.putShort((short) blockPayload.length); buffer.put(type.getCode()); buffer.put(blockPayload); blockOffset += blockPayload.length + Constant.kHeaderSize; } }
package com.sohail.TechAssessment; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.Priority; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONObjectRequestListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /*Created By Sohail Yasin*/ public class ArticleListFragment extends Fragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; List<Article> articles; ListView articalListView; public ArticleListFragment() { // Required empty public constructor } public interface OnFragmentInteractionListener { public void onAnimalSelected(Article article); } OnFragmentInteractionListener listener; @Override public void onAttach(Activity activity) { super.onAttach(activity); if (activity instanceof OnFragmentInteractionListener) { listener = (OnFragmentInteractionListener) activity; } } @Override public void onDetach() { super.onDetach(); listener = null; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment /*I have put the null value as the second parameter of inflate() method because I don't want to attach the inflated View to any ViewGroup now. (host Activity of this Fragment will attach the view automatically but if the View was attacthed, the exception will thrown)*/ View view = inflater.inflate(R.layout.fragment_animal_list, null); return view; } AdapterView.OnItemClickListener onAnimalListViewItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Article article = (Article) adapterView.getItemAtPosition(i); Log.d("Sohail_article", "onAnimalSelected1: " + article.getDescription() + " " + article.getName()); if (listener != null) listener.onAnimalSelected(article); } }; @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); articalListView = (ListView) view.findViewById(android.R.id.list); getArticleList(); } private void getArticleList() { final ProgressDialog pd = new ProgressDialog(getContext()); pd.setMessage("loading"); pd.show(); articles = new ArrayList<Article>(); AndroidNetworking.get(Utils.URL_Article) .setPriority(Priority.LOW) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { Log.d("JsonTest", "GetCarePList: " + response); String status = "", message = ""; try { status = response.getString("status"); if (status.equals("OK")) { //media JSONArray jsonArray = response.getJSONArray("results"); if (jsonArray.length() > 0) { for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Article mObj = new Article(); mObj.setName(jsonObject.getString("title")); mObj.setDetailUrl(jsonObject.getString("url")); mObj.setDescription(jsonObject.getString("abstract")); mObj.setImageURL(jsonObject.getString("abstract")); mObj.setWriter(jsonObject.getString("byline")); mObj.setDate(jsonObject.getString("published_date")); JSONArray jsonArrayM = jsonObject.getJSONArray("media"); if (jsonArrayM.length() > 0) { for (int j = 0; j < jsonArrayM.length(); j++) { JSONObject JsonObjectM = jsonArrayM.getJSONObject(j); if (JsonObjectM.getString("type").equals("image")) { JSONArray jsonArrayImage = JsonObjectM.getJSONArray("media-metadata"); if (jsonArrayImage.length() > 0) { JSONObject JsonObjectImage = jsonArrayImage.getJSONObject(0); mObj.setImageURL(JsonObjectImage.getString("url")); } } } } articles.add(mObj); } } } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getContext(),"Something went wrong with api",Toast.LENGTH_LONG).show(); pd.dismiss(); } if (status.equals("OK")) { pd.dismiss(); ArticleListAdapter articleListAdapter = new ArticleListAdapter(getActivity(), articles); articalListView.setAdapter(articleListAdapter); articalListView.setOnItemClickListener(onAnimalListViewItemClickListener); } else { } } @Override public void onError(ANError anError) { pd.dismiss(); Toast.makeText(getContext(),"Something went wrong with api",Toast.LENGTH_LONG).show(); Log.d("JsonTest", "GetCarePList: " + anError); } }); } }
package com.ynyes.xunwudao.controller.management; 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.data.domain.Page; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; 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.bind.annotation.ResponseBody; import com.ynyes.xunwudao.entity.TdApply; import com.ynyes.xunwudao.entity.TdManager; import com.ynyes.xunwudao.entity.TdManagerRole; import com.ynyes.xunwudao.entity.TdProductCategory; import com.ynyes.xunwudao.entity.TdUser; import com.ynyes.xunwudao.service.TdManagerLogService; import com.ynyes.xunwudao.service.TdManagerRoleService; import com.ynyes.xunwudao.service.TdManagerService; import com.ynyes.xunwudao.service.TdProductCategoryService; import com.ynyes.xunwudao.service.TdUserService; import com.ynyes.xunwudao.util.SiteMagConstant; /** * 后台产品控制器 * * @author Sharon */ @Controller @RequestMapping(value = "/Verwalter/user/rf") public class TdManagerRfController { @Autowired TdProductCategoryService tdProductCategoryService; @Autowired TdManagerLogService tdManagerLogService; @Autowired TdManagerRoleService tdManagerRoleService; @Autowired TdManagerService tdManagerService; @Autowired TdUserService tdUserService; // @RequestMapping(value = "/list") // public String categoryList(String __EVENTTARGET, String __EVENTARGUMENT, // String __VIEWSTATE, Long[] listId, Integer[] listChkId,Integer page, Integer size, String keywords, // Long[] listSortId, ModelMap map, HttpServletRequest req) { // String username = (String) req.getSession().getAttribute("manager"); // if (null == username) { // return "redirect:/Verwalter/login"; // } // if (null != __EVENTTARGET) // { // if (__EVENTTARGET.equalsIgnoreCase("btnPage")) // { // if (null != __EVENTARGUMENT) // { // page = Integer.parseInt(__EVENTARGUMENT); // } // } // } // // if (null == page || page < 0) // { // page = 0; // } // // if (null == size || size <= 0) // { // size = SiteMagConstant.pageSize;; // } // // if (null != keywords) // { // keywords = keywords.trim(); // } // // map.addAttribute("page", page); // map.addAttribute("size", size); // map.addAttribute("keywords", keywords); // map.addAttribute("__EVENTTARGET", __EVENTTARGET); // map.addAttribute("__EVENTARGUMENT", __EVENTARGUMENT); // map.addAttribute("__VIEWSTATE", __VIEWSTATE); // // Page<TdUser> userPage = null; // // if (null == keywords || "".equalsIgnoreCase(keywords)) // { // userPage = tdUserService.findAllOrderBySortIdAsc(page, size); // } // else // { // userPage = tdUserService.searchAndOrderByIdDesc(keywords, page, size); // } // // map.addAttribute("rf_page", userPage); // // // 参数注回 // map.addAttribute("__EVENTTARGET", __EVENTTARGET); // map.addAttribute("__EVENTARGUMENT", __EVENTARGUMENT); // map.addAttribute("__VIEWSTATE", __VIEWSTATE); // // return "/site_mag/user_rf_list"; // } @RequestMapping(value = "/list") public String categoryEditDialog(Long id, String __EVENTTARGET, String __EVENTARGUMENT, String __VIEWSTATE, ModelMap map, HttpServletRequest req) { String username = (String) req.getSession().getAttribute("manager"); if (null == username) { return "redirect:/Verwalter/login"; } map.addAttribute("__EVENTTARGET", __EVENTTARGET); map.addAttribute("__EVENTARGUMENT", __EVENTARGUMENT); map.addAttribute("__VIEWSTATE", __VIEWSTATE); map.addAttribute("category_list", tdProductCategoryService.findAll()); // 参数类型表 // map.addAttribute("param_category_list", // tdParameterCategoryService.findAll()); if (null != id) { map.addAttribute("user",tdUserService.findOne(id)); //分销下一层列表 List<TdUser> userListOne = tdUserService.findByUpUserOneOrderByLastLoginTimeDesc(id); map.addAttribute("one_list", userListOne); //分销下两层列表 if(null != userListOne){ for(TdUser item: userListOne){ List<TdUser> userListTwo = tdUserService.findByUpUserOneOrderByLastLoginTimeDesc(item.getId()); if(null != userListTwo){ map.addAttribute("list_two_"+item.getId(), userListTwo); } } } } return "/site_mag/user_rf_list"; } @RequestMapping(value="/edit") public String applyEdit(Long id, String __VIEWSTATE, ModelMap map, HttpServletRequest req){ String username = (String) req.getSession().getAttribute("manager"); if (null == username) { return "redirect:/Verwalter/login"; } map.addAttribute("__VIEWSTATE", __VIEWSTATE); if (null != id) { TdUser tdUser = tdUserService.findOne(id); map.addAttribute("user",tdUser); if(null != tdUser.getUpUserOne()){ TdUser userOne = tdUserService.findOne(tdUser.getUpUserOne()); map.addAttribute("userOne", userOne); } if(null != tdUser.getUpUserTwo()){ TdUser userTwo = tdUserService.findOne(tdUser.getUpUserTwo()); map.addAttribute("userTwo", userTwo); } } return "/site_mag/user_rf_edit"; } @RequestMapping(value = "/save", method = RequestMethod.POST) public String save(String username, Long id, String __EVENTTARGET, String __EVENTARGUMENT, String __VIEWSTATE, ModelMap map, HttpServletRequest req) { String managerUsername = (String) req.getSession().getAttribute("manager"); if (null == managerUsername) { return "redirect:/Verwalter/login"; } tdManagerLogService.addLog("edit", "修改分销用户", req); TdUser user = tdUserService.findOne(id); if(null != user){ user.setUpUserOne(tdUserService.findByUsername(username).getId()); } tdUserService.save(user); return "redirect:/Verwalter/user/list"; } //更改用户分销弹窗 @RequestMapping(value = "/list/dialog") public String ListDialog( String keywords, Long categoryId, Integer page, Long priceId, Integer size, Integer total, String __EVENTTARGET, String __EVENTARGUMENT, String __VIEWSTATE, ModelMap map, HttpServletRequest req) { String username = (String) req.getSession().getAttribute("manager"); if (null == username) { return "redirect:/Verwalter/login"; } if (null != __EVENTTARGET) { if (__EVENTTARGET.equalsIgnoreCase("btnPage")) { if (null != __EVENTARGUMENT) { page = Integer.parseInt(__EVENTARGUMENT); } } else if (__EVENTTARGET.equalsIgnoreCase("btnSearch")) { } else if (__EVENTTARGET.equalsIgnoreCase("categoryId")) { } } if (null == page || page < 0) { page = 0; } if (null == size || size <= 0) { size = SiteMagConstant.pageSize; ; } if (null != keywords) { keywords = keywords.trim(); } Page<TdUser> userPage = null; if (null == keywords || "".equalsIgnoreCase(keywords)) { userPage = tdUserService.findByRoleIdOrderByIdDesc(0L, page, size); } else { userPage = tdUserService.searchAndFindByRoleIdOrderByIdDesc(keywords, 0L, page, size); } map.addAttribute("user_page", userPage); // 参数注回 map.addAttribute("page", page); map.addAttribute("size", size); map.addAttribute("total", total); map.addAttribute("keywords", keywords); map.addAttribute("categoryId", categoryId); map.addAttribute("__EVENTTARGET", __EVENTTARGET); map.addAttribute("__EVENTARGUMENT", __EVENTARGUMENT); map.addAttribute("__VIEWSTATE", __VIEWSTATE); // 参数注回 // map.addAttribute("category_list", tdProductCategoryService.findAll()); map.addAttribute("page", page); map.addAttribute("size", size); map.addAttribute("total", total); map.addAttribute("keywords", keywords); map.addAttribute("categoryId", categoryId); map.addAttribute("__EVENTTARGET", __EVENTTARGET); map.addAttribute("__EVENTARGUMENT", __EVENTARGUMENT); map.addAttribute("__VIEWSTATE", __VIEWSTATE); return "/site_mag/dialog_rf_list"; } @RequestMapping(value = "/check", method = RequestMethod.POST) @ResponseBody public Map<String, String> validateForm(String param, Long id) { Map<String, String> res = new HashMap<String, String>(); res.put("status", "n"); if (null == param || param.isEmpty()) { res.put("info", "该字段不能为空"); return res; } // if (null == id) // 新增分类,查找所有 // { // if (null != tdProductCategoryService.findByTitle(param)) { // res.put("info", "已存在同名分类"); // return res; // } // } else // 修改,查找除当前ID的所有 // { // if (null != tdProductCategoryService.findByTitleAndIdNot(param, id)) { // res.put("info", "已存在同名分类"); // return res; // } // } res.put("status", "y"); return res; } private void productCategoryBtnSave(Long[] ids, Long[] sortIds) { if (null == ids || null == sortIds || ids.length < 1 || sortIds.length < 1) { return; } for (int i = 0; i < ids.length; i++) { Long id = ids[i]; TdProductCategory category = tdProductCategoryService.findOne(id); if (sortIds.length > i) { category.setSortId(sortIds[i]); tdProductCategoryService.save(category); } } } private void productCategoryBtnDelete(Long[] ids, Integer[] chkIds) { if (null == ids || null == chkIds || ids.length < 1 || chkIds.length < 1) { return; } for (int chkId : chkIds) { if (chkId >= 0 && ids.length > chkId) { Long id = ids[chkId]; tdProductCategoryService.delete(id); } } } }
/* Copyright (C) 2013-2014, Securifera, Inc All rights reserved. The copyright on this package is held by Securifera, Inc */ package pwnbrew.utilities; import java.net.MalformedURLException; import java.net.URL; import java.security.AllPermission; import java.security.CodeSource; import java.security.Permissions; import java.security.ProtectionDomain; import java.security.cert.Certificate; import java.util.Stack; import java.util.logging.Level; import pwnbrew.log.RemoteLog; public class DynamicClassLoader extends ClassLoader { private Stack classDefStack = new Stack(); private static final String NAME_Class = DynamicClassLoader.class.getSimpleName(); private boolean initialized = false; //================================================================== /** * Constructor */ public DynamicClassLoader(){ super(); } //================================================================== /** * * @return */ public Stack getClassDefStack() { return (Stack) classDefStack.clone(); } //================================================================== /** * * @param passedStack */ public void setClassDefStack(Stack passedStack) { classDefStack = (Stack) passedStack.clone(); } //============================================================= /** * * @param byteArr */ public void loadClass( byte[] byteArr ){ //Load the class and resolve it try { Permissions localPermissions = new Permissions(); localPermissions.add(new AllPermission()); ProtectionDomain localProtectionDomain = new ProtectionDomain(new CodeSource(new URL("file:///"), new Certificate[0]), localPermissions); Class localClass = defineClass(null, byteArr, 0, byteArr.length, localProtectionDomain); resolveClass( localClass ); //If not initialized, load all the other classes if( !initialized ){ Stack tempStack = new Stack(); while(!classDefStack.isEmpty()){ byte[] classBytes = (byte[]) classDefStack.pop(); tempStack.push(classBytes); localClass = defineClass(null, classBytes, 0, classBytes.length, localProtectionDomain); resolveClass( localClass ); } //Set stack classDefStack = tempStack; //Set flag initialized = true; } //Add the new one classDefStack.push(byteArr); } catch( MalformedURLException ex){ RemoteLog.log(Level.SEVERE, NAME_Class, "loadJar()", ex.getMessage(), ex ); } } }
package gr.teicm.icd.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.sql.DataSource; import gr.teicm.icd.data.entities.User; import gr.teicm.icd.dao.UserDAO; public class UserDAOImpl implements UserDAO { private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void insert(User user){ String sql = "INSERT INTO USERS " + "(USER_NAME, USER_PASS, USER_EMAIL, USER_SEX, USER_COUNTRY) VALUES (?, ?, ?, ?, ?)"; Connection conn = null; try { conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, user.getUserName()); ps.setString(2, user.getUserPass()); ps.setString(3, user.getUserEmail()); ps.setString(4, user.getUserSex()); ps.setString(5, user.getUserCountry()); ps.executeUpdate(); ps.close(); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } } public User findByUserId(Long userId){ String sql = "SELECT * FROM USERS WHERE USER_ID = ?"; Connection conn = null; try { conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ps.setLong(1, userId); User user = new User(); ResultSet rs = ps.executeQuery(); if (rs.next()) { user.setUserId(rs.getLong("USER_ID")); user.setUserName(rs.getString("USER_NAME")); user.setUserPass(rs.getString("USER_PASS")); user.setUserEmail(rs.getString("USER_EMAIL")); user.setUserSex(rs.getString("USER_SEX")); user.setUserCountry(rs.getString("USER_COUNTRY")); } rs.close(); ps.close(); return user; } catch (SQLException e) { throw new RuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } } public Boolean checkIfUserNameExist(String userName){ String sql = "SELECT * FROM USERS WHERE USER_NAME = ?"; Connection conn = null; try { conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, userName); ResultSet rs = ps.executeQuery(); if (rs.first()) { rs.close(); ps.close(); return true; } else{ rs.close(); ps.close(); return false; } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } } }
package com.org.spring.boot.amqp.processor.bridge; import com.org.spring.boot.amqp.message.panelInfo.PanelInfoMessageData; import com.org.spring.boot.amqp.processor.Event; import com.org.spring.boot.amqp.processor.Processor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @Slf4j @Service public class PanelInfoProcessor extends Processor<PanelInfoMessageData> { public PanelInfoProcessor() { super(PanelInfoMessageData.class); } @Override public void process(final String message) { super.process(message); } @Override protected Event buildEvent(final PanelInfoMessageData panelInfoMessageData) { return new Event("device.panel.info", panelInfoMessageData.getSerial()); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core.test.tools; import org.junit.jupiter.api.Test; import org.springframework.core.io.ByteArrayResource; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ClassFile}. * * @author Stephane Nicoll */ class ClassFileTests { private final static byte[] TEST_CONTENT = new byte[]{'a'}; @Test void ofNameAndByteArrayCreatesClass() { ClassFile classFile = ClassFile.of("com.example.Test", TEST_CONTENT); assertThat(classFile.getName()).isEqualTo("com.example.Test"); assertThat(classFile.getContent()).isEqualTo(TEST_CONTENT); } @Test void ofNameAndInputStreamResourceCreatesClass() { ClassFile classFile = ClassFile.of("com.example.Test", new ByteArrayResource(TEST_CONTENT)); assertThat(classFile.getName()).isEqualTo("com.example.Test"); assertThat(classFile.getContent()).isEqualTo(TEST_CONTENT); } @Test void toClassNameWithPathToClassFile() { assertThat(ClassFile.toClassName("com/example/Test.class")).isEqualTo("com.example.Test"); } @Test void toClassNameWithPathToTextFile() { assertThatIllegalArgumentException().isThrownBy(() -> ClassFile.toClassName("com/example/Test.txt")); } }
package com.calc.antlr.impl; import com.calc.antlr.service.AntlrCalculator; import com.calc.calculator.Calculator; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.math.BigDecimal; class AntlrCalculatorImplTest { Calculator calculator = new AntlrCalculator(); @Test @DisplayName("single value") void singleValue() { Assertions.assertEquals(new BigDecimal(1), calculator.evaluate("1")); } @Test @DisplayName("trim spaces") void trimSpaces() { Assertions.assertEquals(new BigDecimal(2), calculator.evaluate(" 1 + 1 ")); } @Test @DisplayName("multiplication should go first") void operationsOrder() { Assertions.assertEquals(new BigDecimal(3), calculator.evaluate("1 + 1*2")); } @Test @DisplayName("operation in bracket should go first") void brackets() { Assertions.assertEquals(new BigDecimal(4), calculator.evaluate("(1+1)*2")); } @Test @DisplayName("negative values") void negativeValues() { Assertions.assertEquals(new BigDecimal(-4), calculator.evaluate("(1+1)*(-2)")); Assertions.assertEquals(new BigDecimal(-4), calculator.evaluate("-(1+1)*(2)")); } }
package com.jvschool.svc.impl; import com.jvschool.dao.api.CategoryDAO; import com.jvschool.model.CategoryEntity; import com.jvschool.svc.api.CategoryService; import com.jvschool.dto.CategoryAttribute; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; @Service @Transactional public class CategoryServiceImpl implements CategoryService { @Autowired private CategoryDAO categoryDAO; /** * {@inheritDoc} */ @Override public List<String> getAllProductCategoryNames() { List<String> categoryNames = new ArrayList<>(); categoryDAO.getAllProductCategories().stream() .forEachOrdered(categoryEntity -> categoryNames.add(categoryEntity.getCategoryName())); return categoryNames; } /** * {@inheritDoc} */ @Override public CategoryEntity getProductCategoryByName(String name) { return categoryDAO.getProductCategoryByName(name); } /** * {@inheritDoc} */ @Override public void addProductCategory(String name) { categoryDAO.addProductCategory(name); } /** * {@inheritDoc} */ @Override public void editCategory(CategoryAttribute categoryAttribute) { CategoryEntity categoryEntity = categoryDAO.getProductCategoryByName(categoryAttribute.getCategoryName()); if(categoryEntity==null) { categoryEntity = new CategoryEntity(); } categoryEntity.setCategoryName(categoryAttribute.getEditCategoryName()); categoryDAO.editCategory(categoryEntity); } /** * {@inheritDoc} */ @Override public void removeCategory(String category) { categoryDAO.removeCategory(categoryDAO.getProductCategoryByName(category)); } /** * {@inheritDoc} */ @Override public List<String> getRemovedCategories() { List<String> categoryNames = new ArrayList<>(); categoryDAO.getRemovedCategories().stream() .forEachOrdered(categoryEntity -> categoryNames.add(categoryEntity.getCategoryName())); return categoryNames; } /** * {@inheritDoc} */ @Override public void returnCategory(String category) { categoryDAO.returnCategory(categoryDAO.getProductCategoryByName(category)); } }
package midterm; /* * Time complexity:O(n+m) * Space complexity:O(1) */ class ListNode{ int val; ListNode next; ListNode(){ } ListNode(int val){ this.val = val; } ListNode(int val, ListNode next){ this.val = val; this.next = next; } } public class q1 { public static void main(String[] args) { ListNode n1 = new ListNode(45,new ListNode(77,new ListNode(88,new ListNode(90,new ListNode(95))))); ListNode n2 = new ListNode(23,new ListNode(85,new ListNode(88,new ListNode(93,new ListNode(95))))); System.out.println("Given example is: " + areConverging(n1,n2)); } private static int getLength(ListNode node){ int count = 0; ListNode head = node; while(head != null){ count += 1; head = head.next; } return count; } public static boolean areConverging(ListNode n1, ListNode n2){ int len1 = 0, len2 = 0; len1 = getLength(n1); len2 = getLength(n2); ListNode p1 = n1, p2 = n2; int difference = Math.abs((len1-len2)); for(int i = 0; i < difference;i++){ if(len1 > len2) { p1 = p1.next; } else if(len2 > len1){ p2 = p2.next; } } while(p1!= null && p2 != null){ if(p1 == p2){ return true; } p1 = p1.next; p2 = p2.next; } return false; } }
package com.fumei.bg.mapper.system; import com.fumei.bg.domain.system.SysFile; import java.util.List; /** * @author zkh */ public interface SysFileMapper { /** * 根据主键删除记录 * @param fileId id * @return 删除条目数 */ int deleteByPrimaryKey(Long fileId); /** * 新增记录 * @param record 数据对象 * @return 新增条目数 */ int insert(SysFile record); /** * 新增记录 * @param record 数据对象 * @return 新增条目数 */ int insertSelective(SysFile record); /** * 根据主键查询目标 * @param fileId 主键id * @return 目标数据对象 */ SysFile selectByPrimaryKey(Long fileId); /** * 根据主键修改对象 * @param record 数据对象 * @return 修改记录条目数 */ int updateByPrimaryKeySelective(SysFile record); /** * 根据主键修改对象 * @param record 数据对象 * @return 修改记录条目数 */ int updateByPrimaryKey(SysFile record); /** * 查询文件信息列表 * @param file 条件 * @return 文件列表 */ List<SysFile> selectSysFileList(SysFile file); }
package com.kwik.controllers; import static br.com.caelum.vraptor.view.Results.json; import static br.com.six2six.fixturefactory.Fixture.from; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Spy; import br.com.caelum.vraptor.Result; import br.com.caelum.vraptor.Validator; import br.com.caelum.vraptor.util.test.MockResult; import br.com.caelum.vraptor.util.test.MockValidator; import br.com.caelum.vraptor.validator.ValidationException; import br.com.caelum.vraptor.view.Results; import com.kwik.fixture.load.TemplateLoader; import com.kwik.helper.TestHelper; import com.kwik.models.Product; import com.kwik.service.product.ProductService; public class ProductControllerTest extends TestHelper { private @Spy Result result = new MockResult(); private @Spy Validator validator = new MockValidator(); private @Mock ProductService service; private ProductController controller; private Product product; @Before public void setUp() throws Exception { controller = new ProductController(service, result, validator); product = from(Product.class).gimme(TemplateLoader.ProductTemplate.CAMISETA_BRANCA); } @Test public void shouldIncludeNewProduct() throws Exception { controller.add(product); verify(service).add(product); } @Test(expected = ValidationException.class) public void shouldValidateRequiredFields() throws Exception { controller.add(new Product()); } @Test public void shouldExposeProductCatalog() throws Exception { List<Product> products = from(Product.class).gimme(4, TemplateLoader.ProductTemplate.CAMISETA_PRETA_JA_ASSOCIADA); when(service.listAll()).thenReturn(products); controller.list(); verify(result).use(json()); } @Test public void listProductsShouldBeEmpty() throws Exception { when(service.listAll()).thenReturn(new ArrayList<Product>()); controller.list(); verify(result).use(Results.status()); } }
package lab2.level; import java.util.ArrayList; import java.util.Vector; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Observable; import java.util.Observer; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; public class LevelGUI implements Observer { private Level lv; private Display d; private int standardTransparency = 30;//Denna variabel bestämmer hur transparent rummen ska vara. //Denna konstruktor skapar ett nytt fönster. public LevelGUI(Level level, String name) { this.lv = level; JFrame frame = new JFrame(name); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); d = new Display(lv,1200,1000);//Skapar ett nytt display objekt. frame.getContentPane().add(d); frame.pack(); frame.setLocation(0,0); frame.setVisible(true); lv.addObserver(this);//Lägger till en ny observatör som observerar level klassen. } //Denna metod uppdaterar det grafiska gränsnittet när något i leveln ändras. public void update(Observable arg0, Object arg1) { d.repaint(); } private class Display extends JPanel { public Display(Level fp, int x, int y) { addKeyListener(new Listener()); setBackground(Color.GRAY); setPreferredSize(new Dimension(x+20,y+20)); setFocusable(true); } public void paintComponent(Graphics g) { super.paintComponent(g); for(int i = 0; i < lv.rooms.size(); i++) { Room r = lv.rooms.get(i); paintRooms(g, r); paintConnections(g,r); } } //Denna metod ritar upp rummen som blivit placerad i leveln. private void paintRooms(Graphics g, Room r) { if(lv.getCurrentRoom() == r) {// Om spelaren befiiner sig i det rum som skickas in som parameter. g.setColor(r.floorColor); }else { g.setColor(setTransparancy(r,standardTransparency));//Om spelaren inte befinner sig i det rum som skickas in som parmaeter. } g.fillRect(r.xCoor, r.yCoor, r.xSize, r.ySize); } //Denna metod ritar ut cirklarna som ska representera förbindingarna mellan rummen. private void paintConnections(Graphics g, Room r) { int rY = (int) Math.round(0.1 * r.ySize);//Radien på cirekln i y-led. int rX = (int) Math.round(0.1 * r.xSize); //Radien på cirkeln i x-led. int roomSizeHalfX = r.xCoor+r.xSize/2;//Sparar en ny x-koordinat som är x-koordinaten för rummet adderat med halva längden i x-led för rummet. int roomSizeHalfY = r.yCoor+r.ySize/2;//Sparar en ny y-koordinat som är y-koordinaten för rummet adderat med halva längden i y-led för rummet. //Om det rum som tas som parameter är det rum som spelaren befinner sig i. if(lv.getCurrentRoom() == r) { if(r.northRoom != null && r.northRoom.roomExistsOnLevel == true) { g.setColor(r.northRoom.floorColor); g.fillOval(roomSizeHalfX-rX, r.yCoor-rX , 2*rX, 2*rY); } if(r.southRoom != null && r.southRoom.roomExistsOnLevel == true) { g.setColor(r.southRoom.floorColor); g.fillOval(roomSizeHalfX-rX, (r.yCoor+r.ySize)-rX , 2*rX, 2*rY); } if(r.westRoom != null && r.westRoom.roomExistsOnLevel == true) { g.setColor(r.westRoom.floorColor); g.fillOval(r.xCoor-rX,roomSizeHalfY-rY, 2*rX, 2*rY); } if(r.eastRoom != null && r.eastRoom.roomExistsOnLevel == true){ g.setColor(r.eastRoom.floorColor); g.fillOval(r.xCoor+r.xSize-rX,roomSizeHalfY-rY, 2*rX, 2*rY); } }else {//Om metoden tar ett rum som spelaren ej befinner sig i. if(r.northRoom != null && r.northRoom.roomExistsOnLevel == true) { g.setColor(setTransparancy(r.northRoom, standardTransparency)); g.fillOval(roomSizeHalfX-rX, r.yCoor , 2*rX, 2*rY); } if(r.southRoom != null && r.southRoom.roomExistsOnLevel == true) { g.setColor(setTransparancy(r.southRoom, standardTransparency)); g.fillOval(roomSizeHalfX-rX, (r.yCoor+r.ySize)-2*rX , 2*rX, 2*rY); } if(r.westRoom != null && r.westRoom.roomExistsOnLevel == true) { g.setColor(setTransparancy(r.westRoom, standardTransparency)); g.fillOval(r.xCoor,roomSizeHalfY-rY, 2*rX, 2*rY); } if(r.eastRoom != null && r.eastRoom.roomExistsOnLevel == true){ g.setColor(setTransparancy(r.eastRoom, standardTransparency)); g.fillOval(r.xCoor+r.xSize-2*rX,roomSizeHalfY-rY, 2*rX, 2*rY); } } } /* * Denna metod returnerar exakt samma färg som den färg på golvet i det rum * som tas som parameter i metoden, fast mer transparent. */ private Color setTransparancy(Room r, int transparens) { int red = r.floorColor.getRed(); int green = r.floorColor.getGreen(); int blue = r.floorColor.getBlue(); Color color = new Color(red,green,blue,transparens); return color; } //Denna klass implementerar styrning via tangentbordet. private class Listener implements KeyListener { public void keyPressed(KeyEvent arg0) { } public void keyReleased(KeyEvent arg0) { } //Denna metod reagerar när man trycker på någon knapp på tangentbordet. public void keyTyped(KeyEvent event) { switch (event.getKeyChar()) { case 'w': lv.moveNorth();//Denna metod anropas om "w" trycks ner. break; case 'd': lv.moveEast();//Denna metod anropas om "d" trycks ner. break; case 's': lv.moveSouth();//Denna metod anropas om "s" trycks ner. break; case 'a': lv.moveWest();//Denna metod anropas om "a" trycks ner. break; default: System.out.println("Use w-a-s-d");//Detta skrivs ut om någon annan knapp trycks ner. break; } } } } }
package com.somecompany.customermatches.repository; import java.util.Set; import java.util.UUID; public interface TournamentRepository { Set<UUID> getMatchesIdsForTournaments(Set<UUID> tournamentIds); }
package com.tdr.registrationv3.service.impl.car; import com.tdr.registrationv3.bean.InsuranceBean; import com.tdr.registrationv3.http.utils.Callback; import com.tdr.registrationv3.http.utils.DdcResult; import com.tdr.registrationv3.service.BasePresenter; import com.tdr.registrationv3.service.BaseService; import com.tdr.registrationv3.service.presenter.InsurancePresenter; import java.util.List; import okhttp3.RequestBody; public class InsuranceImpl extends BasePresenter<InsurancePresenter.View> implements InsurancePresenter.Presenter { private BaseService mService; public InsuranceImpl() { this.mService = (BaseService) setRetrofitService(BaseService.class); } @Override public void getNewAndRenewInsurance(String url, RequestBody route) { invoke(mService.getInsurance(url, route), new Callback<DdcResult<List<InsuranceBean>>>() { @Override public void onResponse(DdcResult<List<InsuranceBean>> data) { if (data.getCode() == 0) { mView.loadingSuccessForData(data.getData()); } else { mView.loadingFail(data.getMsg()); } } }); } @Override public void submitData(String url, RequestBody route) { invoke(mService.baseRequest(url, route), new Callback<DdcResult>() { @Override public void onResponse(DdcResult data) { if (data.getCode() == 0) { mView.submitDataSuccess(data.getMsg()); } else { mView.submitDataFail(data.getMsg()); } } }); } }
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sandy.user.service; import java.sql.SQLException; import java.util.List; import java.util.Map; import com.sandy.infrastructure.common.AbstractDateEntity; import com.sandy.infrastructure.util.PagingList; import com.sandy.user.dao.AbstractDao; /** * Abstract Service * @author Sandy * @param <T> * @param <PK> * @since 1.0.0 11th 10 2018 */ public abstract class AbstractService<T extends AbstractDateEntity<PK>, PK> { protected AbstractDao<T, PK> abstractDao; public void setAbstractDao(AbstractDao<T, PK> abstractDao) { this.abstractDao = abstractDao; } public T queryById(PK id) { return abstractDao.queryById(id); } public List<T> queryForList() { return abstractDao.queryForList(); } /** * query page for list * @param criteria * @param fieled * @return PageList<T> */ public PagingList<T> queryPageForList(Map<String, Object> criteria, Integer page, Integer pageSize) { return abstractDao.queryPageForList(criteria, page, pageSize); } public T add(T record) throws SQLException { return abstractDao.add(record); } public T update(T record) throws SQLException { return abstractDao.update(record); } public boolean delete(PK id) { return 0 < abstractDao.deleteById(id); } public boolean delete(T record) { return 0 < abstractDao.deleteById(record.getId()); } }
// SPDX-License-Identifier: BSD-3-Clause // -*- Java -*- // // Copyright (c) 2005, Matthew J. Rutherford <rutherfo@cs.colorado.edu> // Copyright (c) 2005, University of Colorado at Boulder // 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 University of Colorado at Boulder 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.xbill.DNS.utils; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; class Base64Test { @Test void toString_empty() { byte[] data = new byte[0]; String out = base64.toString(data); assertEquals("", out); } @Test void toString_basic1() { byte[] data = {0}; String out = base64.toString(data); assertEquals("AA==", out); } @Test void toString_basic2() { byte[] data = {0, 0}; String out = base64.toString(data); assertEquals("AAA=", out); } @Test void toString_basic3() { byte[] data = {0, 0, 1}; String out = base64.toString(data); assertEquals("AAAB", out); } @Test void toString_basic4() { byte[] data = {(byte) 0xFC, 0, 0}; String out = base64.toString(data); assertEquals("/AAA", out); } @Test void toString_basic5() { byte[] data = {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF}; String out = base64.toString(data); assertEquals("////", out); } @Test void toString_basic6() { byte[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9}; String out = base64.toString(data); assertEquals("AQIDBAUGBwgJ", out); } @Test void formatString_empty1() { String out = base64.formatString(new byte[0], 5, "", false); assertEquals("", out); } @Test void formatString_shorter() { byte[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // "AQIDBAUGBwgJ" (12 chars) String out = base64.formatString(in, 13, "", false); assertEquals("AQIDBAUGBwgJ", out); } @Test void formatString_sameLength() { byte[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // "AQIDBAUGBwgJ" (12 chars) String out = base64.formatString(in, 12, "", false); assertEquals("AQIDBAUGBwgJ", out); } @Test void formatString_oneBreak() { byte[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // "AQIDBAUGBwgJ" (12 chars) String out = base64.formatString(in, 10, "", false); assertEquals("AQIDBAUGBw\ngJ", out); } @Test void formatString_twoBreaks1() { byte[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // "AQIDBAUGBwgJ" (12 chars) String out = base64.formatString(in, 5, "", false); assertEquals("AQIDB\nAUGBw\ngJ", out); } @Test void formatString_twoBreaks2() { byte[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // "AQIDBAUGBwgJ" (12 chars) String out = base64.formatString(in, 4, "", false); assertEquals("AQID\nBAUG\nBwgJ", out); } @Test void formatString_shorterWithPrefix() { byte[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // "AQIDBAUGBwgJ" (12 chars) String out = base64.formatString(in, 13, "!_", false); assertEquals("!_AQIDBAUGBwgJ", out); } @Test void formatString_sameLengthWithPrefix() { byte[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // "AQIDBAUGBwgJ" (12 chars) String out = base64.formatString(in, 12, "!_", false); assertEquals("!_AQIDBAUGBwgJ", out); } @Test void formatString_oneBreakWithPrefix() { byte[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // "AQIDBAUGBwgJ" (12 chars) String out = base64.formatString(in, 10, "!_", false); assertEquals("!_AQIDBAUGBw\n!_gJ", out); } @Test void formatString_twoBreaks1WithPrefix() { byte[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // "AQIDBAUGBwgJ" (12 chars) String out = base64.formatString(in, 5, "!_", false); assertEquals("!_AQIDB\n!_AUGBw\n!_gJ", out); } @Test void formatString_twoBreaks2WithPrefix() { byte[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // "AQIDBAUGBwgJ" (12 chars) String out = base64.formatString(in, 4, "!_", false); assertEquals("!_AQID\n!_BAUG\n!_BwgJ", out); } @Test void formatString_shorterWithPrefixAndClose() { byte[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // "AQIDBAUGBwgJ" (12 chars) String out = base64.formatString(in, 13, "!_", true); assertEquals("!_AQIDBAUGBwgJ )", out); } @Test void formatString_sameLengthWithPrefixAndClose() { byte[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // "AQIDBAUGBwgJ" (12 chars) String out = base64.formatString(in, 12, "!_", true); assertEquals("!_AQIDBAUGBwgJ )", out); } @Test void formatString_oneBreakWithPrefixAndClose() { byte[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // "AQIDBAUGBwgJ" (12 chars) String out = base64.formatString(in, 10, "!_", true); assertEquals("!_AQIDBAUGBw\n!_gJ )", out); } @Test void formatString_twoBreaks1WithPrefixAndClose() { byte[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // "AQIDBAUGBwgJ" (12 chars) String out = base64.formatString(in, 5, "!_", true); assertEquals("!_AQIDB\n!_AUGBw\n!_gJ )", out); } @Test void formatString_twoBreaks2WithPrefixAndClose() { byte[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // "AQIDBAUGBwgJ" (12 chars) String out = base64.formatString(in, 4, "!_", true); assertEquals("!_AQID\n!_BAUG\n!_BwgJ )", out); } @Test void fromString_empty1() { byte[] data = new byte[0]; byte[] out = base64.fromString(""); assertArrayEquals(new byte[0], out); } @Test void fromString_basic1() { byte[] exp = {0}; byte[] out = base64.fromString("AA=="); assertArrayEquals(exp, out); } @Test void fromString_basic2() { byte[] exp = {0, 0}; byte[] out = base64.fromString("AAA="); assertArrayEquals(exp, out); } @Test void fromString_basic3() { byte[] exp = {0, 0, 1}; byte[] out = base64.fromString("AAAB"); assertArrayEquals(exp, out); } @Test void fromString_basic4() { byte[] exp = {(byte) 0xFC, 0, 0}; byte[] out = base64.fromString("/AAA"); assertArrayEquals(exp, out); } @Test void fromString_basic5() { byte[] exp = {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF}; byte[] out = base64.fromString("////"); assertArrayEquals(exp, out); } @Test void fromString_basic6() { byte[] exp = {1, 2, 3, 4, 5, 6, 7, 8, 9}; byte[] out = base64.fromString("AQIDBAUGBwgJ"); assertArrayEquals(exp, out); } @Test void fromString_invalid1() { byte[] out = base64.fromString("AAA"); assertNull(out); } @Test void fromString_invalid2() { byte[] out = base64.fromString("AA"); assertNull(out); } @Test void fromString_invalid3() { byte[] out = base64.fromString("A"); assertNull(out); } @Test void fromString_invalid4() { byte[] out = base64.fromString("BB=="); assertNull(out); } @Test void fromString_invalid5() { byte[] out = base64.fromString("BBB="); assertNull(out); } }
package com.xebia.entities; import lombok.Data; import javax.persistence.*; @Data @Entity public class Location { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "covid_details_id") private CovidDetails covidDetails; }
package com.rocky.shiro; import org.apache.shiro.crypto.hash.Md5Hash; public class Shiro_Md5Pwd { public static void main(String[] args) { Md5Hash md5Pwd = new Md5Hash("admin", "admin", 2); // Md5Hash md5Pwd = new Md5Hash("admin", "", 2); System.out.println(md5Pwd.toString()); } }
package by.pvt.herzhot.pojos; import java.io.Serializable; /** * @author Herzhot * @version 1.0 * 03.06.2016 */ public interface Entity extends Serializable { }
package com.cedo.cat2shop.service.impl; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.cedo.cat2shop.dao.CateDao; import com.cedo.cat2shop.model.Cate; import com.cedo.cat2shop.service.CateService; import com.cedo.common.http.HttpResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.sql.Timestamp; /** * @Author chendong * @date 19-3-13 下午7:33 */ @Service public class CateServiceImpl implements CateService { @Autowired private CateDao cateDao; @Override public HttpResult list(Integer current, Integer size) { IPage<Cate> page = new Page<>(current, size); Wrapper<Cate> wrapper = new QueryWrapper<>(); cateDao.selectPage(page, wrapper); return HttpResult.ok(page); } @Override public HttpResult findById(Long id) { return HttpResult.ok(cateDao.selectById(id)); } @Override public HttpResult add(Cate cate) { cate.setCreatedTime(new Timestamp(System.currentTimeMillis())); return cateDao.insert(cate)>0 ?HttpResult.ok("添加成功") :HttpResult.error("添加失败"); } @Override public HttpResult update(Cate cate) { return cateDao.updateById(cate)>0 ?HttpResult.ok("修改成功") :HttpResult.error("修改失败"); } @Override public HttpResult delete(Long id) { return cateDao.deleteById(id) > 0 ?HttpResult.ok("删除成功") :HttpResult.error("删除失败"); } @Override public String findCateNameById(Integer cateId) { return cateDao.findCateNameById(cateId); } }
import java.util.Scanner; public class EmployeeTest { /** this is a test class*/ public static void main( String args[] ){ //we are in the the main Employee firstemployee=new Employee(); Employee secondemployee=new Employee(); Scanner sc=new Scanner(System.in); String first; String last; double salary; System.out.println("Enter First Name of First Employee: "); first=sc.next(); firstemployee.setName(first); System.out.println("Enter Last Name of First Employee: "); last=sc.next(); firstemployee.setLastname(last); System.out.println( "Enter Monthly Salary of First Employee: " ); salary=sc.nextDouble(); firstemployee.setSalary(salary); System.out.println("Enter First Name of Second Employee: "); first=sc.next(); secondemployee.setName(first); System.out.println("Enter Last Name of Second Employee: "); last=sc.next(); secondemployee.setLastname(last); System.out.println( "Enter Monthly Salary of Second Employee: " ); salary=sc.nextDouble(); secondemployee.setSalary(salary); System.out.println("First Employee's Full Name and Yearly Salary.\n"); System.out.println( firstemployee.getName() + " " + firstemployee.getLastname() + " " + firstemployee.getSalary() * 12 + "\n" ); System.out.println("Second Employee's Full Name and Yearly Salary.\n"); System.out.println( secondemployee.getName() + " " + secondemployee.getLastname() + " " + secondemployee.getSalary() * 12 + "\n" ); System.out.println("Displaying New Total Annual Salary After 10% Raise.\n"); System.out.println( firstemployee.getName() + " " + firstemployee.getLastname() + " " + (firstemployee.getSalary()*1.10 * 12 + "\n")); System.out.println( secondemployee.getName() + " " + secondemployee.getLastname() + " " + (secondemployee.getSalary()*1.10 * 12 + "\n")); } }
package com.an.scone.vo; import java.util.ArrayList; public class NewsInfo { private String lastBuildDate; private String total; private String display; private ArrayList<NewsItem> items; public NewsInfo(){} public NewsInfo(String lastBuildDate, String total, String display, ArrayList<NewsItem> items) { this.lastBuildDate = lastBuildDate; this.total = total; this.display = display; this.items = items; } public String getLastBuildDate() { return lastBuildDate; } public void setLastBuildDate(String lastBuildDate) { this.lastBuildDate = lastBuildDate; } public String getTotal() { return total; } public void setTotal(String total) { this.total = total; } public String getDisplay() { return display; } public void setDisplay(String display) { this.display = display; } public ArrayList<NewsItem> getItems() { return items; } public void setItems(ArrayList<NewsItem> items) { this.items = items; } @Override public String toString() { return "NewsInfo{" + "lastBuildDate='" + lastBuildDate + '\'' + ", total='" + total + '\'' + ", display='" + display + '\'' + ", items=" + items + '}'; } }
package com.lenovohit.ssm.mng.web.rest; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import org.apache.http.protocol.RequestDate; import org.springframework.beans.factory.annotation.Autowired; 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.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.lenovohit.core.manager.GenericManager; import com.lenovohit.core.utils.DateUtils; import com.lenovohit.core.web.MediaTypes; import com.lenovohit.core.web.utils.Result; import com.lenovohit.core.web.utils.ResultUtils; import com.lenovohit.ssm.base.web.rest.SSMBaseRestController; import com.lenovohit.ssm.payment.model.Order; import com.lenovohit.ssm.payment.model.Settlement; /** * 统计 * @author victor * */ @RestController @RequestMapping("/ssm/statistics") public class StatisticsController extends SSMBaseRestController { @Autowired private GenericManager<Settlement, String> settlementManager; @Autowired private GenericManager<Order, String> orderManager; @RequestMapping(value = "/ssmSettlement/channel/{startDate}/{endDate}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result ssmSumByChannel(@PathVariable("startDate") String startDate, @PathVariable("endDate") String endDate) { List<Object> settlements = (List<Object>)settlementManager.findBySql("select pay_channel_code, sum(amt) from ssm_settlement where status = '0' and create_time < ? and create_time > ? group by pay_channel_code", startDate, endDate); return ResultUtils.renderSuccessResult(settlements); } @RequestMapping(value = "/loadCardCount", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8) public Result loadCardCount(){ try{ Map<String, List<Object>> result = getCardCount(); return ResultUtils.renderSuccessResult(result); }catch(Exception e){ e.printStackTrace(); return ResultUtils.renderFailureResult("本年度发卡量信息出错!"); } } @RequestMapping(value="/loadDepositAcount/{date}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result loadDepositAcount(@PathVariable("date") String date){ try{ Map<String, Object> result = getDepositAcount(date); return ResultUtils.renderSuccessResult(result); }catch(Exception e){ e.printStackTrace(); return ResultUtils.renderFailureResult("本年度预存信息出错!"); } } @RequestMapping(value="/loadPayFeeAcount", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8) public Result loadPayFeeAcount(){ try{ Map<String, List<Object>> result = getPayFeeCount(); return ResultUtils.renderSuccessResult(result); }catch(Exception e){ e.printStackTrace(); return ResultUtils.renderFailureResult("本年度缴费信息出错!"); } } /** * 获取预存笔数,包括现金,微信,支付宝,银行卡 * @return */ private Map<String, Object> getDepositAcount(String date) { if("1".equals(date)){ date = DateUtils.getCurrentYear()+"-"+DateUtils.getCurrentMonth(); } String sql = " select 'cash',count(order_id) from ssm_settlement where (pay_channel_code = '0000')and settle_type='SP' and to_char(create_time, 'yyyy-mm') = '"+date+"'" + " union all" + " select 'weChat',count(order_id) from ssm_settlement where (pay_channel_code = '9998')and settle_type='SP' and to_char(create_time, 'yyyy-mm') = '"+date+"'" + " union all" + " select 'alipay',count(order_id) from ssm_settlement where (pay_channel_code = '9999')and settle_type='SP' and to_char(create_time, 'yyyy-mm') = '"+date+"'" + " union all" + " select 'bankCard',count(order_id) from ssm_settlement where (pay_channel_code = '0306' or pay_channel_code = '0308')and settle_type='SP' and to_char(create_time, 'yyyy-mm') = '"+date+"'"; List list = orderManager.findBySql(sql); Map<String, Object> map = new HashMap<String, Object>(); for(Object object : list){ Object[] objects = (Object[]) object; map.put((String) objects[0], objects[1]); } return map; } /** * 发卡量统计 * @return */ private Map<String, List<Object>> getCardCount(){ String sql = "select 'issue' ,to_char(create_time ,'yyyy-mm') riqi,count(1) account," + " biz_type type from ssm_order" + " where (biz_type ='06') and status = '0'" + " group by biz_type ,to_char(create_time ,'yyyy-mm') " + " union all " + " select 'reissue' ,to_char(create_time ,'yyyy-mm') riqi,count(1) account," + " biz_type type from ssm_order " + " where (biz_type ='05') and status = '0'" + " group by biz_type ,to_char(create_time ,'yyyy-mm') " + " order by riqi desc "; List list = orderManager.findBySql(sql); Map<String, List<Object>> map = getMap(list); return map; } /** * 缴费统计 * @return */ private Map<String, List<Object>> getPayFeeCount(){ String sql = "select 'miamt',to_char(create_time ,'yyyy-mm') time, sum(mi_amt)from ssm_order where order_desc = '门诊收费' and order_type = 'OP'" + " group by (to_char(create_time,'yyyy-mm')) " + " union all" + " select 'selfamt',to_char(create_time ,'yyyy-mm') time, sum(self_amt)from ssm_order where order_desc = '门诊收费' and order_type = 'OP'" + " group by (to_char(create_time,'yyyy-mm')) order by time desc"; List list = orderManager.findBySql(sql); Map<String, List<Object>> map = getMap(list); return map; } private Map<String, List<Object>> getMap(List rtn) { String year = DateUtils.getCurrentYear(); Map<String,TreeMap<String,Object>> mapView = new HashMap<>(); if(rtn!=null && rtn.size()>0){ for(Object o:rtn){ Object [] oList = (Object[]) o; String feeType = oList[0].toString(); TreeMap<String,Object> tMap = mapView.get(feeType); if(tMap!=null){ tMap.put(oList[1].toString(), oList[2]); }else{ TreeMap<String,Object> tmpMap = new TreeMap<String,Object>(); tmpMap.put(year+"-01", "0"); tmpMap.put(year+"-02", "0"); tmpMap.put(year+"-03", "0"); tmpMap.put(year+"-04", "0"); tmpMap.put(year+"-05", "0"); tmpMap.put(year+"-06", "0"); tmpMap.put(year+"-07", "0"); tmpMap.put(year+"-08", "0"); tmpMap.put(year+"-09", "0"); tmpMap.put(year+"-10", "0"); tmpMap.put(year+"-11", "0"); tmpMap.put(year+"-12", "0"); tmpMap.put(oList[1].toString(), oList[2]); mapView.put(feeType, tmpMap); } } } Map<String,List<Object>> mapList = new HashMap<>(); for (Entry<String, TreeMap<String, Object>> entry : mapView.entrySet()) { String key = entry.getKey(); List<Object> oList = new ArrayList<>(); for(Entry<String, Object> m : entry.getValue().entrySet()){ oList.add(m.getValue()); } mapList.put(key, oList); } return mapList; } }
package iteration03.fr.agh.rule; import iteration03.fr.agh.domain.Grid; import iteration03.fr.agh.domain.State; /** * @author elm * */ public class LifeRule implements Rule { @Override public State apply(int index, Grid grid) { if (grid.isLiving(index - 1) && grid.isLiving(index) && grid.isLiving(index + 1)) { return State.ALIVE; } return State.DEAD; } }
package com.sparshik.yogicapple.ui.events; import android.Manifest; import android.app.AlertDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.firebase.geofire.GeoFire; import com.firebase.geofire.GeoLocation; import com.firebase.geofire.GeoQuery; import com.firebase.geofire.GeoQueryEventListener; import com.google.android.gms.common.GooglePlayServicesNotAvailableException; import com.google.android.gms.common.GooglePlayServicesRepairableException; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.ui.PlacePicker; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.sparshik.yogicapple.R; import com.sparshik.yogicapple.model.Event; import com.sparshik.yogicapple.ui.BaseActivity; import com.sparshik.yogicapple.utils.Constants; import com.sparshik.yogicapple.utils.PermissionUtils; import java.util.HashMap; import java.util.Map; import timber.log.Timber; public class EventsActivity extends BaseActivity implements OnMapReadyCallback, GoogleMap.OnMyLocationButtonClickListener, ActivityCompat.OnRequestPermissionsResultCallback, GoogleMap.OnCameraChangeListener, GeoQueryEventListener { private static final int PLACE_PICKER_REQUEST = 1; private static final int LOCATION_PERMISSION_REQUEST_CODE = 2; boolean mapReady = false; private GoogleMap mMap; private boolean mPermissionDenied = false; private GeoFire mGeoFire; private GeoQuery mGeoQuery; private Map<String, Marker> markers; private Circle mSearchCircle; private DatabaseReference mEventsRef; private int mEventCount; @Override public Resources getResources() { return super.getResources(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_events); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mEventCount = 0; // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); DatabaseReference geoRef = FirebaseDatabase.getInstance().getReferenceFromUrl(Constants.FIREBASE_URL_GEOFIRE); mGeoFire = new GeoFire(geoRef); mGeoQuery = mGeoFire.queryAtLocation(Constants.INITIAL_CENTER, 1); markers = new HashMap<>(); mEventsRef = FirebaseDatabase.getInstance().getReferenceFromUrl(Constants.FIREBASE_URL_EVENTS); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PLACE_PICKER_REQUEST) { if (resultCode == RESULT_OK) { Place place = PlacePicker.getPlace(data, this); String toastMsg = getString(R.string.place_message,place.getName()); Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show(); Timber.i("Places: " + place.getLatLng() + "\n" + place.getAddress() + "\n" + place.getAddress()); CameraPosition updatedPlace = CameraPosition.builder() .target(place.getLatLng()) .zoom(14) .bearing(0) .tilt(45) .build(); flyTo(updatedPlace); } } } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mapReady = true; mMap = googleMap; LatLng latLngCenter = new LatLng(Constants.INITIAL_CENTER.latitude, Constants.INITIAL_CENTER.longitude); mSearchCircle = mMap.addCircle(new CircleOptions().center(latLngCenter).radius(1000)); mSearchCircle.setFillColor(Color.argb(66, 255, 0, 255)); mSearchCircle.setStrokeColor(Color.argb(66, 0, 0, 0)); mMap.setOnMyLocationButtonClickListener(this); enableMyLocation(); CameraPosition initialCamera = CameraPosition.builder() .target(latLngCenter) .zoom(14) .bearing(0) .tilt(14) .build(); mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() { @Override public void onMapLongClick(LatLng latLng) { if (latLng != null) { Timber.i("On Click latlng: " + latLng.toString()); Intent intent = new Intent(EventsActivity.this, AddEventActivity.class); intent.putExtra(Constants.KEY_LATITUDE, latLng.latitude); intent.putExtra(Constants.KEY_LONGITUDE, latLng.longitude); startActivity(intent); } } }); mMap.setOnCameraChangeListener(this); flyTo(initialCamera); } private void flyTo(CameraPosition target) { mMap.moveCamera(CameraUpdateFactory.newCameraPosition(target)); } /** * Override onOptionsItemSelected to use menu_event instead of BaseActivity menu * * @param menu */ @Override public boolean onCreateOptionsMenu(Menu menu) { /* Inflate the menu; this adds items to the action bar if it is present. */ getMenuInflater().inflate(R.menu.menu_event, menu); return true; } /** * Override onOptionsItemSelected to add action_search only to the EventsActivity * * @param item */ @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_search) { openPlacePicker(); return true; } return super.onOptionsItemSelected(item); } public void openPlacePicker() { try { PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder(); startActivityForResult(builder.build(EventsActivity.this), PLACE_PICKER_REQUEST); } catch (GooglePlayServicesRepairableException e) { GooglePlayServicesUtil .getErrorDialog(e.getConnectionStatusCode(), EventsActivity.this, 0); } catch (GooglePlayServicesNotAvailableException e) { Toast.makeText(EventsActivity.this, getString(R.string.play_service_unavailable), Toast.LENGTH_LONG) .show(); } } @Override public boolean onMyLocationButtonClick() { return false; } /** * Enables the My Location layer if the fine location permission has been granted. */ private void enableMyLocation() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Permission to access the location is missing. PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE, Manifest.permission.ACCESS_FINE_LOCATION, true); } else if (mMap != null) { // Access to the location has been granted to the app. mMap.setMyLocationEnabled(true); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) { return; } if (PermissionUtils.isPermissionGranted(permissions, grantResults, Manifest.permission.ACCESS_FINE_LOCATION)) { // Enable the my location layer if the permission has been granted. enableMyLocation(); } else { // Display the missing permission error dialog when the fragments resume. mPermissionDenied = true; } } @Override protected void onResumeFragments() { super.onResumeFragments(); if (mPermissionDenied) { // Permission was not granted, display error dialog. showMissingPermissionError(); mPermissionDenied = false; } } /** * Displays a dialog with error message explaining that the location permission is missing. */ private void showMissingPermissionError() { PermissionUtils.PermissionDeniedDialog .newInstance(true).show(getSupportFragmentManager(), "dialog"); } @Override protected void onStop() { super.onStop(); // remove all event listeners to stop updating in the background mGeoQuery.removeAllListeners(); for (Marker marker : this.markers.values()) { marker.remove(); } this.markers.clear(); } @Override protected void onStart() { super.onStart(); // add an event listener to start updating locations again mGeoQuery.addGeoQueryEventListener(this); } @Override public void onKeyEntered(final String key, final GeoLocation location) { DatabaseReference markerDataRef = mEventsRef.child(key); markerDataRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Event eventData = dataSnapshot.getValue(Event.class); if (eventData != null) { // Add a new marker to the map final Marker marker = mMap.addMarker(new MarkerOptions() .position(new LatLng(location.latitude, location.longitude)) .title(eventData.getTitle()) .snippet(eventData.getEventDesc())); marker.setTag(0); final String url = eventData.getEventUrl(); markers.put(key, marker); mEventCount = mEventCount + 1; updateTitle(); // loadMarkerIcon(marker, eventData.getEventImageUrl()); mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() { @Override public void onInfoWindowClick(Marker markerInt) { Intent browser = new Intent(Intent.ACTION_VIEW); browser.setData(Uri.parse(url)); startActivity(browser); } }); } } @Override public void onCancelled(DatabaseError databaseError) { } }); Timber.d(key); } @Override public void onKeyExited(String key) { // Remove any old marker Marker marker = this.markers.get(key); if (marker != null) { marker.remove(); this.markers.remove(key); mEventCount = mEventCount - 1; updateTitle(); } } @Override public void onKeyMoved(String key, GeoLocation location) { // Move the marker Marker marker = this.markers.get(key); if (marker != null) { this.animateMarkerTo(marker, location.latitude, location.longitude); } } @Override public void onGeoQueryReady() { } @Override public void onGeoQueryError(DatabaseError error) { new AlertDialog.Builder(this) .setTitle(getString(R.string.geofire_dialog_header)) .setMessage(getString(R.string.geofire_error,error.getMessage())) .setPositiveButton(android.R.string.ok, null) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } @Override public void onCameraChange(CameraPosition cameraPosition) { // Update the search criteria for this geoQuery and the circle on the map LatLng center = cameraPosition.target; double radius = zoomLevelToRadius(cameraPosition.zoom); mSearchCircle.setCenter(center); mSearchCircle.setRadius(radius); mGeoQuery.setCenter(new GeoLocation(center.latitude, center.longitude)); // radius in km mGeoQuery.setRadius(radius / 1000); } private double zoomLevelToRadius(double zoomLevel) { // Approximation to fit circle into view return 16384000 / Math.pow(2, zoomLevel); } // Animation handler for old APIs without animation support private void animateMarkerTo(final Marker marker, final double lat, final double lng) { final Handler handler = new Handler(); final long start = SystemClock.uptimeMillis(); final long DURATION_MS = 3000; final Interpolator interpolator = new AccelerateDecelerateInterpolator(); final LatLng startPosition = marker.getPosition(); handler.post(new Runnable() { @Override public void run() { float elapsed = SystemClock.uptimeMillis() - start; float t = elapsed / DURATION_MS; float v = interpolator.getInterpolation(t); double currentLat = (lat - startPosition.latitude) * v + startPosition.latitude; double currentLng = (lng - startPosition.longitude) * v + startPosition.longitude; marker.setPosition(new LatLng(currentLat, currentLng)); // if animation is not finished yet, repeat if (t < 1) { handler.postDelayed(this, 16); } } }); } private void loadMarkerIcon(final Marker marker, String ImageUrl) { Glide.with(this).load(ImageUrl) .asBitmap() .override(100, 100) .centerCrop().into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) { BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(bitmap); marker.setIcon(icon); } }); } private void updateTitle() { if (mEventCount != 0) { setTitle(getString(R.string.title_activity_events) + " (" + mEventCount + ")"); } else { setTitle(getString(R.string.title_activity_events)); } } }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author Brennan Ward * * Google FooBar Level 4: Free the Bunny Prisoners. * Every door requires N keys, and we have B bunnies. * We need to know the combinations such that we can distribute keys so that any Z of the B bunnies can open the door. */ public class FreeBunnies { /** * Input guarantees: * bunnies >= required * bunnies is within [1-9] * required is within [1-9] * * In the case where bunnies == required, we return an array of single-element arrays of increasing values. * In the case where required == 1, we return an array of single-element arrays of zeroes. * What's complicated is the case where neither of these is true. * In this final case, we have (bunnies, required - 1) (as a binomial coefficient) keys. * Then, there are bunnies - required + 1 copies of each key. * Each bunny holds (keys * keyCopies / bunnies) keys. */ public static int[][] solution(int bunnies, int required) { int keys = binomCoeff(bunnies, required - 1); int keyCopies = bunnies - required + 1; Bunny[] bunList = new Bunny[bunnies]; for (int i = 0; i < bunnies; i++) bunList[i] = new Bunny(); List<Bunny[]> combos = new ArrayList<>(); combinations(bunList, keyCopies, 0, new Bunny[keyCopies], combos); for (int i = 0; i < keys; i++) { for (Bunny b : combos.get(i)) b.keys.add(i); } return toOutput(bunList); } static int[][] toOutput(Bunny[] bunnies) { int[][] out = new int[bunnies.length][bunnies[0].keys.size()]; for (int i = 0; i < bunnies.length; i++) { List<Integer> keys = bunnies[i].keys; for (int j = 0; j < keys.size(); j++) { out[i][j] = keys.get(j); } } return out; } private static class Bunny { List<Integer> keys = new ArrayList<>(); @Override public String toString() { return "Bunny: " + Arrays.toString(keys.toArray()); } } public static int binomCoeff(int m, int n) { return factorial(m) / (factorial(n) * factorial(m - n)); } public static int factorial(int n) { int fac = 1; for (int i = 2; i <= n; i++) { fac *= i; } return fac; } static void combinations(Bunny[] arr, int len, int startPosition, Bunny[] result, List<Bunny[]> combos) { if (len == 0) { combos.add(Arrays.copyOf(result, result.length)); return; } for (int i = startPosition; i <= arr.length - len; i++) { result[result.length - len] = arr[i]; combinations(arr, len - 1, i + 1, result, combos); } } }
package dto; import java.util.*; public class Tree { private Person root; private List<Chain> chains; private List<Person> where_update; private final List<Person> waitingList; private Chain[] top_chains; private int top_chain_weight; private int potential_top_chain_weight; private int last_update; public Tree(Person root) { this.root = root; this.root.setWeight(10); this.root.setTree_in(this); this.root.setIn_the_tree(true); top_chains = new Chain[3]; chains = new ArrayList<>(); top_chains[0] = new Chain(root, root); chains.add(top_chains[0]); top_chain_weight = 10; potential_top_chain_weight = 10; where_update = new ArrayList<>(); where_update.add(root); waitingList = new ArrayList<>(); last_update = root.getDiagnosed_ts(); } @Override public String toString() { return "Tree{" + "chains=" + chains + '}'; } public void addPersonToTree(Person new_person, Person contaminated_by) { contaminated_by.addInfected(new_person); new_person.setContaminated_by(contaminated_by); new_person.setWeight(contaminated_by.getWeight() + 10); new_person.setTree_in(this); new_person.setIn_the_tree(true); if (top_chain_weight < new_person.getWeight()) { top_chain_weight = new_person.getWeight(); potential_top_chain_weight = new_person.getWeight(); } if (contaminated_by.getInfect().size() == 1) { for (Chain c : chains) { if (c.getEnd().equals(contaminated_by)) { c.setWeight(new_person.getWeight()); c.setEnd(new_person); if (!c.equals(top_chains[0]) && !c.equals(top_chains[1]) && !c.equals(top_chains[2])) { updateTopChains(c); } else { sortTopChains(); } } } } else { Chain c = new Chain(root, new_person); chains.add(c); updateTopChains(c); } } public void updateTree(int actual_ts) { chains.clear(); top_chains = new Chain[3]; // Update only where it is needed List<Person> where_update_now = new ArrayList<>(where_update); where_update.clear(); for (Person p : where_update_now) { p.update(actual_ts, 0, root, chains, true); } top_chain_weight = 0; // Remove chains with weight = 0 and get top chain weight ListIterator<Chain> iterator = chains.listIterator(); while (iterator.hasNext()) { Chain c = iterator.next(); top_chain_weight = Integer.max(top_chain_weight, c.getWeight()); if (c.getEnd().getWeight() == 0) { deleteChain(c.getEnd()); iterator.remove(); } else { updateTopChains(c); } } potential_top_chain_weight = top_chain_weight; last_update = actual_ts; } // Recursive method (Bottom to top) public void deleteChain(Person p) { if (p.getInfect().isEmpty()) { if (!p.equals(root)) { p.getContaminated_by().getInfect().remove(p); deleteChain(p.getContaminated_by()); } else { this.root = null; } } } public void deleteTree() { for (Person p : where_update) { for (Person infect : p.getInfect()) { PeopleHashMap.removePersonFromMap(infect); } PeopleHashMap.removePersonFromMap(p); } } public void addPersonToWaiting(Person p) { p.setTree_in(this); p.setIn_the_tree(false); waitingList.add(p); potential_top_chain_weight += 10; last_update = p.getDiagnosed_ts(); } public int getWeightOfChainEndingWith(Person end) { for (Chain c : chains) { if (c.getEnd().equals(end)) { return c.getWeight(); } } return 0; } public void updateTopChains(Chain c) { if (top_chains[0] == null || c.compareTo(top_chains[0]) > 0) { top_chains[2] = top_chains[1]; top_chains[1] = top_chains[0]; top_chains[0] = c; } else if (top_chains[1] == null || c.compareTo(top_chains[1]) > 0) { top_chains[2] = top_chains[1]; top_chains[1] = c; } else if (top_chains[2] == null || c.compareTo(top_chains[2]) > 0) { top_chains[2] = c; } } private void sortTopChains() { if (top_chains[1] != null) { if (top_chains[1].compareTo(top_chains[0]) > 0) { Chain temp = top_chains[0]; top_chains[0] = top_chains[1]; top_chains[1] = temp; } else if (top_chains[2] != null) { if (top_chains[2].compareTo(top_chains[1]) > 0) { if (top_chains[2].compareTo(top_chains[0]) > 0) { Chain temp = top_chains[0]; top_chains[0] = top_chains[2]; top_chains[2] = top_chains[1]; top_chains[1] = temp; } else { Chain temp = top_chains[1]; top_chains[1] = top_chains[2]; top_chains[2] = temp; } } } } } // Generated method public List<Chain> getChains() { return chains; } public List<Person> getWhere_update() { return where_update; } public List<Person> getWaitingList() { return waitingList; } public int getPotential_top_chain_weight() { return potential_top_chain_weight; } public int getLast_update() { return last_update; } public Chain[] getTop_chains() { return top_chains; } }
package Java; //parent_10234-01243_child Method public class ChildM extends ParentM { public void method() { super.method1(1); super.method(); super.method2(1,2); super.method3(1,2,3); super.method4(1,2,3,4); System.out.println(" Child Default parameterized Method "); } public void method1(int a) { this.method(); System.out.println(" Child 01 parameterized Method"); } public void method2(int a, int b) { this.method1(1); System.out.println(" Child 02 parameterized Method"); } public void method3(int a, int b, int c) { this.method4(1, 2, 3, 4); System.out.println(" Child 03 parameterized Method"); } public void method4(int a, int b, int c , int d) { this.method2(1, 2); System.out.println(" Child 04 parameterized Method"); } public static void main(String[] args) { ChildM ref=new ChildM(); ref.method3(1,2,3); } }
package kr.or.ddit.projectRegist; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import kr.or.ddit.interview.service.IInterviewService; import kr.or.ddit.project.service.IProjectService; import kr.or.ddit.vo.ProjectVO; import kr.or.ddit.vo.newsboardVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/user/projectRegist/") public class ProjectRegistController { @Autowired private IProjectService projectService; @Autowired private IInterviewService interviewService; @RequestMapping("project_1") public ModelAndView projectForm(HttpServletRequest request, ModelAndView modelAndView, String mem_id) throws Exception{ modelAndView.addObject("breadcrumb_title", "프로젝트"); modelAndView.addObject("breadcrumb_first", "프로젝트"); // modelAndView.addObject("breadcrumb_first_url", request.getContextPath() + "/user/project/project.do?mem_id=" + mem_id); modelAndView.addObject("breadcrumb_second", "프로젝트 등록"); Map<String, String> params = new HashMap<String, String>(); params.put("mem_id", mem_id); //Map<String, String> readNotProject = projectService.readNotProject(params); //modelAndView.addObject("readNotProject", readNotProject); modelAndView.setViewName("user/projectRegist/project_1"); return modelAndView; } @RequestMapping("project_2") public ModelAndView projectReady(HttpServletRequest request, ModelAndView modelAndView, String mem_id, String project_clientinformation, String project_clientintroduce, String project_processstatus, String project_processcategory, String project_title, String endStatus, String endProject_no) throws Exception{ modelAndView.addObject("breadcrumb_title", "프로젝트"); modelAndView.addObject("breadcrumb_first", "프로젝트"); modelAndView.addObject("breadcrumb_second", "프로젝트 등록"); if (endStatus == null) { Map<String, String> params = new HashMap<String, String>(); params.put("mem_id", mem_id); params.put("project_clientinformation", project_clientinformation); params.put("project_clientintroduce", project_clientintroduce); params.put("project_processstatus", project_processstatus); params.put("project_processcategory", project_processcategory); params.put("project_title", project_title); String project_no = projectService.insertProjectInfo(params); this.projectService.insertProjectParticipants(params); modelAndView.addObject("project_no", project_no); } else { modelAndView.addObject("project_no", endProject_no); } modelAndView.setViewName("user/projectRegist/project_2"); return modelAndView; } @RequestMapping("project_3") public ModelAndView project3(HttpServletRequest request, ModelAndView modelAndView, String project_readystatus, String project_reference, String project_no, String endStatus, String endProject_no) throws Exception{ modelAndView.addObject("breadcrumb_title", "프로젝트"); modelAndView.addObject("breadcrumb_first", "프로젝트"); modelAndView.addObject("breadcrumb_second", "프로젝트 등록"); if (endStatus == null) { Map<String, String> params = new HashMap<String, String>(); params.put("project_no", project_no); params.put("project_readystatus", project_readystatus); params.put("project_reference", project_reference); int chk = projectService.insertProjectReady(params); modelAndView.addObject("project_no", project_no); } else { modelAndView.addObject("project_no", endProject_no); } modelAndView.setViewName("user/projectRegist/project_3"); return modelAndView; } @RequestMapping("project_4") public ModelAndView project4(HttpServletRequest request, ModelAndView modelAndView, String project_no, String project_currentstatus, String project_technologies, String endStatus, String endProject_no) throws Exception{ modelAndView.addObject("breadcrumb_title", "프로젝트"); modelAndView.addObject("breadcrumb_first", "프로젝트"); modelAndView.addObject("breadcrumb_second", "프로젝트 등록"); if (endStatus == null) { Map<String, String> params = new HashMap<String, String>(); params.put("project_no", project_no); params.put("project_currentstatus", project_currentstatus); params.put("project_technologies", project_technologies); int chk = projectService.insertProjectDetail(params); modelAndView.addObject("project_no", project_no); } else { modelAndView.addObject("project_no", endProject_no); } modelAndView.setViewName("user/projectRegist/project_4"); return modelAndView; } @RequestMapping("project_5") public ModelAndView project5(HttpServletRequest request, ModelAndView modelAndView, String project_no, String project_budget, String project_startdate, String project_duration, String endStatus, String endProject_no) throws Exception{ modelAndView.addObject("breadcrumb_title", "프로젝트"); modelAndView.addObject("breadcrumb_first", "프로젝트"); modelAndView.addObject("breadcrumb_second", "프로젝트 등록"); if (endStatus == null) { Map<String, String> params = new HashMap<String, String>(); params.put("project_no", project_no); params.put("project_budget", project_budget); params.put("project_startdate", project_startdate); params.put("project_duration", project_duration); int chk = projectService.insertProjectBudget(params); modelAndView.addObject("project_no", project_no); } else { modelAndView.addObject("project_no", endProject_no); } modelAndView.setViewName("user/projectRegist/project_5"); return modelAndView; } @RequestMapping("project_6") public ModelAndView project6(HttpServletRequest request, ModelAndView modelAndView, String project_no, String project_premeeting, String project_proceedingmeeting, String project_meetingcycle, String project_clientlocation, String endStatus, String endProject_no) throws Exception{ modelAndView.addObject("breadcrumb_title", "프로젝트"); modelAndView.addObject("breadcrumb_first", "프로젝트"); modelAndView.addObject("breadcrumb_second", "프로젝트 등록"); if (endStatus == null) { Map<String, String> params = new HashMap<String, String>(); params.put("project_no", project_no); params.put("project_premeeting", project_premeeting); params.put("project_proceedingmeeting", project_proceedingmeeting); params.put("project_meetingcycle", project_meetingcycle); params.put("project_clientlocation", project_clientlocation); int chk = projectService.insertProjectMeeting(params); modelAndView.addObject("project_no", project_no); } else { modelAndView.addObject("project_no", endProject_no); } modelAndView.setViewName("user/projectRegist/project_6"); return modelAndView; } @RequestMapping("project_7") public ModelAndView project7(HttpServletRequest request, ModelAndView modelAndView, String project_no, String project_applicationdeadline, String project_supportstatus, String project_essentialrequirements, String endStatus, String endProject_no) throws Exception{ modelAndView.addObject("breadcrumb_title", "프로젝트"); modelAndView.addObject("breadcrumb_first", "프로젝트"); modelAndView.addObject("breadcrumb_second", "프로젝트 등록"); if (endStatus == null) { Map<String, String> params = new HashMap<String, String>(); params.put("project_no", project_no); params.put("project_applicationdeadline", project_applicationdeadline); params.put("project_supportstatus", project_supportstatus); params.put("project_essentialrequirements", project_essentialrequirements); int chk = projectService.insertProjectMozip(params); modelAndView.addObject("project_no", project_no); } else { modelAndView.addObject("project_no", endProject_no); } modelAndView.setViewName("user/projectRegist/project_7"); return modelAndView; } @RequestMapping("project_interview_1") public ModelAndView project_interview_1(HttpServletRequest request, ModelAndView modelAndView, String project_no, String project_manpower, String project_managementexperience, String project_futureplans, String project_priority, String endStatus, String endProject_no) throws Exception{ modelAndView.addObject("breadcrumb_title", "프로젝트"); modelAndView.addObject("breadcrumb_first", "프로젝트"); modelAndView.addObject("breadcrumb_second", "프로젝트 등록"); if (endStatus == null) { Map<String, String> params = new HashMap<String, String>(); params.put("project_no", project_no); params.put("project_manpower", project_manpower); params.put("project_managementexperience", project_managementexperience); params.put("project_futureplans", project_futureplans); params.put("project_priority", project_priority); int chk = projectService.insertProjectAdd(params); modelAndView.addObject("project_no", project_no); } else { modelAndView.addObject("project_no", endProject_no); } modelAndView.setViewName("user/projectRegist/project_interview_1"); return modelAndView; } @RequestMapping("project_interview_2") public ModelAndView project_interview_2(HttpServletRequest request, ModelAndView modelAndView, String project_no, String interview_title, String interview_hire_shape, String interview_division, String interview_tech, String interview_peoplenum, String interview_method, String interview_authentication, String endStatus, String endProject_no, String endInterview_no) throws Exception{ modelAndView.addObject("breadcrumb_title", "프로젝트"); modelAndView.addObject("breadcrumb_first", "프로젝트"); modelAndView.addObject("breadcrumb_second", "프로젝트 등록"); if (endStatus == null) { Map<String, String> params = new HashMap<String, String>(); params.put("project_no", project_no); params.put("interview_title", interview_title); params.put("interview_hire_shape", interview_hire_shape); params.put("interview_division", interview_division); params.put("interview_tech", interview_tech); params.put("interview_peoplenum", interview_peoplenum); params.put("interview_method", interview_method); params.put("interview_authentication", interview_authentication); String interview_no = interviewService.insertInterview(params); modelAndView.addObject("project_no", project_no); modelAndView.addObject("interview_no", interview_no); } else { modelAndView.addObject("project_no", endProject_no); modelAndView.addObject("interview_no", endInterview_no); } modelAndView.setViewName("user/projectRegist/project_interview_2"); return modelAndView; } @RequestMapping("project_regist") public ModelAndView project_interview_3(HttpServletRequest request, ModelAndView modelAndView, String project_no, String interview_no, String interview_customizing )throws Exception{ modelAndView.addObject("breadcrumb_title", "프로젝트"); modelAndView.addObject("breadcrumb_first", "프로젝트"); modelAndView.addObject("breadcrumb_second", "프로젝트 등록"); Map<String, String> params = new HashMap<String, String>(); params.put("project_no", project_no); params.put("interview_customizing", interview_customizing); params.put("interview_endinput", "Y"); int chk = interviewService.updateInterview(params); ProjectVO projectInfo = new ProjectVO(); projectInfo = projectService.projectInfo(params); modelAndView.addObject("project_no", project_no); modelAndView.addObject("interview_no", interview_no); modelAndView.addObject("projectInfo", projectInfo); modelAndView.setViewName("user/projectRegist/project_regist"); return modelAndView; } // @RequestMapping("project_regist") // public ModelAndView projectRegist(HttpServletRequest request, // ModelAndView modelAndView, // String project_no, // String project_manpower, // String project_managementexperience, // String project_futureplans, // String project_priority // ) throws Exception{ // // modelAndView.addObject("breadcrumb_title", "프로젝트"); // modelAndView.addObject("breadcrumb_first", "프로젝트"); // modelAndView.addObject("breadcrumb_second", "프로젝트 등록 완료"); // // Map<String, String> params = new HashMap<String, String>(); // params.put("project_no", project_no); // params.put("project_manpower", project_manpower); // params.put("project_managementexperience", project_managementexperience); // params.put("project_futureplans", project_futureplans); // params.put("project_priority", project_priority); // // int chk = projectService.insertProjectAdd(params); // ProjectVO projectInfo = new ProjectVO(); // projectInfo = projectService.projectInfo(params); // // modelAndView.addObject("project_no", project_no); // modelAndView.addObject("projectInfo", projectInfo); // // modelAndView.setViewName("user/projectRegist/project_regist"); // // return modelAndView; // } @RequestMapping("deleteWritingProject") @ResponseBody public Boolean deleteWritingProject(String project_no) throws Exception { Boolean returnValue = false; Map<String, String> params = new HashMap<String, String>(); params.put("project_no", project_no); int chk = projectService.deleteProject(params); if (chk > 0) { returnValue = true; } return returnValue; } }
package de.kfs.db.controller.filter; import javafx.scene.control.TextFormatter; /** * Class filters all characters and only allows input of positive integers */ public class IntegerFieldFilter extends TextFormatter<String> { /** * it literally does what its supposed to */ public IntegerFieldFilter() { super(c -> { if(c.getControlNewText().isEmpty()) { return c; } //how am I this fucking smart??? if(c.getControlNewText().matches("\\d+")) { return c; } else { return null; } //literal miracle, I'm suprised it works this well :o }); } }
package com.pyg.manager.controller; import PageBean.PageResult; import ReturnResult.Results; import com.alibaba.dubbo.config.annotation.Reference; import com.pyg.pojo.TbBrand; import com.pyg.sellergoods.service.BrandService; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.sound.midi.Soundbank; import java.util.List; import java.util.Map; @RestController @RequestMapping("/brand") public class BrandController { @Reference private BrandService brandService; @RequestMapping("/findAll")//查询所有品牌信息 public List<TbBrand> findAll() { return brandService.findAll(); } /** * 返回全部列表 * @return */ @RequestMapping("/findPage") public PageResult findPage(int page,int size){ return brandService.findPage(page, size); } @RequestMapping("/findOne") public TbBrand findOne(long id){ return brandService.findOne(id); } // 数据的更新和增加 @RequestMapping("/save") public Results save(@RequestBody TbBrand brand){ if (brand.getId()!=null){ boolean flag=brandService.update(brand); if (flag){ return new Results(true,"更新成功"); }else { return new Results(false,"数据有误,更新失败"); } }else { boolean flag = brandService.add(brand); if (flag){ return new Results(true,"增加成功"); }else { return new Results(false,"数据有误,增加失败"); } } } // 数据删除 @RequestMapping("/delete") public Results delete(long[] ids){ try { brandService.delete(ids); return new Results(true,"删除成功"); }catch (Exception e){ e.printStackTrace(); return new Results(false,"删除失败"); } } // 模糊查询搜索 @RequestMapping("/search") public PageResult search(@RequestBody TbBrand brand,int page,int size){ System.out.println(brand); return brandService.search(brand,page,size); } // 品牌数据查询 @RequestMapping("/selectOption") public List<Map> selectOptionList(){ return brandService.selectOptionList(); } }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class SubstringwithConcatenationofAllWords1 { public List<Integer> findSubstring(String s, String[] words) { HashMap<String, Integer> map = new HashMap<String, Integer>(); List<Integer> list = new ArrayList<Integer>(); int slen = s.length(); if (words.length == 0 || slen < words.length * words[0].length()) return list; int numwords = 0, len = words[0].length(); for (String str : words) { if (map.containsKey(str)) map.put(str, map.get(str) + 1); else map.put(str, 1); numwords++; } String temp,word; HashMap<String, Integer> test = new HashMap<String, Integer>(); for (int i = 0; i < len; i++) { int num = 0; for (int l = i, r = i; r + len <= slen; r += len) { word = s.substring(r, r + len); if (map.containsKey(word)) { if (test.containsKey(word)) test.put(word, test.get(word) + 1); else test.put(word, 1); if (test.get(word) <= map.get(word)) num++; while (test.get(word) > map.get(word)) { temp = s.substring(l, l + len); test.put(temp, test.get(temp) - 1); l = l + len; if(!temp.equals(word))num--; } if (num == numwords) { list.add(l); temp = s.substring(l, len + l); test.put(temp, map.get(temp) - 1); l = l + len; num--; } } else { test.clear(); num = 0; l = r + len; } } test.clear(); } return list; } }
/* * Created on Mar 6, 2007 * */ package com.citibank.ods.persistence.pl.dao.rdb.oracle; import com.citibank.ods.persistence.util.CitiStatement; import java.math.BigInteger; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; import java.util.Date; import com.citibank.ods.common.connection.rdb.ManagedRdbConnection; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.common.dataset.ResultSetDataSet; import com.citibank.ods.common.exception.UnexpectedException; import com.citibank.ods.common.util.ODSConstraintDecoder; import com.citibank.ods.entity.pl.BaseTplCustomerPrvtCmplEntity; import com.citibank.ods.entity.pl.TplCustomerPrvtCmplMovEntity; import com.citibank.ods.entity.pl.valueobject.TplCustomerPrvtCmplMovEntityVO; import com.citibank.ods.persistence.pl.dao.TplCustomerPrvtCmplMovDAO; import com.citibank.ods.persistence.pl.dao.rdb.oracle.factory.OracleODSDAOFactory; /** * @author leonardo.nakada * */ public class OracleTplCustomerPrvtCmplMovDAO extends BaseOracleTplCustomerPrvtCmplDAO implements TplCustomerPrvtCmplMovDAO { private static final String C_OPERN_CODE = "OPERN_CODE"; protected static final String C_OPERN_TEXT = "OPERN_TEXT"; private static final String C_TPL_CUSTOMER_PRVT_CMPL_MOV = C_PL_SCHEMA + "TPL_CUSTOMER_PRVT_CMPL_MOV"; private static final String C_TPL_CUSTOMER_PRVT = C_PL_SCHEMA + "TPL_CUSTOMER_PRVT"; private static final String C_TBG_OFFICER = C_BG_SCHEMA + "TBG_OFFICER"; //Status do cliente public static final String C_PRVT_CUST_ATTD_STAT_CODE = "PRVT_CUST_ATTD_STAT_CODE"; /** * Este método busca uma lista dos dados complementares de cliente que se * enquadre com os critérios informados. */ public DataSet list( String emNbr_, BigInteger glbRevenSysOffcrNbr_, BigInteger prvtCustNbr_, BigInteger prvtKeyNbr_, BigInteger custNbr_, BigInteger wealthPotnlCode_, BigInteger offcrNbr_, BigInteger classCmplcCode_, String lastUpdUserId_, String custFullName_, String officerName_, String custPrvtStatCode_, BigInteger prvtCustTypeCode_ ) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; ResultSet resultSet = null; ResultSetDataSet rsds = null; StringBuffer query = new StringBuffer(); try { connection = OracleODSDAOFactory.getConnection(); query.append( " SELECT CUSTMOV." ); query.append( C_EM_NBR + ", CUSTMOV." ); query.append( C_MAIL_RECV_IND + ", CUSTMOV." ); query.append( C_OFFCL_MAIL_RECV_IND + ", CUSTMOV." ); query.append( C_GLB_REVEN_SYS_OFFCR_NBR + ", CUSTMOV." ); query.append( C_PRVT_CUST_NBR + ", CUSTMOV." ); query.append( C_PRVT_KEY_NBR + ", CUSTMOV." ); query.append( C_LAST_AUTH_DATE + ", CUSTMOV." ); query.append( C_LAST_AUTH_USER_ID + ", CUSTMOV." ); query.append( C_LAST_UPD_DATE + ", CUSTMOV." ); query.append( C_LAST_UPD_USER_ID + ", CUSTMOV." ); query.append( C_OPERN_CODE + ", CUSTMOV." ); query.append( C_WEALTH_POTNL_CODE + ", CUSTMOV." ); query.append( C_CUST_NBR + ", CUST." ); query.append( C_CUST_FULL_NAME_TEXT + ", CUSTMOV." ); query.append( C_OFFCR_NBR + ", OFFC." ); query.append( C_OFFCR_NAME_TEXT + ", CUSTMOV." ); query.append( C_CLASS_CMPLC_CODE + ", CUSTMOV." ); query.append( C_PRVT_CUST_TYPE_CODE ); query.append( " FROM " ); query.append( C_TPL_CUSTOMER_PRVT_CMPL_MOV + " CUSTMOV " ); query.append( " INNER JOIN " ); query.append( C_TPL_CUSTOMER_PRVT + " CUST " ); query.append( " ON " ); query.append( " CUSTMOV." + C_CUST_NBR + " = " + "CUST." + C_CUST_NBR ); query.append( " LEFT JOIN " ); query.append( C_TBG_OFFICER + " OFFC " ); query.append( " ON " ); query.append( " CUSTMOV." + C_OFFCR_NBR + " = " + " OFFC. " + C_OFFCR_NBR ); String criteria = ""; if ( custNbr_ != null ) { criteria = criteria + "CUST." + C_CUST_NBR + " = ? AND "; } if ( prvtKeyNbr_ != null ) { criteria = criteria + C_PRVT_KEY_NBR + " = ? AND "; } if ( wealthPotnlCode_ != null ) { criteria = criteria + C_WEALTH_POTNL_CODE + "= ? AND "; } if ( offcrNbr_ != null ) { criteria = criteria + "OFFC." + C_OFFCR_NBR + "= ? AND "; } if ( classCmplcCode_ != null ) { criteria = criteria + C_CLASS_CMPLC_CODE + "= ? AND "; } if ( prvtCustTypeCode_ != null) { criteria = criteria + C_PRVT_CUST_TYPE_CODE + "= ? AND "; } if ( emNbr_ != null && !"".equals( emNbr_ ) ) { criteria = criteria + "UPPER(\"" + C_EM_NBR + "\") like ? AND "; } if ( glbRevenSysOffcrNbr_ != null ) { criteria = criteria + C_GLB_REVEN_SYS_OFFCR_NBR + "= ? AND "; } if ( prvtCustNbr_ != null ) { criteria = criteria + C_PRVT_CUST_NBR + "= ? AND "; } if ( lastUpdUserId_ != null && lastUpdUserId_.length() > 0 ) { criteria = criteria + "UPPER(\"" + C_LAST_UPD_USER_ID + "\") like ? AND "; } if ( custFullName_ != null && !custFullName_.equals( "" ) ) { criteria = criteria + "UPPER ( CUST." + C_CUST_FULL_NAME_TEXT + ") like ? AND "; } if ( officerName_ != null && !officerName_.equals( "" ) ) { criteria = criteria + "UPPER ( OFFC." + C_OFFCR_NAME_TEXT + ") like ? AND "; } if ( custPrvtStatCode_ != null && !custPrvtStatCode_.equals( "" ) ) { criteria = criteria + "CUSTMOV." + C_PRVT_CUST_ATTD_STAT_CODE + " =? AND "; } if ( criteria.length() > 5 ) { criteria = criteria.substring( 0, criteria.length() - 5 ); query.append( " WHERE " + criteria ); } query.append( " ORDER BY CUST." + C_CUST_FULL_NAME_TEXT ); preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() )); int count = 1; if ( custNbr_ != null ) { preparedStatement.setLong( count++, custNbr_.longValue() ); } if ( prvtKeyNbr_ != null ) { preparedStatement.setLong( count++, prvtKeyNbr_.longValue() ); } if ( wealthPotnlCode_ != null ) { preparedStatement.setLong( count++, wealthPotnlCode_.longValue() ); } if ( offcrNbr_ != null ) { preparedStatement.setLong( count++, offcrNbr_.longValue() ); } if ( classCmplcCode_ != null ) { preparedStatement.setLong( count++, classCmplcCode_.longValue() ); } if ( prvtCustTypeCode_ != null ) { preparedStatement.setLong( count++, prvtCustTypeCode_.longValue() ); } if ( emNbr_ != null && !"".equals( emNbr_ ) ) { preparedStatement.setString( count++, emNbr_.toUpperCase() ); } if ( glbRevenSysOffcrNbr_ != null ) { preparedStatement.setLong( count++, glbRevenSysOffcrNbr_.longValue() ); } if ( prvtCustNbr_ != null ) { preparedStatement.setLong( count++, prvtCustNbr_.longValue() ); } if ( lastUpdUserId_ != null && lastUpdUserId_.length() > 0 ) { preparedStatement.setString( count++, "%" + lastUpdUserId_.toUpperCase() + "%" ); } if ( custFullName_ != null && !custFullName_.equals( "" ) ) { preparedStatement.setString( count++, "%" + custFullName_.toUpperCase() + "%" ); } if ( officerName_ != null && !officerName_.equals( "" ) ) { preparedStatement.setString( count++, "%" + officerName_.toUpperCase() + "%" ); } if ( custPrvtStatCode_ != null && !custPrvtStatCode_.equals( "" ) ) { preparedStatement.setString( count++, custPrvtStatCode_ ); } resultSet = preparedStatement.executeQuery(); preparedStatement.replaceParametersInQuery(query.toString()); rsds = new ResultSetDataSet( resultSet ); resultSet.close(); } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e ); } finally { closeStatement( preparedStatement ); closeConnection( connection ); } String[] codeColumn = { C_OPERN_CODE }; String[] nameColumn = { C_OPERN_TEXT }; rsds.outerJoin( ODSConstraintDecoder.decodeOpern(), codeColumn, codeColumn, nameColumn ); return rsds; } /** * Consulta de Customer */ public boolean search( TplCustomerPrvtCmplMovEntity tplCustomerPrvtCmplEntity_ ) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; ResultSet resultSet = null; ResultSetDataSet rsds = null; StringBuffer query = new StringBuffer(); try { connection = OracleODSDAOFactory.getConnection(); query.append( " SELECT " ); query.append( C_EM_NBR + ", " ); query.append( C_GLB_REVEN_SYS_OFFCR_NBR + ", " ); query.append( C_PRVT_CUST_NBR + ", " ); query.append( C_PRVT_KEY_NBR + ", " ); query.append( C_LAST_AUTH_DATE + ", " ); query.append( C_LAST_AUTH_USER_ID + ", " ); query.append( C_LAST_UPD_DATE + ", " ); query.append( C_LAST_UPD_USER_ID + ", " ); query.append( C_WEALTH_POTNL_CODE + ", " ); query.append( C_CUST_NBR + ", " ); query.append( C_OFFCR_NBR + ", " ); query.append( C_CLASS_CMPLC_CODE + ", " ); query.append( C_PRVT_CUST_TYPE_CODE ); query.append( " FROM " ); query.append( C_TPL_CUSTOMER_PRVT_CMPL_MOV ); String criteria = ""; if ( tplCustomerPrvtCmplEntity_.getData().getPrvtCustNbr() != null ) { criteria = C_PRVT_CUST_NBR + " = ? AND "; } if ( tplCustomerPrvtCmplEntity_.getData().getPrvtKeyNbr() != null ) { criteria = criteria + C_PRVT_KEY_NBR + " = ? AND "; } if ( tplCustomerPrvtCmplEntity_.getData().getWealthPotnlCode() != null ) { criteria = criteria + C_WEALTH_POTNL_CODE + "= ? AND "; } if ( tplCustomerPrvtCmplEntity_.getData().getCustNbr() != null ) { criteria = criteria + C_CUST_NBR + "= ? AND "; } if ( tplCustomerPrvtCmplEntity_.getData().getOffcrNbr() != null ) { criteria = criteria + C_OFFCR_NBR + "= ? AND "; } if ( tplCustomerPrvtCmplEntity_.getData().getClassCmplcCode() != null ) { criteria = criteria + C_CLASS_CMPLC_CODE + "= ? AND "; } if ( tplCustomerPrvtCmplEntity_.getData().getPrvtCustTypeCode() != null ) { criteria = criteria + C_PRVT_CUST_TYPE_CODE + "= ? AND "; } if ( tplCustomerPrvtCmplEntity_.getData().getEmNbr() != null && !tplCustomerPrvtCmplEntity_.getData().getEmNbr().equals( "" ) ) { criteria = " " + criteria + C_EM_NBR + "= ? AND "; } if ( criteria.length() > 0 ) { criteria = criteria.substring( 0, criteria.length() - 5 ); query.append( " WHERE " + criteria ); } preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() )); int count = 1; if ( tplCustomerPrvtCmplEntity_.getData().getPrvtCustNbr() != null ) { preparedStatement.setLong( count++, tplCustomerPrvtCmplEntity_.getData().getPrvtCustNbr().longValue() ); } if ( tplCustomerPrvtCmplEntity_.getData().getPrvtKeyNbr() != null ) { preparedStatement.setLong( count++, tplCustomerPrvtCmplEntity_.getData().getPrvtKeyNbr().longValue() ); } if ( tplCustomerPrvtCmplEntity_.getData().getWealthPotnlCode() != null ) { preparedStatement.setLong( count++, tplCustomerPrvtCmplEntity_.getData().getWealthPotnlCode().longValue() ); } if ( tplCustomerPrvtCmplEntity_.getData().getCustNbr() != null ) { preparedStatement.setLong( count++, tplCustomerPrvtCmplEntity_.getData().getCustNbr().longValue() ); } if ( tplCustomerPrvtCmplEntity_.getData().getOffcrNbr() != null ) { preparedStatement.setLong( count++, tplCustomerPrvtCmplEntity_.getData().getOffcrNbr().longValue() ); } if ( tplCustomerPrvtCmplEntity_.getData().getClassCmplcCode() != null ) { preparedStatement.setLong( count++, tplCustomerPrvtCmplEntity_.getData().getClassCmplcCode().longValue() ); } if ( tplCustomerPrvtCmplEntity_.getData().getPrvtCustTypeCode() != null ) { preparedStatement.setLong( count++, tplCustomerPrvtCmplEntity_.getData().getPrvtCustTypeCode().longValue() ); } if ( tplCustomerPrvtCmplEntity_.getData().getEmNbr() != null && !tplCustomerPrvtCmplEntity_.getData().getEmNbr().equals( "" ) ) { preparedStatement.setString( count++, tplCustomerPrvtCmplEntity_.getData().getEmNbr() ); } resultSet = preparedStatement.executeQuery(); preparedStatement.replaceParametersInQuery(query.toString()); rsds = new ResultSetDataSet( resultSet ); resultSet.close(); } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e ); } finally { closeStatement( preparedStatement ); closeConnection( connection ); } return ( rsds.size() > 0 ); } /* * (non-Javadoc) * @see com.citibank.ods.persistence.pl.dao.TplCustomerPrvtCmplDAO#detailCustomer(com.citibank.ods.modules.client.customer.functionality.valueobject.CustomerCurrentDetailFncVO) */ public BaseTplCustomerPrvtCmplEntity find( BaseTplCustomerPrvtCmplEntity baseTplCustomerPrvtCmplEntity_ ) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; ResultSet resultSet = null; StringBuffer query = new StringBuffer(); ArrayList tplCustomerCmplEntities; BaseTplCustomerPrvtCmplEntity tplCustomerPrvtCmplEntity; try { connection = OracleODSDAOFactory.getConnection(); query.append( "SELECT " ); query.append( C_EM_NBR + ", " ); query.append( C_MAIL_RECV_IND + ", " ); query.append( C_OFFCL_MAIL_RECV_IND + ", " ); query.append( C_GLB_REVEN_SYS_OFFCR_NBR + ", " ); query.append( C_PRVT_CUST_NBR + ", " ); query.append( C_PRVT_KEY_NBR + ", " ); query.append( C_LAST_AUTH_DATE + ", " ); query.append( C_LAST_AUTH_USER_ID + ", " ); query.append( C_LAST_UPD_DATE + ", " ); query.append( C_LAST_UPD_USER_ID + ", " ); query.append( C_OPERN_CODE + ", " ); query.append( C_WEALTH_POTNL_CODE + ", " ); query.append( C_CUST_NBR + ", " ); query.append( C_OFFCR_NBR + ", " ); query.append( C_PRVT_CUST_ATTD_STAT_CODE + ", " ); query.append( C_CLASS_CMPLC_CODE + ", " ); query.append( C_PRVT_CUST_TYPE_CODE ); query.append( " FROM " ); query.append( C_TPL_CUSTOMER_PRVT_CMPL_MOV ); query.append( " WHERE " + C_CUST_NBR + " = ? " ); preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() )); preparedStatement.setLong( 1, ( baseTplCustomerPrvtCmplEntity_.getData().getCustNbr().longValue() ) ); resultSet = preparedStatement.executeQuery(); preparedStatement.replaceParametersInQuery(query.toString()); tplCustomerCmplEntities = instantiateFromResultSet( resultSet ); if ( tplCustomerCmplEntities.size() == 0 ) { //throw new NoRowsReturnedException(); tplCustomerPrvtCmplEntity = null; } else if ( tplCustomerCmplEntities.size() > 1 ) { throw new UnexpectedException( C_ERROR_TOO_MANY_ROWS_RETURNED ); } else { tplCustomerPrvtCmplEntity = ( BaseTplCustomerPrvtCmplEntity ) tplCustomerCmplEntities.get( 0 ); } return tplCustomerPrvtCmplEntity; } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e ); } finally { closeStatement( preparedStatement ); closeConnection( connection ); } } /* * Cria uma lista de entities a partir de um resultset */ private ArrayList instantiateFromResultSet( ResultSet rs_ ) { TplCustomerPrvtCmplMovEntity customerPrvtCmplMovEntity; TplCustomerPrvtCmplMovEntityVO customerMovEntityVO; ArrayList tplCustomerCmplEntities = new ArrayList(); try { while ( rs_.next() ) { customerPrvtCmplMovEntity = new TplCustomerPrvtCmplMovEntity(); customerMovEntityVO = ( TplCustomerPrvtCmplMovEntityVO ) customerPrvtCmplMovEntity.getData(); customerMovEntityVO.setCustNbr( new BigInteger( rs_.getString( C_CUST_NBR ) ) ); customerMovEntityVO.setEmNbr( rs_.getString( C_EM_NBR ) ); if ( rs_.getDate( C_LAST_AUTH_DATE ) != null ) { customerMovEntityVO.setLastAuthDate( new Date(rs_.getDate( C_LAST_AUTH_DATE ).getTime()) ); } customerMovEntityVO.setLastAuthUserId( rs_.getString( C_LAST_AUTH_USER_ID ) ); if ( rs_.getString( C_CLASS_CMPLC_CODE ) != null ) { customerMovEntityVO.setClassCmplcCode( new BigInteger( rs_.getString( C_CLASS_CMPLC_CODE ) ) ); } if ( rs_.getDate( C_LAST_UPD_DATE ) != null ) { customerMovEntityVO.setLastUpdDate( new Date(rs_.getTimestamp( C_LAST_UPD_DATE ).getTime()) ); } customerMovEntityVO.setLastUpdUserId( rs_.getString( C_LAST_UPD_USER_ID ) ); customerMovEntityVO.setMailRecvInd( rs_.getString( C_MAIL_RECV_IND ) ); customerMovEntityVO.setOffclMailRecvInd( rs_.getString( C_OFFCL_MAIL_RECV_IND ) ); if ( rs_.getString( C_PRVT_KEY_NBR ) != null ) { customerMovEntityVO.setPrvtKeyNbr( new BigInteger( rs_.getString( C_PRVT_KEY_NBR ) ) ); } if ( rs_.getString( C_OFFCR_NBR ) != null ) { customerMovEntityVO.setOffcrNbr( new BigInteger( rs_.getString( C_OFFCR_NBR ) ) ); } if ( rs_.getString( C_GLB_REVEN_SYS_OFFCR_NBR ) != null ) { customerMovEntityVO.setGlbRevenSysOffcrNbr( new BigInteger( rs_.getString( C_GLB_REVEN_SYS_OFFCR_NBR ) ) ); } if ( rs_.getString( C_PRVT_CUST_NBR ) != null ) { customerMovEntityVO.setPrvtCustNbr( new BigInteger( rs_.getString( C_PRVT_CUST_NBR ) ) ); } if ( rs_.getString( C_WEALTH_POTNL_CODE ) != null ) { customerMovEntityVO.setWealthPotnlCode( new BigInteger( rs_.getString( C_WEALTH_POTNL_CODE ) ) ); } if ( rs_.getString( C_PRVT_CUST_TYPE_CODE ) != null ) { customerMovEntityVO.setPrvtCustTypeCode( new BigInteger( rs_.getString( C_PRVT_CUST_TYPE_CODE ) ) ); } customerMovEntityVO.setOpernCode( rs_.getString( C_OPERN_CODE ) ); customerMovEntityVO.setCustPrvtStatCode( rs_.getString( C_PRVT_CUST_ATTD_STAT_CODE ) ); tplCustomerCmplEntities.add( customerPrvtCmplMovEntity ); } } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_INSTANTIATE_FROM_RESULT_SET, e ); } return tplCustomerCmplEntities; } /* * (non-Javadoc) * @see com.citibank.ods.persistence.pl.dao.TplCustomerPrvtCmplDAO#existsCustomer(com.citibank.ods.entity.pl.TplCustomerPrvtCmplEntity) */ public boolean exists( TplCustomerPrvtCmplMovEntity tplCustomerPrvtCmplMovEntity_ ) { boolean exists = true; BaseTplCustomerPrvtCmplEntity baseTplCustomerPrvtCmplEntity = this.find( tplCustomerPrvtCmplMovEntity_ ); if ( baseTplCustomerPrvtCmplEntity == null ) { exists = false; } return exists; } /* * (non-Javadoc) * @see com.citibank.ods.persistence.pl.dao.TplCustomerPrvtCmplMovDAO#update(com.citibank.ods.entity.pl.TplCustomerPrvtCmplMovEntity) */ public void update( TplCustomerPrvtCmplMovEntity customerPrvtCmplEntity_ ) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; StringBuffer query = new StringBuffer(); try { connection = OracleODSDAOFactory.getConnection(); query.append( "UPDATE " + C_TPL_CUSTOMER_PRVT_CMPL_MOV + " SET " ); query.append( C_CLASS_CMPLC_CODE + "= ?," ); query.append( C_EM_NBR + "= ?," ); query.append( C_GLB_REVEN_SYS_OFFCR_NBR + "= ?," ); query.append( C_LAST_UPD_DATE + "= ?," ); query.append( C_LAST_UPD_USER_ID + "= ?," ); query.append( C_MAIL_RECV_IND + "= ?," ); query.append( C_OFFCL_MAIL_RECV_IND + "= ?," ); query.append( C_OFFCR_NBR + "= ?," ); query.append( C_OPERN_CODE + "= ?, " ); query.append( C_PRVT_CUST_NBR + "= ?, " ); query.append( C_PRVT_KEY_NBR + "= ?, " ); query.append( C_PRVT_CUST_ATTD_STAT_CODE + " = ?, " ); query.append( C_WEALTH_POTNL_CODE + "= ?, " ); query.append( C_PRVT_CUST_TYPE_CODE + "= ? " ); query.append( "WHERE " + C_CUST_NBR + "= ? " ); preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() )); int count = 1; if ( customerPrvtCmplEntity_.getData().getClassCmplcCode() != null ) { preparedStatement.setLong( count++, customerPrvtCmplEntity_.getData().getClassCmplcCode().longValue() ); } else { preparedStatement.setString( count++, null ); } if ( customerPrvtCmplEntity_.getData().getEmNbr() != null ) { preparedStatement.setString( count++, customerPrvtCmplEntity_.getData().getEmNbr() ); } else { preparedStatement.setString( count++, null ); } if ( customerPrvtCmplEntity_.getData().getGlbRevenSysOffcrNbr() != null ) { preparedStatement.setLong( count++, customerPrvtCmplEntity_.getData().getGlbRevenSysOffcrNbr().longValue() ); } else { preparedStatement.setString( count++, null ); } if (customerPrvtCmplEntity_.getData().getLastUpdDate() != null) { preparedStatement.setTimestamp( count++, new Timestamp( customerPrvtCmplEntity_.getData().getLastUpdDate().getTime() ) ); } else { preparedStatement.setNull( count++, Types.TIMESTAMP ); } if ( customerPrvtCmplEntity_.getData().getLastUpdUserId() != null ) { preparedStatement.setString( count++, customerPrvtCmplEntity_.getData().getLastUpdUserId() ); } else { preparedStatement.setString( count++, null ); } if ( customerPrvtCmplEntity_.getData().getMailRecvInd() != null ) { preparedStatement.setString( count++, customerPrvtCmplEntity_.getData().getMailRecvInd() ); } else { preparedStatement.setString( count++, null ); } if ( customerPrvtCmplEntity_.getData().getOffclMailRecvInd() != null ) { preparedStatement.setString( count++, customerPrvtCmplEntity_.getData().getOffclMailRecvInd() ); } else { preparedStatement.setString( count++, null ); } if ( customerPrvtCmplEntity_.getData().getOffcrNbr() != null ) { preparedStatement.setLong( count++, customerPrvtCmplEntity_.getData().getOffcrNbr().longValue() ); } else { preparedStatement.setString( count++, null ); } preparedStatement.setString( count++, ( ( TplCustomerPrvtCmplMovEntityVO ) customerPrvtCmplEntity_.getData() ).getOpernCode() ); if ( customerPrvtCmplEntity_.getData().getPrvtCustNbr() != null ) { preparedStatement.setLong( count++, customerPrvtCmplEntity_.getData().getPrvtCustNbr().longValue() ); } else { preparedStatement.setString( count++, null ); } if ( customerPrvtCmplEntity_.getData().getPrvtKeyNbr() != null ) { preparedStatement.setLong( count++, customerPrvtCmplEntity_.getData().getPrvtKeyNbr().longValue() ); } else { preparedStatement.setString( count++, null ); } if ( customerPrvtCmplEntity_.getData().getCustPrvtStatCode() != null ) { preparedStatement.setString( count++, customerPrvtCmplEntity_.getData().getCustPrvtStatCode() ); } else { preparedStatement.setString( count++, null ); } if ( customerPrvtCmplEntity_.getData().getWealthPotnlCode() != null ) { preparedStatement.setLong( count++, customerPrvtCmplEntity_.getData().getWealthPotnlCode().longValue() ); } else { preparedStatement.setString( count++, null ); } if ( customerPrvtCmplEntity_.getData().getPrvtCustTypeCode() != null ) { preparedStatement.setLong( count++, customerPrvtCmplEntity_.getData().getPrvtCustTypeCode().longValue() ); } else { preparedStatement.setString( count++, null ); } preparedStatement.setLong( count++, customerPrvtCmplEntity_.getData().getCustNbr().longValue() ); preparedStatement.replaceParametersInQuery(query.toString()); preparedStatement.executeQuery(); } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e ); } finally { closeStatement( preparedStatement ); closeConnection( connection ); } } /* * (non-Javadoc) * @see com.citibank.ods.persistence.pl.dao.TplCustomerPrvtCmplMovDAO#delete(com.citibank.ods.entity.pl.TplCustomerPrvtCmplMovEntity) */ public void delete( TplCustomerPrvtCmplMovEntity customerPrvtCmplEntity_ ) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; StringBuffer query = new StringBuffer(); try { connection = OracleODSDAOFactory.getConnection(); query.append( "DELETE FROM " ); query.append( C_TPL_CUSTOMER_PRVT_CMPL_MOV ); query.append( " WHERE " ); query.append( C_CUST_NBR + " = ?" ); preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() )); preparedStatement.setLong( 1, customerPrvtCmplEntity_.getData().getCustNbr().longValue() ); preparedStatement.executeQuery(); preparedStatement.replaceParametersInQuery(query.toString()); } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e ); } finally { closeStatement( preparedStatement ); closeConnection( connection ); } } /* * (non-Javadoc) * @see com.citibank.ods.persistence.pl.dao.TplCustomerPrvtCmplMovDAO#insert(com.citibank.ods.entity.pl.TplCustomerPrvtCmplMovEntity) */ public TplCustomerPrvtCmplMovEntity insert( TplCustomerPrvtCmplMovEntity customerPrvtCmplMovEntity_ ) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; StringBuffer query = new StringBuffer(); try { connection = OracleODSDAOFactory.getConnection(); query.append( "INSERT INTO " + C_TPL_CUSTOMER_PRVT_CMPL_MOV + " ( " ); query.append( C_CLASS_CMPLC_CODE + ", " ); query.append( C_EM_NBR + ", " ); query.append( C_GLB_REVEN_SYS_OFFCR_NBR + ", " ); query.append( C_LAST_UPD_DATE + ", " ); query.append( C_LAST_UPD_USER_ID + ", " ); query.append( C_MAIL_RECV_IND + ", " ); query.append( C_OFFCL_MAIL_RECV_IND + ", " ); query.append( C_OFFCR_NBR + ", " ); query.append( C_OPERN_CODE + ", " ); query.append( C_PRVT_CUST_NBR + ", " ); query.append( C_PRVT_KEY_NBR + ", " ); query.append( C_WEALTH_POTNL_CODE + ", " ); query.append( C_PRVT_CUST_ATTD_STAT_CODE + ", " ); query.append( C_PRVT_CUST_TYPE_CODE + ", " ); query.append( C_CUST_NBR + " )" ); query.append( " VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) " ); preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() )); int count = 1; if ( customerPrvtCmplMovEntity_.getData().getClassCmplcCode() != null ) { preparedStatement.setLong( count++, customerPrvtCmplMovEntity_.getData().getClassCmplcCode().longValue() ); } else { preparedStatement.setString( count++, null ); } preparedStatement.setString( count++, customerPrvtCmplMovEntity_.getData().getEmNbr() ); if ( customerPrvtCmplMovEntity_.getData().getGlbRevenSysOffcrNbr() != null ) { preparedStatement.setLong( count++, customerPrvtCmplMovEntity_.getData().getGlbRevenSysOffcrNbr().longValue() ); } else { preparedStatement.setLong( count++, 0 ); } if (customerPrvtCmplMovEntity_.getData().getLastUpdDate() != null) { preparedStatement.setTimestamp( count++, new Timestamp( customerPrvtCmplMovEntity_.getData().getLastUpdDate().getTime() ) ); } else { preparedStatement.setNull( count++, Types.TIMESTAMP ); } preparedStatement.setString( count++, customerPrvtCmplMovEntity_.getData().getLastUpdUserId() ); preparedStatement.setString( count++, customerPrvtCmplMovEntity_.getData().getMailRecvInd() ); preparedStatement.setString( count++, customerPrvtCmplMovEntity_.getData().getOffclMailRecvInd() ); if ( customerPrvtCmplMovEntity_.getData().getOffcrNbr() != null ) { preparedStatement.setLong( count++, customerPrvtCmplMovEntity_.getData().getOffcrNbr().longValue() ); } else { preparedStatement.setLong( count++, 0 ); } preparedStatement.setString( count++, ( ( TplCustomerPrvtCmplMovEntityVO ) customerPrvtCmplMovEntity_.getData() ).getOpernCode() ); if ( customerPrvtCmplMovEntity_.getData().getPrvtCustNbr() != null ) { preparedStatement.setLong( count++, customerPrvtCmplMovEntity_.getData().getPrvtCustNbr().longValue() ); } else { preparedStatement.setLong( count++, 0 ); } if ( customerPrvtCmplMovEntity_.getData().getPrvtKeyNbr() != null ) { preparedStatement.setLong( count++, customerPrvtCmplMovEntity_.getData().getPrvtKeyNbr().longValue() ); } else { preparedStatement.setLong( count++, 0 ); } if ( customerPrvtCmplMovEntity_.getData().getWealthPotnlCode() != null && customerPrvtCmplMovEntity_.getData().getWealthPotnlCode().longValue() > 0 ) { preparedStatement.setLong( count++, customerPrvtCmplMovEntity_.getData().getWealthPotnlCode().longValue() ); } else { preparedStatement.setString( count++, null ); } if ( customerPrvtCmplMovEntity_.getData().getCustPrvtStatCode() != null ) { preparedStatement.setString( count++, customerPrvtCmplMovEntity_.getData().getCustPrvtStatCode() ); } else { preparedStatement.setString( count++, null ); } if ( customerPrvtCmplMovEntity_.getData().getPrvtCustTypeCode() != null ) { preparedStatement.setLong(count++,customerPrvtCmplMovEntity_.getData().getPrvtCustTypeCode().longValue() ); } else { preparedStatement.setString( count++, null ); } if ( customerPrvtCmplMovEntity_.getData().getCustNbr() != null ) { preparedStatement.setLong( count++, customerPrvtCmplMovEntity_.getData().getCustNbr().longValue() ); } else { preparedStatement.setLong( count++, 0 ); } preparedStatement.execute(); preparedStatement.replaceParametersInQuery(query.toString()); } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e ); } finally { closeStatement( preparedStatement ); closeConnection( connection ); } return customerPrvtCmplMovEntity_; } }
/** * Created by friday on 16/9/2. */ public class Rectangle extends Shape{ public Rectangle() { type = "Rectangle"; } @Override void draw() { System.out.println(this.getType()+"draw()"); } }
//Abrindo o Firefox import java.io.File; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; public class ExampleTest01{ public static void main(String[] args) { abrirFirefox(); } private static void abrirFirefox() { WebDriver driver = new FirefoxDriver(); driver.get("http://diariodoaluno.com"); String i = driver.getCurrentUrl(); System.out.println(i); driver.close(); } }
package com.syscxp.biz.service.activiti.form; /** * @Author: sunxuelong. * @Cretion Date: 2018-08-28. * @Description: . */ public interface FormKeyService { void startProcess(); }
package github.tornaco.android.thanos.core.pm; import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; import java.util.List; import java.util.Objects; import util.CollectionUtils; public class PackageSet implements Parcelable { private String label; private String id; private long createAt; private List<String> pkgNames; private boolean isPrebuilt; protected PackageSet(Parcel in) { label = in.readString(); id = in.readString(); createAt = in.readLong(); pkgNames = in.createStringArrayList(); if (pkgNames == null) { pkgNames = new ArrayList<>(); } isPrebuilt = in.readInt() == 1; } public PackageSet(String label, String id, long createAt, List<String> pkgNames, boolean isPrebuilt) { this.label = label; this.id = id; this.createAt = createAt; this.pkgNames = pkgNames; this.isPrebuilt = isPrebuilt; } public PackageSet() { } public static PackageSetBuilder builder() { return new PackageSetBuilder(); } public List<String> getPkgNames() { if (pkgNames == null) { pkgNames = new ArrayList<>(); } return pkgNames; } public void addPackage(String pkg) { if (pkgNames == null) { pkgNames = new ArrayList<>(); } pkgNames.add(pkg); } public void removePackage(String pkg) { if (pkgNames == null) { pkgNames = new ArrayList<>(); } pkgNames.remove(pkg); } public int getPackageCount() { return CollectionUtils.sizeOf(pkgNames); } public boolean isPrebuilt() { return isPrebuilt; } public static final Creator<PackageSet> CREATOR = new Creator<PackageSet>() { @Override public PackageSet createFromParcel(Parcel in) { return new PackageSet(in); } @Override public PackageSet[] newArray(int size) { return new PackageSet[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(label); parcel.writeString(id); parcel.writeLong(createAt); parcel.writeStringList(pkgNames); parcel.writeInt(isPrebuilt ? 1 : 0); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PackageSet that = (PackageSet) o; return createAt == that.createAt && id.equals(that.id); } @Override public int hashCode() { return Objects.hash(id, createAt); } public String toString() { return "PackageSet(label=" + this.label + ", id=" + this.id + ", createAt=" + this.createAt + ", pkgNames=" + this.getPkgNames() + ")"; } public String getLabel() { return this.label; } public void setLabel(String label) { this.label = label; } public String getId() { return this.id; } public long getCreateAt() { return this.createAt; } public static class PackageSetBuilder { private String label; private String id; private long createAt; private List<String> pkgNames; private boolean isPrebuilt; PackageSetBuilder() { } public PackageSet.PackageSetBuilder label(String label) { this.label = label; return this; } public PackageSet.PackageSetBuilder id(String id) { this.id = id; return this; } public PackageSet.PackageSetBuilder createAt(long createAt) { this.createAt = createAt; return this; } public PackageSet.PackageSetBuilder pkgNames(List<String> pkgNames) { this.pkgNames = pkgNames; return this; } public PackageSet.PackageSetBuilder prebuilt(boolean isPrebuilt) { this.isPrebuilt = isPrebuilt; return this; } public PackageSet build() { return new PackageSet(label, id, createAt, pkgNames, isPrebuilt); } } }
package com.javarush.test.level18.lesson10.home07; /* Поиск данных внутри файла Считать с консоли имя файла Найти в файле информацию, которая относится к заданному id, и вывести ее на экран в виде, в котором она записана в файле. Программа запускается с одним параметром: id (int) Закрыть потоки. Не использовать try-with-resources В файле данные разделены пробелом и хранятся в следующей последовательности: id productName price quantity где id - int productName - название товара, может содержать пробелы, String price - цена, double quantity - количество, int Информация по каждому товару хранится в отдельной строке */ import java.io.*; public class Solution { public static void main(String[] args) throws IOException { BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); BufferedReader reader = new BufferedReader(new FileReader(read.readLine())); String s ; String v = args[0]; while ((s =reader.readLine())!=null) { String num=""; char[] d = s.trim().toCharArray(); for (int i=0;i<d.length;i++) { if (isInt(d[i])){ num +=String.valueOf(d[i]); } else break; } int i = Integer.parseInt(num); if (Integer.parseInt(num) == Integer.parseInt(v)) System.out.println(s); } reader.close(); read.close(); } public static boolean isInt(char s){ try{ int i = Integer.parseInt(String.valueOf(s)); return true; } catch (Exception e){ return false; } } }
public class Book { private String Title; private String Author; private int CheckinOut; private int Value; public Book(String T, String A, int CK, int V) { Title = T; Author = A; CheckinOut = CK; Value = V; } //getters public String getTitle(){ return Title;} public String getAuthor(){ return Author;} public int getChecked(){ return CheckinOut;} public int getValue(){ return Value;} public void setChecked(int c){ CheckinOut = c; return; } }
package pl.kurs; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; public class KomisWindow extends JFrame{ private static final long serialVersionUID = 1L; /** * Table model jest wstrzykiwany */ KomisTableModel tableModel; public void setTableModel(KomisTableModel tableModel) { this.tableModel = tableModel; } /** * To musi być wystawione, żeby można było skorzystać w akcji usuń */ JTable tbl; /** * Przygotowanie formatki */ public void init() { JPanel contentPane = (JPanel) this.getContentPane(); // dodanie tabelki tbl = new JTable(tableModel); contentPane.add(new JScrollPane(tbl),BorderLayout.CENTER); // dodanie przycisków contentPane.add(getPrzyciski(),BorderLayout.SOUTH); this.pack(); this.setLocationRelativeTo(null); } /** * Generacja przycisków * @return panel z przyciskami */ JPanel getPrzyciski() { JPanel pnPrzyciski = new JPanel(); // Przycisk Dodaj JButton btnDodaj = new JButton("Dodaj"); btnDodaj.setPreferredSize(new Dimension(80,24)); // wyślij do modelu polecenie stworzenia nowego (pustego) samochodu btnDodaj.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { tableModel.addNew(); } }); pnPrzyciski.add(btnDodaj); // Przycisk Usuń JButton btnUsun = new JButton("Usuń"); btnUsun.setPreferredSize(new Dimension(80,24)); // wyślij do modelu polecenie usunięcia zaznaczonego obiektu btnUsun.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int index = tbl.getSelectedRow(); if(index>=0) tableModel.del(index); } }); pnPrzyciski.add(btnUsun); return pnPrzyciski; } }
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.gateway.api.buffer; import io.gravitee.common.util.ServiceLoaderHelper; import java.nio.charset.Charset; /** * Mainly inspired by Vertx.io * * @see io.vertx.core.buffer.Buffer * * @author David BRASSELY (david at gravitee.io) * @author GraviteeSource Team */ public interface Buffer { static Buffer buffer() { return factory.buffer(); } static Buffer buffer(int initialSizeHint) { return factory.buffer(initialSizeHint); } static Buffer buffer(String string) { return factory.buffer(string); } static Buffer buffer(String string, String enc) { return factory.buffer(string, enc); } static Buffer buffer(byte[] bytes) { return factory.buffer(bytes); } Buffer appendBuffer(Buffer buff); Buffer appendString(String str, String enc); Buffer appendString(String str); @Override String toString(); String toString(String enc); String toString(Charset enc); byte[] getBytes(); int length(); Object getNativeBuffer(); BufferFactory factory = ServiceLoaderHelper.loadFactory(BufferFactory.class); }
package com.example.bob.health_helper.Local; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.example.bob.health_helper.Local.LocalBean.Favorite; import com.example.bob.health_helper.Local.LocalBean.Like; import com.example.bob.health_helper.Local.LocalBean.Reminder; import com.example.bob.health_helper.Local.LocalBean.SearchHistory; import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; import java.sql.SQLException; public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static final String DB_NAME="health_helper.db"; private static final int DB_VERSION=1; private DatabaseHelper(Context context){ super(context,DB_NAME,null,DB_VERSION); } //单例模式 private static DatabaseHelper instance; public static synchronized DatabaseHelper getInstance(Context context){ context=context.getApplicationContext(); if(instance==null){ synchronized (DatabaseHelper.class){ if(instance==null) instance=new DatabaseHelper(context); } } return instance; } //建数据库 @Override public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) { try{ TableUtils.createTableIfNotExists(connectionSource, Favorite.class); TableUtils.createTableIfNotExists(connectionSource, Like.class); TableUtils.createTableIfNotExists(connectionSource, SearchHistory.class); TableUtils.createTableIfNotExists(connectionSource, Reminder.class); } catch (SQLException e) { e.printStackTrace(); } } //升级数据库 @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) { try { TableUtils.dropTable(connectionSource,Favorite.class,true); TableUtils.dropTable(connectionSource,Like.class,true); TableUtils.dropTable(connectionSource,SearchHistory.class,true); TableUtils.dropTable(connectionSource,Reminder.class,true); onCreate(sqLiteDatabase,connectionSource); } catch (SQLException e) { e.printStackTrace(); } } }
/* * Welcome to use the TableGo Tools. * * http://vipbooks.iteye.com * http://blog.csdn.net/vipbooks * http://www.cnblogs.com/vipbooks * * Author:bianj * Email:edinsker@163.com * Version:5.8.0 */ package com.lenovohit.hcp.payment.model; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; /** * TREAT_CHARGE_DETAIL * * @author zyus * @version 1.0.0 2017-12-16 */ public class IChargeDetail implements java.io.Serializable { /** 版本号 */ private static final long serialVersionUID = -2092994565557690991L; /** hosId */ private String hosId; /** hosNo */ private String hosNo; /** hosName */ private String hosName; /** depId */ private String depId; /** depNo */ private String depNo; /** depName */ private String depName; /** depClazz */ private String depClazz; /** depClazzName */ private String depClazzName; /** sepId */ private String sepId; /** sepCode */ private String sepCode; /** sepName */ private String sepName; /** sepType */ private String sepType; /** docId */ private String docId; /** docNo */ private String docNo; /** docName */ private String docName; /** docJobTitle */ private String docJobTitle; /** proId */ private String proId; /** proNo */ private String proNo; /** proName */ private String proName; /** cardId */ private String cardId; /** cardNo */ private String cardNo; /** activityId */ private String activityId; /** activityNo */ private String activityNo; /** recordId */ private String recordId; /** code */ private String code; /** name */ private String name; /** spec */ private String spec; /** unit */ private String unit; /** num */ private BigDecimal num; /** price */ private BigDecimal price; /** 治疗费、X光费、化验费 */ private String type; /** miType */ private String miType; /** myselfScale */ private BigDecimal myselfScale; /** cost */ private BigDecimal cost; /** amount */ private BigDecimal amount; /** realAmount */ private BigDecimal realAmount; /** recodeNo */ private String recordNo; /** recordTime */ private Date recordTime; /** invoiceNo */ private String invoiceNo; /** invoiceTime */ private Date invoiceTime; /** chargeId */ private String chargeId; /** chargeNo */ private String chargeNo; /** chargeUser */ private String chargeUser; /** chargeTime */ private Date chargeTime; /** comment */ private String comment; /** status */ private String status; /** * 获取hosId * * @return hosId */ public String getHosId() { return this.hosId; } /** * 设置hosId * * @param hosId */ public void setHosId(String hosId) { this.hosId = hosId; } /** * 获取hosNo * * @return hosNo */ public String getHosNo() { return this.hosNo; } /** * 设置hosNo * * @param hosNo */ public void setHosNo(String hosNo) { this.hosNo = hosNo; } /** * 获取hosName * * @return hosName */ public String getHosName() { return this.hosName; } /** * 设置hosName * * @param hosName */ public void setHosName(String hosName) { this.hosName = hosName; } /** * 获取depId * * @return depId */ public String getDepId() { return this.depId; } /** * 设置depId * * @param depId */ public void setDepId(String depId) { this.depId = depId; } /** * 获取depNo * * @return depNo */ public String getDepNo() { return this.depNo; } /** * 设置depNo * * @param depNo */ public void setDepNo(String depNo) { this.depNo = depNo; } /** * 获取depName * * @return depName */ public String getDepName() { return this.depName; } /** * 设置depName * * @param depName */ public void setDepName(String depName) { this.depName = depName; } /** * 获取depClazz * * @return depClazz */ public String getDepClazz() { return this.depClazz; } /** * 设置depClazz * * @param depClazz */ public void setDepClazz(String depClazz) { this.depClazz = depClazz; } /** * 获取depClazzName * * @return depClazzName */ public String getDepClazzName() { return this.depClazzName; } /** * 设置depClazzName * * @param depClazzName */ public void setDepClazzName(String depClazzName) { this.depClazzName = depClazzName; } /** * 获取sepId * * @return sepId */ public String getSepId() { return this.sepId; } /** * 设置sepId * * @param sepId */ public void setSepId(String sepId) { this.sepId = sepId; } /** * 获取sepCode * * @return sepCode */ public String getSepCode() { return this.sepCode; } /** * 设置sepCode * * @param sepCode */ public void setSepCode(String sepCode) { this.sepCode = sepCode; } /** * 获取sepName * * @return sepName */ public String getSepName() { return this.sepName; } /** * 设置sepName * * @param sepName */ public void setSepName(String sepName) { this.sepName = sepName; } /** * 获取sepType * * @return sepType */ public String getSepType() { return this.sepType; } /** * 设置sepType * * @param sepType */ public void setSepType(String sepType) { this.sepType = sepType; } /** * 获取docId * * @return docId */ public String getDocId() { return this.docId; } /** * 设置docId * * @param docId */ public void setDocId(String docId) { this.docId = docId; } /** * 获取docNo * * @return docNo */ public String getDocNo() { return this.docNo; } /** * 设置docNo * * @param docNo */ public void setDocNo(String docNo) { this.docNo = docNo; } /** * 获取docName * * @return docName */ public String getDocName() { return this.docName; } /** * 设置docName * * @param docName */ public void setDocName(String docName) { this.docName = docName; } /** * 获取docJobTitle * * @return docJobTitle */ public String getDocJobTitle() { return this.docJobTitle; } /** * 设置docJobTitle * * @param docJobTitle */ public void setDocJobTitle(String docJobTitle) { this.docJobTitle = docJobTitle; } /** * 获取proId * * @return proId */ public String getProId() { return this.proId; } /** * 设置proId * * @param proId */ public void setProId(String proId) { this.proId = proId; } /** * 获取proNo * * @return proNo */ public String getProNo() { return this.proNo; } /** * 设置proNo * * @param proNo */ public void setProNo(String proNo) { this.proNo = proNo; } /** * 获取proName * * @return proName */ public String getProName() { return this.proName; } /** * 设置proName * * @param proName */ public void setProName(String proName) { this.proName = proName; } /** * 获取cardId * * @return cardId */ public String getCardId() { return this.cardId; } /** * 设置cardId * * @param cardId */ public void setCardId(String cardId) { this.cardId = cardId; } /** * 获取cardNo * * @return cardNo */ public String getCardNo() { return this.cardNo; } /** * 设置cardNo * * @param cardNo */ public void setCardNo(String cardNo) { this.cardNo = cardNo; } /** * 获取activityId * * @return activityId */ public String getActivityId() { return this.activityId; } /** * 设置activityId * * @param activityId */ public void setActivityId(String activityId) { this.activityId = activityId; } /** * 获取activityNo * * @return activityNo */ public String getActivityNo() { return this.activityNo; } /** * 设置activityNo * * @param activityNo */ public void setActivityNo(String activityNo) { this.activityNo = activityNo; } /** * 获取recordId * * @return recordId */ public String getRecordId() { return this.recordId; } /** * 设置recordId * * @param recordId */ public void setRecordId(String recordId) { this.recordId = recordId; } /** * 获取recordNo * * @return recordNo */ public String getRecordNo() { return this.recordNo; } /** * 设置recordNo * * @param recordNo */ public void setRecordNo(String recordNo) { this.recordNo = recordNo; } /** * 获取code * * @return code */ public String getCode() { return this.code; } /** * 设置code * * @param code */ public void setCode(String code) { this.code = code; } /** * 获取name * * @return name */ public String getName() { return this.name; } /** * 设置name * * @param name */ public void setName(String name) { this.name = name; } /** * 获取spec * * @return spec */ public String getSpec() { return this.spec; } /** * 设置spec * * @param spec */ public void setSpec(String spec) { this.spec = spec; } /** * 获取unit * * @return unit */ public String getUnit() { return this.unit; } /** * 设置unit * * @param unit */ public void setUnit(String unit) { this.unit = unit; } /** * 获取num * * @return num */ public BigDecimal getNum() { return this.num; } /** * 设置num * * @param num */ public void setNum(BigDecimal num) { this.num = num; } /** * 获取price * * @return price */ public BigDecimal getPrice() { return this.price; } /** * 设置price * * @param price */ public void setPrice(BigDecimal price) { this.price = price; } /** * 获取治疗费、X光费、化验费 * * @return 治疗费、X光费、化验费 */ public String getType() { return this.type; } /** * 设置治疗费、X光费、化验费 * * @param type * 治疗费、X光费、化验费 */ public void setType(String type) { this.type = type; } /** * 获取miType * * @return miType */ public String getMiType() { return this.miType; } /** * 设置miType * * @param miType */ public void setMiType(String miType) { this.miType = miType; } /** * 获取myselfScale * * @return myselfScale */ public BigDecimal getMyselfScale() { return this.myselfScale; } /** * 设置myselfScale * * @param myselfScale */ public void setMyselfScale(BigDecimal myselfScale) { this.myselfScale = myselfScale; } /** * 获取cost * * @return cost */ public BigDecimal getCost() { return this.cost; } /** * 设置cost * * @param cost */ public void setCost(BigDecimal cost) { this.cost = cost; } /** * 获取amount * * @return amount */ public BigDecimal getAmount() { return this.amount; } /** * 设置amount * * @param amount */ public void setAmount(BigDecimal amount) { this.amount = amount; } /** * 获取realAmount * * @return realAmount */ public BigDecimal getRealAmount() { return this.realAmount; } /** * 设置realAmount * * @param realAmount */ public void setRealAmount(BigDecimal realAmount) { this.realAmount = realAmount; } /** * 获取recordTime * * @return recordTime */ public Date getrecordTime() { return this.recordTime; } /** * 设置recordTime * * @param recordTime */ public void setRecordTime(Date recordTime) { this.recordTime = recordTime; } /** * 获取invoiceNo * * @return invoiceNo */ public String getInvoiceNo() { return this.invoiceNo; } /** * 设置invoiceNo * * @param invoiceNo */ public void setInvoiceNo(String invoiceNo) { this.invoiceNo = invoiceNo; } /** * 获取invoiceTime * * @return invoiceTime */ public Date getInvoiceTime() { return this.invoiceTime; } /** * 设置invoiceTime * * @param invoiceTime */ public void setInvoiceTime(Date invoiceTime) { this.invoiceTime = invoiceTime; } /** * 获取chargeId * * @return chargeId */ public String getChargeId() { return this.chargeId; } /** * 设置chargeId * * @param chargeId */ public void setChargeId(String chargeId) { this.chargeId = chargeId; } /** * 获取chargeNo * * @return chargeNo */ public String getChargeNo() { return this.chargeNo; } /** * 设置chargeNo * * @param chargeNo */ public void setChargeNo(String chargeNo) { this.chargeNo = chargeNo; } /** * 获取chargeUser * * @return chargeUser */ public String getChargeUser() { return this.chargeUser; } /** * 设置chargeUser * * @param chargeUser */ public void setChargeUser(String chargeUser) { this.chargeUser = chargeUser; } /** * 获取chargeTime * * @return chargeTime */ public Date getChargeTime() { return this.chargeTime; } /** * 设置chargeTime * * @param chargeTime */ public void setChargeTime(Date chargeTime) { this.chargeTime = chargeTime; } /** * 获取comment * * @return comment */ public String getComment() { return this.comment; } /** * 设置comment * * @param comment */ public void setComment(String comment) { this.comment = comment; } /** * 获取status * * @return status */ public String getStatus() { return this.status; } /** * 设置status * * @param status */ public void setStatus(String status) { this.status = status; } }
import java.util.Iterator; import java.io.*; public class Student implements Student_{ String name; String entryNo; String hostel; String department; String completedCredits; String cgpa; LL<CourseGrade> courseList; //Constructor public Student(String a, String b, String c, String d) { name = a; entryNo = b; hostel = c; department = d; this.courseList = new LL<CourseGrade>(); //write for completedCredits and CGPA calculation } //Courseiter class class Courseiter implements Iterator<CourseGrade>{ Position_<CourseGrade> obj; public Courseiter(LL<CourseGrade> courseList) { obj = courseList.getHead(); } public boolean hasNext() { return (obj != null); } public CourseGrade next() { if(obj!=null) { Position_<CourseGrade> temp = obj; obj = obj.after(); return temp.value(); } return null; } } //Method to add a course public void addCourse(CourseGrade ob) { courseList.add(ob); } //Inherited methods public Iterator<CourseGrade> courseList() { return new Courseiter(this.courseList); } public String name() { return name; } public String entryNo() { return entryNo; } public String hostel() { return hostel; } public String department() { return department; } public String completedCredits() { Iterator<CourseGrade> obj = this.courseList(); Integer count = 0; while(obj.hasNext() && !obj.next().g.equals("I") && !obj.next().g.equals("E") && !obj.next().g.equals("F")) { count+=1; } count *= 3; completedCredits = count.toString(); return completedCredits; } public String cgpa() { Iterator<CourseGrade> obj = this.courseList(); Integer nmr = 0; Integer dmr = 0; while(obj.hasNext()) { CourseGrade temp = obj.next(); if(!temp.g.equals("I")) {nmr += temp.gradepoint; dmr++;} } if(dmr == 0) return "0.00"; Double cg = (double)nmr/(double)dmr; cgpa =cg.toString(); cgpa = cgpa.format("%.2f", cg); return cgpa; } }
/* * Copyright (c) 2020 Nikifor Fedorov * 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. * SPDX-License-Identifier: Apache-2.0 * Contributors: * Nikifor Fedorov and others */ package ru.krivocraft.tortoise.core.utils; public class Milliseconds { private final int millis; public Milliseconds(int millis) { //todo: consider throwing IllegalArgumentException for negative values this.millis = millis; } public int seconds() { return (int) Math.ceil(millis / 1000f); } }
import java.util.Scanner; public class Example1 { static void ex1(int x, int y){ System.out.println("정수를 입력하시오 : " + x); System.out.println("정수를 입력하시오 : " + y); if(x%y==0) System.out.println("약수입니다."); else System.out.println("약수가 아닙니다."); } static void ex2(int x, int y){ System.out.println("키를 입력하시오(cm) : " + x); System.out.println("나이를 입력하시오 : " + y); if(x >= 140 && y >=10) System.out.println("타도 좋습니다."); else System.out.println("죄송합니다."); } static void ex3(int x, int y){ System.out.println("체중과 키를 입력하시오(키, 체중) : "+ x + " " + y); if(((x-100)*0.9) < y) System.out.println("과체중"); else if(((x-100)*0.9) > y) System.out.println("저체중"); else System.out.println("정상체중"); } static void ex4(int x, int y){ System.out.println("5시(17시) 이전-> 어른 34000, 소인(3~12세, 65이상) 25000"); System.out.println("5시(17시) 이후 10000"); System.out.println("현재 시간과 나이를 입력하시오 : "+ x + " " + y); if(x < 17 && (y > 12 && 65 > y)) System.out.println("요금은 34000원입니다."); else if(x < 17) System.out.println("요금은 25000원입니다."); else System.out.println("요금은 10000원입니다."); } static void ex5(int x){ int a; if(x>0) a = x / x; else if(x < 0) a = x / -x; else a = x; System.out.println("x의 값을 입력하시오 : " + x); switch(a){ case 1 : System.out.println("f(x)의 값은 " + ((7.0 * x) + 2)); break; case 0 : case -1: System.out.println("f(x)의 값은 " + ((x*x*x) - (9*x) + 2.0)); break; default : } } static void ex6(int x, int y){ //System.out.println("좌표(x, y)" + x + " " + y); if(x > 0 && y > 0) System.out.println("1사분면"); else if(x < 0 && y > 0) System.out.println("2사분면"); else if(x < 0 && y < 0) System.out.println("3사분면"); else System.out.println("4사분면"); } public static void main(String[] args) { Scanner sc= new Scanner(System.in); //ex1(10,5); //ex1(10,3); //ex2(145, 11); //ex2(139, 10); //ex3(180, 80); //ex3(180, 60); //ex3(180, 72); //ex4(22, 20); //ex4(12, 20); //ex4(12, 12); //ex5(0); //ex5(1); System.out.print("좌표(x, y) : "); ex6(sc.nextInt(), sc.nextInt()); } }
package com.lotbyte.inter; import java.util.function.Predicate; import java.util.function.Supplier; @FunctionalInterface public interface ThrowingPredicate<T,E extends Exception>{ boolean test(T t) throws E; static <T> Predicate<T> predicateWrapper(ThrowingPredicate<T,Exception> throwingSupplier){ return (s)->{ // 这里进行异常捕捉 消除lambda try catch 代码 try { return throwingSupplier.test(s); }catch (Exception ex){ throw new RuntimeException(ex); } }; } }
package com.yukai.monash.student_seek; import android.app.Dialog; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.util.Base64; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import cz.msebera.android.httpclient.Header; /** * Created by yukaima on 18/05/16. */ public class Signup_Activity extends AppCompatActivity implements View.OnClickListener{ private Button btn_signup; private EditText firstname; private EditText lastname; private EditText email; private EditText password; private com.yukai.monash.student_seek.RoundImageView addPhoto; private String fn; private String ln; private String sEmail; private String pwd; private View inflate; private TextView choosePhoto; private TextView takePhoto; private Dialog dialog; private static int CAMERA_REQUEST_CODE = 1; private static int GALLERY_REQUEST_CODE = 2; private static int CROP_REQUEST_CODE = 3; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); btn_signup = (Button)findViewById(R.id.btn_signup_finish); firstname = (EditText)findViewById(R.id.et_signupfn); lastname = (EditText)findViewById(R.id.et_signupln); email = (EditText)findViewById(R.id.et_signupemail); password = (EditText)findViewById(R.id.et_signuppwd); addPhoto = (com.yukai.monash.student_seek.RoundImageView)findViewById(R.id.addphoto); btn_signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fn = firstname.getText().toString(); ln = lastname.getText().toString(); sEmail = email.getText().toString(); pwd = password.getText().toString(); if(fn.equals("") || ln.equals("") || sEmail.equals("") || pwd.equals("")) { Toast.makeText(Signup_Activity.this,"Do not leave blank.",Toast.LENGTH_LONG).show(); } else { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.add("firstname",fn); params.add("lastname",ln); params.add("email",sEmail); params.add("password",pwd); client.post("http://173.255.245.239/jobs/user_signup.php", params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String response = new String(responseBody); JSONObject object = null; try { object = new JSONObject(response); String status = object.getString("status"); if(status.equals("exists")) { Toast.makeText(Signup_Activity.this,"User exists,please change.",Toast.LENGTH_LONG).show(); }else if(status.equals("error")) { Toast.makeText(Signup_Activity.this,"Error,please retry.",Toast.LENGTH_LONG).show(); } else if(status.equals("success")) { Toast.makeText(Signup_Activity.this,"Register successfully.",Toast.LENGTH_LONG).show(); Intent intent = new Intent(Signup_Activity.this,JobSeekerHomePage_Activity.class); intent.putExtra("email",sEmail); SharedPreferenceHelper sharedPreferenceHelper = new SharedPreferenceHelper(Signup_Activity.this,"Login Credentials"); sharedPreferenceHelper.savePreferences("status", "login"); startActivity(intent); Signup_Activity.this.finish(); } }catch (JSONException e){} } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } }); } } }); addPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addPhoto(); } }); } public void addPhoto() { dialog = new Dialog(Signup_Activity.this,R.style.ActionSheetDialogStyle); inflate = LayoutInflater.from(Signup_Activity.this).inflate(R.layout.dialog_layout, null); choosePhoto = (TextView) inflate.findViewById(R.id.choosePhoto); takePhoto = (TextView) inflate.findViewById(R.id.takePhoto); choosePhoto.setOnClickListener(Signup_Activity.this); takePhoto.setOnClickListener(Signup_Activity.this); dialog.setContentView(inflate); Window dialogWindow = dialog.getWindow(); dialogWindow.setGravity( Gravity.BOTTOM); WindowManager.LayoutParams lp = dialogWindow.getAttributes(); lp.y = 20; dialogWindow.setAttributes(lp); dialog.show(); } @Override protected void onActivityResult(int requestcode, int resultcode, Intent data) { if(requestcode== CAMERA_REQUEST_CODE) { if(data == null) { return; } else { Bundle extras = data.getExtras(); if(extras != null) { Bitmap bm = extras.getParcelable("data"); // Uri uri = saveBitmap(bm); // Bitmap bitmap = null; // try { // bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri); // } catch (IOException e) { // e.printStackTrace(); // } addPhoto.setImageBitmap(bm); sendImage(bm); // startImageZoom(uri); } } } else if(requestcode == GALLERY_REQUEST_CODE) { if(data == null) { return; } Uri uri; uri = data.getData(); Uri fileuri = convertUri(uri); Bitmap bitmap = null; try { bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri); } catch (IOException e) { e.printStackTrace(); } addPhoto.setImageBitmap(bitmap); sendImage(bitmap); // startImageZoom(fileuri); } // else if (requestcode == CROP_REQUEST_CODE) // { // // data from crop // if (data == null) // { // return; // } // Bitmap bitmap = data.getParcelableExtra("data"); // roundImageView.setImageBitmap(bitmap); // // } } private Uri saveBitmap(Bitmap bm) { File tmpDir = new File(Environment.getExternalStorageDirectory()+ "/com.monash.yukai"); if(!tmpDir.exists()) { tmpDir.mkdir(); } File img = new File (tmpDir.getAbsolutePath() + "usericon.png"); try { FileOutputStream fos = new FileOutputStream(img); bm.compress(Bitmap.CompressFormat.PNG,85,fos); fos.flush(); fos.close(); return Uri.fromFile(img); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } } //convert content Uri to file Uri private Uri convertUri(Uri uri) { InputStream is = null; try { is = getContentResolver().openInputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(is); is.close(); saveBitmap(bitmap); }catch (FileNotFoundException e) {e.printStackTrace(); return null;} catch (IOException e){e.printStackTrace();} return null; } //send image to specific server public void sendImage(Bitmap bm) { //convert bitmap to string type with Base64 ByteArrayOutputStream stream = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 60, stream); byte[] bytes = stream.toByteArray(); String img = new String(Base64.encodeToString(bytes, Base64.DEFAULT)); AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.add("img",img); params.add("userid", "1"); client.post("http://173.255.245.239/stu_seek/Image/ImageUpload.php", params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { Toast.makeText(Signup_Activity.this, "upload success", Toast.LENGTH_LONG).show(); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { Toast.makeText(Signup_Activity.this, "upload fail", Toast.LENGTH_LONG).show(); } }); } // set onclick listener for pop up dialog @Override public void onClick(View view) { switch (view.getId()){ case R.id.takePhoto: // create Intent to take a picture and return control to the calling application Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, CAMERA_REQUEST_CODE); break; case R.id.choosePhoto: // Intent intentOfChoosePhoto = new Intent(Intent.ACTION_GET_CONTENT); intentOfChoosePhoto.setType("image/*"); startActivityForResult(intentOfChoosePhoto,GALLERY_REQUEST_CODE); break; } dialog.dismiss(); } }
package zoku.sample.spring.websample1; import org.springframework.context.ApplicationListener; public class SampleEventListener implements ApplicationListener<SampleBeanEvent> { public void onApplicationEvent(SampleBeanEvent event) { System.out.println("SampleEvent is occured!!"); } }
package gradedGroupProject; import java.util.Scanner; public class KeyInput { public String read( String label ) { System.out.println( "\nProvide " + label + ":" ); System.out.println( ">" ); @SuppressWarnings("resource") Scanner scanner = new Scanner( System.in ); String value = scanner.nextLine(); return value; } }
package pro.likada.bot.products.commands; import org.telegram.telegrambots.api.methods.send.SendMessage; import org.telegram.telegrambots.api.objects.Chat; import org.telegram.telegrambots.api.objects.User; import org.telegram.telegrambots.bots.AbsSender; import org.telegram.telegrambots.bots.commands.BotCommand; import org.telegram.telegrambots.exceptions.TelegramApiException; import org.telegram.telegrambots.logging.BotLogger; import pro.likada.dao.daoImpl.TelegramUserDAOImpl; import pro.likada.model.TelegramUser; import javax.enterprise.context.Dependent; import javax.inject.Named; @Named @Dependent public class HelloCommand extends BotCommand { private static final String LOGTAG = "HELLOCOMMAND"; private static TelegramUserDAOImpl telegramUserDAO= new TelegramUserDAOImpl(); public HelloCommand() { super("hello", "Отправьте команду чтобы получить уведомления об изменении цены"); } @Override public void execute(AbsSender absSender, User user, Chat chat, String[] arguments) { String userName = chat.getFirstName(); if (userName == null || userName.isEmpty()) { userName = user.getFirstName(); } if(telegramUserDAO.findByTelegramUserId(user.getId())!=null && !telegramUserDAO.findByTelegramUserId(user.getId()).isActive()){ TelegramUser telegramUser=telegramUserDAO.findByTelegramUserId(user.getId()); telegramUser.setActive(true); telegramUser.setConversations(null); telegramUserDAO.save(telegramUser); } StringBuilder messageTextBuilder = new StringBuilder(userName).append(" ваш профиль активный и можете получить информацию об изменении цены"); if (arguments != null && arguments.length > 0) { messageTextBuilder.append("\n"); messageTextBuilder.append("Ваш логин зарегистрирован:\n"); messageTextBuilder.append(String.join(" ", arguments)); } SendMessage answer = new SendMessage(); answer.setChatId(chat.getId().toString()); answer.setText(messageTextBuilder.toString()); try { absSender.sendMessage(answer); } catch (TelegramApiException e) { BotLogger.error(LOGTAG, e); } } }
package myProject.third; public class EnemyMotorLevel2 { public EnemyMotorLevel2() { // TODO Auto-generated constructor stub } }
package uzparser; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class EmailSender { private static final String USERNAME_TO = "ks.13.bogdan@gmail.com"; private static final String USERNAME_FROM = "ks.13.bogdan@gmail.com"; private static final String PASSWORD = "51020c2332Ks54107"; private static final String TEXT = "Hello!"; private static final String SUBJECT = "Booking uz.gov.ua"; public void send(String respons) { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(USERNAME_FROM, PASSWORD); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(USERNAME_FROM)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(USERNAME_TO)); message.setSubject(SUBJECT); message.setText(TEXT + " " + respons); System.out.println(respons); Transport.send(message); System.out.println("Email sent"); } catch (MessagingException e) { System.out.println("Email was not sent"); } } }
public class message { private String sender; private String recipient; private String text; public message(String sender, String recipient) { super(); this.recipient = recipient; this.sender = sender; this.text =""; } public String toString() { return "From: " + sender + "%n" + "To: "+ recipient + "%n" + "Text: "+ text; } public void append(String T) { text = text + T; } }
/* * @(#) EbmsMessageHistoryLogDAO.java * Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved. */ package com.esum.wp.ebms.ebmsmessagehistorylog.dao.impl; import java.util.List; import com.esum.appframework.exception.ApplicationException; import com.esum.appframework.dao.impl.SqlMapDAO; import com.esum.wp.ebms.ebmsmessagehistorylog.dao.IEbmsMessageHistoryLogDAO; /** * * @author heowon@esumtech.com * @version $Revision: 1.2 $ $Date: 2007/06/20 09:36:54 $ */ public class EbmsMessageHistoryLogDAO extends SqlMapDAO implements IEbmsMessageHistoryLogDAO { /** * Default constructor. Can be used in place of getInstance() */ public EbmsMessageHistoryLogDAO () {} public String historyListID = ""; public List historyList(Object object) throws ApplicationException { try { return getSqlMapClientTemplate().queryForList(historyListID, object); } catch (Exception e) { throw new ApplicationException(e); } } public String getHistoryListID() { return historyListID; } public void setHistoryListID(String historyListID) { this.historyListID = historyListID; } }
package com.guang.util; import android.content.Context; import com.umeng.analytics.MobclickAgent; //获取友盟在线参数 public class NetworkUtil { /** * 根据友盟判断是否打开Dialog开关 * * @return */ public static boolean getIsOpen(Context context) { MobclickAgent.updateOnlineConfig(context); String datas = MobclickAgent.getConfigParams(context, "cjOpen"); return datas.equals("1") ? true : false; } /** * 获取友盟提供的app名称 * */ public static String getName(Context context) { MobclickAgent.updateOnlineConfig(context); return MobclickAgent.getConfigParams(context, "cjName"); } /** * 获取友盟提供的提示内容 * */ public static String getContet(Context context) { MobclickAgent.updateOnlineConfig(context); return MobclickAgent.getConfigParams(context, "cjContent"); } /** * 获取友盟提供的下载链接 * */ public static String getUrl(Context context) { MobclickAgent.updateOnlineConfig(context); return MobclickAgent.getConfigParams(context, "cjUrl"); } }
import java.io.*; class ThreadPriorityTest implements Runnable { public void run() { System.out.println(" Thread under running"); System.out.println(Thread.currentThread().getName()); } public static void main(String args[]) { ThreadPriorityTest tp1 = new ThreadPriorityTest(); Thread t1 = new Thread(tp1); ThreadPriorityTest tp2 = new ThreadPriorityTest(); Thread t2 = new Thread(tp2); t2.setPriority(Thread.MIN_PRIORITY); t1.setPriority(Thread.MAX_PRIORITY); t2.setName("Nax"); t2.start(); t1.start(); } }
package com.myth.springboot.service; import com.myth.springboot.dao.AdminMapper; import com.myth.springboot.dao.ClassMapper; import com.myth.springboot.entity.Class; import com.myth.springboot.entity.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ClassService { @Autowired ClassMapper mapper; //班级新增,查询,修改,删除 public int classInsert(Class cla){ return mapper.classInsert(cla); } public List<Class> classSelect(Class cla){ return mapper.classSelect(cla); } public int classUpdateById(Class cla){ return mapper.classUpdateById(cla); } public int classDeleteById(Class cla){ return mapper.classDeleteById(cla); } }
import java.util.Scanner; /** * Created by Administrator on 2017/8/8. */ public class chapter3_10 { public static void main(String[] args){ Scanner in = new Scanner(System.in); System.out.println("请输入整数."); int number = in.nextInt(); if (number==0){ System.out.println("请不要输入0好吗"); }else{ if(number%2==0){ System.out.println(number+"它是一个偶数."); }else { System.out.println(number+"它是一个奇数."); } } } }
package comp303.fivehundred.ai; import static comp303.fivehundred.util.AllCards.*; import static comp303.fivehundred.util.AllBids.*; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import comp303.fivehundred.ai.basic.BasicBiddingStrategy; import comp303.fivehundred.model.Bid; import comp303.fivehundred.model.Hand; /** * @author Stephanie Pataracchia 260407002 */ public class TestBasicBiddingStrategy { Bid pBid; Bid[] pBids1 = new Bid[0]; Bid[] pBids2 = new Bid[3]; Bid[] pBids3 = new Bid[3]; Bid[] pBids4 = new Bid[3]; Hand pHand; BasicBiddingStrategy bidding; @Before public void init() { // not partner nor opponent has bid Diamonds pBids2[0] = new Bid(0); pBids2[1] = new Bid(5); pBids2[2] = new Bid(11); // partner has bid Diamonds pBids3[0] = new Bid(0); pBids3[1] = new Bid(2); pBids3[2] = new Bid(11); // opponent has bid Diamonds pBids4[0] = new Bid(0); pBids4[1] = new Bid(5); pBids4[2] = new Bid(2); pHand = new Hand(); bidding = new BasicBiddingStrategy(); } /******************************** * #1 BIDDING first ********************************/ // bid 7 diamonds // 9 pts= 4(HJo) + 2(RJ) + 1(Ace) +2(threshold) @Test public void firstBid06() { pHand.add(aHJo); pHand.add(aJD); pHand.add(aAD); pHand.add(a4D); pHand.add(a5D); pHand.add(a6D); pHand.add(a7D); pHand.add(a5S); pHand.add(a5H); pHand.add(a5C); assertEquals(bidding.selectBid(pBids1, pHand), aBid7D); } // bid 7 diamonds // 10 pts= 3(LJo) + 2(RJ) + 2(LJ) + 1(K) +2(threshold) @Test public void firstBid07() { pHand.add(aLJo); pHand.add(aJD); pHand.add(aJH); pHand.add(aKD); pHand.add(a4D); pHand.add(a5D); pHand.add(a6D); pHand.add(a7S); pHand.add(a5H); pHand.add(a5C); assertEquals(bidding.selectBid(pBids1, pHand), aBid7D); } // bid 8 diamonds // 11 pts= 3(LJo) + 2(RJ) + 2(LJ) + 1(K) + 1(Ace) +2(threshold) @Test public void firstBid08() { pHand.add(aLJo); pHand.add(aJD); pHand.add(aJH); pHand.add(aKD); pHand.add(aAD); pHand.add(a4D); pHand.add(a5D); pHand.add(a6C); pHand.add(a7S); pHand.add(a5H); assertEquals(bidding.selectBid(pBids1, pHand), aBid8D); } // bid 8 diamonds // 12 pts= 3(LJo) + 2(RJ) + 2(LJ) + 1(K) +1(Q) +1(Ace) +2(threshold) @Test public void firstBid09() { pHand.add(aLJo); pHand.add(aJD); pHand.add(aJH); pHand.add(aKD); pHand.add(aQD); pHand.add(aAD); pHand.add(a9D); pHand.add(a6C); pHand.add(a7S); pHand.add(a5H); assertEquals(bidding.selectBid(pBids1, pHand), aBid8D); } // bid 9 diamonds // 13 pts= 4(HJo) +3(LJo) + 2(LJ) + 4(threshold) @Test public void firstBid10() { pHand.add(aHJo); pHand.add(aLJo); pHand.add(aJH); pHand.add(a4D); pHand.add(a5D); pHand.add(a6D); pHand.add(a7D); pHand.add(a8D); pHand.add(a9D); pHand.add(a5H); assertEquals(bidding.selectBid(pBids1, pHand), aBid9D); } // FIRST BID - NO TRUMP // bid 7 no-trump // 9 pts= 4(HJo) + 2(A)+ 2(A) + 1(Q) @Test public void firstNTBid06() { pHand.add(aHJo); pHand.add(aAS); pHand.add(aAD); pHand.add(aQS); pHand.add(a4H); pHand.add(a4S); pHand.add(a4C); pHand.add(a5D); pHand.add(a5C); pHand.add(a5H); assertEquals(bidding.selectBid(pBids1, pHand), aBid7N); } // bid 7 no-trump // 10 pts= 2(A)+ 2(A) +2(A)+ 2(A) + 1(Q) + 1(J) @Test public void firstNTBid07() { pHand.add(aAH); pHand.add(aAS); pHand.add(aAD); pHand.add(aAC); pHand.add(aQH); pHand.add(aJS); pHand.add(a4C); pHand.add(a5D); pHand.add(a5C); pHand.add(a5H); assertEquals(bidding.selectBid(pBids1, pHand), aBid7N); } // bid 8 no-trump // 10 pts= 1(Q) + 1(Q) + 1(Q) + 1(Q) + 1(J) + 1(J) + 1(J) + 1(J) + 2(A) @Test public void firstNTBid08() { pHand.add(aQH); pHand.add(aQS); pHand.add(aQD); pHand.add(aQC); pHand.add(aJH); pHand.add(aJS); pHand.add(aJD); pHand.add(aJC); pHand.add(aAS); pHand.add(a4H); assertEquals(bidding.selectBid(pBids1, pHand), aBid7N); } // bid 8 no-trump // 11 pts= 4(HJo) + 3(LJo) + 2(A)+ 1(K) + 1(Q) @Test public void firstNTBid09() { pHand.add(aHJo); pHand.add(aLJo); pHand.add(aAD); pHand.add(aKS); pHand.add(aQS); pHand.add(a4S); pHand.add(a4C); pHand.add(a5D); pHand.add(a5C); pHand.add(a5H); assertEquals(bidding.selectBid(pBids1, pHand), aBid8N); } // bid 8 no-trump // 11 pts= 3(LJo) + 1(K) + 1(Q) + 1(Q) + 1(Q) + 1(Q) + 1(J) + 1(J) + 1(J) + 1(J) @Test public void firstNTBid10() { pHand.add(aLJo); pHand.add(aKS); pHand.add(aQH); pHand.add(aQS); pHand.add(aQD); pHand.add(aQC); pHand.add(aJH); pHand.add(aJS); pHand.add(aJD); pHand.add(aJC); assertEquals(bidding.selectBid(pBids1, pHand), aBid8N); } /***************************************** * #2 LAST BID - NO ONE BID SUIT *******************************************/ // 9 pts= 4(HJo) + 2(RJ) + 1(Ace) + 2(threshold), but previous bids are better @Test public void lastBid06() { pHand.add(aHJo); pHand.add(aJD); pHand.add(aAD); pHand.add(a4D); pHand.add(a5D); pHand.add(a6D); pHand.add(a7D); pHand.add(a5S); pHand.add(a5H); pHand.add(a5C); assertEquals(bidding.selectBid(pBids2, pHand), aBidPass); } // 13 pts= 4(HJo) + +3(LJo) + 2(LJ) + 4(threshold) @Test public void lastBid10() { pHand.add(aHJo); pHand.add(aLJo); pHand.add(aJH); pHand.add(a4D); pHand.add(a5D); pHand.add(a6D); pHand.add(a7D); pHand.add(a8D); pHand.add(a9D); pHand.add(a5H); assertEquals(bidding.selectBid(pBids2, pHand), aBid9D); } // 9 pts= 4(HJo) + 2(A)+ 2(A) + 1(Q), but there is a better bid @Test public void lastNTBid06() { pHand.add(aHJo); pHand.add(aAS); pHand.add(aAD); pHand.add(aQS); pHand.add(a4H); pHand.add(a4S); pHand.add(a4C); pHand.add(a5D); pHand.add(a5C); pHand.add(a5H); assertEquals(bidding.selectBid(pBids2, pHand), aBidPass); } // 12 pts= 3(LJo) + 1(K) + 1(Q) + 1(Q) + 1(Q) + 1(Q) + 1(J) + 1(J) + 1(J) + 1(J) @Test public void lastNTBid10() { pHand.add(aLJo); pHand.add(aKS); pHand.add(aQH); pHand.add(aQS); pHand.add(aQD); pHand.add(aQC); pHand.add(aJH); pHand.add(aJS); pHand.add(aJD); pHand.add(aJC); assertEquals(bidding.selectBid(pBids2, pHand), aBid8N); } /****************************************** * #3 LAST BID - PARTNER BID SUIT *******************************************/ // 9 pts= 4(HJo) + 2(RJ) + 1(Ace) + 1(threshold) +1(Partner), but there is a better bid @Test public void lastPartnerBid06() { pHand.add(aHJo); pHand.add(aJD); pHand.add(aAD); pHand.add(a4D); pHand.add(a5D); pHand.add(a6D); pHand.add(a7H); pHand.add(a5S); pHand.add(a5H); pHand.add(a5C); assertEquals(bidding.selectBid(pBids3, pHand), aBidPass); } // 13 pts= 4(HJo) + +3(LJo) + 2(LJ) + 3(threshold) +1(Partner) @Test public void lastPartnerBid10() { pHand.add(aHJo); pHand.add(aLJo); pHand.add(aJH); pHand.add(a4D); pHand.add(a5D); pHand.add(a6D); pHand.add(a7D); pHand.add(a8D); pHand.add(a9S); pHand.add(a5H); assertEquals(bidding.selectBid(pBids3, pHand), aBid9D); } // 9 pts= 4(HJo) + 2(A)+ 2(A) +1(Partner), but there is a better bid @Test public void lastPartnerNTBid06() { pHand.add(aHJo); pHand.add(aAS); pHand.add(aAD); pHand.add(a7S); pHand.add(a4H); pHand.add(a4S); pHand.add(a4C); pHand.add(a5D); pHand.add(a5C); pHand.add(a5H); assertEquals(bidding.selectBid(pBids3, pHand), aBidPass); } // 11 pts= 3(LJo) + 1(K) + 1(Q) + 1(Q) + 1(Q) + 1(Q) + 1(J) + 1(J) + 1(J) @Test public void lastPartnerNTBid10() { pHand.add(aLJo); pHand.add(aKS); pHand.add(aQH); pHand.add(aQS); pHand.add(aQD); pHand.add(aQC); pHand.add(aJH); pHand.add(aJS); pHand.add(aJD); pHand.add(a4C); assertEquals(bidding.selectBid(pBids3, pHand), aBid8N); } /****************************************** * #4 LAST BID - OPPONENT BID SUIT ******************************************/ // 9 pts= 4(HJo) + 2(RJ) + 1(Ace) + 3(threshold) -1(Opponent) @Test public void lastOpponentBid06() { pHand.add(aHJo); pHand.add(aJD); pHand.add(aAD); pHand.add(a4D); pHand.add(a5D); pHand.add(a6D); pHand.add(a7D); pHand.add(a8D); pHand.add(a5H); pHand.add(a5C); assertEquals(bidding.selectBid(pBids4, pHand), aBid7D); } // 13 pts= 4(HJo) + +3(LJo) + 2(LJ) + 5(threshold) -1(Opponent) @Test public void lastOpponentBid10() { pHand.add(aHJo); pHand.add(aLJo); pHand.add(aJH); pHand.add(a4D); pHand.add(a5D); pHand.add(a6D); pHand.add(a7D); pHand.add(a8D); pHand.add(a9D); pHand.add(aTD); assertEquals(bidding.selectBid(pBids4, pHand), aBid9D); } // 9 pts= 4(HJo) + 2(A)+ 2(A) + 1(Q) + 1(Q) -1(Opponent) @Test public void lastOpponentNTBid06() { pHand.add(aHJo); pHand.add(aAS); pHand.add(aAD); pHand.add(aQS); pHand.add(aQC); pHand.add(a4S); pHand.add(a4C); pHand.add(a5D); pHand.add(a5C); pHand.add(a5H); assertEquals(bidding.selectBid(pBids4, pHand), aBid7N); } // 11 pts= 3(LJo) + 1(K) + 1(K) + 1(Q) + 1(Q) + 1(Q) + 1(J) + 1(J) + 1(J) + 1(J) -1(Opponent) @Test public void lastOpponentNTBid10() { pHand.add(aLJo); pHand.add(aKS); pHand.add(aKH); pHand.add(aQS); pHand.add(aQD); pHand.add(aQC); pHand.add(aJH); pHand.add(aJS); pHand.add(aJD); pHand.add(aJC); assertEquals(bidding.selectBid(pBids4, pHand), aBid8N); } }
package com.aca.swap; import java.util.Scanner; public class SwapTest { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please input the first number: "); IntegerWrapper number1 = new IntegerWrapper(5); IntegerWrapper number2 = new IntegerWrapper(100); number1.setNumber(scanner.nextInt()); System.out.println("Please input the second number: "); number2.setNumber(scanner.nextInt()); IntegerWrapper.swap(number1, number2); System.out.println("a1 = " + number1.getNumber()); System.out.println("a2 = " + number2.getNumber()); } }
package adefault.loginscreen; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import adefault.loginscreen.model.Planet; public class PlanetDetails extends AppCompatActivity { TextView rotation_period, climate, population,title,diamter,gravity,surface_water; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_planet_details); rotation_period = findViewById(R.id.rotationPeriod); climate = findViewById(R.id.climate); population = findViewById(R.id.population); title=findViewById(R.id.title); Planet planet = (Planet)getIntent().getSerializableExtra("planet"); rotation_period.setText(planet.rotationPeriod); climate.setText(planet.climate); population.setText(planet.population); title.setText(planet.name); } }
/** * Copyright 2014 Bill McDowell * * This file is part of theMess (https://github.com/forkunited/theMess) * * 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 ark.data.annotation; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import net.sf.json.JSONObject; import ark.data.annotation.nlp.ConstituencyParse; import ark.data.annotation.nlp.DependencyParse; import ark.data.annotation.nlp.PoSTag; import ark.util.FileUtil; /** * * Document represents a JSON-serializable text document with * various NLP annotations (e.g. PoS tags, parses, etc). The methods * for getting the NLP annotations are kept abstract so * that they can be implemented in ways that allow for * caching in cases when all of the documents don't fit * in memory. In-memory implementations of these methods * are given by the ark.data.annotation.DocumentInMemory * class. * * @author Bill McDowell * */ public abstract class Document { protected String name; protected Language language; protected String nlpAnnotator; public Document() { } public Document(JSONObject json) { fromJSON(json); } public Document(String jsonPath) { BufferedReader r = FileUtil.getFileReader(jsonPath); String line = null; StringBuffer lines = new StringBuffer(); try { while ((line = r.readLine()) != null) { lines.append(line).append("\n"); } } catch (IOException e) { e.printStackTrace(); } fromJSON(JSONObject.fromObject(lines.toString())); } public String getName() { return this.name; } public Language getLanguage() { return this.language; } public String getNLPAnnotator() { return this.nlpAnnotator; } public List<String> getSentenceTokens(int sentenceIndex) { int sentenceTokenCount = getSentenceTokenCount(sentenceIndex); List<String> sentenceTokens = new ArrayList<String>(sentenceTokenCount); for (int i = 0; i < sentenceTokenCount; i++) sentenceTokens.add(getToken(sentenceIndex, i)); return sentenceTokens; } public List<PoSTag> getSentencePoSTags(int sentenceIndex) { int sentenceTokenCount = getSentenceTokenCount(sentenceIndex); List<PoSTag> sentencePoSTags = new ArrayList<PoSTag>(sentenceTokenCount); for (int i = 0; i < sentenceTokenCount; i++) sentencePoSTags.add(getPoSTag(sentenceIndex, i)); return sentencePoSTags; } public boolean saveToJSONFile(String path) { try { BufferedWriter w = new BufferedWriter(new FileWriter(path)); w.write(toJSON().toString()); w.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } public abstract int getSentenceCount(); public abstract int getSentenceTokenCount(int sentenceIndex); public abstract String getText(); public abstract String getSentence(int sentenceIndex); public abstract String getToken(int sentenceIndex, int tokenIndex); public abstract PoSTag getPoSTag(int sentenceIndex, int tokenIndex); public abstract ConstituencyParse getConstituencyParse(int sentenceIndex); public abstract DependencyParse getDependencyParse(int sentenceIndex); public abstract JSONObject toJSON(); public abstract Document makeInstanceFromJSONFile(String path); protected abstract boolean fromJSON(JSONObject json); }
package com.damlakayali.notdefterim; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class NoteInsert extends AppCompatActivity implements AdapterView.OnItemSelectedListener { EditText headerET; EditText contentET; Spinner priority; Button btnInsert; Note n=new Note(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_note_insert); final DBHelper dbHelper = new DBHelper(getApplicationContext()); headerET=(EditText)findViewById(R.id.baslik); contentET=(EditText)findViewById(R.id.icerik); priority=(Spinner)findViewById(R.id.prioritySpinner); btnInsert=(Button)findViewById(R.id.btnInsert); priority.setOnItemSelectedListener(this); // Spinner Drop down elements List<String> categories = new ArrayList<String>(); categories.add("Çok Önemli"); categories.add("Önemli"); categories.add("Normal"); ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories); // Drop down layout style - list view with radio button dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); priority.setAdapter(dataAdapter); /* ALERT DIOLOG START */ final AlertDialog.Builder alertbox2 = new AlertDialog.Builder(this); alertbox2.setTitle("BİLGİ"); alertbox2.setMessage("Notunuz başarıyla eklendi. :)"); alertbox2.setNegativeButton("Not Listesine Git", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Intent i=new Intent(getApplicationContext(),MainActivity.class); startActivity(i); } }); alertbox2.setPositiveButton("Yeni Not Ekle", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Intent i= new Intent(getApplicationContext(),NoteInsert.class); startActivity(i); } }); // ALERT DIOLOG FINISH btnInsert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { n.setHeader(headerET.getText().toString()); n.setContent(contentET.getText().toString()); dbHelper.insertNotes(n); alertbox2.show(); } }); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String item = parent.getItemAtPosition(position).toString(); if(item.equals("Çok Önemli")){ n.setPriority(1); } if (item.equals("Önemli")){ n.setPriority(2); } if(item.equals("Normal")){ n.setPriority(3); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }
package com.lesports.albatross.activity; import android.app.LauncherActivity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Message; import android.support.v7.widget.Toolbar; import android.text.ClipboardManager; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import android.webkit.DownloadListener; import android.webkit.GeolocationPermissions; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.lesports.albatross.Constants; import com.lesports.albatross.R; import com.lesports.albatross.share.ShareNetEntity; import com.lesports.albatross.utils.StringUtils; import com.lesports.albatross.utils.Utils; import java.util.HashMap; /** * webVIew */ public class WebViewActivity extends ToolBarActivity { public static final String EXTRA_URL = "URL"; public static final String EXTRA_TITLE = "title"; public static final String EXTRA_RIGHT_ICON = "rightIcon"; public static final String PRESSED_BACKICON_IMMEDIATE_BACK = "PRESSED_BACKICON_IMMEDIATE_BACK"; public static final String RIGHT_SHARE_BUTTON_DISPLAY = "right_share_btn_display"; public static final String EXTRA_SHARE_URL = "extra_share_url"; private static final String FROM_LAUNCHER = "launcher"; private static final String FROM_RESTART_APP = "restartApp"; public static final String FROM_RICHTEXT_NEWS = "richtext"; private ProgressBar mHorizontalProgress; private WebView mWebView; private boolean mIsRightShareBtnDisplay = false; private String url; private String from; private String title; private String baseUrl; boolean rightIcon = true; // private UserCenter userCenter; private ShareNetEntity shareNetEntity; private View toolBarView; //红包相关 private int source = 0; public static final String SOURCE_FROM = "SOURCE"; public static final int FROM_RED_BAG = 0x1; private String sso_tk; private HashMap<String, String> headers; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // getWindow().requestFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.activity_web_view); // userCenter = new UserCenter(this); shareNetEntity = new ShareNetEntity(); headers = new HashMap<>(); //注销掉调起客户端的逻辑 // if (getIntent() != null) { // source = getIntent().getIntExtra(SOURCE_FROM, 0); // title = getIntent().getStringExtra(EXTRA_TITLE); // switch (source) { // case FROM_RED_BAG: // //拼接参数 // final String token1 = userCenter.getSSO_TOKEN(); // sso_tk = token1; // //final String token1 = "103d75754bUTAD6wvrbdG30kpagiTUklSl44am1IUSXcG6EBfie1Nv7vdOjTaF2yrjgAPDuvw"; // final String deviceId1 = DeviceUtil.getDeviceId(this); // final long currentTime1 = System.currentTimeMillis(); // final String auth1 = StringUtil.MD5(deviceId1 + token1 + currentTime1 + "springPackage").toLowerCase(); // // url = "http://sso.letv.com/user/setUserStatus?from=mobile&next_action=" + URLEncoder.encode(String.format(Constants.LeUrls.URL_GET_MY_RED_BAG, deviceId1, // currentTime1, auth1, RedPacketSdkUtil.APPID)); // headers.put("SSOTK", token1); // break; // case 0: // default: // if (getIntent().getData() != null && getIntent().getDataString() != null) { // String loadUrl = getIntent().getDataString(); // Uri loadUri = Uri.parse(loadUrl); // url = loadUri.getQueryParameter("url"); // // if (StringUtil.isEmpty(url)) { // from = FROM_RESTART_APP; // finish(); // } // String debug = loadUri.getQueryParameter("debug"); // String whiteKey = loadUri.getHost(); // if (whiteKey != null && (whiteKey.contains("lesports.com") || "1".equals(debug) || whiteKey.contains("letv.com"))) { // mIsRightShareBtnDisplay = true; // } // // Uri uri = Uri.parse(url); // Uri.Builder builder = Uri.parse(url).buildUpon(); // // if (uri.getScheme() == null) { // builder.scheme("http"); // } // baseUrl = builder.build().toString(); // // //拼接参数 // String token = userCenter.getSSO_TOKEN(); // String udid = DeviceUtil.getAppUniqueToken(this); // long currentTime = SystemClock.elapsedRealtime() / 1000;//此处时间服务器以秒为单位 // String key = "tooaQsrpUfvH2u3HYoDgkWLJ9RvhQ2sr"; // String auth = StringUtil.MD5(udid + currentTime + key); // // builder.appendQueryParameter("token", token).appendQueryParameter("udid", udid) // .appendQueryParameter("tm", String.valueOf(currentTime)).appendQueryParameter("auth", auth) // .appendQueryParameter("versions", "androidBasic"); // url = builder.build().toString(); // // title = loadUri.getQueryParameter("title") == null ? "" : uri.getQueryParameter("title"); // from = FROM_RESTART_APP; // } else { // url = getIntent().getStringExtra(EXTRA_URL); // Uri uri = Uri.parse(url); // Uri.Builder builder = Uri.parse(url).buildUpon(); // // if (uri.getScheme() == null) { // builder.scheme("http"); // url = builder.build().toString(); // } // // String shareUrl = getIntent().getStringExtra(EXTRA_SHARE_URL); // if (shareUrl != null) { // baseUrl = shareUrl; // } else { // baseUrl = url; // } // Uri baseUri = Uri.parse(baseUrl); // if (baseUri.getScheme() == null) { // baseUrl = baseUri.buildUpon().scheme("http").build().toString(); // } // // from = getIntent().getStringExtra("from"); // mIsRightShareBtnDisplay = getIntent().getBooleanExtra(RIGHT_SHARE_BUTTON_DISPLAY, true); // } // } // rightIcon = getIntent().getBooleanExtra(EXTRA_RIGHT_ICON, true); // initToolbar(); // } mHorizontalProgress = (ProgressBar) findViewById(R.id.progress_horizontal); refresh(); //注册登录广播接收器用于回调h5传token id // IntentFilter intentFilter = new IntentFilter(); // intentFilter.addAction(UserCenter.LOGIN_STATUS_CHANGE_ACTION); // mLoginReceiver = new LoginReceiver(); // LocalBroadcastManager.getInstance(this).registerReceiver(mLoginReceiver, intentFilter); } private void refresh() { mWebView = (WebView) findViewById(R.id.webview); String userAgent = mWebView.getSettings().getUserAgentString(); mWebView.getSettings().setUserAgentString(userAgent+" LeSportsAPP "+ Utils.getLeVersionName(this)); // 设置支持JavaScript WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(true); // webSettings.setDatabaseEnabled(true); // String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); webSettings.setGeolocationEnabled(true); // webSettings.setGeolocationDatabasePath(dir); webSettings.setDomStorageEnabled(true); webSettings.setUseWideViewPort(true); webSettings.setSavePassword(false); //5.0以上打开webView跨域携带cookie的许可 if (Build.VERSION.SDK_INT >= 21) { CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setAcceptThirdPartyCookies(mWebView, true); } mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); if (Build.VERSION.SDK_INT > 11) { mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } mWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (source == FROM_RED_BAG) { CookieSyncManager.createInstance(WebViewActivity.this); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setCookie(url, "sso_tk=" + sso_tk); // cookieManager.setCookie(".letv.com", "sso_tk=" + sso_tk); CookieSyncManager.getInstance().sync(); } Uri uri = Uri.parse(url); if (url.startsWith("tel:") || url.startsWith("mailto:")) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } else if (uri.getScheme().equals("letvsportslaunch") && uri.getHost().equals("com.lesports.glivesports")) { url = uri.getQueryParameter("url"); mWebView.loadUrl(url); return true; } else if (uri.getScheme().equals("letvclient")) { return true; } else { view.loadUrl(url); return super.shouldOverrideUrlLoading(view, url); } } @Override public void onFormResubmission(WebView view, Message dontResend, Message resend) { resend.sendToTarget(); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { view.loadUrl(Constants.DefaultUrl); Toast.makeText(view.getContext(), R.string.net_error, Toast.LENGTH_SHORT).show(); } }); mWebView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress >= 100) { if (mHorizontalProgress != null) { mHorizontalProgress.setVisibility(View.GONE); } } else { if (mHorizontalProgress != null && newProgress >= 0) { mHorizontalProgress.setVisibility(View.VISIBLE); mHorizontalProgress.setProgress(newProgress); } } } public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); super.onGeolocationPermissionsShowPrompt(origin, callback); } @Override public void onReceivedTitle(WebView view, String mTitle) { super.onReceivedTitle(view, mTitle); if (FROM_RICHTEXT_NEWS.equals(from)) { title = mTitle; ((TextView) toolBarView.findViewById(R.id.tv_action_title)).setText(mTitle); } } }); mWebView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } }); mWebView.removeJavascriptInterface("searchBoxJavaBridge_"); mWebView.removeJavascriptInterface("accessibility"); mWebView.removeJavascriptInterface("accessibilityTraversal"); // mWebView.addJavascriptInterface(new JsInterface(), "lesportJsInterface"); if (getIntent() != null) { switch (source) { case FROM_RED_BAG: /* Log.e("---url", url); mWebView.loadUrl(url, headers);*/ CookieSyncManager.createInstance(this); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setCookie(url, "sso_tk=" + sso_tk); // cookieManager.setCookie(".letv.com", "sso_tk=" + sso_tk); CookieSyncManager.getInstance().sync(); mWebView.loadUrl(url,headers); break; case 0: default: mWebView.loadUrl(url); break; } } } private void initToolbar() { mToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mToolbar); /*getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeAsUpIndicator(R.drawable.title_bar_back_arrow); getSupportActionBar().setDisplayShowTitleEnabled(true);*/ getSupportActionBar().setDisplayHomeAsUpEnabled(false); getSupportActionBar().setDisplayShowCustomEnabled(true); toolBarView = View.inflate(this, R.layout.actionbar_back_icon, null); toolBarView.findViewById(R.id.img_back_btn).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); ((TextView) toolBarView.findViewById(R.id.tv_action_title)).setText(title); getSupportActionBar().setCustomView(toolBarView); } @Override protected void onResume() { super.onResume(); mWebView.onResume(); } @Override protected void onPause() { super.onPause(); mWebView.onPause(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (mWebView.canGoBack()) { mWebView.goBack(); } else { onBackPressed(); } return true; } return super.onKeyDown(keyCode, event); } @Override public void finish() { if (FROM_LAUNCHER.equalsIgnoreCase(from)) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } else if (FROM_RESTART_APP.equalsIgnoreCase(from)) { Intent intent = new Intent(this, LauncherActivity.class); startActivity(intent); } super.finish(); } @Override public void onDestroy() { mWebView.destroy(); // if (mLoginReceiver!=null){ // LocalBroadcastManager.getInstance(this).unregisterReceiver(mLoginReceiver); // } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar if (rightIcon){ MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_webview, menu); if(!mIsRightShareBtnDisplay)menu.findItem(R.id.share).setVisible(false); if (source == FROM_RED_BAG) { menu.findItem(R.id.share).setVisible(false); menu.findItem(R.id.copy).setVisible(false); menu.findItem(R.id.open_in_explore).setVisible(false); } } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.share: // ShareNetEntity shareEntity = new ShareNetEntity(); // shareEntity.url = baseUrl; // shareEntity.title = title; // ShareService.addShareLayout(WebViewActivity.this, shareEntity, ShowShareDialog.FROM_WEBVIEW); break; case R.id.copy: if (StringUtils.isEmpty(baseUrl)) break; ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); if (clipboard == null) break; clipboard.setText(baseUrl); if (clipboard.getText().equals(baseUrl)) Toast.makeText(this, R.string.url_has_been_copied, Toast.LENGTH_LONG).show(); break; case R.id.open_in_explore: if (StringUtils.isEmpty(baseUrl)) break; Uri uri = Uri.parse(baseUrl); // uri = uri.buildUpon().scheme("http").build(); Intent intent = new Intent(Intent.ACTION_VIEW, uri); try { startActivity(intent); }catch (Exception e) { e.printStackTrace(); } break; case R.id.refresh: refresh(); break; case android.R.id.home: finish(); break; } return super.onOptionsItemSelected(item); } // private JsInterface jsInterface = new JsInterface(); // final class JsInterface { // @JavascriptInterface // public void getLoginData() { // runOnUiThread(new Runnable() { // // @Override // public void run() { // try { // String cUrl = mWebView.getUrl(); // if(TextUtils.isEmpty(cUrl)) { // return; // } // Uri cUri = Uri.parse(cUrl); // /*String debug = cUri.getQueryParameter("debug");*/ // String whiteKey = cUri.getHost(); // if (whiteKey != null && (whiteKey.contains("lesports.com") /*|| "1".equals(debug)*/ || whiteKey.contains("letv.com"))) { // // } else { // return; // } // } catch (Exception e) { // return ; // } // if (userCenter.isLogin()) { // mWebView.loadUrl("javascript:loginCallBack('"+userCenter.getId()+"','"+userCenter.getSSO_TOKEN()+"')"); // } else { // LoginService.addLetvLoginLayout(WebViewActivity.this); // } // // } // }); // // } // // @JavascriptInterface // public void shareData(final String shareText, final String shareTitle, final String shareContentURL, final String shareIconUrl ) { // // runOnUiThread(new Runnable() { // // @Override // public void run() { // try { // shareNetEntity.text = shareText; // shareNetEntity.title = shareTitle; // shareNetEntity.url = shareContentURL; // shareNetEntity.imagePath = shareIconUrl; // String cUrl = mWebView.getUrl(); // if(TextUtils.isEmpty(cUrl)) { // return; // } // Uri cUri = Uri.parse(cUrl); // /*String debug = cUri.getQueryParameter("debug");*/ // String whiteKey = cUri.getHost(); // if (whiteKey != null && (whiteKey.contains("lesports.com") /*|| "1".equals(debug)*/ || whiteKey.contains("letv.com"))) { // // } else { // return; // } // if (TextUtils.isEmpty(shareText) ||TextUtils.isEmpty(shareTitle)||TextUtils.isEmpty(shareContentURL) ){ // mWebView.loadUrl("javascript:shareCallBack('0')"); // return; // }else{ // mWebView.loadUrl("javascript:shareCallBack('1')"); // ShareService.addShareLayout(WebViewActivity.this,shareNetEntity,ShowShareDialog.FROM_WEBVIEW); // } // } catch (Exception e) { // return ; // } // // // } // }); // // } // } // class LoginReceiver extends BroadcastReceiver // { // // @Override // public void onReceive(Context context, Intent intent) { // // String action = intent.getAction(); // if (UserCenter.LOGIN_STATUS_CHANGE_ACTION.equals(action)) { // onLoginStatusChanged(); // } // // } // } // private LoginReceiver mLoginReceiver; // private void onLoginStatusChanged() { // // if (userCenter.isLogin()) { // mWebView.loadUrl("javascript:loginCallBack('"+userCenter.getId()+"','"+userCenter.getSSO_TOKEN()+"')"); // } // // } }
package gromcode.main.lesson29.homework29_1; import java.util.*; public class HashSetTest { public Set<Order> useHashTest(){ Set<Order> orders = new HashSet<>(); Order order1 = new Order(1, 2, "USD", "item1", "1"); Order order2 = new Order(2, 42, "USD", "item2", "1"); Order order3 = new Order(3, 124, "USD", "item3", "1"); Order order4 = new Order(4, 23, "USD", "item4", "1"); Order order5 = new Order(5, 122, "USD", "item5", "1"); //add System.out.println("\nadd 1,3,4,5:"); orders.add(order1); orders.add(order3); orders.add(order4); orders.add(order5); print(orders.iterator()); //remove System.out.println("\nremove 5:"); orders.remove(order5); print(orders.iterator()); //retainAll System.out.println("\nretainAll:"); ArrayList<Order> list = new ArrayList<>(); list.add(order1); list.add(order2); list.add(order3); orders.retainAll(list); print(orders.iterator()); //toArray System.out.println("\ntoArray:"); System.out.println(Arrays.toString(orders.toArray(new Order[3]))); //size System.out.println("\nsize:"); System.out.println("HashSet size: "+orders.size()); System.out.println(Arrays.toString(orders.toArray(new Order[orders.size()]))); Order order41 = new Order(41, 23, "USD", "item4", "1"); Order order51 = new Order(51, 1232, "USD", "item5", "1"); Order order61 = new Order(61, 122, "USD", "item5", "1"); orders.add(order41); orders.add(order51); orders.add(order61); return orders; } private void print(Iterator<Order> iterator){ while(iterator.hasNext()){ System.out.print(iterator.next().getId()+" "); } } }
package MVC.views; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import MVC.controllers.deleteInvController; import MVC.models.inventoryModel; public class deleteInvView extends JFrame { private inventoryModel model; private JPanel deletePanel = new JPanel(); private JLabel confirm = new JLabel("Are you sure you want to delete this part?"); private JButton deleteButton = new JButton("Delete"); private JButton cancelButton = new JButton("Cancel"); public deleteInvView (inventoryModel model){ this.model = model; deletePanel.add(confirm);/*adds confirmation label and delete/cancel buttons to deletePartView*/ deletePanel.add(deleteButton); deletePanel.add(cancelButton); this.add(deletePanel); } public void registerListeners(deleteInvController deleteController) { cancelButton.addActionListener(deleteController); deleteButton.addActionListener(deleteController); } public void closeWindow (){ this.dispose(); } }
package com.ahu.dao; import com.ahu.pojo.Role; import java.util.Set; /** * @author :XXXX * @date :Created in 2020/12/1 * @description : * @version: 1.0 */ public interface RoleDao { Set<Role> findByUserId(Integer userId); }
package ZadankaBootcamp; public class Zadanie2 { }
package com.praktyki.log.web.message.models; import org.springframework.lang.Nullable; import javax.validation.constraints.Null; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Objects; public class ScheduleConfigurationModel { public double capital; public String installmentType; public int installmentAmount; public double interestRate; public LocalDate withdrawalDate; public double commissionRate; public Integer age; public boolean insurance; public ScheduleConfigurationModel() { } public ScheduleConfigurationModel( double capital, String installmentType, int installmentAmount, double interestRate, LocalDate withdrawalDate, double commissionRate, Integer age, boolean insurance ) { this.capital = capital; this.installmentType = installmentType; this.installmentAmount = installmentAmount; this.interestRate = interestRate; this.withdrawalDate = withdrawalDate; this.commissionRate = commissionRate; this.age = age; this.insurance = insurance; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScheduleConfigurationModel that = (ScheduleConfigurationModel) o; return Double.compare(that.capital, capital) == 0 && installmentAmount == that.installmentAmount && Double.compare(that.interestRate, interestRate) == 0 && Double.compare(that.commissionRate, commissionRate) == 0 && age.equals(that.age) && insurance == that.insurance && installmentType.equals(that.installmentType) && withdrawalDate.equals(that.withdrawalDate); } @Override public int hashCode() { return Objects.hash( capital, installmentType, installmentAmount, interestRate, withdrawalDate, commissionRate, age, insurance ); } @Override public String toString() { return "ScheduleConfiguration {" + " Capital = " + capital + ", InstallmentType = " + installmentType + ", InstallmentAmount = " + installmentAmount + ", InterestRate = " + interestRate + ", WithdrawalDate = " + withdrawalDate + ", CommissionRate = " + commissionRate + ", InsuranceRate = " + age + ", Insurance = " + insurance + " }"; } }
package InterviewBitAssignments.Week5; import java.util.*; /** * Created by akshaymathur on 1/29/18. */ public class CloneGraph { class UndirectedGraphNode { int label; List<UndirectedGraphNode> neighbors; UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } } public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { UndirectedGraphNode newNode = new UndirectedGraphNode(node.label); HashMap<Integer,UndirectedGraphNode> map = new HashMap<>(); map.put(node.label,newNode); Queue<UndirectedGraphNode> queue = new LinkedList<>(); queue.add(node); while (!queue.isEmpty()){ UndirectedGraphNode realNode = queue.remove(); if(!map.containsKey(realNode.label)){ map.put(realNode.label,new UndirectedGraphNode(realNode.label)); } UndirectedGraphNode cloneNode = map.get(realNode.label); Iterator<UndirectedGraphNode> it = realNode.neighbors.iterator(); while(it.hasNext()){ UndirectedGraphNode neighNode = it.next(); if(!map.containsKey(neighNode.label)){ map.put(neighNode.label,new UndirectedGraphNode(neighNode.label)); queue.add(neighNode); } cloneNode.neighbors.add(map.get(neighNode.label)); } } return newNode; } }
module modc { }
package com.stk123.model.bo; import com.stk123.common.util.JdbcUtils.Column; import java.io.Serializable; import com.stk123.common.util.JdbcUtils.Table; import java.sql.Timestamp; @SuppressWarnings("serial") @Table(name="STK_SEARCH_CONDITION") public class StkSearchCondition implements Serializable { @Column(name="ID") private Integer id; @Column(name="TYPE") private String type; @Column(name="NAME") private String name; @Column(name="TEXT") private String text; @Column(name="INSERT_TIME") private Timestamp insertTime; @Column(name="UPDATE_TIME") private Timestamp updateTime; public Integer getId(){ return this.id; } public void setId(Integer id){ this.id = id; } public String getType(){ return this.type; } public void setType(String type){ this.type = type; } public String getName(){ return this.name; } public void setName(String name){ this.name = name; } public String getText(){ return this.text; } public void setText(String text){ this.text = text; } public Timestamp getInsertTime(){ return this.insertTime; } public void setInsertTime(Timestamp insertTime){ this.insertTime = insertTime; } public Timestamp getUpdateTime(){ return this.updateTime; } public void setUpdateTime(Timestamp updateTime){ this.updateTime = updateTime; } public String toString(){ return "id="+id+",type="+type+",name="+name+",text="+text+",insertTime="+insertTime+",updateTime="+updateTime; } }
/* * Copyright 2014 Basho Technologies Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.basho.riak.client.api.convert; import com.basho.riak.client.api.convert.RiakJacksonModule; import com.basho.riak.client.api.annotations.RiakKey; import com.basho.riak.client.api.annotations.RiakUsermeta; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import org.junit.Test; /** * @author russell * */ @SuppressWarnings("unchecked") public class RiakBeanSerializerModifierTest { @Test public void changePropertiesDropsRiakAnnotatedProperties() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new RiakJacksonModule()); RiakAnnotatedClass rac = new RiakAnnotatedClass(); String json = mapper.writeValueAsString(rac); @SuppressWarnings("unchecked") Map<String, String> map = mapper.readValue(json, Map.class); assertEquals(2, map.size()); assertTrue(map.containsKey("someField")); assertTrue(map.containsKey("someOtherField")); RiakAnnotatedClassWithPublicFields racwpf = new RiakAnnotatedClassWithPublicFields(); json = mapper.writeValueAsString(racwpf); map = mapper.readValue(json, Map.class); assertEquals(2, map.size()); assertTrue(map.containsKey("someField")); assertTrue(map.containsKey("someOtherField")); // Test the combination of a Riak annotation and the Jackson @JsonProperty RiakAnnotatedClassWithJsonProp racwjp = new RiakAnnotatedClassWithJsonProp(); json = mapper.writeValueAsString(racwjp); map = mapper.readValue(json, Map.class); assertEquals(4, map.size()); assertTrue(map.containsKey("keyField")); assertTrue(map.containsKey("metaValueField")); assertTrue(map.containsKey("someField")); assertTrue(map.containsKey("someOtherField")); } @SuppressWarnings("unused") private static final class RiakAnnotatedClass { @RiakKey private String keyField = "key"; @RiakUsermeta(key = "metaKey1") private String metaValueField = "ONE"; @RiakUsermeta private Map<String, String> usermeta = new HashMap<String, String>(); private String someField = "TWO"; private String someOtherField = "THREE"; public String getSomeField() { return someField; } public void setSomeField(String someField) { this.someField = someField; } public String getSomeOtherField() { return someOtherField; } public void setSomeOtherField(String someOtherField) { this.someOtherField = someOtherField; } public String getKeyField() { return keyField; } public String getMetaValueField() { return metaValueField; } } @SuppressWarnings("unused") private static final class RiakAnnotatedClassWithPublicFields { @RiakKey public String keyField = "key"; @RiakUsermeta(key = "metaKey1") public String metaValueField = "ONE"; @RiakUsermeta public Map<String, String> usermeta = new HashMap<String, String>(); public String someField = "TWO"; public String someOtherField = "THREE"; } @SuppressWarnings("unused") private static final class RiakAnnotatedClassWithJsonProp { @JsonProperty @RiakKey private String keyField = "key"; @JsonProperty @RiakUsermeta(key = "metaKey1") public String metaValueField = "ONE"; @RiakUsermeta public Map<String, String> usermeta = new HashMap<String, String>(); public String someField = "TWO"; public String someOtherField = "THREE"; public String getKeyField() { return keyField; } } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.validation; import java.io.Serializable; import org.springframework.beans.BeanWrapper; import org.springframework.beans.ConfigurablePropertyAccessor; import org.springframework.beans.PropertyAccessorFactory; import org.springframework.lang.Nullable; /** * Default implementation of the {@link Errors} and {@link BindingResult} * interfaces, for the registration and evaluation of binding errors on * JavaBean objects. * * <p>Performs standard JavaBean property access, also supporting nested * properties. Normally, application code will work with the * {@code Errors} interface or the {@code BindingResult} interface. * A {@link DataBinder} returns its {@code BindingResult} via * {@link DataBinder#getBindingResult()}. * * @author Juergen Hoeller * @since 2.0 * @see DataBinder#getBindingResult() * @see DataBinder#initBeanPropertyAccess() * @see DirectFieldBindingResult */ @SuppressWarnings("serial") public class BeanPropertyBindingResult extends AbstractPropertyBindingResult implements Serializable { @Nullable private final Object target; private final boolean autoGrowNestedPaths; private final int autoGrowCollectionLimit; @Nullable private transient BeanWrapper beanWrapper; /** * Create a new {@code BeanPropertyBindingResult} for the given target. * @param target the target bean to bind onto * @param objectName the name of the target object */ public BeanPropertyBindingResult(@Nullable Object target, String objectName) { this(target, objectName, true, Integer.MAX_VALUE); } /** * Create a new {@code BeanPropertyBindingResult} for the given target. * @param target the target bean to bind onto * @param objectName the name of the target object * @param autoGrowNestedPaths whether to "auto-grow" a nested path that contains a null value * @param autoGrowCollectionLimit the limit for array and collection auto-growing */ public BeanPropertyBindingResult(@Nullable Object target, String objectName, boolean autoGrowNestedPaths, int autoGrowCollectionLimit) { super(objectName); this.target = target; this.autoGrowNestedPaths = autoGrowNestedPaths; this.autoGrowCollectionLimit = autoGrowCollectionLimit; } @Override @Nullable public final Object getTarget() { return this.target; } /** * Returns the {@link BeanWrapper} that this instance uses. * Creates a new one if none existed before. * @see #createBeanWrapper() */ @Override public final ConfigurablePropertyAccessor getPropertyAccessor() { if (this.beanWrapper == null) { this.beanWrapper = createBeanWrapper(); this.beanWrapper.setExtractOldValueForEditor(true); this.beanWrapper.setAutoGrowNestedPaths(this.autoGrowNestedPaths); this.beanWrapper.setAutoGrowCollectionLimit(this.autoGrowCollectionLimit); } return this.beanWrapper; } /** * Create a new {@link BeanWrapper} for the underlying target object. * @see #getTarget() */ protected BeanWrapper createBeanWrapper() { if (this.target == null) { throw new IllegalStateException("Cannot access properties on null bean instance '" + getObjectName() + "'"); } return PropertyAccessorFactory.forBeanPropertyAccess(this.target); } }
public class Repainter extends Thread{ MapWindow m; public Repainter(MapWindow m) { this.m = m; } public void run() { while(true){ m.repaintPainter(); try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package com.zc.pivas.docteradvice.dtsystem.autocheck.req; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; /** * * xml药品类 * * @author cacabin * @version 0.1 */ @XmlAccessorType(XmlAccessType.FIELD) public class Medicine { /** * 商品名 */ private String name = ""; /** * 医院药品代码 */ private String his_code = ""; /** * 医保代码 */ private String insur_code = ""; /** * 批准文号 */ private String approval = ""; /** * 规格 */ private String spec = ""; /** * 组号 */ private String group = ""; /** * 用药理由 */ private String reason = ""; /** * 单次量单位 */ private String dose_unit = ""; /** * 单次量 */ private String dose = ""; /** * 频次代码 */ private String freq = ""; /** * 给药途径代码 */ private String administer = ""; /** * (住院)用药开始时间 */ private String begin_time = ""; /** * (住院)用药结束时间 */ private String end_time = ""; /** * 服药天数(门诊) */ private String days = ""; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getHis_code() { return his_code; } public void setHis_code(String his_code) { this.his_code = his_code; } public String getInsur_code() { return insur_code; } public void setInsur_code(String insur_code) { this.insur_code = insur_code; } public String getApproval() { return approval; } public void setApproval(String approval) { this.approval = approval; } public String getSpec() { return spec; } public void setSpec(String spec) { this.spec = spec; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public String getDose_unit() { return dose_unit; } public void setDose_unit(String dose_unit) { this.dose_unit = dose_unit; } public String getDose() { return dose; } public void setDose(String dose) { this.dose = dose; } public String getFreq() { return freq; } public void setFreq(String freq) { this.freq = freq; } public String getAdminister() { return administer; } public void setAdminister(String administer) { this.administer = administer; } public String getBegin_time() { return begin_time; } public void setBegin_time(String begin_time) { this.begin_time = begin_time; } public String getEnd_time() { return end_time; } public void setEnd_time(String end_time) { this.end_time = end_time; } public String getDays() { return days; } public void setDays(String days) { this.days = days; } }
package HotelReservationJavalin.Dao; import HotelReservationJavalin.pojos.Guest; public interface GuestDao { public void createGuest(Guest guest); public Guest readGuest(int guestId); public Guest readAllGuests(); public Guest updateGuest(int guestId, Guest guest); public void deleteGuest(Guest guest); }
package utn.sau.hp.com.modelo; // Generated 04/12/2014 23:31:51 by Hibernate Tools 3.6.0 import java.util.Date; /** * Anexos generated by hbm2java */ public class Anexos implements java.io.Serializable { private Integer id; private Empresas empresas; private byte pagaSeguroTrabajoAnterior; private Byte pagaObraSocialAnterior; private Integer porcentajeGastoAnterior; private String anexoConvenioMarco; private Date convenioFechaAnterior; private Integer empresaCuit; public Anexos() { } public Anexos(Empresas empresas, byte pagaSeguroTrabajoAnterior) { this.empresas = empresas; this.pagaSeguroTrabajoAnterior = pagaSeguroTrabajoAnterior; } public Anexos(Empresas empresas, byte pagaSeguroTrabajoAnterior, Byte pagaObraSocialAnterior, Integer porcentajeGastoAnterior, String anexoConvenioMarco, Date convenioFechaAnterior, Integer empresaCuit) { this.empresas = empresas; this.pagaSeguroTrabajoAnterior = pagaSeguroTrabajoAnterior; this.pagaObraSocialAnterior = pagaObraSocialAnterior; this.porcentajeGastoAnterior = porcentajeGastoAnterior; this.anexoConvenioMarco = anexoConvenioMarco; this.convenioFechaAnterior = convenioFechaAnterior; this.empresaCuit = empresaCuit; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public Empresas getEmpresas() { return this.empresas; } public void setEmpresas(Empresas empresas) { this.empresas = empresas; } public byte getPagaSeguroTrabajoAnterior() { return this.pagaSeguroTrabajoAnterior; } public void setPagaSeguroTrabajoAnterior(byte pagaSeguroTrabajoAnterior) { this.pagaSeguroTrabajoAnterior = pagaSeguroTrabajoAnterior; } public Byte getPagaObraSocialAnterior() { return this.pagaObraSocialAnterior; } public void setPagaObraSocialAnterior(Byte pagaObraSocialAnterior) { this.pagaObraSocialAnterior = pagaObraSocialAnterior; } public Integer getPorcentajeGastoAnterior() { return this.porcentajeGastoAnterior; } public void setPorcentajeGastoAnterior(Integer porcentajeGastoAnterior) { this.porcentajeGastoAnterior = porcentajeGastoAnterior; } public String getAnexoConvenioMarco() { return this.anexoConvenioMarco; } public void setAnexoConvenioMarco(String anexoConvenioMarco) { this.anexoConvenioMarco = anexoConvenioMarco; } public Date getConvenioFechaAnterior() { return this.convenioFechaAnterior; } public void setConvenioFechaAnterior(Date convenioFechaAnterior) { this.convenioFechaAnterior = convenioFechaAnterior; } public Integer getEmpresaCuit() { return this.empresaCuit; } public void setEmpresaCuit(Integer empresaCuit) { this.empresaCuit = empresaCuit; } }
package org.rita.harris.embeddedsystemhomework_termproject.UserData; import android.content.SharedPreferences; import android.util.Log; import org.rita.harris.embeddedsystemhomework_termproject.MainActivity; /** * Created by Harris on 2015/12/17. */ public class User_BasicData { private String Account = ""; private String Password = ""; private String NickName = ""; public void setAccount(String Account) { this.Account = Account; } public void setPassword(String Password) { this.Password = Password; } public void setNickName(String Nickname) { this.NickName = Nickname; } public String getAccount() { return Account; } public String getPassword() { return Password; } public String getNickName() { return NickName; } // <Navigation> 判斷reference裡面是否有存帳號資訊 public boolean IsChangeButtonText() { SharedPreferences settings = MainActivity.MainActivity_Context().getSharedPreferences("AccountData", 0); String Account = settings.getString("Account", ""); String Password = settings.getString("Password",""); String Nickname = settings.getString("Nickname",""); Log.v("Mail",Account); Log.v("Password",Password); Log.v("Nickname",Nickname); if(Account == "" && Password == "")//裡面是空的代表沒有帳號的資訊 return false; else { this.Account = Account; this.Password = Password; this.NickName = Nickname; return true; } } }
package com.producerconsumer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ProducerConsumer { public static void main(String[] args) { Blockingqueue q=new Blockingqueue(5); ExecutorService es= Executors.newFixedThreadPool(2); es.execute(new producer(q)); es.execute(new consumer(q)); es.shutdown(); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans; import org.springframework.aot.hint.MemberCategory; import org.springframework.aot.hint.ReflectionHints; import org.springframework.aot.hint.RuntimeHints; import org.springframework.aot.hint.RuntimeHintsRegistrar; import org.springframework.core.io.ResourceEditor; import org.springframework.lang.Nullable; /** * {@link RuntimeHintsRegistrar} to register hints for popular conventions in * {@link BeanUtils#findEditorByConvention(Class)}. * * @author Sebastien Deleuze * @since 6.0.10 */ class BeanUtilsRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { ReflectionHints reflectionHints = hints.reflection(); reflectionHints.registerType(ResourceEditor.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); reflectionHints.registerTypeIfPresent(classLoader, "org.springframework.http.MediaTypeEditor", MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); } }
package staticAndDefault; import java.util.function.Function; import java.util.function.Predicate; public class FuncionalInterface { public static void main(String[] args) { Runnable runnable = () -> System.out.println("test"); Thread thread = new Thread(runnable); thread.start(); Function<Integer, String> integerConcat = x -> x + "m"; System.out.println(integerConcat.apply(3)); Predicate<Integer> isBiggerThan5 = x -> x > 5; System.out.println(isBiggerThan5.test(3)); } }
package com.sherpa.sherpa.Interfaces; import android.widget.ImageView; import com.parse.ParseFile; import com.parse.ParseUser; /** * Created by Kirtan on 10/30/15. */ public interface Profile { ParseUser getCurrentParseUser(); String getUsername(); String getFirstname(); String getLastname(); String getEmail(); String getPhone(); Double getCost(); Boolean getAvailability(); String getCostType(); void getProfilePic(ImageView view); String getCity(); String getPlaces(); void setCurrentParseUser(); void setEmail(String email); void setPhone(String phone); void setCost(Double cost); void setAvailability(Boolean availability); void setCostType(String costType); void setProfilePic(ParseFile file); void setCity(String city); void setPlaces(String places); void saveUser(); Boolean contains(String s); }
package nightgames.skills; import nightgames.characters.Attribute; import nightgames.characters.Character; import nightgames.characters.Emotion; import nightgames.characters.Trait; import nightgames.combat.Combat; import nightgames.combat.Result; import nightgames.global.Global; import nightgames.status.Enthralled; public class Whisper extends Skill { public Whisper(Character self) { super("Whisper", self); } @Override public boolean usable(Combat c, Character target) { return c.getStance().kiss(getSelf()) && getSelf().canAct() && !getSelf().has(Trait.direct); } @Override public float priorityMod(Combat c) { return getSelf().has(Trait.darkpromises) ? .2f : 0; } @Override public int getMojoBuilt(Combat c) { return 10; } @Override public boolean resolve(Combat c, Character target) { int roll = Global.centeredrandom(4, getSelf().get(Attribute.Dark) / 5.0, 2); int m = 4 + Global.random(6); if (target.has(Trait.imagination)) { m += 4; } if (getSelf().has(Trait.darkpromises)) { m += 3; } if (getSelf().has(Trait.darkpromises) && roll == 4 && getSelf().canSpend(15) && !target.wary()) { getSelf().spendMojo(c, 15); if (getSelf().human()) { c.write(getSelf(), deal(c, 0, Result.special, target)); } else if (target.human()) { c.write(getSelf(), receive(c, 0, Result.special, target)); } target.add(c, new Enthralled(target, getSelf(), 4)); } else { if (getSelf().human()) { c.write(getSelf(), deal(c, 0, Result.normal, target)); } else if (target.human()) { c.write(getSelf(), receive(c, 0, Result.normal, target)); } } target.tempt(c, getSelf(), m); target.emote(Emotion.horny, 30); return true; } @Override public boolean requirements(Combat c, Character user, Character target) { return user.get(Attribute.Seduction) >= 32 && !user.has(Trait.direct); } @Override public Skill copy(Character user) { return new Whisper(user); } @Override public int speed() { return 9; } @Override public Tactics type(Combat c) { return Tactics.pleasure; } @Override public String deal(Combat c, int damage, Result modifier, Character target) { if (modifier == Result.special) { return "You whisper words of domination in " + target.name() + "'s ear, filling her with your darkness. The spirit in her eyes seems to dim as she submits to your will."; } else { return "You whisper sweet nothings in " + target.name() + "'s ear. Judging by her blush, it was fairly effective."; } } @Override public String receive(Combat c, int damage, Result modifier, Character target) { if (modifier == Result.special) { return getSelf().name() + " whispers in your ear in some eldritch language." + " Her words echo through your head and you feel a" + " strong compulsion to do what she tells you."; } else { return getSelf().name() + " whispers some deliciously seductive suggestions in your ear."; } } @Override public String describe(Combat c) { return "Arouse opponent by whispering in her ear"; } }
package com.lei.tang.frame.service.user; import entity.user.LoginRecord; import entity.user.UserAccount; import javax.servlet.http.HttpServletRequest; /** * @author tanglei * @date 18/10/11 */ public interface LoginRecordService { /** * 保存登录记录 * @param userAccount * @return */ LoginRecord save(HttpServletRequest request, UserAccount userAccount); }
package com.wb.welfare.repository; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.springframework.stereotype.Repository; import com.wb.welfare.model.Pedido; @Repository public class PedidoRepository { @PersistenceContext private EntityManager entityManager; public List<Pedido> recuperaTodoOsPedidos(){ Query query = entityManager.createQuery("select p from Pedido p",Pedido.class); return query.getResultList(); } }
package com.volvobuses.client.service; import com.volvobuses.client.bean.GenTbBuseseventos; public interface GenTbBusesEventoService extends ServiceTemplate<GenTbBuseseventos, Integer> { }
package edu.rutgers.MOST.optimization.FBA; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Vector; import org.apache.log4j.Logger; import edu.rutgers.MOST.data.*; import edu.rutgers.MOST.optimization.solvers.*; public class FBA { static Logger log = Logger.getLogger(FBA.class); private FBAModel model; private static Solver solver; private Vector<String> varNames; private double maxObj; public FBA() { FBA.setSolver(SolverFactory.createSolver()); this.varNames = new Vector<String>(); } public FBA(FBAModel m) { this.model = m; FBA.setSolver(SolverFactory.createSolver()); this.varNames = new Vector<String>(); } private void setVars() { Vector<ModelReaction> reactions = this.model.getReactions(); for (int i = 0; i < reactions.size(); i++) { SBMLReaction reac = (SBMLReaction) (reactions.elementAt(i)); String varName = Integer.toString((Integer)this.model.getReactionsIdPositionMap().get(reac.getId())); //String varName = Integer.toString(reac.getId()); double lb = reac.getLowerBound(); double ub = reac.getUpperBound(); FBA.getSolver().setVar(varName, VarType.CONTINUOUS, lb, ub); this.varNames.add(varName); } } private void setConstraints() { Vector<ModelReaction> reactions = this.model.getReactions(); setConstraints(reactions,ConType.EQUAL,0.0); } private void setConstraints(Vector<ModelReaction> reactions, ConType conType, double bValue) { ArrayList<Map<Integer, Double>> sMatrix = this.model.getSMatrix(); for (int i = 0; i < sMatrix.size(); i++) { FBA.getSolver().addConstraint(sMatrix.get(i), conType, bValue); } } private void setObjective() { FBA.getSolver().setObjType(ObjType.Maximize); Vector<Double> objective = this.model.getObjective(); Map<Integer, Double> map = new HashMap<Integer, Double>(); for (int i = 0; i < objective.size(); i++) { if (objective.elementAt(i) != 0.0) { map.put(i, objective.elementAt(i)); } } FBA.getSolver().setObj(map); } public void setFBAModel(FBAModel m) { this.model = m; } public ArrayList<Double> run() { log.debug("Set Vars"); this.setVars(); log.debug("setConstraints"); this.setConstraints(); log.debug("setObjective"); this.setObjective(); log.debug("optimize"); this.maxObj = FBA.getSolver().optimize(); return FBA.getSolver().getSoln(); } public double getMaxObj() { return this.maxObj; } public static void main(String[] argv) { } public static Solver getSolver() { return solver; } public static void setSolver(Solver solver) { FBA.solver = solver; } }