hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
02b28825cd06adb35dd6d2a4a0df297bab936789
8,100
package com.example.notes; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ComponentActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.Html; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; 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.ServerValue; import com.google.firebase.database.ValueEventListener; import com.shashank.sony.fancytoastlib.FancyToast; import java.util.HashMap; import java.util.Map; public class task extends AppCompatActivity { private EditText editText,editText2; private Button button,button2; private FirebaseAuth firebaseAuth; private Menu mainMenu; private DatabaseReference databaseReference; String noteId; private boolean exists; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_task); button2=(Button)findViewById(R.id.button2); try { noteId=getIntent().getStringExtra("noteId"); if(!noteId.trim().equals("")){ exists=true; } else{ exists=false; } } catch (Exception e){ e.printStackTrace(); } editText = (EditText) findViewById(R.id.editText); editText2 = (EditText) findViewById(R.id.editText2); button = (Button) findViewById(R.id.button); firebaseAuth=FirebaseAuth.getInstance(); databaseReference= FirebaseDatabase.getInstance().getReference().child("Notes").child(firebaseAuth.getCurrentUser().getUid()); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String title = editText.getText().toString().trim(); String content = editText2.getText().toString().trim(); if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)) { createNote(title, content); } else { Toast.makeText(task.this,"Enter the contents",Toast.LENGTH_SHORT).show(); } } }); putData(); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { markDone(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.del_menu , menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch(item.getItemId()){ case R.id.delete: if(exists){ new AlertDialog.Builder(this,R.style.AlertDialog) .setTitle("DELETE ITEM") .setMessage("Are you sure you want to delete this ? ") .setPositiveButton(Html.fromHtml("<font color='#FF7F27'>Yes</font>"), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { deleteNote(); } }) .setNegativeButton(Html.fromHtml("<font color='#FF7F27'>Cancel</font>"), null) .setIcon(R.drawable.ic_delete_forever_black_24dp) .show(); } else{ Toast.makeText(task.this,"Nothing to Delete.",Toast.LENGTH_SHORT).show(); } break; } return true; } private void putData(){ if(exists) { databaseReference.child(noteId).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.hasChild("title") && dataSnapshot.hasChild("content")) { String title = dataSnapshot.child("title").getValue().toString(); String content = dataSnapshot.child("content").getValue().toString(); editText.setText(title); editText2.setText(content); if(!title.isEmpty() && !content.isEmpty()){ button.setText("UPDATE TASK"); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } } private void createNote(String title, String content) { if(exists){ Map updateMap=new HashMap(); updateMap.put("title", editText.getText().toString()); updateMap.put("content", editText2.getText().toString()); updateMap.put("timestamp", ServerValue.TIMESTAMP); databaseReference.child(noteId).updateChildren(updateMap); FancyToast.makeText(task.this,"Task Updated!!",FancyToast.LENGTH_SHORT,FancyToast.SUCCESS,true).show(); } else{ final DatabaseReference dref = databaseReference.push(); final Map map = new HashMap(); map.put("title", title); map.put("content", content); map.put("timestamp", ServerValue.TIMESTAMP); map.put("task","NOT DONE"); Thread thread = new Thread(new Runnable() { @Override public void run() { dref.setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { Toast.makeText(task.this, "Note added sucessfully", Toast.LENGTH_SHORT).show(); finish(); } else { Toast.makeText(task.this, "Note adding failed!!", Toast.LENGTH_SHORT).show(); } } }); } }); thread.start(); } } public void deleteNote(){ databaseReference.child(noteId).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ Toast.makeText(task.this,"Item Deleted",Toast.LENGTH_SHORT); } else{ Toast.makeText(task.this,"Oops!! Item cannot be Deleted ",Toast.LENGTH_SHORT); } } }); Intent intent =new Intent(task.this,start.class); startActivity(intent); } public void markDone(){ Map updateMap=new HashMap(); updateMap.put("task","DONE"); updateMap.put("timestamp", ServerValue.TIMESTAMP); databaseReference.child(noteId).updateChildren(updateMap); FancyToast.makeText(task.this,"Task Completed!",FancyToast.LENGTH_SHORT,FancyToast.SUCCESS,true).show(); } }
35.526316
137
0.571111
54aeef01ff3898fa6cba3a83a9ee8d4e3237a8a9
178
package io.simplelocalize.cli.processor.files; import java.nio.file.Path; import java.util.List; public interface FilesFinder { List<Path> findFilesToProcess(Path path); }
16.181818
46
0.780899
ac7dd686a7a647935f7ae621456c3a891d9fae25
1,635
/* * Copyright (C) 2017 Red Hat, 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 org.jboss.pnc.build.finder.core; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; @JsonDeserialize public class LocalFile { private final String filename; private final long size; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) @ProtoFactory public LocalFile(@JsonProperty("filename") String filename, @JsonProperty("size") long size) { this.filename = filename; this.size = size; } @ProtoField(value = 1, required = true) public String getFilename() { return filename; } @ProtoField(value = 2, required = true) public long getSize() { return size; } @Override public String toString() { return "LocalFile{" + "filename='" + filename + '\'' + ", size=" + size + '}'; } }
30.849057
98
0.704587
2a1b40dae1bf4fae2e612141e67f067c7abf392e
260
package com.bin.mybatis.entity; import lombok.Data; import java.util.Date; /** * @author shaobin.qin */ @Data public class Student { private Integer id; private String name; private Integer age; private Date birthDay; private Date createTime; }
11.304348
31
0.723077
e417063321251c5e7230786c441a2627d86421c5
1,644
package com.blakebr0.extendedcrafting.client.gui; import com.blakebr0.cucumber.helper.RenderHelper; import com.blakebr0.cucumber.helper.ResourceHelper; import com.blakebr0.cucumber.util.Utils; import com.blakebr0.extendedcrafting.ExtendedCrafting; import com.blakebr0.extendedcrafting.client.container.ContainerUltimateTable; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.ResourceLocation; public class GuiUltimateTable extends GuiContainer { public static final ResourceLocation GUI = ResourceHelper.getResource(ExtendedCrafting.MOD_ID, "textures/gui/ultimate_table.png"); public GuiUltimateTable(ContainerUltimateTable container) { super(container); this.xSize = 234; this.ySize = 278; } @Override public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.drawDefaultBackground(); super.drawScreen(mouseX, mouseY, partialTicks); this.renderHoveredToolTip(mouseX, mouseY); } @Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { this.fontRenderer.drawString(Utils.localize("container.ec.table_ultimate"), 8, 6, 4210752); this.fontRenderer.drawString(Utils.localize("container.inventory"), 39, this.ySize - 94, 4210752); } @Override protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); this.mc.renderEngine.bindTexture(GUI); int x = (this.width - this.xSize) / 2; int y = (this.height - this.ySize) / 2; RenderHelper.drawTexturedModelRect(x, y, 0, 0, this.xSize, this.ySize, 512, 512); } }
37.363636
131
0.786496
3fa6697c9931cc43cea1dfaec8fa65400a163619
155
package com.brageast.blog.service; import java.util.Set; public interface GroupService { Set<String> getGroup(); Set<String> getPermissions(); }
17.222222
34
0.729032
5df8b257cee4955e5cc938cd73a97c0d62195e5a
10,927
/* * Copyright (c) 2009, Takao Sumitomo * 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. * * 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 HOLDER 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. * * The views and conclusions contained in the software * and documentation are those of the authors and should * not be interpreted as representing official policies, * either expressed or implied. */ /* * $Id: MdDrawerModePanel.java 232 2009-08-01 07:06:41Z cattaka $ */ package net.cattaka.mathdrawer.gui.drawer; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JSplitPane; import net.cattaka.mathdrawer.config.MdConfig; import net.cattaka.mathdrawer.core.MdSingletonBundle; import net.cattaka.mathdrawer.gui.MdGuiInterface; import net.cattaka.mathdrawer.gui.MdMessage; import net.cattaka.mathdrawer.gui.MdModeInterface; import net.cattaka.swing.util.ButtonsBundle; public class MdDrawerModePanel extends JPanel implements MdGuiInterface, MdModeInterface { private static final long serialVersionUID = 1L; private JSplitPane splitPane; private MdDrawerAssistTabbedPanel mdDrawerAssistTabbedPanel; private MdDrawerEditorTabbedPanel mdDrawerEditorPanel; private MdGuiInterface parentComponent; class ActionListenerImpl implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("new_drawer")) { mdDrawerEditorPanel.addTab(); } else if (e.getActionCommand().equals("open_drawer")) { mdDrawerEditorPanel.openDrawer(); } else if (e.getActionCommand().equals("save_drawer")) { mdDrawerEditorPanel.saveDrawer(null); } else if (e.getActionCommand().equals("saveAs_drawer")) { mdDrawerEditorPanel.saveAsDrawer(null); } else if (e.getActionCommand().equals("close_drawer")) { mdDrawerEditorPanel.closeTab(); } else if (e.getActionCommand().equals("editor_comment_out")) { mdDrawerEditorPanel.doCommentOut(); } else if (e.getActionCommand().equals("editor_undo")) { mdDrawerEditorPanel.undo(); } else if (e.getActionCommand().equals("editor_redo")) { mdDrawerEditorPanel.redo(); } else if (e.getActionCommand().equals("editor_cut")) { mdDrawerEditorPanel.cut(); } else if (e.getActionCommand().equals("editor_copy")) { mdDrawerEditorPanel.copy(); } else if (e.getActionCommand().equals("editor_paste")) { mdDrawerEditorPanel.paste(); } else if (e.getActionCommand().equals("editor_select_all")) { mdDrawerEditorPanel.selectAll(); } else if (e.getActionCommand().equals("editor_find")) { mdDrawerEditorPanel.openFindDialog(); } else if (e.getActionCommand().equals("editor_find_next")) { mdDrawerEditorPanel.searchNext(); } else if (e.getActionCommand().equals("editor_find_prev")) { mdDrawerEditorPanel.searchPrev(); } else if (e.getActionCommand().equals("run_drawer")) { mdDrawerEditorPanel.runDrawer(); } else if (e.getActionCommand().equals("compile_drawer")) { mdDrawerEditorPanel.compileDrawer(); } else if (e.getActionCommand().equals("next_drawer")) { mdDrawerEditorPanel.nextDrawer(); } else if (e.getActionCommand().equals("prev_drawer")) { mdDrawerEditorPanel.prevDrawer(); } else if (e.getActionCommand().equals("switch_result_panel")) { mdDrawerEditorPanel.switchResultPanel(); } } } public MdDrawerModePanel(MdGuiInterface parentComponent) { this.parentComponent = parentComponent; makeLayout(); } private void makeLayout() { mdDrawerAssistTabbedPanel = new MdDrawerAssistTabbedPanel(this.parentComponent); mdDrawerEditorPanel = new MdDrawerEditorTabbedPanel(this.parentComponent); mdDrawerAssistTabbedPanel.setMinimumSize(new Dimension(0,0)); mdDrawerEditorPanel.setMinimumSize(new Dimension(0,0)); mdDrawerAssistTabbedPanel.setMdDrawerEditorTabbedPanel(mdDrawerEditorPanel); splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, mdDrawerAssistTabbedPanel, mdDrawerEditorPanel); this.setLayout(new GridLayout()); this.add(splitPane); } public void doGuiLayout() { this.splitPane.setDividerLocation(0.4); this.mdDrawerEditorPanel.doGuiLayout(); this.mdDrawerAssistTabbedPanel.doGuiLayout(); } public void reloadMdConfig() { this.mdDrawerEditorPanel.reloadMdConfig(); this.mdDrawerAssistTabbedPanel.reloadMdConfig(); } public void sendMdMessage(MdMessage mdMessage) { this.parentComponent.sendMdMessage(mdMessage); } public void relayMdMessage(MdMessage rbdaMessage) { this.mdDrawerAssistTabbedPanel.relayMdMessage(rbdaMessage); this.mdDrawerEditorPanel.relayMdMessage(rbdaMessage); } public MdSingletonBundle getMdSingletonBundle() { return this.parentComponent.getMdSingletonBundle(); } public MdConfig getMdConfig() { return this.parentComponent.getMdConfig(); } /** {@link MdModeInterface} */ public JMenu[] getExtraMenu() { ActionListenerImpl al = new ActionListenerImpl(); JMenu drawerMenu = new JMenu(); ButtonsBundle.applyButtonDifinition(drawerMenu, "menu_drawer"); { JMenuItem runDrawerItem = new JMenuItem(); JMenuItem compileDrawerItem = new JMenuItem(); JMenuItem switchResultPanelItem = new JMenuItem(); JMenuItem commentOutItem = new JMenuItem(); runDrawerItem.setActionCommand("run_drawer"); compileDrawerItem.setActionCommand("compile_drawer"); switchResultPanelItem.setActionCommand("switch_result_panel"); commentOutItem.setActionCommand("editor_comment_out"); runDrawerItem.addActionListener(al); compileDrawerItem.addActionListener(al); switchResultPanelItem.addActionListener(al); commentOutItem.addActionListener(al); ButtonsBundle.applyMenuDifinition(runDrawerItem, "run_drawer"); ButtonsBundle.applyMenuDifinition(compileDrawerItem, "compile_drawer"); ButtonsBundle.applyMenuDifinition(switchResultPanelItem, "switch_result_panel"); ButtonsBundle.applyMenuDifinition(commentOutItem, "comment_out"); drawerMenu.add(runDrawerItem); drawerMenu.add(compileDrawerItem); drawerMenu.add(switchResultPanelItem); drawerMenu.addSeparator(); drawerMenu.add(commentOutItem); } return new JMenu[]{drawerMenu}; } /** {@link MdModeInterface} */ public boolean updateMenu(TargetMenu targetMenu, JMenu menu) { boolean result = false; ActionListenerImpl al = new ActionListenerImpl(); if (targetMenu == TargetMenu.FILE_MENU) { JMenuItem newItem = new JMenuItem(); JMenuItem openItem = new JMenuItem(); JMenuItem saveItem = new JMenuItem(); JMenuItem saveAsItem = new JMenuItem(); JMenuItem closeItem = new JMenuItem(); newItem.setActionCommand("new_drawer"); openItem.setActionCommand("open_drawer"); saveItem.setActionCommand("save_drawer"); saveAsItem.setActionCommand("saveAs_drawer"); closeItem.setActionCommand("close_drawer"); newItem.addActionListener(al); openItem.addActionListener(al); saveItem.addActionListener(al); saveAsItem.addActionListener(al); closeItem.addActionListener(al); ButtonsBundle.applyMenuDifinition(newItem, "file_new"); ButtonsBundle.applyMenuDifinition(openItem, "file_open"); ButtonsBundle.applyMenuDifinition(saveItem, "file_save"); ButtonsBundle.applyMenuDifinition(saveAsItem, "file_save_as"); ButtonsBundle.applyMenuDifinition(closeItem, "file_close"); menu.add(newItem); menu.add(openItem); menu.add(saveItem); menu.add(saveAsItem); menu.add(closeItem); result = true; } else if (targetMenu == TargetMenu.EDIT_MENU) { JMenuItem undoItem = new JMenuItem(); JMenuItem redoItem = new JMenuItem(); JMenuItem cutItem = new JMenuItem(); JMenuItem copyItem = new JMenuItem(); JMenuItem pasteItem = new JMenuItem(); JMenuItem selectAllItem = new JMenuItem(); JMenuItem findItem = new JMenuItem(); JMenuItem findNextItem = new JMenuItem(); JMenuItem findPrevItem = new JMenuItem(); undoItem.setActionCommand("editor_undo"); redoItem.setActionCommand("editor_redo"); cutItem.setActionCommand("editor_cut"); copyItem.setActionCommand("editor_copy"); pasteItem.setActionCommand("editor_paste"); selectAllItem.setActionCommand("editor_select_all"); findItem.setActionCommand("editor_find"); findNextItem.setActionCommand("editor_find_next"); findPrevItem.setActionCommand("editor_find_prev"); undoItem.addActionListener(al); redoItem.addActionListener(al); cutItem.addActionListener(al); copyItem.addActionListener(al); pasteItem.addActionListener(al); selectAllItem.addActionListener(al); findItem.addActionListener(al); findNextItem.addActionListener(al); findPrevItem.addActionListener(al); ButtonsBundle.applyMenuDifinition(undoItem, "editor_undo"); ButtonsBundle.applyMenuDifinition(redoItem, "editor_redo"); ButtonsBundle.applyMenuDifinition(cutItem, "editor_cut"); ButtonsBundle.applyMenuDifinition(copyItem, "editor_copy"); ButtonsBundle.applyMenuDifinition(pasteItem, "editor_paste"); ButtonsBundle.applyMenuDifinition(selectAllItem, "editor_select_all"); ButtonsBundle.applyMenuDifinition(findItem, "search_replace"); ButtonsBundle.applyMenuDifinition(findNextItem, "search_next"); ButtonsBundle.applyMenuDifinition(findPrevItem, "search_prev"); menu.add(undoItem); menu.add(redoItem); menu.addSeparator(); menu.add(cutItem); menu.add(copyItem); menu.add(pasteItem); menu.addSeparator(); menu.add(selectAllItem); menu.addSeparator(); menu.add(findItem); menu.add(findNextItem); menu.add(findPrevItem); result = true; } return result; } }
39.305755
106
0.760502
813cc51dd8f8e9b161c588331dcfd0e2c3a9e1b7
1,449
package bsoft.com.clipboard.model; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import java.io.*; @Data @Entity(name = "PostMessage") @Table(name = "postmessage") public class PostMessage implements Serializable { @Id @GeneratedValue(generator = "increment") @GenericGenerator(name = "increment", strategy = "increment") @Column(name = "ID") private Long id; @NotBlank @Column(name = "MESSAGE") private String message; @NotBlank @Size(min = 0, max = 24) @Column(name = "CLIPTOPIC_NAME") private String clipTopicName; // name of the cliptopic @NotBlank @Size(min = 0, max = 36) @Column(name = "APIKEY") private String apiKey; public static byte[] objToByte(PostMessage postMessage) throws IOException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); ObjectOutputStream objStream = new ObjectOutputStream(byteStream); objStream.writeObject(postMessage); return byteStream.toByteArray(); } public static Object byteToObj(byte[] bytes) throws IOException, ClassNotFoundException { ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes); ObjectInputStream objStream = new ObjectInputStream(byteStream); return objStream.readObject(); } }
28.98
93
0.712905
13c44b5d45bbb3c88bc0b98f65d6fc2d6eb3bbe4
113
package net.modificationstation.stationapi.api.common.item.tool; public interface Shovel extends ToolLevel { }
18.833333
64
0.823009
5e575092dcff9d5eab8a7f4a13be710f4bcfe7d1
5,475
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|karaf operator|. name|event operator|. name|command package|; end_package begin_import import|import static name|org operator|. name|easymock operator|. name|EasyMock operator|. name|expect import|; end_import begin_import import|import static name|org operator|. name|easymock operator|. name|EasyMock operator|. name|mock import|; end_import begin_import import|import static name|org operator|. name|easymock operator|. name|EasyMock operator|. name|replay import|; end_import begin_import import|import static name|org operator|. name|easymock operator|. name|EasyMock operator|. name|verify import|; end_import begin_import import|import name|java operator|. name|io operator|. name|PrintStream import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|ExecutorService import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|Executors import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|TimeUnit import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|event operator|. name|command operator|. name|EventTailCommand import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|event operator|. name|service operator|. name|EventCollector import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|karaf operator|. name|shell operator|. name|api operator|. name|console operator|. name|Session import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|org operator|. name|osgi operator|. name|service operator|. name|event operator|. name|Event import|; end_import begin_class specifier|public class|class name|EventTailCommandTest block|{ specifier|private name|Exception name|exception decl_stmt|; annotation|@ name|Test specifier|public name|void name|testTail parameter_list|() throws|throws name|Exception block|{ name|EventTailCommand name|tail init|= operator|new name|EventTailCommand argument_list|() decl_stmt|; name|tail operator|. name|session operator|= name|mock argument_list|( name|Session operator|. name|class argument_list|) expr_stmt|; name|tail operator|. name|collector operator|= operator|new name|EventCollector argument_list|() expr_stmt|; name|PrintStream name|out init|= name|System operator|. name|out decl_stmt|; name|expect argument_list|( name|tail operator|. name|session operator|. name|getConsole argument_list|() argument_list|) operator|. name|andReturn argument_list|( name|out argument_list|) expr_stmt|; name|exception operator|= literal|null expr_stmt|; name|replay argument_list|( name|tail operator|. name|session argument_list|) expr_stmt|; name|ExecutorService name|executor init|= name|Executors operator|. name|newSingleThreadExecutor argument_list|() decl_stmt|; name|executor operator|. name|execute argument_list|( parameter_list|() lambda|-> block|{ try|try block|{ name|tail operator|. name|execute argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ name|exception operator|= name|e expr_stmt|; block|} block|} argument_list|) expr_stmt|; name|tail operator|. name|collector operator|. name|handleEvent argument_list|( name|event argument_list|() argument_list|) expr_stmt|; name|Thread operator|. name|sleep argument_list|( literal|200 argument_list|) expr_stmt|; name|executor operator|. name|shutdownNow argument_list|() expr_stmt|; comment|// Will interrupt the tail name|executor operator|. name|awaitTermination argument_list|( literal|10 argument_list|, name|TimeUnit operator|. name|SECONDS argument_list|) expr_stmt|; if|if condition|( name|exception operator|!= literal|null condition|) block|{ throw|throw name|exception throw|; block|} name|verify argument_list|( name|tail operator|. name|session argument_list|) expr_stmt|; block|} specifier|private name|Event name|event parameter_list|() block|{ return|return operator|new name|Event argument_list|( literal|"myTopic" argument_list|, operator|new name|HashMap argument_list|<> argument_list|() argument_list|) return|; block|} block|} end_class end_unit
14.110825
810
0.795982
c2b59db278b24be2b08babd4ef666c168317e0b3
141
package com.devteam.module.enums; public enum EditMode { DRAFT, VALIDATED, LOCKED; static public EditMode[] ALL = EditMode.values(); }
17.625
51
0.730496
ccc038cb721e53fed3d89e01418629a520850268
3,530
/* * Copyright (c) 2014, Andreas P. Koenzen <akc at apkc.net> * 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. * * 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 HOLDER 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 net.apkc.sf.mvc; import javax.swing.*; /** * Skeleton class for all frames. * * @author Andreas P. Koenzen <akc at apkc.net> * @version 0.1 */ public abstract class AbstractFrame extends JFrame { /** * Override this method to include code that builds this frame. * * <p> * The following tasks should be executed inside this method: * <ul> * <li>Initialize all GUI components.</li> * <li>Add components to each other.</li> * <li>Some generic task.</li> * </ul> * </p> * * <p> * The following tasks should NOT be executed inside this method: * <ul> * <li>All tasks inside the {@link configure()} method.</li> * </ul> * </p> * * @return This GUI instance. */ protected abstract AbstractFrame createGUI(); /** * Override this method to include code that configures this frame. * * <p> * The following tasks should be executed inside this method: * <ul> * <li>Make calls to other resources.</li> * <li>Receive information to add to components. i.e. Populating a table * with database information.</li> * <li>Some generic configuration task.</li> * </ul> * </p> * * <p> * The following tasks should NOT be executed inside this method: * <ul> * <li>All tasks inside the {@link createGUI()} method.</li> * </ul> * </p> * * @return This GUI instance. */ public abstract AbstractFrame configure(); /** * Override this method to include code that makes this frame visible. * * <p> * The following tasks should be executed inside this method: * <ul> * <li>Any action to make this GUI visible.</li> * </ul> * </p> * * <p> * The following tasks should NOT be executed inside this method: * <ul> * <li>All tasks inside the {@link createGUI()} method.</li> * <li>All tasks inside the {@link configure()} method.</li> * </ul> * </p> * * @return This GUI instance. */ public abstract AbstractFrame makeVisible(); }
32.990654
80
0.651841
8d0546de77219fa7b89a703f774add887d6b5d55
692
package razerdp.friendcircle.app.mvp.view; import java.util.List; import razerdp.friendcircle.app.mvp.model.entity.CommentInfo; import razerdp.friendcircle.app.mvp.model.entity.LikesInfo; import razerdp.friendcircle.app.mvp.model.entity.UserInfo; import razerdp.github.com.baselibrary.mvp.IBaseView; import razerdp.friendcircle.ui.widget.commentwidget.CommentWidget; /** * Created by 大灯泡 on 2016/12/7. */ public interface IMomentView extends IBaseView { void onLikeChange(int itemPos, List<LikesInfo> likeUserList); void onCommentChange(int itemPos, List<CommentInfo> commentInfoList); void showCommentBox(int itemPos, String momentid, CommentWidget commentWidget); }
26.615385
83
0.799133
1aa1c38956fba4597dd38fdb78887c67f66f28bd
3,471
/** * Package: MAG - VistA Imaging WARNING: Per VHA Directive 2004-038, this routine should not be modified. Date Created: Jun 17, 2011 Site Name: Washington OI Field Office, Silver Spring, MD Developer: VHAISWWERFEJ Description: ;; +--------------------------------------------------------------------+ ;; Property of the US Government. ;; No permission to copy or redistribute this software is given. ;; Use of unreleased versions of this software requires the user ;; to execute a written test agreement with the VistA Imaging ;; Development Office of the Department of Veterans Affairs, ;; telephone (301) 734-0100. ;; ;; The Food and Drug Administration classifies this software as ;; a Class II medical device. As such, it may not be changed ;; in any way. Modifications to this software may result in an ;; adulterated medical device under 21CFR820, the use of which ;; is considered to be a violation of US Federal Statutes. ;; +--------------------------------------------------------------------+ */ package gov.va.med.imaging.router.commands.annotations; import gov.va.med.RoutingToken; import gov.va.med.imaging.AbstractImagingURN; import gov.va.med.imaging.ImageAnnotationURN; import gov.va.med.imaging.core.interfaces.exceptions.ConnectionException; import gov.va.med.imaging.core.interfaces.exceptions.MethodException; import gov.va.med.imaging.core.router.AbstractDataSourceCommandImpl; import gov.va.med.imaging.datasource.ImageAnnotationDataSourceSpi; import gov.va.med.imaging.exchange.business.annotations.ImageAnnotationDetails; /** * @author VHAISWWERFEJ * */ public class GetImageAnnotationDetailsCommandImpl extends AbstractDataSourceCommandImpl<ImageAnnotationDetails, ImageAnnotationDataSourceSpi> { private static final long serialVersionUID = 5588995673006440151L; private final ImageAnnotationURN imageAnnotationUrn; private final AbstractImagingURN imagingUrn; private static final String SPI_METHOD_NAME = "getAnnotationDetails"; private static final Class<?>[] SPI_METHOD_PARAMETER_TYPES = new Class<?>[]{AbstractImagingURN.class, ImageAnnotationURN.class}; public GetImageAnnotationDetailsCommandImpl(AbstractImagingURN imagingUrn, ImageAnnotationURN imageAnnotationUrn) { this.imageAnnotationUrn = imageAnnotationUrn; this.imagingUrn = imagingUrn; } public ImageAnnotationURN getImageAnnotationUrn() { return imageAnnotationUrn; } public AbstractImagingURN getImagingUrn() { return imagingUrn; } @Override public RoutingToken getRoutingToken() { return getImagingUrn(); } @Override protected Class<ImageAnnotationDataSourceSpi> getSpiClass() { return ImageAnnotationDataSourceSpi.class; } @Override protected String getSpiMethodName() { return SPI_METHOD_NAME; } @Override protected Class<?>[] getSpiMethodParameterTypes() { return SPI_METHOD_PARAMETER_TYPES; } @Override protected Object[] getSpiMethodParameters() { return new Object [] {getImagingUrn(), getImageAnnotationUrn()}; } @Override protected String getSiteNumber() { return getRoutingToken().getRepositoryUniqueId(); } @Override protected ImageAnnotationDetails getCommandResult( ImageAnnotationDataSourceSpi spi) throws ConnectionException, MethodException { return spi.getAnnotationDetails(getImagingUrn(), getImageAnnotationUrn()); } }
29.922414
91
0.731201
48362e96e2305f6f869064b90dec108c80247334
10,151
/* * 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 org.redkale.source; import java.util.*; import org.redkale.convert.*; import org.redkale.convert.json.JsonConvert; /** * SearchQuery用于构建搜索过滤条件<br> * * 不被标记为&#64;javax.persistence.Transient 的字段均视为过滤条件 <br> * * <p> * 详情见: https://redkale.org * * @author zhangjx * * @since 2.7.0 */ @ConvertImpl(SearchQuery.SearchSimpleQuery.class) public interface SearchQuery extends java.io.Serializable { public static final String SEARCH_FILTER_NAME = "#search"; public static SearchSimpleQuery create() { return new SearchSimpleQuery(); } public static SearchSimpleQuery create(String keyword, String... fields) { return new SearchSimpleQuery(keyword, fields); } public static SearchSimpleHighlight createHighlight() { return new SearchSimpleHighlight(); } /** * 需要搜索的index集合,无值则使用当前entity类 * * @return Class[] */ public Class[] searchClasses(); /** * 搜索字段集合, 必须字段值 * * @return String[] */ public String[] searchFields(); /** * 搜索关键字, 必须字段值 * * @return String */ public String searchKeyword(); /** * 搜索分词器,可以为空 * * @return String */ public String searchAnalyzer(); /** * 扩展的信息 * * @return Map */ default Map<String, Object> extras() { return null; } /** * 高亮显示 * * @return SearchHighlight */ public SearchHighlight highlight(); @ConvertImpl(SearchQuery.SearchSimpleHighlight.class) public static interface SearchHighlight { public static SearchSimpleHighlight create() { return new SearchSimpleHighlight(); } public static SearchSimpleHighlight createTag(String preTag, String postTag) { return new SearchSimpleHighlight().tag(preTag, postTag); } public String preTag(); public String postTag(); public String boundaryLocale(); public int fragmentSize(); default int fragmentCount() { return 1; } default Map<String, Object> extras() { return null; } } public static class SearchSimpleQuery implements SearchQuery { @ConvertColumn(index = 1) @FilterColumn(ignore = true) private Class[] classes; @ConvertColumn(index = 2) @FilterColumn(ignore = true) private String[] fields; @ConvertColumn(index = 3) @FilterColumn(ignore = true) private String keyword; @ConvertColumn(index = 4) @FilterColumn(ignore = true) private String analyzer; @ConvertColumn(index = 5) @FilterColumn(ignore = true) private SearchHighlight highlight; @ConvertColumn(index = 6) @FilterColumn(ignore = true) private Map<String, Object> extras; public SearchSimpleQuery() { } public SearchSimpleQuery(String keyword, String... fields) { this.keyword = keyword; this.fields = fields; if (fields == null || fields.length < 1) throw new IllegalArgumentException("fields is empty"); } public SearchSimpleQuery keyword(String keyword) { this.keyword = keyword; return this; } public SearchSimpleQuery analyzer(String analyzer) { this.analyzer = analyzer; return this; } public SearchSimpleQuery fields(String... fields) { if (fields == null || fields.length < 1) throw new IllegalArgumentException("fields is empty"); this.fields = fields; return this; } public SearchSimpleQuery classes(Class[] classes) { this.classes = classes; return this; } public SearchSimpleQuery highlight(SearchHighlight highlight) { this.highlight = highlight; return this; } public SearchSimpleQuery extras(Map<String, Object> map) { this.extras = map; return this; } public SearchSimpleQuery extras(String key, Object value) { if (this.extras == null) this.extras = new LinkedHashMap<>(); this.extras.put(key, value); return this; } @Override public String searchKeyword() { return keyword; } @Override public Class[] searchClasses() { return classes; } @Override public String[] searchFields() { return fields; } @Override public Map<String, Object> extras() { return extras; } @Override public String searchAnalyzer() { return analyzer; } @Override public SearchHighlight highlight() { return highlight; } public Class[] getClasses() { return classes; } public void setClasses(Class[] classes) { this.classes = classes; } public String[] getFields() { return fields; } public void setFields(String[] fields) { this.fields = fields; } public String getKeyword() { return keyword; } public void setKeyword(String keyword) { this.keyword = keyword; } public String getAnalyzer() { return analyzer; } public void setAnalyzer(String analyzer) { this.analyzer = analyzer; } public SearchHighlight getHighlight() { return highlight; } public void setHighlight(SearchHighlight highlight) { this.highlight = highlight; } public Map<String, Object> getExtras() { return extras; } public void setExtras(Map<String, Object> extras) { this.extras = extras; } @Override public String toString() { return JsonConvert.root().convertTo(this); } } public static class SearchSimpleHighlight implements SearchHighlight { @ConvertColumn(index = 1) private String preTag; @ConvertColumn(index = 2) private String postTag; @ConvertColumn(index = 3) private String boundaryLocale; @ConvertColumn(index = 4) private int fragmentSize = 100; @ConvertColumn(index = 5) private int fragmentCount = 1; @ConvertColumn(index = 6) @FilterColumn(ignore = true) private Map<String, Object> extras; public SearchSimpleHighlight tag(String preTag, String postTag) { this.preTag = preTag; this.postTag = postTag; return this; } public SearchSimpleHighlight boundaryLocale(String boundaryLocale) { this.boundaryLocale = boundaryLocale; return this; } public SearchSimpleHighlight fragmentSize(int fragmentSize) { this.fragmentSize = fragmentSize; return this; } public SearchSimpleHighlight fragmentCount(int fragmentCount) { this.fragmentCount = fragmentCount; return this; } public SearchSimpleHighlight extras(Map<String, Object> map) { this.extras = map; return this; } public SearchSimpleHighlight extras(String key, Object value) { if (this.extras == null) this.extras = new LinkedHashMap<>(); this.extras.put(key, value); return this; } @Override public Map<String, Object> extras() { return extras; } @Override public String preTag() { return preTag; } @Override public String postTag() { return postTag; } @Override public String boundaryLocale() { return boundaryLocale; } @Override public int fragmentSize() { return fragmentSize; } @Override public int fragmentCount() { return fragmentCount; } public String getPreTag() { return preTag; } public void setPreTag(String preTag) { this.preTag = preTag; } public String getPostTag() { return postTag; } public void setPostTag(String postTag) { this.postTag = postTag; } public String getBoundaryLocale() { return boundaryLocale; } public void setBoundaryLocale(String boundaryLocale) { this.boundaryLocale = boundaryLocale; } public int getFragmentSize() { return fragmentSize; } public void setFragmentSize(int fragmentSize) { this.fragmentSize = fragmentSize; } public int getFragmentCount() { return fragmentCount; } public void setFragmentCount(int fragmentCount) { this.fragmentCount = fragmentCount; } public Map<String, Object> getExtras() { return extras; } public void setExtras(Map<String, Object> extras) { this.extras = extras; } @Override public String toString() { return JsonConvert.root().convertTo(this); } } }
24.819071
108
0.540242
af158c9e7232924ec68d194adb447056584b6188
6,948
package com.momia.service.impl; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.stereotype.Service; import com.momia.entity.AssortGoods; //import com.momia.entity.Crowd; import com.momia.entity.GoodsAssort; //import com.momia.entity.GoodsCrowd; //import com.momia.entity.TopicGoodsAssort; import com.momia.service.AssortGoodsService; /** * 商品分类 * @author duohongzhi * */ @Service public class AssortGoodsServiceImpl implements AssortGoodsService{ @Resource private JdbcTemplate jdbcTemplate; public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public List<AssortGoods> findAssortments() { String sql = "select id,name,parentid,status,updateTime from t_goods_assortment "; List<AssortGoods> ls = new ArrayList<AssortGoods>(); List<Map<String, Object>> list = jdbcTemplate.queryForList(sql); for (int i = 0; i < list.size(); i++) { AssortGoods entity = new AssortGoods(); entity.setId(Integer.parseInt(list.get(i).get("id").toString())); entity.setName(list.get(i).get("name").toString()); entity.setParentid(Integer.parseInt(list.get(i).get("parentid").toString())); entity.setStatus(Integer.parseInt(list.get(i).get("status").toString())); entity.setUpdateTime(list.get(i).get("updateTime").toString()); entity.setListGoods(new ArrayList<AssortGoods>()); entity.setFlag(0); ls.add(entity); } return ls; } public AssortGoods findAssortmentById(int id) { String sql = "select * from t_goods_assortment where id = ?"; final AssortGoods assort = new AssortGoods(); final Object[] params = new Object[] {id}; // 调用jdbcTemplate的query方法 jdbcTemplate.query(sql,params, new RowCallbackHandler(){ public void processRow(ResultSet rs) throws SQLException { assortGoodsForm(rs, assort); } }); return assort; } public int update(AssortGoods assort) { String sql = "update t_goods_assortment set name = ?, parentid = ?, status = ?, updateTime = ? where id = ?"; Object[] params = new Object[] {assort.getName(), assort.getParentid(), assort.getStatus(), assort.getUpdateTime(), assort.getId()}; int flag = jdbcTemplate.update(sql,params); return flag; } public int insert(AssortGoods assort) { String sql = "insert into t_goods_assortment (name, parentid, status, updateTime) values (?, ?, ?, ?)"; Object[] params = new Object[] {assort.getName(), assort.getParentid(), assort.getStatus(), assort.getUpdateTime()}; int flag = jdbcTemplate.update(sql,params); return flag; } public int delete(int id) { String sql = "delete from t_goods_assortment where id = ?"; Object[] params = new Object[] {id}; int flag = jdbcTemplate.update(sql,params); return flag; } public AssortGoods assortGoodsForm(ResultSet rs,AssortGoods assort){ try { assort.setId(rs.getInt("id")); assort.setName(rs.getString("name")); assort.setParentid(Integer.parseInt(rs.getString("parentid"))); assort.setStatus(Integer.parseInt(rs.getString("status"))); assort.setUpdateTime(rs.getString("updateTime")); assort.setListGoods(new ArrayList<AssortGoods>()); } catch (SQLException e) { e.printStackTrace(); } return assort; } public AssortGoods formAssortGoods(HttpServletRequest req,int falg){ AssortGoods assort = new AssortGoods(); if(falg == 0){ assort.setId(Integer.parseInt(req.getParameter("id"))); } assort.setName(req.getParameter("name")); assort.setParentid(Integer.parseInt(req.getParameter("parentid"))); assort.setStatus(1); assort.setUpdateTime((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date())); assort.setListGoods(new ArrayList<AssortGoods>()); return assort; } /** * goods中获取标识选中的分类数据 */ public List<AssortGoods> findAssortGoods(List<AssortGoods> assortGoods,List<GoodsAssort> gAssort) { List<AssortGoods> list = new ArrayList<AssortGoods>(); if(assortGoods.size() > 0 && gAssort.size() > 0){ for (int i = 0; i < assortGoods.size(); i++) { int r = 0; for (int j = 0; j < gAssort.size(); j++) { int id = assortGoods.get(i).getId(); int cid = gAssort.get(j).getAssid(); if( id == cid){ AssortGoods entity = assortGoods.get(i); entity.setFlag(1); list.add(entity); r = 1; break; } } if(r == 0){ list.add(assortGoods.get(i)); } } }else{ list.addAll(assortGoods); } return list; } /** * 商品专题分类 */ // public List<AssortGoods> findAssortgoods(List<AssortGoods> entitys1,List<TopicGoodsAssort> entitys2) { // List<AssortGoods> ls = new ArrayList<AssortGoods>(); // if(entitys1.size() > 0 ){ // ls.addAll(findLevel(entitys1)); // } // if(ls.size() > 0){ // for (int i = 0; i < ls.size(); i++) { // List<AssortGoods> sss = new ArrayList<AssortGoods>(); // sss = findForTopic(ls.get(i).getListGoods(),entitys2); // ls.get(i).setListGoods(sss); // } // } // // return ls; // } /** * 查找专题二级被选中项 * @param entitys1 * @param entitys2 * @return */ // public List<AssortGoods> findForTopic(List<AssortGoods> entitys1,List<TopicGoodsAssort> entitys2){ // List<AssortGoods> ls = new ArrayList<AssortGoods>(); // if(entitys1.size()>0){ // for (int i = 0; i < entitys1.size(); i++) { // int aid = entitys1.get(i).getId(); // AssortGoods entity = new AssortGoods(); // entity = entitys1.get(i); // for (int j = 0; j < entitys2.size(); j++) { // int bid = entitys2.get(j).getAssid(); // if(aid == bid){ // entity.setFlag(1); // }else{ // continue; // } // } // ls.add(entity); // } // } // return ls; // } /** * 组装一级和二级 * @param list * @return */ // public List<AssortGoods> findLevel(List<AssortGoods> list){ // List<AssortGoods> pls = new ArrayList<AssortGoods>(); // List<AssortGoods> ls = new ArrayList<AssortGoods>(); // // if(list.size() > 0){ // for (int i = 0; i < list.size(); i++) { // if(list.get(i).getParentid() == 0){ // pls.add(list.get(i)); // }else{ // ls.add(list.get(i)); // } // } // } // // if(pls.size() > 0 && ls.size() > 0){ // for (int i = 0; i < pls.size(); i++) { // int aid = pls.get(i).getId(); // List<AssortGoods> mapls = new ArrayList<AssortGoods>(); // for (int j = 0; j < ls.size(); j++) { // int bid = ls.get(j).getParentid(); // if(aid == bid){ // mapls.add(ls.get(j)); // }else{ // continue; // } // } // pls.get(i).setListGoods(mapls); // } // } // // return pls; // // } }
28.359184
134
0.651267
639fc82dfbdd362775bcb916d2b7d65949c2eb57
1,023
package org.nutz.ioc.java; import org.nutz.ioc.IocMaking; import org.nutz.lang.Lang; public abstract class ChainNode { private ChainNode next; public void setNext(ChainNode next) { this.next = next; } protected abstract Object getValue(IocMaking ing, Object obj) throws Exception; protected abstract String asString(); public Object eval(IocMaking ing) { return eval(ing, null); } private Object eval(IocMaking ing, Object obj) { try { Object v = getValue(ing, obj); if (null == next) { return v; } return next.eval(ing, v); } catch (Exception e) { throw Lang.wrapThrow(e); } } @Override public String toString() { StringBuilder sb = new StringBuilder(asString()); if (null != next) { sb.append('.').append(next.toString()); } return sb.toString(); } }
22.733333
84
0.537634
270b97f1e487a354795d7231821d159865d8d6e2
3,208
/* * Copyright (C) 2018 Sergej Shafarenka, www.halfbit.de * * 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 magnet; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import magnet.internal.Factory; import magnet.internal.Range; final class MagnetImplementationManager implements ImplementationManager { private static final String DEFAULT_TARGET = ""; private Factory[] factories; private Map<Class, Object> index; MagnetImplementationManager() { registerImplementations(); } private void registerImplementations() { try { Class<?> magnetClass = Class.forName("magnet.MagnetIndexer"); Method registerFactories = magnetClass.getMethod("register", MagnetImplementationManager.class); registerFactories.invoke(magnetClass, this); } catch (Exception e) { System.out.println( "MagnetIndexer.class cannot be found. " + "Add a @MagnetizeImplementations-annotated class to the application module."); } } // called by generated index class void register(Factory[] factories, Map<Class, Object> index) { this.factories = factories; this.index = index; } @Override public <T> List<T> get(Class<T> forType, DependencyScope dependencyScope) { return get(forType, DEFAULT_TARGET, dependencyScope); } @Override public <T> List<T> get(Class<T> forType, String forTarget, DependencyScope dependencyScope) { Object indexed = index.get(forType); if (indexed instanceof Range) { Range range = (Range) indexed; if (range.getTarget().equals(forTarget)) { return createFromRange(range, dependencyScope); } return Collections.emptyList(); } if (indexed instanceof Map) { //noinspection unchecked Map<String, Range> ranges = (Map<String, Range>) indexed; Range range = ranges.get(forTarget); if (range != null) { return createFromRange(range, dependencyScope); } return Collections.emptyList(); } return Collections.emptyList(); } private <T> List<T> createFromRange(Range range, DependencyScope dependencyScope) { List<T> impls = new ArrayList<>(); for (int i = range.getFrom(), to = range.getFrom() + range.getCount(); i < to; i++) { //noinspection unchecked impls.add((T) factories[i].create(dependencyScope)); } return impls; } }
33.072165
108
0.645574
f75427355b569ebdebb844f0a218b0e37b65c4ba
569
package dao.entities; public class ReturnNowPlayingAlbum extends ReturnNowPlaying { private final String album; public ReturnNowPlayingAlbum(ReturnNowPlaying other, String album) { this(other.getDiscordId(), other.getLastFMId(), other.getArtist(), other.getPlayNumber(), album); } public ReturnNowPlayingAlbum(long discordId, String lastFMId, String artist, int playNumber, String album) { super(discordId, lastFMId, artist, playNumber); this.album = album; } public String getAlbum() { return album; } }
29.947368
112
0.706503
503845a9abf4e83598463bc0a18f6eafbdd696dd
2,205
package com.uic.cs581.utils; import lombok.extern.slf4j.Slf4j; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; @Slf4j public class SendHttpRequest { public static void main(String args[]) { TimeZone.setDefault(TimeZone.getTimeZone("America/New_York")); SendHttpRequest.getRequest(1451635510000L, false); } public static Map<String, Double> getRequest(long millis, boolean readJson) { BufferedReader in; HttpURLConnection con; if (readJson) { try { return new ObjectMapper().readValue( new File("scores.json"), new TypeReference<Map<String, Double>>() { }); } catch (IOException e) { log.error("Zones score file cannot be found/read.Please solve this issue first"); System.exit(1); return null; } } try { log.info("Python Api hit:" + millis); URL url = new URL("http://127.0.0.1:5000/?times=" + millis); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder content = new StringBuilder(); while ((inputLine = in.readLine()) != null) { content.append(inputLine); } in.close(); con.disconnect(); log.info("Python Api response success for:" + millis); return new ObjectMapper().readValue(content.toString(), new TypeReference<Map<String, Double>>() { }); } catch (IOException e) { log.error("Exception with fetch data from Python api.", e); } return new HashMap<>(); } }
32.426471
97
0.577324
3d10f4877571067cba63be15dec5ec2c07783258
450
package net.aionstudios.api.errors; import net.aionstudios.api.error.AOSError; /** * An {@link AOSError} encountered when a request fails due to the absence of a request {@link Action} in the requested {@link Context}. * * @author Winter Roberts * */ public class NoSuchActionError extends AOSError { public NoSuchActionError() { super("NoSuchAction", 404, "The request action was not recognized by the context!"); } }
25
137
0.704444
40920b3b9f24464c7b157fe8ec5e088b82ccce0e
3,228
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.highcharts.export.interceptor; import com.highcharts.export.service.MonitorService; import java.io.IOException; import java.util.Date; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; /** * * @author gert */ public class RequestInterceptor extends HandlerInterceptorAdapter { private static final Logger logger = Logger.getLogger(RequestInterceptor.class.getName()); private static final String lineSeparator = System.getProperty("line.separator"); @Autowired MonitorService monitor; private String extractPostRequestBody(HttpServletRequest request) throws IOException { StringBuilder sb = new StringBuilder(); Map<String, String[]> paramMap = request.getParameterMap(); for (Map.Entry<String, String[]> entry : paramMap.entrySet()) { sb.append("\t"); sb.append(entry.getKey()) .append("="); String[] values = entry.getValue(); for (int i = 0; i < values.length; i++) { sb.append(values[i]); if (i < values.length) { sb.append(", "); } } sb.append(lineSeparator); } return sb.toString(); } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { request.setAttribute("startTime", System.currentTimeMillis()); monitor.add(); return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { long startTime = (Long) request.getAttribute("startTime"); int httpStatus = response.getStatus(); if (httpStatus == 500) { monitor.addError(); logger.log(Level.INFO, "Time={0} :: Time taken(ms) {1}{3} :: RequestMethod {5} :: Status {6} :: Referer={2}{3} :: Request parameters {4}", new Object[]{ new Date().toString(), //0 System.currentTimeMillis() - startTime, //1 request.getHeader("referer"), //2 lineSeparator, //3 extractPostRequestBody(request), //4 request.getMethod(), //5 response.getStatus()}); //6 } else { logger.log(Level.INFO, "Time={0} :: Time taken(ms) {1}{3} :: RequestMethod {4} :: Status {5} :: Referer={2}", new Object[]{ new Date().toString(), //0 System.currentTimeMillis() - startTime, //1 request.getHeader("referer"), //2 lineSeparator, //3 request.getMethod(), //4 response.getStatus()}); //5 } logger.log(Level.INFO, monitor.report()); } }
35.086957
151
0.60316
4f8e63afe7748c289c1d8fc7efb3a44e2cc6e805
256
package spencercjh.problems; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class CanPlaceFlowersTest { private CanPlaceFlowers solution = new CanPlaceFlowers(); @Test void canPlaceFlowers() { } }
15.058824
59
0.734375
0c35388f2f838f95c5439558ebe6eaef29e34660
10,699
// Created by plusminus on 23:18:23 - 02.10.2008 package com.mapbox.mapboxsdk.overlay; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.PointF; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.view.MotionEvent; import com.mapbox.mapboxsdk.views.MapView; import com.mapbox.mapboxsdk.views.safecanvas.ISafeCanvas; import com.mapbox.mapboxsdk.views.safecanvas.ISafeCanvas.UnsafeCanvasHandler; import com.mapbox.mapboxsdk.views.safecanvas.SafePaint; import com.mapbox.mapboxsdk.views.util.Projection; import java.util.ArrayList; /** * Draws a list of {@link Marker} as markers to a map. The item with the lowest index is drawn * as last and therefore the 'topmost' marker. It also gets checked for onTap first. This class is * generic, because you then you get your custom item-class passed back in onTap(). * * @author Marc Kurtz * @author Nicolas Gramlich * @author Theodore Hong * @author Fred Eisele */ public abstract class ItemizedOverlay extends SafeDrawOverlay implements Overlay.Snappable { private final ArrayList<Marker> mInternalItemList; protected boolean mDrawFocusedItem = true; private Marker mFocusedItem; private boolean mPendingFocusChangedEvent = false; private OnFocusChangeListener mOnFocusChangeListener; private static SafePaint mClusterTextPaint; /** * Method by which subclasses create the actual Items. This will only be called from populate() * we'll cache them for later use. */ protected abstract Marker createItem(int i); /** * The number of items in this overlay. */ public abstract int size(); public ItemizedOverlay() { super(); if (mClusterTextPaint == null) { mClusterTextPaint = new SafePaint(); mClusterTextPaint.setTextAlign(Paint.Align.CENTER); mClusterTextPaint.setTextSize(30); mClusterTextPaint.setFakeBoldText(true); } mInternalItemList = new ArrayList<Marker>(); } /** * Draw a marker on each of our items. populate() must have been called first.<br/> * <br/> * The marker will be drawn twice for each Item in the Overlay--once in the shadow phase, * skewed * and darkened, then again in the non-shadow phase. The bottom-center of the marker will be * aligned with the geographical coordinates of the Item.<br/> * <br/> * The order of drawing may be changed by overriding the getIndexToDraw(int) method. An item * may * provide an alternate marker via its Marker.getMarker(int) method. If that method returns * null, the default marker is used.<br/> * <br/> * The focused item is always drawn last, which puts it visually on top of the other * items.<br/> * * @param canvas the Canvas upon which to draw. Note that this may already have a * transformation * applied, so be sure to leave it the way you found it * @param mapView the MapView that requested the draw. Use MapView.getProjection() to convert * between on-screen pixels and latitude/longitude pairs * @param shadow if true, draw the shadow layer. If false, draw the overlay contents. */ @Override protected void drawSafe(ISafeCanvas canvas, MapView mapView, boolean shadow) { if (shadow) { return; } if (mPendingFocusChangedEvent && mOnFocusChangeListener != null) { mOnFocusChangeListener.onFocusChanged(this, mFocusedItem); } mPendingFocusChangedEvent = false; final Projection pj = mapView.getProjection(); final int size = this.mInternalItemList.size() - 1; final RectF bounds = new RectF(0, 0, mapView.getMeasuredWidth(), mapView.getMeasuredHeight()); pj.rotateRect(bounds); final float mapScale = 1 / mapView.getScale(); /* Draw in backward cycle, so the items with the least index are on the front. */ for (int i = size; i >= 0; i--) { final Marker item = getItem(i); if (item == mFocusedItem) { continue; } onDrawItem(canvas, item, pj, mapView.getMapOrientation(), bounds, mapScale); } if (mFocusedItem != null) { onDrawItem(canvas, mFocusedItem, pj, mapView.getMapOrientation(), bounds, mapScale); } } /** * Utility method to perform all processing on a new ItemizedOverlay. Subclasses provide Items * through the createItem(int) method. The subclass should call this as soon as it has data, * before anything else gets called. */ protected void populate() { final int size = size(); mInternalItemList.clear(); mInternalItemList.ensureCapacity(size); for (int a = 0; a < size; a++) { mInternalItemList.add(createItem(a)); } } /** * Returns the Item at the given index. * * @param position the position of the item to return * @return the Item of the given index. */ public final Marker getItem(final int position) { return mInternalItemList.get(position); } /** * Draws an item located at the provided screen coordinates to the canvas. * * @param canvas what the item is drawn upon * @param item the item to be drawn */ protected void onDrawItem(ISafeCanvas canvas, final Marker item, final Projection projection, final float aMapOrientation, final RectF mapBounds, final float mapScale) { item.updateDrawingPosition(); final PointF position = item.getPositionOnMap(); final Point roundedCoords = new Point((int) position.x, (int) position.y); if (!RectF.intersects(mapBounds, item.getDrawingBounds(projection, null))) { //dont draw item if offscreen return; } canvas.save(); canvas.scale(mapScale, mapScale, position.x, position.y); final int state = (mDrawFocusedItem && (mFocusedItem == item) ? Marker.ITEM_STATE_FOCUSED_MASK : 0); final Drawable marker = item.getMarker(state); if (marker == null) { return; } final Point point = item.getAnchor(); // draw it if (this.isUsingSafeCanvas()) { Overlay.drawAt(canvas.getSafeCanvas(), marker, roundedCoords, point, false, aMapOrientation); } else { canvas.getUnsafeCanvas(new UnsafeCanvasHandler() { @Override public void onUnsafeCanvas(Canvas canvas) { Overlay.drawAt(canvas, marker, roundedCoords, point, false, aMapOrientation); } }); } canvas.restore(); } protected boolean markerHitTest(final Marker pMarker, final Projection pProjection, final float pX, final float pY) { RectF rect = pMarker.getDrawingBounds(pProjection, null); rect.bottom -= rect.height() / 2; //a marker drawing bounds is twice the actual size of the marker return rect.contains(pX, pY); } @Override public boolean onSingleTapConfirmed(MotionEvent e, MapView mapView) { final int size = this.size(); final Projection projection = mapView.getProjection(); final float x = e.getX(); final float y = e.getY(); for (int i = 0; i < size; i++) { final Marker item = getItem(i); if (markerHitTest(item, projection, x, y)) { // We have a hit, do we get a response from onTap? if (onTap(i)) { // We got a response so consume the event return true; } } } return super.onSingleTapConfirmed(e, mapView); } /** * Override this method to handle a "tap" on an item. This could be from a touchscreen tap on * an * onscreen Item, or from a trackball click on a centered, selected Item. By default, does * nothing and returns false. * * @return true if you handled the tap, false if you want the event that generated it to pass to * other overlays. */ protected boolean onTap(int index) { return false; } /** * Set whether or not to draw the focused item. The default is to draw it, but some clients may * prefer to draw the focused item themselves. */ public void setDrawFocusedItem(final boolean drawFocusedItem) { mDrawFocusedItem = drawFocusedItem; } /** * If the given Item is found in the overlay, force it to be the current focus-bearer. Any * registered {@link ItemizedOverlay} will be notified. This does not move * the map, so if the Item isn't already centered, the user may get confused. If the Item is * not * found, this is a no-op. You can also pass null to remove focus. */ public void setFocus(final Marker item) { mPendingFocusChangedEvent = item != mFocusedItem; mFocusedItem = item; } /** * @return the currently-focused item, or null if no item is currently focused. */ public Marker getFocus() { return mFocusedItem; } /** * an item want's to be blured, if it is the focused one, blur it */ public void blurItem(final Marker item) { if (mFocusedItem == item) { setFocus(null); } } // /** // * Adjusts a drawable's bounds so that (0,0) is a pixel in the location described by the anchor // * parameter. Useful for "pin"-like graphics. For convenience, returns the same drawable that // * was passed in. // * // * @param marker the drawable to adjust // * @param anchor the anchor for the drawable (float between 0 and 1) // * @return the same drawable that was passed in. // */ // protected synchronized Drawable boundToHotspot(final Drawable marker, Point anchor) { // final int markerWidth = marker.getIntrinsicWidth(); // final int markerHeight = marker.getIntrinsicHeight(); // // mRect.set(0, 0, markerWidth, markerHeight); // mRect.offset(anchor.x, anchor.y); // marker.setBounds(mRect); // return marker; // } public void setOnFocusChangeListener(OnFocusChangeListener l) { mOnFocusChangeListener = l; } public static interface OnFocusChangeListener { void onFocusChanged(ItemizedOverlay overlay, Marker newFocus); } }
36.023569
105
0.634826
5249f7710703a5f10516a558678128fbd96d2afc
4,473
package de.stevenschwenke.java.writingawesomejavacodeworkshop.part1JavaLanguageAndMethods.c05_immutable.cc2_immutablesOrg; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.*; public class AmountOfMoneyExample { @Test public void immutableClassGeneratedFromInterface() throws Exception { AmountOfMoneyWithCurrencyAsInterface amount = ImmutableAmountOfMoneyWithCurrencyAsInterface.builder() .amount(300) .currency("EUR") .build(); assertEquals(300, amount.getAmount()); assertEquals("EUR", amount.getCurrency()); } @Test public void immutableClassGeneratedFromAbstractClass() throws Exception { ImmutableAmountOfMoneyWithCurrency amount = ImmutableAmountOfMoneyWithCurrency.builder() .amount(300) .currency("EUR") .build(); assertEquals(300, amount.getAmount()); assertEquals("EUR", amount.getCurrency()); } @Test public void invalidObjectCreationWillThrowIllegalStateException() throws Exception { assertThrows(IllegalStateException.class, () -> { ImmutableAmountOfMoneyWithCurrency gb = ImmutableAmountOfMoneyWithCurrency.builder() .amount(100) .build(); }); } @Test public void invalidObjectCreationWillNotThrowExceptionWhenOptionalsAreUsed() throws Exception { ImmutableAmountOfMoneyWithOptionalCurrencyAsInterface gb = ImmutableAmountOfMoneyWithOptionalCurrencyAsInterface.builder() .amount(100) .build(); assertFalse(gb.getCurrency().isPresent()); } @Test public void lazyAttributes() throws Exception { ImmutableOrderItemsAsInterface orderItem = ImmutableOrderItemsAsInterface.builder().amount(2).price(12).build(); AbstractOrder order = ImmutableOrder.builder().addOrderItems(orderItem).build(); order.getAllRoundPrice(); order.getAllRoundPrice(); order.getAllRoundPrice(); order.getAllRoundPrice(); } @Test public void from() throws Exception { AmountOfMoneyWithCurrencyAsInterface templateAmount = ImmutableAmountOfMoneyWithCurrencyAsInterface.builder() .amount(300) .currency("EUR") .build(); ImmutableAmountOfMoneyWithCurrencyAsInterface amount2 = ImmutableAmountOfMoneyWithCurrencyAsInterface.builder().from(templateAmount).amount(500).build(); assertEquals(500, amount2.getAmount()); assertEquals("EUR", amount2.getCurrency()); // copied via builder.from(...) } @Test public void immutableCollectionsAreNotNativeInJava() throws Exception { List<Integer> list1 = new ArrayList<>(); list1.add(1); list1.add(2); List<Integer> unmodifiableList = Collections.unmodifiableList(list1); // unmodifiableList.add(3); // throws UnsupportedOperationException because unmodifiableList cannot be changed list1.add(3); // Works, but alters seemingly unmodifiable list2 } @Test public void supportedCollectionTypes() throws Exception { ImmutableAmountOfMoneyWithCurrency money1 = ImmutableAmountOfMoneyWithCurrency.builder().amount(100).currency("EUR").build(); ImmutableAmountOfMoneyWithCurrency money2 = ImmutableAmountOfMoneyWithCurrency.builder().amount(100).currency("EUR").build(); ImmutableBagOfMoney bagOfMoney = ImmutableBagOfMoney.builder().addMoney(money1, money2).build(); /* supported are: T[] java.util.List<T> java.util.Set<T> java.util.Map<K, V> com.google.common.collect.Multiset<T> com.google.common.collect.Multimap<K, V> (ListMultimap, SetMultimap) com.google.common.collect.BiMap<K, V> com.google.common.collect.Immutable* variants for collections above Also: For every Type nice methods are generated like addMoney(T...) above. "Array attributes are cloned for safety (due to the mutable nature of Java arrays). Collection attributes are backed by Guava immutable collections if Guava is available on the classpath. Otherwise, they are safely copied and wrapped in unmodifiable collection classes from the standard JDK." */ } }
39.584071
300
0.687011
15071826c0c31618388d35c6d529f7e8d90b7f13
4,818
package kieker.tools.slastic.plugins.cloud.amazon.service.ec2ToolsIntegration; /** * * @author Florian Fittkau * */ public class AmazonCommandFactory { private final static String allocateNodeCommand = /* proxychains */"ec2-run-instances && --key && KEY-NAME && --group && GROUP-NAME && -t && m1.small && "; private final static String startRemoteCommandCommand = "ssh && -i && SSH_PRIV_KEY && -o && StrictHostKeyChecking=no && SSH_USER_NAME@DESTIP && 'REMOTE-COMMAND'"; private final static String deallocateNodeCommand = /* proxychains */"ec2-terminate-instances && "; private final static String describeNodeCommand = /* proxychains */"ec2-describe-instances && "; // needs SSH StrictHostKeyChecking disabled private final static String applicationDeployCommand = "scp && -i && SSH_PRIV_KEY && -o && StrictHostKeyChecking=no && SOURCEFILE && SSH_USER_NAME@DESTIP:TOMCAT_HOME" + "webapps/"; private final static String applicationUndeployCommand = "ls"; // TODO fixme private final static String cpKiekerConfigCommand = "scp && -i && SSH_PRIV_KEY && -o && StrictHostKeyChecking=no && SOURCEFILE && SSH_USER_NAME@DESTIP:TOMCAT_HOME" + "lib/META-INF/"; private final static String fetchWebSiteCommand = "wget && URL"; private AmazonCommandFactory() { } public static AmazonCommand getAllocateNodeCommand( final String emiNumber, final String keyName, final String group) { String command = AmazonCommandFactory.allocateNodeCommand + emiNumber; command = command.replaceAll("KEY-NAME", keyName); command = command.replaceAll("GROUP-NAME", group); return new AmazonCommand(command); } public static AmazonCommand getDescribeNodeCommand( final String instanceID) { return new AmazonCommand( AmazonCommandFactory.describeNodeCommand + instanceID); } public static AmazonCommand getDeallocateNodeCommand( final String instanceID) { return new AmazonCommand( AmazonCommandFactory.deallocateNodeCommand + instanceID); } public static AmazonCommand getApplicationDeployCommand( final String sshPrivKey, final String sshUserName, final String tomcatHome, final String warFile, final String instanceIP) { String command = AmazonCommandFactory.applicationDeployCommand; command = command.replace("SSH_PRIV_KEY", sshPrivKey); command = command.replace("SSH_USER_NAME", sshUserName); command = command.replace("TOMCAT_HOME", tomcatHome); command = command.replace("SOURCEFILE", warFile); command = command.replace("DESTIP", instanceIP); return new AmazonCommand(command); } public static AmazonCommand getCopyKiekerConfigCommand( final String sshPrivKey, final String sshUserName, final String tomcatHome, final String kiekerFile, final String instanceIP) { String command = AmazonCommandFactory.cpKiekerConfigCommand; command = command.replace("SSH_PRIV_KEY", sshPrivKey); command = command.replace("SSH_USER_NAME", sshUserName); command = command.replace("TOMCAT_HOME", tomcatHome); command = command.replace("SOURCEFILE", kiekerFile); command = command.replace("DESTIP", instanceIP); return new AmazonCommand(command); } public static AmazonCommand getFetchWebSiteCommand( final String url) { String command = AmazonCommandFactory.fetchWebSiteCommand; command = command.replace("URL", url); return new AmazonCommand(command); } public static AmazonCommand getStartTomcatCommand( final String sshPrivKey, final String sshUserName, final String instanceIP, final String tomcatStartScript) { return AmazonCommandFactory.getStartRemoteCommandCommand(sshPrivKey, sshUserName, instanceIP, tomcatStartScript); } // TODO: turn /bin/hostname into property public static AmazonCommand getFetchHostnameCommand( final String sshPrivKey, final String sshUserName, final String instanceIP) { return AmazonCommandFactory.getStartRemoteCommandCommand(sshPrivKey, sshUserName, instanceIP, "/bin/hostname"); } public static AmazonCommand getStartRemoteCommandCommand( final String sshPrivKey, final String sshUserName, final String instanceIP, final String remoteCommand) { String command = AmazonCommandFactory.startRemoteCommandCommand; command = command.replace("SSH_PRIV_KEY", sshPrivKey); command = command.replace("SSH_USER_NAME", sshUserName); command = command.replace("DESTIP", instanceIP); command = command.replace("REMOTE-COMMAND", remoteCommand); return new AmazonCommand(command); } public static AmazonCommand getApplicationUndeployCommand( final String warFile, final String instanceIP) { String command = AmazonCommandFactory.applicationUndeployCommand; command = command.replace("SOURCEFILE", warFile); command = command.replace("DESTIP", instanceIP); return new AmazonCommand(command); } }
35.955224
114
0.76484
76e29180b3716431b8e6973866c93c62d9173ea7
2,307
package org.terifan.security.messagedigest; import java.security.MessageDigest; import java.util.Arrays; public final class HMAC extends MessageDigest implements Cloneable { private transient MessageDigest mMessageDigest; private transient byte [] mInputPad; private transient byte [] mOutputPad; private HMAC(MessageDigest aMessageDigest) { super("HMAC-"+aMessageDigest.getAlgorithm()); mMessageDigest = aMessageDigest; } public HMAC(MessageDigest aMessageDigest, byte [] aPassword) { this(aMessageDigest); init(aPassword); } private void init(byte [] aPassword) { mMessageDigest.reset(); int blockLength; if (mMessageDigest instanceof SHA512) { blockLength = 128; } else { blockLength = 64; } if (aPassword.length > blockLength) { aPassword = mMessageDigest.digest(aPassword); } mInputPad = new byte[blockLength]; System.arraycopy(aPassword, 0, mInputPad, 0, aPassword.length); mOutputPad = mInputPad.clone(); for (int i = 0; i < mInputPad.length; i++) { mInputPad[i] ^= 0x36; mOutputPad[i] ^= 0x5c; } engineReset(); } public MessageDigest getMessageDigest() { return mMessageDigest; } @Override protected byte [] engineDigest() { byte [] tmp = mMessageDigest.digest(); mMessageDigest.update(mOutputPad); byte [] out = mMessageDigest.digest(tmp); engineReset(); return out; } @Override protected int engineGetDigestLength() { return mMessageDigest.getDigestLength(); } @Override protected void engineReset() { mMessageDigest.reset(); mMessageDigest.update(mInputPad); } @Override protected void engineUpdate(byte aBuffer) { mMessageDigest.update(aBuffer); } @Override protected void engineUpdate(byte [] aBuffer, int aOffset, int aLength) { mMessageDigest.update(aBuffer, aOffset, aLength); } @Override public HMAC clone() throws CloneNotSupportedException { HMAC h = new HMAC((MessageDigest)mMessageDigest.clone()); h.mInputPad = mInputPad.clone(); h.mOutputPad = mOutputPad.clone(); return h; } @Override public String toString() { return "HMAC-" + mMessageDigest.toString(); } @Override public void reset() { mMessageDigest.reset(); Arrays.fill(mInputPad, (byte)0); Arrays.fill(mOutputPad, (byte)0); super.reset(); } }
16.717391
71
0.707412
8331ddcaa77f750449177c93bab899d4deef4804
2,148
/** * @see https://mit-license.org/ * The MIT License (MIT) * Copyright © 2019 <copyright holders> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the “Software”), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: The above copyright * notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package estruturas; import grafocidades.Cidade; /** * 29/10/2019 23:13:47 * * @author murilotuvani */ public class VetorOrdenado { private Cidade[] cidades; private int numeroElementos = 0; public VetorOrdenado(int size) { this.cidades = new Cidade[size]; numeroElementos = 0; } public void inserir(Cidade cidade) { int posicao; for (posicao = 0; posicao < numeroElementos; posicao++) { if (cidades[posicao].getDistanciaObjetivo() > cidade.getDistanciaObjetivo()) { break; } } for (int k = numeroElementos; k > posicao; k--) { cidades[k] = cidades[k - 1]; } } public void mostrar() { for (int i = 0; i < numeroElementos; i++) { System.out.println(cidades[i].getNome() + "- " + cidades[i].getDistanciaObjetivo()); } } public Cidade getPrimeiro() { return cidades[0]; } }
32.059701
96
0.667132
0886c4336682de898d9b2b7b473830f960d2fad5
10,923
/* * Copyright 2016-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 org.jetbrains.teamcity.vault.support; import com.intellij.openapi.diagnostic.Logger; import jetbrains.buildServer.agent.BuildProgressLogger; import jetbrains.buildServer.log.Loggers; import org.jetbrains.annotations.NotNull; import org.springframework.beans.factory.DisposableBean; import org.springframework.http.HttpEntity; import org.springframework.scheduling.TaskScheduler; import org.springframework.util.Assert; import org.springframework.vault.authentication.ClientAuthentication; import org.springframework.vault.authentication.LoginToken; import org.springframework.vault.authentication.SessionManager; import org.springframework.vault.client.VaultHttpHeaders; import org.springframework.vault.support.VaultResponse; import org.springframework.vault.support.VaultToken; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestOperations; import java.util.Date; import java.util.Map; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * Simplified version of org.springframework.vault.authentication.LifecycleAwareSessionManager * with ability to override and manipulate everything and improved logging */ @SuppressWarnings("LocalVariableHidesMemberVariable") public class LifecycleAwareSessionManager implements SessionManager, DisposableBean { protected final static Logger LOG = Logger.getInstance(Loggers.AGENT_CATEGORY + "." + "VaultLifecycleAwareSessionManager"); protected final BuildProgressLogger logger; protected final ClientAuthentication clientAuthentication; protected final RestOperations restOperations; protected final TaskScheduler taskScheduler; protected final FixedTimeoutRefreshTrigger refreshTrigger; protected final Object lock = new Object(); private volatile VaultToken token; private volatile ScheduledFuture scheduled; public LifecycleAwareSessionManager(@NotNull ClientAuthentication clientAuthentication, @NotNull TaskScheduler taskScheduler, @NotNull RestOperations restOperations, @NotNull FixedTimeoutRefreshTrigger refreshTrigger, @NotNull BuildProgressLogger logger) { this.clientAuthentication = clientAuthentication; this.restOperations = restOperations; this.taskScheduler = taskScheduler; this.refreshTrigger = refreshTrigger; this.logger = logger; } @Override public void destroy() { VaultToken token = this.token; this.token = null; if (token instanceof LoginToken) { revoke(token); } } protected void revoke(VaultToken token) { RuntimeException e = null; int[] backoffs = {1, 3, 6, 0}; // last is not used for (int backoff : backoffs) { try { restOperations.postForObject("auth/token/revoke-self", new HttpEntity<Object>(VaultHttpHeaders.from(token)), Map.class); return; } catch (RuntimeException re) { e = re; try { //noinspection ImplicitNumericConversion TimeUnit.SECONDS.sleep(backoff); } catch (InterruptedException ignored) { } } } String message = "Cannot revoke HashiCorp Vault token: "; if (e instanceof HttpStatusCodeException) { message += VaultResponses.getError((HttpStatusCodeException) e); } else { message += e.getMessage(); } LOG.warn(message, e); logger.warning(message); } /** * Performs a token refresh. Create a new token if no token was obtained before. If a * token was obtained before, it uses self-renewal to renew the current token. * Client-side errors (like permission denied) indicate the token cannot be renewed * because it's expired or simply not found. * * @return {@literal true} if the refresh was successful. {@literal false} if a new * token was obtained or refresh failed. */ protected boolean renewToken() { LOG.info("Renewing HashiCorp Vault token"); VaultToken token = this.token; if (token == null) { return false; } try { VaultResponse vaultResponse = restOperations.postForObject( "auth/token/renew-self", new HttpEntity<Object>(VaultHttpHeaders.from(token)), VaultResponse.class); LoginToken renewed = from(vaultResponse.getAuth()); LOG.info(String.format("Received token: LoginToken(renewable=%b, lease_duration=%d):", renewed.isRenewable(), renewed.getLeaseDuration())); long validTtlThreshold = TimeUnit.MILLISECONDS.toSeconds(refreshTrigger.getValidTtlThreshold()); if (renewed.getLeaseDuration() <= validTtlThreshold) { LOG.warn(String.format("Token TTL (%s) exceeded validity TTL threshold (%s). Dropping token.", renewed.getLeaseDuration(), validTtlThreshold)); logger.warning("HashiCorp Vault token exceed validity TTL threshold and would be dropped."); this.token = null; return false; } this.token = renewed; LOG.info("Renewed HashiCorp Vault token successfully"); return true; } catch (HttpStatusCodeException e) { logger.warning("Cannot renew HashiCorp Vault token, resetting token and performing re-login: " + e.getStatusCode() + " " + VaultResponses.getError(e)); LOG.warn("Cannot renew HashiCorp Vault token, resetting token and performing re-login: " + e.getStatusCode() + " " + VaultResponses.getError(e), e); this.token = null; return false; } catch (RuntimeException e) { logger.warning("Cannot renew HashiCorp Vault token, resetting token and performing re-login: " + e.getMessage()); LOG.warn("Cannot renew HashiCorp Vault token, resetting token and performing re-login: " + e.getMessage()); this.token = null; return false; } } @Override public VaultToken getSessionToken() { if (token == null) { synchronized (lock) { if (token == null) { token = login(); if (isTokenRenewable()) { scheduleRenewal(); } } } } return token; } @SuppressWarnings("VariableNotUsedInsideIf") protected VaultToken login() { VaultToken token = clientAuthentication.login(); if (token instanceof LoginToken) { LOG.info(String.format("Logged in with token: LoginToken(renewable=%b, lease_duration=%d):", ((LoginToken) token).isRenewable(), ((LoginToken) token).getLeaseDuration())); } else if (token != null) { LOG.info("Logged in with token: regular VaultToken"); } else { LOG.info("Logged in with token: null"); } return token; } protected boolean isTokenRenewable() { VaultToken token = this.token; if (token instanceof LoginToken) { LoginToken loginToken = (LoginToken) token; return loginToken.getLeaseDuration() > 0L && loginToken.isRenewable(); } return false; } protected void scheduleRenewal() { VaultToken token = this.token; if (token instanceof LoginToken) { final Runnable task = new Runnable() { @Override public void run() { try { if (isTokenRenewable()) { boolean mayRenewAgainLater = renewToken(); if (mayRenewAgainLater) { scheduleRenewal(); } } } catch (Exception e) { logger.error("Cannot renew HashiCorp Vault token: " + e.getMessage()); LOG.error("Cannot renew HashiCorp Vault token", e); } } }; Date startTime = refreshTrigger.nextExecutionTime((LoginToken) token); LOG.info("Scheduling HashiCorp Vault token refresh to " + startTime); this.scheduled = taskScheduler.schedule(task, startTime); } } public static class FixedTimeoutRefreshTrigger { protected final long duration; protected final long validTtlThreshold; protected final TimeUnit timeUnit; public FixedTimeoutRefreshTrigger(long timeout, TimeUnit timeUnit) { Assert.isTrue(timeout >= 0L, "Timeout duration must be greater or equal to zero"); Assert.notNull(timeUnit, "TimeUnit must not be null"); this.duration = timeout; this.validTtlThreshold = timeUnit.toMillis(duration) + 2000L; this.timeUnit = timeUnit; } public Date nextExecutionTime(LoginToken loginToken) { long milliseconds = Math.max( TimeUnit.SECONDS.toMillis(1L), TimeUnit.SECONDS.toMillis(loginToken.getLeaseDuration()) - timeUnit.toMillis(duration)); return new Date(System.currentTimeMillis() + milliseconds); } public long getValidTtlThreshold() { return validTtlThreshold; } } protected static LoginToken from(Map<String, Object> auth) { String token = (String) auth.get("client_token"); Boolean renewable = (Boolean) auth.get("renewable"); Number leaseDuration = (Number) auth.get("lease_duration"); if (renewable != null && renewable) { return LoginToken.renewable(token, leaseDuration.longValue()); } if (leaseDuration != null) { return LoginToken.of(token, leaseDuration.longValue()); } return LoginToken.of(token); } }
40.010989
183
0.624096
bff11bad64fdabfac2aa5cbf09f975e30bfd8587
107
package com.newpecunia.unicredit; public enum PackageStatus { PREPARING, ERROR, PARTLY_SIGNED, SIGNED }
21.4
41
0.794393
fac7293b35f416a70c034fbb0459e222e6c0ea90
1,195
package com.mt.main.plugin; import com.mt.mybatis.mapper.MapperData; import com.mt.mybatis.plugin.MtInterceptor; import com.mt.mybatis.plugin.MtInvocation; import com.mt.mybatis.plugin.MtPlugin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>执行日志输出插件</p> * * @author grand 2018/6/21 * @version V1.0 * @modificationHistory=========================逻辑或功能性重大变更记录 * @modify by user: {修改人} * @modify by reason:{方法名}:{原因} */ public class ExecutorLogPlugin implements MtInterceptor { private final Logger logger = LoggerFactory.getLogger(ExecutorLogPlugin.class); @Override public Object intercept(MtInvocation invocation) throws Throwable { MapperData mapperData = (MapperData)invocation.getArgs()[0]; Object[] parameter = (Object[])invocation.getArgs()[1]; logger.info("ExecutorLogPlugin is in processing...."); logger.info("mapperData is :"+ mapperData); for (int i=0;i<parameter.length;i++) { logger.info("parameter "+ i +" is :" + parameter[i]); } return invocation.proceed(); } @Override public Object plugin(Object var1) { return MtPlugin.wrap(var1,this); } }
29.875
83
0.667782
dc078ca091fbb9e53f7e5be7bfa73d789905dd14
1,806
package rocks.inspectit.ui.rcp.handlers; import java.util.Iterator; import org.apache.commons.lang.StringUtils; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.IHandler; import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.handlers.HandlerUtil; import rocks.inspectit.ui.rcp.editor.root.AbstractRootEditor; import rocks.inspectit.ui.rcp.editor.tree.TreeSubView; /** * Collapse handler for trees. * * @author Ivan Senic * */ public class TreeCollapseHandler extends AbstractHandler implements IHandler { /** * Parameter that defines if collapse is performed on all elements or just the selected ones. */ public static final String IS_COLLAPSE_ALL_PARAMETER = "rocks.inspectit.ui.rcp.commands.collapse.isCollapseAll"; /** * {@inheritDoc} */ @Override public Object execute(ExecutionEvent event) throws ExecutionException { String param = event.getParameter(IS_COLLAPSE_ALL_PARAMETER); if (StringUtils.isNotEmpty(param)) { boolean isCollapseAll = Boolean.parseBoolean(param); AbstractRootEditor rootEditor = (AbstractRootEditor) HandlerUtil.getActiveEditor(event); TreeSubView treeSubView = (TreeSubView) rootEditor.getActiveSubView(); if (isCollapseAll) { treeSubView.getTreeViewer().collapseAll(); } else { IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getCurrentSelection(event); for (Iterator<?> iterator = selection.iterator(); iterator.hasNext();) { Object object = iterator.next(); treeSubView.getTreeViewer().collapseToLevel(object, AbstractTreeViewer.ALL_LEVELS); } } } return null; } }
34.075472
113
0.778516
9ff1c34418cce8e3de5d3e902faccdf4843706df
135
package com.algorand.prediction.service.core; public enum QuestionState { CREATED, PUBLISHED, COMPLETE, DISTRIBUTED }
15
45
0.718519
f5a48ec9fb9ceae83f5de46048fdb9d81b7a0ea0
5,422
/* ==================================================================== Copyright 2002-2004 Apache Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package org.apache.poi.hssf.record; import org.apache.poi.util.LittleEndian; import org.apache.poi.util.StringUtil; /** * Title: Header Record<P> * Description: Specifies a header for a sheet<P> * REFERENCE: PG 321 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2)<P> * @author Andrew C. Oliver (acoliver at apache dot org) * @author Shawn Laubach (slaubach at apache dot org) Modified 3/14/02 * @author Jason Height (jheight at chariot dot net dot au) * @version 2.0-pre */ public class HeaderRecord extends Record { public final static short sid = 0x14; private byte field_1_header_len; private String field_2_header; public HeaderRecord() { } /** * Constructs an Header record and sets its fields appropriately. * * @param id id must be 0x14 or an exception will be throw upon validation * @param size the size of the data area of the record * @param data data of the record (should not contain sid/len) */ public HeaderRecord(short id, short size, byte [] data) { super(id, size, data); } /** * Constructs an Header record and sets its fields appropriately. * * @param id id must be 0x14 or an exception will be throw upon validation * @param size the size of the data area of the record * @param data data of the record (should not contain sid/len) * @param offset of the record's data */ public HeaderRecord(short id, short size, byte [] data, int offset) { super(id, size, data, offset); } protected void validateSid(short id) { if (id != sid) { throw new RecordFormatException("NOT A HEADERRECORD"); } } protected void fillFields(byte [] data, short size, int offset) { if (size > 0) { field_1_header_len = data[ 0 + offset ]; field_2_header = StringUtil.getFromCompressedUnicode(data, 3 + offset, // [Shawn] Changed 1 to 3 for offset of string LittleEndian.ubyteToInt(field_1_header_len)); } } /** * set the length of the header string * * @param len length of the header string * @see #setHeader(String) */ public void setHeaderLength(byte len) { field_1_header_len = len; } /** * set the header string * * @param header string to display * @see #setHeaderLength(byte) */ public void setHeader(String header) { field_2_header = header; } /** * get the length of the header string * * @return length of the header string * @see #getHeader() */ public short getHeaderLength() { return (short)(0xFF & field_1_header_len); // [Shawn] Fixed needing unsigned byte } /** * get the header string * * @return header string to display * @see #getHeaderLength() */ public String getHeader() { return field_2_header; } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("[HEADER]\n"); buffer.append(" .length = ").append(getHeaderLength()) .append("\n"); buffer.append(" .header = ").append(getHeader()) .append("\n"); buffer.append("[/HEADER]\n"); return buffer.toString(); } public int serialize(int offset, byte [] data) { int len = 4; if (getHeaderLength() != 0) { len+=3; // [Shawn] Fixed for two null bytes in the length } LittleEndian.putShort(data, 0 + offset, sid); LittleEndian.putShort(data, 2 + offset, ( short ) ((len - 4) + getHeaderLength())); if (getHeaderLength() > 0) { data[ 4 + offset ] = (byte)getHeaderLength(); StringUtil.putCompressedUnicode(getHeader(), data, 7 + offset); // [Shawn] Place the string in the correct offset } return getRecordSize(); } public int getRecordSize() { int retval = 4; if (getHeaderLength() != 0) { retval+=3; // [Shawn] Fixed for two null bytes in the length } retval += getHeaderLength(); return retval; } public short getSid() { return this.sid; } public Object clone() { HeaderRecord rec = new HeaderRecord(); rec.field_1_header_len = field_1_header_len; rec.field_2_header = field_2_header; return rec; } }
27.805128
133
0.578015
ad29a9da93051c358136ca9451f6add4b1be6ee9
2,845
package org.brightify.torch.util; import android.util.SparseArray; import android.util.SparseBooleanArray; import org.brightify.torch.EntityDescription; import org.brightify.torch.TorchService; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Custom implementation of {@link ArrayList} which doesn't load all * * @param <ENTITY> type of entity being handled */ class LazyArrayListImpl<ENTITY> extends ArrayList<ENTITY> implements LazyArrayList<ENTITY> { private final EntityDescription<ENTITY> entityDescription; private final SparseArray<Long> ids = new SparseArray<Long>(); private final SparseBooleanArray loaded = new SparseBooleanArray(); public LazyArrayListImpl(EntityDescription<ENTITY> entityDescription, Long... ids) { this(entityDescription, Arrays.asList(ids)); } public LazyArrayListImpl(EntityDescription<ENTITY> entityDescription, List<Long> ids) { super(ids.size()); this.entityDescription = entityDescription; for (Long id : ids) { this.ids.put(super.size(), id); loaded.put(super.size(), false); super.add(null); } } @Override public ENTITY get(int i) { ENTITY object = super.get(i); if (object != null) { return object; } return loadIfNeeded(i); } @Override public ENTITY set(int i, ENTITY t) { loadIfNeeded(i); return super.set(i, t); } @Override public boolean contains(Object o) { if (!entityDescription.getEntityClass().isAssignableFrom(o.getClass())) { return false; } ENTITY castObject = (ENTITY) o; Long id = entityDescription.getEntityId(castObject); if (id != null) { Integer count = TorchService.torch().load().type(entityDescription.getEntityClass()).filter( entityDescription .getIdProperty().equalTo(id)).count(); if (count == 1) { return true; } } return super.contains(o); } /** * @param i index of item to load * @return instance of T if load was needed, null if value was already cached */ @Override public ENTITY loadIfNeeded(int i) { Boolean loaded = this.loaded.valueAt(i); Long id = ids.valueAt(i); if (loaded != null && !loaded && id != null) { ENTITY object = TorchService.torch().load().type(entityDescription.getEntityClass()).id(id); this.loaded.put(i, true); super.set(i, object); return object; } else { return null; } } @Override public void loadAll() { for (int i = 0; i < ids.size(); i++) { loadIfNeeded(i); } } }
29.329897
104
0.602812
e030225090ac664219c8b4f5b89d3249fd2c67c1
1,626
package interview; import java.util.concurrent.ArrayBlockingQueue; /** * 要求用两个线程顺序交替打印1-26,A-Z,例如A1B2C3....Z26 * * 主要考的是线程的通信,这里我们使用BlockingQueue的方式来阻塞 * * @author wliduo[[email protected]] * @date 2020/4/26 14:15 */ public class T03_3_BlockingQueue { public static class InterviewTest { public static ArrayBlockingQueue arrayBlockQueue1 = new ArrayBlockingQueue(1); public static ArrayBlockingQueue arrayBlockQueue2 = new ArrayBlockingQueue(1); public static char[] aI = "123456789".toCharArray(); public static char[] aC = "ABCDEFGHI".toCharArray(); public static void main(String[] args) { new Thread(() -> { for (char c : aC) { System.out.print(c); try { arrayBlockQueue1.put("ok"); arrayBlockQueue2.take(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "t1").start(); new Thread(() -> { for (char i : aI) { try { arrayBlockQueue1.take(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.print(i); try { arrayBlockQueue2.put("ok"); } catch (InterruptedException e) { e.printStackTrace(); } } }, "t2").start(); } } }
27.559322
86
0.46679
68ca9a8c21fbf428a6c3b098b8286c7b33f1585e
1,439
package com.nshirley.engine3d.entities; import java.nio.FloatBuffer; import com.nshirley.engine3d.graphics.Texture; import com.nshirley.engine3d.graphics.VertexArray; import com.nshirley.engine3d.math.Matrix4f; import com.nshirley.engine3d.math.Vector4f; public class Mesh { protected Matrix4f mlMatrix; protected boolean mlMatrixDirty; protected FloatBuffer mlMatrixBuffer; protected VertexArray va; protected RenderStrategy rs; protected Texture tex; protected Vector4f color; public Mesh(VertexArray va, Texture tex) { this(va, tex, null); } public Mesh(VertexArray va, Texture tex, RenderStrategy rs) { if (rs == null) { rs = new StandardRenderStrategy(); } this.va = va; this.rs = rs; this.tex = tex; this.color = new Vector4f(1, 1, 1, 1); } public void setColor(Vector4f col) { this.color = col; } public Vector4f getColor() { return color; } public void setModelMatrix(Matrix4f m) { this.mlMatrix = m; } public Matrix4f getModelMatrix() { return mlMatrix; } public VertexArray getVertexArray() { return va; } public void setVertexArray(VertexArray va) { this.va = va; } public void setRenderStrategy(RenderStrategy rs) { this.rs = rs; } public void render() { rs.render(this); } public Texture getTexture() { return tex; } public void free() { va.free(); } }
18.934211
63
0.66991
5ed00abb48c1c7e02e76e8af22f6391ad6df44b1
21,883
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.dev.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.dev.models.AgentPoolQueue; import com.azure.dev.models.BuildAuthorizationScope; import com.azure.dev.models.BuildDefinitionReference32; import com.azure.dev.models.BuildDefinitionStep; import com.azure.dev.models.BuildDefinitionVariable; import com.azure.dev.models.BuildOption; import com.azure.dev.models.BuildRepository; import com.azure.dev.models.BuildTrigger; import com.azure.dev.models.DefinitionQuality; import com.azure.dev.models.DefinitionQueueStatus; import com.azure.dev.models.DefinitionReference; import com.azure.dev.models.DefinitionType; import com.azure.dev.models.Demand; import com.azure.dev.models.IdentityRef; import com.azure.dev.models.ProcessParameters; import com.azure.dev.models.ReferenceLinks; import com.azure.dev.models.RetentionPolicy; import com.azure.dev.models.TeamProjectReference; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; import java.util.List; import java.util.Map; /** For back-compat with extensions that use the old Steps format instead of Process and Phases. */ @Fluent public final class BuildDefinition32Inner extends BuildDefinitionReference32 { @JsonIgnore private final ClientLogger logger = new ClientLogger(BuildDefinition32Inner.class); /* * Indicates whether badges are enabled for this definition */ @JsonProperty(value = "badgeEnabled") private Boolean badgeEnabled; /* * The build property. */ @JsonProperty(value = "build") private List<BuildDefinitionStep> build; /* * The build number format */ @JsonProperty(value = "buildNumberFormat") private String buildNumberFormat; /* * The comment entered when saving the definition */ @JsonProperty(value = "comment") private String comment; /* * The demands property. */ @JsonProperty(value = "demands") private List<Demand> demands; /* * The description */ @JsonProperty(value = "description") private String description; /* * The drop location for the definition */ @JsonProperty(value = "dropLocation") private String dropLocation; /* * The job authorization scope for builds which are queued against this * definition */ @JsonProperty(value = "jobAuthorizationScope") private BuildAuthorizationScope jobAuthorizationScope; /* * The job cancel timeout in minutes for builds which are cancelled by user * for this definition */ @JsonProperty(value = "jobCancelTimeoutInMinutes") private Integer jobCancelTimeoutInMinutes; /* * The job execution timeout in minutes for builds which are queued against * this definition */ @JsonProperty(value = "jobTimeoutInMinutes") private Integer jobTimeoutInMinutes; /* * Data representation of a build. */ @JsonProperty(value = "latestBuild") private BuildInner latestBuild; /* * Data representation of a build. */ @JsonProperty(value = "latestCompletedBuild") private BuildInner latestCompletedBuild; /* * The options property. */ @JsonProperty(value = "options") private List<BuildOption> options; /* * Process Parameters */ @JsonProperty(value = "processParameters") private ProcessParameters processParameters; /* * The class represents a property bag as a collection of key-value pairs. * Values of all primitive types (any type with a `TypeCode != * TypeCode.Object`) except for `DBNull` are accepted. Values of type * Byte[], Int32, Double, DateType and String preserve their type, other * primitives are retuned as a String. Byte[] expected as base64 encoded * string. */ @JsonProperty(value = "properties") private PropertiesCollectionInner properties; /* * The repository */ @JsonProperty(value = "repository") private BuildRepository repository; /* * The retentionRules property. */ @JsonProperty(value = "retentionRules") private List<RetentionPolicy> retentionRules; /* * The tags property. */ @JsonProperty(value = "tags") private List<String> tags; /* * The triggers property. */ @JsonProperty(value = "triggers") private List<BuildTrigger> triggers; /* * Dictionary of <BuildDefinitionVariable> */ @JsonProperty(value = "variables") @JsonInclude(value = JsonInclude.Include.NON_NULL, content = JsonInclude.Include.ALWAYS) private Map<String, BuildDefinitionVariable> variables; /** * Get the badgeEnabled property: Indicates whether badges are enabled for this definition. * * @return the badgeEnabled value. */ public Boolean badgeEnabled() { return this.badgeEnabled; } /** * Set the badgeEnabled property: Indicates whether badges are enabled for this definition. * * @param badgeEnabled the badgeEnabled value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withBadgeEnabled(Boolean badgeEnabled) { this.badgeEnabled = badgeEnabled; return this; } /** * Get the build property: The build property. * * @return the build value. */ public List<BuildDefinitionStep> build() { return this.build; } /** * Set the build property: The build property. * * @param build the build value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withBuild(List<BuildDefinitionStep> build) { this.build = build; return this; } /** * Get the buildNumberFormat property: The build number format. * * @return the buildNumberFormat value. */ public String buildNumberFormat() { return this.buildNumberFormat; } /** * Set the buildNumberFormat property: The build number format. * * @param buildNumberFormat the buildNumberFormat value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withBuildNumberFormat(String buildNumberFormat) { this.buildNumberFormat = buildNumberFormat; return this; } /** * Get the comment property: The comment entered when saving the definition. * * @return the comment value. */ public String comment() { return this.comment; } /** * Set the comment property: The comment entered when saving the definition. * * @param comment the comment value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withComment(String comment) { this.comment = comment; return this; } /** * Get the demands property: The demands property. * * @return the demands value. */ public List<Demand> demands() { return this.demands; } /** * Set the demands property: The demands property. * * @param demands the demands value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withDemands(List<Demand> demands) { this.demands = demands; return this; } /** * Get the description property: The description. * * @return the description value. */ public String description() { return this.description; } /** * Set the description property: The description. * * @param description the description value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withDescription(String description) { this.description = description; return this; } /** * Get the dropLocation property: The drop location for the definition. * * @return the dropLocation value. */ public String dropLocation() { return this.dropLocation; } /** * Set the dropLocation property: The drop location for the definition. * * @param dropLocation the dropLocation value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withDropLocation(String dropLocation) { this.dropLocation = dropLocation; return this; } /** * Get the jobAuthorizationScope property: The job authorization scope for builds which are queued against this * definition. * * @return the jobAuthorizationScope value. */ public BuildAuthorizationScope jobAuthorizationScope() { return this.jobAuthorizationScope; } /** * Set the jobAuthorizationScope property: The job authorization scope for builds which are queued against this * definition. * * @param jobAuthorizationScope the jobAuthorizationScope value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withJobAuthorizationScope(BuildAuthorizationScope jobAuthorizationScope) { this.jobAuthorizationScope = jobAuthorizationScope; return this; } /** * Get the jobCancelTimeoutInMinutes property: The job cancel timeout in minutes for builds which are cancelled by * user for this definition. * * @return the jobCancelTimeoutInMinutes value. */ public Integer jobCancelTimeoutInMinutes() { return this.jobCancelTimeoutInMinutes; } /** * Set the jobCancelTimeoutInMinutes property: The job cancel timeout in minutes for builds which are cancelled by * user for this definition. * * @param jobCancelTimeoutInMinutes the jobCancelTimeoutInMinutes value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withJobCancelTimeoutInMinutes(Integer jobCancelTimeoutInMinutes) { this.jobCancelTimeoutInMinutes = jobCancelTimeoutInMinutes; return this; } /** * Get the jobTimeoutInMinutes property: The job execution timeout in minutes for builds which are queued against * this definition. * * @return the jobTimeoutInMinutes value. */ public Integer jobTimeoutInMinutes() { return this.jobTimeoutInMinutes; } /** * Set the jobTimeoutInMinutes property: The job execution timeout in minutes for builds which are queued against * this definition. * * @param jobTimeoutInMinutes the jobTimeoutInMinutes value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withJobTimeoutInMinutes(Integer jobTimeoutInMinutes) { this.jobTimeoutInMinutes = jobTimeoutInMinutes; return this; } /** * Get the latestBuild property: Data representation of a build. * * @return the latestBuild value. */ public BuildInner latestBuild() { return this.latestBuild; } /** * Set the latestBuild property: Data representation of a build. * * @param latestBuild the latestBuild value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withLatestBuild(BuildInner latestBuild) { this.latestBuild = latestBuild; return this; } /** * Get the latestCompletedBuild property: Data representation of a build. * * @return the latestCompletedBuild value. */ public BuildInner latestCompletedBuild() { return this.latestCompletedBuild; } /** * Set the latestCompletedBuild property: Data representation of a build. * * @param latestCompletedBuild the latestCompletedBuild value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withLatestCompletedBuild(BuildInner latestCompletedBuild) { this.latestCompletedBuild = latestCompletedBuild; return this; } /** * Get the options property: The options property. * * @return the options value. */ public List<BuildOption> options() { return this.options; } /** * Set the options property: The options property. * * @param options the options value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withOptions(List<BuildOption> options) { this.options = options; return this; } /** * Get the processParameters property: Process Parameters. * * @return the processParameters value. */ public ProcessParameters processParameters() { return this.processParameters; } /** * Set the processParameters property: Process Parameters. * * @param processParameters the processParameters value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withProcessParameters(ProcessParameters processParameters) { this.processParameters = processParameters; return this; } /** * Get the properties property: The class represents a property bag as a collection of key-value pairs. Values of * all primitive types (any type with a `TypeCode != TypeCode.Object`) except for `DBNull` are accepted. Values of * type Byte[], Int32, Double, DateType and String preserve their type, other primitives are retuned as a String. * Byte[] expected as base64 encoded string. * * @return the properties value. */ public PropertiesCollectionInner properties() { return this.properties; } /** * Set the properties property: The class represents a property bag as a collection of key-value pairs. Values of * all primitive types (any type with a `TypeCode != TypeCode.Object`) except for `DBNull` are accepted. Values of * type Byte[], Int32, Double, DateType and String preserve their type, other primitives are retuned as a String. * Byte[] expected as base64 encoded string. * * @param properties the properties value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withProperties(PropertiesCollectionInner properties) { this.properties = properties; return this; } /** * Get the repository property: The repository. * * @return the repository value. */ public BuildRepository repository() { return this.repository; } /** * Set the repository property: The repository. * * @param repository the repository value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withRepository(BuildRepository repository) { this.repository = repository; return this; } /** * Get the retentionRules property: The retentionRules property. * * @return the retentionRules value. */ public List<RetentionPolicy> retentionRules() { return this.retentionRules; } /** * Set the retentionRules property: The retentionRules property. * * @param retentionRules the retentionRules value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withRetentionRules(List<RetentionPolicy> retentionRules) { this.retentionRules = retentionRules; return this; } /** * Get the tags property: The tags property. * * @return the tags value. */ public List<String> tags() { return this.tags; } /** * Set the tags property: The tags property. * * @param tags the tags value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withTags(List<String> tags) { this.tags = tags; return this; } /** * Get the triggers property: The triggers property. * * @return the triggers value. */ public List<BuildTrigger> triggers() { return this.triggers; } /** * Set the triggers property: The triggers property. * * @param triggers the triggers value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withTriggers(List<BuildTrigger> triggers) { this.triggers = triggers; return this; } /** * Get the variables property: Dictionary of &lt;BuildDefinitionVariable&gt;. * * @return the variables value. */ public Map<String, BuildDefinitionVariable> variables() { return this.variables; } /** * Set the variables property: Dictionary of &lt;BuildDefinitionVariable&gt;. * * @param variables the variables value to set. * @return the BuildDefinition32Inner object itself. */ public BuildDefinition32Inner withVariables(Map<String, BuildDefinitionVariable> variables) { this.variables = variables; return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withLinks(ReferenceLinks links) { super.withLinks(links); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withAuthoredBy(IdentityRef authoredBy) { super.withAuthoredBy(authoredBy); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withDraftOf(DefinitionReference draftOf) { super.withDraftOf(draftOf); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withDrafts(List<DefinitionReference> drafts) { super.withDrafts(drafts); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withMetrics(List<BuildMetricInner> metrics) { super.withMetrics(metrics); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withQuality(DefinitionQuality quality) { super.withQuality(quality); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withQueue(AgentPoolQueue queue) { super.withQueue(queue); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withCreatedDate(OffsetDateTime createdDate) { super.withCreatedDate(createdDate); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withId(Integer id) { super.withId(id); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withName(String name) { super.withName(name); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withPath(String path) { super.withPath(path); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withProject(TeamProjectReference project) { super.withProject(project); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withQueueStatus(DefinitionQueueStatus queueStatus) { super.withQueueStatus(queueStatus); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withRevision(Integer revision) { super.withRevision(revision); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withType(DefinitionType type) { super.withType(type); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withUri(String uri) { super.withUri(uri); return this; } /** {@inheritDoc} */ @Override public BuildDefinition32Inner withUrl(String url) { super.withUrl(url); return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ @Override public void validate() { super.validate(); if (build() != null) { build().forEach(e -> e.validate()); } if (demands() != null) { demands().forEach(e -> e.validate()); } if (latestBuild() != null) { latestBuild().validate(); } if (latestCompletedBuild() != null) { latestCompletedBuild().validate(); } if (options() != null) { options().forEach(e -> e.validate()); } if (processParameters() != null) { processParameters().validate(); } if (properties() != null) { properties().validate(); } if (repository() != null) { repository().validate(); } if (retentionRules() != null) { retentionRules().forEach(e -> e.validate()); } if (triggers() != null) { triggers().forEach(e -> e.validate()); } if (variables() != null) { variables() .values() .forEach( e -> { if (e != null) { e.validate(); } }); } } }
29.216288
118
0.651099
579fbcd269c8691ba5814c50dade0be040bc99d2
248
package com.ctrip.xpipe.api.proxy; import com.ctrip.xpipe.api.command.Command; import io.netty.buffer.ByteBuf; /** * @author chen.zhu * <p> * Oct 23, 2018 */ public interface ProxyCommand<T> extends Command<T> { ByteBuf getRequest(); }
15.5
53
0.697581
ec4695c32329ab1409092e96459c5b939d77a040
620
public class MyException extends Exception{ double radius; public MyException(){ super(); } public MyException(String message) { super(message); } public void setRadius(double radius) throws MyException{ if(radius<0){ throw new MyException(" Invalid "+" radius "); } this.radius = radius; } public static void main(String[] args)throws MyException{ MyException c = new MyException(); try { c.setRadius(-5); } catch(MyException e) { System.out.println(e.getMessage()); } } }
20.666667
62
0.564516
a04126c1657679c1ff649527d0faedbc85e92a31
1,055
package com.osmino.sova.db; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import androidx.room.Update; import com.osmino.sova.model.Assistant; import java.util.List; @Dao public interface AssistantDao { @Query("SELECT * FROM assistants WHERE id = :assistantId") Assistant getAssistant(long assistantId); @Query("SELECT * FROM assistants") LiveData<List<Assistant>> getAll(); @Query("SELECT COUNT(id) FROM assistants") int getCount(); @Query("SELECT id FROM assistants ORDER BY ROWID ASC LIMIT 1") int getFirstAssistantId(); @Insert(onConflict = OnConflictStrategy.REPLACE) long insert(Assistant assistant); @Update void update(Assistant assistant); @Query("DELETE FROM assistants WHERE id = :id") void delete(long id); @Query("UPDATE assistants SET cuid = :cuid WHERE id = :assistantId") void saveCUID(long assistantId, String cuid); }
25.119048
72
0.729858
01f4c107e553a21c4aed09eb9e0ffa9c0ac944d3
1,426
package JavaCode.top_interview_questions_easy.trees; public class two { /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isValidBST(TreeNode root) { if(root==null) { return true; } return dfs(root,Long.MAX_VALUE,Long.MIN_VALUE); } /** * 用Long 是为了防止int极端情况 * @param root * @param max * @param min * @return */ boolean dfs(TreeNode root,long max,long min) { if(root==null) { return true; } if(root.val<=min||root.val>=max) { return false; } return dfs(root.left,root.val,min)&&dfs(root.right,max,root.val); } } } /** * https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/7/trees/48/ * 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 * 假设一个二叉搜索树具有如下特征: * 节点的左子树只包含小于当前节点的数。 * 节点的右子树只包含大于当前节点的数。 * 所有左子树和右子树自身必须也是二叉搜索树。 * 示例 1: * 输入: * 2 * / \ * 1 3 * 输出: true * 示例 2: * 输入: * 5 * / \ * 1 4 * / \ * 3 6 * 输出: false * 解释: 输入为: [5,1,4,null,null,3,6]。 * 根节点的值为 5 ,但是其右子节点值为 4 。 */
20.371429
90
0.475456
b5139354a2b9bf148b86b9fbd286ed0fa90f849d
2,265
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.ugraphic.g2d; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import net.sourceforge.plantuml.EnsureVisible; import net.sourceforge.plantuml.ugraphic.UDriver; import net.sourceforge.plantuml.ugraphic.UImage; import net.sourceforge.plantuml.ugraphic.UParam; import net.sourceforge.plantuml.ugraphic.color.ColorMapper; public class DriverImageG2d implements UDriver<UImage, Graphics2D> { private final EnsureVisible visible; private final double dpiFactor; public DriverImageG2d(double dpiFactor, EnsureVisible visible) { this.visible = visible; this.dpiFactor = dpiFactor; } public void draw(UImage shape, double x, double y, ColorMapper mapper, UParam param, Graphics2D g2d) { visible.ensureVisible(x, y); visible.ensureVisible(x + shape.getWidth(), y + shape.getHeight()); if (dpiFactor == 1) { g2d.drawImage(shape.getImage(1), (int) (x), (int) (y), null); } else { final AffineTransform back = g2d.getTransform(); g2d.scale(1 / dpiFactor, 1 / dpiFactor); g2d.drawImage(shape.getImage(dpiFactor), (int) (x * dpiFactor), (int) (y * dpiFactor), null); g2d.setTransform(back); } } }
33.80597
103
0.684768
f9604c87f9b8529bd6076e2b343c90012c9c7592
6,930
package mendixsso.implementation.utils; import com.mendix.core.Core; import com.mendix.logging.ILogNode; import com.mendix.m2ee.api.IMxRuntimeRequest; import com.mendix.m2ee.api.IMxRuntimeResponse; import com.mendix.systemwideinterfaces.core.ISession; import mendixsso.implementation.handlers.OpenIDHandler; import mendixsso.proxies.constants.Constants; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.security.SecureRandom; import java.util.Base64; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import static mendixsso.implementation.handlers.OpenIDHandler.CALLBACK; import static mendixsso.implementation.handlers.OpenIDHandler.OPENID_CLIENTSERVLET_LOCATION; public class OpenIDUtils { private OpenIDUtils() { } private static final String ALPHA_CAPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final String ALPHA = "abcdefghijklmnopqrstuvwxyz"; private static final String HTTP = "http"; private static final String HTTPS = "https"; private static final String LOCATION_HEADER_NAME = "location"; private static final String NUM = "0123456789"; private static final String SPL_CHARS = "!@#$%^&*_=+-/"; private static final ILogNode LOG = Core.getLogger(Constants.getLogNode()); private static final Pattern OPENID_UUID_REGEX = Pattern.compile("mxid2/id\\?id=(\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12})$"); private static final SecureRandom RANDOM = new SecureRandom(); public static String getApplicationUrl(IMxRuntimeRequest req) { final String serverName = req.getHttpServletRequest().getServerName(); if (serverName == null) { LOG.warn("Something went wrong while determining the server name from the request, defaulting to the application root URL."); return getDefaultAppRootUrl(); } try { // Because the Mendix Cloud load balancers terminate SSL connections, it is not possible to determine // the original request scheme (whether it is http or https). Therefore we assume https for all connections // except localhost (to enable local development). final String scheme = serverName.toLowerCase().endsWith(".test") || "localhost".equalsIgnoreCase(serverName) ? HTTP : HTTPS; final int serverPort = req.getHttpServletRequest().getServerPort(); // Ports 80 and 443 should be avoided, as they are the default, therefore we pass in -1 final URI appUri = new URI(scheme, null, serverName, serverPort == 80 || serverPort == 443 ? -1 : serverPort, "/", null, null); return appUri.toString(); } catch (URISyntaxException e) { LOG.warn("Something went wrong while constructing the application URL, defaulting to the application root URL.", e); return getDefaultAppRootUrl(); } } private static String getDefaultAppRootUrl() { return ensureEndsWithSlash(Core.getConfiguration().getApplicationRootUrl()); } public static String extractUUID(String openID) { if (openID != null) { final Matcher m = OPENID_UUID_REGEX.matcher(openID); if (m.find()) { return m.group(1); } } return null; } public static String getOpenID(String uuid) { return ensureEndsWithSlash(Constants.getMxID2_OpenIDPrefix()) + "id?id=" + uuid; } public static String getRedirectUri(IMxRuntimeRequest req) { return getApplicationUrl(req) + OPENID_CLIENTSERVLET_LOCATION + CALLBACK; } public static void redirectToIndex(IMxRuntimeRequest req, IMxRuntimeResponse resp, String continuation) { resp.setStatus(IMxRuntimeResponse.SEE_OTHER); //no continuation provided, use index if (continuation == null) resp.addHeader(LOCATION_HEADER_NAME, OpenIDHandler.INDEX_PAGE); else { if (continuation.trim().startsWith("javascript:")) { throw new IllegalArgumentException("Javascript injection detected!"); } else if (!continuation.startsWith("http://") && !continuation.startsWith("https://")) { resp.addHeader(LOCATION_HEADER_NAME, getApplicationUrl(req) + continuation); } else { resp.addHeader(LOCATION_HEADER_NAME, continuation); } } } private static String base64Encode(byte[] bytes) { return Base64.getEncoder().encodeToString(bytes); } public static String getFingerPrint(IMxRuntimeRequest req) { String agent = req.getHeader("User-Agent"); if (agent != null) return base64Encode(agent.getBytes()); return ""; } public static String getFingerPrint(ISession session) { String agent = session.getUserAgent(); if (agent != null) return base64Encode(agent.getBytes()); return ""; } public static String ensureEndsWithSlash(String text) { return text.endsWith("/") ? text : text + "/"; } public static String randomStrongPassword(int minLen, int maxLen, int noOfCAPSAlpha, int noOfDigits, int noOfSplChars) { if (minLen > maxLen) throw new IllegalArgumentException("Min. Length > Max. Length!"); if ((noOfCAPSAlpha + noOfDigits + noOfSplChars) > minLen) throw new IllegalArgumentException ("Min. Length should be at least sum of (CAPS, DIGITS, SPL CHARS) Length!"); int len = RANDOM.nextInt(maxLen - minLen + 1) + minLen; char[] pswd = new char[len]; int index; for (int i = 0; i < noOfCAPSAlpha; i++) { index = getNextIndex(len, pswd); pswd[index] = ALPHA_CAPS.charAt(RANDOM.nextInt(ALPHA_CAPS.length())); } for (int i = 0; i < noOfDigits; i++) { index = getNextIndex(len, pswd); pswd[index] = NUM.charAt(RANDOM.nextInt(NUM.length())); } for (int i = 0; i < noOfSplChars; i++) { index = getNextIndex(len, pswd); pswd[index] = SPL_CHARS.charAt(RANDOM.nextInt(SPL_CHARS.length())); } for (int i = 0; i < len; i++) { if (pswd[i] == 0) { pswd[i] = ALPHA.charAt(RANDOM.nextInt(ALPHA.length())); } } return String.valueOf(pswd); } private static int getNextIndex(int len, char[] pswd) { int index; //noinspection StatementWithEmptyBody while (pswd[index = RANDOM.nextInt(len)] != 0) ; return index; } public static String convertInputStreamToString(InputStream is) { final Scanner s = new Scanner(is).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } }
40.764706
165
0.644156
be567abebec69e3d07236a1c1c0ea53d7aa1253f
2,423
package commandPackage; import fileSystem.Directory; import fileSystem.FileSystemEntity; import fileSystem.FileSystemErrors; import fileSystem.FileSystemTerminal; import fileSystem.Permission; public class Rmdir extends FileCommand { public Rmdir(String commandName, String commandArguments) { super(commandName, commandArguments); } @Override public void executeCommand() { FileSystemTerminal terminalInstance = FileSystemTerminal.getInstance(); FileSystemErrors errorInstance = FileSystemErrors.getInstance(); String copy = commandArguments; if (commandArguments.endsWith("/") && !commandArguments.equals("/")) copy = commandArguments.substring(0, commandArguments.length() - 1); if (copy.equals(".") || copy.equals("..")) { System.out.println(errorInstance.getErrorMessage(getCommand(), 13)); return; } if (copy.equals("/..")) { System.out.println(errorInstance.getErrorMessage(getCommand(), 13)); return; } String entityName = processArguments(copy); if (entityName == null) return; boolean found = false; Directory toRemove = null; for (FileSystemEntity childEntity : ((Directory) targetEntity).getChildEntities()) { if (childEntity.getName().equals(entityName)) { switch (childEntity.getType()) { case "f": System.out.println(errorInstance.getErrorMessage(getCommand(), 3)); return; case "d": found = true; toRemove = (Directory) childEntity; break; default: break; } } } if (found) { FileSystemEntity auxiliary = terminalInstance.getCurrentDirectory(); while (!auxiliary.equals(terminalInstance.getRootDirectory())) { if (toRemove.equals(auxiliary)) { System.out.println(errorInstance.getErrorMessage(getCommand(), 13)); return; } auxiliary = auxiliary.getParent(); } } if (found && toRemove.getChildEntities().size() != 0) { System.out.println(errorInstance.getErrorMessage(getCommand(), 14)); return; } if (found && !Permission.checkPermissions(targetEntity, "w")) { System.out.println(errorInstance.getErrorMessage(getCommand(), 5)); return; } if (!found) { System.out.println(errorInstance.getErrorMessage(getCommand(), 2)); return; } ((Directory) targetEntity).getChildEntities().remove(toRemove); toRemove.getOwner().getOwnedEntities().remove(toRemove); toRemove.setParent(null); toRemove = null; } }
26.336957
86
0.704086
c8d495bc0930ff724e5e87f4e276aafa63a87821
3,515
/** * Copyright (c) 2013-Now http://jeesite.com All rights reserved. */ package com.jeesite.modules.oy_order_management.entity; import com.jeesite.common.entity.DataEntity; import com.jeesite.common.mybatis.annotation.Column; import com.jeesite.common.mybatis.annotation.Table; import com.jeesite.common.mybatis.mapper.query.QueryType; import com.jeesite.modules.oy_client.entity.OyClient; import com.jeesite.modules.oy_send_account.entity.OySendAccount; import org.hibernate.validator.constraints.Length; /** * oy_task_auditEntity * @author chf * @version 2018-07-11 */ @Table(name="oy_task_audit", alias="a", columns={ @Column(name="id", attrName="id", label="id", isPK=true), @Column(name="client_id", attrName="clientId", label="客户关联id"), @Column(name="data_size", attrName="dataSize", label="数据量"), @Column(name="crop", attrName="crop", label="运营商", queryType=QueryType.LIKE), @Column(name="audit_status", attrName="auditStatus", label="审核状态", comment="审核状态(0 未审核,1 审核不通过,2审核通过)", queryType=QueryType.LIKE), @Column(name="acount_id", attrName="acountId", label="发送账号关联id", queryType=QueryType.LIKE), @Column(name="audit_reason", attrName="auditReason", label="审核不通过原因"), @Column(name="message_text", attrName="messageText", label="短信内容", queryType=QueryType.LIKE), @Column(includeEntity=DataEntity.class), }, orderBy="a.update_date DESC" ) public class OyTaskAudit extends DataEntity<OyTaskAudit> { private static final long serialVersionUID = 1L; private String clientId; // 客户关联id private Integer dataSize; // 数据量 private String crop; // 运营商 private String auditStatus; // 审核状态(0 未审核,1 审核不通过,2审核通过) private String acountId; // 发送账号关联id private OySendAccount oySendAccount; // 发送账号实体类 private OyClient oyClient; // 客户实体类 private String auditReason; // 审核不通过原因 private String messageText; // 短信内容 public OyClient getOyClient() { return oyClient; } public void setOyClient(OyClient oyClient) { this.oyClient = oyClient; } public OySendAccount getOySendAccount() { return oySendAccount; } public void setOySendAccount(OySendAccount oySendAccount) { this.oySendAccount = oySendAccount; } public OyTaskAudit() { this(null); } public OyTaskAudit(String id){ super(id); } @Length(min=0, max=64, message="客户关联id长度不能超过 64 个字符") public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public Integer getDataSize() { return dataSize; } public void setDataSize(Integer dataSize) { this.dataSize = dataSize; } @Length(min=0, max=32, message="运营商长度不能超过 32 个字符") public String getCrop() { return crop; } public void setCrop(String crop) { this.crop = crop; } @Length(min=0, max=64, message="审核状态长度不能超过 64 个字符") public String getAuditStatus() { return auditStatus; } public void setAuditStatus(String auditStatus) { this.auditStatus = auditStatus; } @Length(min=0, max=64, message="发送账号关联id长度不能超过 64 个字符") public String getAcountId() { return acountId; } public void setAcountId(String acountId) { this.acountId = acountId; } @Length(min=0, max=64, message="审核不通过原因长度不能超过 64 个字符") public String getAuditReason() { return auditReason; } public void setAuditReason(String auditReason) { this.auditReason = auditReason; } @Length(min=0, max=70, message="短信内容长度不能超过 70 个字符") public String getMessageText() { return messageText; } public void setMessageText(String messageText) { this.messageText = messageText; } }
27.038462
132
0.735704
8b15561fed876897816a0fd5ef67cfd2e7a6c805
1,239
package com.example.demo.controller.homework; import com.example.demo.utility.area.areaKind; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Slf4j @Controller @RequestMapping("homework3/board") public class Bank9_3 { areaKind area = new areaKind(2); @GetMapping("/main") public String boardMain() { log.info("boardMain()"); return "homework3/board/main"; } @GetMapping("/triangleGet") public String triangleGet(Model model) { log.info("triangleGet()"); model.addAttribute("triangle", area.Triangle()); return "homework3/board/triangleGet"; } @GetMapping("/squareGet") public String squareGet(Model model) { log.info("squareGet()"); model.addAttribute("square", area.Square()); return "homework3/board/squareGet"; } @GetMapping("/hexagonGet") public String hexagonGet(Model model) { log.info("hexagonGet()"); model.addAttribute("hexagon", area.Hexagon()); return "homework3/board/hexagonGet"; } }
28.159091
62
0.68523
059810a379b6e3a34245392a329ff37d1a1c098b
1,659
package com.orekaria.jenkins.plugins.globalprescript; import hudson.Extension; import hudson.util.FormValidation; import org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.QueryParameter; /** * @author Orekaria * Add global configuration options */ @Extension public class GPSGlobalConfiguration extends jenkins.model.GlobalConfiguration { /** * @return the singleton instance */ public static GPSGlobalConfiguration get() { return jenkins.model.GlobalConfiguration.all().get(GPSGlobalConfiguration.class); } public GPSGlobalConfiguration() { // When Jenkins is restarted, load any saved configuration from disk. load(); } private SecureGroovyScript secureGroovyScript; /** * @return the currently configured scriptContent, if any */ public SecureGroovyScript getSecureGroovyScript() { return secureGroovyScript; } /** * Together with {@link #getSecureGroovyScript}, binds to entry in {@code config.jelly}. * * @param secureGroovyScript the new value of this field */ @DataBoundSetter public void setSecureGroovyScript(SecureGroovyScript secureGroovyScript) { this.secureGroovyScript = secureGroovyScript; save(); } public FormValidation doCheckScriptContent(@QueryParameter String value) { // TODO: check if the script is valid // if (StringUtils.isEmpty(value)) { // return FormValidation.warning("Please specify a script."); // } return FormValidation.ok(); } }
30.163636
92
0.703436
04ecee665f8c87d9d800bb2a4b17d8b7def8a6dd
7,508
package io.github.mayunfei.rxdownload.entity; import android.content.ContentValues; import android.database.Cursor; import io.github.mayunfei.rxdownload.db.DBHelper; import java.util.List; import static io.github.mayunfei.rxdownload.entity.DownloadStatus.DOWNLOADING; import static io.github.mayunfei.rxdownload.entity.DownloadStatus.ERROR; import static io.github.mayunfei.rxdownload.entity.DownloadStatus.FINISH; import static io.github.mayunfei.rxdownload.entity.DownloadStatus.PAUSE; import static io.github.mayunfei.rxdownload.entity.DownloadStatus.QUEUE; /** * 下载组合 * Created by yunfei on 17-3-25. */ public class DownloadBundle { public static final String TABLE_NAME = "DownloadBundle"; public static final String ID = "id"; public static final String KEY = "key"; public static final String PATH = "path"; public static final String TOTAL_SIZE = "totalSize"; public static final String COMPLETED_SIZE = "completedSize"; public static final String STATUS = "status"; //分类存储 public static final String TYPE = "type"; public static final String ARGS0 = "args0"; public static final String ARGS1 = "args1"; public static final String ARGS2 = "args2"; public static final String ARGS3 = "args3"; public static final String WHERE0 = "where0"; public static final String WHERE1 = "where1"; public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY + " TEXT NOT NULL," + PATH + " TEXT NOT NULL," + TOTAL_SIZE + " LONG," + COMPLETED_SIZE + " LONG," + STATUS + " INTEGER," + ARGS0 + " TEXT," + ARGS1 + " TEXT," + ARGS2 + " TEXT," + ARGS3 + " TEXT," + WHERE0 + " TEXT," + WHERE1 + " TEXT," + TYPE + " INTEGER" + ")"; public static ContentValues insert(DownloadBundle downloadBundle) { ContentValues contentValues = new ContentValues(); contentValues.put(KEY, downloadBundle.key); contentValues.put(PATH, downloadBundle.path); contentValues.put(TOTAL_SIZE, downloadBundle.totalSize); contentValues.put(COMPLETED_SIZE, downloadBundle.completedSize); contentValues.put(STATUS, downloadBundle.status); contentValues.put(TYPE, downloadBundle.type); contentValues.put(ARGS0, downloadBundle.args0); contentValues.put(ARGS1, downloadBundle.args1); contentValues.put(ARGS2, downloadBundle.args2); contentValues.put(ARGS3, downloadBundle.args3); contentValues.put(WHERE0, downloadBundle.where0); contentValues.put(WHERE1, downloadBundle.where0); return contentValues; } public static DownloadBundle getDownloadBundle(Cursor cursor) { int id = DBHelper.getInt(cursor, ID); String key = DBHelper.getString(cursor, KEY); String path = DBHelper.getString(cursor, PATH); long totalSize = DBHelper.getLong(cursor, TOTAL_SIZE); long completedSize = DBHelper.getLong(cursor, COMPLETED_SIZE); int status = DBHelper.getInt(cursor, STATUS); int type = DBHelper.getInt(cursor, TYPE); String arg0 = DBHelper.getString(cursor, ARGS0); String arg1 = DBHelper.getString(cursor, ARGS1); String arg2 = DBHelper.getString(cursor, ARGS2); String arg3 = DBHelper.getString(cursor, ARGS3); String where0 = DBHelper.getString(cursor, WHERE0); String where1 = DBHelper.getString(cursor, WHERE1); DownloadBundle downloadBundle = new DownloadBundle(); downloadBundle.setId(id); downloadBundle.setKey(key); downloadBundle.setPath(path); downloadBundle.setTotalSize(totalSize); downloadBundle.setCompletedSize(completedSize); downloadBundle.setStatus(status); downloadBundle.setType(type); downloadBundle.setArgs0(arg0); downloadBundle.setArgs0(arg1); downloadBundle.setArgs0(arg2); downloadBundle.setArgs0(arg3); downloadBundle.setWhere0(where0); downloadBundle.setWhere1(where1); return downloadBundle; } public static ContentValues update(int status) { ContentValues contentValues = new ContentValues(); contentValues.put(STATUS, status); return contentValues; } public static ContentValues update(DownloadBundle downloadBundle) { ContentValues insert = insert(downloadBundle); insert.put(ID, downloadBundle.getId()); return insert; } private int id; private String key; private String path; private long totalSize; private long completedSize; private int status; private int type; private String args0; private String args1; private String args2; private String args3; private String where0; private String where1; private List<DownloadBean> downloadList; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public long getTotalSize() { return totalSize; } public void setTotalSize(long totalSize) { this.totalSize = totalSize; } public long getCompletedSize() { return completedSize; } public void setCompletedSize(long completedSize) { this.completedSize = completedSize; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getArgs0() { return args0; } public void setArgs0(String args0) { this.args0 = args0; } public String getArgs1() { return args1; } public void setArgs1(String args1) { this.args1 = args1; } public String getArgs2() { return args2; } public void setArgs2(String args2) { this.args2 = args2; } public String getArgs3() { return args3; } public void setArgs3(String args3) { this.args3 = args3; } public String getWhere0() { return where0; } public void setWhere0(String where0) { this.where0 = where0; } public String getWhere1() { return where1; } public void setWhere1(String where1) { this.where1 = where1; } public List<DownloadBean> getDownloadList() { return downloadList; } public void setDownloadList(List<DownloadBean> downloadList) { this.downloadList = downloadList; } @Override public String toString() { String showStatus = ""; switch (status) { case DOWNLOADING: showStatus = "下载中"; break; case PAUSE: showStatus = "暂停"; break; case QUEUE: showStatus = "等待中"; break; case FINISH: showStatus = "完成"; break; case ERROR: showStatus = "错误"; } return "DownloadBundle{" + "id = " + id + ", path =" + path + ", key=" + key + '\'' + ", totalSize=" + totalSize + ", completedSize=" + completedSize + ", status=" + showStatus + ", type=" + type + '}'; } public void init(DownloadBundle oldBundle) { this.setId(oldBundle.id); this.setPath(oldBundle.path); this.setDownloadList(oldBundle.downloadList); this.setTotalSize(oldBundle.totalSize); this.setCompletedSize(oldBundle.completedSize); } }
25.026667
78
0.666889
49ff4d2b86c0d78b76b24a6704f8cf6579e34399
289
/* * 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 mx.majori.vo; /** * * @author Ricardo Hiram */ public class ClienteVO { }
19.266667
80
0.66436
fa5ffa3d38a9739f132a44865ee695242bf9308d
2,799
package com.goldze.mvvmhabit.ui.base.viewmodel; import android.app.Application; import android.databinding.ObservableField; import android.databinding.ObservableInt; import android.support.annotation.NonNull; import android.view.View; import me.goldze.mvvmhabit.base.BaseModel; import me.goldze.mvvmhabit.base.BaseViewModel; import me.goldze.mvvmhabit.binding.command.BindingAction; import me.goldze.mvvmhabit.binding.command.BindingCommand; /** * Create Author:goldze * Create Date:2019/01/03 * Description: 对应include标题的ToolbarViewModel * Toolbar的封装方式有很多种,具体封装需根据项目实际业务和习惯来编写 * 所有例子仅做参考,业务多种多样,可能我这里写的例子和你的需求不同,理解如何使用才最重要。 */ public class ToolbarViewModel<M extends BaseModel> extends BaseViewModel<M> { //标题文字 public ObservableField<String> titleText = new ObservableField<>(""); //右边文字 public ObservableField<String> rightText = new ObservableField<>("完成"); //右边文字的观察者 public ObservableInt rightTextVisibleObservable = new ObservableInt(View.GONE); //右边图标的观察者 public ObservableInt rightIconVisibleObservable = new ObservableInt(View.GONE); //兼容databinding,去泛型化 public ToolbarViewModel toolbarViewModel; public ToolbarViewModel(@NonNull Application application) { this(application, null); } public ToolbarViewModel(@NonNull Application application, M model) { super(application, model); toolbarViewModel = this; } /** * 设置标题 * * @param text 标题文字 */ public void setTitleText(String text) { titleText.set(text); } /** * 设置右边文字 * * @param text 右边文字 */ public void setRightText(String text) { rightText.set(text); } /** * 设置右边文字的显示和隐藏 * * @param visibility */ public void setRightTextVisible(int visibility) { rightTextVisibleObservable.set(visibility); } /** * 设置右边图标的显示和隐藏 * * @param visibility */ public void setRightIconVisible(int visibility) { rightIconVisibleObservable.set(visibility); } /** * 返回按钮的点击事件 */ public final BindingCommand backOnClick = new BindingCommand(new BindingAction() { @Override public void call() { finish(); } }); public BindingCommand rightTextOnClick = new BindingCommand(new BindingAction() { @Override public void call() { rightTextOnClick(); } }); public BindingCommand rightIconOnClick = new BindingCommand(new BindingAction() { @Override public void call() { rightIconOnClick(); } }); /** * 右边文字的点击事件,子类可重写 */ protected void rightTextOnClick() { } /** * 右边图标的点击事件,子类可重写 */ protected void rightIconOnClick() { } }
24.552632
86
0.658092
ccd03892ba15327bef1354c44745abb97672946b
4,013
package org.vatplanner.dataformats.vatsimpublic.entities.status; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; /** * A {@link FacilityType} describes the area of responsibility of an ATC * station. * <p> * In general, all controlling facilities provide full replacement service if a * lower, more specific facility is offline. * </p> * <p> * Note: Below descriptions of individual stations may be inaccurate and do of * course not apply to real-world aviation. * </p> */ public enum FacilityType { // TODO: check status file IDs against more data /** * Observers only watch and do not control or provide information. */ OBSERVER(0, "OBS"), /** * Flight service stations (FSS, FIS, "Info") do not control traffic but only * provide information to pilots. */ FSS(1, "FSS"), /** * Delivery stations provide only clearances on ground. */ DELIVERY(2, "DEL"), /** * Ground stations control all traffic on ground except for tower-controlled * area (for example ground is not allowed to control taxi routes crossing * runways). Ground service includes Delivery if a dedicated station is offline * (top-bottom service). */ GROUND(3, "GND"), /** * Tower stations control the immediate lower airspace around an airport as well * as runways on ground. Tower service includes Ground and Delivery if dedicated * stations are offline (top-bottom service). */ TOWER(4, "TWR"), /** * Approach and departure stations control IFR traffic which is in- or outbound * a specific airport and neither in Tower nor Center control area. * Approach/Departure service includes Tower, Ground and Delivery services if * dedicated stations are offline (top-bottom service). */ APPROACH_DEPARTURE(5, "APP"), /** * Center stations control IFR traffic outside Approach/Departure stations. * Center service includes all other station services if dedicated stations are * offline (top-bottom service). */ CENTER(6, "CTR"); private final int statusFileId; private final String shortName; private static final Map<Integer, FacilityType> typeById = new TreeMap<>(); private static final Map<String, FacilityType> typeByShortName = new HashMap<>(); static { for (FacilityType facilityType : values()) { typeById.put(facilityType.statusFileId, facilityType); typeByShortName.put(facilityType.shortName, facilityType); } } private FacilityType(int statusFileId, String shortName) { this.statusFileId = statusFileId; this.shortName = shortName; } /** * Resolves the given ID as used on legacy status files (data.txt) to the * corresponding {@link FacilityType} enum. * * @param statusFileId ID as used on data.txt status file * @return resolved enumeration object * @throws IllegalArgumentException if the ID is unknown and could not be * resolved */ public static FacilityType resolveStatusFileId(int statusFileId) throws IllegalArgumentException { FacilityType resolved = typeById.get(statusFileId); if (resolved != null) { return resolved; } throw new IllegalArgumentException(String.format("unknown facility type ID %d", statusFileId)); } /** * Resolves the given short name to the corresponding {@link FacilityType} enum. * * @param shortName short name of facility to resolve * @return resolved enumeration object or null if unknown */ public static FacilityType resolveShortName(String shortName) { return typeByShortName.get(shortName); } /** * Returns the ID used to refer to this {@link FacilityType} in legacy data * files. * * @return ID used in legacy data files */ public int getLegacyId() { return statusFileId; } }
32.104
103
0.670321
14b522aee7ae7de4b9b5b3e4af3295b2101d25fe
10,620
package synth.osc; import net.beadsproject.beads.core.AudioContext; import net.beadsproject.beads.core.UGen; import net.beadsproject.beads.data.Pitch; import synth.modulation.*; import synth.container.Device; import javax.sound.midi.*; public abstract class Oscillator extends UGen implements Device { protected String type; /** The frequency the oscillation is happening at */ protected Modulatable frequency; /** Oscillator output gain */ protected Modulatable gain; /** Phase UGen */ //protected UGen phase; /** MIDI note value */ protected int midiNote; /** The AudioContext the oscillator is working in */ protected AudioContext ac; // TODO create function to add together Envelope and LFO to create one coherent modulatable parameter // TODO this can probably done by modifying the Modulatable interface / Modulator to wrap around Static (for static knob parameters), Envelopes and LFOs /** Volume Envelope */ protected Envelope gainEnvelope; /** Frequency Envelope */ protected Envelope frequencyEnvelope; /** Gain LFO */ protected LFO gainLFO; /** Frequency LFO */ protected LFO frequencyLFO; /** Gain Static */ protected Static gainStatic; /** Frequency Static */ protected Static frequencyStatic; /** Whether Oscillator is velocity sensitive or not */ protected boolean isVelocitySensitive; /** * Factor by which the linear velocity falloff gets multiplied * By default this is 1 meaning: velocity / 127 * output.gain(); */ protected float velocityFactor; private String name; public String getName(){ return this.name; } public void setName(String name){ this.name = name; } /** * Creates an empty oscillator frame * @param ac AudioContext */ public Oscillator(AudioContext ac){ this(ac, 0f); } /** * Creates a new Oscillator frame * @param ac AudioContext * @param frequency Oscillator frequency */ public Oscillator(AudioContext ac, float frequency){ this(ac, new Static(ac, frequency)); } public Oscillator(AudioContext ac, Modulatable frequency){ super(ac, 2, 2); this.ac = ac; this.gainEnvelope = new Envelope(this.ac, 5, 0, 1f, 20); this.frequencyEnvelope = new Envelope(this.ac, 0, 0, 1f, 0); this.frequencyLFO = new LFO(this.ac, LFO.Type.SINE, 0f, 1f); this.gainLFO = new LFO(this.ac, LFO.Type.SINE, 0f, 1f); this.gainStatic = new Static(this.ac, 1f); this.frequencyStatic = new Static(this.ac, frequency.getValue()); this.frequency = new Sum(ac, frequencyStatic, frequencyEnvelope, frequencyLFO); this.gain = new Sum(ac, gainStatic, gainEnvelope, gainLFO); velocityFactor = 1; isVelocitySensitive = false; midiNote = -1; this.outputInitializationRegime = OutputInitializationRegime.ZERO; this.outputPauseRegime = OutputPauseRegime.ZERO; this.setType(); } public String getType(){ return this.type; } public abstract void setType(); /** * Returns the current frequency of oscillation * @return frequency UGen */ public Modulatable getFrequency(){ return this.frequency; } /** * Returns the current oscillator output gain * @return gain UGen */ public Modulatable getGain(){ return this.gain; } /** * Returns the current phase offset * @return phase UGen */ /*public UGen getPhase(){ return this.phase; }*/ /** * Sets the frequency of oscillation * NOTE This REPLACES the frequency UGen with a new one * @param frequency static oscillation frequency * @return this oscillator instance */ public Oscillator setFrequency(LFO frequency){ if(frequency != null){ this.frequencyLFO = frequency; ((Sum)this.frequency).setLFO(frequency); } return this; } /** * Sets the frequency of oscillation * NOTE This REPLACES the frequency UGen with a new one * @param frequency static oscillation frequency * @return this oscillator instance */ public Oscillator setFrequency(Envelope frequency){ if(frequency != null){ this.frequencyEnvelope = frequency; ((Sum)this.frequency).setEnvelope(frequency); } return this; } /** * Sets the frequency of oscillation * NOTE This only SETS the value of the current UGen (which might be a modulator) * to the new static float value. To replace the UGen, rather use {@see Oscillator.setFrequency(UGen frequency)} * @param frequency static oscillation frequency * @return this oscillator instance */ public Oscillator setFrequency(float frequency){ this.frequencyStatic = new Static(ac, frequency); this.frequency.setValue(frequency); return this; } public Oscillator setFrequency(Sum frequency){ if(frequency != null){ this.frequency = frequency; this.frequencyStatic = frequency.getStatic(); this.frequencyEnvelope = frequency.getEnvelope(); this.frequencyLFO = frequency.getLFO(); } return this; } public Oscillator setFrequency(ModulationOscillator frequencyOsc){ if(frequencyOsc != null){ this.frequency = frequencyOsc; this.frequencyStatic = null; this.frequencyEnvelope = null; this.frequencyLFO = null; } return this; } /** * Sets the gain of the oscillator * NOTE This REPLACES the gain UGen with a new one * @param gain gain UGen * @return this oscillator instance */ public Oscillator setGain(LFO gain){ if(gain != null){ this.gainLFO = gain; ((Sum)this.gain).setLFO(gain); } return this; } /** * Sets the gain of the oscillator * NOTE This REPLACES the gain UGen with a new one * @param gain gain UGen * @return this oscillator instance */ public Oscillator setGain(Envelope gain){ if(gain != null){ this.gainEnvelope = gain; ((Sum)this.gain).setEnvelope(gain); } return this; } /** * Sets the gain of the oscillator * NOTE This only SETS the value of the current UGen (which might be a modulator) * to the new static float value. To replace the UGen, rather use {@see Oscillator.setGain(UGen gain)} * @param gain static gain value as float * @return this oscillator instance */ public Oscillator setGain(float gain){ this.gainStatic = new Static(ac, gain); this.gain.setValue(gain); return this; } public Oscillator setGain(Sum gain){ if(gain != null){ this.gain = gain; this.gainStatic = gain.getStatic(); this.gainEnvelope = gain.getEnvelope(); this.gainLFO = gain.getLFO(); } return this; } public Oscillator setGain(ModulationOscillator gainOsc){ if(gainOsc != null){ this.gain = gainOsc; this.gainStatic = null; this.gainEnvelope = null; this.gainLFO = null; } return this; } @Override public void calculateBuffer(){ } /** * Sets the currently playing MIDI note * @param midiNote integer value of the MIDI note */ public void setMidiNote(int midiNote) { this.midiNote = midiNote; } /** * Gets the current playing MIDI note * @return the currently playing MIDI note */ public int getMidiNote() { return midiNote; } /* Velocity functions */ /** * Enable or disable oscillator velocity sensitivity * meaning whether the key velocity by a MIDI event should * affect the volume of the oscillator by a constant factor (velocityFactor) * @param isSensitive boolean whether to enable or disable velocity sensitivity */ public void setVelocitySensitivity(boolean isSensitive){ this.isVelocitySensitive = isSensitive; } /** * Whether the oscillator is velocity sensitive * @return true, if sensitive, false otherwise */ public boolean isVelocitySensitive() { return isVelocitySensitive; } /** * Sets the velocityFactor which is applied to the volume * Note: The new factor gets applied as soon as a new MIDI note on command is received * * Note: Clipping is to be prevented by the user, either by using a limiter * (RangeLimiter Beads UGen, when implementing a chain) otherwise, for factors greateer * than 1, clipping may occur, when velocity/127 * velocityFactor * gain is greater than 1 * @param velocityFactor constant factor to be applied onto the volume */ public void setVelocityFactor(float velocityFactor) { this.velocityFactor = velocityFactor; } /** * Gets the current velocity factor * @return constant velocity factor as float */ public float getVelocityFactor() { return velocityFactor; } public void noteOff(){ this.gain.noteOff(); this.frequency.noteOff(); } public void noteOn(){ this.gain.noteOn(); this.frequency.noteOn(); } public void send(ShortMessage message, long timeStamp){ if(message.getCommand() == ShortMessage.NOTE_OFF){ this.noteOff(); } else { // call for the static function translating the MIDI key to frequency range this.setFrequency(Pitch.mtof(message.getData1())); this.setMidiNote(message.getData1()); // if oscillator is velocity sensitive, adjust volume if(this.isVelocitySensitive){ this.setGain(message.getData2() / 127f * this.gain.getValue()); } this.noteOn(); } } public Envelope gainEnvelope() { return gainEnvelope; } public Envelope frequencyEnvelope() { return frequencyEnvelope; } public LFO gainLFO() { return gainLFO; } public LFO frequencyLFO() { return frequencyLFO; } public Static gainStatic() { return gainStatic; } public Static frequencyStatic() { return frequencyStatic; } }
28.702703
156
0.62354
400d633b9db1029b9178012bf1c45c7114d664bc
2,012
package com.mapbox.services.android.navigation.ui.v5.map; import android.content.Context; import android.content.res.Resources; import com.mapbox.mapboxsdk.maps.MapView; import com.mapbox.mapboxsdk.maps.MapboxMap; import com.mapbox.services.android.navigation.ui.v5.R; class MapPaddingAdjustor { private static final int[] ZERO_MAP_PADDING = {0, 0, 0, 0}; private static final int BOTTOMSHEET_PADDING_MULTIPLIER = 4; private static final int WAYNAME_PADDING_MULTIPLIER = 2; private final int defaultTopPadding; private final int waynameTopPadding; private MapboxMap mapboxMap; MapPaddingAdjustor(MapView mapView, MapboxMap mapboxMap) { this.mapboxMap = mapboxMap; defaultTopPadding = calculateTopPaddingDefault(mapView); waynameTopPadding = calculateTopPaddingWithWayname(mapView.getContext(), defaultTopPadding); } void updateTopPaddingWithWayname() { updateTopPadding(waynameTopPadding); } void updateTopPaddingWithDefault() { updateTopPadding(defaultTopPadding); } void removeAllPadding() { updatePadding(ZERO_MAP_PADDING); } private int calculateTopPaddingDefault(MapView mapView) { Context context = mapView.getContext(); Resources resources = context.getResources(); int mapViewHeight = mapView.getHeight(); int bottomSheetHeight = (int) resources.getDimension(R.dimen.summary_bottomsheet_height); return mapViewHeight - (bottomSheetHeight * BOTTOMSHEET_PADDING_MULTIPLIER); } private int calculateTopPaddingWithWayname(Context context, int defaultTopPadding) { Resources resources = context.getResources(); int waynameLayoutHeight = (int) resources.getDimension(R.dimen.wayname_view_height); return defaultTopPadding - (waynameLayoutHeight * WAYNAME_PADDING_MULTIPLIER); } private void updatePadding(int[] padding) { mapboxMap.setPadding(padding[0], padding[1], padding[2], padding[3]); } private void updateTopPadding(int topPadding) { mapboxMap.setPadding(0, topPadding, 0, 0); } }
33.533333
96
0.77336
a4f2dc42c067b2d8c7148d2947d65b3c1378fee4
2,958
package com.interview.analyse; import java.util.*; public class ConnectionPoolDesign { static class ObjectsPool { // Type, instanceName, Instance Map<String, Map<String, Object>> lookup; static ObjectsPool instance = null; ObjectsPool getInstance() { if (instance == null) { return new ObjectsPool(); } } ObjectsPool() { lookup = new HashMap<>(); } Map<String, Map<String, Object>> getLookup() { return lookup; } } class ObjectPool { public ObjectPool get() { for (String key : lookup.keySet()) { // match type and instance name and then remove count from looup Map<String, Object> objectsPool = lookup.get(key); for (String childkey : objectsPool.keySet()) { if (type.equals(childkey)) { } } } return null; } public boolean release() { try { // match type and instance name and then add count into lookup for (String key : lookup.keySet()) { // match type and instance name and then remove count from looup } } catch (Exception e) { } return false; } ObjectPool(String type, int number) { ObjectsPool ObjectsPoolInstance = ObjectsPool.getInstance(); Map<String, Map<String, Object>> lookup = ObjectsPoolInstance.getLookup(); this.type = type; this.instanceName = type + number; //Factory class to create instance of type and total count it will return map Map<String, Object> objects = //create from fatcory witll return map; lookup.putIfObsent(type, new HashMap<this.instanceName , objects>()); Map<String, ObjectPool> objectPool = lookup.get(type); lookup.get(type).put(type, objects); } String type; String instanceName; } class instaceFactory { createInstance(String type) { switch() { case: } } } class Student extends ObjectPool { Student(String type) { super(type); } Object get() { return null; } release () { } } List<ObjectPool> createObjectType(String type) { return null; } public static void main(String[] args) { // TODO Auto-generated method stub } }
25.947368
89
0.463827
8b7f8a7cd97e0a3dbdec315c8eb8e6cc23377ede
3,317
/* * Copyright © ${project.inceptionYear} ismezy ([email protected]) * * 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.zy.mylib.webmvc.base; import com.zy.mylib.base.exception.BusException; import com.zy.mylib.base.i18n.I18n; import com.zy.mylib.base.i18n.LocalMessage; import com.zy.mylib.webmvc.model.RestMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.validation.BindException; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.WebRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; /** * @author ASUS */ public class BaseRest extends I18n { protected Logger logger = LoggerFactory.getLogger(BaseRest.class); @Autowired(required = false) private LocalMessage message; @Value("${mylib.exception.defaultMessage:请求失败}") private String defaultMessage; @ExceptionHandler(Exception.class) @ResponseBody public RestMessage handleUncaughtException(Exception ex, WebRequest request, HttpServletResponse response) throws Exception { RestMessage result = new RestMessage("501", ex.getMessage()); response.setStatus(500); if (ex instanceof BusException) { logger.warn(ex.getMessage()); BusException bex = (BusException) ex; response.setStatus(bex.getHttpStatus()); result.setCode(bex.getCode()); } else if (ex instanceof MethodArgumentNotValidException) { MethodArgumentNotValidException vex = (MethodArgumentNotValidException) ex; List<ObjectError> errors = vex.getBindingResult().getAllErrors(); String message = ""; for (ObjectError err : errors) { message += err.getDefaultMessage() + "!"; } logger.warn(message); result.setMessage(message); } else if (ex instanceof BindException) { BindException bex = (BindException) ex; List<ObjectError> errors = bex.getBindingResult().getAllErrors(); String message = "验证错误,共有" + errors.size() + "个错误:<br/>\n"; for (ObjectError err : errors) { message += err.getDefaultMessage() + "<br/>\n"; } logger.warn(message); result.setMessage(message); } else { logger.error(ex.getMessage(), ex); result.setMessage(defaultMessage); } return result; } }
39.488095
129
0.694001
b0c4c2ba45c3890a15035063b804f14ca7ead665
1,488
/* * Copyright © 2015 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.cdap.explore.service.hive; import io.cdap.cdap.proto.ColumnDesc; import io.cdap.cdap.proto.QueryStatus; import java.util.List; /** * OperationInfo representing an inactive operation. */ final class InactiveOperationInfo extends OperationInfo { private final List<ColumnDesc> schema; private final QueryStatus status; InactiveOperationInfo(OperationInfo operationInfo, List<ColumnDesc> schema, QueryStatus status) { super(operationInfo.getSessionHandle(), operationInfo.getOperationHandle(), operationInfo.getSessionConf(), operationInfo.getStatement(), operationInfo.getTimestamp(), operationInfo.getHiveDatabase(), operationInfo.isReadOnly()); this.schema = schema; this.status = status; } public List<ColumnDesc> getSchema() { return schema; } @Override public QueryStatus getStatus() { return status; } }
31
101
0.744624
34dc24515578b67b4d7d9c28bf7d9923cd70d4ed
5,592
/* * Copyright 2014 Igor Maznitsa. * * 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.igormaznitsa.jhexed.swing.editor.ui.dialogs; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; public class CellCommentDialog extends AbstractDialog { private static final long serialVersionUID = 2114970595029076215L; private String result = null; public CellCommentDialog(final java.awt.Frame parent, final String title, final String text) { super(parent, true); initComponents(); if (text == null) { this.textFieldText.setText(""); } else { this.textFieldText.setText(text); } this.setTitle(title); this.setLocationRelativeTo(parent); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonCancel = new javax.swing.JButton(); buttonOk = new javax.swing.JButton(); textFieldText = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); buttonCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/igormaznitsa/jhexed/swing/editor/icons/cross.png"))); // NOI18N buttonCancel.setText("Cancel"); buttonCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonCancelActionPerformed(evt); } }); buttonOk.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/igormaznitsa/jhexed/swing/editor/icons/tick.png"))); // NOI18N buttonOk.setText("OK"); buttonOk.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { buttonOkActionPerformed(evt); } }); textFieldText.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { textFieldTextKeyPressed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 184, Short.MAX_VALUE) .addComponent(buttonOk) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(buttonCancel)) .addComponent(textFieldText)) .addContainerGap()) ); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonCancel, buttonOk}); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(textFieldText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(buttonCancel) .addComponent(buttonOk)) .addContainerGap()) ); layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {buttonCancel, buttonOk}); pack(); }// </editor-fold>//GEN-END:initComponents private void buttonOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOkActionPerformed this.result = this.textFieldText.getText(); setVisible(false); }//GEN-LAST:event_buttonOkActionPerformed private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed this.result = null; setVisible(false); }//GEN-LAST:event_buttonCancelActionPerformed private void textFieldTextKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textFieldTextKeyPressed if(evt.getKeyCode() == KeyEvent.VK_ESCAPE){ this.buttonCancel.doClick(); } if (evt.getKeyCode() == KeyEvent.VK_ENTER){ this.buttonOk.doClick(); } }//GEN-LAST:event_textFieldTextKeyPressed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton buttonCancel; private javax.swing.JButton buttonOk; private javax.swing.JTextField textFieldText; // End of variables declaration//GEN-END:variables public String getResult() { return this.result; } @Override public void processEscape(ActionEvent e) { buttonCancelActionPerformed(e); } }
37.530201
154
0.728362
da52f849ce5f0b08630022abdf505454e8b9aedc
3,723
package pl.grzegorz2047.databaseapi; import java.sql.*; /** * Created by grzegorz2047 on 23.04.2016 */ public class MoneyAPI { private DatabaseAPI sql; private String moneyTable; private MoneyAPI() { } public MoneyAPI(String host, int port, String db, String user, String password) { sql = new DatabaseAPI(host, port, db, user, password); } public void insertPlayer(String player) { Connection c = null; Statement st = null; try { String query = "INSERT IGNORE INTO " + getMoneyTable() + " (userid, money, id) " + " VALUES " + " ((SELECT userid FROM Players WHERE Players.username='" + player + "'), 0, 0)"; c = sql.getConnection(); st = c.createStatement(); st.execute(query); st.close(); c.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (c != null) { c.close(); } } catch (SQLException ex) { ex.printStackTrace(); } try { if (st != null) { st.close(); } } catch (SQLException ex) { ex.printStackTrace(); } } } public int getPlayer(String player) { String query = "SELECT * FROM " + getMoneyTable() + " WHERE userid=(SELECT userid FROM Players WHERE Players.username='" + player + "') LIMIT 1"; Connection c = null; Statement st = null; try { c = sql.getConnection(); st = c.createStatement(); ResultSet result = st.executeQuery(query); while (result.next()) { return result.getInt("money"); } st.close(); c.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (c != null) { c.close(); } } catch (SQLException ex) { ex.printStackTrace(); } try { if (st != null) { st.close(); } } catch (SQLException ex) { ex.printStackTrace(); } } return -1; } public void changePlayerMoney(String player, int money) { Connection c = null; Statement st = null; try { //UPDATE TheWallsMoney SET money=money + 5 WHERE userid=(SELECT userid FROM Player WHERE Player.username='grzegorz2047') String query = "UPDATE " + getMoneyTable() + " SET money=money+'" + money + "' WHERE userid=" + "(SELECT userid FROM Players WHERE Players.username='" + player + "')"; c = sql.getConnection(); st = c.createStatement(); st.executeUpdate(query); st.close(); c.close(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (c != null) { c.close(); } } catch (SQLException ex) { ex.printStackTrace(); } try { if (st != null) { st.close(); } } catch (SQLException ex) { ex.printStackTrace(); } } } public String getMoneyTable() { return moneyTable; } public void setMoneyTable(String moneyTable) { this.moneyTable = moneyTable; } }
30.516393
220
0.452055
6d10751acd3179124a4af83f7e22760415a1b601
3,572
package course.examples.maps.earthquakemap; import android.app.Activity; import android.os.Bundle; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class MapsEarthquakeMapActivity extends Activity implements RetainedFragment.OnFragmentInteractionListener, OnMapReadyCallback { // Coordinates used for centering the Map private static final double CAMERA_LNG = 100.0; private static final double CAMERA_LAT = 28.0; // The Map Object private GoogleMap mMap; // URL for getting the earthquake // replace with your own user name @SuppressWarnings("unused") public static final String TAG = "MapsEarthquakeMapActivity"; private RetainedFragment mRetainedFragment; private boolean mMapReady; private boolean mDataReady; // Set up UI and get earthquake data @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); if (null != savedInstanceState) { mRetainedFragment = (RetainedFragment) getFragmentManager() .findFragmentByTag(RetainedFragment.TAG); onDownloadfinished(); } else { mRetainedFragment = new RetainedFragment(); getFragmentManager().beginTransaction() .add(mRetainedFragment, RetainedFragment.TAG) .commit(); mRetainedFragment.onButtonPressed(); } // The GoogleMap instance underlying the GoogleMapFragment defined in main.xml MapFragment map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)); map.getMapAsync(this); } // Called when data is downloaded public void onDownloadfinished() { mDataReady = true; if (mMapReady) { placeMarkers(); mDataReady = false; } } private void placeMarkers() { // Add a marker for every earthquake for (EarthQuakeRec rec : mRetainedFragment.getData()) { // Add a new marker for this earthquake mMap.addMarker(new MarkerOptions() // Set the Marker's position .position(new LatLng(rec.getLat(), rec.getLng())) // Set the title of the Marker's information window .title(String.valueOf(rec.getMagnitude())) // Set the color for the Marker .icon(BitmapDescriptorFactory .defaultMarker(getMarkerColor(rec .getMagnitude())))); } } // Called when Map is ready @Override public void onMapReady(GoogleMap googleMap) { mMapReady = true; mMap = googleMap; mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(CAMERA_LAT, CAMERA_LNG))); if (mDataReady) { placeMarkers(); mMapReady = false; } } // Assign marker color private float getMarkerColor(double magnitude) { if (magnitude < 6.0) { magnitude = 6.0; } else if (magnitude > 9.0) { magnitude = 9.0; } return (float) (120 * (magnitude - 6)); } }
31.333333
135
0.630739
e3eda956eb951936517e5c7e676f46aa02628c06
1,855
package org.ovirt.engine.core.bll; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.action.ChangeDiskCommandParameters; import org.ovirt.engine.core.common.businessentities.VM; import org.ovirt.engine.core.common.vdscommands.ChangeDiskVDSCommandParameters; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.compat.StringHelper; import org.ovirt.engine.core.compat.backendcompat.Path; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.CustomLogField; import org.ovirt.engine.core.dal.dbbroker.auditloghandling.CustomLogFields; @CustomLogFields({ @CustomLogField("DiskName") }) public class ChangeFloppyCommand<T extends ChangeDiskCommandParameters> extends VmOperationCommandBase<T> { private String mCdImagePath; public ChangeFloppyCommand(T parameters) { super(parameters); mCdImagePath = ImagesHandler.cdPathWindowsToLinux(parameters.getCdImagePath(), getVm().getstorage_pool_id()); } public String getDiskName() { return Path.GetFileName(mCdImagePath); } @Override protected void Perform() { if (VM.isStatusUpOrPaused(getVm().getstatus())) { setActionReturnValue(Backend .getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.ChangeFloppy, new ChangeDiskVDSCommandParameters(getVdsId(), getVm().getvm_guid(), mCdImagePath)) .getReturnValue()); setSucceeded(true); } } @Override public AuditLogType getAuditLogTypeValue() { return getSucceeded() ? StringHelper.EqOp(mCdImagePath, "") ? AuditLogType.USER_EJECT_VM_FLOPPY : AuditLogType.USER_CHANGE_FLOPPY_VM : AuditLogType.USER_FAILED_CHANGE_FLOPPY_VM; } }
41.222222
117
0.720755
1ab8a388b08eb6047b9a9918558540fa46f67438
1,301
package br.com.zup.bootcamp.domain.entity; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.time.LocalDateTime; // Intrinsic charge = 2 @Entity public class Question { @Id @GeneratedValue(generator = "UUID") @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") private String id; @NotBlank @Column(nullable = false) private String title; @NotNull @Column(nullable = false) private LocalDateTime creationDate; @NotNull @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(nullable = false) private Product product; @NotNull @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(nullable = false) private User user; @Deprecated public Question() {} public Question(@NotBlank String title, @NotNull Product product, @NotNull User user) { this.title = title; this.creationDate = LocalDateTime.now(); this.product = product; this.user = user; } public String getId() { return this.id; } public String getTitle() { return title; } public Product getProduct() { return product; } }
22.050847
91
0.668716
faf20e82e7c030cf509f161e1160e8b72dd6dca5
1,068
package cz.cuni.mff.kocur.considerations; import cz.cuni.mff.kocur.base.Location; import cz.cuni.mff.kocur.decisions.DecisionContext; import cz.cuni.mff.kocur.world.GridBase; /** * Considers distance to target. * @author kocur * */ public class ConsiderDistanceToTarget extends Consideration{ public ConsiderDistanceToTarget() { super(); readableName = "ConsiderDistanceToTarget"; } @Override public double score(DecisionContext context) { Location s = context.getSource(); Location target = context.getTarget().getLocation(); if (target == null) { target = context.getTarget().getEntity(); if (target == null) { //logger.warn("Target is not location nor entity."); return 0; } } double minRange = getDoubleParameter(PARAM_RANGE_MIN); double maxRange = getDoubleParameter(PARAM_RANGE_MAX); double distance = GridBase.distance(s, target); double normalized = normalize(distance, minRange, maxRange); // logger.info("Normalized distance to target: " + normalized); return normalized; } }
22.723404
65
0.712547
0397323f922b4a5c19354867f21ecadc973e57af
456
package com.faforever.client.user; import com.faforever.client.task.CompletableTask; import java.util.concurrent.CompletableFuture; public interface UserService { CompletableFuture<Void> login(String username, String password, boolean autoLogin); String getUsername(); String getPassword(); Integer getUserId(); void cancelLogin(); void logOut(); CompletableTask<Void> changePassword(String currentPassword, String newPassword); }
19
85
0.778509
0d8b19caf26d346798641926f51321818f5898c6
842
package com.javafortesters.chap015Stringsrevisitedclasses.examples; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class StringReplaceTest { @Test public void replaceMethods() { String hello = "Hello fella fella fella"; assertThat(hello.replace("fella", "World") , is("Hello World World World")); assertThat(hello.replaceFirst("fella", "World") , is("Hello World fella fella")); assertThat(hello.replaceAll("fella", "World") , is("Hello World World World")); } @Test public void replaceDigitMethods() { String digits = "1,2,3"; assertThat(digits.replaceFirst("[0-9]", "digit") , is("digit,2,3")); assertThat(digits.replaceAll("[0-9]", "World") , is("World,World,World")); } }
32.384615
89
0.667458
66911bdfdf30cbdcef82a3e25971a8ace23a95a9
174
package org.apache.sparkmeta.join.helper; import org.apache.sparkmeta.join.vo.MetaData; public class MetaDataParser { public MetaData getMetaData() { return null; } }
15.818182
45
0.764368
a4d7286f7b3bbd5f5f7d3147fb3bfafc6b3a2fe2
809
package main.model.dto.project; import lombok.Data; import lombok.EqualsAndHashCode; import main.annotations.DataBaseInsert; import main.annotations.DataBaseName; import main.annotations.DataBaseSearchable; import main.model.dto.BaseDto; import java.util.List; @Data @EqualsAndHashCode(callSuper = true) public class SuiteDashboardDto extends BaseDto { @DataBaseName(name = "request_name") @DataBaseInsert private String name; @DataBaseName(name = "request_id") @DataBaseInsert @DataBaseSearchable private Integer id; @DataBaseName(name = "request_project_id") @DataBaseInsert @DataBaseSearchable private Integer project_id; @DataBaseName(name = "request_detailed") @DataBaseInsert private Integer detailed; private List<TestSuiteDto> suites; }
25.28125
48
0.76267
3d41d78bae5c4497a5f59ac5dab82d1806bfe6c4
3,182
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.quicksearchbox.util; import android.util.Log; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; /** * Executor that uses a single thread and an unbounded work queue. */ public class SingleThreadNamedTaskExecutor implements NamedTaskExecutor { private static final boolean DBG = false; private static final String TAG = "QSB.SingleThreadNamedTaskExecutor"; private final LinkedBlockingQueue<NamedTask> mQueue; private final Thread mWorker; private volatile boolean mClosed = false; public SingleThreadNamedTaskExecutor(ThreadFactory threadFactory) { mQueue = new LinkedBlockingQueue<NamedTask>(); mWorker = threadFactory.newThread(new Worker()); mWorker.start(); } public void cancelPendingTasks() { if (DBG) Log.d(TAG, "Cancelling " + mQueue.size() + " tasks: " + mWorker.getName()); if (mClosed) { throw new IllegalStateException("cancelPendingTasks() after close()"); } mQueue.clear(); } public void close() { mClosed = true; mWorker.interrupt(); mQueue.clear(); } public void execute(NamedTask task) { if (mClosed) { throw new IllegalStateException("execute() after close()"); } mQueue.add(task); } private class Worker implements Runnable { public void run() { try { loop(); } finally { if (!mClosed) Log.w(TAG, "Worker exited before close"); } } private void loop() { Thread currentThread = Thread.currentThread(); String threadName = currentThread.getName(); while (!mClosed) { NamedTask task; try { task = mQueue.take(); } catch (InterruptedException ex) { continue; } currentThread.setName(threadName + " " + task.getName()); try { task.run(); } catch (RuntimeException ex) { Log.e(TAG, "Task " + task.getName() + " failed", ex); } } } } public static Factory<NamedTaskExecutor> factory(final ThreadFactory threadFactory) { return new Factory<NamedTaskExecutor>() { public NamedTaskExecutor create() { return new SingleThreadNamedTaskExecutor(threadFactory); } }; } }
31.50495
92
0.604023
53a85244fad2b246c70607971f62fa50c8e19460
2,043
package socketsconconexion.stream; import java.net.*; import java.io.*; /** * Este ejemplo ilustra la sintaxis b�sica del socket * en modo stream. * @author M. L. Liu */ public class SolicitanteConexion { // Una aplicaci�n que solicita una conexi�n y manda un mensaje utilizando // un socket en modo stream // Se esperan dos argumentos de l�nea de mandato, en orden: // <nombre de la m�quina del aceptador de la conexi�n> // <n�mero de puerto del aceptador de la conexi�n> public static void main(String[] args) { /*if (args.length != 2) System.out.println ("Este programa requiere dos argumentos de l�nea de mandato"); else {*/ try { args = new String[2]; args[0] = "localhost"; args[1] = "5000"; //optiene la direccion ip InetAddress maquinaAceptadora = InetAddress.getByName(args[0]); int puertoAceptador = Integer.parseInt(args[1]); // instancia un socket de datos Socket miSocket = new Socket(maquinaAceptadora, puertoAceptador); /**/ System.out.println("Solicitud de conexi�n concedida"); // obtiene un flujo de entrada para leer del socket de datos InputStream flujoEntrada = miSocket.getInputStream(); // crea un objeto BufferedReader para la entrada en modo car�cter BufferedReader socketInput = new BufferedReader(new InputStreamReader(flujoEntrada)); /**/ System.out.println("esperando leer"); // lee una l�nea del flujo de datos String mensaje = socketInput.readLine( ); /**/ System.out.println("Mensaje recibido:"); System.out.println("\t" + mensaje); miSocket.close( ); /**/ System.out.println("socket de datos cerrado"); } // fin de try catch (Exception ex) { ex.printStackTrace( ); } // fin de catch // } // fin de else } // fin de main } // fin de class
39.288462
77
0.596672
84438e15fe81e4d473ab350f6a160b6ba6269bff
306
package com.github.davidfantasy.mybatisplus.generatorui.strategy; import com.baomidou.mybatisplus.generator.config.ConstVal; import lombok.Data; @Data public class ServiceStrategy { /** * 自定义继承的Service类全称,带包名 */ private String superServiceClass = ConstVal.SUPER_SERVICE_CLASS; }
19.125
68
0.754902
daaccca7feb89198f6fbc5165ca4b76bde692af5
1,185
package org.otaibe.commons.quarkus.aws.extension.deployment; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.FeatureBuildItem; import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem; import org.otaibe.commons.quarkus.reflection.utils.ReflectUtils; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; class AwsExtensionProcessor { private static final String FEATURE = "aws-extension"; @BuildStep FeatureBuildItem feature() { return new FeatureBuildItem(FEATURE); } @BuildStep public void registerReflection(BuildProducer<ReflectiveClassBuildItem> resource) { resource.produce(new ReflectiveClassBuildItem(true, true, ExecutionInterceptor.class)); ReflectUtils.getAllClassesFromPackage( software.amazon.awssdk.services.s3.internal.handlers.AddContentMd5HeaderInterceptor.class.getPackage().getName(), Object.class) .forEach(aClass -> resource .produce(new ReflectiveClassBuildItem(true, true, aClass))); ; } }
37.03125
129
0.747679
2dcb0e6d209c350dcb4c8da3d2ba8a49b63c3b0f
2,687
package com.snk.door.enums; /** * 报警记录 */ public enum AlarmRecord { /** * 门磁报警 */ TYPE_1(1, "门磁报警"), /** * 匪警报警 */ TYPE_2(2, "匪警报警"), /** * 消防报警 */ TYPE_3(3, "消防报警"), /** * 非法卡刷报警 */ TYPE_4(4, "非法卡刷报警"), /** * 胁迫报警 */ TYPE_5(5, "胁迫报警"), /** * 消防报警(命令通知) */ TYPE_6(6, "消防报警(命令通知)"), /** * 烟雾报警 */ TYPE_7(7, "烟雾报警"), /** * 防盗报警 */ TYPE_8(8, "防盗报警"), /** * 黑名单报警 */ TYPE_9(9, "黑名单报警"), /** * 开门超时报警 */ TYPE_10(10, "开门超时报警"), /** * 门磁报警撤销 */ TYPE_11(0x11, "门磁报警撤销"), /** * 匪警报警撤销 */ TYPE_12(0x12, "匪警报警撤销"), /** * 消防报警撤销 */ TYPE_13(0x13, "消防报警撤销"), /** * 非法卡刷报警撤销 */ TYPE_14(0x14, "非法卡刷报警撤销"), /** * 胁迫报警撤销 */ TYPE_15(0x15, "胁迫报警撤销"), /** * 撤销烟雾报警 */ TYPE_16(0x17, "撤销烟雾报警"), /** * 关闭防盗报警 */ TYPE_17(0x18, "关闭防盗报警"), /** * 关闭黑名单报警 */ TYPE_18(0x19, "关闭黑名单报警"), /** * 关闭开门超时报警 */ TYPE_19(0x1A, "关闭开门超时报警"), /** * 门磁报警撤销(命令通知) */ TYPE_20(0x21, "门磁报警撤销(命令通知)"), /** * 匪警报警撤销(命令通知) */ TYPE_21(0x22, "匪警报警撤销(命令通知)"), /** * 消防报警撤销(命令通知) */ TYPE_22(0x23, "消防报警撤销(命令通知)"), /** * 非法卡刷报警撤销(命令通知) */ TYPE_23(0x24, "非法卡刷报警撤销(命令通知)"), /** * 胁迫报警撤销(命令通知) */ TYPE_24(0x25, "胁迫报警撤销(命令通知)"), /** * 撤销烟雾报警(命令通知) */ TYPE_25(0x27, "撤销烟雾报警(命令通知)"), /** * 关闭防盗报警(软件关闭) */ TYPE_26(0x28, "关闭防盗报警(软件关闭)"), /** * 关闭黑名单报警(软件关闭) */ TYPE_27(0x29, "关闭黑名单报警(软件关闭)"), /** * 关闭开门超时报警 */ TYPE_28(0x2A, "关闭开门超时报警"); private Integer value; private String comment; AlarmRecord(Integer value, String comment) { this.value = value; this.comment = comment; } public Integer getValue() { return this.value; } public String getComment() { return comment; } public static AlarmRecord getAlarmRecord(Short value) { for (AlarmRecord alarmRecord : AlarmRecord.values()) { if (alarmRecord.getValue().equals(Integer.valueOf(value))) { return alarmRecord; } } return null; } public static String getComment(Short value) { for (AlarmRecord alarmRecord : AlarmRecord.values()) { if (alarmRecord.getValue().equals(Integer.valueOf(value))) { return alarmRecord.getComment(); } } return null; } }
14.763736
72
0.453294
67b6fc46038626af1ad527a104143b02585ebf68
187
package com.sumygg.excelexportor; /** * 格式化方法接口 * * @author SumyGG * @since 2018-06-11 */ @FunctionalInterface public interface ColumnFormatter { String format(Object value); }
14.384615
34
0.71123
467a5f401e3b022959577f155557205a56c0fef6
17,573
package wassilni.pl.driver.ui; import android.Manifest; import android.app.ProgressDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.provider.Settings; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import android.location.LocationListener; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.appindexing.Thing; import com.google.android.gms.common.api.GoogleApiClient; 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.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import modules.ConnectivityReceiver; import modules.DirectionFinder; import modules.DirectionFinderListener; import modules.Route; import objects.MyApp; import objects.Passenger; import wassilni.pl.driver.R; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, DirectionFinderListener , ConnectivityReceiver.ConnectivityReceiverListener { String original; /* * -retrieve locations of passengers who assigned to a certain SCHEDULE for a certain DRIVER, and represent an optimized path. * -or a simulated path to help the driver to decide if he want to accept/reject the passenger base on it's location. * */ private GoogleMap mMap; private Button btnFindPath; private TextView tvPath; private List<Polyline> polylinePaths = new ArrayList<>(); private ProgressDialog progressDialog; // ******************************************************************** public DirectionFinder directionFinder; public LatLng a = new LatLng(24.688857, 46.711454); public LatLng d = new LatLng(24.751130, 46.668221); public LatLng c = new LatLng(24.770821, 46.716369); public LatLng b = new LatLng(24.725910, 46.752387); public LatLng userLocation; public LatLng destLocation; public String extractPoint; // ******************************************************************** public ArrayList<Passenger> passengers = new ArrayList<Passenger>(); public ArrayList<LatLng> pickupLocations =new ArrayList<LatLng>(); public ArrayList<LatLng> dropoffLocations =new ArrayList<LatLng>(); private LocationManager locationManager; private LocationListener listener; String flag; LatLng simDropoff; LatLng simPickup; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; //@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB) @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); original= (String) getTitle(); setContentView(R.layout.activity_maps); // 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); tvPath=(TextView)findViewById(R.id.tvPath); //get data sent from the previous Activity Intent i= getIntent(); flag=i.getStringExtra("flag"); if( flag.equals("real")) { String json = i.getStringExtra("json"); String time = i.getStringExtra("time"); //extractPoint = i.getStringExtra("destination"); //System.out.println("####@@@@@@@@#########@@@@@@@@@######@@@@@@@#########@@##### real \t"+extractPoint); //destLocation = MyApp.getLatlng(extractPoint); parseJSON(json); tvPath.setText(" مسار فترة الساعة "+time); } else //flag= simulation { String json = i.getStringExtra("json"); String time = i.getStringExtra("time"); extractPoint = i.getStringExtra("destination"); System.out.println("####@@@@@@@@#########@@@@@@@@@######@@@@@@@#########@@##### simulation \t"+extractPoint); destLocation = MyApp.getLatlng(extractPoint); simPickup=MyApp.getLatlng(i.getStringExtra("pickup")); simDropoff=MyApp.getLatlng(i.getStringExtra("dropoff")); parseJSON(json); tvPath.setText("محاكاة مسار فترة الساعة "+time); } // button to trigger searching for a path. btnFindPath = (Button) findViewById(R.id.btnFindPath); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); //configure locationListner and locationManager to get the user's current location listener = new LocationListener() { @Override public void onLocationChanged(Location location) { userLocation = new LatLng(location.getLatitude(), location.getLongitude()); Log.d("Maps","userLocation have changed \t"+userLocation.toString()); } @Override public void onStatusChanged(String s, int i, Bundle bundle) {} @Override public void onProviderEnabled(String s) {} @Override public void onProviderDisabled(String s) { // prompt the user to turn on GPS service. Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(i); } }; btnFindPath.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendRequest(); } }); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); }//finish onCreate() ******* private void sendRequest() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling //prompt the user to make Wassilni application grant location from the GPS. Toast.makeText(getApplicationContext(),"الرجاء تفعيل أذونات الموقع من الإعدادات",Toast.LENGTH_LONG).show(); ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },0 );//*/ Log.d("MAP", "PERMISSION ISSUE"); return; } // this triggered by location changes to get user's current location locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this.listener); Log.d("Maps","after requestLocationUpdates"); try { //to avoid null pointer exceptions check if userLocation != null. if (userLocation != null) { directionFinder = new DirectionFinder(getApplicationContext(),this,destLocation,userLocation,pickupLocations,dropoffLocations); directionFinder.execute(); } else { Toast.makeText(getApplicationContext(), "عفواً, لم يتم توصيل GPS حاول بعد ثواني", Toast.LENGTH_SHORT).show(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // initially the focus will be on Riyadh city. LatLng riyadh = new LatLng(24.6796205, 46.6981272); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(riyadh, 10)); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } // set my location enabled to assign value to userLocation variable. mMap.setMyLocationEnabled(true); } @Override public void onDirectionFinderStart() { // This will display a progressDialog to the user until the requested path is ready. progressDialog = ProgressDialog.show(this, "ارجو الإنتظار", "جاري البحث عن المسار المناسب.", true); } @Override public void onDirectionFinderSuccess(List<Route> routes) { progressDialog.dismiss(); polylinePaths = new ArrayList<>(); /* all passengers, pickuplocations and dropofflocation all indeceis coresspond to the same passengers' info * this loop will represent the polyline on the map and the pickup/dropoff markers. * it'll also provide info about the total distance and total duration.*/ for (Route route : routes) { mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(route.startLocation, 10)); ((TextView) findViewById(R.id.tvDuration)).setText(" دقائق "+route.duration); ((TextView) findViewById(R.id.tvDistance)).setText(" كم " +Math.round(route.distance)); int sizeOfList=pickupLocations.size(); // consider these points are retreived from a database. it must be represented on the map as MARKERS. if(flag.equals("simulation")) sizeOfList--;// decrement the simulated points, because it'll be represented using different marker for (int i=0; i< sizeOfList; i++) { /* represent pickup & dropoff locations of each passenger and display her name & phone.*/ mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.pushpin2)) .title(passengers.get(i).getFName()+" "+passengers.get(i).getLName()) .snippet(" هاتف :"+passengers.get(i).getPhone()) .position(pickupLocations.get(i))); mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.destpushpin2)) .position(dropoffLocations.get(i)) .title(passengers.get(i).getFName()+" "+passengers.get(i).getLName()) .snippet(" هاتف :"+passengers.get(i).getPhone())); } if(flag.equals("simulation")) { mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.pushpinsim)) .title("محاكاة نقطة انطلاق الراكب") .position(pickupLocations.get(sizeOfList))); mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.pushpinsim)) .title("محاكاة نقطة وصول الراكب") .position(dropoffLocations.get(sizeOfList))); } // to represent the polyline (path) on the map PolylineOptions polylineOptions = new PolylineOptions(). geodesic(true). color(Color.BLUE). width(8); for (int i = 0; i < route.points.size(); i++) { polylineOptions.add(route.points.get(i)); } polylinePaths.add(mMap.addPolyline(polylineOptions)); } } /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ public Action getIndexApiAction() { Thing object = new Thing.Builder() .setName("Maps Page") // TODO: Define a title for the content shown. // TODO: Make sure this auto-generated URL is correct. .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]")) .build(); return new Action.Builder(Action.TYPE_VIEW) .setObject(object) .setActionStatus(Action.STATUS_TYPE_COMPLETED) .build(); } @Override public void onStart() { super.onStart(); MyApp.showFeedback(this, original,false); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); AppIndex.AppIndexApi.start(client, getIndexApiAction()); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling //prompt the user to make Wassilni application grant location from the GPS. Toast.makeText(getApplicationContext(),"الرجاء تفعيل أذونات الموقع من الإعدادات",Toast.LENGTH_LONG).show(); ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },0 );//*/ Log.d("MAP", "PERMISSION ISSUE"); return; } // this triggered by location changes to get user's current location locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this.listener); Log.d("Maps","after requestLocationUpdates"); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. AppIndex.AppIndexApi.end(client, getIndexApiAction()); client.disconnect(); } public void parseJSON(String s) { String picloc,droploc;//POINT(24.844278 46.780666) PHP format of a point String[] sp; LatLng pickup,dropoff; try { JSONArray auser= null; JSONObject j = new JSONObject(s); auser=j.getJSONArray("result"); for (int i = 0 ; i <auser.length() ; i++) { JSONObject jsonObject=auser.getJSONObject(i); String JSON_ARRAY = "result"; String p_id = "P_ID"; String FName = "P_F_Name"; String LName = "P_L_Name"; String phone = "P_phone"; String email = "P_email"; String school = "school"; String R_ID = "R_ID"; String R_pickup = "R_pickup_loc"; String R_dropoff = "R_dropoff_loc"; Passenger p=new Passenger(); p.setID(jsonObject.getInt(p_id)); p.setFName(jsonObject.getString(FName)); p.setLName(jsonObject.getString(LName)); p.setPhone(jsonObject.getString(phone)); p.setEmail(jsonObject.getString(email)); p.setSchool(jsonObject.getString(school)); passengers.add(p); picloc = jsonObject.getString(R_pickup); pickup= MyApp.getLatlng(picloc); droploc = jsonObject.getString(R_dropoff); dropoff= MyApp.getLatlng(droploc); if(flag.equals("real")) destLocation=MyApp.getLatlng(jsonObject.getString("destination")); pickupLocations.add(pickup); dropoffLocations.add(dropoff); }//end for auser.length if(flag.equals("simulation")) { pickupLocations.add(simPickup); dropoffLocations.add(simDropoff); } System.out.println(passengers.toString()+" LatLng : "+pickupLocations.toString()); } catch (JSONException e) { e.printStackTrace(); } } @Override protected void onResume() { super.onResume(); // register connection status listener MyApp.getInstance().setConnectivityListener(this); } /** * Callback will be triggered when there is change in * network connection */ @Override public void onNetworkConnectionChanged(boolean isConnected) { MyApp.showFeedback(this,original,true); } }
44.488608
259
0.641837
1b5319fa56e037ac334f68d68c26e1efe70c4116
5,695
/* * Copyright 2017 NAVER Corp. * * 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.navercorp.pinpoint.common.server.bo.codec.stat.v2; import com.navercorp.pinpoint.common.buffer.Buffer; import com.navercorp.pinpoint.common.server.bo.codec.stat.AgentStatCodec; import com.navercorp.pinpoint.common.server.bo.codec.stat.AgentStatDataPointCodec; import com.navercorp.pinpoint.common.server.bo.codec.stat.header.AgentStatHeaderDecoder; import com.navercorp.pinpoint.common.server.bo.codec.stat.header.AgentStatHeaderEncoder; import com.navercorp.pinpoint.common.server.bo.codec.stat.header.BitCountingHeaderDecoder; import com.navercorp.pinpoint.common.server.bo.codec.stat.header.BitCountingHeaderEncoder; import com.navercorp.pinpoint.common.server.bo.codec.stat.strategy.StrategyAnalyzer; import com.navercorp.pinpoint.common.server.bo.codec.stat.strategy.UnsignedLongEncodingStrategy; import com.navercorp.pinpoint.common.server.bo.codec.strategy.EncodingStrategy; import com.navercorp.pinpoint.common.server.bo.serializer.stat.AgentStatDecodingContext; import com.navercorp.pinpoint.common.server.bo.stat.ResponseTimeBo; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import java.util.ArrayList; import java.util.List; /** * @author Taejin Koo */ @Component("responseTimeCodecV2") public class ResponseTimeCodecV2 implements AgentStatCodec<ResponseTimeBo> { private static final byte VERSION = 2; private final AgentStatDataPointCodec codec; @Autowired public ResponseTimeCodecV2(AgentStatDataPointCodec codec) { Assert.notNull(codec, "agentStatDataPointCodec must not be null"); this.codec = codec; } @Override public byte getVersion() { return VERSION; } @Override public void encodeValues(Buffer valueBuffer, List<ResponseTimeBo> responseTimeBos) { if (CollectionUtils.isEmpty(responseTimeBos)) { throw new IllegalArgumentException("responseTimeBos must not be empty"); } final int numValues = responseTimeBos.size(); valueBuffer.putVInt(numValues); List<Long> startTimestamps = new ArrayList<Long>(numValues); List<Long> timestamps = new ArrayList<Long>(numValues); UnsignedLongEncodingStrategy.Analyzer.Builder avgAnalyzerBuilder = new UnsignedLongEncodingStrategy.Analyzer.Builder(); for (ResponseTimeBo responseTimeBo : responseTimeBos) { startTimestamps.add(responseTimeBo.getStartTimestamp()); timestamps.add(responseTimeBo.getTimestamp()); avgAnalyzerBuilder.addValue(responseTimeBo.getAvg()); } this.codec.encodeValues(valueBuffer, UnsignedLongEncodingStrategy.REPEAT_COUNT, startTimestamps); this.codec.encodeTimestamps(valueBuffer, timestamps); this.encodeDataPoints(valueBuffer, avgAnalyzerBuilder.build()); } private void encodeDataPoints(Buffer valueBuffer, StrategyAnalyzer<Long> avgStrategyAnalyzer) { // encode header AgentStatHeaderEncoder headerEncoder = new BitCountingHeaderEncoder(); headerEncoder.addCode(avgStrategyAnalyzer.getBestStrategy().getCode()); final byte[] header = headerEncoder.getHeader(); valueBuffer.putPrefixedBytes(header); // encode values this.codec.encodeValues(valueBuffer, avgStrategyAnalyzer.getBestStrategy(), avgStrategyAnalyzer.getValues()); } @Override public List<ResponseTimeBo> decodeValues(Buffer valueBuffer, AgentStatDecodingContext decodingContext) { final String agentId = decodingContext.getAgentId(); final long baseTimestamp = decodingContext.getBaseTimestamp(); final long timestampDelta = decodingContext.getTimestampDelta(); final long initialTimestamp = baseTimestamp + timestampDelta; int numValues = valueBuffer.readVInt(); List<Long> startTimestamps = this.codec.decodeValues(valueBuffer, UnsignedLongEncodingStrategy.REPEAT_COUNT, numValues); List<Long> timestamps = this.codec.decodeTimestamps(initialTimestamp, valueBuffer, numValues); // decode headers final byte[] header = valueBuffer.readPrefixedBytes(); AgentStatHeaderDecoder headerDecoder = new BitCountingHeaderDecoder(header); EncodingStrategy<Long> avgEncodingStrategy = UnsignedLongEncodingStrategy.getFromCode(headerDecoder.getCode()); // decode values List<Long> avgs = this.codec.decodeValues(valueBuffer, avgEncodingStrategy, numValues); List<ResponseTimeBo> responseTimeBos = new ArrayList<ResponseTimeBo>(numValues); for (int i = 0; i < numValues; ++i) { ResponseTimeBo responseTimeBo = new ResponseTimeBo(); responseTimeBo.setAgentId(agentId); responseTimeBo.setStartTimestamp(startTimestamps.get(i)); responseTimeBo.setTimestamp(timestamps.get(i)); responseTimeBo.setAvg(avgs.get(i)); responseTimeBos.add(responseTimeBo); } return responseTimeBos; } }
46.300813
128
0.750834
9e1fe5529d86f7bffb612a24531186c89eb8ce4f
2,014
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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.amazon.sampleapp.impl.DeviceSetup; import android.app.Activity; import android.view.View; import android.widget.Toast; import com.amazon.aace.alexa.DeviceSetup; import com.amazon.sampleapp.R; import com.amazon.sampleapp.impl.Logger.LoggerHandler; public class DeviceSetupHandler extends DeviceSetup { private static final String sTag = DeviceSetupHandler.class.getSimpleName(); private final Activity mActivity; private final LoggerHandler mLogger; public DeviceSetupHandler(Activity activity, LoggerHandler logger) { mActivity = activity; mLogger = logger; setupGUI(); } @Override public void setupCompletedResponse(final StatusCode statusCode) { mLogger.postInfo(sTag, "setupCompletedResponse " + statusCode.toString()); mActivity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(mActivity, statusCode.toString(), Toast.LENGTH_SHORT).show(); } }); } private void setupGUI() { View logoutView = mActivity.findViewById(R.id.cblLogout); logoutView.findViewById(R.id.sendSetupCompleted).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mLogger.postInfo(sTag, "Sending setupCompleted"); setupCompleted(); } }); } }
33.566667
104
0.686197
a0364982df40897f927e15f8d1b476b39b057754
1,048
package cn.sakurablossom.freeblog; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class User { @Id private Integer user_id; private String user_name; private String user_password; /** * @return the user_id */ public Integer getUser_id() { return user_id; } /** * @param user_id the user_id to set */ public void setUser_id(Integer user_id) { this.user_id = user_id; } /** * @return the user_name */ public String getUser_name() { return user_name; } /** * @param user_name the user_name to set */ public void setUser_name(String user_name) { this.user_name = user_name; } /** * @return the user_password */ public String getUser_password() { return user_password; } /** * @param user_password the user_password to set */ public void setUser_password(String user_password) { this.user_password = user_password; } }
19.054545
56
0.605916
43592eaf7d5a6475c6042597941d771964f6a812
728
package behavioral.observer; import java.util.LinkedList; import java.util.List; public class ObservableImpl implements ObservableContract { private List<ObserverContract> observers = new LinkedList<>(); Item item; @Override public void add(ObserverContract observer) { observers.add(observer); } @Override public void remove(ObserverContract observer) { if(observers.size() != 0) observers.remove(observer); } @Override public void notifyObservers() { for (ObserverContract observerContract: observers) observerContract.update(item); } public Item getItem() { return item; } public void updateItem(Item item) { this.item = item; notifyObservers(); } }
19.157895
64
0.706044
4a3ab05c4ce2025c921768ec7802278d31943ff2
4,354
/* Copyright Airship and Contributors */ package com.urbanairship.automation.auth; import com.urbanairship.TestClock; import com.urbanairship.channel.AirshipChannel; import com.urbanairship.http.RequestException; import com.urbanairship.http.Response; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import androidx.test.ext.junit.runners.AndroidJUnit4; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(AndroidJUnit4.class) public class AuthManagerTest { private AuthManager authManager; private AuthApiClient mockClient; private AirshipChannel mockChannel; private TestClock clock; @Before public void setup() { this.mockChannel = mock(AirshipChannel.class); this.mockClient = mock(AuthApiClient.class); this.clock = new TestClock(); this.authManager = new AuthManager(mockClient, mockChannel, clock); } @Test public void testGetTokenFromClient() throws RequestException, AuthException { when(mockChannel.getId()).thenReturn("channel id"); when(mockClient.getToken("channel id")) .thenReturn(new Response.Builder<AuthToken>(200) .setResult(new AuthToken("channel id", "some token", 100)) .build()); assertEquals("some token", authManager.getToken()); } @Test(expected = AuthException.class) public void testGetTokenFailed() throws RequestException, AuthException { when(mockChannel.getId()).thenReturn("channel id"); when(mockClient.getToken("channel id")) .thenReturn(new Response.Builder<AuthToken>(400) .build()); authManager.getToken(); } @Test public void testGetTokenExpired() throws RequestException, AuthException { clock.currentTimeMillis = 0; when(mockChannel.getId()).thenReturn("channel id"); when(mockClient.getToken("channel id")) .thenReturn(new Response.Builder<AuthToken>(200) .setResult(new AuthToken("channel id", "some token", 100)) .build()) .thenReturn(new Response.Builder<AuthToken>(200) .setResult(new AuthToken("channel id", "some other token", 200)) .build()); assertEquals("some token", authManager.getToken()); clock.currentTimeMillis = 99; assertEquals("some token", authManager.getToken()); clock.currentTimeMillis = 100; assertEquals("some other token", authManager.getToken()); } @Test public void testGetTokenChannelIdChanged() throws RequestException, AuthException { clock.currentTimeMillis = 0; when(mockChannel.getId()).thenReturn("channel id"); when(mockClient.getToken("channel id")) .thenReturn(new Response.Builder<AuthToken>(200) .setResult(new AuthToken("channel id", "some token", 100)) .build()); assertEquals("some token", authManager.getToken()); when(mockChannel.getId()).thenReturn("other channel id"); when(mockClient.getToken("other channel id")) .thenReturn(new Response.Builder<AuthToken>(200) .setResult(new AuthToken("other channel id", "some other token", 100)) .build()); assertEquals("some other token", authManager.getToken()); } @Test public void tokenExpired() throws RequestException, AuthException { clock.currentTimeMillis = 0; when(mockChannel.getId()).thenReturn("channel id"); when(mockClient.getToken("channel id")) .thenReturn(new Response.Builder<AuthToken>(200) .setResult(new AuthToken("channel id", "some token", 100)) .build()) .thenReturn(new Response.Builder<AuthToken>(200) .setResult(new AuthToken("channel id", "some other token", 200)) .build()); assertEquals("some token", authManager.getToken()); authManager.tokenExpired("some token"); assertEquals("some other token", authManager.getToken()); } }
35.688525
94
0.629306
cb142a7f2b38fd4c9561db0876c884bee7f143d2
2,284
package cn.javareview.ssm.service.impl; import java.util.List; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import cn.javareview.ssm.exception.CustomException; import cn.javareview.ssm.mapper.ItemsMapper; import cn.javareview.ssm.mapper.ItemsMapperCustom; import cn.javareview.ssm.mapper.UserMapper; import cn.javareview.ssm.po.Items; import cn.javareview.ssm.po.ItemsCustom; import cn.javareview.ssm.po.ItemsQueryVo; import cn.javareview.ssm.po.User; import cn.javareview.ssm.service.ItemsService; /** * * <p>Title: ItemsServiceImpl</p> * <p>Description: 商品管理</p> * <p>Company: www.itcast.com</p> * @author 传智.燕青 * @date 2015-4-13下午3:49:54 * @version 1.0 */ public class ItemsServiceImpl implements ItemsService{ @Autowired private ItemsMapperCustom itemsMapperCustom; @Autowired private ItemsMapper itemsMapper; @Autowired private UserMapper userMapper; @Override public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception { //通过ItemsMapperCustom查询数据库 return itemsMapperCustom.findItemsList(itemsQueryVo); } @Override public ItemsCustom findItemsById(Integer id) throws Exception { Items items = itemsMapper.selectByPrimaryKey(id); if(items==null){ throw new CustomException("修改的商品信息不存在!"); } //中间对商品信息进行业务处理 //.... //返回ItemsCustom ItemsCustom itemsCustom = null; //将items的属性值拷贝到itemsCustom if(items!=null){ itemsCustom = new ItemsCustom(); BeanUtils.copyProperties(items, itemsCustom); } return itemsCustom; } @Override public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception { //添加业务校验,通常在service接口对关键参数进行校验 //校验 id是否为空,如果为空抛出异常 //更新商品信息使用updateByPrimaryKeyWithBLOBs根据id更新items表中所有字段,包括 大文本类型字段 //updateByPrimaryKeyWithBLOBs要求必须转入id itemsCustom.setId(id); itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom); } @Override public Integer selectByPrimaryKey() throws Exception { // TODO Auto-generated method stub return userMapper.selectByPrimaryKey(); } @Override public void insertSelective(User user) throws Exception { // TODO Auto-generated method stub } }
25.098901
81
0.73993
d675b32b11f6350434632fdfd5326704531dc68c
730
package wordTree.threadMgmt; import wordTree.util.FileProcessor; import wordTree.util.TreeBuilder; import wordTree.util.MyLogger; public class DeleteThread implements Runnable{ private String word = null; private TreeBuilder tb = null; /** * DeleteThread constructor * @param tbI - TreeBuilder instance * @param wordI - word to be deleted */ public DeleteThread(TreeBuilder tbI, String wordI) { MyLogger.writeMessage("DeleteThread constructor called", MyLogger.DebugLevel.CONSTRUCTOR); tb = tbI; word = wordI; } public void run(){ MyLogger.writeMessage("DeleteThread's run() method called", MyLogger.DebugLevel.IN_RUN); tb.delete(word); } }
27.037037
95
0.690411
bf6a69d656ead40dac14c9d5bd5efe2403325ee7
4,531
package me.braggs.BraggBot.Commands.CommandFactories; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import me.braggs.BraggBot.Commandarguments.paramType; import me.braggs.BraggBot.Commands.CommandFramework.Command; import me.braggs.BraggBot.Commands.CommandFramework.CommandArg; import me.braggs.BraggBot.Commands.CommandFramework.CommandBuilder; import me.braggs.BraggBot.Commands.CommandFramework.CommandCategory; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.plugins.jpeg.JPEGImageWriteParam; import javax.imageio.stream.ImageOutputStream; import java.awt.image.BufferedImage; import java.io.*; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Random; public class FunCommands implements CommandBuilder { private CommandCategory commandCategory = CommandCategory.fun; Random rnd = new Random(); OkHttpClient client = new OkHttpClient(); @Override public List<Command> buildCommandList() { List<Command> commandList = new ArrayList<>(); Command ping = new Command() .setName("ping") .setCategory(commandCategory) .setMethod(event -> event.getSender().sendMessage("pong")); commandList.add(ping); Command rtd = new Command() .setName("rtd") .setCategory(commandCategory) .setParameters(new CommandArg(paramType.Integer, true, "6")) .setMethod(event -> { int sides = Integer.parseInt(event.getArgument(0)); int result = rnd.nextInt(sides) + 1; event.getSender().sendMessage("you rolled a die with `" + sides + "` sides, you rolled a: " + result); }); commandList.add(rtd); Command joke = new Command() .setName("joke") .setCategory(commandCategory) .setMethod(event -> { try { Request request = new Request.Builder() .url("https://08ad1pao69.execute-api.us-east-1.amazonaws.com/dev/random_joke") .build(); Response response = client.newCall(request).execute(); Gson builder = new GsonBuilder().setPrettyPrinting().create(); JsonObject jsonObj = builder.fromJson(response.body().string(), JsonObject.class); event.getSender().sendMessage(jsonObj.get("setup").getAsString() + "\n" + jsonObj.get("punchline").getAsString()); } catch (IOException e) { event.getSender().sendMessage("I'm afraid there won't be any jokes today, sad!"); //log error with discord logger } }); commandList.add(joke); Command jpeg = new Command() .setName("jpeg") .setCategory(commandCategory) .setParameters(new CommandArg(paramType.Url)) .setMethod(event -> { try { URL url = new URL(event.getArgument(0)); BufferedImage img = ImageIO.read(url); JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null); jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); jpegParams.setCompressionQuality(0.01f); ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); ImageOutputStream imgOs = ImageIO.createImageOutputStream(byteOs); ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next(); writer.setOutput(imgOs); writer.write(null, new IIOImage(img, null, null), jpegParams); byte[] data = byteOs.toByteArray(); event.getSender().sendByteArray(data, "Jpeg.jpeg", "Added moar Jpeg!"); } catch (IOException e) { event.getSender().sendMessage("Woopsie I can't Jpeggify that image"); } }); commandList.add(jpeg); return commandList; } }
41.568807
138
0.589936
74005ba9633b4fd7191c60949a5ccbdf198d540a
7,235
/* * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.imageio.plugins.tiff; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.awt.image.SampleModel; import java.awt.image.WritableRaster; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Vector; import javax.imageio.ImageReadParam; import javax.imageio.ImageTypeSpecifier; import javax.imageio.plugins.tiff.TIFFImageReadParam; import javax.imageio.plugins.tiff.TIFFTagSet; public class TIFFRenderedImage implements RenderedImage { private TIFFImageReader reader; private int imageIndex; private ImageReadParam tileParam; private int subsampleX; private int subsampleY; private boolean isSubsampling; private int width; private int height; private int tileWidth; private int tileHeight; private ImageTypeSpecifier its; public TIFFRenderedImage(TIFFImageReader reader, int imageIndex, ImageReadParam readParam, int width, int height) throws IOException { this.reader = reader; this.imageIndex = imageIndex; this.tileParam = cloneImageReadParam(readParam, false); this.subsampleX = tileParam.getSourceXSubsampling(); this.subsampleY = tileParam.getSourceYSubsampling(); this.isSubsampling = this.subsampleX != 1 || this.subsampleY != 1; this.width = width/subsampleX; this.height = height/subsampleY; // If subsampling is being used, we may not match the // true tile grid exactly, but everything should still work this.tileWidth = reader.getTileWidth(imageIndex)/subsampleX; this.tileHeight = reader.getTileHeight(imageIndex)/subsampleY; Iterator<ImageTypeSpecifier> iter = reader.getImageTypes(imageIndex); this.its = iter.next(); tileParam.setDestinationType(its); } /** * Creates a copy of {@code param}. The source subsampling and * and bands settings and the destination bands and offset settings * are copied. If {@code param} is a {@code TIFFImageReadParam} * then the {@code TIFFDecompressor} and * {@code TIFFColorConverter} settings are also copied; otherwise * they are explicitly set to {@code null}. * * @param param the parameters to be copied. * @param copyTagSets whether the {@code TIFFTagSet} settings * should be copied if set. * @return copied parameters. */ private ImageReadParam cloneImageReadParam(ImageReadParam param, boolean copyTagSets) { // Create a new TIFFImageReadParam. TIFFImageReadParam newParam = new TIFFImageReadParam(); // Copy the basic settings. newParam.setSourceSubsampling(param.getSourceXSubsampling(), param.getSourceYSubsampling(), param.getSubsamplingXOffset(), param.getSubsamplingYOffset()); newParam.setSourceBands(param.getSourceBands()); newParam.setDestinationBands(param.getDestinationBands()); newParam.setDestinationOffset(param.getDestinationOffset()); if (param instanceof TIFFImageReadParam && copyTagSets) { // Copy the settings from the input parameter. TIFFImageReadParam tparam = (TIFFImageReadParam) param; List<TIFFTagSet> tagSets = tparam.getAllowedTagSets(); if (tagSets != null) { Iterator<TIFFTagSet> tagSetIter = tagSets.iterator(); if (tagSetIter != null) { while (tagSetIter.hasNext()) { TIFFTagSet tagSet = tagSetIter.next(); newParam.addAllowedTagSet(tagSet); } } } } return newParam; } public Vector<RenderedImage> getSources() { return null; } public Object getProperty(String name) { return java.awt.Image.UndefinedProperty; } public String[] getPropertyNames() { return null; } public ColorModel getColorModel() { return its.getColorModel(); } public SampleModel getSampleModel() { return its.getSampleModel(); } public int getWidth() { return width; } public int getHeight() { return height; } public int getMinX() { return 0; } public int getMinY() { return 0; } public int getNumXTiles() { return (width + tileWidth - 1)/tileWidth; } public int getNumYTiles() { return (height + tileHeight - 1)/tileHeight; } public int getMinTileX() { return 0; } public int getMinTileY() { return 0; } public int getTileWidth() { return tileWidth; } public int getTileHeight() { return tileHeight; } public int getTileGridXOffset() { return 0; } public int getTileGridYOffset() { return 0; } public Raster getTile(int tileX, int tileY) { Rectangle tileRect = new Rectangle(tileX*tileWidth, tileY*tileHeight, tileWidth, tileHeight); return getData(tileRect); } public Raster getData() { return read(new Rectangle(0, 0, getWidth(), getHeight())); } public Raster getData(Rectangle rect) { return read(rect); } // This method needs to be synchronized as it updates the instance // variable 'tileParam'. public synchronized WritableRaster read(Rectangle rect) { tileParam.setSourceRegion(isSubsampling ? new Rectangle(subsampleX*rect.x, subsampleY*rect.y, subsampleX*rect.width, subsampleY*rect.height) : rect); try { BufferedImage bi = reader.read(imageIndex, tileParam); WritableRaster ras = bi.getRaster(); return ras.createWritableChild(0, 0, ras.getWidth(), ras.getHeight(), rect.x, rect.y, null); } catch (IOException e) { throw new RuntimeException(e); } } public WritableRaster copyData(WritableRaster raster) { if (raster == null) { return read(new Rectangle(0, 0, getWidth(), getHeight())); } else { Raster src = read(raster.getBounds()); raster.setRect(src); return raster; } } }
29.056225
79
0.581755
d8de0f990fbb06ceeb7e8d7db2c7579502a28a8d
858
package liber.abaci.config; import liber.abaci.controller.FibonacciSequenceController; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; @EnableAutoConfiguration public class FibonacciSequenceConfig { @Bean public LocalValidatorFactoryBean localValidatorFactoryBean() { return new LocalValidatorFactoryBean(); } @Bean public MethodValidationPostProcessor methodValidationPostProcessor() { return new MethodValidationPostProcessor(); } @Bean public FibonacciSequenceController fibonacciSequenceController() { return new FibonacciSequenceController(); } }
29.586207
83
0.806527
35ab85ce5150e4fdfd2d89e799f94ac2385c9ca0
1,628
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.RobotContainer; import edu.wpi.first.wpilibj.Servo; public class ShooterHoodBase extends SubsystemBase { public static Servo LeftShooterServo = RobotContainer.leftShooterServo; public static Servo RightShooterServo = RobotContainer.rightShooterServo; public double currentExtenstion; /** Creates a new ShooterHoodBase. */ public ShooterHoodBase() { LeftShooterServo.setBounds(2.0,1.8,1.5,1.2,1.0); RightShooterServo.setBounds(2.0,1.8,1.5,1.2,1.0); LeftShooterServo.setAngle(0); RightShooterServo.setAngle(0); } @Override public void periodic() { // This method will be called once per scheduler run } public void setExtension(double extension){ if (extension == 0) { LeftShooterServo.setAngle(0); RightShooterServo.setAngle(0); currentExtenstion = 0; } else if (extension > 100 && extension < 180) { LeftShooterServo.setAngle(extension); RightShooterServo.setAngle(extension); currentExtenstion = extension; } else { if(extension > 179){ LeftShooterServo.setAngle(179); RightShooterServo.setAngle(179); currentExtenstion = 179; } else{ LeftShooterServo.setAngle(101); RightShooterServo.setAngle(101); currentExtenstion = 101; } } } }
26.688525
75
0.694717
29bb73d9073e915df59acd11ddff5d41a5acefbe
2,243
package seedu.address.logic.commands; import static java.util.Objects.requireNonNull; import java.util.List; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.event.Event; /** * Marks an Event identified using its displayed index as done. */ public class DoneCommand extends Command { public static final String COMMAND_WORD = "done"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Marks the event identified by the " + "index number used in the displayed event list as done.\n" + "Index should be positive integer.\n" + "Parameters: INDEX\n" + "Example: " + COMMAND_WORD + " 1"; public static final String MESSAGE_DONE_EVENT_SUCCESS = "Marked event as done:\n%1$s"; public static final String MESSAGE_EVENT_ALREADY_DONE = "This event is already marked as done!"; private final Index targetIndex; /** * This is a constructor for DoneCommand. * * @param targetIndex The index of the event to be marked as done, as seen in the displayed event list. */ public DoneCommand(Index targetIndex) { this.targetIndex = targetIndex; } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); List<Event> lastShownList = model.getFilteredEventList(); if (targetIndex.getZeroBased() >= lastShownList.size()) { throw new CommandException(Messages.MESSAGE_INVALID_EVENT_DISPLAYED_INDEX); } Event eventToMarkDone = lastShownList.get(targetIndex.getZeroBased()); if (eventToMarkDone.getDoneValue()) { throw new CommandException(MESSAGE_EVENT_ALREADY_DONE); } model.markEventAsDone(eventToMarkDone); return new CommandResult(String.format(MESSAGE_DONE_EVENT_SUCCESS, eventToMarkDone)); } @Override public boolean equals(Object other) { return other == this || (other instanceof DoneCommand && targetIndex.equals(((DoneCommand) other).targetIndex)); } }
35.046875
107
0.693714
1055127ef85539bd7ff6019b8c41d3b2ff0922d9
936
package io.octoprime.algo.math.num; public class ZSandbox { public static int fibi(int n) { if (n <= 1) return n; return fibi(n - 1) + fibi(n - 2); } public static int fib(int n) { int a = 0; int b = 1; int c = 0; for (int i = 2; i < n; i++) { c = a + b; a = b; b = c; } return c; } public static int fact(int n) { if (n <= 1) return 1; return n * fact(n - 1); } public static int facti(int n) { int sum = 1; for (int i = 2; i <= n; i++) sum *= i; return sum; } // 0, 1, 1, 2, 3, 5, 8, 13, public static void main(String[] args) { int n = 7; int fn = 4; int f = fibi(n); int ff = facti(fn); System.out.println("fib is: " + f); System.out.println("factorial is: " + ff); } }
16.714286
50
0.412393
1997254f5d1702a1974c2466b3a04f32aa8c47a7
1,593
package org.apereo.cas.authentication.device; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder; import lombok.extern.jackson.Jacksonized; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; /** * This is {@link MultifactorAuthenticationRegisteredDevice}. * * @author Misagh Moayyed * @since 6.6.0 */ @SuperBuilder @Getter @ToString(of = {"name", "type", "id", "model"}) @EqualsAndHashCode(of = {"name", "type", "id", "model"}) @Jacksonized @JsonInclude(JsonInclude.Include.NON_DEFAULT) @Setter @NoArgsConstructor(force = true) public class MultifactorAuthenticationRegisteredDevice implements Serializable { /** * The device name as chosen/managed by the mfa provider. */ private final String name; /** * Phone, tablet, etc. */ private final String type; /** * Unique identifier for the device registration entry. */ private final String id; /** * Phone number assigned to the device, if any. */ private final String number; /** * Platform type and details. (Android, iOS, Samsung, LG, etc) */ private final String model; @Builder.Default private Map<String, Object> details = new LinkedHashMap<>(); /** * The actual device record produced by the provider * typically captured here as JSON. */ private final String payload; }
24.136364
80
0.700565
0ff96f1c1f75d9e371df39fcb5d0baa52b11816e
2,681
/* * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package goodman.org.omg.CORBA; import org.omg.CORBA.CompletionStatus; import org.omg.CORBA.SystemException; /** * This exception is raised if an operation implementation * throws a non-CORBA exception (such as an exception * specific to the implementation's programming language), * or if an operation raises a user exception that does not * appear in the operation's raises expression. UNKNOWN is * also raised if the server returns a system exception that * is unknown to the client. (This can happen if the server * uses a later version of CORBA than the client and new system * exceptions have been added to the later version.)<P> * It contains a minor code, which gives more detailed information about * what caused the exception, and a completion status. It may also contain * a string describing the exception. * <P> * See the section <A href="../../../../technotes/guides/idl/jidlExceptions.html#minorcodemeanings">Minor * Code Meanings</A> to see the minor codes for this exception. * * @see <A href="../../../../technotes/guides/idl/jidlExceptions.html">documentation on * Java&nbsp;IDL exceptions</A> */ public final class UNKNOWN extends SystemException { /** * Constructs an <code>UNKNOWN</code> exception with a default minor code * of 0, a completion state of CompletionStatus.COMPLETED_NO, * and a null description. */ public UNKNOWN() { this(""); } /** * Constructs an <code>UNKNOWN</code> exception with the specified description message, * a minor code of 0, and a completion state of COMPLETED_NO. * @param s the String containing a detail message */ public UNKNOWN(String s) { this(s, 0, CompletionStatus.COMPLETED_NO); } /** * Constructs an <code>UNKNOWN</code> exception with the specified * minor code and completion status. * @param minor the minor code * @param completed the completion status */ public UNKNOWN(int minor, CompletionStatus completed) { this("", minor, completed); } /** * Constructs an <code>UNKNOWN</code> exception with the specified description * message, minor code, and completion status. * @param s the String containing a description message * @param minor the minor code * @param completed the completion status */ public UNKNOWN(String s, int minor, CompletionStatus completed) { super(s, minor, completed); } }
29.141304
105
0.682208
9e0708932d0ee760b75439eddb5f23b9868c3891
1,413
package org.usfirst.frc.team4950.robot.subsystems; import edu.wpi.first.wpilibj.command.Subsystem; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.usfirst.frc.team4950.robot.Database; import org.usfirst.frc.team4950.robot.Robot; import org.usfirst.frc.team4950.robot.RobotMap; import org.usfirst.frc.team4950.robot.commands.ExampleCommand; import com.ctre.CANTalon; import edu.wpi.first.wpilibj.AnalogGyro; import edu.wpi.first.wpilibj.AnalogInput; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.RobotDrive.MotorType; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * */ public class ExampleSubsystem extends Subsystem { // Put methods for controlling this subsystem // here. Call these from Commands. public static CANTalon leftMotor; private static ReentrantReadWriteLock readWriteLock; public ExampleSubsystem() { leftMotor = new CANTalon(RobotMap.leftMotor); readWriteLock = new ReentrantReadWriteLock(); } public void initDefaultCommand() { if(Robot.isRecordingForAutoPlay) setDefaultCommand(new ExampleCommand()); } public void power(double p) { readWriteLock.readLock().lock(); try { leftMotor.set(p); } finally { readWriteLock.readLock().unlock(); } } }
28.26
62
0.788393
f1f02f3fb924354f2f4e43a52900ca2dccf2b018
1,246
package sasj.controller.principal; import sasj.data.course.Course; import sasj.data.course.CourseRepository; import sasj.controller.Extensions; import sasj.controller.AuthorizedController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/principal/courses") public class PrincipalCourseController implements AuthorizedController { @Autowired private CourseRepository courseRepository; @Autowired private Extensions extensions; // TODO this lists all courses regardless of school year. /** * Lists all courses entered in the system. * These are the courses for all school years, all school classes, * and all subjects. * @param model The object where the view model is kept. * @return The name of the template for this view. */ @GetMapping public String list(Model model) { Iterable<Course> courses = courseRepository.findAll(); model.addAttribute("courses", courses); return "principal/courses"; } }
34.611111
72
0.756822
3a6b845509335bf48d5281f536ffe8436048a5b8
79
package org.nanotek.entities; public interface BaseArtistCreditEntity<K> { }
13.166667
44
0.797468
678144466c3036c322097dd8af0772710209c0d6
5,735
/* * Copyright (C) 2021 stylist Development Team * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT */ package stylist.value; public class Font implements CharSequence { /** * Glyphs have finishing strokes, flared or tapering ends, or have actual serifed endings. E.g. * Palatino, "Palatino Linotype", Palladio, "URW Palladio", serif */ public static final Font Serif = Font.of("serif"); /** * <p> * Glyphs have stroke endings that are plain. E.g. 'Trebuchet MS', 'Liberation Sans', 'Nimbus * Sans L', sans-serif * </p> */ public static final Font SansSerif = Font.of("sans-serif"); /** * <p> * Glyphs in cursive fonts generally have either joining strokes or other cursive * characteristics beyond those of italic typefaces. The glyphs are partially or completely * connected, and the result looks more like handwritten pen or brush writing than printed * letterwork. * </p> */ public static final Font Cursive = Font.of("cursive"); /** * <p> * Fantasy fonts are primarily decorative fonts that contain playful representations of * characters. * </p> */ public static final Font Fantasy = Font.of("fantasy"); /** * <p> * All glyphs have the same fixed width. E.g. "DejaVu Sans Mono", Menlo, Consolas, "Liberation * Mono", Monaco, "Lucida Console", monospace * </p> */ public static final Font Monospace = Font.of("monospace"); /** * <p> * Glyphs are taken from the default user interface font on a given platform. Because * typographic traditions vary widely across the world, this generic is provided for typefaces * that don't map cleanly into the other generics. * </p> */ public static final Font SystemUI = Font.of("system-ui"); /** * <p> * This is for the particular stylistic concerns of representing mathematics: superscript and * subscript, brackets that cross several lines, nesting expressions, and double struck glyphs * with distinct meanings. * </p> */ public static final Font Math = Font.of("math"); /** * <p> * Fonts that are specifically designed to render emoji. * </p> */ public static final Font Emoji = Font.of("emoji"); /** * <p> * A particular style of Chinese characters that are between serif-style Song and cursive-style * Kai forms. This style is often used for government documents * </p> */ public static final Font FangSong = Font.of("fangsong"); /** The built-in font. */ public static final Font Awesome = Font .of("FontAwesome", "https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css"); /** The built-in font. */ public static final Font MaterialIcon = Font.of("Material Icons", "https://fonts.googleapis.com/icon?family=Material+Icons"); /** The font name. */ public final String name; /** The font uri. */ public final String uri; /** * <p> * Create font with name and uri. * </p> * * @param name A font name. * @param uri A font uri. */ protected Font(String name, String uri) { this.name = name; this.uri = uri; } /** * {@inheritDoc} */ @Override public int length() { return name.length(); } /** * {@inheritDoc} */ @Override public char charAt(int index) { return name.charAt(index); } /** * {@inheritDoc} */ @Override public CharSequence subSequence(int start, int end) { return name.substring(start, end); } /** * {@inheritDoc} */ @Override public int hashCode() { return name.hashCode() ^ uri.hashCode(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj instanceof Font) { Font other = (Font) obj; return name.equals(other.name) && uri.equals(other.uri); } return false; } /** * {@inheritDoc} */ @Override public String toString() { return name; } /** * Build local font. * * @param name Font name. * @return */ public static Font of(String name) { return new Font(name, ""); } /** * Build external font. * * @param name Font name. * @param url External location. * @return */ public static Font of(String name, String url) { return new Font(name, url); } /** * <p> * Load from <a href="https://www.google.com/fonts">Google Fonts</a>. * </p> * * @param name A name of font to load. * @param params A list of extra parameters. * @return A loaded font. */ public static Font fromGoogle(String name, String... params) { StringBuilder builder = new StringBuilder("https://fonts.googleapis.com/css?display=swap&family="); builder.append(name.replaceAll("\\s", "+")); if (params != null && params.length != 0) { builder.append(":"); for (String param : params) { builder.append(param).append(","); } } return new Font(name, builder.toString()); } }
27.440191
130
0.561465
13852bd63adfa4e339783739c2d1df38f2ea2e8c
278
package it.unibz.inf.ontop.spec.mapping.transformer; import com.google.common.collect.ImmutableSet; import it.unibz.inf.ontop.spec.mapping.Mapping; public interface MappingMerger { Mapping merge(Mapping... mappings); Mapping merge(ImmutableSet<Mapping> mappings); }
23.166667
52
0.780576
87a0d31e63c519070151300730b6825dcf916b83
2,302
package org.tatools.sunshine.core; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.List; import lombok.EqualsAndHashCode; /** * The {@link FileSystemOfPath} class allows to search files by given path. * * @author Dmytro Serdiuk ([email protected]) * @version $Id: 87a0d31e63c519070151300730b6825dcf916b83 $ * @since 0.1 */ @EqualsAndHashCode final class FileSystemOfPath implements FileSystem { private final Path path; FileSystemOfPath(String path) { this(new FileSystemPathBase(path).path()); } FileSystemOfPath(Path path) { this.path = path; } @Override public List<FileSystemPath> files() throws FileSystemException { try { List<FileSystemPath> files = new ArrayList<>(); Files.walkFileTree( path, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory( Path dir, BasicFileAttributes attrs) { files.add(new FileSystemPathRelative(path, dir.toString())); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { files.add(new FileSystemPathRelative(path, file.toString())); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { return FileVisitResult.CONTINUE; } }); return files; } catch (IOException e) { throw new FileSystemException(e); } } }
33.852941
96
0.560817
dda5cb5c1060f9e7b5c62aa1dee14dd6f0919f7a
5,606
package agp.ajax; import static agp.ajax.AjaxHandler.CONTENT_TYPE_HTML; import static agp.ajax.AjaxHandler.CONTENT_TYPE_JSON; import static agp.ajax.AjaxHandler.FILENAME; import static agp.ajax.AjaxHandler.FILE_PARAMETER; import static agp.ajax.AjaxHandler.PENDING; import static agp.ajax.AjaxHandler.PENDING_FILE; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import javax.portlet.GenericPortlet; import javax.portlet.PortletException; import javax.portlet.PortletRequestDispatcher; import javax.portlet.PortletURL; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.ResourceRequest; import javax.portlet.ResourceResponse; import javax.portlet.ResourceURL; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; public class AjaxPortlet extends GenericPortlet { AjaxHandler handler; @Override public void init() { String handlerClass = getPortletConfig().getInitParameter("handler-class"); Class<?> clazz; try { clazz = Class.forName(handlerClass); handler = (AjaxHandler) clazz.newInstance(); } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) { throw new RuntimeException("Incorrect parameter handler-class in portlet.xml"); } } // Renders a page. Passes a resourceUrl to the jsp, // which the frontend framework will call to get data // Also generates a CSRF token per page, draws it on the page // and stores it to the session public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException { String page = request.getParameter("page"); if (page == null) // if this is the initial render page = handler.getDefaultPage(); // create a csrf token and store it to the session GenericSession session = new GenericSession(request.getPortletSession()); String csrfToken = CsrfUtils.registerCSRFToken(session, page); // create the resource url for AJAX calls ResourceURL url = response.createResourceURL(); url.setParameter("page", page); // pass these parameters to the jsp file request.setAttribute("ajaxUrl", url); request.setAttribute("csrfToken", csrfToken); // get the jsp to render PortletRequestDispatcher rd = this.getPortletContext().getRequestDispatcher("/" + page + ".jsp"); response.setContentType(CONTENT_TYPE_HTML); rd.include(request, response); } // Responds only with JSON. Redirect to another page is possible by creating and // sending a url to javascript. public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { GenericSession session = new GenericSession(request.getPortletSession()); if (PENDING.equals(request.getParameter(FILE_PARAMETER))) { fileResponse(response, session); } else { jsonResponse(request, response, session); } } private void jsonResponse(ResourceRequest request, ResourceResponse response, GenericSession session) throws IOException, UnsupportedEncodingException { String payload = IOUtils.toString(request.getReader()); HttpServletRequest httpRequest = (HttpServletRequest) request.getAttribute("httpRequest"); String csrfToken = httpRequest.getHeader("csrf-token"); String page = request.getParameter("page"); CsrfUtils.validateCSRFToken(page, csrfToken, session); GenericResponse handlerResponse = handler.handleAjaxRequest(payload, page, session); checkForRedirectResponse(handlerResponse, response); checkForFileResponse(handlerResponse, response, session); response.setContentType(CONTENT_TYPE_JSON); PrintWriter writer = response.getWriter(); writer.write(handlerResponse.getResponse()); } // this means previous response created a resource URL and stored a file in the // session. private void fileResponse(ResourceResponse response, GenericSession session) throws IOException { byte[] file = (byte[]) session.getAttribute(PENDING_FILE); OutputStream os = response.getPortletOutputStream(); os.write(file); response.setProperty("Content-Disposition", "attachment; filename=" + session.getAttribute(FILENAME)); os.close(); session.removeAttribute(FILENAME); session.removeAttribute(PENDING_FILE); } private void checkForFileResponse(GenericResponse handlerResponse, ResourceResponse response, GenericSession session) { if (ResponseType.FILE.equals(handlerResponse.getResponseType())) { // create a resource for this file and store it in the session ResourceURL url = response.createResourceURL(); url.setParameter(FILE_PARAMETER, PENDING); session.setAttribute(PENDING_FILE, handlerResponse.getFile()); session.setAttribute(FILENAME, handlerResponse.getResponse()); AjaxHandler.convertResponseToRedirect(handlerResponse, url.toString()); } } private void checkForRedirectResponse(GenericResponse handlerResponse, ResourceResponse response) { // If the response demands a redirect to another page create a render url and // append it to the JSON // The redirect will be performed in javascript with window.location if (ResponseType.REDIRECT.equals(handlerResponse.getResponseType())) { PortletURL url = response.createRenderURL(); // the page parameter defines which jsp will be loaded on doView method url.setParameter("page", handlerResponse.getResponse()); AjaxHandler.convertResponseToRedirect(handlerResponse, url.toString()); } } }
41.220588
118
0.765787
567e4f49f9d3d7cd79dfbc3485c03a6c1fd46378
989
package sort_list; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /** * @author [email protected] */ public class SolutionTest { private Solution solution1 = new Solution(); @Test public void test_empty_list() throws Exception { ListNode listNode = null; assertThat(solution1.sortList(listNode)).isEqualTo(listNode); } @Test public void test_one_node_list() throws Exception { ListNode listNode = new ListNode(5); assertThat(solution1.sortList(listNode)).isEqualTo(listNode); } @Test public void test_two_node_list() throws Exception { ListNode listNode = new ListNode(2); listNode.next = new ListNode(1); assertThat(solution1.sortList(listNode)).isNotEqualTo(listNode); } @Test public void test_3_node_list() throws Exception { ListNode listNode = new ListNode(3); listNode.next = new ListNode(4); listNode.next.next = new ListNode(1); assertThat(solution1.sortList(listNode)).isNotEqualTo(listNode); } }
24.121951
66
0.751264
0f84d442f683f266dd4cef748a57f4e82e31ccc8
8,500
package org.firstinspires.ftc.teamcode.Systems.Core; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import java.util.ArrayList; import java.util.Collections; public class Positions extends LinearOpMode { /* POSITION SETUP VARIABLES */ //Position Variables: private static Robot robot = new Robot(); private static double positionX = 0.0; private static double positionY = 0.0; private static double theta = 0.0; //Position Block Variables: private static ArrayList<Double> roadblockX = new ArrayList<Double>(); private static ArrayList<Double> roadblockY = new ArrayList<Double>(); /* POSITION CONTROL METHODS */ @Override public void runOpMode() { /* Access Hardware Methods */ } //Set Current Position Method: public void setCurrentPosition(double x, double y, double angle) { //Sets the Current Position: positionX = x; positionY = y; theta = angle; } //Resets the Current Position Method: public void resetCurrentPosition() { //Sets the Current Position: positionX = 0.0; positionY = 0.0; theta = robot.getTheta(); } //Sets the Roadblocks on the Field: public void setRoadblocks(double x[], double y[]) { //Checks the Case: if (x.length == y.length) { //Sets the Roadblocks: roadblockX = toDoubleList(x); roadblockY = toDoubleList(y); } } /* POSITION MOVEMENT METHODS */ //Move to Position Method: public void runToPosition(double targetX, double targetY, double direction, double power, boolean correct) { //Gets the Triangle: double start[] = {positionX, positionY}; double end [] = {targetX, targetY}; double triangle[] = getTriangle(start, end); //Checks the Case: if (isRoadClear(targetX, targetY)) { //Runs to Position: double rotations = (direction * getConvertedRotations(triangle[2])); runGyro(rotations, power, correct); //Sets the New Position: positionX = targetX; positionY = targetY; theta = robot.getTheta(); } } //Turn to Position Method: public void turnToPosition(double targetX, double targetY, double power, boolean correct) { //Gets the Triangle: double start[] = {positionX, positionY}; double end [] = {targetX, targetY}; double triangle[] = getTriangle(start, end); //Checks the Case: if (isRoadClear(targetX, targetY)) { //Turns and Sets New Position: double turnAngle = (-theta + triangle[3]); turnGyro(turnAngle, power, correct); theta = robot.getTheta(); } } //Shift to Position Method (ONLY USE IF NEEDED): public void shiftToPosition(double targetX, double targetY, double direction, double power, boolean correct) { //Gets the Triangle: double start[] = {positionX, positionY}; double end [] = {targetX, targetY}; double triangle[] = getTriangle(start, end); //Checks the Case: if (isRoadClear(targetX, targetY)) { //Shifts to Position: double rotations = (direction * getConvertedRotations(triangle[2])); shiftGyro(rotations, power, correct); //Sets the New Position: positionX = targetX; positionY = targetY; theta = robot.getTheta(); } } /* POSITION CORE METHODS */ //Runs with Gyro Corrects: public void runGyro(double rotations, double power, boolean correct) { //Runs: robot.runRobot(rotations, power); //Checks the Case: if (correct) { //Corrects the Motion: gyroCorrect(theta); } //Sets the Current Theta: theta = robot.getTheta(); } //Makes turns with Gyro Corrections: public void turnGyro(double angle, double power, boolean correct) { //Calculates and Turns: double turnValue = robot.calculateTurnRotations(angle); double expected = (theta + angle); robot.turnRobot(turnValue, power); //Checks the Case: if (correct) { //Corrects the Motion: gyroCorrect(expected); } //Sets the Current Theta: theta = robot.getTheta(); } //Shifts with Gyro Corrects (ONLY USE IF NEEDED): public void shiftGyro(double rotations, double power, boolean correct) { //Shifts: robot.shiftRobot(rotations, power); //Checks the Case: if (correct) { //Corrects the Motion: gyroCorrect(theta); } //Sets the Current Theta: theta = robot.getTheta(); } //Gyro Correction Method (Reset Gyro Before): public void gyroCorrect(double expectedAngle) { //Checks the Case: if (robot.isWithinRange(robot.getTheta(), expectedAngle, robot.gyroStabilization)) { //Gyro Correction: double gyroValue = robot.getGyroCorrection(expectedAngle); robot.turnRobot(gyroValue, robot.gyroPower); } //Sets the Current Theta: theta = robot.getTheta(); } /* POSITION PATH METHODS */ //Find Open Paths to Target Method: public static boolean isRoadClear(double targetX, double targetY) { //Main Variables: int turns = 0; int counter = 0; double mainLine[] = findLineEquation(positionX, positionY, targetX, targetY); //Loops through Array: mainLoop: while (turns < roadblockX.size()) { //Checks the Case: if (!isPointOnLine(mainLine, roadblockX.get(turns), roadblockY.get(turns))) { //Adds to the Counter: counter++; } turns++; } //Checks the Case: if (counter == roadblockX.size()) { //Returns the Value: return true; } else { //Returns the Value: return false; } } //Finds the Equation of Line: public static double[] findLineEquation(double x, double y, double targetX, double targetY) { //Finds the Initial Values: double slope = ((targetY - y) / (targetX - x)); double intercept = (y - (slope * x)); //Formats and Returns: double array[] = {slope, intercept}; return array; } //Finds If Point on Line: public static boolean isPointOnLine(double line[], double x, double y) { //Gets the Line: double left = y; double right = ((x * line[0]) + line[1]); //Checks the Case: if (left == right) { //Returns the Value: return true; } else { //Returns the Value: return false; } } //Gets Position Triangle: public static double[] getTriangle(double startCoordinates[], double endCoordinates[]) { //Main Array Variable: double triangle[] = new double[6]; //Defines the Dimensions of Triangle: double x = startCoordinates[0] - endCoordinates[0]; double y = startCoordinates[1] - endCoordinates[1]; double h = Math.sqrt((x * x) + (y * y)); double xDirection = (x / Math.abs(x)); double yDirection = (y / Math.abs(y)); //Gets the Angle of Triangle: double angle = Math.abs(robot.convertAngle(Math.atan(x / y), true)); angle = transformAngle(angle, x, y); //Formats Triangle: triangle[0] = x; triangle[1] = y; triangle[2] = h; triangle[3] = angle; triangle[4] = xDirection; triangle[5] = yDirection; //Returns the Triangle: return triangle; } /* POSITION UTILITY METHODS */ //Gets the Transformed Angle: public static double transformAngle(double angle, double xDiff, double yDiff) { //Main Value: double localAngle = angle; //Checks the Case: if (xDiff > 0 && yDiff < 0 || xDiff < 0 && yDiff > 0) { //Sets the Angle: localAngle = -localAngle; } //Returns the Angle: return localAngle; } //Get Converted Rotations: public static double getConvertedRotations(double pixelDistance) { //Converts and Returns Data: double coordinatesToInches = (pixelDistance * robot.POSITION_RATIO); double inchesToRotations = (coordinatesToInches / robot.wheelCirc); return inchesToRotations; } //Array to ArrayList Method: public static ArrayList<Double> toDoubleList(double array[]) { //Main Variables: ArrayList<Double> list = new ArrayList<Double>(); int turns = 0; //Loops through Array: mainLoop: while (turns < array.length) { //Adds to List: list.add(array[turns]); turns++; } //Returns List: return list; } }
27.777778
96
0.621765
64ee0d175bbf87ad2ba931057ad42b8884a03cdc
1,609
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.selenium; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.testing.JUnit4TestBase; import org.openqa.selenium.testing.NoDriverAfterTest; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assumptions.assumeThat; public class AuthenticationTest extends JUnit4TestBase { @Before public void testRequiresAuthentication() { assumeThat(driver).isInstanceOf(HasAuthentication.class); } @Test(timeout = 10000) @NoDriverAfterTest public void canAccessUrlProtectedByBasicAuth() { ((HasAuthentication) driver).register(UsernameAndPassword.of("test", "test")); driver.get(appServer.whereIs("basicAuth")); assertThat(driver.findElement(By.tagName("h1")).getText()).isEqualTo("authorized"); } }
36.568182
87
0.768179
6bae08cc26431b242a7c0682e2e5bd23e0653539
1,474
/** * This program and the accompanying materials * are made available under the terms of the License * which accompanies this distribution in the file LICENSE.txt */ package com.archimatetool.editor.views.tree.commands; import org.eclipse.gef.commands.Command; import com.archimatetool.model.IFolder; /** * Move Folder Command * * @author Phillip Beauvoir */ public class MoveFolderCommand extends Command { private IFolder fOldParent; private IFolder fNewParent; private IFolder fFolder; private int fOldPos; public MoveFolderCommand(IFolder newParent, IFolder folder) { super(Messages.MoveFolderCommand_0 + " " + folder.getName()); //$NON-NLS-1$ fOldParent = (IFolder)folder.eContainer(); fNewParent = newParent; fFolder = folder; } @Override public void execute() { fOldPos = fOldParent.getFolders().indexOf(fFolder); // do this here as its part of a compound command redo(); } @Override public void undo() { fNewParent.getFolders().remove(fFolder); fOldParent.getFolders().add(fOldPos, fFolder); } @Override public void redo() { fOldParent.getFolders().remove(fFolder); fNewParent.getFolders().add(fFolder); } @Override public void dispose() { fOldParent = null; fNewParent = null; fFolder = null; } }
26.8
110
0.628901