method_id
stringlengths
36
36
cyclomatic_complexity
int32
0
9
method_text
stringlengths
14
410k
83aeb3db-3ba6-4ca3-a3c7-332ecdb85659
5
private static void skipWhitespace() { char ch=lookChar(); while (ch != EOF && Character.isWhitespace(ch)) { readChar(); if (ch == '\n' && readingStandardInput && writingStandardOutput) { out.print("? "); out.flush(); } ch = lookChar(); } }
77956ee6-3fae-42e7-bd3e-4a1b2508e8c8
6
synchronized void changeMap(int intLocX, int intLocY, short value) { if (value < 0 || value > vctTiles.size()) { log.printMessage(Log.INFO, "Invalid value passed to changeMap("+intLocX+","+intLocY+","+value+")"); return; } if (intLocX < 0 || intLocX > MapColumns || intLocY < 0 || intLocY > MapRows) { log.printMessage(Log.INFO, "Invalid location to changeMap("+intLocX+","+intLocY+","+value+")"); return; } shrMap[intLocX][intLocY] = value; blnMapHasChanged=true; updateMap(intLocX,intLocY); }
51978b92-e060-4f1c-a69c-b47b7a8169ee
9
public void mark(int[][] matrix, int x, int y) { int n = matrix.length - 1; int row = x; int col = y; for(int i = 0; i <= n; ++i){ matrix[x][i] = 2; matrix[i][y] = 2; } while(row <= n && col <= n){ matrix[row++][col++] = 2; } row = x; col = y; while(row >= 0 && col >= 0){ matrix[row--][col--] = 2; } row = x; col = y; while(row >= 0 && col <= n){ matrix[row--][col++] = 2; } row = x; col = y; while(row <= n && col >= 0){ matrix[row++][col--] = 2; } matrix[x][y] = 1; }
8a7ab63b-d88a-4ccc-8c80-043666819ae4
8
public String getInnerClassString(ClassInfo info, int scopeType) { InnerClassInfo[] outers = info.getOuterClasses(); if (outers == null) return null; for (int i = 0; i < outers.length; i++) { if (outers[i].name == null || outers[i].outer == null) return null; Scope scope = getScope(ClassInfo.forName(outers[i].outer), Scope.CLASSSCOPE); if (scope != null && !conflicts(outers[i].name, scope, scopeType)) { StringBuffer sb = new StringBuffer(outers[i].name); for (int j = i; j-- > 0;) { sb.append('.').append(outers[j].name); } return sb.toString(); } } String name = getClassString( ClassInfo.forName(outers[outers.length - 1].outer), scopeType); StringBuffer sb = new StringBuffer(name); for (int j = outers.length; j-- > 0;) sb.append('.').append(outers[j].name); return sb.toString(); }
ee516dba-93ba-4576-8671-c4ce29fe3187
7
@Override public void update() { int xa = 0, ya = 0; if (anim < 7500) { anim++; } else { anim = 0; } if (input.up) { ya--; } if (input.down) { ya++; } if (input.left) { xa--; } if (input.right) { xa++; } if (xa != 0 || ya != 0) { move(xa, ya); walking = true; } else { walking = false; } }
dd0936be-979b-4d81-9a0c-2c1604e05251
7
public static double binomialCoefficientDouble(final int n, final int k) { ArithmeticUtils.checkBinomial(n, k); if ((n == k) || (k == 0)) { return 1d; } if ((k == 1) || (k == n - 1)) { return n; } if (k > n / 2) { return binomialCoefficientDouble(n, n - k); } if (n < 67) { return binomialCoefficient(n, k); } double result = 1d; for (int i = 1; i <= k; i++) { result *= (double) (n - k + i) / (double) i; } return FastMath.floor(result + 0.5); }
3ade4b3c-812d-46ab-aa22-8b25fa9bdcb8
5
public static void addPainters(final Paintable... painters) { if (painters == null || getPaintHandler() == null) { return; } for (final Paintable p : painters) { if (p != null) { if (p instanceof PaintTab) { getMainPaint().add((PaintTab) p); } else { getPaintHandler().add(p); } } } }
51a38078-01f0-4fd0-a37e-190198cd78bd
7
@Override public final LinkedPointer addEffect(AbstractEffect<Boolean> e) { if (e == null) throw new NullPointerException("The effect is null."); if (!e.affectTo().equals(type)) throw new NullPointerException("The effect cannot affect this property."); lock(); try { switch (e.getEffectType()) { case TYPE_SIMPLE: return addAdditionValue(e); case TYPE_BUFF: case TYPE_BUFF_INTERVAL: return addBuffEffect((BuffEffect<Boolean>) e); case TYPE_MODIFIED: setFixedEffect((ModifiedEffect<Boolean>) e); return null; case TYPE_LONGTIME: return addLongTimeEffect((LongTimeEffect<Boolean>) e); default: throw new ErrorTypeException("Error effect type."); } } finally { unlock(); } }
07ac6b20-e97a-4173-b432-a937ddc2f5ab
0
public void setClient(List<Client> client) { this.client = client; }
5457c870-f911-4d63-80e5-16d56fb67cde
9
public boolean similar(Object other) { try { if (!(other instanceof JSONObject)) { return false; } Set<String> set = this.keySet(); if (!set.equals(((JSONObject)other).keySet())) { return false; } Iterator<String> iterator = set.iterator(); while (iterator.hasNext()) { String name = iterator.next(); Object valueThis = this.get(name); Object valueOther = ((JSONObject)other).get(name); if (valueThis instanceof JSONObject) { if (!((JSONObject)valueThis).similar(valueOther)) { return false; } } else if (valueThis instanceof JSONArray) { if (!((JSONArray)valueThis).similar(valueOther)) { return false; } } else if (!valueThis.equals(valueOther)) { return false; } } return true; } catch (Throwable exception) { return false; } }
09ed633b-b404-4202-bf9b-51c85dd3f421
3
private void updateLink() { try { LinkListViewHelper helper = (LinkListViewHelper) updateLinkListComboBox.getSelectedItem(); if(helper == null) return; ElementListViewHelper to = (ElementListViewHelper) updateLinkToComboBox.getSelectedItem(); ElementListViewHelper from = (ElementListViewHelper) updateLinkFromComboBox.getSelectedItem(); if(!to.equals(from)) { Link link = helper.getLink(); link.setFromId(from.getNetworkHardware()); link.setToId(to.getNetworkHardware()); link.setType( (String) updateLinkTypeComboBox.getSelectedItem()); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeBytes(ServerFrame.updateLinkCmd + "\n"); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); oos.writeObject(link); } else { JOptionPane.showConfirmDialog(this, "Can't connect to itself.", "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE); } } catch(Exception e) { e.printStackTrace(); } }
da261783-3867-487a-b0e8-b25ba72864b9
9
private void restoreFullDescendantComponentStates(FacesContext facesContext, Iterator<UIComponent> childIterator, Object state, boolean restoreChildFacets) { Iterator<? extends Object[]> descendantStateIterator = null; while (childIterator.hasNext()) { if (descendantStateIterator == null && state != null) { descendantStateIterator = ((Collection<? extends Object[]>) state) .iterator(); } UIComponent component = childIterator.next(); // reset the client id (see spec 3.1.6) component.setId(component.getId()); if (!component.isTransient()) { Object childState = null; Object descendantState = null; if (descendantStateIterator != null && descendantStateIterator.hasNext()) { Object[] object = descendantStateIterator.next(); childState = object[0]; descendantState = object[1]; } component.clearInitialState(); component.restoreState(facesContext, childState); component.markInitialState(); Iterator<UIComponent> childsIterator; if (restoreChildFacets) { childsIterator = component.getFacetsAndChildren(); } else { childsIterator = component.getChildren().iterator(); } restoreFullDescendantComponentStates(facesContext, childsIterator, descendantState, true); } } }
f60c6f53-1cfc-45c8-bf8f-f61508b96149
1
public void addMaterial(String asId, String asName) { if (this.getMaterials() == null) { this.setMaterials(new Vector<MaterialAttr>()); } this.getMaterials().add(new MaterialAttr(asId, asName)); }
a4afa7f4-9579-45d7-b4d5-bf4b174eab81
3
public static void sortCards(ArrayList<Card> cards, boolean ascending_descending, boolean value_suite) { if (ascending_descending) { sortAscending(cards, (value_suite) ? CardValueComparator : CardSuiteComparator); } else { sortDescending(cards, (value_suite) ? CardValueComparator : CardSuiteComparator); } }
b1f5aee5-e938-4570-b479-01527dff52e6
8
@Override public String convertSelfToString() { Integer lackLength; String idStr = String.valueOf(id); if(idStr.length() <= 6){ lackLength = 6 - idStr.length(); for(int i = 0; i < lackLength; i++){ idStr = "0" + idStr; } } else{ idStr = idStr.substring(idStr.length() - 6); } String agentIdStr = String.valueOf(agentId); if(agentIdStr.length() <= 8){ lackLength = 8 - agentIdStr.length(); for(int i = 0; i < lackLength; i++){ agentIdStr = "0" + agentIdStr; } } else{ agentIdStr = agentIdStr.substring(agentIdStr.length() - 8); } String volumeStr = String.valueOf(volume); if(volumeStr.length() <= 10){ lackLength = 10 - volumeStr.length(); for(int i = 0; i < lackLength; i++){ volumeStr = "0" + volumeStr; } } else{ volumeStr = volumeStr.substring(0,10); } String priceStr = String.valueOf(price); if(priceStr.length() <= 8){ lackLength = 8 - priceStr.length(); for(int i = 0; i < lackLength; i++){ priceStr = "0" + priceStr; } } else{ priceStr = priceStr.substring( 0,8 ); } String directionStr = String.valueOf(direction); // String timeStr = Long.toString(createTime); return idStr + agentIdStr + priceStr + volumeStr + directionStr /*+ timeStr*/; }
5baf9240-1886-46ba-bd2e-fdfc3696380f
2
public static void main(String[] args) { long start = System.currentTimeMillis(); try { ObjectOutputStream outputStream = new ObjectOutputStream( new FileOutputStream("myBinaryIntegers.dat")); for (int i = 1; i<=1000000; i++){ outputStream.writeInt(i); } System.out.println("Numbers have been written to the file."); outputStream.close(); } catch(IOException e) { System.out.println("Problem with file output."); } long end = System.currentTimeMillis(); System.out.println("Took: " + ((end - start)) + "ms"); }
9bfeef62-b9d5-49ff-9590-c3f06991c5cc
6
public static long getZobristKey(Board board) { long zobristKey = 0L; for (int index = 0; index < 120; index++) { if ((index & 0x88) == 0) { int piece = board.boardArray[index]; if (piece > 0) // White piece { zobristKey ^= PIECES[Math.abs(piece) - 1][0][index]; } else if (piece < 0) // Black piece { zobristKey ^= PIECES[Math.abs(piece) - 1][1][index]; } } else index += 7; } zobristKey ^= W_CASTLING_RIGHTS[board.white_castle]; zobristKey ^= B_CASTLING_RIGHTS[board.black_castle]; if (board.enPassant != -1) zobristKey ^= EN_PASSANT[board.enPassant]; if (board.toMove == -1) zobristKey ^= SIDE; return zobristKey; }
b7749a8d-a0d2-4251-a782-a62bcefce884
6
@Override public Candidato alterar(IEntidade entidade) throws SQLException { if (entidade instanceof Candidato) { Candidato candidato = (Candidato) entidade; PessoaDao pdao = new PessoaDao(); pdao.alterar(candidato); String sql = "UPDATE candidato SET " + "id_pessoa = ?, " + "id_concurso = ?, " + "apto_prova_escrita = ?, " + "apto_prova_didatica = ?, " + "apto_prova_memorial = ?, " + "id_prova_escrita = ? " + "WHERE id_candidato = ?"; Connection connection = ConnectionFactory.getConnection(); PreparedStatement stmt = connection.prepareStatement(sql); stmt.setInt(1, candidato.getIdPessoa()); stmt.setInt(2, candidato.getConcurso().getIdConcurso()); if (candidato.getAptoProvaEscrita() != null) { stmt.setBoolean(3, candidato.getAptoProvaEscrita()); } else { stmt.setString(3, null); } if (candidato.getAptoProvaDidatica() != null) { stmt.setBoolean(4, candidato.getAptoProvaDidatica()); } else { stmt.setString(4, null); } if (candidato.getAptoProvaMemorial() != null) { stmt.setBoolean(5, candidato.getAptoProvaMemorial()); } else { stmt.setString(5, null); } if (candidato.getProvaEscrita() != null) { stmt.setInt(6, candidato.getProvaEscrita().getIdProvaEscrita()); } else { stmt.setString(6, null); } stmt.setInt(7, candidato.getIdCandidato()); System.out.println("SQL"+stmt.toString()); if (stmt.executeUpdate() == 1) { return candidato; } } return null; }
e2daf5b9-3bcb-4630-8d89-f3495bbcbcac
3
public void create_table(String tableName, ArrayList<String> headers, ArrayList<Integer> types, ArrayList<Integer> sizes, ArrayList<Boolean> isNullAble, String objectIdColumnName) throws SeException{ _log.info("Create table ... "+tableName); SeTable table = new SeTable(conn, (conn.getUser()+"."+tableName)); int numOfCols = headers.size(); SeColumnDefinition colDefs[] = new SeColumnDefinition[numOfCols]; for(int i=0; i<headers.size(); i++){ colDefs[i] = new SeColumnDefinition(headers.get(i), types.get(i), sizes.get(i), 0, isNullAble.get(i)); } table.create( colDefs, "DEFAULTS" ); if(objectIdColumnName!=null){ SeRegistration registration = null; registration = new SeRegistration( conn, tableName); // Check if table has been registered as ArcSDE maintained table. // If already registered return to main. if( registration.getRowIdColumnType() == SeRegistration.SE_REGISTRATION_ROW_ID_COLUMN_TYPE_SDE ) return; // Update the table's registration to give it an ArcSDE maintained row id. registration.setRowIdColumnName(objectIdColumnName); registration.setRowIdColumnType(SeRegistration.SE_REGISTRATION_ROW_ID_COLUMN_TYPE_SDE); registration.alter(); } }
0c26fe7c-2294-4464-b785-deffade3ac10
9
private static boolean stack_boolean(CallFrame frame, int i) { Object x = frame.stack[i]; if (x == Boolean.TRUE) { return true; } else if (x == Boolean.FALSE) { return false; } else if (x == UniqueTag.DOUBLE_MARK) { double d = frame.sDbl[i]; return d == d && d != 0.0; } else if (x == null || x == Undefined.instance) { return false; } else if (x instanceof Number) { double d = ((Number)x).doubleValue(); return (d == d && d != 0.0); } else if (x instanceof Boolean) { return ((Boolean)x).booleanValue(); } else { return ScriptRuntime.toBoolean(x); } }
c02b84f7-9e11-4012-849c-dd5a276326d4
4
LinkedList<Review> getReviews(String reviewer, String isbn, int amount) throws SQLException { LinkedList<String> select = new LinkedList<String>(); select.add("*"); LinkedList<String> from = new LinkedList<String>(); from.add("Reviews"); LinkedList<Pair<String, String>> whereClauses = new LinkedList<Pair<String, String>>(); if (!reviewer.isEmpty()) { whereClauses.add(new Pair<String, String>("Reviewer=?", reviewer)); } if (!isbn.isEmpty()) { whereClauses.add(new Pair<String, String>("ISBN=?", isbn)); } LinkedList<String> whereConjunctions = new LinkedList<String>(); if (whereClauses.size() == 2) { whereConjunctions.add("AND"); } Pair<String, LinkedList<String>> orderBy = new Pair<String, LinkedList<String>>("(SELECT AVG(SCORE) " + "FROM Usefulness WHERE Usefulness.Reviewer = Reviews.Reviewer AND Usefulness.ISBN = Reviews.ISBN)", new LinkedList<String>()); String orderDirection = "DESC"; ResultSet resultSet = executeDynamicQuery(select, from, whereClauses, whereConjunctions, orderBy, orderDirection, amount); LinkedList<Review> result = new LinkedList<Review>(); while (resultSet.next()) { result.add(new Review(resultSet.getString(1), resultSet.getString(2), resultSet.getInt(3), resultSet.getDate(4), resultSet.getString(5))); } return result; }
e5b2c222-99ce-4de7-ae8b-8acea059c8c1
2
public static double getMultiplier(){ double value = (targetFPS/currentFPS) * multiplier; if(Double.isInfinite(value) || Double.isNaN(value)){ return 1; } return value; }
08624d2f-f9c1-4df4-846e-b1170183abbf
2
private static boolean isPrimitive(Class<?> c) { if (c.isPrimitive()) { return true; } else { return primitives.contains(c); } }
e485cc81-a886-4c63-8a98-d233f625601c
9
public boolean containsUnionThatContains( K key ) { List<K> all = new ArrayList<K>(); for( Map.Entry<K, List<V>> e : mMap.entrySet() ) { int c0 = mComp.compareMinToMax( key, e.getKey() ); int c1 = mComp.compareMinToMax( e.getKey(), key ); if( c0 < 0 && c1 < 0 ) { all.add( e.getKey() ); } else if( c1 >= 0 ) { break; } } if( all.isEmpty() || mComp.compareMins( key, all.get( 0 ) ) < 0 ) { return false; } K left = all.get( 0 ); for( int i = 1; i < all.size(); i++ ) { K current = all.get( i ); int c0 = mComp.compareMinToMax( current, left ); int c1 = mComp.compareMaxes( current, left ); if( c0 > 0 ) { continue; } if( c1 > 0 ) { left = current; } } return mComp.compareMaxes( left, key ) >= 0; }
5dcc7a0d-0e6a-4a35-919d-5d48b135bba5
2
public boolean CheckGameComplete() { return (this.blackPieces==0 || this.whitePieces == 0)?true:false; }
3e53aaac-b497-4605-b96e-ea1bc51b606a
1
public JSONObject getJSONObject(String key) throws JSONException { Object object = get(key); if (object instanceof JSONObject) { return (JSONObject)object; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); }
33a24e5a-7111-4d38-bab4-ba277644bcce
7
public double[] distributionForInstance (Instance instance) throws Exception { if (!getDoNotReplaceMissingValues()) { m_ReplaceMissingValues.input(instance); m_ReplaceMissingValues.batchFinished(); instance = m_ReplaceMissingValues.output(); } if (getConvertNominalToBinary() && m_NominalToBinary != null) { m_NominalToBinary.input(instance); m_NominalToBinary.batchFinished(); instance = m_NominalToBinary.output(); } if (m_Filter != null) { m_Filter.input(instance); m_Filter.batchFinished(); instance = m_Filter.output(); } Object x = instanceToArray(instance); double v; double[] result = new double[instance.numClasses()]; if (m_ProbabilityEstimates) { if (m_SVMType != SVMTYPE_L2_LR) { throw new WekaException("probability estimation is currently only " + "supported for L2-regularized logistic regression"); } int[] labels = (int[])invokeMethod(m_Model, "getLabels", null, null); double[] prob_estimates = new double[instance.numClasses()]; v = ((Integer) invokeMethod( Class.forName(CLASS_LINEAR).newInstance(), "predictProbability", new Class[]{ Class.forName(CLASS_MODEL), Array.newInstance(Class.forName(CLASS_FEATURENODE), Array.getLength(x)).getClass(), Array.newInstance(Double.TYPE, prob_estimates.length).getClass()}, new Object[]{ m_Model, x, prob_estimates})).doubleValue(); // Return order of probabilities to canonical weka attribute order for (int k = 0; k < prob_estimates.length; k++) { result[labels[k]] = prob_estimates[k]; } } else { v = ((Integer) invokeMethod( Class.forName(CLASS_LINEAR).newInstance(), "predict", new Class[]{ Class.forName(CLASS_MODEL), Array.newInstance(Class.forName(CLASS_FEATURENODE), Array.getLength(x)).getClass()}, new Object[]{ m_Model, x})).doubleValue(); assert (instance.classAttribute().isNominal()); result[(int) v] = 1; } return result; }
088b2b4c-50cc-4f47-afbb-06054ee9dba6
9
public void setup() { if((MODUS & CODEX_MODE) == CODEX_MODE) size((int) (displayWidth*(2/3f)),displayHeight,render); else if((MODUS & PRESENT_MODE) == PRESENT_MODE) size(displayWidth,displayHeight, render); else size(alternativeWidth,alternativeHeight, render); if(render == P2D) ((PGraphics2D)g).textureWrap(Texture.REPEAT); frameRate(60); try { new Robot().mousePress(InputEvent.BUTTON1_DOWN_MASK); } catch (AWTException e) { // TODO Auto-generated catch block e.printStackTrace(); } if((MODUS & CODE_MODE) == CODE_MODE) { frame.setAlwaysOnTop(true); frame.addComponentListener(new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { super.componentMoved(e); Point newLocation = frame.getLocationOnScreen(); newLocation.x += frame.getWidth(); viewer.setLocation(newLocation); }} ); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); if((MODUS & CODEX_MODE) == CODEX_MODE) frame.setLocation(0,0); else frame.setLocation(dim.width/2-alternativeWidth,dim.height/2-alternativeHeight/2); } hint(DISABLE_DEPTH_TEST); hint(DISABLE_DEPTH_SORT); hint(DISABLE_OPENGL_ERROR_REPORT); noCursor(); shaders[0] = new GLShader_Instance[] { // shadertoy new Deform(this,SHADERTOY_PLANE+"Deform"), new Monjori(this,SHADERTOY_PLANE+"Monjori"), new Star(this,SHADERTOY_PLANE+"Star"), new Twist(this,SHADERTOY_PLANE+"Twist") , new Kaleidoscope(this,SHADERTOY_PLANE+"Kaleidoscope"), new ZInvert(this,SHADERTOY_PLANE+"ZInvert"), new Tunnel(this,SHADERTOY_PLANE+"Tunnel"), new Relieftunnel(this,SHADERTOY_PLANE+"Relieftunnel"), new Squaretunnel(this,SHADERTOY_PLANE+"Squaretunnel"), new Fly(this,SHADERTOY_PLANE+"Fly"), new shadertoy.plane_deformations.Pulse(this,SHADERTOY_PLANE+"Pulse"), new Radialblur(this,SHADERTOY_2D+"Radialblur"), new Motionblur(this,SHADERTOY_2D+"Motionblur"), new Pepa(this,SHADERTOY_2D+"Pepa"), new Postprocessing(this,SHADERTOY_2D+"Postprocessing"), new Julia(this,SHADERTOY_2D+"Julia"), new Mandel(this,SHADERTOY_2D+"Mandel"), // Multitexture missing new shadertoy.two_dimensional.Flower(this,SHADERTOY_2D+"Flower"), new Heart(this,SHADERTOY_2D+"Heart"), new Sierpinski(this,SHADERTOY_2D+"Sierpinski"), new Metablob(this,SHADERTOY_2D+"Metablob"), new Plasma(this,SHADERTOY_2D+"Plasma"), new Shapes(this,SHADERTOY_2D+"Shapes"), new Water(this,SHADERTOY_2D+"Water"), new Apple(this,SHADERTOY_3D+"Apple"), new Shadertoy_704(this,SHADERTOY_3D+"704"), new Landscape(this,SHADERTOY_3D+"Landscape"), new Totheroadofribbon(this,SHADERTOY_3D+"Totheroadofribbon"), new Chocolux(this,SHADERTOY_3D+"Chocolux"), new Nautilus(this,SHADERTOY_3D+"Nautilus"), new Mengersponge(this,SHADERTOY_3D+"Mengersponge"), new Clod(this,SHADERTOY_3D+"Clod"), //new Earth(this,SHADERTOY_3D+"Earth"), -> OpenGL error 1282 at bot endDraw(): invalid operation new Slisesix(this,SHADERTOY_3D+"Slisesix"), new Sult(this,SHADERTOY_3D+"Sult"), new Valleyball(this,SHADERTOY_3D+"Valleyball"), new Kinderpainter(this,SHADERTOY_3D+"Kinderpainter"), new Red(this,SHADERTOY_3D+"Red"), new Quaternion(this,SHADERTOY_3D+"Quaternion"), new Quaternion(this,SHADERTOY_3D+"Lunaquatic"), new Metatunnel(this,SHADERTOY_3D+"Metatunnel"), new Droid(this,SHADERTOY_3D+"Droid"), new Disco(this,SHADERTOY_3D+"Disco"), new Mandelbulb(this,SHADERTOY_3D+"Mandelbulb"), new Leizex(this,SHADERTOY_3D+"Leizex") }; shaders[1] = new GLShader_Instance[] { // GLSLSANDBOX new Compilation(this,GLSLSANDBOX+"Compilation"), new Meteors(this,GLSLSANDBOX+"Meteors"), new Continua(this,GLSLSANDBOX+"Continua"), new Hills(this,GLSLSANDBOX+"Hills"), new Flags(this,GLSLSANDBOX+"Flags"), new Timewarp(this,GLSLSANDBOX+"Timewarp"), // -> flickering new Green(this,GLSLSANDBOX+"Green"), new City(this,GLSLSANDBOX+"City"), new Street(this,GLSLSANDBOX+"Street"), //new Blankslate(this,GLSLSANDBOX+"Blankslate"), -> same as Timewarp, wrong rendering new Sandbox(this,GLSLSANDBOX+"Sandbox"), new Planedeformation(this,GLSLSANDBOX+"Planedeformation"), new Blackandwhite(this,GLSLSANDBOX+"Blackandwhite"), new Jungle(this,GLSLSANDBOX+"Jungle"), new Terrain(this,GLSLSANDBOX+"Terrain"), new Blobs(this,GLSLSANDBOX+"Blobs"), new Blocks(this,GLSLSANDBOX+"Blocks"), new Startunnel(this,GLSLSANDBOX+"Startunnel"), new Leds(this,GLSLSANDBOX+"Leds"), new Raymarcher(this,GLSLSANDBOX+"Raymarcher"), // -> bla bla...seee above new Fish(this,GLSLSANDBOX+"Fish"), new Tigrou(this,GLSLSANDBOX+"Tigrou"), new Sunsetonthesea(this,GLSLSANDBOX+"Sunsetonthesea"), new Blobneon(this,GLSLSANDBOX+"Blobneon"), new Clock(this,GLSLSANDBOX+"Clock"), new Cloudy(this,GLSLSANDBOX+"Cloudy"), new Torus(this,GLSLSANDBOX+"Torus"), new Cnoise(this,GLSLSANDBOX+"Cnoise"), new Hyberbolicspace(this,GLSLSANDBOX+"Hyberbolicspace"), new Coffeeandtable(this,GLSLSANDBOX+"Coffeeandtable"), // -> result different to WebGL new Shabtronic(this,GLSLSANDBOX+"Shabtronic"), new Minecraft(this,GLSLSANDBOX+"Minecraft"), new Starspace(this,GLSLSANDBOX+"Starspace"), // -> flickering new Pacman(this,GLSLSANDBOX+"Pacman"), new Pnoise(this,GLSLSANDBOX+"Pnoise"), new Bubblegum(this,GLSLSANDBOX+"Bubblegum"), new glslsandbox.Julia(this,GLSLSANDBOX+"Julia"), new Colourtunnel(this,GLSLSANDBOX+"Colourtunnel"), new Sinus(this,GLSLSANDBOX+"Sinus"), new Rects(this,GLSLSANDBOX+"Rects"), // -> flickering new Blurspline(this,GLSLSANDBOX+"Blurspline"), new Lofiterrain(this,GLSLSANDBOX+"Lofiterrain"), new Voronoi(this,GLSLSANDBOX+"Voronoi"), // -> Mouse inverted new Yellowandblue(this,GLSLSANDBOX+"Yellowandblue"), new Warp(this,GLSLSANDBOX+"Warp"), //new Boy(this,GLSLSANDBOX+"Boy"), -> array offset argument "infoLog_offset" (0) equals or exceeds array length (0) new Spheres(this,GLSLSANDBOX+"Spheres"), // -> noisy new glslsandbox.Puls(this,GLSLSANDBOX+"Puls"), new Rileycorpsefinder(this,GLSLSANDBOX+"Rileycorpsefinder"), new Chains(this,GLSLSANDBOX+"Chains"), //new Gameoflife(this,GLSLSANDBOX+"Gameoflife"), -> backbuffer new Light(this,GLSLSANDBOX+"Light"), new Chainsandgears(this,GLSLSANDBOX+"Chainsandgears"), new Bouncingspheres(this,GLSLSANDBOX+"Bouncingspheres"), new Eggs(this,GLSLSANDBOX+"Eggs"), new Gifts(this,GLSLSANDBOX+"Gifts"), new Anotherworld(this,GLSLSANDBOX+"Anotherworld"), new Flower(this,GLSLSANDBOX+"Flower"), // new Christmastree(this,GLSLSANDBOX+"Christmastree"), -> rendering not correct new Rings(this,GLSLSANDBOX+"Rings"), new Rock(this,GLSLSANDBOX+"Rock"), // is it correct?? new Autumntrees(this,GLSLSANDBOX+"Autumntrees"), // little bit flickering new Lighttexture(this,GLSLSANDBOX+"Lighttexture"), //new Redjulia(this,GLSLSANDBOX+"Redjulia"), -> not working new Train(this,GLSLSANDBOX+"Train"), new Fireblobs(this,GLSLSANDBOX+"Fireblobs"), new Movingup(this,GLSLSANDBOX+"Movingup"), new Magister(this,GLSLSANDBOX+"Magister"), new Zebra(this,GLSLSANDBOX+"Zebra"), new Wave(this,GLSLSANDBOX+"Wave"), }; if(!indexChanged) { /* shaderVertIndex = shaders.length-1; shaderHorizIndex = shaders[shaderVertIndex].length-1; */ shaderVertIndex = 0; shaderHorizIndex = 0; } if((MODUS & CODE_MODE) == CODE_MODE) { viewer = new GLSLViewer(this); if((MODUS & CODEX_MODE) == CODEX_MODE) { viewer.setUndecorated(true); viewer.setOpacity(0.8f); Dimension dim = frame.getSize(); viewer.setSize((int) (dim.width*(2/3f)),dim.height); } else { viewer.setSize(frame.getSize()); } viewer.setVisible(true); viewer.setAlwaysOnTop(true); } switchShader(); }
8a1a2bb6-79ad-410b-876d-808d89dec476
4
public void holes_to_win(){ for (int i = 0; i < hoyde; i++) { for (int j = 0; j < bredde; j++) { if((map[i][j] == target) ||(map[i][j] == box_on_target)){ holes++; } } } }
f5020b5a-4a72-4a16-b0bd-76f4d55f0569
8
public void helper (String defName, SemanticAction node) { if( Compiler.extendedDebug ){ System.out.println( node.getName() ); } if( node.getBranches().isEmpty() ){ if(node.getType() == SemanticAction.TYPE.INTEGER || node.getType() == SemanticAction.TYPE.BOOLEAN ){ return; } else { if( !symbolTable.compare( defName, node ) ){ System.out.println( "No formal parameter: " + node + " inside defintion of " + defName ); } } } if( node.getType() == SemanticAction.TYPE.FUNCTION && !symbolTable.checkFunctionCall( node.getName() ) ){ System.out.println( "No function definition for call to: " + node.getName() ); } for( SemanticAction branch: node.getBranches() ) { helper( defName, branch ); } }
ba378c3d-f93e-474e-8929-0cd1c60e47b1
7
public static <E extends Comparable<E>> void sortWithQueue(Stack<E> stack) { if(stack==null || stack.size()==0) { return; } Queue<E> auxQueue = new LinkedList<E>(); while(!stack.isEmpty()) { E item = stack.pop(); int auxQSize = auxQueue.size(); while(auxQSize>0 && auxQueue.peek().compareTo(item)<=0) { auxQueue.offer(auxQueue.poll()); auxQSize--; } auxQueue.offer(item); while(auxQSize>0) { auxQueue.offer(auxQueue.poll()); auxQSize--; } } while(!auxQueue.isEmpty()) { stack.push(auxQueue.poll()); } }
39ddb2b4-c5e6-4618-a2ea-7fdd2da5aab7
3
private boolean checkSingleRow(int z) { for(int x = 0; x < length; x++) { for(int y = 0; y < width; y++) { if(cubes[x][y][z] == Piece.NOTHING) return false; } } return true; }
a12ba800-4e5b-428c-a68f-20b0a53d30de
2
private void initAllItems() { allItems.clear(); // allItems.addAll(resource.findAllByGraph()); if (selectedSlot != null && selectedSlot.getSlotType() == ViewportSlotType.PRESENTATIONSTREAM) { // final PresentationStream ps = controller.getPresentationStreamForViewport(viewport); allItems.addAll(resource.findAllItemsForPresentationStream(selectedSlot.getPresentationStream())); } }
db0208c0-92c0-4c9f-8442-cacfddc29eeb
7
@EventHandler public void WitherConfusion(EntityDamageByEntityEvent event) { Entity e = event.getEntity(); Entity damager = event.getDamager(); String world = e.getWorld().getName(); boolean dodged = false; Random random = new Random(); double randomChance = plugin.getZombieConfig().getDouble("Wither.Nausea.DodgeChance") / 100; final double ChanceOfHappening = random.nextDouble(); if (ChanceOfHappening >= randomChance) { dodged = true; } if (damager instanceof WitherSkull) { WitherSkull a = (WitherSkull) event.getDamager(); LivingEntity shooter = a.getShooter(); if (plugin.getWitherConfig().getBoolean("Wither.Nausea.Enabled", true) && shooter instanceof Wither && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) { Player player = (Player) e; player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, plugin.getWitherConfig().getInt("Wither.Nausea.Time"), plugin.getWitherConfig().getInt("Wither.Nausea.Power"))); } } }
bee2a00d-4d47-483d-82e8-47ace46bcff9
1
public void setShutdownMenuFontstyle(Fontstyle fontstyle) { if (fontstyle == null) { this.shutdownMenuFontStyle = UIFontInits.SHDMENU.getStyle(); } else { this.shutdownMenuFontStyle = fontstyle; } somethingChanged(); }
6be63a89-57aa-49ad-b311-c88e5214236f
4
public void usingBang() { visibleScreen.getSetup().getRound().getCheckerForPlayedCard().playingCard(visibleScreen.getIndex()); if (visibleScreen.getSetup().getRound().getCheckerForPlayedCard().checkBarrel()) { if (visibleScreen.getSetup().getRound().getPlayerInTurn().getAvatar().toString().equals("Slab The Killer")) { visibleScreen.getSetup().getRound().getCheckerForAvatarSpeciality().checkJourdonnais(); } else if (!visibleScreen.getSetup().getRound().getPlayerInTurn().getLastCheckedCard().getSuit().equals("Hearts")) { visibleScreen.getSetup().getRound().getCheckerForAvatarSpeciality().checkJourdonnais(); } visibleScreen.barrelScreen(); } else if (visibleScreen.getSetup().getRound().getCheckerForAvatarSpeciality().checkJourdonnais()) { visibleScreen.jourdonnaisScreen(); } else { visibleScreen.attackingPlayerPleaseLookAway(); } }
69c26869-fe91-43b4-8f40-4916e30b2d0f
3
public void leaveChannel(ChatChannel channel, User user){ try { Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); String url = "jdbc:derby:" + DBName; Connection connection = DriverManager.getConnection(url); Statement statement = connection.createStatement(); String deleteStatement = "DELETE FROM userchatrelations WHERE userID=" + user.getID() + " " + "AND channelID = " + channel.getChannelID(); statement.executeUpdate(deleteStatement); if(channel.getChannelType().equals("custom")){ String selectStatement = "SELECT * FROM userchatrelations WHERE channelID = " + channel.getChannelID(); ResultSet rs = statement.executeQuery(selectStatement); if(!rs.next()){ String deleteMessagesStatement = "DELETE FROM chatmessages WHERE channel_cid = " + channel.getChannelID(); statement.executeUpdate(deleteMessagesStatement); String deleteChannelStatement = "DELETE FROM chatchannels WHERE channelID = " + channel.getChannelID(); statement.executeUpdate(deleteChannelStatement); } } statement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } }
5131fb99-1aac-47c7-a63c-853fa31b1423
5
public PrivateKey decodePrivateKey(byte[] k) { // magic if (k[0] != Registry.MAGIC_RAW_DSS_PRIVATE_KEY[0] || k[1] != Registry.MAGIC_RAW_DSS_PRIVATE_KEY[1] || k[2] != Registry.MAGIC_RAW_DSS_PRIVATE_KEY[2] || k[3] != Registry.MAGIC_RAW_DSS_PRIVATE_KEY[3]) { throw new IllegalArgumentException("magic"); } // version if (k[4] != 0x01) { throw new IllegalArgumentException("version"); } int i = 5; int l; byte[] buffer; // p l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8 | (k[i++] & 0xFF); buffer = new byte[l]; System.arraycopy(k, i, buffer, 0, l); i += l; BigInteger p = new BigInteger(1, buffer); // q l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8 | (k[i++] & 0xFF); buffer = new byte[l]; System.arraycopy(k, i, buffer, 0, l); i += l; BigInteger q = new BigInteger(1, buffer); // g l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8 | (k[i++] & 0xFF); buffer = new byte[l]; System.arraycopy(k, i, buffer, 0, l); i += l; BigInteger g = new BigInteger(1, buffer); // x l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8 | (k[i++] & 0xFF); buffer = new byte[l]; System.arraycopy(k, i, buffer, 0, l); i += l; BigInteger x = new BigInteger(1, buffer); return new DSSPrivateKey(p, q, g, x); }
4927be7f-3ec5-4864-85f4-6e90269806d3
0
@Id @Column(name = "percent") public double getPercent() { return percent; }
07f27d16-85a8-41d0-8cca-88298407555a
7
public static void main(String[] args) { System.out.print("Enter size of grid: "); int n = scanner.nextInt(); StdDraw.setScale(-n, n); StdDraw.setPenRadius((0.9*size)/((double)n*2+1)); final int[] pos = {0,0}; while (true) { System.out.println("Position = (" + pos[x] + "," + pos[y]+ ")"); if(Math.abs(pos[x]) > n || Math.abs(pos[y]) > n) break; StdDraw.point(pos[x], pos[y]); steps++; switch (random.nextInt(4)) { case 0: pos[y]++; // Right break; case 1: pos[x]++; // Up break; case 2: pos[y]--; // Left break; case 3: pos[x]--; // Down break; } } System.out.println("\nTotal number of steps = " + steps); }
9e3b375a-46e2-4c1a-b2e3-81b611d6a4f2
5
@Override public int decidePlay(int turn, int drawn, boolean fromDiscard){ //If it gives us a bad score, take from draw pile if (!fromDiscard || cache_turn != turn){ cache_pos = findBestMove(turn, drawn); //If it hurts our score, we'll discard if (last_score.output <= base_score.output) cache_pos = -1; } //Add training data if (TRAIN_score){ if (old_score != null){ old_score.output = last_score.output; train_data.add(old_score); } old_score = last_score; } return cache_pos; }
9ad27a07-ea1e-4c51-b0b4-1d0f5283fc2c
2
public final List<Direction> getDirectionsToMoveTo(Element element) { final List<Direction> directions = new ArrayList<Direction>(); for (Direction direction : Direction.values()) if (canMoveElement(element, direction)) directions.add(direction); return directions; }
7ff49ba0-b7d1-4b20-8e02-f55131d1f3da
2
@Override synchronized int vider() { int compte = 0; for (int i = 0; i < vehicules.length; i = i + 1) { compte = compte + (vehicules[i] == null ? 0 : 1); vehicules[i] = null; } return compte; }
e8ac06b7-5f40-40df-ad66-4a953949600c
2
private static Connection initConnection() { Connection thisCon = null; try { Class.forName("com.mysql.jdbc.Driver"); thisCon = DriverManager.getConnection("jdbc:mysql://" + server, account ,password); Statement stmt = thisCon.createStatement(); stmt.executeQuery("USE " + database); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return thisCon; }
af47139c-f293-495a-a0e8-7c1153cff6bc
0
public void setAge(long age) { this.age = age; }
bf20375c-bc02-4b36-9694-25a7aa72bb4a
5
public Edge getEdgeWithChunk(Chunk another){ for(Edge edge : this.edges){ if((edge.getIdA() == this.id && edge.getIdB() == another.getId()) || (edge.getIdB() == this.id && edge.getIdA() == another.getId())){ return edge; } } return null; }
d028f518-302c-4254-9a1e-42b836c603a9
6
public static HashMap<String, HashMap<String, Integer>> getMap(String filePath) throws Exception { HashMap<String, HashMap<String, Integer>> map = new HashMap<String, HashMap<String,Integer>>(); BufferedReader reader = filePath.toLowerCase().endsWith("gz") ? new BufferedReader(new InputStreamReader( new GZIPInputStream( new FileInputStream( filePath)))) : new BufferedReader(new FileReader(new File(filePath ))); String nextLine = reader.readLine(); int numDone =0; while(nextLine != null) { StringTokenizer sToken = new StringTokenizer(nextLine, "\t"); String sample = sToken.nextToken().replace(".extendedFrags.fastatoRDP.txt.gz", ""); String taxa= sToken.nextToken(); int count = Integer.parseInt(sToken.nextToken()); if( sToken.hasMoreTokens()) throw new Exception("No"); HashMap<String, Integer> innerMap = map.get(sample); if( innerMap == null) { innerMap = new HashMap<String, Integer>(); map.put(sample, innerMap); } if( innerMap.containsKey(taxa)) throw new Exception("parsing error " + taxa); innerMap.put(taxa, count); nextLine = reader.readLine(); numDone++; if( numDone % 1000000 == 0 ) System.out.println(numDone); } return map; }
32581343-eb58-4b32-827c-12b4619a655c
6
public String retrieveXML(){ // create file chooser and ensure it displays in the center of the main window JFileChooser xmlBrowser = new JFileChooser(); //sets xml filter xmlBrowser.setFileFilter(new XMLFilter()); if(curDir!=null){ //if jFileChooser has been used before, load to previous directory xmlBrowser.setCurrentDirectory(curDir); } int returnVal = xmlBrowser.showOpenDialog(Gui.getContentPane()); if(returnVal == JFileChooser.APPROVE_OPTION){ xmlFilePath = xmlBrowser.getSelectedFile(); //get the selected filename curDir = xmlBrowser.getCurrentDirectory(); //save the last used directory String path = xmlFilePath.getAbsolutePath(); String fileExtension = path.substring(path.lastIndexOf(".")+1, path.length()); if(Debug.localXML)System.out.println(fileExtension); // Checks the file extension of the file selected, if it is not an XML file // a dialog box will appear informing the user that they have not selected // a valid xml presentation file. if(VALIDFILEEXTENSION.equals(fileExtension)){ SafetyNet.setPath(path); //set the path to be stored by config path = path.replace('\\', '/'); }else{ JOptionPane.showMessageDialog(Gui.getContentPane(), "A Valid XML Presentation File was not selected"); path = null; } //Test case to check current directory updates if(Debug.localXML)System.out.println("current directory is" + curDir); //Test case to check string of file. if(Debug.localXML)System.out.println("file path is" + path); return path; } else return null; }
427f04d2-ae66-4bf1-8eb8-342851e71714
4
@EventHandler public void onQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); ItemStack[] inv = player.getInventory().getContents(); ItemStack[] armor = player.getInventory().getArmorContents(); ItemStack is; for(int i = 0; i < inv.length; i++) { is = inv[i]; if(p.getTool().isSimilar(is)) { inv[i] = null; } } for(int i = 0; i < inv.length; i++) { is = inv[i]; if(p.getTool().isSimilar(is)) { armor[i] = null; } } player.getInventory().setContents(inv); player.getInventory().setArmorContents(armor); player.saveData(); }
b5931d6f-e6d3-400a-a461-63aabb41751d
2
@SuppressWarnings("unchecked") public static float[] restore1D(String findFromFile) { float[] dataSet = null; try { FileInputStream filein = new FileInputStream(findFromFile); ObjectInputStream objin = new ObjectInputStream(filein); try { dataSet = (float[]) objin.readObject(); } catch (ClassCastException cce) { cce.printStackTrace(); return null; } objin.close(); } catch (Exception ioe) { //ioe.printStackTrace(); System.out.println("NO resume: saver"); return null; } return dataSet; } // /////////// ////////////////////////////
c04da70f-b81f-484f-9ff3-691e4f9f9e1c
0
private CategoryDataset getDataSet() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(2221, "14-2-4", "80"); dataset.addValue(3245, "14-2-5", "81"); dataset.addValue(5342, "14-2-6", "34"); dataset.addValue(7653, "14-2-7", "56"); return dataset; }
36ab6cb1-08f1-4d4b-85f0-f20aed0841be
9
@Override public void run() { while (isRunning) { try { if (lcd instanceof LCDController) ((LCDController) lcd).aquireLock(); for (Button button : Button.values()) { if (button.isButtonPressed(lcd.buttonsPressedBitmask())) { if (buttonDownTimes[button.getPin()] != 0) { continue; } buttonDownTimes[button.getPin()] = System.currentTimeMillis(); } else if (buttonDownTimes[button.getPin()] != 0) { if ((System.currentTimeMillis() - buttonDownTimes[button.getPin()]) > 15) { fireNotification(button); } buttonDownTimes[button.getPin()] = 0; } } if (lcd instanceof LCDController) ((LCDController) lcd).releaseLock(); } catch (IOException e) { Logger.getLogger("se.hirt.pi.adafruit").log(Level.SEVERE, "Could not get buttons bitmask!", e); } sleep(15); Thread.yield(); } }
3a56ed8d-ebee-4548-a042-75d02fabb3ab
0
public int getRowCount() { return variables.length; }
99a3a5fc-572c-4b9e-8688-47ed8b1a2795
8
public void addNewOrder(UserType type, Order newOrder) throws DbException { con = new Connector(DBCredentials.getInstance().getDBUserByType(type)); try { con.startTransaction(); String sql = "INSERT INTO \"Orders\" (user_id, start_date, end_date) VALUES (?, ?, ?);"; PreparedStatement st = con.prepareStatement(sql); st.setInt(1, newOrder.getUserid()); st.setDate(2, newOrder.getStartdate()); st.setDate(3, newOrder.getEnddate()); st.executeUpdate(); sql = "SELECT \"order_id\" FROM \"Orders\" ORDER BY \"order_id\" DESC LIMIT 1;"; st = con.prepareStatement(sql); ResultSet result = st.executeQuery(); int orderID = 0; if (result.next()) { orderID = result.getInt(1); } for (int i = 0; i < newOrder.getOrdereditems().size(); i++) { OrderedItem oi = newOrder.getOrdereditems().get(i); sql = "SELECT \n" + " \"Inventory\".available\n" + "FROM \n" + " public.\"Inventory\"\n" + "WHERE\n" + " \"Inventory\".item_id = ?;"; st = con.prepareStatement(sql); st.setInt(1, oi.itemid); result = st.executeQuery(); int available = 0; if (result.next()) { available = result.getInt(1); } if (available == 0) { throw new DbException("Twoje zamówienie zawiera niedostępne produkty!"); } sql = "UPDATE \"Inventory\" SET available = ? WHERE item_id = ?;"; st = con.prepareStatement(sql); st.setInt(1, available - oi.quantity); st.setInt(2, oi.itemid); st.executeUpdate(); sql = "INSERT INTO \"OrderedItems\" (item_id, quantity, order_id) VALUES (?, ?, ?);"; st = con.prepareStatement(sql); st.setInt(1, oi.itemid); st.setInt(2, oi.quantity); st.setInt(3, orderID); st.executeUpdate(); } con.commit(); } catch (SQLException ex) { Logger.getLogger(ModelInventory.class.getName()).log(Level.SEVERE, null, ex); try { con.rollback(); con.closeConnection(); throw new DbException(); } catch (SQLException ex1) { Logger.getLogger(ModelOrders.class.getName()).log(Level.SEVERE, null, ex1); throw new DbException(); } } catch (DbException e) { try { con.rollback(); con.closeConnection(); throw e; } catch (SQLException ex1) { Logger.getLogger(ModelOrders.class.getName()).log(Level.SEVERE, null, ex1); throw new DbException(); } } }
dd8c319f-2865-43e7-9c1d-6e260a256e87
1
@Override public RepairHandlePOA get() { if (poa_ == null) { poa_ = new DefaultRepairHandle(delegate_); } return poa_; }
4cedf175-e9d8-4860-bbd3-491e725504cd
1
@GET @Path("/v2.0/networks") @Produces({MediaType.APPLICATION_JSON, OpenstackNetProxyConstants.TYPE_RDF}) public Response listNetwork(@HeaderParam("Accept") String accept) throws MalformedURLException, IOException{ if (accept.equals(OpenstackNetProxyConstants.TYPE_RDF)){ String dataFromKB=NetworkOntology.listNetwork(); System.out.println(dataFromKB); System.out.println(accept); // XmlTester t=new XmlTester(); return Response.ok().status(200).header("Access-Control-Allow-Origin", "*").entity(dataFromKB).build(); } else{ //Send HTTP request and receive a list of Json content HttpURLConnection conn=HTTPConnector.HTTPConnect(new URL(this.URLpath), OpenstackNetProxyConstants.HTTP_METHOD_GET, null); String response=HTTPConnector.printStream(conn); Object result; result=(ExtendedNetwork) JsonUtility.fromResponseStringToObject(response, ExtendedNetwork.class); int responseCode=conn.getResponseCode(); HTTPConnector.HTTPDisconnect(conn); return Response.ok().status(responseCode).header("Access-Control-Allow-Origin", "*").entity(result).build(); } }
c21b37e0-5c1b-4f16-8b41-14ba4832ae57
9
public void actionPerformed(ActionEvent event) { if(event.getActionCommand().equals(info.getActionCommand())){ new NodeInfoDialog(parent, node); } else if(event.getActionCommand().equals(delete.getActionCommand())){ Runtime.removeNode(node); parent.redrawGUI(); } else if(event.getActionCommand().equals(showCoordinateCube.getActionCommand())) { parent.getGraphPanel().setNodeToDrawCoordinateCube(node); parent.repaint(); // need not repaint the graph, only the toppings } else if(event.getActionCommand().equals(hideCoordinateCube.getActionCommand())) { parent.getGraphPanel().removeNodeToDrawCoordinateCube(node); parent.repaint(); // need not repaint the graph, only the toppings } else { // try to execute a custom-command Method clickedMethod = methodsAndDescriptions.get(event.getActionCommand()); if(clickedMethod == null) { Main.fatalError("Cannot find method associated with menu item " + event.getActionCommand()); return; } try{ synchronized(parent.getTransformator()){ //synchronize it on the transformator to grant not to be concurrent with //any drawing or modifying action clickedMethod.invoke(node, new Object[0]); } } catch(InvocationTargetException e) { String text = ""; if(null != e.getCause()) { text = "\n\n" + e.getCause() + "\n\n" + e.getCause().getMessage(); } Main.minorError("The method '" + clickedMethod.getName() + "' has thrown an exception and did not terminate properly:\n" + e + text); } catch (IllegalArgumentException e) { Main.minorError("The method '" + clickedMethod.getName() + "' cannot be invoked without parameters:\n" + e + "\n\n" + e.getMessage()); } catch (IllegalAccessException e) { Main.minorError("The method '" + clickedMethod.getName() + "' cannot be accessed:\n" + e + "\n\n" + e.getMessage()); } parent.redrawGUI(); } }
27316f60-9816-43a3-be7a-9f43cf09b69e
0
public void setParent(ClusterNode parent) { this.parent = parent; }
ee70b7ad-095b-4e3b-835e-f88b48938412
5
@Override public boolean equals(final Object o) { boolean isEqual = false; if (o != null && getClass() == o.getClass()) { final Human h = (Human)o; isEqual = getName().equals(h.getName()) && getSacks() == h.getSacks() && getHealth() == h.getHealth() && getStrength() == h.getStrength(); } return isEqual; }
21ad1c8b-99ed-48c1-9006-cd2e6ce3f1b0
9
private int getNextStatesOfMaskByCharacter(int mask, Character ch) { int nextMask = 0; for (int i = 0; i < states.length; i++) { if ((mask & pow[i]) != 0 && states[i] != null) {//mask contain state i State state = states[i].getNextState(ch); if (state != null) { nextMask |= pow[state.getNumber()]; } { state = states[i].getNextState('e'); if (state != null) { boolean visited[] = new boolean[states.length]; for (int j = 0; j < states.length; j++) { visited[j] = false; } visited[i] = true; while (state != null) { if (visited[state.getNumber()]) { break; } visited[state.getNumber()] = true; if (state.getNextState(ch) != null) { nextMask |= pow[state.getNextState(ch).getNumber()]; break; } else { state = state.getNextState('e'); } } } } } } return nextMask; }
81ed9b73-6cdf-4bd1-9e2c-c4e2d4d63334
6
public List<String> validate(){ List<String> errors = new ArrayList<>(); if (!isValid(name, NAME_PATTERN)) { errors.add("Name is not valid"); } if (!isValid(lastName, NAME_PATTERN)) { errors.add("Last Name is not valid"); } if (!isValid(email, EMAIL_PATTERN)) { errors.add("Email is not valid"); } if (isValid(password, PASSWORD_PATTERN) && password == passwordConfirmation) { errors.add("Password is not valid"); } if (!isValid(birthDate, BIRTH_DATE_PATTERN)) { errors.add("Birth Date is not valid"); } return errors; }
6eb2ec90-5297-4a65-8dc2-782743e77c16
9
private String prepareTag(String tag) { if (tag.length() == 0) { throw new EmitterException("tag must not be empty"); } if ("!".equals(tag)) { return tag; } String handle = null; String suffix = tag; for (String prefix : tagPrefixes.keySet()) { if (tag.startsWith(prefix) && ("!".equals(prefix) || prefix.length() < tag.length())) { handle = prefix; } } if (handle != null) { suffix = tag.substring(handle.length()); handle = tagPrefixes.get(handle); } int end = suffix.length(); String suffixText = end > 0 ? suffix.substring(0, end) : ""; if (handle != null) { return handle + suffixText; } return "!<" + suffixText + ">"; }
8caf05b6-b828-4238-9047-b728727669c0
2
public void reset() { Random random = new Random(); for (int i = 0; i < layers.length; i++) { int layerInputs = neuronCount; if (i == 0) { layerInputs = inputCount; } layers[i] = new NeuronLayer(layerInputs, neuronCount, random); } outputLayer = new NeuronLayer(neuronCount, outputCount, random); }
6de0f9de-a686-4cc0-8608-edd0d867a9fa
1
private void startOutput(String fileName){ leavesNodeFile = new java.io.File(fileName + ".leavesNode.txt"); leavesContentFile = new java.io.File(fileName + ".leavesContent.txt"); try { leavesNodeFileWriter = new FileWriter(leavesNodeFile); leavesContentFileWriter = new FileWriter(leavesContentFile); leavesNodeFileWriter.write("開始時間: " + getRightNowTimeStr("/", ":", " ") + "\r\n"); leavesContentFileWriter.write("開始時間: " + getRightNowTimeStr("/", ":", " ") + "\r\n"); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
d78373a9-2890-47df-817c-0becae576224
6
public Deck() { // Generates ordered pair of 52 Cards int cardValue; int currHand; int boundary; for(int index = 3; index >= 0; index--) { currHand = 14; boundary = 2; while(currHand >= boundary) { suitValue = suit[index]; cardValue = currHand; switch(cardValue) { case 14: finalCardValue = "Ace"; break; case 13: finalCardValue = "King"; break; case 12: finalCardValue = "Queen"; break; case 11: finalCardValue = "Jack"; break; default: finalCardValue = Integer.toString(cardValue); break; } completeCard = this.toString(); deckStack.push(completeCard); currHand--; } } }
218a38c1-8d71-4cc5-b6c9-0303a7075183
5
@Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Rechnung)) { return false; } Rechnung other = (Rechnung) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; }
4a347077-7bff-4a1c-9cc5-994b92a97d23
4
private static long ggT(long a, long b) { while (true) { if (a > b) { a %= b; if (a == 0) return b; } else { b %= a; if (b == 0) return a; } } }
57903e65-ad9e-4e8e-b5a4-1e8ff1e746cd
4
public void propertyChange(PropertyChangeEvent e) { boolean update = false; String prop = e.getPropertyName(); //If the directory changed, don't show an image. if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) { file = null; update = true; //If a file became selected, find out which one. } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) { file = (File) e.getNewValue(); update = true; } //Update the preview accordingly. if (update) { thumbnail = null; if (isShowing()) { loadImage(); repaint(); } } }
66b4a733-747c-4f19-b924-f8ad57cf418f
1
public RegisteredListener[] getRegisteredListeners() { RegisteredListener[] handlers; while ((handlers = this.events) == null) bake(); // This prevents fringe cases of returning null return handlers; }
f59e27aa-b677-4858-bcbc-7ce4e24bc2da
7
@Override public final void tActionEvent(TActionEvent e) { Object eventSource = e.getSource(); if (eventSource == saveGenesButton) { Hub.geneIO.saveGenes( new Genes(geneEditorField.getText(), seedSizeSlider.getValue(), (int) redLeafSlider.getValue(), (int) greenLeafSlider.getValue(), (int) blueLeafSlider.getValue()), saveNameField.getText()); } else if (eventSource == loadGenesButton) { JFileChooser chooser = new JFileChooser(saveDirectory); int returnVal = chooser.showOpenDialog(getObserver()); if (returnVal == JFileChooser.APPROVE_OPTION) { BufferedReader in = null; try { File geneFile = new File(saveDirectory + "//" + chooser.getSelectedFile().getName()); in = new BufferedReader(new FileReader(geneFile)); saveNameField.setText(chooser.getSelectedFile().getName().substring(0, chooser.getSelectedFile().getName().length() - 4)); geneEditorField.setText(readStringFromLine(in.readLine())); seedSizeSlider.setValue(readValueFromLine(in.readLine())); redLeafSlider.setValue(readValueFromLine(in.readLine())); greenLeafSlider.setValue(readValueFromLine(in.readLine())); blueLeafSlider.setValue(readValueFromLine(in.readLine())); } catch (Exception ex) {} finally { try { in.close(); } catch (IOException ex) { ex.printStackTrace(); } } updateExamplePlant(); } } else if (eventSource == openGenesFolderButton) Hub.geneIO.openFolder(); else if (eventSource == mainMenuButton) changeRenderableObject(Hub.menu); }
30eaa3ab-1e56-446c-91db-92fb5ed67cc3
2
private void displayAttacks(){ // this.jPanel1.setVisible(false); // this.jPanel2.setVisible(true); if (this.character.getAttacks() != null){ DefaultListModel listModel = new DefaultListModel(); for(Attack attack : this.character.getAttacks()){ listModel.addElement(attack.getDisplay()); } this.jList1.setModel(listModel); } }
13024af4-b00a-4286-8864-4a3f00093276
9
private void addInLines(StringBounder stringBounder, String s) { if (maxMessageSize == 0) { addSingleLine(s); } else if (maxMessageSize > 0) { final StringTokenizer st = new StringTokenizer(s, " ", true); final StringBuilder currentLine = new StringBuilder(); while (st.hasMoreTokens()) { final String token = st.nextToken(); final double w = getTextWidth(stringBounder, currentLine + token); if (w > maxMessageSize) { addSingleLineNoSpace(currentLine.toString()); currentLine.setLength(0); if (token.startsWith(" ") == false) { currentLine.append(token); } } else { currentLine.append(token); } } addSingleLineNoSpace(currentLine.toString()); } else if (maxMessageSize < 0) { final StringBuilder currentLine = new StringBuilder(); for (int i = 0; i < s.length(); i++) { final char c = s.charAt(i); final double w = getTextWidth(stringBounder, currentLine.toString() + c); if (w > -maxMessageSize) { addSingleLineNoSpace(currentLine.toString()); currentLine.setLength(0); if (c != ' ') { currentLine.append(c); } } else { currentLine.append(c); } } addSingleLineNoSpace(currentLine.toString()); } }
6da384d7-e662-4aa0-9fb5-babb6645b9f8
8
public int getLandPrice(Tile tile) { Player nationOwner = tile.getOwner(); int price = 0; if (nationOwner == null || nationOwner == this) { return 0; // Freely available } else if (tile.getSettlement() != null) { return -1; // Not for sale } else if (nationOwner.isEuropean()) { if (tile.getOwningSettlement() != null && tile.getOwningSettlement().getOwner() == nationOwner) { return -1; // Nailed down by a European colony } else { return 0; // Claim abandoned or only by tile improvement } } // Else, native ownership for (GoodsType type : getSpecification().getGoodsTypeList()) { if (type == getSpecification().getPrimaryFoodType()) { // Only consider specific food types, not the aggregation. continue; } price += tile.potential(type, null); } price *= getSpecification().getIntegerOption("model.option.landPriceFactor").getValue(); price += 100; return (int) applyModifier(price, "model.modifier.landPaymentModifier", null, getGame().getTurn()); }
cc1bc75e-d5a7-43a5-9387-da232b45baa8
0
public FrameWithPanel(String title) { super(title); }
ad886281-d6e3-4147-94f8-fa2616ae43b5
3
public int calcTotal(){ int total = 0; for(int i=1; i<=this.five; i++){ total+=5; } for(int i=1; i<=this.ten; i++){ total+=10; } for(int i=1; i<=this.twenty; i++){ total+=20; } return total; }
812fbc48-baa5-425e-8357-fbd1245c78fa
7
private boolean _decompose() { double h[] = QH.data; for( int k = 0; k < N-2; k++ ) { // find the largest value in this column // this is used to normalize the column and mitigate overflow/underflow double max = 0; for( int i = k+1; i < N; i++ ) { // copy the householder vector to vector outside of the matrix to reduce caching issues // big improvement on larger matrices and a relatively small performance hit on small matrices. double val = u[i] = h[i*N+k]; val = Math.abs(val); if( val > max ) max = val; } if( max > 0 ) { // -------- set up the reflector Q_k double tau = 0; // normalize to reduce overflow/underflow // and compute tau for the reflector for( int i = k+1; i < N; i++ ) { double val = u[i] /= max; tau += val*val; } tau = Math.sqrt(tau); if( u[k+1] < 0 ) tau = -tau; // write the reflector into the lower left column of the matrix double nu = u[k+1] + tau; u[k+1] = 1.0; for( int i = k+2; i < N; i++ ) { h[i*N+k] = u[i] /= nu; } double gamma = nu/tau; gammas[k] = gamma; // ---------- multiply on the left by Q_k QrHelperFunctions.rank1UpdateMultR(QH,u,gamma,k+1,k+1,N,b); // ---------- multiply on the right by Q_k QrHelperFunctions.rank1UpdateMultL(QH,u,gamma,0,k+1,N); // since the first element in the householder vector is known to be 1 // store the full upper hessenberg h[(k+1)*N+k] = -tau*max; } else { gammas[k] = 0; } } return true; }
3b252680-c6c3-4517-a5a5-05444fa985c1
3
static public void copyFile(String path, String filename, InputStream content) { File file = new File("plugins" + path, filename); try { if(!file.exists()) { File dir = new File("plugins/", path); dir.mkdirs(); file.createNewFile(); } OutputStream out = new FileOutputStream(file); byte[] buf = new byte[1024]; int len; while((len = content.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } catch (IOException e) { e.printStackTrace(); } }
5ee80534-7194-4e9b-a392-7d66a923f5c3
1
public List<QuadTree> getRightNeighbors() { QuadTree sibling = this.getRightSibling(); if ( sibling == null ) return new ArrayList<QuadTree>(); return sibling.getLeftChildren(); }
10a0aa70-ed3e-497a-bbd3-5be7094c53c0
4
@Override public void validarSemantica() { Tipo condicion=null; try { condicion =expr1.validarSemantica(); } catch (Exception ex) { Logger.getLogger(SentenciaWhile.class.getName()).log(Level.SEVERE, null, ex); } if(condicion instanceof TipoBooleano){ Sentencia tmp= bloque; while(tmp!=null){ tmp.validarSemantica(); tmp=tmp.getSiguiente(); } } else{ try { throw new Exception("Error Semantico -- La condicion tiene que ser booleana"); } catch (Exception ex) { Logger.getLogger(SentenciaWhile.class.getName()).log(Level.SEVERE, null, ex); } } }
6b0d3277-e604-431f-ab53-0205accbb468
4
private boolean isValidField() { if(getLogin().indexOf(' ') != -1 || getPassword().indexOf(' ') != -1 || getConfirmPassword().indexOf(' ') != -1) { setMessage("Login and password can't contain spases."); return false; } else { if(isValidPassword()) { return true; } else { setMessage("Passwprds not equals."); return false; } } }
bbdf98de-691c-4307-8bb4-3105317bef53
5
static final void method556(boolean bool) { anInt8656++; if (ObjectDefinition.loadingHandler != null) ObjectDefinition.loadingHandler.method2319((byte) -75); if (bool == false) { if (Class348_Sub32.aThread6946 != null) { for (;;) { try { Class348_Sub32.aThread6946.join(); break; } catch (InterruptedException interruptedexception) { /* empty */ } } } } }
ba926cb0-69e4-4ce8-97eb-d364b0315746
5
@Override protected Object doProcessIncoming(Object o) throws FetionException { // -_-!!! , 好吧,我承认这里判断逻辑有点乱。。 if (o instanceof SipcResponse) { SipcResponse response = (SipcResponse) o; // 先检查这个回复是不是分块回复的一部分 SliceSipcResponseHelper helper = this .findSliceResponseHelper(response); if (helper != null) { // 如果是分块回复,就添加到分块回复列表中 helper.addSliceSipcResponse(response); if (helper.isFullSipcResponseRecived()) { synchronized (sliceResponseQueue) { sliceResponseQueue.remove(helper); } // 构造新的回复 SipcResponse some = helper.getFullSipcResponse(); this.handleFullResponse(some); return some; // 返回新的完整的请求 } else { return null; // 分块回复还没接收完,返回null停止处理链 } } else if (response.getStatus() == SipcStatus.PARTIAL) { // 可能是第一次收到的分块回复 helper = new SliceSipcResponseHelper(response); synchronized (sliceResponseQueue) { sliceResponseQueue.add(helper); } return null; // 第一个分块回复,返回null停止处理链 } else { // 不是分块回复的对象就直接进行下一步操作 this.handleFullResponse(response); return response; } } else if (o instanceof SipcNotify) { this.handleFullNotify((SipcNotify) o); return (SipcNotify) o; } else { return null; // 未知类型,一般不会发生。。 } }
f21d87b2-7bdd-47eb-ab3b-83b42c3501e5
6
public View create(Element elem) { String kind = elem.getName(); if (kind != null) if (kind.equals(AbstractDocument.ContentElementName)) { return new LabelView(elem); } else if (kind.equals(AbstractDocument.ParagraphElementName)) { return new NumberedParagraphView(elem); } else if (kind.equals(AbstractDocument.SectionElementName)) { return new BoxView(elem, View.Y_AXIS); } else if (kind.equals(StyleConstants.ComponentElementName)) { return new ComponentView(elem); } else if (kind.equals(StyleConstants.IconElementName)) { return new IconView(elem); } return new LabelView(elem); }
e64b760f-9765-4780-a262-1c161a24d9c0
7
public boolean start() { synchronized (optOutLock) { // Did we opt out? if (isOptOut()) { return false; } // Is metrics already running? if (task != null) { return true; } // Begin hitting the server with glorious data task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { private boolean firstPost = true; public void run() { try { // This has to be synchronized or it can collide with the disable method. synchronized (optOutLock) { // Disable Task, if it is running and the server owner decided to opt-out if (isOptOut() && task != null) { task.cancel(); task = null; // Tell all plotters to stop gathering information. for (Graph graph : graphs) { graph.onOptOut(); } } } // We use the inverse of firstPost because if it is the first time we are posting, // it is not a interval ping, so it evaluates to FALSE // Each time thereafter it will evaluate to TRUE, i.e PING! postPlugin(!firstPost); // After the first post we set firstPost to false // Each post thereafter will be a ping firstPost = false; } catch (IOException e) { if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); } } } }, 0, PING_INTERVAL * 1200); return true; } }
2231c152-f5ef-4dc8-9b35-5cd90ec0634e
1
public void addElement(String key, String label) { if (!listLabel.containsKey(key)) { listLabel.put(key, label); listKey.add(key); } fireIntervalAdded(this, 0, listKey.size()); }
04fa456d-7f57-4392-8e85-c3c01306ca65
8
public void decode( ByteBuffer socketBuffer ) { if( !socketBuffer.hasRemaining() || flushandclosestate ) return; if( DEBUG ) System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" ); if( readystate == READYSTATE.OPEN ) { decodeFrames( socketBuffer ); } else { if( decodeHandshake( socketBuffer ) ) { decodeFrames( socketBuffer ); } } assert ( isClosing() || isFlushAndClose() || !socketBuffer.hasRemaining() ); }
8c48ae12-3fa7-4068-aef5-717610c2fa64
9
public String toString(){ String result = new String(); if (getLeftChild() != null) result += leftChild.toString(); if (getOp() != null) switch(op){ case ADD: result += "+"; break; case SUBTRACT: result += "-"; break; case MULTIPLY: result += "*"; break; case DIVIDE: result += "/"; break; case POWER: result += "^"; break; case ASSIGN: result += "="; break; } else{ result += " no op "; } if (getRightChild() != null) result += rightChild.toString(); return result; }
cd750c44-1701-4380-afb2-98d80291e2e5
0
@Test public void runTestReflection1() throws IOException { InfoflowResults res = analyzeAPKFile("Reflection_Reflection1.apk"); Assert.assertEquals(1, res.size()); }
7fc0bd0b-ab38-4557-9a62-32b5dc1e0c73
9
public static boolean checkSOAP(SOAPMessage message, boolean printCert) throws Exception { boolean rez = false; System.setProperty("com.ibm.security.enableCRLDP", "false"); // Add namespace declaration of the wsse SOAPEnvelope envelope = message.getSOAPPart().getEnvelope(); envelope.addNamespaceDeclaration( "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); // Получение блока, содержащего сертификат. Document doc = envelope.getOwnerDocument(); final Element wssecontext = doc.createElementNS(null, "namespaceContext"); wssecontext .setAttributeNS( "http://www.w3.org/2000/xmlns/", "xmlns:" + "wsse".trim(), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); NodeList secnodeList = XPathAPI.selectNodeList( doc.getDocumentElement(), "//wsse:Security"); // Поиск элемента сертификата. Element r = null; Element el = null; if (secnodeList != null && secnodeList.getLength() > 0) { String actorAttr = null; for (int i = 0; i < secnodeList.getLength(); i++) { el = (Element) secnodeList.item(i); actorAttr = el.getAttributeNS( "http://schemas.xmlsoap.org/soap/envelope/", "actor"); if (actorAttr != null && actorAttr .equals("http://smev.gosuslugi.ru/actors/smev")) { r = (Element) XPathAPI.selectSingleNode(el, "//wsse:BinarySecurityToken[1]", wssecontext); break; } } } if (r == null) { return false; } // Получение сертификата. final X509Security x509 = new X509Security(r); X509Certificate cert = (X509Certificate) CertificateFactory .getInstance("X.509").generateCertificate( new ByteArrayInputStream(x509.getToken())); if (cert == null) { throw new Exception("Сертификат не найден."); } else { if (printCert) System.out.println("Имя сертификата: " + cert.getSubjectDN()); } // Поиск элемента с подписью. NodeList nl = doc.getElementsByTagNameNS( "http://www.w3.org/2000/09/xmldsig#", "Signature"); if (nl.getLength() == 0) { throw new Exception("Не найден элемент Signature."); } Provider xmlDSigProvider = new ru.CryptoPro.JCPxml.dsig.internal.dom.XMLDSigRI(); // Задаем открытый ключ для проверки подписи. XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", xmlDSigProvider); DOMValidateContext valContext = new DOMValidateContext( KeySelector.singletonKeySelector(cert.getPublicKey()), nl.item(0)); javax.xml.crypto.dsig.XMLSignature signature = fac .unmarshalXMLSignature(valContext); // Проверяем подпись. rez = signature.validate(valContext); return rez; }
85d6da93-8eff-4833-bff0-ab5288d7189d
8
public void testDataDependance1() { try { int[] label = new int[0]; TreeNode result = contains(new TreeNode(label), mkChain(new int[][]{ label })); assertTrue(null, "Failed to locate the only node of a leaf!", result != null && result.getData() != null && ((int[])(result.getData())).length == 0 && result.getBranch() != null && result.getBranch().length == 0); } catch(NotFound exn) { fail(exn, "You can not locate the only node of a leaf!"); } catch(TreeException exn) { fail(exn, "An unexpected `TreeException` was thrown!"); } catch(ClassCastException exn) { fail(exn, "Your code fails to deal with tree nodes that are **not** labeled with string data structures! Make sure that: \n* You have **not** written your answer assuming that `String`'s will be the only data type used\n* You have used the `correct` type of `equal`ity."); } catch(Throwable exn) { fail(exn, "Unexpected exception thrown: " + exn.getClass().getName()); } // end of try-catch } // end of method testDataDependance1
fd711352-da4a-4538-b0f9-80187793b374
1
private boolean jj_2_60(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_60(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(59, xla); } }
865fb2f9-6ba6-4028-938a-bf84c15343f1
5
public void decryptFile(String filePath, byte[][][] reversedSubKeys) { System.out.println(); System.out.println("Decrypting"); try { final File inputFile = new File(filePath); final File outputFile = new File(filePath.replace(".des",".decrypted")); final InputStream inputStream = new BufferedInputStream(new FileInputStream(inputFile)); final OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); final long nbBytesFileWithoutHeader = inputFile.length() - 1; final long nbTotalBlocks = (long) Math.ceil(nbBytesFileWithoutHeader / (double) BLOCK_SIZE_IN_BYTES); final int nbBytesHeading = inputStream.read(); byte[] block = new byte[BLOCK_SIZE_IN_BYTES]; for (long nbBlocks = 1; nbBlocks <= nbTotalBlocks; nbBlocks++) { inputStream.read(block); //System.out.println("Decrypting block " + nbBlocks); byte[] decryptedBlock = DesAlgorithm.decryptBlock(block, reversedSubKeys); // schrijf geencrypteerd blok weg naar output bestand // laatste blok => verwijder padding if (nbBlocks == nbTotalBlocks) { byte[] blockWithoutPadding = Arrays.copyOfRange(decryptedBlock, 0, BLOCK_SIZE_IN_BYTES - nbBytesHeading); outputStream.write(blockWithoutPadding); } else { outputStream.write(decryptedBlock); } block = new byte[BLOCK_SIZE_IN_BYTES]; } inputStream.close(); outputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
f8f313ba-794d-4fd1-ae33-f670008dccdf
5
private void voteButtonListener() { viewRecipiesPanel.nickLabel1.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { currentRecipe.setVotes(1.0); recipes.set(currentRecipePos, currentRecipe); try { Recipe.writeToFile(recipes); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } viewRecipiesPanel.emptyPanel(); viewRecipies.validate(); viewRecipies.repaint(); viewRecipiesPanel.viewRecipe(currentRecipe); viewRecipies.validate(); viewRecipies.repaint(); deleteable = true; deleteButtonListener(); commentButtonListener(); voteButtonListener(); } }); viewRecipiesPanel.nickLabel2.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { currentRecipe.setVotes(2.0); recipes.set(currentRecipePos, currentRecipe); try { Recipe.writeToFile(recipes); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } viewRecipiesPanel.emptyPanel(); viewRecipies.validate(); viewRecipies.repaint(); viewRecipiesPanel.viewRecipe(currentRecipe); viewRecipies.validate(); viewRecipies.repaint(); deleteable = true; deleteButtonListener(); commentButtonListener(); voteButtonListener(); } }); viewRecipiesPanel.nickLabel3.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { currentRecipe.setVotes(3.0); recipes.set(currentRecipePos, currentRecipe); try { Recipe.writeToFile(recipes); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } viewRecipiesPanel.emptyPanel(); viewRecipies.validate(); viewRecipies.repaint(); viewRecipiesPanel.viewRecipe(currentRecipe); viewRecipies.validate(); viewRecipies.repaint(); deleteable = true; deleteButtonListener(); commentButtonListener(); voteButtonListener(); } }); viewRecipiesPanel.nickLabel4.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { currentRecipe.setVotes(4.0); recipes.set(currentRecipePos, currentRecipe); try { Recipe.writeToFile(recipes); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } viewRecipiesPanel.emptyPanel(); viewRecipies.validate(); viewRecipies.repaint(); viewRecipiesPanel.viewRecipe(currentRecipe); viewRecipies.validate(); viewRecipies.repaint(); deleteable = true; deleteButtonListener(); commentButtonListener(); voteButtonListener(); } }); viewRecipiesPanel.nickLabel5.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { currentRecipe.setVotes(5.0); recipes.set(currentRecipePos, currentRecipe); try { Recipe.writeToFile(recipes); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } viewRecipiesPanel.emptyPanel(); viewRecipies.validate(); viewRecipies.repaint(); viewRecipiesPanel.viewRecipe(currentRecipe); viewRecipies.validate(); viewRecipies.repaint(); deleteable = true; deleteButtonListener(); commentButtonListener(); voteButtonListener(); } }); }
b34b8c13-e278-4ef3-ba43-59f47b3e3a98
1
private boolean jj_2_80(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_80(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(79, xla); } }
e5aff85e-cbcd-4e58-afd9-d1d2cccf80ee
4
@Override public Response performRequest(Request request) { if (request.getParams().containsKey("Innermessage")) { String inner = request.getParams().get("Innermessage").get(0); if ("exit".equals(inner)) { node.getHttpServer().stop(23); FileStorage.getInstance().flush(); Logger.getLogger("").info("exit"); System.exit(23); } return new Response(Response.Code.OK, null); } else if (!request.getParams().containsKey("In")) { return new Response(Response.Code.METHOD_NOT_ALLOWED, "Это " + node.getServerName() + ". доступ только для своих"); } else if (request.getParams().containsKey("Id")) { return callDB(request); } else { return new Response(Response.Code.FORBIDDEN, "Это " + node.getServerName() + ". запрос непоятен. роутер, ты чего творишь?"); } }
eee557d6-7b5e-4c73-8b5c-0b1985da4010
0
public void setCtrCcResponsable(long ctrCcResponsable) { this.ctrCcResponsable = ctrCcResponsable; }
fdadb48c-05a6-479c-9c36-b6d53b8ce389
0
@Override public void init(List<String> argumentList) { operator = argumentList.get(0); }
9be0584a-cda9-47b4-92d7-d09b37aecf0a
6
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MenuPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MenuPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MenuPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MenuPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> MenuPrincipal.setDefaultLookAndFeelDecorated(true); SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.BusinessBlackSteelSkin"); /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MenuPrincipal().setVisible(true); } }); }
965d7e57-051b-4f8a-bfdc-689994db3704
3
public synchronized void update(long elapsedTime) { if (frames.size() > 1) { animTime += elapsedTime; if (animTime >= totalDuration) { animTime = animTime % totalDuration; currFrameIndex = 0; } while (animTime > getFrame(currFrameIndex).endTime) { currFrameIndex++; } } }
ba56ee7f-f84a-4513-bb66-32bcb281661b
7
private void doConstructParsingTable() { //[TODO] construct parsing table //for title use and $ LinkedList<String> pTableHeader = new LinkedList<String>(); LinkedList<NonTerminalValue> nt = new LinkedList<NonTerminalValue>(); pTableHeader.addAll(terminals); pTableHeader.add("$"); nt.addAll(nonTerminals); String tabs = ""; int max_x = pTableHeader.size()+1; int max_y = nt.size()+1; int x=0,y=0,i=0; parsingTable = new String[max_y][max_x]; parsingTable[0][0] = tabs; for(x=1;x<max_x;x++){ parsingTable[0][x]=tabs+pTableHeader.get(x-1); //log.debugInfo(parsingTable[0][x]); } /*for(y=0;y<max_y;y++){ parsingTable[y][0]=tabs+nt.get(y); }*/ log.debugInfo("table size"+max_y+"*"+max_x+" grammar size>"+this.grammars.size()); y=0; for(Grammar g:this.grammars){ x=0; y++; parsingTable[y][x]=g.getNonTerminal(); NonTerminalValue ntv = getNonTerminalValueByNonTerminal(g.getNonTerminal()); //[DONE]for each first for(String f:ntv.getFirst() ){ i = searchIndexByString(f,pTableHeader); parsingTable[y][i] = tabs; //[FIXME] different expression for different nonterminals for(String es:g.getExpression()){ parsingTable[y][i] = parsingTable[y][i]+es; } } //[TODO]for each follow //[FIXME] Expression derives eps instead of only eps nulable if(ntv.isNullable()) for(String f:ntv.getFollow() ){ i = searchIndexByString(f,pTableHeader); parsingTable[y][i] = tabs; //[FIXME] different expression for different nonterminals for(String es:g.getExpression()){ parsingTable[y][i] = parsingTable[y][i]+es; } } } }