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 |
|---|---|---|---|---|---|
d2b60861d3779c5c69be36d36c112b801e0b03d0 | 3,250 | package com.blnz.xsl.tr;
import com.blnz.xsl.om.*;
import com.blnz.xsl.expr.StringExpr;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLFilterImpl;
import org.xml.sax.helpers.ParserAdapter;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.SAXException;
import org.xml.sax.InputSource;
import org.xml.sax.Attributes;
/**
* Converts a SAX 2 event stream to calls on a Result -- which
* is useful for connecting to extension elements
* which generate SAX events
*/
class ContentHandlingResultWriter extends XMLFilterImpl
{
private Result _downstream = null;
private NamespacePrefixMap _nsMap;
private Name _names[] = new Name[100];
private int _stack = 0;
ContentHandlingResultWriter(NamespacePrefixMap nsMap,
XMLReader upstream,
Result downstream)
{
super(upstream);
_nsMap = nsMap;
_downstream = downstream;
}
public void characters(char[] ch, int start, int length)
throws SAXException
{
try {
_downstream.characters(new String(ch, start, length));
} catch (XSLException ex) {
throw new SAXException(ex);
}
}
public void startElement(String nsURI,
String localName,
String qname,
Attributes atts)
throws SAXException
{
try {
Name name;
int i = qname.indexOf(':');
if (nsURI == null || nsURI.length() == 0) {
name = _nsMap.getNameTable().createName(qname.substring(i + 1));
} else {
if (i > 0) {
_nsMap = _nsMap.bind(qname.substring(0, i), nsURI);
} else {
_nsMap = _nsMap.bindDefault(nsURI);
}
name = _nsMap.expandElementTypeName(qname, null);
}
_downstream.startElement(name, _nsMap);
_names[_stack++] = name;
int natts = atts.getLength();
for (int j = 0; j < natts; ++j) {
writeAttribute(atts.getURI(j), atts.getQName(j),
atts.getValue(j));
}
} catch (XSLException ex) {
throw new SAXException(ex);
}
}
public void endElement(String namespaceURI,
String localName,
String qName)
throws SAXException
{
try {
_downstream.endElement(_names[--_stack]);
} catch (XSLException ex) {
throw new SAXException(ex);
}
}
private void writeAttribute(String ns, String qname, String value)
throws XSLException
{
Name name;
if (ns.length() == 0) {
name =
_nsMap.getNameTable().createName(qname.substring(qname.indexOf(';') +
1));
} else {
name = _nsMap.getNameTable().createName(qname, ns);
}
_downstream.attribute(name, value);
}
}
| 27.777778 | 85 | 0.530769 |
fad9f7e0c76cd9de26bad38a07041179cc3264b5 | 6,925 | package fr.redstonneur1256.redutilities.graphics;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.font.TextLayout;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.*;
import java.util.Arrays;
public class ImageHelper {
private static final ColorConvertOp grayConvertor;
static {
grayConvertor = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
}
public static BufferedImage color(BufferedImage image, Color color) {
image = copy(image);
Graphics graphics = image.getGraphics();
graphics.setColor(color);
graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
graphics.dispose();
return image;
}
public static BufferedImage resize(BufferedImage image, int width, int height) {
return resize(image, width, height, image.getType());
}
public static BufferedImage resize(BufferedImage image, int width, int height, int type) {
BufferedImage copy = new BufferedImage(width, height, type);
Graphics graphics = copy.getGraphics();
graphics.drawImage(image, 0, 0, width, height, null);
graphics.dispose();
return copy;
}
public static BufferedImage changeFormat(BufferedImage image, int newImageType) {
return resize(image, image.getWidth(), image.getHeight(), newImageType);
}
public static BufferedImage copy(BufferedImage original) {
return resize(original, original.getWidth(), original.getHeight());
}
public static int getAverageColor(BufferedImage image) {
int a = 0;
int r = 0;
int g = 0;
int b = 0;
boolean hasAlpha = hasAlpha(image);
for(int x = 0; x < image.getWidth(); x++) {
for(int y = 0; y < image.getHeight(); y++) {
int rgb = image.getRGB(x, y);
a += hasAlpha ? (rgb >> 24) & 0xFF : 0xFF;
r += (rgb >> 16) & 0xFF;
g += (rgb >> 8) & 0xFF;
b += (rgb) & 0xFF;
}
}
float size = (image.getWidth() * image.getHeight());
a = (int) Math.floor(a / size);
r = (int) Math.floor(r / size);
g = (int) Math.floor(g / size);
b = (int) Math.floor(b / size);
return ((a & 0xFF) << 24) |
((r & 0xFF) << 16) |
((g & 0xFF) << 8) |
(b & 0xFF);
}
public static int getOpposite(int color) {
float[] hsb = Color.RGBtoHSB(color >> 16 & 0xFF, color >> 8 & 0xFF, color & 0xFF, null);
float brightness = hsb[2];
if(brightness == 0) {
return 0xFFFFFF; // White
}
if(brightness == 1) {
return 0x000000; // Black
}
if(brightness < 0.5F) {
hsb[2] = (brightness + 0.5F) % 1.0F;
}
return Color.HSBtoRGB((hsb[0] + 0.5F) % 1.0F, hsb[1], hsb[2]);
}
public static boolean hasAlpha(BufferedImage image) {
int type = image.getType();
return type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_ARGB_PRE ||
type == BufferedImage.TYPE_4BYTE_ABGR || type == BufferedImage.TYPE_4BYTE_ABGR_PRE;
}
public static void drawCenteredImageRounded(Graphics graphics, BufferedImage image, int x, int y, ImageObserver observer) {
drawCenteredImageRounded(graphics, image, x, y, image.getHeight(), image.getWidth(), observer);
}
public static void drawCenteredImageRounded(Graphics graphics, BufferedImage image, int x, int y, int width, int height, ImageObserver observer) {
Shape shape = graphics.getClip();
int xx = x - (width / 2);
int yy = y - (height / 2);
graphics.setClip(new Ellipse2D.Double(xx, yy, height, width));
graphics.drawImage(image, xx, yy, width, height, observer);
graphics.setClip(shape);
}
public static void ellipse(Graphics2D graphics, int x, int y, int width, int height) {
Shape shape = graphics.getClip();
int xx = x - (width / 2);
int yy = y - (height / 2);
graphics.setClip(new Ellipse2D.Double(xx, yy, height, width));
graphics.fillOval(xx, yy, width, height);
graphics.setClip(shape);
}
public static void drawCenteredImage(Graphics graphics, BufferedImage image, int x, int y, ImageObserver observer) {
drawCenteredImage(graphics, image, x, y, image.getHeight(), image.getWidth(), observer);
}
public static void drawCenteredImage(Graphics graphics, BufferedImage image, int x, int y, int width, int height, ImageObserver observer) {
int xx = x - (width / 2);
int yy = y - (height / 2);
graphics.drawImage(image, xx, yy, width, height, observer);
}
public static void drawCenterText(Graphics graphics, String text, int x, int y) {
FontMetrics fontMetrics = graphics.getFontMetrics();
Rectangle2D bounds = fontMetrics.getStringBounds(text, graphics);
int width = (int) bounds.getWidth();
graphics.drawString(text, x - (width / 2), y + fontMetrics.getDescent());
}
public static void drawCenterTextShadowed(Graphics2D graphics, String text, int x, int y) {
TextLayout layout = new TextLayout(text, graphics.getFont(), graphics.getFontRenderContext());
Rectangle2D bounds = graphics.getFontMetrics().getStringBounds(text, graphics);
int stringWidth = (int) bounds.getWidth();
int stringHeight = (int) bounds.getHeight();
BufferedImage shadowImage = new BufferedImage(stringWidth, stringHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D temp = (Graphics2D) shadowImage.getGraphics();
temp.setColor(Color.BLACK);
temp.setFont(graphics.getFont());
temp.drawString(text, 0, temp.getFontMetrics().getAscent());
temp.dispose();
int size = 5;
float[] data = new float[stringWidth * stringHeight];
Arrays.fill(data, 1F / (size * size));
Kernel kernel = new Kernel(size, size, data);
BufferedImageOp op = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
BufferedImage blurredShadow = op.filter(shadowImage, null);
graphics.drawImage(blurredShadow, x - (stringWidth / 2) + 3, y - temp.getFontMetrics().getAscent() + 3, null);
graphics.setPaint(Color.WHITE);
layout.draw(graphics, x - (stringWidth / 2F), y);
}
public static BufferedImage convertBlackAndWhite(BufferedImage image) {
BufferedImage output = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
grayConvertor.filter(image, output);
return output;
}
}
| 39.346591 | 151 | 0.606643 |
d4fe1c8081a73750892aa2b927b8a90371f9472d | 320 | package com.stylefeng.guns.modular.system.dao;
import com.stylefeng.guns.modular.system.model.OrderMember;
import com.baomidou.mybatisplus.mapper.BaseMapper;
/**
* <p>
* 订单用户信息 Mapper 接口
* </p>
*
* @author stylefeng
* @since 2018-11-17
*/
public interface OrderMemberMapper extends BaseMapper<OrderMember> {
}
| 18.823529 | 68 | 0.74375 |
cdbd9c03bba459bc96787dd5e2acc5c1bbc402b8 | 201 | package br.com.pjbank.sdk.enums;
/**
* @author Vinícius Silva <vinicius.silva@superlogica.com>
* @version 1.0
* @since 1.0
*/
public enum FormaRecebimento {
BOLETO_BANCARIO, CARTAO_CREDITO;
}
| 18.272727 | 58 | 0.711443 |
459d678bd496a780fb7c1a4b6955c69132e10afc | 260 | package com.example.myapplication;
/**
* Some constants to check permissions
*
*/
public class Constant {
public static final int PERMISSIONS_REQUEST_ENABLE_GPS = 9002;
public static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 9003;
}
| 18.571429 | 76 | 0.761538 |
dddf8581cadb01f6d46430f4e18412a85cb1d121 | 2,140 | /**
* Copyright (C) 2016 - 2030 youtongluan.
*
* 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.yx.bean;
import java.util.List;
import org.yx.common.Ordered;
import org.yx.exception.SumkException;
import org.yx.log.Logs;
public final class IOC {
/**
* 获取对应的bean
*
* @param <T>
* 返回值类型
* @param name
* bean的名称
* @return 如果不存在,就返回null。如果bean不止一个,会抛出SumkException异常
*/
public static <T> T get(String name) {
return get(name, null);
}
public static <T> T get(Class<T> clz) {
return get(null, clz);
}
public static <T> T get(String name, Class<T> clz) {
return InnerIOC.pool.getBean(name, clz);
}
public static <T> List<T> getBeans(Class<T> clz) {
return InnerIOC.pool.getBeans(null, clz);
}
/**
* 获取该类型bean的第一个,如果不存在就抛出异常。
*
* @param <T>
* bean的类型
* @param clz
* bean的类型,返回order最小的那个
* @param allowEmpty
* true表示允许为空,否则会抛出异常
* @return 返回第一个符合条件的bean。被自定义名称的bean可能获取不到
*/
public static <T extends Ordered> T getFirstBean(Class<T> clz, boolean allowEmpty) {
List<T> factorys = IOC.getBeans(clz);
if (factorys.isEmpty()) {
if (allowEmpty) {
return null;
}
throw new SumkException(-353451, clz.getName() + "没有实现类,或者实现类不是Bean");
}
T f = factorys.get(0);
Logs.ioc().debug("{}第一个bean是{}", clz.getName(), f);
return f;
}
public static <T> List<T> getBeans(String name, Class<T> clz) {
return InnerIOC.pool.getBeans(name, clz);
}
public static String info() {
return InnerIOC.pool.toString();
}
public static List<String> beanNames() {
return InnerIOC.beanNames();
}
}
| 24.318182 | 85 | 0.666355 |
31744530f9bb9e7790d23a2ca1ebd2ea87c38aa8 | 2,457 | /**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.course.learningpath.evaluation;
import org.olat.course.run.scoring.AccountingEvaluators;
import org.olat.course.run.scoring.AccountingEvaluatorsBuilder;
import org.olat.course.run.scoring.EndDateEvaluator;
import org.olat.course.run.scoring.StartDateEvaluator;
import org.olat.course.run.scoring.StatusEvaluator;
import org.olat.modules.assessment.model.AssessmentEntryStatus;
/**
*
* Initial date: 17 Sep 2019<br>
* @author uhensler, urs.hensler@frentix.com, http://www.frentix.com
*
*/
public class LearningPathEvaluatorBuilder {
private static final StartDateEvaluator CONFIG_START_DATE_EVALUATOR = new ConfigStartDateEvaluator();
private static final EndDateEvaluator CONFIG_END_DATE_EVALUATOR = new ConfigEndDateEvaluator();
private static final ConfigObligationEvaluator CONFIG_OBLIGATION_EVALUATOR = new ConfigObligationEvaluator();
private static final ConfigDurationEvaluator CONFIG_DURATION_EVALUATOR = new ConfigDurationEvaluator();
private static final StatusEvaluator STATUS_EVALUATOR = new DefaultLearningPathStatusEvaluator(AssessmentEntryStatus.notStarted);
private static final AccountingEvaluators DEFAULT = defaults().build();
public static AccountingEvaluators buildDefault() {
return DEFAULT;
}
public static AccountingEvaluatorsBuilder defaults() {
return AccountingEvaluatorsBuilder
.builder()
.withStartDateEvaluator(CONFIG_START_DATE_EVALUATOR)
.withEndDateEvaluator(CONFIG_END_DATE_EVALUATOR)
.withObligationEvaluator(CONFIG_OBLIGATION_EVALUATOR)
.withDurationEvaluator(CONFIG_DURATION_EVALUATOR)
.withStatusEvaluator(STATUS_EVALUATOR);
}
}
| 40.95 | 130 | 0.789988 |
f83e414d05fe93315b2dcfe2a3d23be4430574bc | 1,155 | package org.example.controller.session;
import org.apache.catalina.realm.GenericPrincipal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static org.example.utils.Utils.requestInitialized;
@WebServlet(name = "logout", urlPatterns = "/logout", loadOnStartup = 1)
public class LogoutController extends HttpServlet {
private static Logger log = LoggerFactory.getLogger(LogoutController.class);
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
requestInitialized(request, log);
GenericPrincipal principal = (GenericPrincipal) request.getSession().getAttribute("principal");
log.debug("logout: {}", principal);
if (principal!=null) {
request.logout();
request.getSession().removeAttribute("principal");
}
response.sendRedirect("/home");
}
}
| 36.09375 | 121 | 0.754113 |
252c48142a1adfa59750c17a8ec4125484850f0e | 527 | package today.flux.addon.api.packet.server;
import com.soterdev.SoterObfuscator;
import net.minecraft.network.play.server.S2EPacketCloseWindow;
import today.flux.addon.api.packet.AddonPacket;
public class PacketCloseWindow extends AddonPacket {
public PacketCloseWindow(S2EPacketCloseWindow packet) {
super(packet);
}
public int getWindowId() {
return ((S2EPacketCloseWindow) nativePacket).windowId;
}
public void setWindowId(int windowId) {
((S2EPacketCloseWindow) nativePacket).windowId = windowId;
}
}
| 22.913043 | 62 | 0.787476 |
8d975f9bc5210fdc63966aa6e7308bcaf9cfefa3 | 6,653 | /*
* 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.
*/
/**
* @author Pavel Dolgov
*/
package org.apache.harmony.awt.theme.windows;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;
import org.apache.harmony.awt.gl.MultiRectArea;
import org.apache.harmony.awt.gl.windows.WinGDIPGraphics2D;
/**
* Native painting of standard components
*/
public final class WinThemeGraphics {
private long hOldClipRgn;
private long hTheme;
private final long gi;
private final int trX;
private final int trY;
public WinThemeGraphics(Graphics gr) {
WinGDIPGraphics2D wgr = (WinGDIPGraphics2D)gr;
this.gi = wgr.getGraphicsInfo();
trX = Math.round((float)wgr.getTransform().getTranslateX());
trY = Math.round((float)wgr.getTransform().getTranslateY());
int clip[];
Shape clipShape = gr.getClip();
if (clipShape instanceof MultiRectArea) {
clip = ((MultiRectArea) clipShape).rect;
if (trX != 0 || trY != 0) {
int rect[] = clip;
int len = clip[0];
clip = new int[len];
System.arraycopy(rect, 0, clip, 0, len);
for (int i = 1; i < len; i += 2) {
clip[i] += trX;
clip[i+1] += trY;
}
}
} else {
Rectangle r = clipShape.getBounds();
clip = new int[] { 5, trX + r.x, trY + r.y,
trX + r.x + r.width - 1, trY + r.x + r.height - 1 };
}
hOldClipRgn = setGdiClip(gi, clip, clip[0]-1);
}
public void dispose() {
restoreGdiClip(gi, hOldClipRgn);
hOldClipRgn = 0;
}
public void setTheme(long hTheme) {
this.hTheme = hTheme;
}
public void drawXpBackground(Rectangle r, int type, int state) {
drawXpBackground(r.x, r.y, r.width, r.height, type, state);
}
public void drawXpBackground(Dimension size, int type, int state) {
drawXpBackground(0, 0, size.width, size.height, type, state);
}
public void drawXpBackground(int x, int y, int w, int h,
int type, int state) {
drawXpBackground(gi, trX + x, trY + y, w, h, hTheme, type, state);
}
public void drawClassicBackground(Rectangle r, int type, int state) {
drawClassicBackground(r.x, r.y, r.width, r.height, type, state);
}
public void drawClassicBackground(Dimension size, int type, int state) {
drawClassicBackground(0, 0, size.width, size.height, type, state);
}
public void drawClassicBackground(int x, int y, int w, int h,
int type, int state) {
drawClassicBackground(gi, trX + x, trY + y, w, h, type, state);
}
public void fillBackground(Dimension size, Color color, boolean solid) {
fillBackground(0, 0, size.width, size.height, color, solid);
}
public void fillBackground(Rectangle r, Color color, boolean solid) {
fillBackground(r.x, r.y, r.width, r.height, color, solid);
}
public void fillBackground(int x, int y, int w, int h,
Color color, boolean solid) {
fillBackground(gi, trX + x, trY + y, w, h, getRGB(color), solid);
}
public void drawFocusRect(Rectangle r, int offset) {
drawFocusRect(r.x + offset, r.y + offset,
r.width - 2 * offset, r.height - 2 * offset);
}
public void drawFocusRect(Dimension size, int offset) {
drawFocusRect(offset, offset,
size.width - 2 * offset, size.height - 2 * offset);
}
public void drawFocusRect(int x, int y, int w, int h, int offset) {
drawFocusRect(x + offset, y + offset,
w - 2 * offset, h - 2 * offset);
}
public void drawFocusRect(int x, int y, int w, int h) {
drawFocusRect(gi, trX + x, trY + y, w, h);
}
public void drawEdge(Rectangle r, int type) {
drawEdge(r.x, r.y, r.width, r.height, type);
}
public void drawEdge(Dimension size, int type) {
drawEdge(0, 0, size.width, size.height, type);
}
public void drawEdge(int x, int y, int w, int h, int type) {
drawEdge(gi, trX + x, trY + y, w, h, type);
}
public void fillHatchedSysColorRect(Rectangle r,
int sysColor1, int sysColor2) {
fillHatchedSysColorRect(r.x, r.y, r.width, r.height,
sysColor1, sysColor2);
}
public void fillHatchedSysColorRect(Dimension size,
int sysColor1, int sysColor2) {
fillHatchedSysColorRect(0, 0, size.width, size.height,
sysColor1, sysColor2);
}
public void fillHatchedSysColorRect(int x, int y, int w, int h,
int sysColor1, int sysColor2) {
fillHatchedSysColorRect(gi, trX + x, trY + y, w, h,
sysColor1, sysColor2);
}
private static int getRGB(Color c) {
return (c != null) ? c.getRGB() : 0xFFFFFFFF;
}
public static native long setGdiClip(long gi, int clip[], int clipLength);
public static native void restoreGdiClip(long gi, long hOldClipRgn);
private static native void drawXpBackground(long gi, int x, int y, int w,
int h, long hTheme, int type, int state);
private static native void drawClassicBackground(long gi, int x, int y,
int w, int h, int type, int state);
private static native void fillBackground(long gi, int x, int y,
int w, int h, int backColorRGB, boolean solidBack);
private static native void drawFocusRect(long gi,
int x, int y, int w, int h);
private static native void drawEdge(long gi,
int x, int y, int w, int h, int type);
private static native void fillHatchedSysColorRect(long gi,
int x, int y, int w, int h, int sysColor1, int sysColor2);
} | 34.117949 | 78 | 0.616113 |
78984bd53518fd93d17aba4bec64dc68a26417eb | 4,810 |
/*
* Janino - An embedded Java[TM] compiler
*
* Copyright (c) 2018 Arno Unkrig. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* 2. 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.
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 org.codehaus.commons.compiler.util;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.codehaus.commons.nullanalysis.Nullable;
/**
* Generates human-readable Java assembler code from Java bytecode.
*/
public final
class Disassembler {
@Nullable private static Object disassemblerInstance;
static {
@Nullable Class<?> disassemblerClass;
try {
disassemblerClass = Class.forName("de.unkrig.jdisasm.Disassembler");
} catch (ClassNotFoundException cnfe) {
System.err.println((
"Notice: Could not disassemble class file for logging because "
+ "\"de.unkrig.jdisasm.Disassembler\" is not on the classpath. "
+ "If you are interested in disassemblies of class files generated by JANINO, "
+ "get de.unkrig.jdisasm and put it on the classpath."
));
disassemblerClass = null;
}
if (disassemblerClass != null) {
try {
Disassembler.disassemblerInstance = disassemblerClass.getConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private Disassembler() {}
/**
* Loads a "{@code de.unkrig.jdisasm.Disassembler}" through reflection (to avoid a compile-time dependency) and
* uses it to disassemble the given bytes to {@code System.out}.
* <p>
* Prints an error message to {@code System.err} if that class cannot be loaded through the classpath.
* </p>
* <p>
* System variable {@code disasm.verbose} controls whether the disassembler operates in "verbose" mode. The
* default is {@code false}.
* </p>
*/
public static void
disassembleToStdout(byte[] contents) {
Object d = Disassembler.disassemblerInstance;
if (d == null) return;
try {
for (String attributeName : new String[] {
"verbose",
"showClassPoolIndexes",
"dumpConstantPool",
"printAllAttributes",
"printStackMap",
"showLineNumbers",
"showVariableNames",
"symbolicLabels",
"printAllOffsets",
}) {
String pv = SystemProperties.getClassProperty(Disassembler.class, attributeName);
if (pv != null) {
boolean argument = Boolean.parseBoolean(pv);
final String setterMethodName = (
"set"
+ Character.toUpperCase(attributeName.charAt(0))
+ attributeName.substring(1)
);
d.getClass().getMethod(setterMethodName, boolean.class).invoke(d, argument);
}
}
d.getClass().getMethod("disasm", InputStream.class).invoke(d, new ByteArrayInputStream(contents));
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 42.566372 | 120 | 0.620166 |
092b49fbe4fa03a6988fccce7ed7b6b17db85fac | 2,953 | package com.tazzie02.tazbot;
import com.tazzie02.tazbot.util.JDAUtil;
import com.tazzie02.tazbot.util.MessageLogger;
import com.tazzie02.tazbot.util.SendMessage;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.guild.GuildJoinEvent;
import net.dv8tion.jda.core.events.guild.GuildLeaveEvent;
import net.dv8tion.jda.core.events.message.priv.PrivateMessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.tazzie02.tazbot.managers.ConfigManager;
import com.tazzie02.tazbot.managers.SettingsManager;
public class Listeners extends ListenerAdapter {
@Override
public void onPrivateMessageReceived(PrivateMessageReceivedEvent e) {
if (!e.getAuthor().getId().equals(e.getJDA().getSelfUser().getId())) {
MessageLogger.receivePrivateMessage(e);
}
}
@Override
public void onGuildJoin(GuildJoinEvent e) {
Guild g = e.getGuild();
// Check if bot is already in the guild.
// If there is a discord outage, onGuildJoin may be fired incorrectly.
if (SettingsManager.getInstance(g.getId()).getSettings().isJoined()) {
return;
}
String message = "JOINED GUILD " + JDAUtil.guildToString(g);
MessageLogger.guildEvent(g, message);
SendMessage.sendDeveloper(message);
String botName = ConfigManager.getInstance().getConfig().getBotName();
StringBuilder sb = new StringBuilder()
.append("Hello! Thank you for adding ").append(botName).append(" to ").append(g.getName()).append(".\n");
SettingsManager manager = SettingsManager.getInstance(g.getId());
if (!manager.getSettings().getModerators().isEmpty()) {
sb.append("Since this is not the first time ").append(botName).append(" has been joined ").append(g.getName()).append(", please note that your settings have been reset.\n");
manager.resetSettings();
}
List<User> us = JDAUtil.addDefaultModerators(g);
sb.append("Added ").append(StringUtils.join(JDAUtil.userListToString(us), ", ")).append(" as moderators.\n")
.append("The guild owner (currently " + g.getOwner().getEffectiveName() + ") may add or remove moderators at any time.\n")
.append("The default command prefix is \"" + manager.getSettings().getPrefix() + "\". You can also mention instead of using a prefix.\n")
.append("Use the help and about commands for more information.");
SendMessage.sendMessage(JDAUtil.findTopWriteChannel(g), sb.toString());
}
@Override
public void onGuildLeave(GuildLeaveEvent e) {
Guild g = e.getGuild();
String message = "LEFT GUILD " + JDAUtil.guildToString(g);
// Set joined to false in settings file
SettingsManager settingsManager = SettingsManager.getInstance(g.getId());
settingsManager.getSettings().setJoined(false);
settingsManager.saveSettings();
MessageLogger.guildEvent(g, message);
SendMessage.sendDeveloper(message);
}
}
| 36.45679 | 176 | 0.742635 |
b7aa2e7f2a721c8a28d50dad0e21464bc3a1d316 | 75 | package lumien.randomthings.potion;
public class SimpleBrewingRecipe
{
}
| 10.714286 | 35 | 0.813333 |
a6228e6fb021367add46fb7dfb9e7fed9682c53e | 1,764 | package cws.core.storage.cache;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import cws.core.VM;
import cws.core.cloudsim.CloudSimWrapper;
import cws.core.core.VMType;
import cws.core.dag.DAGFile;
import cws.core.dag.Task;
import cws.core.jobs.Job;
/**
* Abstract tests for {@link VMCacheManager}
*/
public abstract class VMCacheManagerTest {
protected VMCacheManager cm;
protected CloudSimWrapper cloudsim;
protected Job job;
protected VM vm;
protected VMType vmType;
protected Task task;
@Before
public void setUpVMCacheTest() {
cloudsim = Mockito.spy(new CloudSimWrapper());
cloudsim.init();
job = Mockito.mock(Job.class);
vm = Mockito.mock(VM.class);
vmType = Mockito.mock(VMType.class);
Mockito.when(vm.getId()).thenReturn(100);
Mockito.when(vm.getVmType()).thenReturn(vmType);
job.setVM(vm);
Mockito.when(job.getVM()).thenReturn(vm);
task = Mockito.mock(Task.class);
Mockito.when(job.getTask()).thenReturn(task);
}
@Test
public void testFilesNotInCache() {
Assert.assertFalse(cm.getFileFromCache(new DAGFile("abc.txt", 100, null), job.getVM()));
Assert.assertFalse(cm.getFileFromCache(new DAGFile("abc.txt", 100, null), job.getVM()));
Assert.assertFalse(cm.getFileFromCache(new DAGFile("sadsadsaddsa", 100, null), job.getVM()));
}
@Test
public void testTooBigFile() {
Mockito.when(vmType.getCacheSize()).thenReturn((long) 100);
DAGFile file = new DAGFile("abc.txt", 10000, null);
cm.putFileToCache(file, job.getVM());
Assert.assertFalse(cm.getFileFromCache(file, job.getVM()));
}
}
| 30.413793 | 101 | 0.671769 |
7162b16cc29b608cf429017f4f47c2b93b907843 | 2,850 | package de.vinado.wicket.participate.components.panels;
import de.vinado.wicket.participate.components.modals.BootstrapModal;
import de.vinado.wicket.participate.components.modals.BootstrapModalPanel;
import de.vinado.wicket.participate.components.snackbar.Snackbar;
import de.vinado.wicket.participate.email.Email;
import de.vinado.wicket.participate.email.service.EmailService;
import de.vinado.wicket.participate.providers.Select2EmailAddressProvider;
import de.vinado.wicket.participate.services.PersonService;
import lombok.extern.slf4j.Slf4j;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.wicketstuff.select2.Select2BootstrapTheme;
import org.wicketstuff.select2.Select2MultiChoice;
import javax.mail.internet.InternetAddress;
import java.util.stream.Stream;
/**
* @author Vincent Nadoll (vincent.nadoll@gmail.com)
*/
@Slf4j
public class SendEmailPanel extends BootstrapModalPanel<Email> {
@SpringBean
private PersonService personService;
@SpringBean
private EmailService emailService;
public SendEmailPanel(final BootstrapModal modal, final IModel<Email> model) {
super(modal, new ResourceModel("email.new", "New Email"), model);
setModalSize(ModalSize.Large);
final TextField<String> fromTf = new TextField<>("from");
fromTf.setEnabled(false);
inner.add(fromTf);
final Select2MultiChoice<InternetAddress> toTf = new Select2MultiChoice<>("to", new Select2EmailAddressProvider(personService));
toTf.getSettings().setLanguage(getLocale().getLanguage());
toTf.getSettings().setCloseOnSelect(true);
toTf.getSettings().setTheme(new Select2BootstrapTheme(true));
toTf.getSettings().setPlaceholder(new ResourceModel("select.placeholder", "Please Choose").getObject());
toTf.setLabel(new ResourceModel("email.recipient", "Recipient"));
inner.add(toTf);
final TextField<String> subjectTf = new TextField<>("subject");
inner.add(subjectTf);
final TextArea<String> messageTa = new TextArea<>("message");
inner.add(messageTa);
addBootstrapFormDecorator(inner);
}
@Override
protected void onSaveSubmit(final IModel<Email> model, final AjaxRequestTarget target) {
Email mail = model.getObject();
Stream<Email> mails = mail.toSingleRecipient();
emailService.send(mails);
Snackbar.show(target, new ResourceModel("email.send.success", "Email sent"));
}
@Override
protected IModel<String> getSubmitBtnLabel() {
return new ResourceModel("send", "Send");
}
}
| 38.513514 | 136 | 0.745614 |
f2db5947d96b8ac04c895455600b7b742b5c60d2 | 3,356 | package com.bytezone.dm3270.orders;
import java.io.UnsupportedEncodingException;
import com.bytezone.dm3270.display.DisplayScreen;
import com.bytezone.dm3270.display.Pen;
import com.bytezone.dm3270.utilities.Dm3270Utility;
// -----------------------------------------------------------------------------------//
public class TextOrder extends Order
// -----------------------------------------------------------------------------------//
{
private int bufferOffset;
byte[] originalBuffer;
// ---------------------------------------------------------------------------------//
public TextOrder (byte[] buffer, int ptr, int max)
// ---------------------------------------------------------------------------------//
{
bufferOffset = ptr; // save for later scrambling
originalBuffer = buffer;
int dataLength = getDataLength (buffer, ptr, max);
this.buffer = new byte[dataLength];
System.arraycopy (buffer, ptr, this.buffer, 0, dataLength);
}
// ---------------------------------------------------------------------------------//
public TextOrder (String text)
// ---------------------------------------------------------------------------------//
{
try
{
buffer = text.getBytes ("CP1047");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace ();
}
}
// ---------------------------------------------------------------------------------//
private int getDataLength (byte[] buffer, int offset, int max)
// ---------------------------------------------------------------------------------//
{
int ptr = offset + 1;
int length = 1;
outer_loop: while (ptr < max)
{
byte value = buffer[ptr++];
for (int i = 0; i < orderValues.length; i++)
if (value == orderValues[i])
break outer_loop;
length++;
}
return length;
}
// ---------------------------------------------------------------------------------//
public void scramble ()
// ---------------------------------------------------------------------------------//
{
for (int ptr = 0; ptr < buffer.length; ptr++)
originalBuffer[bufferOffset + ptr] = 0x7B;
}
// ---------------------------------------------------------------------------------//
public String getTextString ()
// ---------------------------------------------------------------------------------//
{
return Dm3270Utility.getString (buffer);
}
// ---------------------------------------------------------------------------------//
@Override
public boolean isText ()
// ---------------------------------------------------------------------------------//
{
return true;
}
// ---------------------------------------------------------------------------------//
@Override
public void process (DisplayScreen screen)
// ---------------------------------------------------------------------------------//
{
Pen pen = screen.getPen ();
for (byte b : buffer)
pen.write (b);
}
// ---------------------------------------------------------------------------------//
@Override
public String toString ()
// ---------------------------------------------------------------------------------//
{
return buffer.length == 0 ? "" : "Text: [" + Dm3270Utility.getString (buffer) + "]";
}
} | 33.56 | 88 | 0.326877 |
3f382eb65049ba3972afd5c9a598031136528fb5 | 783 | package de.gishmo.gwt.example.domain.services.client.utils;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.Constants;
public interface ExceptionUtilsConstants
extends Constants {
ExceptionUtilsConstants INSTANCE = GWT.create(ExceptionUtilsConstants.class);
String applicationErrorText();
String applicationErrorMessage();
String methodName();
String serverErrorData();
String serverErrorMessage();
String serverErrorPayload();
String serverErrorText();
String serverMessageStatus();
String serverMessageResponseHeader();
String serverNoResponseDataExist();
String serverNoRespneseHeaderInforamationExist();
String serverTechnischerFehler();
String notYetImplemetat();
String applicationErrorStackTrace();
}
| 19.575 | 79 | 0.789272 |
0801b364914297d8f2e28396983e151acd0ce461 | 1,380 | package org.bridgedb.util.taverna.ui.config;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import net.sf.taverna.t2.workbench.ui.actions.activity.ActivityConfigurationAction;
import net.sf.taverna.t2.workbench.ui.views.contextualviews.activity.ActivityConfigurationDialog;
import org.bridgedb.util.taverna.BridgeDbActivity;
import org.bridgedb.util.taverna.BridgeDbActivityConfigurationBean;
@SuppressWarnings("serial")
public class BridgeDbConfigureAction
extends
ActivityConfigurationAction<BridgeDbActivity, BridgeDbActivityConfigurationBean> {
public BridgeDbConfigureAction(BridgeDbActivity activity, Frame owner) {
super(activity);
}
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent e) {
ActivityConfigurationDialog<BridgeDbActivity, BridgeDbActivityConfigurationBean> currentDialog = ActivityConfigurationAction
.getDialog(getActivity());
if (currentDialog != null) {
currentDialog.toFront();
return;
}
BridgeDbConfigurationPanel panel = new BridgeDbConfigurationPanel(
getActivity());
ActivityConfigurationDialog<BridgeDbActivity, BridgeDbActivityConfigurationBean> dialog = new ActivityConfigurationDialog<BridgeDbActivity, BridgeDbActivityConfigurationBean>(
getActivity(), panel);
ActivityConfigurationAction.setDialog(getActivity(), dialog);
}
}
| 35.384615 | 178 | 0.802174 |
43eb1f18503c6d407278e650f55371c43f4cda6b | 3,404 |
import java.io.*;
public class Valutatore {
private Lexer lex;
private BufferedReader pbr;
private Token look;
public Valutatore(Lexer l, BufferedReader br) {
lex = l;
pbr = br;
move();
}
void move() {
look = lex.lexical_scan(pbr);
System.out.println("token = " + look);
}
void error(String s) {
throw new Error("near line " + lex.line + ": " + s);
}
void match(int t) {
if (look.tag == t) {
if (look.tag != Tag.EOF) move();
} else error("syntax error");
}
public void start() {
int expr_val;
expr_val = expr();
match(Tag.EOF);
System.out.println(expr_val); // stampa valore finale (risultato)
}
private int expr() { // non ha attributi ereditati,
int term_val, exprp_val;// ha un attributo sintetizzato(return int)
term_val = term(); // invoca metodo term che ha un attributo sintetizzato
exprp_val = exprp(term_val);// exprp ha un attributo sintetizzato, attributo ereditato == term.val
return exprp_val; // expr.val = exprp.val
}
private int exprp(int exprp_i) { // switch sui vari case
int term_val, exprp_val;
switch (look.tag) {
case '+':
match('+');
term_val = term(); // attributo sintetizzato di term
exprp_val = exprp(exprp_i + term_val);// attributo sintetizzato di expr
break; // attributo ereditato equivalente a (exprp.i + term.val)
case '-':
match('-');
term_val = term();
exprp_val = exprp(exprp_i - term_val);
break;
default:
exprp_val = exprp_i;
}
return exprp_val; // attributo sintetizzato di exprp.val
}
private int term() {
int fact_val, termp_val;
fact_val = fact();
termp_val = termp(fact_val);
return termp_val;
}
private int termp(int termp_i) {
int fact_val, termp_val;
switch(look.tag){
case '*':
match('*');
fact_val = fact();
termp_val = termp(termp_i * fact_val);
break;
case '/':
match('/');
fact_val = fact();
termp_val = termp(termp_i / fact_val);
break;
default:
termp_val = termp_i;
}
return termp_val;
}
private int fact() {
int fact_val = 0;
switch(look.tag){
case '(':
match('(');
fact_val = expr();
match(')');
break;
case Tag.NUM:
fact_val = ((NumberTok) look).n;
match(Tag.NUM);
break;
default:
error("ERROR FACT()");
}
return fact_val;
}
public static void main(String[] args) {
Lexer lex = new Lexer();
String path = "Input.lft"; // il percorso del file da leggere
try {
BufferedReader br = new BufferedReader(new FileReader(path));
Valutatore valutatore = new Valutatore(lex, br);
valutatore.start();
br.close();
} catch (IOException e) {e.printStackTrace();}
}
}
| 27.674797 | 106 | 0.494712 |
dcb353fdb7d568809cc6d8b63f078c5e87fbeaa5 | 5,216 | package se.alipsa.ride.inout;
import javafx.concurrent.Task;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import se.alipsa.ride.code.CodeComponent;
import se.alipsa.ride.code.CodeType;
import se.alipsa.ride.code.TextAreaTab;
import se.alipsa.ride.model.MuninReport;
import se.alipsa.ride.utils.Alerts;
import se.alipsa.ride.utils.ExceptionAlert;
import se.alipsa.ride.utils.TikaUtils;
import java.awt.*;
import java.io.File;
import java.io.IOException;
public class FileOpener {
private CodeComponent codeComponent;
private static final Logger log = LogManager.getLogger(FileOpener.class);
public FileOpener(CodeComponent codeComponent) {
this.codeComponent = codeComponent;
}
public TextAreaTab openFile(File file, boolean... openExternalIfUnknownType) {
final boolean allowOpenExternal = openExternalIfUnknownType.length <= 0 || openExternalIfUnknownType[0];
String type = guessContentType(file);
log.debug("File ContentType for {} detected as {}", file.getName(), type);
if (file.isFile()) {
String fileNameLower = file.getName().toLowerCase();
if (strEndsWith(fileNameLower, ".r", ".s") || strEquals(type, "text/x-rsrc")) {
return codeComponent.addTab(file, CodeType.R);
}
if (strEndsWith(fileNameLower, MuninReport.FILE_EXTENSION)) {
return codeComponent.addTab(file, CodeType.MR);
}
if ( strEquals(type, "application/xml", "text/xml", "text/html")
|| strEndsWith(type, "+xml")
// in case an xml declaration was omitted or empty file:
|| strEndsWith(fileNameLower,".xml")
|| strEndsWith(fileNameLower,".html")){
return codeComponent.addTab(file, CodeType.XML);
}
if (strEndsWith(fileNameLower, ".java")) {
return codeComponent.addTab(file, CodeType.JAVA);
}
if (strEquals(type, "text/x-groovy") || strEndsWith(fileNameLower, ".groovy", ".gvy", ".gy", ".gsh", ".gradle")) {
return codeComponent.addTab(file, CodeType.GROOVY);
}
if (strEquals(type, "text/x-sql", "application/sql") || strEndsWith(fileNameLower, "sql")) {
return codeComponent.addTab(file, CodeType.SQL);
}
if (strEndsWith(fileNameLower, ".js")
|| strEquals(type, "application/javascript", "application/ecmascript", "text/javascript", "text/ecmascript")) {
return codeComponent.addTab(file, CodeType.JAVA_SCRIPT);
}
if (strEndsWith(fileNameLower, ".md") || strEndsWith(fileNameLower, ".rmd")) {
return codeComponent.addTab(file, CodeType.MD);
}
if (strEndsWith(fileNameLower, ".mdr")) {
return codeComponent.addTab(file, CodeType.MDR);
}
if (strStartsWith(type, "text")
|| strEquals(type, "application/x-bat",
"application/x-sh", "application/json", "application/x-sas")
|| "namespace".equals(fileNameLower)
|| "description".equals(fileNameLower)
|| strEndsWith(fileNameLower, ".txt", ".csv", ".gitignore", ".properties", "props")) {
return codeComponent.addTab(file, CodeType.TXT);
}
if (allowOpenExternal && isDesktopSupported()) {
log.info("Try to open {} in associated application", file.getName());
openApplicationExternal(file);
} else {
Alerts.info("Unknown file type",
"Unknown file type, not sure what to do with " + file.getName());
}
}
return null;
}
private boolean isDesktopSupported() {
try {
return Desktop.isDesktopSupported();
} catch (Exception e) {
return false;
}
}
private String guessContentType(File file) {
final String unknown = "unknown";
if (!file.exists() || file.length() == 0) {
return unknown;
}
String type;
try {
//type = Files.probeContentType(file.toPath());
type = TikaUtils.instance().detectContentType(file);
} catch (IOException e) {
e.printStackTrace();
return unknown;
}
if (type != null) {
return type;
} else {
return unknown;
}
}
private void openApplicationExternal(File file) {
Task<Void> task = new Task<>() {
@Override
protected Void call() throws Exception {
Desktop.getDesktop().open(file);
return null;
}
};
task.setOnFailed(e -> ExceptionAlert.showAlert("Failed to open " + file, task.getException()));
Thread appthread = new Thread(task);
appthread.start();
}
private boolean strStartsWith(String fileNameLower, String... strOpt) {
for (String start : strOpt) {
if (fileNameLower.startsWith(start.toLowerCase())) {
return true;
}
}
return false;
}
private boolean strEndsWith(String fileNameLower, String... strOpt) {
for (String end : strOpt) {
if (fileNameLower.endsWith(end.toLowerCase())) {
return true;
}
}
return false;
}
private boolean strEquals(String fileNameLower, String... strOpt) {
for (String str : strOpt) {
if (fileNameLower.equalsIgnoreCase(str)) {
return true;
}
}
return false;
}
}
| 33.435897 | 121 | 0.636311 |
1eab009cfa9e9594414224d387fd9f8c844581d8 | 415 | package test.comments.block;
public class X11 {
public X11() {
this(/* comment */
false, /* whitespace */
false, /* nls */
false, /* sourceLevel */
0, /* taskTag */
null, /* taskPriorities */
null, /* taskCaseSensitive */
true);
}
public X11(boolean b, boolean c, boolean d, int i, Object object, Object object2, boolean e) {
}
}
| 21.842105 | 99 | 0.525301 |
59cfa823773b942a07c1d70799e095e3b174d7ae | 1,244 | package com.refactify.arguments;
public class ConversionArgumentsParser {
public ConversionArguments parseArguments(String[] arguments) {
ConversionArguments conversionArguments = new ConversionArguments();
try {
conversionArguments.setSource(arguments[arguments.length - 1]);
for (int i = 0; i < arguments.length - 1; i++) {
String argument = arguments[i];
if (argument.equals("-t") || argument.equals("--type")) {
String value = arguments[++i];
conversionArguments.setConversionType(ConversionArguments.ConversionType.fromString(value));
}
else if (argument.equals("-db") || argument.equals("--database")) {
String value = arguments[++i];
conversionArguments.setDatabase(value);
}
else if (argument.equals("-overwrite") || argument.equals("--overwrite")) {
conversionArguments.setOverwrite(true);
}
}
}
catch (ArrayIndexOutOfBoundsException exc) {
System.out.println("Invalid arguments.");
}
return conversionArguments;
}
}
| 41.466667 | 112 | 0.567524 |
c8a4abf42c472fbd1994a42a297c05aee99698d5 | 5,381 | package barsan.opengl.rendering;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import barsan.opengl.Yeti;
import barsan.opengl.input.InputProvider;
import barsan.opengl.math.Vector3;
import barsan.opengl.rendering.cameras.Camera;
import barsan.opengl.rendering.cameras.PerspectiveCamera;
import barsan.opengl.rendering.lights.AmbientLight;
import barsan.opengl.rendering.lights.Light;
import barsan.opengl.resources.ResourceLoader;
import barsan.opengl.util.Color;
import barsan.opengl.util.GUI;
public class Scene {
protected ArrayList<ModelInstance> modelInstances = new ArrayList<>();
// Billboards get special treatment as they're transparent
protected ArrayList<Billboard> billboards = new ArrayList<>();
protected Renderer renderer;
protected Camera camera;
protected boolean exiting = false;
/** Timing ****************************************************************/
long lastTime;
/** Lights ****************************************************************/
protected ArrayList<Light> lights = new ArrayList<>();
protected AmbientLight globalAmbientLight = new AmbientLight(new Color(0.1f, 0.1f, 0.1f, 1.0f));
/** Fog *******************************************************************/
protected boolean fogEnabled = false;
protected Fog fog;
protected GUI gui;
public boolean shadowsEnabled = false;
List<InputProvider> inputProviders = new ArrayList<>();
public void init(GLAutoDrawable drawable) {
// Setup basic elements
camera = new PerspectiveCamera(Yeti.get().settings.width, Yeti.get().settings.height);
try {
ResourceLoader.loadAllShaders(ResourceLoader.RESBASE);
} catch (IOException e) {
e.printStackTrace();
}
// TODO: a more elegat way to specify a renderer
// Prepare the renderer; use the default renderer
if(renderer == null) {
renderer = new ForwardRenderer(Yeti.get().gl.getGL3());
}
Renderer.renderDebug = Yeti.get().debug;
lastTime = System.nanoTime();
}
public void display(GLAutoDrawable drawable) {
if(exiting) {
exit();
return;
}
// Setup the renderer
RendererState rs = renderer.getState();
rs.setAmbientLight(globalAmbientLight);
rs.setCamera(camera);
rs.setLights(lights);
rs.setScene(this);
if(fogEnabled) {
rs.setFog(fog);
} else {
rs.setFog(null);
}
renderer.render(this);
if(gui != null) {
Yeti.get().gl.glDisable(GL2.GL_DEPTH_TEST);
gui.render();
Yeti.get().gl.glEnable(GL2.GL_DEPTH_TEST);
}
lastTime = System.nanoTime();
}
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
// TODO: this isn't enough - the renderer needs to resize its postprocess
// buffers as well - not a priority
/*
camera.width = width;
camera.height = height;
camera.refreshProjection();
*/
}
public void setCamera(Camera camera) {
// FIXME: connected camera inputs might have a problem with this
this.camera = camera;
}
public Camera getCamera() {
return camera;
}
public List<ModelInstance> getModelInstances() {
return modelInstances;
}
public void addModelInstance(ModelInstance modelInstance) {
assert (! (modelInstance instanceof Billboard)) : "Billboards should be handled separately!";
modelInstances.add(modelInstance);
}
public void removeModelInstance(ModelInstance modelInstance) {
modelInstances.remove(modelInstance);
}
public void addBillboard(Billboard billboard) {
billboards.add(billboard);
}
/**
* Adds a billboard and sets its z position. Useful in 2D scenes for positioning
* sprites "on top" of each other.
*/
public void addBillboard(Billboard billboard, float z) {
Vector3 p = billboard.getTransform().getTranslate();
billboard.getTransform().updateTranslate(p.x, p.y, z);
billboards.add(billboard);
}
public void addInput(InputProvider inputProvider) {
inputProviders.add(inputProvider);
Yeti.get().addInputProvider(inputProvider);
}
private void unregisterInputSources() {
Yeti y = Yeti.get();
for(InputProvider ip : inputProviders) {
y.removeInputProvider(ip);
}
}
public void setRenderer(Renderer renderer) {
this.renderer = renderer;
}
public Renderer getRenderer() {
return renderer;
}
/**
* Called when the scene simulation is to become interactive.
*/
public void play() { }
/**
* Called when the scene simulation should halt its interactivity and,
* among other things, release the cursor (if captured).
*/
public void pause() { }
/**
* Tells the OpenGL engine to shutdown before its next render cycle.
* Note: this might just begin a transition to quit the scene - the shutdown
* is not guaranteed to be immediate.
*
* @param engine Reference to the central engine.
* @param next (NYI) The next scene to transition to.
*/
public void beginExit(Yeti engine, Scene next) {
exiting = true;
this.engine = engine;
}
private Yeti engine;
protected void exit() {
// Temporary cleanup behavior - at the moment, scenes are independent
// of each other; for games, this doesn't make sense;
pause();
ResourceLoader.cleanUp();
renderer.dispose();
engine.transitionFinished();
unregisterInputSources();
exiting = false;
}
public List<Light> getLights() {
return lights;
}
}
| 25.995169 | 97 | 0.692994 |
d61064c425960b40083d65efe789c8a40412ba45 | 3,216 | /*
* Copyright © 2018 Mark Raynsford <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jrai;
import java.io.IOException;
import java.util.Objects;
import java.util.Properties;
import java.util.regex.Pattern;
/**
* Functions to parse configurations.
*/
public final class RConfigurations
{
private static final Pattern WHITESPACE = Pattern.compile("\\s+");
private RConfigurations()
{
}
/**
* Parse a configuration from the given properties.
*
* @param properties The input properties
*
* @return A parsed message
*
* @throws IOException On errors
*/
public static RConfiguration ofProperties(
final Properties properties)
throws IOException
{
Objects.requireNonNull(properties, "properties");
try {
final RConfiguration.Builder builder = RConfiguration.builder();
final String queues_value =
properties.getProperty("com.io7m.jrai.queues");
builder.setIrcHost(properties.getProperty("com.io7m.jrai.irc_server_host"));
builder.setIrcPort(Integer.parseInt(properties.getProperty("com.io7m.jrai.irc_server_port")));
builder.setIrcNickName(properties.getProperty("com.io7m.jrai.irc_nick"));
builder.setIrcUserName(properties.getProperty("com.io7m.jrai.irc_user"));
builder.setIrcChannel(properties.getProperty("com.io7m.jrai.irc_channel"));
for (final String queue : WHITESPACE.split(queues_value)) {
builder.addQueues(parseQueue(properties, queue));
}
return builder.build();
} catch (final Exception e) {
throw new IOException(e);
}
}
private static RQueueConfiguration parseQueue(
final Properties properties,
final String directory)
{
final RQueueConfiguration.Builder builder =
RQueueConfiguration.builder();
builder.setQueueAddress(properties.getProperty(
String.format("com.io7m.jrai.queues.%s.queue_address", directory)));
builder.setBrokerUser(properties.getProperty(
String.format("com.io7m.jrai.queues.%s.broker_user", directory)));
builder.setBrokerPassword(properties.getProperty(
String.format("com.io7m.jrai.queues.%s.broker_password", directory)));
builder.setBrokerAddress(properties.getProperty(
String.format("com.io7m.jrai.queues.%s.broker_address", directory)));
builder.setBrokerPort(Integer.parseInt(properties.getProperty(
String.format("com.io7m.jrai.queues.%s.broker_port", directory))));
return builder.build();
}
}
| 33.5 | 100 | 0.73041 |
a43c7a149ca2b6b298a99d39a1abef51197c791c | 1,433 | package de.tototec.cmdoption.handler;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import java.util.Arrays;
import de.tototec.cmdoption.internal.I18n;
import de.tototec.cmdoption.internal.I18n.PreparedI18n;
import de.tototec.cmdoption.internal.I18nFactory;
/**
* Apply an n-arg option to an (setter) method with n parameters of type
* {@link String}.
*
*/
public class StringMethodHandler implements CmdOptionHandler {
public boolean canHandle(final AccessibleObject element, final int argCount) {
if (element instanceof Method) {
final Method method = (Method) element;
if (method.getParameterTypes().length == argCount) {
boolean areStrings = true;
for (final Class<?> p : method.getParameterTypes()) {
areStrings &= String.class.isAssignableFrom(p);
}
return areStrings;
}
}
return false;
}
public void applyParams(final Object config, final AccessibleObject element, final String[] args,
final String optionName) throws CmdOptionHandlerException {
try {
final Method method = (Method) element;
method.invoke(config, (Object[]) args);
} catch (final Exception e) {
final I18n i18n = I18nFactory.getI18n(StringMethodHandler.class);
final PreparedI18n msg = i18n.preparetr("Could not apply parameters: {0} to method {1}",
Arrays.toString(args), element);
throw new CmdOptionHandlerException(msg.notr(), e, msg.tr());
}
}
}
| 31.844444 | 98 | 0.734124 |
c4ec2576adc73e86b4cf82730edd0afaca847332 | 14,483 | /*
* 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 com.github.lxyscls.jvmjava.nativemethod.java.lang;
import com.github.lxyscls.jvmjava.nativemethod.NativeMethod;
import com.github.lxyscls.jvmjava.runtimedata.Frame;
import com.github.lxyscls.jvmjava.runtimedata.heap.Jobject;
import com.github.lxyscls.jvmjava.runtimedata.heap.Jstring;
import com.github.lxyscls.jvmjava.runtimedata.heap.classfile.ClassLoader;
import com.github.lxyscls.jvmjava.runtimedata.heap.classfile.Field;
import com.github.lxyscls.jvmjava.runtimedata.heap.classfile.Jclass;
import com.github.lxyscls.jvmjava.runtimedata.heap.classfile.Method;
import com.github.lxyscls.jvmjava.runtimedata.heap.classfile.constant.MethodLookup;
import java.io.IOException;
/**
*
* @author sk-xinyilong
*/
public final class Nclass {
private Nclass() {}
public static void init() {
NativeMethod.registerNativeMethod("java/lang/Class", "registerNatives", "()V",
new NativeMethod() {
@Override
public void func(Frame frame) {
NativeMethod.registerNativeMethod("java/lang/Class", "getName0", "()Ljava/lang/String;",
new NativeMethod() {
@Override
public void func(Frame frame) {
Jobject clsobj = frame.getLocalVars().getRef(0);
Jclass cls = clsobj.getExtra();
frame.getOperandStack().pushRef(
Jstring.stringToInternObject(
cls.getClassLoader(), cls.getClassName().replace('/', '.')
)
);
}
}
);
NativeMethod.registerNativeMethod("java/lang/Class", "getModifiers", "()I",
new NativeMethod() {
@Override
public void func(Frame frame) {
Jobject clsObj = frame.getLocalVars().getRef(0);
frame.getOperandStack().pushInt(clsObj.getExtra().getAccessFlags());
}
}
);
NativeMethod.registerNativeMethod("java/lang/Class", "getSuperclass", "()Ljava/lang/Class;",
new NativeMethod() {
@Override
public void func(Frame frame) {
Jobject clsObj = frame.getLocalVars().getRef(0);
Jclass superCls = clsObj.getExtra().getSuperClass();
if (superCls != null) {
frame.getOperandStack().pushObject(superCls.getClassObject());
} else {
frame.getOperandStack().pushObject(null);
}
}
}
);
NativeMethod.registerNativeMethod("java/lang/Class", "desiredAssertionStatus0",
"(Ljava/lang/Class;)Z",
new NativeMethod() {
@Override
public void func(Frame frame) {
frame.getOperandStack().pushInt(0);
}
}
);
NativeMethod.registerNativeMethod("java/lang/Class", "isPrimitive",
"()Z",
new NativeMethod() {
@Override
public void func(Frame frame) {
Jobject obj = frame.getLocalVars().getRef(0);
if (obj.getExtra().isPrimitive()) {
frame.getOperandStack().pushInt(1);
} else {
frame.getOperandStack().pushInt(0);
}
}
}
);
NativeMethod.registerNativeMethod("java/lang/Class", "isInterface",
"()Z",
new NativeMethod() {
@Override
public void func(Frame frame) {
Jobject obj = frame.getLocalVars().getRef(0);
if (obj.getExtra().isInterface()) {
frame.getOperandStack().pushInt(1);
} else {
frame.getOperandStack().pushInt(0);
}
}
}
);
NativeMethod.registerNativeMethod("java/lang/Class", "getDeclaredFields0",
"(Z)[Ljava/lang/reflect/Field;",
new NativeMethod() {
@Override
public void func(Frame frame) {
try {
ClassLoader cl = frame.getMethod().getBelongClass().getClassLoader();
Jobject clsObj = frame.getLocalVars().getRef(0);
int publicOnly = frame.getLocalVars().getInt(1);
Field[] fields = clsObj.getExtra().getPublicOnlyField(publicOnly);
Jclass fieldCls = cl.loadClass("java/lang/reflect/Field");
Jobject fieldArr = fieldCls.newArrayClass().newArray(fields.length);
frame.getOperandStack().pushRef(fieldArr);
if (fieldArr.getArrayLength() > 0) {
Method fieldCtor = MethodLookup.lookupMethodInClass(fieldCls, "<init>",
"(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/Class;IILjava/lang/String;[B)V");
for (int i = 0; i < fieldArr.getArrayLength(); i++) {
fieldArr.getArray()[i] = fieldCls.newObject();
Frame newFrame = new Frame(frame.getThread(), fieldCtor);
frame.getThread().pushFrame(newFrame);
newFrame.getLocalVars().setRef(0, (Jobject)fieldArr.getArray()[i]); // this
newFrame.getLocalVars().setRef(1, clsObj); // declaringClass
newFrame.getLocalVars().setRef(2, Jstring.stringToInternObject(cl, fields[i].getName())); // name
newFrame.getLocalVars().setRef(3, fields[i].getTypeClass().getClassObject()); // type
newFrame.getLocalVars().setInt(4, fields[i].getAccessFlags()); // modifiers
newFrame.getLocalVars().setInt(5, fields[i].getSlotId()); // slot
newFrame.getLocalVars().setRef(6, Jstring.stringToInternObject(cl, fields[i].getSignature())); // signature
newFrame.getLocalVars().setRef(7, cl.loadClass("byte").newArrayClass().newArray(fields[i].getAnnotationData().length)); // annotations
}
}
} catch (IOException ex) {
System.err.println(ex);
System.exit(-1);
}
}
}
);
NativeMethod.registerNativeMethod("java/lang/Class", "getDeclaredConstructors0",
"(Z)[Ljava/lang/reflect/Constructor;",
new NativeMethod() {
@Override
public void func(Frame frame) {
try {
ClassLoader cl = frame.getMethod().getBelongClass().getClassLoader();
Jobject clsObj = frame.getLocalVars().getRef(0);
// 'not' publicOnly: DECLARED
int publicOnly = frame.getLocalVars().getInt(1);
Method[] ctors = clsObj.getExtra().getPublicOnlyCtor(publicOnly);
Jclass ctorCls = cl.loadClass("java/lang/reflect/Constructor");
Jobject ctorArr = ctorCls.newArrayClass().newArray(ctors.length);
frame.getOperandStack().pushRef(ctorArr);
if (ctorArr.getArrayLength() > 0) {
Method ctorCtor = MethodLookup.lookupMethodInClass(ctorCls, "<init>",
"(Ljava/lang/Class;[Ljava/lang/Class;[Ljava/lang/Class;IILjava/lang/String;[B[B)V");
for (int i = 0; i < ctorArr.getArrayLength(); i++) {
ctorArr.getArray()[i] = ctorCls.newObject();
Frame newFrame = new Frame(frame.getThread(), ctorCtor);
frame.getThread().pushFrame(newFrame);
newFrame.getLocalVars().setRef(0, (Jobject)ctorArr.getArray()[i]); // this
newFrame.getLocalVars().setRef(1, clsObj); // declaringClass
newFrame.getLocalVars().setObject(2, Jclass.toClassArr(cl, ctors[i].getArgTypes())); // parameterTypes
newFrame.getLocalVars().setObject(3, Jclass.toClassArr(cl, ctors[i].getExceptionTypes())); // checkedExceptions
newFrame.getLocalVars().setInt(4, ctors[i].getAccessFlags()); // modifiers
newFrame.getLocalVars().setInt(5, 0); // slot
newFrame.getLocalVars().setRef(6, Jstring.stringToInternObject(cl, ctors[i].getSignature())); // signature
newFrame.getLocalVars().setRef(7, cl.loadClass("byte").newArrayClass().newArray(ctors[i].getAnnotationData().length)); // annotations
newFrame.getLocalVars().setRef(8, cl.loadClass("byte").newArrayClass().newArray(ctors[i].getArgAnnotationData().length)); // parameterAnnotations
}
}
} catch (IOException ex) {
System.err.println(ex);
System.exit(-1);
}
}
}
);
}
}
);
NativeMethod.registerNativeMethod("java/lang/Class", "getPrimitiveClass",
"(Ljava/lang/String;)Ljava/lang/Class;",
new NativeMethod() {
@Override
public void func(Frame frame) {
Jobject jstr = frame.getLocalVars().getRef(0);
String clsname = Jstring.internObjectToString(jstr);
ClassLoader loader = frame.getMethod().getBelongClass().getClassLoader();
try {
Jobject clsobj = loader.loadClass(clsname).getClassObject();
frame.getOperandStack().pushRef(clsobj);
} catch (IOException ex) {
System.err.println(ex);
System.exit(-1);
}
}
}
);
NativeMethod.registerNativeMethod("java/lang/Class", "forName0",
"(Ljava/lang/String;ZLjava/lang/ClassLoader;Ljava/lang/Class;)Ljava/lang/Class;",
new NativeMethod() {
@Override
public void func(Frame frame) {
try {
String name = Jstring.internObjectToString(frame.getLocalVars().getRef(0));
int initialize = frame.getLocalVars().getInt(1);
Jclass cls = frame.getMethod().getBelongClass().getClassLoader().loadClass(name.replace(".", "/"));
if (initialize == 1&& !cls.getInitStarted()) {
frame.revertNextPc();
cls.clInitClass(frame);
} else {
frame.getOperandStack().pushRef(cls.getClassObject());
}
} catch (IOException ex) {
System.err.println(ex);
System.exit(-1);
}
}
}
);
}
}
| 62.158798 | 234 | 0.411724 |
bfd6c0c0ee0df35397c6b0d22985038f7f135e6c | 3,622 | package localhost.abec2304.kurokohi.lazy;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import localhost.abec2304.kurokohi.AttributeInfo;
import localhost.abec2304.kurokohi.AttrUnknown;
import localhost.abec2304.kurokohi.util.MultiByteArrayInputStream;
public class LazyAttrCode extends AttributeInfo {
public int maxStack;
public int maxLocals;
public byte[] code;
public int[][] exceptionTable;
public AttributeInfo[] attributes;
public boolean pre1_0;
public void init(AttrUnknown base) throws IOException {
attributeNameIndex = base.attributeNameIndex;
attributeLength = base.attributeLength;
InputStream sis = new MultiByteArrayInputStream(base.info);
DataInputStream dis = new DataInputStream(sis);
long codeLength;
if(pre1_0) {
maxStack = dis.readUnsignedByte();
maxLocals = dis.readUnsignedByte();
codeLength = dis.readUnsignedShort();
} else {
maxStack = dis.readUnsignedShort();
maxLocals = dis.readUnsignedShort();
codeLength = dis.readInt() & 0xFFFFFFFFL;
}
if(codeLength == 0 || codeLength >= 65536)
throw new IOException("codeLength must be 1-65535, was " + codeLength);
code = new byte[(int)codeLength];
dis.readFully(code);
exceptionTable = new int[dis.readUnsignedShort()][4];
for(int i = 0; i < exceptionTable.length; i++) {
int[] entry = exceptionTable[i];
entry[0] = dis.readUnsignedShort();
entry[1] = dis.readUnsignedShort();
entry[2] = dis.readUnsignedShort();
entry[3] = dis.readUnsignedShort();
}
attributes = new AttributeInfo[dis.readUnsignedShort()];
for(int i = 0; i < attributes.length; i++) {
AttributeInfo attribute = new AttrUnknown();
attribute.init(dis);
attributes[i] = attribute;
}
}
public void write(DataOutputStream dos) throws IOException {
writeHeader(dos);
if(pre1_0) {
dos.writeByte(maxStack);
dos.writeByte(maxLocals);
dos.writeShort(code.length);
} else {
dos.writeShort(maxStack);
dos.writeShort(maxLocals);
dos.writeInt(code.length);
}
dos.write(code);
dos.writeShort(exceptionTable.length);
for(int i = 0; i < exceptionTable.length; i++) {
int[] entry = exceptionTable[i];
dos.writeShort(entry[0]);
dos.writeShort(entry[1]);
dos.writeShort(entry[2]);
dos.writeShort(entry[3]);
}
dos.writeShort(attributes.length);
for(int i = 0; i < attributes.length; i++)
attributes[i].write(dos);
}
public void recalculateLength() {
if(pre1_0)
attributeLength = 4;
else
attributeLength = 8;
attributeLength += code.length;
attributeLength += 2;
attributeLength += 4 * exceptionTable.length;
attributeLength += 2;
attributeLength += 6 * attributes.length;
for(int i = 0; i < attributes.length; i++)
attributeLength += attributes[i].attributeLength;
}
public String getName() {
return "Code";
}
}
| 33.537037 | 84 | 0.569575 |
1a68524c06bb165296e0feebb5da61b6b539c4e3 | 15,103 | /*
* Copyright 2012 - 2014 Anton Tananaev (anton.tananaev@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.survos.tracker;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.util.Patterns;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.edmodo.rangebar.RangeBar;
import com.survos.tracker.Constants.Constants;
import com.survos.tracker.data.Utils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
/**
* Main user interface
*/
@SuppressWarnings("deprecation")
public class TraccarActivity extends PreferenceActivity implements View.OnClickListener {
public static final String LOG_TAG = "traccar";
public static final String KEY_ID = "id";
public static final String KEY_SUBJECT_ID = "subject_id";
// public static final String KEY_DEVICE_NAME = "device_name";
// public static final String KEY_ADDRESS = "address";
// public static final String KEY_PORT = "port";
public static final String KEY_INTERVAL = "interval";
public static final String KEY_STATUS = "status";
public static final String KEY_RESTRICT_TIME = "time_restrict";
public static final String KEY_RESTRICT_START_TIME = "restrict_start_time";
public static final String KEY_RESTRICT_STOP_TIME = "restrict_stop_time";
String oldVal;
/**
* holds the dialog for selecting time range
*/
private Dialog mSelectRestrictTimeDialog;
/**
* variable for holding sharedpreferences
*/
private SharedPreferences mSharedPreferences;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
mSharedPreferences = getPreferenceScreen().getSharedPreferences();
initPreferences();
oldVal = mSharedPreferences.getString(KEY_SUBJECT_ID, null);
if (mSharedPreferences.getBoolean(KEY_STATUS, false))
startService(new Intent(this, TraccarService.class));
}
@Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(
preferenceChangeListener);
}
@Override
protected void onPause() {
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
preferenceChangeListener);
super.onPause();
}
OnSharedPreferenceChangeListener preferenceChangeListener = new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, String key) {
if (key.equals(KEY_STATUS)) {
if (sharedPreferences.getBoolean(KEY_STATUS, false)) {
startService(new Intent(TraccarActivity.this, TraccarService.class));
} else {
stopService(new Intent(TraccarActivity.this, TraccarService.class));
}
} else if (key.equals(KEY_ID)) {
findPreference(KEY_ID).setSummary(sharedPreferences.getString(KEY_ID, null));
// } else if (key.equals(KEY_ADDRESS)) {
// findPreference(KEY_ADDRESS).setSummary(sharedPreferences.getString(KEY_ADDRESS, null));
} else if (key.equals(KEY_RESTRICT_TIME)) {
if (!sharedPreferences.getBoolean(KEY_RESTRICT_TIME, false)) {
findPreference(KEY_RESTRICT_TIME).setSummary(getResources().
getString(R.string.select_time_interval));
} else {
openSelectRestrictTimeDialog();
}
// } else if (key.equals(KEY_PORT)) {
//
// findPreference(KEY_PORT).setSummary(sharedPreferences.getString(KEY_PORT,
// getResources().getString(R.string.settings_port_summary)));
} else if (key.equals(KEY_INTERVAL)) {
findPreference(KEY_INTERVAL).setSummary(sharedPreferences.getString(KEY_INTERVAL,
getResources().getString(R.string.settings_interval_summary)));
}else if (key.equals(KEY_SUBJECT_ID)) {
Log.d("aaa","new val =>"+sharedPreferences.getString(KEY_SUBJECT_ID, null)+" and old=>"+oldVal);
if(Utils.validateSubjectID(Integer.parseInt(sharedPreferences.getString(KEY_SUBJECT_ID, null)))) {
Log.d("aaa", "inside if");
findPreference(KEY_SUBJECT_ID).setSummary(sharedPreferences.getString(KEY_SUBJECT_ID, null));
}
else
{
Log.d("aaa","inside else");
sharedPreferences.edit().putString(KEY_SUBJECT_ID, oldVal).commit();
PreferenceScreen screen = (PreferenceScreen) findPreference("preferencescreen");
screen.onItemClick( null, null, 2, 0 );
screen.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Log.d("aaa","preference change");
if(Utils.validateSubjectID(Integer.parseInt(sharedPreferences.getString(KEY_SUBJECT_ID, null))))
findPreference(KEY_SUBJECT_ID).setSummary(sharedPreferences.getString(KEY_SUBJECT_ID, null));
return false;
}
});
Toast.makeText(TraccarActivity.this,"Enter Valid SubjectId",Toast.LENGTH_SHORT).show();
}
}/*else if (key.equals(KEY_DEVICE_NAME)) {
// findPreference(KEY_DEVICE_NAME).setSummary(sharedPreferences.getString(KEY_DEVICE_NAME, null));
}*/
}
};
private void openSelectRestrictTimeDialog() {
// custom dialog
mSelectRestrictTimeDialog = new Dialog(this);
mSelectRestrictTimeDialog.setContentView(R.layout.layout_restrict_time_dialog);
mSelectRestrictTimeDialog.setTitle("Restrict Time");
final TextView timeDifferenceText = (TextView) mSelectRestrictTimeDialog.findViewById(R.id.time_difference);
final Button setButton = (Button) mSelectRestrictTimeDialog.findViewById(R.id.set_button);
//setting up range bar
RangeBar rangebar = (RangeBar) mSelectRestrictTimeDialog.findViewById(R.id.rangebar);
rangebar.setTickCount(24);
rangebar.setTickHeight(25);
rangebar.setBarWeight(6);
rangebar.setBarColor(229999999);
int startTime = mSharedPreferences.getInt(KEY_RESTRICT_START_TIME, 0);
int stopTime = mSharedPreferences.getInt(KEY_RESTRICT_STOP_TIME, 24);
rangebar.setThumbIndices(startTime , stopTime - 1);
String startString = "",stopString = "";
try {
DateFormat f1 = new SimpleDateFormat("HH");
Date d = f1.parse(startTime + "");
DateFormat f2 = new SimpleDateFormat("hh:mma");
stopString = f2.format(f1.parse(startTime + "")).toLowerCase();
startString = f2.format(d).toLowerCase();
}
catch (ParseException e) {
}
timeDifferenceText.setText(startString + " - " + stopString);
rangebar.setOnRangeBarChangeListener(new RangeBar.OnRangeBarChangeListener() {
@Override
public void onIndexChangeListener(RangeBar rangeBar, int leftThumbIndex, int rightThumbIndex) {
mSharedPreferences.edit().putInt(KEY_RESTRICT_START_TIME, leftThumbIndex + 1).commit();
mSharedPreferences.edit().putInt(KEY_RESTRICT_STOP_TIME, rightThumbIndex + 1).commit();
String startString = "",stopString = "";
try {
DateFormat f1 = new SimpleDateFormat("HH");
Date d = f1.parse(leftThumbIndex + "");
DateFormat f2 = new SimpleDateFormat("hh:mma");
stopString = f2.format(f1.parse(rightThumbIndex + 1 + "")).toLowerCase();
startString = f2.format(d).toLowerCase();
}
catch (ParseException e) {
}
findPreference(KEY_RESTRICT_TIME).setSummary(startString + " - " + stopString);
timeDifferenceText.setText(startString + " - " + stopString);
}
});
setButton.setOnClickListener(this);
mSelectRestrictTimeDialog.show();
}
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_map_home, menu);
// return true;
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// // Handle action bar item clicks here. The action bar will
// // automatically handle clicks on the Home/Up button, so long
// // as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
//
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
//
//
// final Intent settings = new Intent(this,
// TraccarActivity.class);
// startActivity(settings);
// return true;
// }
//
//// else if (id == R.id.status) {
////
//// startActivity(new Intent(this, StatusActivity.class));
////
//// return true;
//// }
// else if (id == R.id.about) {
//
//
// startActivity(new Intent(this, AboutActivity.class));
//
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }
private boolean isServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (TraccarService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
private void initPreferences() {
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
// TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// String id = telephonyManager.getDeviceId();
String id = getPrimaryEmailAccount();
Log.d("divyesh", "email=>"+id);
SharedPreferences sharedPreferences = getPreferenceScreen().getSharedPreferences();
if (!sharedPreferences.contains(KEY_ID)) {
sharedPreferences.edit().putString(KEY_ID, id).commit();
}
// String serverAddress = sharedPreferences.getString(KEY_ADDRESS, getResources().getString(R.string.settings_address_summary));
//
// findPreference(KEY_PORT).setSummary(sharedPreferences.getString(KEY_PORT,
// getResources().getString(R.string.settings_port_summary)));
/* findPreference(KEY_INTERVAL).setSummary(sharedPreferences.getString(KEY_INTERVAL,
getResources().getString(R.string.settings_interval_summary)));*/
findPreference(KEY_INTERVAL).setSummary(sharedPreferences.getString(KEY_INTERVAL,""+60));
findPreference("mobilenumber").setSummary(sharedPreferences.getString("mobilenumber",sharedPreferences.getString("mobilenumber","")));
findPreference(KEY_SUBJECT_ID).setSummary(sharedPreferences.getString(KEY_SUBJECT_ID,
getResources().getString(R.string.settings_subject_id_summary)));
// findPreference(KEY_DEVICE_NAME).setSummary(sharedPreferences.getString(KEY_DEVICE_NAME,
// getResources().getString(R.string.settings_device_name_summary)));
findPreference(KEY_ID).setSummary(sharedPreferences.getString(KEY_ID, id));
// findPreference(KEY_ADDRESS).setSummary(sharedPreferences.getString(KEY_ADDRESS, serverAddress));
if (sharedPreferences.getBoolean(KEY_RESTRICT_TIME, false)) {
int startTime = sharedPreferences.getInt(KEY_RESTRICT_START_TIME, 0);
int stopTime = sharedPreferences.getInt(KEY_RESTRICT_STOP_TIME, 24);
String startString = "",stopString = "";
try {
DateFormat f1 = new SimpleDateFormat("HH");
Date d = f1.parse(startTime+1 + "");
DateFormat f2 = new SimpleDateFormat("hh:mma");
stopString = f2.format(f1.parse(stopTime+1 + "")).toLowerCase();
startString = f2.format(d).toLowerCase();
}
catch (ParseException e) {
}
findPreference(KEY_RESTRICT_TIME).setSummary(startString + " - " + stopString);
} else {
// findPreference(KEY_RESTRICT_TIME).setSummary(getResources().getString(R.string.select_time_interval));
findPreference(KEY_RESTRICT_TIME).setSummary("12:00am - 11:59pm");
}
}
private String getPrimaryEmailAccount() {
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
String possibleEmail = "";
Account[] accounts = AccountManager.get(this).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
possibleEmail = account.name;
}
}
return possibleEmail;
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.set_button) {
mSelectRestrictTimeDialog.dismiss();
}
}
}
| 40.382353 | 142 | 0.651261 |
0d9c79d2a9863b50b02c11228191c406654bf28a | 753 | package ru.job4j.array;
/**
* Class
* {true, true, true} - return true;
* {true, false, true} - return false;
* {false, false, false} - return true;
*/
public class Check {
/**
* Checking that all array items have the same boolean value.
* {true, true, true} - return true;
* {true, false, true} - return false;
* {false, false, false} - return true;
*
* @param array Input array
* @return Boolean value of the array checking.
*/
public boolean mono(boolean[] array) {
boolean result = true;
for (int i = 0; i < array.length - 1 && result; i++) {
if (array[i] != array[i + 1]) {
result = false;
}
}
return result;
}
}
| 25.965517 | 66 | 0.528552 |
2f1d95fda8f27caa3b359c49b0f3b6213c79e7bd | 1,516 | package org.knowm.xchange.huobi.service;
import java.io.IOException;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.huobi.HuobiUtils;
import org.knowm.xchange.huobi.dto.marketdata.HuobiAssetPair;
import org.knowm.xchange.huobi.dto.marketdata.HuobiDepth;
import org.knowm.xchange.huobi.dto.marketdata.HuobiTicker;
import org.knowm.xchange.huobi.dto.marketdata.results.HuobiAssetPairsResult;
import org.knowm.xchange.huobi.dto.marketdata.results.HuobiDepthResult;
import org.knowm.xchange.huobi.dto.marketdata.results.HuobiTickerResult;
public class HuobiMarketDataServiceRaw extends HuobiBaseService {
public HuobiMarketDataServiceRaw(Exchange exchange) {
super(exchange);
}
public HuobiTicker getHuobiTicker(CurrencyPair currencyPair) throws IOException {
String huobiCurrencyPair = HuobiUtils.createHuobiCurrencyPair(currencyPair);
HuobiTickerResult tickerResult = huobi.getTicker(huobiCurrencyPair);
return checkResult(tickerResult);
}
public HuobiAssetPair[] getHuobiAssetPairs() throws IOException {
HuobiAssetPairsResult assetPairsResult = huobi.getAssetPairs();
return checkResult(assetPairsResult);
}
public HuobiDepth getHuobiDepth(CurrencyPair currencyPair, String depthType) throws IOException {
String huobiCurrencyPair = HuobiUtils.createHuobiCurrencyPair(currencyPair);
HuobiDepthResult depthResult = huobi.getDepth(huobiCurrencyPair, depthType);
return checkResult(depthResult);
}
}
| 40.972973 | 99 | 0.82124 |
43c7764f218f30523f2b00f687907cfd46fb2ca8 | 1,354 | package io.github.winterbear.wintercore.wonderhaul.sockets.application;
import io.github.winterbear.wintercore.utils.LoreUtils;
import io.github.winterbear.wintercore.wonderhaul.sockets.ISocketable;
import io.github.winterbear.wintercore.wonderhaul.sockets.SocketType;
import io.github.winterbear.wintercore.wonderhaul.sockets.infusions.Infusions;
import io.github.winterbear.wintercore.wonderhaul.sockets.ornaments.Ornaments;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
/**
* Created by WinterBear on 31/08/2020.
*/
public class SocketParser {
public static Optional<ISocketable> parse(ItemStack item){
return Arrays.stream(SocketType.values())
.flatMap(s -> LoreUtils.getTag(item, s.getName()).stream())
.map(SocketParser::parse)
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
}
public static Optional<ISocketable> parse(String string){
Collection<ISocketable> sockets = new ArrayList<>();
sockets.addAll(Infusions.INFUSIONS);
sockets.addAll(Ornaments.ORNAMENTS);
return sockets.stream()
.filter(i -> i.getAbilityName().equals(string))
.findFirst();
}
}
| 33.02439 | 78 | 0.700148 |
1272b0da9630f7aa2e7a4d54f0f3dec9b02331cc | 2,675 | package com.woshidaniu.cache.core;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.woshidaniu.basicutils.StringUtils;
import com.woshidaniu.cache.core.exception.CacheException;
import com.woshidaniu.cache.core.utils.LifecycleUtils;
@SuppressWarnings({"unchecked","rawtypes"})
public abstract class AbstractCacheManager implements CacheManager,Destroyable {
/**
* Retains all Cache objects maintained by this cache manager.
*/
private final ConcurrentMap<String, Cache> caches;
/**
* Default no-arg constructor that instantiates an internal name-to-cache {@code ConcurrentMap}.
*/
public AbstractCacheManager() {
this.caches = new ConcurrentHashMap<String, Cache>();
}
//protected abstract Collection<? extends Cache> addCaches();
protected abstract <K, V> Cache<K, V> createCache(String name) throws CacheException;
@Override
public final <K, V> Cache<K, V> getCache(String name) throws IllegalArgumentException, CacheException {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Cache name cannot be null or empty.");
}
Cache cache = caches.get(name);
if (cache == null) {
cache = this.createCache(name);
Cache existing = caches.putIfAbsent(name, cache);
if (existing != null) {
cache = existing;
}
}
//noinspection unchecked
return cache;
}
@Override
public Collection<String> getCacheNames() {
if(caches != null){
Set<String> cacheNames = new LinkedHashSet<String>();
for (Cache cache : caches.values()) {
cacheNames.add(cache.getName());
}
return Collections.unmodifiableSet(cacheNames);
}
return null;
}
public void destroy() throws Exception {
while (!caches.isEmpty()) {
for (Cache cache : caches.values()) {
LifecycleUtils.destroy(cache);
}
caches.clear();
}
}
public String toString() {
Collection<Cache> values = caches.values();
StringBuilder sb = new StringBuilder(getClass().getSimpleName())
.append(" with ")
.append(caches.size())
.append(" cache(s)): [");
int i = 0;
for (Cache cache : values) {
if (i > 0) {
sb.append(", ");
}
sb.append(cache.toString());
i++;
}
sb.append("]");
return sb.toString();
}
}
| 28.763441 | 104 | 0.620187 |
41e2b7d306d4e4aeb4da968d79251b4405a4e80e | 177 | package net.canarymod.api.world.blocks;
/**
* Map Color wrapper
*
* @author Jason (darkdiplomat)
*/
public interface MapColor {
int getIndex();
int getValue();
}
| 12.642857 | 39 | 0.655367 |
67d4d28714182c269d4e7a05f833e779401ef7bc | 2,027 | package com.github.wdestroier.chamomile.classfile.attributeinfo;
import com.github.wdestroier.chamomile.classfile.pseudostructure.PseudoStructure;
import com.github.wdestroier.chamomile.classfile.pseudostructure.PseudoStructureFactory;
import com.github.wdestroier.chamomile.io.MultiEndianInputStream;
import com.github.wdestroier.chamomile.io.MultiEndianOutputStream;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MethodParametersAttribute implements PseudoStructure<MethodParametersAttribute> {
private int attributeNameIndex;
private long attributeLength;
private short parametersCount;
private Parameter[] parameters;
@Override
public MethodParametersAttribute read(MultiEndianInputStream input, PseudoStructureFactory pseudoStructureFactory) {
attributeNameIndex = input.readUnsignedShort();
attributeLength = input.readUnsignedInt();
parametersCount = input.readUnsignedByte();
parameters = new Parameter[parametersCount];
for (var i = 0; i < parametersCount; i++) {
parameters[i] = new Parameter().read(input, pseudoStructureFactory);
}
return this;
}
@Override
public void write(MultiEndianOutputStream output) {
output.writeUnsignedShort(attributeNameIndex);
output.writeUnsignedInt(attributeLength);
output.writeUnsignedShort(attributeNameIndex);
for (var parameter : parameters) {
parameter.write(output);
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class Parameter implements PseudoStructure<Parameter> {
private int nameIndex;
private int accessFlags;
@Override
public Parameter read(MultiEndianInputStream input, PseudoStructureFactory pseudoStructureFactory) {
nameIndex = input.readUnsignedShort();
accessFlags = input.readUnsignedShort();
return this;
}
@Override
public void write(MultiEndianOutputStream output) {
output.writeUnsignedShort(nameIndex);
output.writeUnsignedShort(accessFlags);
}
}
}
| 28.152778 | 117 | 0.806117 |
60b571d17e27f05900427bc6cb3dc942bef6b23f | 3,027 | package com.bytehonor.sdk.server.bytehonor.jdbc.update;
import java.util.List;
import java.util.Objects;
import com.bytehonor.sdk.define.bytehonor.error.ServerBasicException;
import com.bytehonor.sdk.define.bytehonor.util.StringObject;
import com.bytehonor.sdk.lang.bytehonor.string.StringCreator;
import com.bytehonor.sdk.server.bytehonor.jdbc.AbstractStatement;
import com.bytehonor.sdk.server.bytehonor.jdbc.MatchColumnHolder;
import com.bytehonor.sdk.server.bytehonor.jdbc.SqlInjectUtils;
import com.bytehonor.sdk.server.bytehonor.query.MatchColumn;
public class UpdatePreparedStatement implements AbstractStatement {
private final String table;
private final UpdateColumnHolder updateHolder;
private final MatchColumnHolder matchHolder;
private UpdatePreparedStatement(String table) {
this.table = table;
this.updateHolder = UpdateColumnHolder.create();
this.matchHolder = MatchColumnHolder.create();
}
public static UpdatePreparedStatement create(String table) {
Objects.requireNonNull(table, "table");
return new UpdatePreparedStatement(table);
}
public UpdatePreparedStatement set(String key, String value) {
if (StringObject.isEmpty(value)) {
return this;
}
this.updateHolder.set(key, value);
return this;
}
public UpdatePreparedStatement set(String key, Long value) {
this.updateHolder.set(key, value);
return this;
}
public UpdatePreparedStatement set(String key, Integer value) {
this.updateHolder.set(key, value);
return this;
}
public UpdatePreparedStatement set(String key, Boolean value) {
this.updateHolder.set(key, value);
return this;
}
public UpdatePreparedStatement set(String key, Double value) {
this.updateHolder.set(key, value);
return this;
}
public UpdatePreparedStatement match(MatchColumn column) {
this.matchHolder.and(column);
return this;
}
public String getTable() {
return table;
}
public UpdateColumnHolder getHolder() {
return updateHolder;
}
@Override
public String toString() {
return toUpdateSql();
}
public String toUpdateSql() {
return StringCreator.create().append("UPDATE ").append(table).append(updateHolder.toSql()).append(" WHERE 1=1")
.append(matchHolder.toAndSql()).toString();
}
public List<Object> listArgs() {
if (matchHolder.getArgs().isEmpty()) {
throw new ServerBasicException(44, "update but without any match condition");
}
List<Object> args = updateHolder.getArgs();
args.addAll(matchHolder.getArgs());
return args;
}
@Override
public List<Integer> listTypes() {
return matchHolder.getArgTypes();
}
@Override
public Object[] args() {
return listArgs().toArray();
}
@Override
public int[] types() {
return SqlInjectUtils.listArray(listTypes());
}
}
| 27.770642 | 119 | 0.685828 |
e664a4f6ce413b2729fb53ed9f598ae3c14da02e | 2,384 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axiom.ts.om.element;
import java.util.Arrays;
import javax.xml.stream.XMLStreamReader;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMMetaFactory;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.om.OMText;
import org.apache.axiom.ts.AxiomTestCase;
public class TestGetXMLStreamReaderCDATAEventFromElement extends AxiomTestCase {
public TestGetXMLStreamReaderCDATAEventFromElement(OMMetaFactory metaFactory) {
super(metaFactory);
}
@Override
protected void runTest() throws Throwable {
OMFactory omfactory = metaFactory.getOMFactory();
OMElement element = omfactory.createOMElement("test", null);
OMText cdata = omfactory.createOMText("hello world", OMNode.CDATA_SECTION_NODE);
element.addChild(cdata);
// Get the XMLStreamReader for the element. This will return an OMStAXWrapper.
XMLStreamReader reader2 = element.getXMLStreamReader();
// Check the sequence of events
int event = reader2.next();
assertEquals(XMLStreamReader.START_ELEMENT, event);
while (reader2.hasNext() && event != XMLStreamReader.CDATA) {
event = reader2.next();
}
assertEquals(XMLStreamReader.CDATA, event);
assertEquals("hello world", reader2.getText()); // AXIOM-146
assertTrue(Arrays.equals("hello world".toCharArray(), reader2.getTextCharacters())); // AXIOM-144
assertEquals(XMLStreamReader.END_ELEMENT, reader2.next());
}
}
| 39.733333 | 105 | 0.723993 |
cb77e0b38b4cb6529e90989f35b2a2332e575f15 | 6,323 | /*
* This file is a part of BSL Language Server.
*
* Copyright (c) 2018-2021
* Alexey Sosnoviy <labotamy@gmail.com>, Nikita Gryzlov <nixel2007@gmail.com> and contributors
*
* SPDX-License-Identifier: LGPL-3.0-or-later
*
* BSL Language Server is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* BSL Language Server is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BSL Language Server.
*/
package com.github._1c_syntax.bsl.languageserver.diagnostics;
import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticMetadata;
import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticScope;
import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticSeverity;
import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticTag;
import com.github._1c_syntax.bsl.languageserver.diagnostics.metadata.DiagnosticType;
import com.github._1c_syntax.bsl.languageserver.utils.Trees;
import com.github._1c_syntax.bsl.parser.BSLParser;
import com.github._1c_syntax.bsl.parser.BSLParserRuleContext;
import com.github._1c_syntax.utils.CaseInsensitivePattern;
import org.antlr.v4.runtime.tree.ParseTree;
import javax.annotation.Nullable;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
@DiagnosticMetadata(
type = DiagnosticType.CODE_SMELL,
severity = DiagnosticSeverity.MAJOR,
scope = DiagnosticScope.BSL,
minutesToFix = 5,
tags = {
DiagnosticTag.ERROR
}
)
public class IsInRoleMethodDiagnostic extends AbstractVisitorDiagnostic {
private static final Pattern IS_IN_ROLE_NAME_PATTERN = CaseInsensitivePattern.compile(
"(РольДоступна|IsInRole)"
);
private static final Pattern PRIVILEGED_MODE_NAME_PATTERN = CaseInsensitivePattern.compile(
"(ПривилегированныйРежим|PrivilegedMode)"
);
private static final Set<Integer> ROOT_PARENTS_FOR_GLOBAL_METHODS =
Set.of(BSLParser.RULE_ifStatement, BSLParser.RULE_assignment);
private final Set<String> isInRoleVars = new HashSet<>();
private final Set<String> privilegedModeNameVars = new HashSet<>();
@Override
public ParseTree visitFile(BSLParser.FileContext ctx) {
isInRoleVars.clear();
privilegedModeNameVars.clear();
return super.visitFile(ctx);
}
@Override
public ParseTree visitIfBranch(BSLParser.IfBranchContext ctx) {
computeDiagnostics(ctx.expression());
return super.visitIfBranch(ctx);
}
@Override
public ParseTree visitElsifBranch(BSLParser.ElsifBranchContext ctx) {
computeDiagnostics(ctx.expression());
return super.visitElsifBranch(ctx);
}
private void computeDiagnostics(BSLParser.ExpressionContext expression) {
Trees.findAllRuleNodes(expression, BSLParser.RULE_complexIdentifier).stream()
.map(complexCtx -> (BSLParser.ComplexIdentifierContext) complexCtx)
.filter(complexCtx -> isInRoleVars.contains(complexCtx.getText()))
.filter(ctx -> checkStatement(ctx, expression))
.forEach(diagnosticStorage::addDiagnostic);
}
@Override
public ParseTree visitGlobalMethodCall(BSLParser.GlobalMethodCallContext ctx) {
final var text = ctx.methodName().getText();
if (IS_IN_ROLE_NAME_PATTERN.matcher(text).matches()) {
handleIsInRoleGlobalMethod(ctx);
} else if (PRIVILEGED_MODE_NAME_PATTERN.matcher(text).matches()) {
handlePrivilegedModeGlobalMethod(ctx);
}
return super.visitGlobalMethodCall(ctx);
}
private void handleIsInRoleGlobalMethod(BSLParser.GlobalMethodCallContext ctx) {
var rootParent = Trees.getRootParent(ctx, ROOT_PARENTS_FOR_GLOBAL_METHODS);
if (rootParent == null) {
return;
}
if (rootParent.getRuleIndex() == BSLParser.RULE_ifStatement) {
if (checkStatement(ctx)) {
diagnosticStorage.addDiagnostic(ctx);
}
} else if (rootParent.getRuleIndex() == BSLParser.RULE_assignment) {
addAssignedNameVar(rootParent, isInRoleVars);
}
}
private void handlePrivilegedModeGlobalMethod(BSLParser.GlobalMethodCallContext ctx) {
var assignmentNode = Trees.getRootParent(ctx, BSLParser.RULE_assignment);
if (assignmentNode != null) {
addAssignedNameVar(assignmentNode, privilegedModeNameVars);
}
}
private static void addAssignedNameVar(BSLParserRuleContext assignmentNode, Set<String> nameVars) {
var childNode = Trees.getFirstChild(assignmentNode, BSLParser.RULE_lValue);
childNode.ifPresent(node -> nameVars.add(node.getText()));
}
@Override
public ParseTree visitAssignment(BSLParser.AssignmentContext ctx) {
var childNode = Trees.getFirstChild(ctx, BSLParser.RULE_lValue);
childNode.ifPresent((BSLParserRuleContext node) ->
{
isInRoleVars.remove(node.getText());
privilegedModeNameVars.remove(node.getText());
});
return super.visitAssignment(ctx);
}
private boolean checkStatement(BSLParserRuleContext ctx) {
var parentExpression = Trees.getRootParent(ctx, BSLParser.RULE_expression);
return checkStatement(ctx, parentExpression);
}
private boolean checkStatement(BSLParserRuleContext ctx, @Nullable BSLParserRuleContext parentExpression) {
if (parentExpression == null) {
return false;
}
var identifierList = Trees.findAllRuleNodes(parentExpression, BSLParser.RULE_complexIdentifier);
for (ParseTree parseTree : identifierList) {
if (privilegedModeNameVars.contains(parseTree.getText())) {
return false;
}
}
var nextGlobalMethodNode = Trees.getNextNode(parentExpression,
ctx, BSLParser.RULE_globalMethodCall);
boolean hasPrivilegedModeCheck = (nextGlobalMethodNode instanceof BSLParser.GlobalMethodCallContext
&& PRIVILEGED_MODE_NAME_PATTERN.matcher(((BSLParser.GlobalMethodCallContext) nextGlobalMethodNode)
.methodName().getText()).matches());
return !hasPrivilegedModeCheck;
}
}
| 36.976608 | 109 | 0.765301 |
31a2afe676344010a67e4c8d84d107a925b87210 | 4,316 | /*
* Copyright (c) 2014. stuart-warren
* Last modified: 17/08/14 12:06
*
* 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.stuartwarren.chatit;
import com.hazelcast.config.ClasspathXmlConfig;
import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import org.atmosphere.config.service.*;
import org.atmosphere.cpr.*;
import org.atmosphere.plugin.hazelcast.HazelcastBroadcaster;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ConcurrentMap;
/**
* Created by stuart-warren on 17/08/14.
*/
@ManagedService(path = "/chat/{room: [a-zA-Z][a-zA-Z0-9]*}", broadcaster = HazelcastBroadcaster.class)
public class ChatRoomManagedService {
private final HazelcastInstance hzlcst = Hazelcast.getAllHazelcastInstances().iterator().next();
private final Logger logger = LoggerFactory.getLogger(ChatRoomManagedService.class);
@PathParam("room")
private String chatroomName;
private ConcurrentMap<String, String> users;
private BroadcasterFactory broadcasterFactory;
private AtmosphereResourceFactory resourceFactory;
@Ready(encoders = {JacksonEncoder.class})
@DeliverTo(DeliverTo.DELIVER_TO.ALL)
public ChatProtocol onReady(final AtmosphereResource resource) {
logger.info("Browser {} connected.", resource.uuid());
broadcasterFactory = resource.getAtmosphereConfig().getBroadcasterFactory();
resourceFactory = resource.getAtmosphereConfig().resourcesFactory();
users = hzlcst.getMap("users-in-room_" + chatroomName);
return new ChatProtocol(users.keySet(), getRooms(broadcasterFactory.lookupAll()));
}
private static Collection<String> getRooms(Collection<Broadcaster> broadcasters) {
Collection<String> result = new ArrayList<String>();
for (Broadcaster broadcaster: broadcasters) {
if (!("/*".equals(broadcaster.getID()))) {
result.add(broadcaster.getID().split("/")[2]);
}
}
return result;
}
@Disconnect
public void onDisconnect(AtmosphereResourceEvent event) {
if (event.isCancelled()) {
// We didn't get notified, so remove the user
users.values().remove(event.getResource().uuid());
logger.warn("Browser {} unexpectedly disconnected.", event.getResource().uuid());
} else if (event.isClosedByClient()) {
logger.info("Browser {} closed it's connection.", event.getResource().uuid());
}
}
@Message(encoders = {JacksonEncoder.class}, decoders = {ChatProtocolDecoder.class})
public ChatProtocol onMessage(ChatProtocol message) throws IOException{
logger.debug("Author: {} | Users: {} | Msg: {} ", new String[]{message.getAuthor(), users.keySet().toString(), message.getUuid()});
if ((!users.containsKey(message.getAuthor())) && (message.getAuthor() != "")) {
users.putIfAbsent(message.getAuthor(), message.getUuid());
return new ChatProtocol(message.getAuthor(), " entered room " + chatroomName, users.keySet(), getRooms(broadcasterFactory.lookupAll()));
}
if (message.getMessage().contains("disconnecting")) {
users.remove(message.getAuthor());
return new ChatProtocol(message.getAuthor(), " disconnected from room " + chatroomName, users.keySet(), getRooms(broadcasterFactory.lookupAll()));
}
message.setUsers(users.keySet());
logger.info("{} just sent {}", message.getAuthor(), message.getMessage());
return new ChatProtocol(message.getAuthor(), message.getMessage(), users.keySet(), getRooms(broadcasterFactory.lookupAll()));
}
}
| 41.902913 | 158 | 0.698795 |
6424737e7eeb1f421387b9e61bddc903e0f2e720 | 1,049 | package com.puppycrawl.tools.checkstyle.checks.annotation;
//this file compiles in eclipse 3.4 but not with Sun's JDK 1.6.0.11
/**
*/
public class InputAnnotationUseWithTrailingComma
{
@SuppressWarnings({"common",})
public void foo() {
@SuppressWarnings({"common","foo",})
Object o = new Object() {
@SuppressWarnings(value={"common",})
public String toString() {
@SuppressWarnings(value={"leo","herbie",})
final String pooches = "leo.herbie";
return pooches;
}
};
}
@Test(value={(false) ? "" : "foo",}, more={(true) ? "" : "bar",})
/**
*/
enum P {
@Pooches(tokens={Pooches.class,},other={1,})
L,
/**
*/
Y;
}
}
@interface Test {
String[] value();
String[] more() default {};
/**
*/
}
@interface Pooches {
Class<?>[] tokens();
int[] other();
}
| 18.403509 | 69 | 0.458532 |
9a739bec8b54e0c2cf77418327b0d8554f1524c7 | 4,952 | /*
* JBoss, Home of Professional Open Source
* Copyright 2009 Red Hat Inc. and/or its affiliates and other contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.arquillian.container.spi.client.deployment;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.jboss.arquillian.container.spi.ConfigurationException;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
/**
* Validate
* <p>
* Validation utility
*
* @author <a href="mailto:aslak@conduct.no">Aslak Knutsen</a>
* @author <a href="mailto:tommy.tynja@diabol.se">Tommy Tynjä</a>
* @version $Revision: $
*/
public final class Validate {
private static Map<Class<? extends Archive<?>>, String> archiveExpressions;
static {
archiveExpressions = new HashMap<Class<? extends Archive<?>>, String>();
archiveExpressions.put(JavaArchive.class, ".jar");
archiveExpressions.put(WebArchive.class, ".war");
archiveExpressions.put(EnterpriseArchive.class, ".ear");
archiveExpressions.put(ResourceAdapterArchive.class, ".rar");
}
private Validate() {
}
public static String getArchiveExpression(Class<? extends Archive<?>> type) {
return archiveExpressions.get(type);
}
public static boolean archiveHasExpectedFileExtension(final Archive<?> archive) {
final String name = archive.getName();
for (Map.Entry<Class<? extends Archive<?>>, String> entry : archiveExpressions.entrySet()) {
if (!name.endsWith(entry.getValue()) && entry.getKey().isInstance(archive)) {
return false;
}
}
return true;
}
public static boolean isArchiveOfType(Class<? extends Archive<?>> type, Archive<?> archive) {
String expression = getArchiveExpression(type);
if (expression == null) {
return false;
}
return archive.getName().endsWith(expression);
}
/**
* Checks that object is not null, throws exception if it is.
*
* @param obj
* The object to check
* @param message
* The exception message
*
* @throws IllegalArgumentException
* Thrown if obj is null
*/
public static void notNull(final Object obj, final String message) throws IllegalArgumentException {
if (obj == null) {
throw new IllegalArgumentException(message);
}
}
/**
* Checks that the specified String is not null or empty,
* throws exception if it is.
*
* @param string
* The object to check
* @param message
* The exception message
*
* @throws IllegalArgumentException
* Thrown if obj is null
*/
public static void notNullOrEmpty(final String string, final String message) throws IllegalArgumentException {
if (string == null || string.length() == 0) {
throw new IllegalArgumentException(message);
}
}
/**
* Checks that obj is not null, throws exception if it is.
*
* @param obj
* The object to check
* @param message
* The exception message
*
* @throws IllegalStateException
* Thrown if obj is null
*/
public static void stateNotNull(final Object obj, final String message) throws IllegalStateException {
if (obj == null) {
throw new IllegalStateException(message);
}
}
/**
* Checks that string is not null and not empty and it represents a path to a valid directory
*
* @param string
* The path to check
* @param message
* The exception message
*
* @throws ConfigurationException
* Thrown if string is empty, null or it does not represent a path the a valid directory
*/
public static void configurationDirectoryExists(final String string, final String message)
throws ConfigurationException {
if (string == null || string.length() == 0 || new File(string).isDirectory() == false) {
throw new ConfigurationException(message);
}
}
}
| 34.388889 | 114 | 0.659128 |
2943d9cea0ec32233b362de67d408e09c1c8c766 | 2,327 | package no.nordicsemi.android.mesh.utils;
import android.os.Parcel;
import android.os.Parcelable;
import no.nordicsemi.android.mesh.transport.ProvisionedMeshNode;
/**
* Class containing Network Transmit values in a {@link ProvisionedMeshNode}
*/
@SuppressWarnings("WeakerAccess")
public class NetworkTransmitSettings implements Parcelable {
private final int networkTransmitCount;
private final int networkIntervalSteps;
/**
* Constructs {@link NetworkTransmitSettings}
* @param networkTransmitCount Number of transmissions for each Network PDU originating from the node
* @param networkIntervalSteps Number of 10-millisecond steps between transmissions
*/
public NetworkTransmitSettings(final int networkTransmitCount, final int networkIntervalSteps){
this.networkTransmitCount = networkTransmitCount;
this.networkIntervalSteps = networkIntervalSteps;
}
protected NetworkTransmitSettings(Parcel in) {
networkTransmitCount = in.readInt();
networkIntervalSteps = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(networkTransmitCount);
dest.writeInt(networkIntervalSteps);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<NetworkTransmitSettings> CREATOR = new Creator<NetworkTransmitSettings>() {
@Override
public NetworkTransmitSettings createFromParcel(Parcel in) {
return new NetworkTransmitSettings(in);
}
@Override
public NetworkTransmitSettings[] newArray(int size) {
return new NetworkTransmitSettings[size];
}
};
/**
* Returns the network transmit count
*/
public int getNetworkTransmitCount() {
return networkTransmitCount;
}
/**
* Returns the number of transmissions.
*/
public int getTransmissionCount(){
return networkTransmitCount + 1;
}
/**
* Returns the network interval steps
*/
public int getNetworkIntervalSteps() {
return networkIntervalSteps;
}
/**
* Returns the Network transmission interval.
*/
public int getNetworkTransmissionInterval(){
return (networkIntervalSteps + 1) * 10;
}
}
| 28.036145 | 107 | 0.690589 |
928415fea15ec9d8515b343800baa41a0ba45596 | 13,452 | /*
// Licensed to DynamoBI Corporation (DynamoBI) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. DynamoBI 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 net.sf.farrago.test;
import java.util.*;
import net.sf.farrago.catalog.*;
import net.sf.farrago.cwm.relational.*;
import net.sf.farrago.fem.med.*;
import net.sf.farrago.fem.sql2003.*;
import net.sf.farrago.resource.*;
import net.sf.farrago.session.*;
import org.eigenbase.sql.validate.*;
/**
* Utility class for manipulating statistics stored in the catalog
*
* @author John Pham
* @version $Id$
*/
public class FarragoStatsUtil
{
//~ Static fields/initializers ---------------------------------------------
public static final int DEFAULT_HISTOGRAM_BAR_COUNT = 100;
//~ Methods ----------------------------------------------------------------
public static void setTableRowCount(
FarragoSession session,
String catalogName,
String schemaName,
String tableName,
long rowCount)
throws SqlValidatorException
{
FarragoRepos repos = session.getRepos();
FarragoReposTxnContext txn = repos.newTxnContext();
try {
txn.beginWriteTxn();
FemAbstractColumnSet columnSet =
lookupColumnSet(
session,
repos,
catalogName,
schemaName,
tableName);
FarragoCatalogUtil.updateRowCount(
columnSet,
rowCount,
true,
true,
repos);
txn.commit();
} finally {
txn.rollback();
}
}
public static CwmCatalog lookupCatalog(
FarragoSession session,
FarragoRepos repos,
String catalogName)
throws SqlValidatorException
{
if ((catalogName == null) || (catalogName.length() == 0)) {
catalogName = session.getSessionVariables().catalogName;
}
CwmCatalog catalog = repos.getCatalog(catalogName);
if (catalog == null) {
throw FarragoResource.instance().ValidatorUnknownObject.ex(
catalogName);
}
return catalog;
}
public static FemLocalSchema lookupSchema(
FarragoSession session,
CwmCatalog catalog,
String schemaName)
throws SqlValidatorException
{
if ((schemaName == null) || (schemaName.length() == 0)) {
schemaName = session.getSessionVariables().schemaName;
}
FemLocalSchema schema =
FarragoCatalogUtil.getSchemaByName(catalog, schemaName);
if (schema == null) {
throw FarragoResource.instance().ValidatorUnknownObject.ex(
schemaName);
}
return schema;
}
public static FemAbstractColumnSet lookupColumnSet(
FemLocalSchema schema,
String tableName)
throws SqlValidatorException
{
FemAbstractColumnSet columnSet = null;
if (tableName != null) {
columnSet =
FarragoCatalogUtil.getModelElementByNameAndType(
schema.getOwnedElement(),
tableName,
FemAbstractColumnSet.class);
}
if (columnSet == null) {
throw FarragoResource.instance().ValidatorUnknownObject.ex(
tableName);
}
return columnSet;
}
/**
* Maps a table, given its name components, to its corresponding
* FemAbstractColumnSet
*
* @param session currrent session
* @param repos repository associated with the session
* @param catalogName catalog name for the table
* @param schemaName schema name for the table
* @param tableName table name
*
* @return FemAbstractColumnSet corresponding to the desired table
*
* @throws SqlValidatorException
*/
public static FemAbstractColumnSet lookupColumnSet(
FarragoSession session,
FarragoRepos repos,
String catalogName,
String schemaName,
String tableName)
throws SqlValidatorException
{
CwmCatalog catalog = lookupCatalog(session, repos, catalogName);
FemLocalSchema schema = lookupSchema(session, catalog, schemaName);
return lookupColumnSet(schema, tableName);
}
public static void setIndexPageCount(
FarragoSession session,
String catalogName,
String schemaName,
String indexName,
long pageCount)
throws SqlValidatorException
{
FarragoRepos repos = session.getRepos();
FarragoReposTxnContext txn = repos.newTxnContext();
try {
txn.beginWriteTxn();
CwmCatalog catalog = lookupCatalog(session, repos, catalogName);
FemLocalSchema schema = lookupSchema(session, catalog, schemaName);
FemLocalIndex index = lookupIndex(schema, indexName);
FarragoCatalogUtil.updatePageCount(index, pageCount, repos);
txn.commit();
} finally {
txn.rollback();
}
}
/**
* Creates a column histogram
*/
public static void createColumnHistogram(
FarragoSession session,
String catalogName,
String schemaName,
String tableName,
String columnName,
long distinctValues,
int samplePercent,
long sampleDistinctValues,
int distributionType,
String valueDigits)
throws SqlValidatorException
{
FarragoRepos repos = session.getRepos();
FarragoReposTxnContext txn = repos.newTxnContext();
try {
txn.beginWriteTxn();
FemAbstractColumnSet columnSet =
lookupColumnSet(
session,
repos,
catalogName,
schemaName,
tableName);
FemAbstractColumn column = lookupColumn(columnSet, columnName);
Long [] rowCountStats = new Long[2];
FarragoCatalogUtil.getRowCounts(
columnSet,
null,
rowCountStats);
long rowCount = rowCountStats[0];
long sampleRows = (rowCount * samplePercent) / 100;
assert (distinctValues <= rowCount);
assert (sampleDistinctValues <= distinctValues);
assert (sampleDistinctValues <= sampleRows);
int barCount = 0;
long rowsPerBar = 0;
long rowsLastBar = 0;
if (sampleRows <= DEFAULT_HISTOGRAM_BAR_COUNT) {
barCount = (int) sampleRows;
rowsPerBar = rowsLastBar = 1;
} else {
barCount = DEFAULT_HISTOGRAM_BAR_COUNT;
rowsPerBar = sampleRows / barCount;
if ((sampleRows % barCount) != 0) {
rowsPerBar++;
}
rowsLastBar = sampleRows - ((barCount - 1) * rowsPerBar);
if (rowsLastBar < 0) {
rowsLastBar = 0;
}
}
List<FemColumnHistogramBar> bars =
createColumnHistogramBars(
repos,
column,
sampleDistinctValues,
barCount,
rowsPerBar,
rowsLastBar,
distributionType,
valueDigits);
FarragoCatalogUtil.updateHistogram(
repos,
column,
distinctValues,
false,
(float) samplePercent,
sampleRows,
barCount,
rowsPerBar,
rowsLastBar,
bars);
txn.commit();
} finally {
txn.rollback();
}
}
private static List<FemColumnHistogramBar> createColumnHistogramBars(
FarragoRepos repos,
FemAbstractColumn column,
long distinctValues,
int barCount,
long rowsPerBar,
long rowsLastBar,
int distributionType,
String valueDigits)
{
FemColumnHistogram origHistogram =
FarragoCatalogUtil.getHistogram(column, null);
int origBarCount = 0;
List<FemColumnHistogramBar> origBars = null;
if (origHistogram != null) {
origBarCount = origHistogram.getBarCount();
origBars = origHistogram.getBar();
}
List<FemColumnHistogramBar> bars =
new LinkedList<FemColumnHistogramBar>();
List<Long> valueCounts =
createValueCounts(barCount, distinctValues, distributionType);
List<String> values =
createValues(barCount, valueDigits, distributionType, valueCounts);
for (int i = 0; i < barCount; i++) {
FemColumnHistogramBar bar;
if (i < origBarCount) {
bar = origBars.get(i);
assert (bar.getOrdinal() == i);
} else {
bar = repos.newFemColumnHistogramBar();
bar.setOrdinal(i);
}
bar.setStartingValue(values.get(i));
bar.setValueCount(valueCounts.get(i));
bars.add(bar);
}
return bars;
}
private static List<String> createValues(
int barCount,
String valueDigits,
int distributionType,
List<Long> valueCounts)
{
int digitCount = valueDigits.length();
assert (barCount <= (digitCount * digitCount));
List<String> values = new ArrayList<String>(barCount);
int iterations = barCount / digitCount;
int residual = barCount % digitCount;
for (int i = 0; i < digitCount; i++) {
int currentIterations = iterations;
if (i < residual) {
currentIterations++;
}
for (int j = 0; j < currentIterations; j++) {
char [] chars =
{ valueDigits.charAt(i), valueDigits.charAt(j) };
String next = new String(chars);
if (distributionType > 0) {
next += valueDigits.charAt(0);
}
values.add(next);
}
}
return values;
}
private static List<Long> createValueCounts(
int barCount,
long distinctValueCount,
int distributionType)
{
List<Long> valueCounts = new ArrayList<Long>(barCount);
Double estValuesPerBar =
(double) distinctValueCount / (double) barCount;
long remaining = distinctValueCount;
for (int i = 0; i < barCount; i++) {
long barStart = (long) Math.ceil(estValuesPerBar * i);
long barEnd = (long) Math.ceil(estValuesPerBar * (i + 1));
long current;
if (i == (barCount - 1)) {
current = remaining;
} else {
current = barEnd - barStart;
}
valueCounts.add(current);
remaining -= current;
}
// note: the first bar should be at least 1
if (barCount > 0) {
assert valueCounts.get(0) >= 1
: "first histogram bar must be at least 1";
assert remaining == 0
: "generated histogram bars had remaining distinct values";
}
return valueCounts;
}
private static FemLocalIndex lookupIndex(
FemLocalSchema schema,
String indexName)
throws SqlValidatorException
{
FemLocalIndex index = null;
if (indexName != null) {
index =
FarragoCatalogUtil.getModelElementByNameAndType(
schema.getOwnedElement(),
indexName,
FemLocalIndex.class);
}
if (index == null) {
throw FarragoResource.instance().ValidatorUnknownObject.ex(
indexName);
}
return index;
}
public static FemAbstractColumn lookupColumn(
FemAbstractColumnSet columnSet,
String columnName)
throws SqlValidatorException
{
FemAbstractColumn column = null;
if (columnName != null) {
column =
FarragoCatalogUtil.getModelElementByNameAndType(
columnSet.getFeature(),
columnName,
FemAbstractColumn.class);
}
if (column == null) {
throw FarragoResource.instance().ValidatorUnknownObject.ex(
columnName);
}
return column;
}
}
// End FarragoStatsUtil.java
| 31.726415 | 80 | 0.559025 |
d0c87e06e0ca71be80242779981cc43ca017a8ba | 3,724 | package evilcraft.commands;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.StatCollector;
import evilcraft.api.Helpers;
/**
* The EvilCraft command.
* @author rubensworks
*
*/
public class CommandEvilCraft implements ICommand {
private static final String NAME = "evilcraft";
protected List<String> getAliases() {
List<String> list = new LinkedList<String>();
list.add(NAME);
list.add("evilCraft");
list.add("EvilCraft");
return list;
}
protected Map<String, ICommand> getSubcommands() {
Map<String, ICommand> map = new HashMap<String, ICommand>();
map.put("config", new CommandConfig());
map.put("version", new CommandVersion());
map.put("recursion", new CommandRecursion());
return map;
}
private List<String> getSubCommands(String cmd) {
List<String> completions = new LinkedList<String>();
for(String full : getSubcommands().keySet()) {
if(full.startsWith(cmd)) {
completions.add(full);
}
}
return completions;
}
@Override
public int compareTo(Object o) {
return 0;
}
@Override
public String getCommandName() {
return NAME;
}
@Override
public String getCommandUsage(ICommandSender icommandsender) {
String possibilities = "";
for(String full : getSubcommands().keySet()) {
possibilities += full + " ";
}
return NAME + " " + possibilities;
}
@SuppressWarnings("rawtypes")
@Override
public List getCommandAliases() {
return this.getAliases();
}
protected String[] shortenArgumentList(String[] astring) {
String[] asubstring = new String[astring.length - 1];
for(int i = 1; i < astring.length; i++) {
asubstring[i - 1] = astring[i];
}
return asubstring;
}
@Override
public void processCommand(ICommandSender icommandsender, String[] astring) {
if(astring.length == 0) {
icommandsender.addChatMessage(new ChatComponentText(StatCollector.translateToLocal("chat.command.invalidArguments")));
} else {
ICommand subcommand = getSubcommands().get(astring[0]);
if(subcommand != null) {
String[] asubstring = shortenArgumentList(astring);
subcommand.processCommand(icommandsender, asubstring);
} else {
icommandsender.addChatMessage(new ChatComponentText(StatCollector.translateToLocal("chat.command.invalidSubcommand")));
}
}
}
@Override
public boolean canCommandSenderUseCommand(ICommandSender icommandsender) {
return Helpers.isOp(icommandsender);
}
@SuppressWarnings("rawtypes")
@Override
public List addTabCompletionOptions(ICommandSender icommandsender,
String[] astring) {
if(astring.length != 0) {
ICommand subcommand = getSubcommands().get(astring[0]);
if(subcommand != null) {
String[] asubstring = shortenArgumentList(astring);
return subcommand.addTabCompletionOptions(icommandsender, asubstring);
} else {
return getSubCommands(astring[0]);
}
} else {
return getSubCommands("");
}
}
@Override
public boolean isUsernameIndex(String[] astring, int i) {
return false;
}
}
| 29.792 | 135 | 0.61493 |
219f09fe407bdfc009e6c2b2a3628726389f62ac | 3,761 | package climber_example.level_creator;
import Kartoha_Engine2D.geometry.Point2;
import Kartoha_Engine2D.physics.Block;
import Kartoha_Engine2D.physics.Material;
import Kartoha_Engine2D.physics.Space;
import Kartoha_Engine2D.physics.Wall;
import climber_example.Level;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
public class Container {
private final Space space;
private boolean addingMode;
@Getter @Setter
private float g;
@Getter
private ArrayList<Wall> walls;
@Getter
private ArrayList<Block> blocks;
private final ArrayList<ReferencePoint> points;
@Getter
private Material currentMaterial;
private Point2 point1, point2;
{
points = new ArrayList<>();
addingMode = false;
point1 = null;
point2 = null;
walls = new ArrayList<>();
blocks = new ArrayList<>();
currentMaterial = Material.CONSTANTIN;
}
public Container(Space space){
this.space = space;
}
private void addWall(){
space.addWall(point1.x, point1.y, point2.x, point2.y, currentMaterial);
walls.add(new Wall(point1.x, point1.y, point2.x, point2.y, currentMaterial, space));
point1 = null;
point2 = null;
}
private void addBlock(){
space.addBlock(Math.min(point1.x, point2.x), Math.min(point1.y, point2.y), Math.abs(point2.x - point1.x), Math.abs(point2.y - point1.y), currentMaterial);
blocks.add(new Block(Math.min(point1.x, point2.x), Math.min(point1.y, point2.y), Math.abs(point2.x - point1.x), Math.abs(point2.y - point1.y), currentMaterial, space));
point1 = null;
point2 = null;
}
public void addPoint(Point2 point){
if (point1 != null && point2 == null){
point2 = point;
if (addingMode)
addWall();
else
addBlock();
}
else point1 = point;
}
public void setCurrentMaterial(Material currentMaterial) {
this.currentMaterial = currentMaterial;
}
public Level getLevel(){
Level level = new Level();
for (Wall wall : walls)
level.getWalls().add(wall);
for (Block block : blocks)
level.getBlocks().add(block);
level.setG(g);
return level;
}
public void setLevel(Level level){
this.walls = level.getWalls();
this.blocks = level.getBlocks();
points.clear();
space.getWalls().clear();
space.getBlocks().clear();
space.getDrawables().clear();
space.setG(level.getG());
walls.forEach(wall -> wall.setSpace(space));
blocks.forEach(block -> block.setSpace(space));
for (Wall wall : walls){
space.getDrawables().add(wall);
space.getWalls().add(wall);
}
for (Block block : blocks){
space.addBlock(block.getX(), block.getY(), block.getW(), block.getH(), block.getMaterial());
}
point1 = null;
point2 = null;
}
public void deleteAllObjects(){
walls.clear();
blocks.clear();
space.getWalls().clear();
space.getBlocks().clear();
space.getDrawables().clear();
for (ReferencePoint point : points){
space.getDrawables().remove(point);
}
points.clear();
}
public void changeAddingMode(){
addingMode = !addingMode;
}
public ArrayList<ReferencePoint> getPoints() {
return points;
}
public void addReferencePoint(Point2 point){
ReferencePoint referencePoint = new ReferencePoint(point, this);
points.add(referencePoint);
space.getDrawables().add(referencePoint);
}
}
| 28.930769 | 176 | 0.606222 |
fcd8dde3994154fbfa80bfe3f110dfc8f4ca877c | 256 | package com.techreturners.cats;
public interface CatBehaviour {
public boolean isAsleep();
public String getSetting();
public int getAverageHeight();
public String eat();
public String goToSleep();
public String wakeUp();
}
| 14.222222 | 34 | 0.6875 |
6aa6bc9edd126388f9ceca9391f6f30df5b53f71 | 6,824 | package info.manuelmayer.licensed.service;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.time.Clock;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import info.manuelmayer.licensed.model.License;
import info.manuelmayer.licensed.model.License.LicenseRestrictions;
import info.manuelmayer.licensed.model.Licensing;
@RunWith(MockitoJUnitRunner.class)
public class LicensingServiceImplTest {
private static final Long ID = 1L;
private static final String LICENSE_KEY = "license";
private static final String LOGIN = "login";
@Mock
private License license;
@Mock
private LicensingCache licensingCache;
@Mock
private LicenseRestrictions restrictions;
@Mock
private LicenseManager licenseManager;
@Spy
private Licensing activeLicensing = new Licensing(),
inactiveLicensing = new Licensing(),
savedLicensing = new Licensing();
@Mock
private LicensingRepository licensingRepo;
@Mock
private SecurityContext securityContext;
@InjectMocks
private final LicensingServiceImpl licensingService = new LicensingServiceImpl(Clock.systemDefaultZone());
@Before
public void init() {
Set<Licensing> licensing = new HashSet<>();
licensing.add(savedLicensing);
activeLicensing.setActive(Boolean.TRUE);
activeLicensing.setLicenseKey(LICENSE_KEY);
inactiveLicensing.setActive(Boolean.FALSE);
inactiveLicensing.setLicenseKey(LICENSE_KEY);
savedLicensing.setLicenseKey(LICENSE_KEY);
savedLicensing.setUserLogin(LOGIN);
when(licenseManager.getLicense(LICENSE_KEY)).thenReturn(Optional.of(license));
when(license.getRestrictions()).thenReturn(restrictions);
when(licensingRepo.countByLicenseKeyAndActiveTrueAndUserLoginNotNull(LICENSE_KEY)).thenReturn(0L);
when(licensingRepo.saveAndFlush(any(Licensing.class))).thenReturn(savedLicensing);
when(restrictions.getNumberOfUsers()).thenReturn(1);
}
@Test
public void test_activate_unknown_id() {
when(licensingRepo.findById(ID)).thenReturn(Optional.empty());
Licensing activated = licensingService.activate(ID);
assertThat(activated, nullValue());
verify(licensingRepo, never()).saveAndFlush(any(Licensing.class));
verify(licensingCache, never()).invalidate(any(String.class));
}
@Test
public void test_activate_max_users_reached() {
when(licensingRepo.findById(ID)).thenReturn(Optional.of(inactiveLicensing));
when(licensingRepo.countByLicenseKeyAndActiveTrueAndUserLoginNotNull(LICENSE_KEY)).thenReturn(1L);
when(restrictions.getNumberOfUsers()).thenReturn(1);
Licensing activated = licensingService.activate(ID);
assertThat(activated, sameInstance(inactiveLicensing));
verify(activated, never()).setActive(Boolean.TRUE);
verify(licensingRepo, never()).saveAndFlush(any(Licensing.class));
verify(licensingCache, never()).invalidate(any(String.class));
}
@Test
public void test_activate_successfull() {
when(licensingRepo.findById(ID)).thenReturn(Optional.of(inactiveLicensing));
when(licensingRepo.countByLicenseKeyAndActiveTrueAndUserLoginNotNull(LICENSE_KEY)).thenReturn(0L);
when(restrictions.getNumberOfUsers()).thenReturn(1);
Licensing activated = licensingService.activate(ID);
assertThat(activated, sameInstance(savedLicensing));
verify(inactiveLicensing).setActive(Boolean.TRUE);
verify(licensingRepo).saveAndFlush(inactiveLicensing);
verify(licensingCache).invalidate(LOGIN);
}
@Test
public void test_deactivate_unknown_id() {
when(licensingRepo.findById(ID)).thenReturn(Optional.empty());
Licensing deactivated = licensingService.deactivate(ID);
assertThat(deactivated, nullValue());
verify(licensingRepo, never()).saveAndFlush(any(Licensing.class));
verify(licensingCache, never()).invalidate(any(String.class));
}
@Test
public void test_deactivate_successfull() {
when(licensingRepo.findById(ID)).thenReturn(Optional.of(activeLicensing));
Licensing deactivated = licensingService.deactivate(ID);
assertThat(deactivated, sameInstance(savedLicensing));
verify(activeLicensing).setActive(Boolean.FALSE);
verify(licensingRepo).saveAndFlush(activeLicensing);
verify(licensingCache).invalidate(LOGIN);
}
@Test
public void test_assignUserLicense_already_licensed() {
when(licensingRepo.findByUserLogin(LOGIN)).thenReturn(Arrays.asList(activeLicensing));
Licensing assigned = licensingService.assignUserLicense(LICENSE_KEY, LOGIN);
assertThat(assigned, sameInstance(activeLicensing));
verify(licensingRepo, never()).saveAndFlush(any(Licensing.class));
verify(licensingCache, never()).invalidate(any(String.class));
}
@Test
public void test_assignUserLicense_max_users() {
when(licensingRepo.findByUserLogin(LOGIN)).thenReturn(Arrays.asList(inactiveLicensing));
Licensing assigned = licensingService.assignUserLicense(LICENSE_KEY, LOGIN);
assertThat(assigned, sameInstance(inactiveLicensing));
verify(licensingRepo, never()).saveAndFlush(any(Licensing.class));
verify(licensingCache, never()).invalidate(any(String.class));
}
@Test
public void test_assignUserLicense_successfull() {
when(licensingRepo.findByUserLogin(LOGIN)).thenReturn(Collections.emptyList());
Licensing assigned = licensingService.assignUserLicense(LICENSE_KEY, LOGIN);
assertThat(assigned, sameInstance(savedLicensing));
verify(licensingRepo).saveAndFlush(any(Licensing.class));
verify(licensingCache).invalidate(LOGIN);
}
@Test(expected=UnsupportedOperationException.class)
public void test_assignLicenseToCurrentDevice() {
licensingService.assignLicenseToCurrentDevice(LICENSE_KEY);
}
@Test
public void test_assignLicenseToCurrentUser() {
when(securityContext.getUsername()).thenReturn(LOGIN);
when(licensingRepo.findByUserLogin(LOGIN)).thenReturn(Collections.emptyList());
Licensing assigned = licensingService.assignLicenseToCurrentUser(LICENSE_KEY);
assertThat(assigned, sameInstance(savedLicensing));
verify(licensingRepo).findByUserLogin(LOGIN);
verify(licensingRepo).saveAndFlush(any(Licensing.class));
verify(licensingCache).invalidate(LOGIN);
}
}
| 34.816327 | 109 | 0.771249 |
6dc5065da56527b8f45da37b470f76a72b0c3d94 | 4,506 | /*
* Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.epam.pipeline.autotests.ao;
public enum Primitive {
OK,
CANCEL,
COMMIT,
PAUSE,
RESUME,
ENDPOINT,
DELETE,
REFRESH,
RELOAD,
EDIT_STORAGE,
EDIT_FOLDER,
UPLOAD,
SELECT_ALL,
CREATE_FOLDER,
CREATE_PIPELINE,
ADDRESS_BAR,
CLEAR_SELECTION,
REMOVE_ALL,
EDIT,
REGISTRY,
DELETE_RUNTIME_FILES,
STOP_PIPELINE,
IMAGE_NAME,
NAME,
ALIAS,
TYPE,
VALUE,
DELETE_ICON,
ADD,
ANOTHER_DOCKER_IMAGE,
ANOTHER_COMPUTE_NODE,
DOCKER_IMAGE_COMBOBOX,
COMMAND,
OUTPUT_ADD,
INPUT_ADD,
INPUT_PANEL,
OUTPUT_PANEL,
ADD_TASK,
SAVE,
REVERT,
LAYOUT,
FIT,
SHOW_LINKS,
ADD_SCATTER,
PROPERTIES,
ZOOM_IN,
ZOOM_OUT,
FULLSCREEN,
STATUS,
SSH_LINK,
CREATE,
CREATE_STORAGE,
CREATE_NFS_MOUNT,
CREATE_FILE,
ADD_EXISTING_STORAGE,
PATH,
DESCRIPTION,
REPOSITORY,
TOKEN,
EDIT_REPOSITORY_SETTINGS,
EDIT_TASK,
EDIT_WORKFLOW,
MESSAGE,
CLOSE,
RENAME,
NEW_FILE,
RUN,
ADD_NEW_RULE,
TITLE,
LABELS,
PORT,
LABEL_INPUT_FIELD,
DEFAULT_COMMAND,
CODE_TAB,
CONFIGURATION_TAB,
GRAPH_TAB,
DOCUMENTS_TAB,
HISTORY_TAB,
CANVAS,
DOWNLOAD,
STORAGE_RULES_TAB,
PIPELINE,
VERSION,
STARTED_TIME,
COMPLETED_TIME,
OWNER,
STOP,
LOG,
RERUN,
FILE_MASK,
MOVE_TO_STS,
RUN_NAME,
PERMISSIONS,
INFO,
USER_NAME,
PASSWORD,
CERTIFICATE,
EDIT_CREDENTIALS,
STORAGEPATH,
HEADER,
NAVIGATION,
STS_DURATION,
LTS_DURATION,
ENABLE_VERSIONING,
BACKUP_DURATION,
MOUNT_POINT,
MOUNT_OPTIONS,
UNREGISTER,
SHOW_METADATA,
HIDE_METADATA,
UPLOAD_METADATA,
ADD_KEY,
REMOVE_ALL_KEYS,
KEY_FIELD,
KEY_FIELD_INPUT,
VALUE_FIELD,
VALUE_FIELD_INPUT,
INFO_TAB,
PARAMETER_NAME,
PARAMETER_PATH,
PARAMETER_VALUE,
REMOVE_PARAMETER,
BUCKET_PANEL,
FILES_PANEL,
CROSS,
CONFIGURATION,
ESTIMATE_PRICE,
INSTANCE,
EXEC_ENVIRONMENT,
PARAMETERS,
ADD_PARAMETER,
ADD_CONFIGURATION,
DISK,
TIMEOUT,
TEMPLATE,
SET_AS_DEFAULT,
RELEASE,
CONFIRM_RELEASE,
LAUNCH_CLUSTER,
CLUSTER_DIALOG,
WORKING_NODES,
NEXT_PAGE,
PREV_PAGE,
UPDATE_CONFIGURATION,
FIRST_VERSION,
ADVANCED_PANEL,
PARAMETERS_PANEL,
BODY,
GROUP,
REGISTRIES_LIST,
GROUPS_LIST,
SETTINGS,
REGISTRY_SETTINGS,
GROUP_SETTINGS,
CREATE_REGISTRY,
EDIT_REGISTRY,
BACK_TO_GROUP,
RUN_DROPDOWN,
DEFAULT_SETTINGS,
CUSTOM_SETTINGS,
TOOL_MENU,
ENABLE_TOOL,
IMAGE,
ENABLE,
SEARCH,
SEARCH_INPUT,
CREATE_PERSONAL_GROUP,
GROUPS_SEARCH,
CLI_TAB,
SYSTEM_EVENTS_TAB,
USER_MANAGEMENT_TAB,
PREFERENCES_TAB,
USERS_TAB,
ROLE_TAB,
GROUPS_TAB,
CLUSTER_TAB,
SYSTEM_TAB,
DOCKER_SECURITY_TAB,
AUTOSCALING_TAB,
TABLE,
EDIT_GROUP,
DELETE_GROUP,
SHORT_DESCRIPTION,
FULL_DESCRIPTION,
CREATE_GROUP,
CREATE_PERSONAL_GROUP_FROM_SETTINGS,
VERSIONS,
PRICE_TYPE,
IP,
TOOL_SETTINGS,
INSTANCE_TYPE,
NEW_ENDPOINT,
DOCKER_IMAGE,
SEVERITY,
STATE,
STATE_CHECKBOX,
TITLE_FIELD,
BODY_FIELD,
SEVERITY_COMBOBOX,
ACTIVE_LABEL,
WARNING,
CRITICAL,
EXPAND,
NARROW,
DATE,
SEVERITY_ICON,
ENLARGE,
FILE_PREVIEW,
VIEW_AS_TEXT,
CREATE_CONFIGURATION,
TREE,
FOLDERS,
START_IDLE,
AUTO_PAUSE,
LAUNCH,
ESTIMATED_PRICE,
INFORMATION_ICON,
PRICE_TABLE,
ARROW,
PIPELINES,
RUNS,
TOOLS,
DATA,
ISSUES,
QUESTION_MARK,
SEARCH_RESULT,
NEW_ISSUE,
WRITE_TAB,
PREVIEW_TAB,
PREVIEW,
HIGHLIGHTS
}
| 17.952191 | 75 | 0.651798 |
04e631558932146811a438b4696b76a3e7b8a267 | 5,105 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.core.fs;
import org.apache.flink.annotation.Internal;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.WrappingProxy;
import java.io.IOException;
import java.net.URI;
/**
* This is a {@link WrappingProxy} around {@link FileSystem} which (i) wraps all opened streams as
* {@link ClosingFSDataInputStream} or {@link ClosingFSDataOutputStream} and (ii) registers them to
* a {@link SafetyNetCloseableRegistry}.
*
* <p>Streams obtained by this are therefore managed by the {@link SafetyNetCloseableRegistry} to
* prevent resource leaks from unclosed streams.
*/
@Internal
public class SafetyNetWrapperFileSystem extends FileSystem implements WrappingProxy<FileSystem> {
private final SafetyNetCloseableRegistry registry;
private final FileSystem unsafeFileSystem;
public SafetyNetWrapperFileSystem(FileSystem unsafeFileSystem, SafetyNetCloseableRegistry registry) {
this.registry = Preconditions.checkNotNull(registry);
this.unsafeFileSystem = Preconditions.checkNotNull(unsafeFileSystem);
}
@Override
public Path getWorkingDirectory() {
return unsafeFileSystem.getWorkingDirectory();
}
@Override
public Path getHomeDirectory() {
return unsafeFileSystem.getHomeDirectory();
}
@Override
public URI getUri() {
return unsafeFileSystem.getUri();
}
@Override
public FileStatus getFileStatus(Path f) throws IOException {
return unsafeFileSystem.getFileStatus(f);
}
@Override
public RecoverableWriter createRecoverableWriter() throws IOException {
return unsafeFileSystem.createRecoverableWriter();
}
@Override
public BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len) throws IOException {
return unsafeFileSystem.getFileBlockLocations(file, start, len);
}
@Override
public FSDataInputStream open(Path f, int bufferSize) throws IOException {
FSDataInputStream innerStream = unsafeFileSystem.open(f, bufferSize);
return ClosingFSDataInputStream.wrapSafe(innerStream, registry, String.valueOf(f));
}
@Override
public FSDataInputStream open(Path f) throws IOException {
FSDataInputStream innerStream = unsafeFileSystem.open(f);
return ClosingFSDataInputStream.wrapSafe(innerStream, registry, String.valueOf(f));
}
@Override
@SuppressWarnings("deprecation")
public long getDefaultBlockSize() {
return unsafeFileSystem.getDefaultBlockSize();
}
@Override
public FileStatus[] listStatus(Path f) throws IOException {
return unsafeFileSystem.listStatus(f);
}
@Override
public boolean exists(Path f) throws IOException {
return unsafeFileSystem.exists(f);
}
@Override
public boolean delete(Path f, boolean recursive) throws IOException {
return unsafeFileSystem.delete(f, recursive);
}
@Override
public boolean mkdirs(Path f) throws IOException {
return unsafeFileSystem.mkdirs(f);
}
@Override
@SuppressWarnings("deprecation")
public FSDataOutputStream create(Path f, boolean overwrite, int bufferSize, short replication, long blockSize)
throws IOException {
FSDataOutputStream innerStream = unsafeFileSystem.create(f, overwrite, bufferSize, replication, blockSize);
return ClosingFSDataOutputStream.wrapSafe(innerStream, registry, String.valueOf(f));
}
@Override
public FSDataOutputStream create(Path f, WriteMode overwrite) throws IOException {
FSDataOutputStream innerStream = unsafeFileSystem.create(f, overwrite);
return ClosingFSDataOutputStream.wrapSafe(innerStream, registry, String.valueOf(f));
}
@Override
public boolean rename(Path src, Path dst) throws IOException {
return unsafeFileSystem.rename(src, dst);
}
@Override
public boolean initOutPathLocalFS(Path outPath, WriteMode writeMode, boolean createDirectory) throws IOException {
return unsafeFileSystem.initOutPathLocalFS(outPath, writeMode, createDirectory);
}
@Override
public boolean initOutPathDistFS(Path outPath, WriteMode writeMode, boolean createDirectory) throws IOException {
return unsafeFileSystem.initOutPathDistFS(outPath, writeMode, createDirectory);
}
@Override
public boolean isDistributedFS() {
return unsafeFileSystem.isDistributedFS();
}
@Override
public FileSystemKind getKind() {
return unsafeFileSystem.getKind();
}
@Override
public FileSystem getWrappedDelegate() {
return unsafeFileSystem;
}
}
| 31.90625 | 115 | 0.787463 |
e41022d6a7be1d02f9c7b15c17c8ac7a3e77e55c | 687 | package com.yeyouluo;
/**
* @Auther: yeyouluo
* @Date: 2018/7/16
*/
public abstract class Element {
public abstract void accept(Visitor visitor);
}
class ConcreteElementA extends Element{
@Override
public void accept(Visitor visitor) {
visitor.visitConcreteElementA(this);
}
// 其他相关方法
public void operateA(){
System.out.println( this.getClass().getName() + "的其他操作");
}
}
class ConcreteElementB extends Element{
@Override
public void accept(Visitor visitor) {
visitor.visitConcreteElementB(this);
}
// 其他相关方法
public void operateB(){
System.out.println( this.getClass().getName() + "的其他操作");
}
} | 19.628571 | 65 | 0.647744 |
7bb7407c58a78f7e23f8b9b0af5504e9c8c02262 | 1,084 | package com.sgcc.exam.wxImages.bizc;
import java.util.*;
import com.sgcc.uap.rest.support.QueryResultObject;
import com.sgcc.uap.rest.support.RequestCondition;
import com.sgcc.uap.mdd.runtime.base.BizCDefaultImpl;
import com.sgcc.exam.wxImages.po.WxImageConf;
import java.io.Serializable;
public class WxImageConfBizc extends BizCDefaultImpl<WxImageConf, Serializable> implements IWxImageConfBizc {
/**************** 标准方法执行前后事件,默认全部返回true *******************/
@Override
protected void afterDelete(WxImageConf wximageconf) {
// 自定义逻辑
}
@Override
protected void afterAdd(WxImageConf wximageconf) {
// 自定义逻辑
}
@Override
protected boolean beforeDelete(WxImageConf wximageconf) {
// 自定义逻辑
return true;
}
@Override
protected boolean beforeAdd(WxImageConf wximageconf) {
// 自定义逻辑
return true;
}
@Override
protected void afterUpdate(WxImageConf wximageconf ,Serializable pk) {
// 自定义逻辑
}
@Override
protected boolean beforeUpdate(WxImageConf wximageconf, Serializable pk) {
// 自定义逻辑
return true;
}
}
| 22.122449 | 110 | 0.7131 |
d0bffc9d31977e5f9ebe508015e60f688ba2e36e | 6,034 | /*****************************************************************************
* Copyright 2012 bitsofinfo.g [at] gmail [dot] com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*
* Author: bitsofinfo.g [at] gmail [dot] com
* @see bitsofinfo.wordpress.com
*****************************************************************************/
package org.bitsofinfo.util.address.usps.ais.index;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.bitsofinfo.util.address.usps.ais.USPSRecord;
import org.bitsofinfo.util.address.usps.ais.USPSUtils;
public class LuceneIndexService implements USPSIndexService {
@Autowired
private USPSUtils uspsUtils;
// the root dir for all of our indexes
private File indexRootDir = null;
// if we are read only or not
private boolean readOnly = false;
private USPSRecordAnalyzer uspsRecordAnalyzer = new USPSRecordAnalyzer();
private HashMap<Class,LuceneIndex> indexMap = new HashMap<Class,LuceneIndex>();
private int indexCount = 0;
public void setIndexRootDir(String path) {
this.indexRootDir = new File(path);
}
private IndexWriter getIndexWriter(File targetDirPath,boolean optimizeForHeavyWriteOp, boolean create)
throws CorruptIndexException, LockObtainFailedException,IOException {
boolean autoCommit = true;
long ramBufferSize = 64;//mb
boolean compoundFile = true;
int mergeFactor = 20;
if (optimizeForHeavyWriteOp) {
autoCommit = false;
ramBufferSize = 100;//mb
compoundFile = false;
mergeFactor = mergeFactor * 2;
}
IndexWriter indexWriter = new IndexWriter(FSDirectory.open(targetDirPath),uspsRecordAnalyzer,create,MaxFieldLength.UNLIMITED);
indexWriter.setRAMBufferSizeMB(ramBufferSize);
indexWriter.setUseCompoundFile(compoundFile);
indexWriter.setMergeFactor(mergeFactor);
return indexWriter;
}
protected void indexRecords(List<USPSRecord> records) throws Exception {
//IndexWriter idxWriter = new IndexWriter();
}
protected Document uspsRecordToDocument(USPSRecord record) throws Exception {
// create a new document
Document doc = new Document();
// add the identifier field (stored, indexed but not analyzed)
Field idField = new Field("identifier",record.getIdentifier(),Field.Store.YES,Field.Index.NOT_ANALYZED);
// get all field names, and index these values
String[] fields2index = uspsUtils.getKeyFieldNames(record);
for (String fieldName : fields2index) {
Object rawVal = null;
try {
rawVal = PropertyUtils.getProperty(record, fieldName);
} catch(Exception e) {
// HANDLE THIS..(bad prop name etc).
rawVal = null;
}
// index/analyze the field value, do NOT store it
if (rawVal != null) {
Field f = new Field(fieldName,rawVal.toString(),Field.Store.NO,Field.Index.ANALYZED);
doc.add(f);
}
}
return doc;
}
public void initialize() {
try {
// ensure the indexer root dir exists
if (!indexRootDir.exists()) {
indexRootDir.mkdirs();
}
// create the storage structure for all our indexes
Set<Class> clazzes = uspsUtils.getUSPSRecordClasses();
for (Class clazz : clazzes) {
File baseDir = new File(indexRootDir.getAbsolutePath() + "/" + clazz.getSimpleName());
File repopDir = new File(baseDir.getAbsolutePath() + "/repopulate");
File activeDir = new File(baseDir.getAbsolutePath() + "/active");
if (!baseDir.exists()) {
baseDir.mkdirs();
}
if (!repopDir.exists()) {
repopDir.mkdirs();
this.getIndexWriter(repopDir, false, true); // create it
}
if (!activeDir.exists()) {
activeDir.mkdirs();
this.getIndexWriter(activeDir, false, true); // create it
}
indexMap.put(clazz,new LuceneIndex(activeDir,repopDir));
}
} catch(Exception e) {
}
}
@Override
public void index(List<USPSRecord> records) {
// sort em all out
HashMap<Class,List<USPSRecord>> clazzMap = new HashMap<Class,List<USPSRecord>>();
for (USPSRecord record : records) {
Class clazz = record.getClass();
List<USPSRecord> tmp = clazzMap.get(clazz);
if (tmp == null) {
tmp = new ArrayList<USPSRecord>();
clazzMap.put(clazz, tmp);
}
tmp.add(record);
}
for (Class clazz : clazzMap.keySet()) {
List<USPSRecord> items = clazzMap.get(clazz);
LuceneIndex index = indexMap.get(clazz);
IndexWriter writer = null;
try {
writer = this.getIndexWriter(index.activeDir, true, false);
for (USPSRecord r : items) {
Document doc = this.uspsRecordToDocument(r);
Term id = new Term("identifier",r.getIdentifier());
writer.updateDocument(id, doc, this.uspsRecordAnalyzer);
}
if (indexCount == 10) {
writer.optimize();
indexCount=0;
}
} catch(Exception e) {
} finally {
if (writer != null) {
try {writer.close();} catch(Exception ignoreForNow){}
}
}
}
indexCount++;
}
}
| 29.291262 | 128 | 0.688101 |
85a34cc6d3b151785cfa05c2850d02a83e0cc794 | 307 | package com.atguigu.srb.core.service;
import com.atguigu.srb.core.pojo.entity.IntegralGrade;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 积分等级表 服务类
* </p>
*
* @author Helen
* @since 2021-11-25
*/
public interface IntegralGradeService extends IService<IntegralGrade> {
}
| 18.058824 | 71 | 0.736156 |
4d3bfd250ecd756aff35d8deda74b78df90f3a8f | 3,857 | package com.newsblur.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.newsblur.R;
import com.newsblur.databinding.InfrequentCutoffDialogBinding;
public class InfrequentCutoffDialogFragment extends DialogFragment {
private static String CURRENT_CUTOFF = "currentCutoff";
private int currentValue;
private InfrequentCutoffDialogBinding binding;
public static InfrequentCutoffDialogFragment newInstance(int currentValue) {
InfrequentCutoffDialogFragment dialog = new InfrequentCutoffDialogFragment();
Bundle args = new Bundle();
args.putInt(CURRENT_CUTOFF, currentValue);
dialog.setArguments(args);
return dialog;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
currentValue = getArguments().getInt(CURRENT_CUTOFF);
View v = inflater.inflate(R.layout.infrequent_cutoff_dialog, null);
binding = InfrequentCutoffDialogBinding.bind(v);
binding.radio5.setChecked(currentValue == 5);
binding.radio15.setChecked(currentValue == 15);
binding.radio30.setChecked(currentValue == 30);
binding.radio60.setChecked(currentValue == 60);
binding.radio90.setChecked(currentValue == 90);
getDialog().setTitle(R.string.infrequent_choice_title);
getDialog().getWindow().getAttributes().gravity = Gravity.BOTTOM;
return v;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding.radio5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
select5();
}
});
binding.radio15.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
select15();
}
});
binding.radio30.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
select30();
}
});
binding.radio60.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
select60();
}
});
binding.radio90.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
select90();
}
});
}
private void select5() {
if (currentValue != 5) {
((InfrequentCutoffChangedListener) getActivity()).infrequentCutoffChanged(5);
}
dismiss();
}
private void select15() {
if (currentValue != 15) {
((InfrequentCutoffChangedListener) getActivity()).infrequentCutoffChanged(15);
}
dismiss();
}
private void select30() {
if (currentValue != 30) {
((InfrequentCutoffChangedListener) getActivity()).infrequentCutoffChanged(30);
}
dismiss();
}
private void select60() {
if (currentValue != 60) {
((InfrequentCutoffChangedListener) getActivity()).infrequentCutoffChanged(60);
}
dismiss();
}
private void select90() {
if (currentValue != 90) {
((InfrequentCutoffChangedListener) getActivity()).infrequentCutoffChanged(90);
}
dismiss();
}
public interface InfrequentCutoffChangedListener {
void infrequentCutoffChanged(int newValue);
}
}
| 31.104839 | 90 | 0.657247 |
dd117c5b10faff549c1210ba4d53fa677ddfbe74 | 853 | package com.vladkel.eFindMe.xml.parsing.demo.model;
public class Personne {
private int id;
private String nom;
private String prenom;
private String adresse;
public Personne(){
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public void showYourself(){
System.out.println(this.getId());
System.out.println("\t" + this.getNom());
System.out.println("\t" + this.getPrenom());
System.out.println("\t" + this.getAdresse());
}
}
| 14.706897 | 51 | 0.657679 |
305ab62ab6b2d399eb9a8448bb712bc5387db647 | 289 | package com.antonioalejandro.smkt.cookbook.utils;
import java.util.UUID;
/**
*
* UUID generator interface
*/
public interface UUIDGenerator {
/**
* Default generate UUID
*
* @return the string
*/
default String generateUUID() {
return UUID.randomUUID().toString();
}
}
| 14.45 | 49 | 0.685121 |
724a547da9fe9c00cc34f3498cc61c9b3514d202 | 1,152 | package com.tazine.mvc.pojo;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
/**
* @author jiaer.ly
* @date 2018/02/24
*/
public class Player {
private String name;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date;
private Integer num;
// public Player(String name, Date date) {
// this.name = name;
// this.date = date;
// }
//
public Player(String name, Date date, Integer num) {
this.name = name;
this.date = date;
this.num = num;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
@Override
public String toString() {
return "Player{" +
"name='" + name + '\'' +
", date=" + date +
", num=" + num +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
| 18 | 60 | 0.521701 |
70967baa77a88e59b520e0ccae7ba93b32c8fc21 | 5,676 | package com.croconaut.ratemebuddy.activities.notifications;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.text.Html;
import android.util.Log;
import com.croconaut.ratemebuddy.R;
import com.croconaut.ratemebuddy.activities.CommentActivity;
import com.croconaut.ratemebuddy.activities.SettingsActivity;
import com.croconaut.ratemebuddy.data.pojo.VoteUp;
import com.croconaut.ratemebuddy.utils.pojo.profiles.IProfile;
import com.croconaut.ratemebuddy.utils.pojo.profiles.MyProfile;
import java.util.ArrayList;
public class VoteUpNotification extends Notification {
public static final int VOTE_UP_NOTIF_ID = 1;
private static final String TAG = VoteUpNotification.class.getName();
public VoteUpNotification(Context context) {
super(context);
MyProfile myProfile = MyProfile.getInstance(context);
if (notificationDisabled()) return;
// retrieve vote-up profiles with notification displayed
ArrayList<IProfile> voteUpProfiles = new ArrayList<>();
ArrayList<VoteUp> unseenVotes = myProfile.getStatus().getUnseenVotes();
for (VoteUp voteUp : unseenVotes) {
IProfile profile = profileUtils.findProfile(voteUp.getCrocoId(), voteUp.getProfileName());
if (!voteUpProfiles.contains(profile)) {
voteUpProfiles.add(profile);
}
}
IProfile profile = voteUpProfiles.get(0);
if (profile == null) {
Log.e(TAG, "First profile is null!");
return;
}
// get voteUpProfiles size
int voteUpProfilesSize = voteUpProfiles.size();
int unseenVotesSize = unseenVotes.size();
// create a target intent
Intent intent = new Intent(context, CommentActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(CommentActivity.EXTRA_CROCO_ID, myProfile.getProfileId());
// stack builder for intent
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(CommentActivity.class);
stackBuilder.addNextIntent(intent);
// final pending intent
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(VOTE_UP_NOTIF_ID, PendingIntent.FLAG_CANCEL_CURRENT);
// builder fot notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_notif_vote_up).setContentIntent(resultPendingIntent).setAutoCancel(false);
mBuilder.setContentTitle(res.getQuantityString(R.plurals.notif_voteup_title, unseenVotesSize, unseenVotesSize));
mBuilder.setNumber(unseenVotesSize);
// String firstArg = voteUpProfilesSize > 1 ? String.valueOf(voteUpProfilesSize) : profile.getName();
// mBuilder.setContentText(res.getQuantityString(R.plurals.notif_voteup_text, voteUpProfilesSize, firstArg, myProfile.getStatus().getContent()));
if (voteUpProfilesSize == 1) {
mBuilder.setLargeIcon(createBitmapIcon(context, profile));
}
// big text style, so notificaion will expend in bar if it have space
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle(res.getQuantityString(R.plurals.notif_voteup_title, voteUpProfilesSize, voteUpProfilesSize));
// retrieve first profile
IProfile firstProfile = voteUpProfiles.get(FIRST_USER);
if (voteUpProfilesSize <= CRITICAL_COUNT) {
String status = "<b>" + myProfile.getStatus().getContent() + "</b>";
String msg = res.getQuantityString(
R.plurals.mesage_voteup_big_style,
voteUpProfilesSize,
firstProfile.getName(),
voteUpProfilesSize <= 1 ? status : voteUpProfiles.get(SECOND_USER).getName(),
status
);
bigTextStyle.bigText(Html.fromHtml(msg));
mBuilder.setContentText(Html.fromHtml(msg));
} else {
IProfile secondProfile = voteUpProfiles.get(SECOND_USER);
String bigText = res.getQuantityString(
R.plurals.notif_voteup_big_style_text_body,
(voteUpProfilesSize - CRITICAL_COUNT),
firstProfile.getName(),
secondProfile.getName(),
(voteUpProfilesSize - CRITICAL_COUNT)
);
bigTextStyle.bigText(Html.fromHtml(bigText));
mBuilder.setContentText(Html.fromHtml(bigText));
}
mBuilder.setStyle(bigTextStyle);
mBuilder.setAutoCancel(true);
// if vibs are enabled, set vibs
if (prefs.getBoolean(SettingsActivity.VIB_PREF, true)) {
mBuilder.setVibrate(new long[]{0, 500, 200, 500});
}
// if sound is enabled, set sound
if (prefs.getBoolean(SettingsActivity.SOUND_PREF, true)) {
mBuilder.setSound(Uri.parse(prefs.getString(SettingsActivity.SOUND_RING_TONE_PREF, Settings.System.DEFAULT_NOTIFICATION_URI.toString())));
}
// finally, create and display new notification
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(VOTE_UP_NOTIF_ID, mBuilder.build());
}
} | 43.661538 | 187 | 0.692918 |
be222e7cfbc8c8a50a55462b59a89bba6c906364 | 858 | package lm44_xw47.chatRoom.model;
import common.IChatRoom;
import common.IUser;
/**
* Following defines the adapter the lobby model uses to communicate with lobby view.
*
* @author Xiaojun Wu
* @author Lu Ma
*/
public interface ILobbyModel2ViewAdapter {
/**
* Add a user to the lobby view.
*
* @param user The user being added to the lobby view.
*/
public void addUser(IUser user);
/**
* Add a team to the lobby view.
*
* @param team The team being added to the lobby view.
*/
public void addTeam(IChatRoom team);
/**
* Null implementation of this interface.
*/
public static final ILobbyModel2ViewAdapter NULL_OBJECT = new ILobbyModel2ViewAdapter() {
/**
* No-op.
*/
@Override
public void addUser(IUser user) {
}
/**
* No-op.
*/
@Override
public void addTeam(IChatRoom team) {
}
};
}
| 18.255319 | 90 | 0.66317 |
cf9b45748533d2d08a917de5b25b1f455ba0e830 | 730 | package com.zed.dingtalk.service.contact.department;
import com.zed.dingtalk.common.BaseResponse;
import lombok.Data;
import lombok.ToString;
import java.util.List;
import java.util.Map;
/**
* @Author liwenguang
* @Date 2018/11/27 12:32 AM
* @Description 获取所有部门列表
*/
@ToString(callSuper = true)
public class DeptAllResponse extends BaseResponse<DeptAllResponse.SucDetail> {
@Data
public class SucDetail {
/**
* key 为 depId, value 为该 deptId 的详情
*/
Map<String, DeptDetail> deptDetailMap;
@Data
public class DeptDetail {
private String deptName;
private String parentDeptId;
private List<String> childrenDeptId;
}
}
} | 22.121212 | 78 | 0.657534 |
f25f5bd84596389bed8412c55734af779902c64c | 4,777 | /**
* Copyright (C) 2011 Inqwell Ltd
*
* You may distribute under the terms of the Artistic License, as specified in
* the README file.
*/
package com.inqwellx;
import com.inqwell.any.AbstractComposite;
import com.inqwell.any.AbstractValue;
import com.inqwell.any.Any;
import com.inqwell.any.Call;
import com.inqwell.any.LocateNode;
import com.inqwell.any.Map;
/**
* This class is an example configurator for systems requiring host database
* credentials and integration plugins. It is also the default when no
* override is provided with the <code>-configurator</code> command line
* option to the server.
* <p>
* A "configurator" is a class containing static methods to provide
* information about the environment to an Inq application. The static
* methods herein may be called from Inq script as and when the
* information is required.
* <p>
* A system may require such things as database credentials to be stored
* securely. Integrators may wish to implement this class to silently
* decrypt and return passwords, for example.
* @author tom
*
*/
public class Configurator
{
static private Any which__ = AbstractValue.flyweightString("which");
static private Any xylinq__ = AbstractValue.flyweightString("xylinq");
static private Any inq__ = AbstractValue.flyweightString("inq");
static private Any xyuser__ = AbstractValue.flyweightString("xy1");
static private Any xypassword__ = AbstractValue.flyweightString("xy1");
static private Any xyurl__ = AbstractValue.flyweightString("jdbc:mysql://localhost/xydev?verifyServerCertificate=false&useSSL=false&requireSSL=false");
static private Any inquser__ = AbstractValue.flyweightString("inq");
static private Any inqpassword__ = AbstractValue.flyweightString("inq123");
static private Any inqurl__ = AbstractValue.flyweightString("jdbc:mysql://localhost/inq?verifyServerCertificate=false&useSSL=false&requireSSL=false");
static private Map mXylinqDb__;
static private Map mInqDb__;
static
{
mXylinqDb__ = Helpers.makeInqMap();
mXylinqDb__.add(Helpers.USER, xyuser__);
mXylinqDb__.add(Helpers.PASSWORD, xypassword__);
mXylinqDb__.add(Helpers.URL, xyurl__);
mInqDb__ = Helpers.makeInqMap();
mInqDb__.add(Helpers.USER, inquser__);
mInqDb__.add(Helpers.PASSWORD, inqpassword__);
mInqDb__.add(Helpers.URL, inqurl__);
}
/**
* Returns a map whose keys are plugin names and values are
* the fully-qualified class names of {@link com.inqwellx.plugin.AbstractPlugin} extensions.
* The return type must be a {@link com.inqwell.any.Map} and
* classes may use {@link com.inqwellx.Helpers#makeInqMap()}
* and {@link com.inqwellx.Helpers#convertToInqMap(java.util.Map)} as appropriate.
* @param argsMap Inq environment's command line arguments.
* @return a {@link com.inqwell.any.Map} describing the plugins
* or null if there are no plugins configured.
*/
static public Any getPlugins(Map argsMap)
{
return null;
}
/**
* Returns a map describing a database connection, consisting of
* a user name, password and url. The map keys must
* be {@link Helpers#USER}, {@link Helpers#PASSWORD}
* and {@link Helpers#URL}. The values are strings to be used
* in the JDBC connection.
* @param argsMap
* Inq environment's command line arguments.
* @param id
* the identifier of the database connection being requested,
* for example, <code>"xylinq"</code>.
* @return
*/
static public Any getDatabaseLogin(Map argsMap, Any id)
{
// if (id.equals(xylinq__))
// return mXylinqDb__;
// else if (id.equals(inq__))
// return mInqDb__;
return getDbLogin(id);
}
/**
* Returns the database administrative password. This method need
* not be implemented if there is no need to provide privileged
* database access
*/
static public Any getDbPwd()
{
return getPwd();
}
static private Any getPwd()
{
Call fetchDbPwd = new Call(new LocateNode("$catalog.xy.test.exprs.fetchDbPwd"));
Any ret = Call.call(fetchDbPwd, null);
return ret;
}
static private Any getDbLogin(Any which)
{
Call fetchLogins = new Call(new LocateNode("$catalog.xy.test.exprs.fetchLogins"));
Map args = AbstractComposite.simpleMap();
args.add(which__, which);
Any ret = Call.call(fetchLogins, args);
return ret;
}
/**
* Returns a JMS Connection Factory object. This (default) implementation
* uses the Sun GlassFish Message Queue 4.4 specific connection factory
* and does not require JNDI.
* @param args
* @return
static public Any getJMSConnectionFactory(Map args)
{
return new AnyConnectionFactory(new com.sun.messaging.ConnectionFactory());
}
*/
}
| 32.719178 | 158 | 0.717605 |
b0577459f5852b079695a42cae1cdc9f896015b8 | 7,629 | /*
* Copyright 2017 - 2021 Whole Bean Software, LTD.
*
* 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 happynewmoonwithreport.type;
import happynewmoonwithreport.WasmRuntimeException;
import happynewmoonwithreport.type.JavaType.ByteUnsigned;
import java.util.UUID;
/**
* I64 is the WebAssembly runtime 64 bit Integer. It can be interpreted as either signed or
* unsigned.
* <br>
* source https://webassembly.github.io/spec/core/text/values.html#integers
*/
public class I64 extends IntWasm {
protected Long value;
public I64() {
super();
}
public I64(Integer value) {
this.value = value.longValue();
}
public I64(Long value) {
this();
this.value = value.longValue();
}
/**
* Create a I64 given an array of bytes.
*
* @param byteAll an Array of bytes. <b>Little Endian</b>
* <p>
* byte[0] - Most significant byte
* <p>
* byte[7] - Least significant byte
*/
public I64(ByteUnsigned[] byteAll) {
this();
value = 0L;
value += byteAll[0].longValue() << 56;
value += byteAll[1].longValue() << 48;
value += byteAll[2].longValue() << 40;
value += byteAll[3].longValue() << 32;
value += byteAll[4].longValue() << 24;
value += byteAll[5].longValue() << 16;
value += byteAll[6].longValue() << 8;
value += byteAll[7].longValue() << 0;
}
/**
* Create an I64 using a Byte array, length, and sign extension.
*
* @param byteAll an array of unsigned bytes. Little Endian.
* @param length the number of bits to interpret. Valid values 8, 16, 32. Use only
* the >length< bits. The unused bits are ignored.
* <p>
* byte[0] - Most significant byte
* <p>
* byte[7] - Least significant byte
* @param signExtension is this a signed value? True = signed.
*/
public I64(ByteUnsigned[] byteAll, Integer length, Boolean signExtension) {
this();
create(byteAll, length, signExtension);
}
private void create(ByteUnsigned[] byteAll, Integer length, Boolean signExtension) {
value = 0L;
switch (length) {
case 8: {
value += byteAll[0].intValue();
if (signExtension) {
value = signExtend8To64(byteAll[0]);
}
break;
}
case 16: {
value += ((byteAll[1].intValue()) << 0); // Least Significant Byte
value += ((byteAll[0].intValue()) << 8); // Most Significant Byte
if (signExtension) {
value = signExtend16To64(value);
}
break;
}
case 32: {
value += ((byteAll[3].intValue()) << 0); // Least Significant Byte
value += ((byteAll[2].intValue()) << 8);
value += ((byteAll[1].intValue()) << 16);
// (byteAll[0] << 24) must be cast to long. The compiler defaults to an int and we
// get negative numbers when (0x8000 <= byteAll[0]).
value += ((long) (byteAll[0].intValue()) << 24); // Most Significant Byte
if (signExtension) {
value = signExtend32To64(value);
}
break;
}
default: {
throw new WasmRuntimeException(
UUID.fromString("15ffb37c-ad38-4f03-8499-a77d87ba83b1"),
"I32 Constructor Illegal value in length. Valid values are 8, 16, 32."
+ "Length = " + length);
}
}
}
/**
* Get an array of the bytes. Little Endian.
*
* @return array of bytes. Size of array is 8.
* <br>
* byte[0] - Most significant byte
* <br>
* byte[7] - Least significant byte
*/
@Override
public ByteUnsigned[] getBytes() {
ByteUnsigned[] byteAll = new ByteUnsigned[8];
byteAll[7] = new ByteUnsigned((value >>> 0) & 0x0000_00FF); // Least Significant Byte
byteAll[6] = new ByteUnsigned((value >>> 8) & 0x0000_00FF);
byteAll[5] = new ByteUnsigned((value >>> 16) & 0x0000_00FF);
byteAll[4] = new ByteUnsigned((value >>> 24) & 0x0000_00FF);
byteAll[3] = new ByteUnsigned((value >>> 32) & 0x0000_00FF);
byteAll[2] = new ByteUnsigned((value >>> 40) & 0x0000_00FF);
byteAll[1] = new ByteUnsigned((value >>> 48) & 0x0000_00FF);
byteAll[0] = new ByteUnsigned((value >>> 56) & 0x0000_00FF); // Most Significant Byte
return byteAll;
}
/**
* Extend 8 to 64 signed. Interpreting the 8 least significant bits as signed and convert to
* 32 bits I64.
*
* @return An I64 value
*/
public I64 extend8To64Signed() {
long resultLong = signExtend8To64(value);
I64 result = new I64(resultLong);
return result;
}
/**
* Extend 16 to 64 signed. Interpreting the 16 least significant bits as signed and convert to
* 64 bits I64.
*
* @return An I64 value
*/
public I64 extend16To64Signed() {
long resultInt = signExtend16To64(value);
I64 result = new I64(resultInt);
return result;
}
/**
* Extend 32 to 64 signed. Interpreting the 32 least significant bits as signed and convert to
* 64 bits I64.
*
* @return An I64 value
*/
public I64 extend32To64Signed() {
long resultInt = signExtend32To64(value);
I64 result = new I64(resultInt);
return result;
}
/**
* Count the number of leading zeros in the value.
* <br>
*
* @return I32 (0 <= result && result <= 64).
*/
public I32 countLeadingZeros() {
Integer result = Long.numberOfLeadingZeros(value);
return new I32(result);
}
/**
* Count the number of trailing zeros in the value.
* <br>
*
* @return I32 (0 <= result && result <= 64).
*/
public I32 countTrailingZeros() {
Integer result = Long.numberOfTrailingZeros(value);
return new I32(result);
}
/**
* Count the number one-bits in the value.
* <br>
*
* @return I32 (0 <= result && result <= 64).
*/
public I32 populationCount() {
Integer result = Long.bitCount(value);
return new I32(result);
}
@Override
public Integer maxBits() {
return 64;
}
@Override
public Long minValue() {
Long minValue = -1L * (1L << (maxBits() - 1L));
return minValue;
}
@Override
public Long maxValue() {
Long maxValue = (1L << (maxBits() - 1L)) - 1L;
return maxValue;
}
@Override
public Boolean isBoundByInteger() {
return (Integer.MIN_VALUE <= value.longValue() && value.longValue() <= Integer.MAX_VALUE);
}
public S64 signedValue() {
return new S64(value);
}
public U64 unsignedValue() {
return new U64(value);
}
@Override
public Boolean booleanValue() {
return value != 0;
}
@Override
public Byte byteValue() {
return value.byteValue();
}
@Override
public Integer integerValue() {
return value.intValue();
}
@Override
public Long longValue() {
return value.longValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
I64 i64Other = (I64) other;
return value != null ? value.equals(i64Other.value) : i64Other.value == null;
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
@Override
public String toString() {
String result = "I64{ value = " + value + " (hex = " + toHex(value) + ") }";
return result;
}
}
| 26.126712 | 96 | 0.630882 |
b9098edb80f1fda3f0b96b42402afadac8cd0968 | 1,616 | package indi.mybatis.flying.service;
import java.util.Collection;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import indi.mybatis.flying.mapper.RoleMapper;
import indi.mybatis.flying.pojo.Role_;
import indi.mybatis.flying.pojoHelper.ServiceSupport;
@Service
public class RoleService extends ServiceSupport<Role_> implements RoleMapper {
@Autowired
private RoleMapper mapper;
@Override
public Role_ select(Object id) {
return supportSelect(mapper, id);
}
@Override
public Role_ selectEverything(Object id) {
return mapper.selectEverything(id);
}
@Override
public Role_ selectNoId(Object id) {
return mapper.selectNoId(id);
}
@Override
public Role_ selectOne(Role_ t) {
return supportSelectOne(mapper, t);
}
@Override
public void insert(Role_ t) {
supportInsert(mapper, t);
}
@Override
public int update(Role_ t) {
return supportUpdate(mapper, t);
}
@Override
public Collection<Role_> selectAll(Role_ t) {
return supportSelectAll(mapper, t);
}
@Override
public int updatePersistent(Role_ t) {
return supportUpdatePersistent(mapper, t);
}
@Override
public int delete(Role_ t) {
return supportDelete(mapper, t);
}
@Override
public int count(Role_ t) {
return supportCount(mapper, t);
}
@Override
public int updateDirect(Map<String, Object> m) {
return mapper.updateDirect(m);
}
@Override
public Role_ selectWithoutCache(Object id) {
return mapper.selectWithoutCache(id);
}
} | 20.455696 | 79 | 0.716584 |
975a85125fc0593e44455023dede62cc9e91a37a | 18,454 | package com.example.zls.widget.custom_view;
import com.example.zls.R;
import com.example.zls.utils.ScreenUtils;
import com.example.zls.widget.action.Action0;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.concurrent.TimeUnit;
import androidx.annotation.DrawableRes;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;
public class BackgroundCountdownView extends View {
private final int ONE_BG = 1;
private final int TWO_BG = 2;
private final int THREE_BG = 3;
private Disposable mDisposable;
private long mDuration;
private int mDigitalGap;
private int mImgTextGap;
private Paint mPaint;
private Paint.FontMetrics mMetrics;
private String mFirstLineText;
private int mYears;
private int mDays;
private String mHours;
private String mMinutes;
private String mSeconds;
private Bitmap mBackground;
private int mLastBgNum;
public BackgroundCountdownView(Context context) {
this(context, null);
}
public BackgroundCountdownView(Context context,
@androidx.annotation.Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BackgroundCountdownView(Context context,
@androidx.annotation.Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mBackground = BitmapFactory
.decodeResource(context.getResources(), R.drawable.ic_countdown_span_bg);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mFirstLineText = getContext().getString(R.string.chicken_dialog_still_wait);
mDigitalGap = ScreenUtils.dip2px(getContext(), 22);
mImgTextGap = ScreenUtils.dip2px(getContext(), 8);
mPaint.setColor(Color.parseColor("#392626"));
mPaint.setStrokeWidth(10);
mPaint.setTextSize(ScreenUtils.sp2px(getContext(), 18));
mPaint.setTypeface(Typeface.DEFAULT_BOLD);
mMetrics = mPaint.getFontMetrics();
}
private void duration2String(long duration) {
//如果duration为0,策略为显示两个背景,显示00:00
int hour = (int) (duration / 3600);
int minute = (int) ((duration % 3600) / 60);
int second = (int) ((duration % 3600) % 60);
int day = hour / 24;
int year = day / 365;
if (year != 0) {
mYears = year;
} else if (day != 0) {
mYears = 0;
mDays = day;
} else if (hour == 0) {
mYears = 0;
mDays = 0;
mHours = "";
mMinutes = getResources().getString(R.string.minutes_formatter, minute % 60);
mSeconds = getResources().getString(R.string.seconds_formatter, second % 60);
} else {
mYears = 0;
mDays = 0;
mHours = getResources().getString(R.string.hours_formatter, hour);
mMinutes = getResources().getString(R.string.minutes_formatter, minute % 60);
mSeconds = getResources().getString(R.string.seconds_formatter, second % 60);
}
Timber.d("calculate complete");
}
private int bgNumNeedDraw() {
if (mDays != 0 || mYears != 0) { //需要一个背景
return ONE_BG;
} else if (mHours.equals("")) { //需要两个背景
return TWO_BG;
} else { //有 时分秒 需要三个背景
return THREE_BG;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Timber.d("on measure");
int measuredWidth, measureHeight;
measureHeight = mBackground.getHeight() + (int) getCountdownDrawStartY();
switch (bgNumNeedDraw()) {
case ONE_BG:
measuredWidth = Math.max((int) mPaint.measureText(mFirstLineText),
mBackground.getWidth() + mImgTextGap + (int) (mYears > 0 ? mPaint
.measureText(getResources().getString(R.string.text_time_year))
: mPaint.measureText(
getResources().getString(R.string.text_time_day))));
break;
case TWO_BG:
measuredWidth = Math.max((int) mPaint.measureText(mFirstLineText),
mBackground.getWidth() * 2 + mDigitalGap);
break;
case THREE_BG:
default:
measuredWidth = Math.max((int) mPaint.measureText(mFirstLineText),
mBackground.getWidth() * 3 + mDigitalGap * 2);
break;
}
setMeasuredDimension(measuredWidth, measureHeight);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Timber.d("on layout");
super.onLayout(changed, left, top, right, bottom);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
}
@Override
protected void onDraw(Canvas canvas) {
Timber.d("on draw");
super.onDraw(canvas);
// float textHeight = mMetrics.bottom + Math.abs(mMetrics.top);
float textWidth = mPaint.measureText(mFirstLineText);
if (mLastBgNum != bgNumNeedDraw()) {
requestLayout();
}
switch (bgNumNeedDraw()) {
case ONE_BG:
mLastBgNum = ONE_BG;
drawOneBg(textWidth, canvas);
break;
case TWO_BG:
mLastBgNum = TWO_BG;
drawTwoBg(textWidth, canvas);
break;
case THREE_BG:
mLastBgNum = THREE_BG;
drawThreeBg(textWidth, canvas);
break;
default:
break;
}
Timber.d("on draw complete");
}
private void drawThreeBg(float textWidth, Canvas canvas) {
int countdownWidth = mBackground.getWidth() * 3 + mDigitalGap * 2;
float endY = getCountdownDrawStartY() + mBackground.getHeight();
if (textWidth > countdownWidth) { //首行文字宽度大于 倒计时宽度 让倒计时中心对齐文字中心
mPaint.setTextAlign(Paint.Align.LEFT);
canvas.drawText(mFirstLineText, 0, Math.abs(mMetrics.top), mPaint);
canvas.drawBitmap(mBackground,
textWidth / 2 - (mBackground.getWidth() * 1.5f + mDigitalGap),
getCountdownDrawStartY(), null);
mPaint.setTextAlign(Paint.Align.CENTER);
drawTextCenter(canvas, String.valueOf(mHours),
new RectF(textWidth / 2 - (mBackground.getWidth() * 1.5f + mDigitalGap),
getCountdownDrawStartY(),
textWidth / 2 - (mBackground.getWidth() * 1.5f + mDigitalGap)
+ mBackground.getWidth(), endY));
drawTextCenter(canvas, ":",
new RectF(
textWidth / 2 - (mDigitalGap + (mBackground.getWidth() >> 1)),
getCountdownDrawStartY(),
textWidth / 2 - (mBackground.getWidth() >> 1),
endY));
canvas.drawBitmap(mBackground, textWidth / 2 - (mBackground.getWidth() >> 1),
getCountdownDrawStartY(), null);
drawTextCenter(canvas, String.valueOf(mMinutes),
new RectF(textWidth / 2 - (mBackground.getWidth() >> 1),
getCountdownDrawStartY(),
textWidth / 2 - (mBackground.getWidth() >> 1) + mBackground.getWidth(),
endY));
drawTextCenter(canvas, ":", new RectF(
textWidth / 2 + (mBackground.getWidth() >> 1),
getCountdownDrawStartY(),
textWidth / 2 + (mBackground.getWidth() >> 1) + mDigitalGap,
endY));
canvas.drawBitmap(mBackground,
textWidth / 2 + (mBackground.getWidth() >> 1) + mDigitalGap,
getCountdownDrawStartY(), null);
drawTextCenter(canvas, String.valueOf(mSeconds),
new RectF(textWidth / 2 + (mBackground.getWidth() >> 1) + mDigitalGap,
getCountdownDrawStartY(),
textWidth / 2 + (mBackground.getWidth() >> 1) + mDigitalGap
+ mBackground.getWidth(), endY));
} else { //首行文字宽度小于 倒计时宽度 让文字中心对齐倒计时中心
mPaint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(mFirstLineText, countdownWidth / 2, Math.abs(mMetrics.top), mPaint);
canvas.drawBitmap(mBackground, 0, getCountdownDrawStartY(), null);
drawTextCenter(canvas, String.valueOf(mHours),
new RectF(0, getCountdownDrawStartY(), mBackground.getWidth(), endY));
drawTextCenter(canvas, ":", new RectF(
mBackground.getWidth(),
getCountdownDrawStartY(),
mBackground.getWidth() + mDigitalGap,
endY));
canvas.drawBitmap(mBackground, mBackground.getWidth() + mDigitalGap,
getCountdownDrawStartY(), null);
drawTextCenter(canvas, String.valueOf(mMinutes),
new RectF(mBackground.getWidth() + mDigitalGap,
getCountdownDrawStartY(), mBackground.getWidth() * 2 + mDigitalGap,
endY));
drawTextCenter(canvas, ":", new RectF(
mBackground.getWidth() * 2 + mDigitalGap,
getCountdownDrawStartY(),
(mBackground.getWidth() + mDigitalGap) * 2,
endY));
canvas.drawBitmap(mBackground,
(mBackground.getWidth() + mDigitalGap) * 2,
getCountdownDrawStartY(), null);
drawTextCenter(canvas, String.valueOf(mSeconds),
new RectF((mBackground.getWidth() + mDigitalGap) * 2,
getCountdownDrawStartY(), mBackground.getWidth() * 3 + mDigitalGap * 2,
endY));
}
}
private void drawTwoBg(float textWidth, Canvas canvas) {
int countdownWidth = mBackground.getWidth() * 2 + mDigitalGap;
float endY = getCountdownDrawStartY() + mBackground.getHeight();
if (textWidth > countdownWidth) { //首行文字宽度大于 倒计时宽度 让倒计时中心对齐文字中心
mPaint.setTextAlign(Paint.Align.LEFT);
canvas.drawText(mFirstLineText, 0, Math.abs(mMetrics.top), mPaint);
canvas.drawBitmap(mBackground,
textWidth / 2 - (mBackground.getWidth() + (mDigitalGap >> 1)),
getCountdownDrawStartY(), null);
mPaint.setTextAlign(Paint.Align.CENTER);
drawTextCenter(canvas, String.valueOf(mMinutes),
new RectF(textWidth / 2 - (mBackground.getWidth() + (mDigitalGap >> 1)),
getCountdownDrawStartY(),
textWidth / 2 - (mBackground.getWidth() + (mDigitalGap >> 1))
+ mBackground.getWidth(),
getCountdownDrawStartY() + mBackground.getHeight()));
drawTextCenter(canvas, ":",
new RectF(
textWidth / 2 - (mDigitalGap >> 1),
getCountdownDrawStartY(),
textWidth / 2 + (mDigitalGap >> 1),
endY));
canvas.drawBitmap(mBackground, textWidth / 2 + (mDigitalGap >> 1),
getCountdownDrawStartY(), null);
drawTextCenter(canvas, String.valueOf(mSeconds),
new RectF(textWidth / 2 + (mDigitalGap >> 1), getCountdownDrawStartY(),
textWidth / 2 + (mDigitalGap >> 1) + mBackground.getWidth(),
getCountdownDrawStartY() + mBackground.getHeight()));
} else { //首行文字宽度小于 倒计时宽度 让文字中心对齐倒计时中心
mPaint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(mFirstLineText, countdownWidth / 2, Math.abs(mMetrics.top), mPaint);
canvas.drawBitmap(mBackground, 0, getCountdownDrawStartY(), null);
drawTextCenter(canvas, String.valueOf(mMinutes),
new RectF(0, getCountdownDrawStartY(), mBackground.getWidth(),
getCountdownDrawStartY() + mBackground.getHeight()));
drawTextCenter(canvas, ":", new RectF(
mBackground.getWidth(),
getCountdownDrawStartY(),
mBackground.getWidth() + mDigitalGap,
endY));
canvas.drawBitmap(mBackground, mBackground.getWidth() + mDigitalGap,
getCountdownDrawStartY(), null);
drawTextCenter(canvas, String.valueOf(mSeconds),
new RectF(mBackground.getWidth() + mDigitalGap, getCountdownDrawStartY(),
mBackground.getWidth() * 2 + mDigitalGap,
getCountdownDrawStartY() + mBackground.getHeight()));
}
}
private void drawOneBg(float textWidth, Canvas canvas) {
int countdownWidth = mBackground.getWidth() + mImgTextGap + (int) (mYears > 0 ? mPaint
.measureText(getResources().getString(R.string.text_time_year))
: mPaint.measureText(getResources().getString(R.string.text_time_day)));
if (textWidth > countdownWidth) { //首行文字宽度大于 倒计时宽度 让倒计时中心对齐文字中心
mPaint.setTextAlign(Paint.Align.LEFT);
canvas.drawText(mFirstLineText, 0, Math.abs(mMetrics.top), mPaint);
canvas.drawBitmap(mBackground, textWidth / 2 - (mBackground.getWidth() >> 1),
getCountdownDrawStartY(), null);
mPaint.setTextAlign(Paint.Align.CENTER);
drawTextCenter(canvas, mYears > 0 ? String.valueOf(mYears) : String.valueOf(mDays),
new RectF(
textWidth / 2 - (mBackground.getWidth() >> 1),
getCountdownDrawStartY(),
textWidth / 2 - (mBackground.getWidth() >> 1) + mBackground.getWidth(),
getCountdownDrawStartY() + mBackground.getHeight()
));
mPaint.setTextAlign(Paint.Align.LEFT);
canvas.drawText(getResources().getString(mYears > 0 ? R.string.text_time_year
: R.string.text_time_day),
textWidth / 2 - (mBackground.getWidth() >> 1) + mBackground.getWidth()
+ mImgTextGap,
getCountdownDrawStartY() + mBackground.getHeight() - mMetrics.descent, mPaint);
} else { //首行文字宽度小于 倒计时宽度 让文字中心对齐倒计时中心
mPaint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(mFirstLineText, countdownWidth >> 1, Math.abs(mMetrics.top), mPaint);
canvas.drawBitmap(mBackground, 0, getCountdownDrawStartY(), null);
drawTextCenter(canvas, mYears > 0 ? String.valueOf(mYears) : String.valueOf(mDays),
new RectF(0, getCountdownDrawStartY(), mBackground.getWidth(),
getCountdownDrawStartY() + mBackground.getHeight()));
mPaint.setTextAlign(Paint.Align.LEFT);
canvas.drawText(getResources().getString(mYears > 0 ? R.string.text_time_year
: R.string.text_time_day),
mBackground.getWidth() + mImgTextGap,
getCountdownDrawStartY() + mBackground.getHeight() - mMetrics.descent, mPaint);
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
private float getCountdownDrawStartY() {
return mMetrics.bottom + Math.abs(mMetrics.top) + ScreenUtils.dip2px(getContext(), 9);
}
/**
* 使文字矩形区域内居中绘制
*/
private void drawTextCenter(Canvas canvas, String text, RectF rectF) {
Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
float top = fontMetrics.top;
float bottom = fontMetrics.bottom;
int baseLineY = (int) (rectF.centerY() - top / 2 - bottom / 2);
canvas.drawText(text, rectF.centerX(), baseLineY, mPaint);
}
public void startCountDown(long duration, Action0 endAction) {
initCountDown(duration);
mDisposable = Observable.interval(0, 1, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(aLong -> {
mDuration = duration - aLong;
handleDrawCondition(aLong);
if (mDuration == aLong && endAction != null) {
endAction.call();
}
}, throwable -> {
Timber.d("count down error");
});
}
private void initCountDown(long duration) {
duration2String(duration);
invalidate();
Timber.d("calculate first time");
}
private void handleDrawCondition(Long aLong) {
duration2String(mDuration);
invalidate();
Timber.d("calculate countdown time : %s", aLong);
}
public void setFirstLineText(String firstLineText) {
mFirstLineText = firstLineText;
requestLayout();
}
public void setBackgroundResource(@DrawableRes int background) {
mBackground = BitmapFactory.decodeResource(getResources(), background);
requestLayout();
}
public void setDigitalGap(int digitalGap) {
mDigitalGap = digitalGap;
requestLayout();
}
public void release() {
if (mDisposable != null && !mDisposable.isDisposed()) {
mDisposable.dispose();
}
mDisposable = null;
}
}
| 43.319249 | 99 | 0.572559 |
75de315acb70396616fcdfeaaa9be3ed71afbe62 | 25,151 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.operators.sort;
import org.apache.flink.api.common.typeutils.TypeComparator;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.runtime.io.disk.ChannelReaderInputViewIterator;
import org.apache.flink.runtime.io.disk.iomanager.BlockChannelReader;
import org.apache.flink.runtime.io.disk.iomanager.BlockChannelWriter;
import org.apache.flink.runtime.io.disk.iomanager.ChannelReaderInputView;
import org.apache.flink.runtime.io.disk.iomanager.ChannelWriterOutputView;
import org.apache.flink.runtime.io.disk.iomanager.FileIOChannel;
import org.apache.flink.runtime.io.disk.iomanager.IOManager;
import org.apache.flink.runtime.memory.MemoryManager;
import org.apache.flink.runtime.util.EmptyMutableObjectIterator;
import org.apache.flink.util.MutableObjectIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import static org.apache.flink.runtime.operators.sort.CircularElement.EOF_MARKER;
import static org.apache.flink.runtime.operators.sort.CircularElement.SPILLING_MARKER;
import static org.apache.flink.util.Preconditions.checkNotNull;
/**
* The thread that handles the spilling of intermediate results and sets up the merging. It also
* merges the channels until sufficiently few channels remain to perform the final streamed merge.
*/
final class SpillingThread<E> extends ThreadBase<E> {
/** An interface for injecting custom behaviour for spilling and merging phases. */
interface SpillingBehaviour<E> {
default void open() {}
default void close() {}
/**
* A method that allows adjusting the spilling phase. We can inject e.g. combining the
* elements while spilling.
*/
void spillBuffer(
CircularElement<E> element,
ChannelWriterOutputView output,
LargeRecordHandler<E> largeRecordHandler)
throws IOException;
/**
* A method that allows adjusting the merging phase. We can inject e.g. combining the
* spilled elements.
*/
void mergeRecords(MergeIterator<E> mergeIterator, ChannelWriterOutputView output)
throws IOException;
}
/** Logging. */
private static final Logger LOG = LoggerFactory.getLogger(SpillingThread.class);
private final MemoryManager memManager; // memory manager to release memory
private final IOManager ioManager; // I/O manager to create channels
private final TypeSerializer<E> serializer; // The serializer for the data type
private final TypeComparator<E>
comparator; // The comparator that establishes the order relation.
private final List<MemorySegment> writeMemory; // memory segments for writing
private final List<MemorySegment> mergeReadMemory; // memory segments for sorting/reading
private final int maxFanIn;
private final SpillChannelManager spillChannelManager;
private final LargeRecordHandler<E> largeRecordHandler;
private final SpillingBehaviour<E> spillingBehaviour;
private volatile boolean spillingBehaviourOpened = false;
private final int minNumWriteBuffers;
private final int maxNumWriteBuffers;
SpillingThread(
@Nullable ExceptionHandler<IOException> exceptionHandler,
StageMessageDispatcher<E> dispatcher,
MemoryManager memManager,
IOManager ioManager,
TypeSerializer<E> serializer,
TypeComparator<E> comparator,
List<MemorySegment> sortReadMemory,
List<MemorySegment> writeMemory,
int maxNumFileHandles,
SpillChannelManager spillingChannelManager,
@Nullable LargeRecordHandler<E> largeRecordHandler,
SpillingBehaviour<E> spillingBehaviour,
int minNumWriteBuffers,
int maxNumWriteBuffers) {
super(exceptionHandler, "SortMerger spilling thread", dispatcher);
this.memManager = checkNotNull(memManager);
this.ioManager = checkNotNull(ioManager);
this.serializer = checkNotNull(serializer);
this.comparator = checkNotNull(comparator);
this.mergeReadMemory = checkNotNull(sortReadMemory);
this.writeMemory = checkNotNull(writeMemory);
this.maxFanIn = maxNumFileHandles;
this.spillChannelManager = checkNotNull(spillingChannelManager);
this.largeRecordHandler = largeRecordHandler;
this.spillingBehaviour = checkNotNull(spillingBehaviour);
this.minNumWriteBuffers = minNumWriteBuffers;
this.maxNumWriteBuffers = maxNumWriteBuffers;
}
/** Entry point of the thread. */
@Override
public void go() throws IOException, InterruptedException {
// ------------------- In-Memory Cache ------------------------
final Queue<CircularElement<E>> cache = new ArrayDeque<>();
boolean cacheOnly = readCache(cache);
// check whether the thread was canceled
if (!isRunning()) {
return;
}
MutableObjectIterator<E> largeRecords = null;
// check if we can stay in memory with the large record handler
if (cacheOnly && largeRecordHandler != null && largeRecordHandler.hasData()) {
List<MemorySegment> memoryForLargeRecordSorting = new ArrayList<>();
CircularElement<E> circElement;
while ((circElement = this.dispatcher.poll(SortStage.READ)) != null) {
circElement.getBuffer().dispose();
memoryForLargeRecordSorting.addAll(circElement.getMemory());
}
if (memoryForLargeRecordSorting.isEmpty()) {
cacheOnly = false;
LOG.debug("Going to disk-based merge because of large records.");
} else {
LOG.debug("Sorting large records, to add them to in-memory merge.");
largeRecords =
largeRecordHandler.finishWriteAndSortKeys(memoryForLargeRecordSorting);
}
}
// ------------------- In-Memory Merge ------------------------
if (cacheOnly) {
mergeInMemory(cache, largeRecords);
return;
}
// ------------------- Spilling Phase ------------------------
List<ChannelWithBlockCount> channelIDs = startSpilling(cache);
// ------------------- Merging Phase ------------------------
mergeOnDisk(channelIDs);
}
@Override
public void close() throws InterruptedException {
super.close();
if (spillingBehaviourOpened) {
this.spillingBehaviour.close();
this.spillingBehaviourOpened = false;
}
}
private boolean readCache(Queue<CircularElement<E>> cache) throws InterruptedException {
// fill cache
while (isRunning()) {
// take next element from queue
final CircularElement<E> element = this.dispatcher.take(SortStage.SPILL);
if (element == SPILLING_MARKER) {
return false;
} else if (element == EOF_MARKER) {
return true;
}
cache.add(element);
}
return false;
}
private void mergeOnDisk(List<ChannelWithBlockCount> channelIDs) throws IOException {
// make sure we have enough memory to merge and for large record handling
List<MemorySegment> mergeReadMemory;
MutableObjectIterator<E> largeRecords = null;
if (largeRecordHandler != null && largeRecordHandler.hasData()) {
List<MemorySegment> longRecMem;
if (channelIDs.isEmpty()) {
// only long records
longRecMem = this.mergeReadMemory;
mergeReadMemory = Collections.emptyList();
} else {
int maxMergedStreams = Math.min(this.maxFanIn, channelIDs.size());
int pagesPerStream =
Math.max(
minNumWriteBuffers,
Math.min(
maxNumWriteBuffers,
this.mergeReadMemory.size() / 2 / maxMergedStreams));
int totalMergeReadMemory = maxMergedStreams * pagesPerStream;
// grab the merge memory
mergeReadMemory = new ArrayList<>(totalMergeReadMemory);
for (int i = 0; i < totalMergeReadMemory; i++) {
mergeReadMemory.add(this.mergeReadMemory.get(i));
}
// the remainder of the memory goes to the long record sorter
longRecMem = new ArrayList<>();
for (int i = totalMergeReadMemory; i < this.mergeReadMemory.size(); i++) {
longRecMem.add(this.mergeReadMemory.get(i));
}
}
LOG.debug("Sorting keys for large records.");
largeRecords = largeRecordHandler.finishWriteAndSortKeys(longRecMem);
} else {
mergeReadMemory = this.mergeReadMemory;
}
// merge channels until sufficient file handles are available
while (isRunning() && channelIDs.size() > this.maxFanIn) {
channelIDs = mergeChannelList(channelIDs, mergeReadMemory, this.writeMemory);
}
// from here on, we won't write again
this.memManager.release(this.writeMemory);
this.writeMemory.clear();
// check if we have spilled some data at all
if (channelIDs.isEmpty()) {
if (largeRecords == null) {
this.dispatcher.sendResult(EmptyMutableObjectIterator.get());
} else {
this.dispatcher.sendResult(largeRecords);
}
} else {
LOG.debug("Beginning final merge.");
// allocate the memory for the final merging step
List<List<MemorySegment>> readBuffers = new ArrayList<>(channelIDs.size());
// allocate the read memory and register it to be released
getSegmentsForReaders(readBuffers, mergeReadMemory, channelIDs.size());
// get the readers and register them to be released
this.dispatcher.sendResult(
getMergingIterator(
channelIDs,
readBuffers,
new ArrayList<>(channelIDs.size()),
largeRecords));
}
// done
LOG.debug("Spilling and merging thread done.");
}
private void mergeInMemory(
Queue<CircularElement<E>> cache, MutableObjectIterator<E> largeRecords)
throws IOException {
// operates on in-memory buffers only
LOG.debug("Initiating in memory merge.");
List<MutableObjectIterator<E>> iterators = new ArrayList<>(cache.size() + 1);
// iterate buffers and collect a set of iterators
for (CircularElement<E> cached : cache) {
// note: the yielded iterator only operates on the buffer heap (and disregards the
// stack)
iterators.add(cached.getBuffer().getIterator());
}
if (largeRecords != null) {
iterators.add(largeRecords);
}
// release the remaining sort-buffers
LOG.debug("Releasing unused sort-buffer memory.");
disposeSortBuffers(true);
// set lazy iterator
if (iterators.isEmpty()) {
this.dispatcher.sendResult(EmptyMutableObjectIterator.get());
} else if (iterators.size() == 1) {
this.dispatcher.sendResult(iterators.get(0));
} else {
this.dispatcher.sendResult(new MergeIterator<>(iterators, this.comparator));
}
}
private List<ChannelWithBlockCount> startSpilling(Queue<CircularElement<E>> cache)
throws IOException, InterruptedException {
final FileIOChannel.Enumerator enumerator = this.ioManager.createChannelEnumerator();
List<ChannelWithBlockCount> channelIDs = new ArrayList<>();
// loop as long as the thread is marked alive and we do not see the final element
openSpillingBehaviour();
while (isRunning()) {
final CircularElement<E> element =
cache.isEmpty() ? this.dispatcher.take(SortStage.SPILL) : cache.poll();
// check if we are still running
if (!isRunning()) {
return Collections.emptyList();
}
// check if this is the end-of-work buffer
if (element == EOF_MARKER) {
break;
}
// open next channel
FileIOChannel.ID channel = enumerator.next();
spillChannelManager.registerChannelToBeRemovedAtShutdown(channel);
// create writer
final BlockChannelWriter<MemorySegment> writer =
this.ioManager.createBlockChannelWriter(channel);
spillChannelManager.registerOpenChannelToBeRemovedAtShutdown(writer);
final ChannelWriterOutputView output =
new ChannelWriterOutputView(
writer, this.writeMemory, this.memManager.getPageSize());
// write sort-buffer to channel
LOG.debug("Spilling buffer " + element.getId() + ".");
spillingBehaviour.spillBuffer(element, output, largeRecordHandler);
LOG.debug("Spilled buffer " + element.getId() + ".");
output.close();
spillChannelManager.unregisterOpenChannelToBeRemovedAtShutdown(writer);
if (output.getBytesWritten() > 0) {
channelIDs.add(new ChannelWithBlockCount(channel, output.getBlockCount()));
}
// pass empty sort-buffer to reading thread
element.getBuffer().reset();
this.dispatcher.send(SortStage.READ, element);
}
// done with the spilling
LOG.debug("Spilling done.");
LOG.debug("Releasing sort-buffer memory.");
// clear the sort buffers, but do not return the memory to the manager, as we use it for
// merging
disposeSortBuffers(false);
return channelIDs;
}
private void openSpillingBehaviour() {
if (!spillingBehaviourOpened) {
this.spillingBehaviour.open();
this.spillingBehaviourOpened = true;
}
}
/** Releases the memory that is registered for in-memory sorted run generation. */
private void disposeSortBuffers(boolean releaseMemory) {
CircularElement<E> element;
while ((element = this.dispatcher.poll(SortStage.READ)) != null) {
element.getBuffer().dispose();
if (releaseMemory) {
this.memManager.release(element.getMemory());
}
}
}
// ------------------------------------------------------------------------
// Result Merging
// ------------------------------------------------------------------------
/**
* Returns an iterator that iterates over the merged result from all given channels.
*
* @param channelIDs The channels that are to be merged and returned.
* @param inputSegments The buffers to be used for reading. The list contains for each channel
* one list of input segments. The size of the <code>inputSegments</code> list must be equal
* to that of the <code>channelIDs</code> list.
* @return An iterator over the merged records of the input channels.
* @throws IOException Thrown, if the readers encounter an I/O problem.
*/
private MergeIterator<E> getMergingIterator(
final List<ChannelWithBlockCount> channelIDs,
final List<List<MemorySegment>> inputSegments,
List<FileIOChannel> readerList,
MutableObjectIterator<E> largeRecords)
throws IOException {
// create one iterator per channel id
LOG.debug("Performing merge of {} sorted streams.", channelIDs.size());
final List<MutableObjectIterator<E>> iterators = new ArrayList<>(channelIDs.size() + 1);
for (int i = 0; i < channelIDs.size(); i++) {
final ChannelWithBlockCount channel = channelIDs.get(i);
final List<MemorySegment> segsForChannel = inputSegments.get(i);
// create a reader. if there are multiple segments for the reader, issue multiple
// together per I/O request
final BlockChannelReader<MemorySegment> reader =
this.ioManager.createBlockChannelReader(channel.getChannel());
readerList.add(reader);
spillChannelManager.registerOpenChannelToBeRemovedAtShutdown(reader);
spillChannelManager.unregisterChannelToBeRemovedAtShutdown(channel.getChannel());
// wrap channel reader as a view, to get block spanning record deserialization
final ChannelReaderInputView inView =
new ChannelReaderInputView(
reader, segsForChannel, channel.getBlockCount(), false);
iterators.add(new ChannelReaderInputViewIterator<>(inView, null, this.serializer));
}
if (largeRecords != null) {
iterators.add(largeRecords);
}
return new MergeIterator<>(iterators, this.comparator);
}
/**
* Merges the given sorted runs to a smaller number of sorted runs.
*
* @param channelIDs The IDs of the sorted runs that need to be merged.
* @param allReadBuffers
* @param writeBuffers The buffers to be used by the writers.
* @return A list of the IDs of the merged channels.
* @throws IOException Thrown, if the readers or writers encountered an I/O problem.
*/
private List<ChannelWithBlockCount> mergeChannelList(
final List<ChannelWithBlockCount> channelIDs,
final List<MemorySegment> allReadBuffers,
final List<MemorySegment> writeBuffers)
throws IOException {
// A channel list with length maxFanIn<sup>i</sup> can be merged to maxFanIn files in i-1
// rounds where every merge
// is a full merge with maxFanIn input channels. A partial round includes merges with fewer
// than maxFanIn
// inputs. It is most efficient to perform the partial round first.
final double scale = Math.ceil(Math.log(channelIDs.size()) / Math.log(this.maxFanIn)) - 1;
final int numStart = channelIDs.size();
final int numEnd = (int) Math.pow(this.maxFanIn, scale);
final int numMerges = (int) Math.ceil((numStart - numEnd) / (double) (this.maxFanIn - 1));
final int numNotMerged = numEnd - numMerges;
final int numToMerge = numStart - numNotMerged;
// unmerged channel IDs are copied directly to the result list
final List<ChannelWithBlockCount> mergedChannelIDs = new ArrayList<>(numEnd);
mergedChannelIDs.addAll(channelIDs.subList(0, numNotMerged));
final int channelsToMergePerStep = (int) Math.ceil(numToMerge / (double) numMerges);
// allocate the memory for the merging step
final List<List<MemorySegment>> readBuffers = new ArrayList<>(channelsToMergePerStep);
getSegmentsForReaders(readBuffers, allReadBuffers, channelsToMergePerStep);
final List<ChannelWithBlockCount> channelsToMergeThisStep =
new ArrayList<>(channelsToMergePerStep);
int channelNum = numNotMerged;
while (isRunning() && channelNum < channelIDs.size()) {
channelsToMergeThisStep.clear();
for (int i = 0;
i < channelsToMergePerStep && channelNum < channelIDs.size();
i++, channelNum++) {
channelsToMergeThisStep.add(channelIDs.get(channelNum));
}
mergedChannelIDs.add(mergeChannels(channelsToMergeThisStep, readBuffers, writeBuffers));
}
return mergedChannelIDs;
}
/**
* Merges the sorted runs described by the given Channel IDs into a single sorted run. The
* merging process uses the given read and write buffers.
*
* @param channelIDs The IDs of the runs' channels.
* @param readBuffers The buffers for the readers that read the sorted runs.
* @param writeBuffers The buffers for the writer that writes the merged channel.
* @return The ID and number of blocks of the channel that describes the merged run.
*/
private ChannelWithBlockCount mergeChannels(
List<ChannelWithBlockCount> channelIDs,
List<List<MemorySegment>> readBuffers,
List<MemorySegment> writeBuffers)
throws IOException {
// the list with the readers, to be closed at shutdown
final List<FileIOChannel> channelAccesses = new ArrayList<>(channelIDs.size());
// the list with the target iterators
final MergeIterator<E> mergeIterator =
getMergingIterator(channelIDs, readBuffers, channelAccesses, null);
// create a new channel writer
final FileIOChannel.ID mergedChannelID = this.ioManager.createChannel();
spillChannelManager.registerChannelToBeRemovedAtShutdown(mergedChannelID);
final BlockChannelWriter<MemorySegment> writer =
this.ioManager.createBlockChannelWriter(mergedChannelID);
spillChannelManager.registerOpenChannelToBeRemovedAtShutdown(writer);
final ChannelWriterOutputView output =
new ChannelWriterOutputView(writer, writeBuffers, this.memManager.getPageSize());
openSpillingBehaviour();
spillingBehaviour.mergeRecords(mergeIterator, output);
output.close();
final int numBlocksWritten = output.getBlockCount();
// register merged result to be removed at shutdown
spillChannelManager.unregisterOpenChannelToBeRemovedAtShutdown(writer);
// remove the merged channel readers from the clear-at-shutdown list
for (FileIOChannel access : channelAccesses) {
access.closeAndDelete();
spillChannelManager.unregisterOpenChannelToBeRemovedAtShutdown(access);
}
return new ChannelWithBlockCount(mergedChannelID, numBlocksWritten);
}
/**
* Divides the given collection of memory buffers among {@code numChannels} sublists.
*
* @param target The list into which the lists with buffers for the channels are put.
* @param memory A list containing the memory buffers to be distributed. The buffers are not
* removed from this list.
* @param numChannels The number of channels for which to allocate buffers. Must not be zero.
*/
private void getSegmentsForReaders(
List<List<MemorySegment>> target, List<MemorySegment> memory, int numChannels) {
// determine the memory to use per channel and the number of buffers
final int numBuffers = memory.size();
final int buffersPerChannelLowerBound = numBuffers / numChannels;
final int numChannelsWithOneMore = numBuffers % numChannels;
final Iterator<MemorySegment> segments = memory.iterator();
// collect memory for the channels that get one segment more
for (int i = 0; i < numChannelsWithOneMore; i++) {
final ArrayList<MemorySegment> segs = new ArrayList<>(buffersPerChannelLowerBound + 1);
target.add(segs);
for (int k = buffersPerChannelLowerBound; k >= 0; k--) {
segs.add(segments.next());
}
}
// collect memory for the remaining channels
for (int i = numChannelsWithOneMore; i < numChannels; i++) {
final ArrayList<MemorySegment> segs = new ArrayList<>(buffersPerChannelLowerBound);
target.add(segs);
for (int k = buffersPerChannelLowerBound; k > 0; k--) {
segs.add(segments.next());
}
}
}
}
| 42.058528 | 100 | 0.637072 |
f447f1ac1f32ce3cccc53a1cc49f13cf42189808 | 432 | package dev.plugin;
import dev.tensor.Tensor;
import dev.tensor.misc.plugin.Plugin;
/**
* @author IUDevman
* @since 08-10-2021
*/
@Plugin.Info(name = "Example Plugin", version = "0.1.0")
public final class ExamplePlugin extends Plugin {
@Override
public void load() {
Tensor.INSTANCE.LOGGER.info("Sheeet example plugin loaded");
Tensor.INSTANCE.MODULE_MANAGER.addModule(new ExampleModule());
}
}
| 20.571429 | 70 | 0.689815 |
3b4e68cfdfe2f23594da73298f83b84f30411370 | 6,463 | package com.scottescue.dropwizard.entitymanager;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.scottescue.dropwizard.entitymanager.entity.Person;
import io.dropwizard.jersey.errors.ErrorMessage;
import io.dropwizard.setup.Environment;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Before;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.ws.rs.*;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import java.sql.SQLDataException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
public class JerseyIntegrationTest extends AbstractIntegrationTest {
public static class TestApplication extends AbstractTestApplication {
@Override
protected ImmutableList<Class<?>> supportedEntities() {
return ImmutableList.of(Person.class);
}
@Override
public void onRun(TestConfiguration configuration, Environment environment) throws Exception {
final EntityManager sharedEntityManager = entityManagerBundle.getSharedEntityManager();
environment.jersey().register(new PersonResource(new PersonService(sharedEntityManager)));
environment.jersey().register(new DataExceptionMapper());
}
@Override
protected void onInitDatabase(EntityManager entityManager) {
entityManager.createNativeQuery("DROP TABLE people IF EXISTS").executeUpdate();
entityManager.createNativeQuery(
"CREATE TABLE people (name varchar(100) primary key, email varchar(16), birthday timestamp with time zone)")
.executeUpdate();
entityManager.createNativeQuery(
"INSERT INTO people VALUES ('Coda', 'coda@example.com', '1979-01-02 00:22:00+0:00')")
.executeUpdate();
}
}
public static class PersonService {
private final EntityManager entityManager;
public PersonService(EntityManager entityManager) {
this.entityManager = entityManager;
}
public Optional<Person> findByName(String name) {
return Optional.fromNullable(entityManager.find(Person.class, name));
}
public Person persist(Person entity) {
entityManager.persist(entity);
return entity;
}
}
@Path("/people/{name}")
@Produces(MediaType.APPLICATION_JSON)
public static class PersonResource {
private final PersonService service;
public PersonResource(PersonService service) {
this.service = service;
}
@GET
@UnitOfWork(readOnly = true)
public Optional<Person> find(@PathParam("name") String name) {
return service.findByName(name);
}
@PUT
@UnitOfWork
public void save(Person person) {
service.persist(person);
}
}
public static class DataExceptionMapper implements ExceptionMapper<PersistenceException> {
@Override
public Response toResponse(PersistenceException e) {
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
SQLDataException sqlException = unwrapThrowable(SQLDataException.class, e);
String message = (sqlException != null && sqlException.getMessage().contains("EMAIL"))
? "Wrong email"
: "Wrong input";
return Response.status(Response.Status.BAD_REQUEST)
.entity(new ErrorMessage(Response.Status.BAD_REQUEST.getStatusCode(), message))
.build();
}
}
@Before
public void setup() {
setup(TestApplication.class);
}
@Test
public void findsExistingData() throws Exception {
final Person coda = client.target(getUrl("/people/Coda")).request(MediaType.APPLICATION_JSON).get(Person.class);
assertThat(coda.getName())
.isEqualTo("Coda");
assertThat(coda.getEmail())
.isEqualTo("coda@example.com");
assertThat(coda.getBirthday())
.isEqualTo(new DateTime(1979, 1, 2, 0, 22, DateTimeZone.UTC));
}
@Test
public void doesNotFindMissingData() throws Exception {
try {
client.target(getUrl("/people/Poof")).request(MediaType.APPLICATION_JSON)
.get(Person.class);
failBecauseExceptionWasNotThrown(WebApplicationException.class);
} catch (WebApplicationException e) {
assertThat(e.getResponse().getStatus())
.isEqualTo(404);
}
}
@Test
public void createsNewData() throws Exception {
final Person person = new Person();
person.setName("Hank");
person.setEmail("hank@example.com");
person.setBirthday(new DateTime(1971, 3, 14, 19, 12, DateTimeZone.UTC));
client.target(getUrl("/people/Hank")).request().put(Entity.entity(person, MediaType.APPLICATION_JSON));
final Person hank = client.target(getUrl("/people/Hank"))
.request(MediaType.APPLICATION_JSON)
.get(Person.class);
assertThat(hank.getName())
.isEqualTo("Hank");
assertThat(hank.getEmail())
.isEqualTo("hank@example.com");
assertThat(hank.getBirthday())
.isEqualTo(person.getBirthday());
}
@Test
public void testSqlExceptionIsHandled() throws Exception {
final Person person = new Person();
person.setName("Jeff");
person.setEmail("jeff.hammersmith@targetprocessinc.com");
person.setBirthday(new DateTime(1984, 2, 11, 0, 0, DateTimeZone.UTC));
final Response response = client.target(getUrl("/people/Jeff")).request().
put(Entity.entity(person, MediaType.APPLICATION_JSON));
assertThat(response.getStatusInfo()).isEqualTo(Response.Status.BAD_REQUEST);
assertThat(response.getHeaderString(HttpHeaders.CONTENT_TYPE)).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(response.readEntity(ErrorMessage.class).getMessage()).isEqualTo("Wrong email");
}
}
| 36.721591 | 128 | 0.657435 |
89797d3153856efc405183c5aae8b46b37497891 | 3,859 | /*
* Copyright 2014-2018 Lukas Krejci
* and other contributors as indicated by the @author tags.
*
* 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.revapi.java.transforms.annotations;
import java.io.Reader;
import java.io.StringReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.jboss.dmr.ModelNode;
import org.revapi.AnalysisContext;
import org.revapi.CompatibilityType;
import org.revapi.Difference;
import org.revapi.DifferenceSeverity;
import org.revapi.DifferenceTransform;
import org.revapi.java.spi.JavaModelElement;
/**
* @author Lukas Krejci
* @since 0.12.0
*/
public final class DownplayHarmlessAnnotationChanges implements DifferenceTransform<JavaModelElement> {
private boolean skip = false;
private static final Set<String> HARMLESS_ANNOTATIONS = new HashSet<>(Arrays.asList(
"java.lang.FunctionalInterface", //having this is purely informational
"java.lang.annotation.Documented", //this doesn't affect the runtime at any rate
"jdk.internal.HotSpotIntrinsicCandidate" //
));
@Nonnull @Override public Pattern[] getDifferenceCodePatterns() {
return new Pattern[] {exact("java.annotation.added"), exact("java.annotation.removed"),
exact("java.annotation.attributeValueChanged"), exact("java.annotation.attributeAdded"),
exact("java.annotation.attributeRemoved")};
}
@Nullable @Override
public Difference transform(@Nullable JavaModelElement oldElement, @Nullable JavaModelElement newElement,
@Nonnull Difference difference) {
if (skip) {
return difference;
}
String annotationType = difference.attachments.get("annotationType");
if (annotationType == null) {
return difference;
}
if (HARMLESS_ANNOTATIONS.contains(annotationType)) {
return new Difference(difference.code, difference.name, difference.description,
reclassify(difference.classification), difference.attachments);
} else {
return difference;
}
}
@Override public void close() throws Exception {
}
@Nullable @Override public String getExtensionId() {
return "revapi.java.downplayHarmlessAnnotationChanges";
}
@Nullable @Override public Reader getJSONSchema() {
return new StringReader("{\"type\": \"boolean\"}");
}
@Override public void initialize(@Nonnull AnalysisContext analysisContext) {
ModelNode conf = analysisContext.getConfiguration()
.get("downplayHarmlessAnnotationChanges");
if (conf.isDefined()) {
skip = !conf.asBoolean();
}
}
private static Pattern exact(String string) {
return Pattern.compile("^" + Pattern.quote(string) + "$");
}
private static Map<CompatibilityType, DifferenceSeverity> reclassify(Map<CompatibilityType, DifferenceSeverity> orig) {
return orig.keySet().stream()
.collect(Collectors.toMap(Function.identity(), v -> DifferenceSeverity.EQUIVALENT));
}
}
| 35.731481 | 123 | 0.697072 |
c4440b68298072ba5aaa9ea5e4e04b627527793f | 12,065 | /*
* Copyright © 2019 Mark Raynsford <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
* BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
*/
package com.io7m.smfj.format.binary2.internal.serial;
import com.io7m.jbssio.api.BSSWriterSequentialType;
import com.io7m.junreachable.UnreachableCodeException;
import com.io7m.smfj.core.SMFAttribute;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEFloat1_16;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEFloat1_32;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEFloat1_64;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEFloat2_16;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEFloat2_32;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEFloat2_64;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEFloat3_16;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEFloat3_32;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEFloat3_64;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEFloat4_16;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEFloat4_32;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEFloat4_64;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBESigned1_16;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBESigned1_32;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBESigned1_64;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBESigned2_16;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBESigned2_32;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBESigned2_64;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBESigned3_16;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBESigned3_32;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBESigned3_64;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBESigned4_16;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBESigned4_32;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBESigned4_64;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEUnsigned1_16;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEUnsigned1_32;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEUnsigned1_64;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEUnsigned2_16;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEUnsigned2_32;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEUnsigned2_64;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEUnsigned3_16;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEUnsigned3_32;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEUnsigned3_64;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEUnsigned4_16;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEUnsigned4_32;
import com.io7m.smfj.format.binary2.internal.serial.be.WriterBEUnsigned4_64;
import com.io7m.smfj.serializer.api.SMFSerializerDataAttributesValuesType;
// CHECKSTYLE:OFF
/*
* Unavoidable class-data coupling; too many classes referenced.
*/
public final class SMFB2SerializerDataAttributeNonInterleavedBE
{
// CHECKSTYLE:ON
private SMFB2SerializerDataAttributeNonInterleavedBE()
{
}
static SMFSerializerDataAttributesValuesType serializeFloatBE(
final BSSWriterSequentialType writer,
final SMFAttribute attribute)
{
switch (attribute.componentCount()) {
case 1:
return serializeFloat1BE(writer, attribute);
case 2:
return serializeFloat2BE(writer, attribute);
case 3:
return serializeFloat3BE(writer, attribute);
case 4:
return serializeFloat4BE(writer, attribute);
default:
throw new UnreachableCodeException();
}
}
private static SMFSerializerDataAttributesValuesType serializeFloat1BE(
final BSSWriterSequentialType writer,
final SMFAttribute attribute)
{
switch (attribute.componentSizeBits()) {
case 16:
return new WriterBEFloat1_16(writer, attribute);
case 32:
return new WriterBEFloat1_32(writer, attribute);
case 64:
return new WriterBEFloat1_64(writer, attribute);
default:
throw new UnreachableCodeException();
}
}
private static SMFSerializerDataAttributesValuesType serializeFloat2BE(
final BSSWriterSequentialType writer,
final SMFAttribute attribute)
{
switch (attribute.componentSizeBits()) {
case 16:
return new WriterBEFloat2_16(writer, attribute);
case 32:
return new WriterBEFloat2_32(writer, attribute);
case 64:
return new WriterBEFloat2_64(writer, attribute);
default:
throw new UnreachableCodeException();
}
}
private static SMFSerializerDataAttributesValuesType serializeFloat3BE(
final BSSWriterSequentialType writer,
final SMFAttribute attribute)
{
switch (attribute.componentSizeBits()) {
case 16:
return new WriterBEFloat3_16(writer, attribute);
case 32:
return new WriterBEFloat3_32(writer, attribute);
case 64:
return new WriterBEFloat3_64(writer, attribute);
default:
throw new UnreachableCodeException();
}
}
private static SMFSerializerDataAttributesValuesType serializeFloat4BE(
final BSSWriterSequentialType writer,
final SMFAttribute attribute)
{
switch (attribute.componentSizeBits()) {
case 16:
return new WriterBEFloat4_16(writer, attribute);
case 32:
return new WriterBEFloat4_32(writer, attribute);
case 64:
return new WriterBEFloat4_64(writer, attribute);
default:
throw new UnreachableCodeException();
}
}
static SMFSerializerDataAttributesValuesType serializeSignedBE(
final BSSWriterSequentialType writer,
final SMFAttribute attribute)
{
switch (attribute.componentCount()) {
case 1:
return serializeSigned1BE(writer, attribute);
case 2:
return serializeSigned2BE(writer, attribute);
case 3:
return serializeSigned3BE(writer, attribute);
case 4:
return serializeSigned4BE(writer, attribute);
default:
throw new UnreachableCodeException();
}
}
private static SMFSerializerDataAttributesValuesType serializeSigned1BE(
final BSSWriterSequentialType writer,
final SMFAttribute attribute)
{
switch (attribute.componentSizeBits()) {
case 8:
return new Signed1_8(writer, attribute);
case 16:
return new WriterBESigned1_16(writer, attribute);
case 32:
return new WriterBESigned1_32(writer, attribute);
case 64:
return new WriterBESigned1_64(writer, attribute);
default:
throw new UnreachableCodeException();
}
}
private static SMFSerializerDataAttributesValuesType serializeSigned2BE(
final BSSWriterSequentialType writer,
final SMFAttribute attribute)
{
switch (attribute.componentSizeBits()) {
case 8:
return new Signed2_8(writer, attribute);
case 16:
return new WriterBESigned2_16(writer, attribute);
case 32:
return new WriterBESigned2_32(writer, attribute);
case 64:
return new WriterBESigned2_64(writer, attribute);
default:
throw new UnreachableCodeException();
}
}
private static SMFSerializerDataAttributesValuesType serializeSigned3BE(
final BSSWriterSequentialType writer,
final SMFAttribute attribute)
{
switch (attribute.componentSizeBits()) {
case 8:
return new Signed3_8(writer, attribute);
case 16:
return new WriterBESigned3_16(writer, attribute);
case 32:
return new WriterBESigned3_32(writer, attribute);
case 64:
return new WriterBESigned3_64(writer, attribute);
default:
throw new UnreachableCodeException();
}
}
private static SMFSerializerDataAttributesValuesType serializeSigned4BE(
final BSSWriterSequentialType writer,
final SMFAttribute attribute)
{
switch (attribute.componentSizeBits()) {
case 8:
return new Signed4_8(writer, attribute);
case 16:
return new WriterBESigned4_16(writer, attribute);
case 32:
return new WriterBESigned4_32(writer, attribute);
case 64:
return new WriterBESigned4_64(writer, attribute);
default:
throw new UnreachableCodeException();
}
}
static SMFSerializerDataAttributesValuesType serializeUnsignedBE(
final BSSWriterSequentialType writer,
final SMFAttribute attribute)
{
switch (attribute.componentCount()) {
case 1:
return serializeUnsigned1BE(writer, attribute);
case 2:
return serializeUnsigned2BE(writer, attribute);
case 3:
return serializeUnsigned3BE(writer, attribute);
case 4:
return serializeUnsigned4BE(writer, attribute);
default:
throw new UnreachableCodeException();
}
}
private static SMFSerializerDataAttributesValuesType serializeUnsigned1BE(
final BSSWriterSequentialType writer,
final SMFAttribute attribute)
{
switch (attribute.componentSizeBits()) {
case 8:
return new Unsigned1_8(writer, attribute);
case 16:
return new WriterBEUnsigned1_16(writer, attribute);
case 32:
return new WriterBEUnsigned1_32(writer, attribute);
case 64:
return new WriterBEUnsigned1_64(writer, attribute);
default:
throw new UnreachableCodeException();
}
}
private static SMFSerializerDataAttributesValuesType serializeUnsigned2BE(
final BSSWriterSequentialType writer,
final SMFAttribute attribute)
{
switch (attribute.componentSizeBits()) {
case 8:
return new Unsigned2_8(writer, attribute);
case 16:
return new WriterBEUnsigned2_16(writer, attribute);
case 32:
return new WriterBEUnsigned2_32(writer, attribute);
case 64:
return new WriterBEUnsigned2_64(writer, attribute);
default:
throw new UnreachableCodeException();
}
}
private static SMFSerializerDataAttributesValuesType serializeUnsigned3BE(
final BSSWriterSequentialType writer,
final SMFAttribute attribute)
{
switch (attribute.componentSizeBits()) {
case 8:
return new Unsigned3_8(writer, attribute);
case 16:
return new WriterBEUnsigned3_16(writer, attribute);
case 32:
return new WriterBEUnsigned3_32(writer, attribute);
case 64:
return new WriterBEUnsigned3_64(writer, attribute);
default:
throw new UnreachableCodeException();
}
}
private static SMFSerializerDataAttributesValuesType serializeUnsigned4BE(
final BSSWriterSequentialType writer,
final SMFAttribute attribute)
{
switch (attribute.componentSizeBits()) {
case 8:
return new Unsigned4_8(writer, attribute);
case 16:
return new WriterBEUnsigned4_16(writer, attribute);
case 32:
return new WriterBEUnsigned4_32(writer, attribute);
case 64:
return new WriterBEUnsigned4_64(writer, attribute);
default:
throw new UnreachableCodeException();
}
}
}
| 35.907738 | 76 | 0.737671 |
e5144aa88576992ced09aa44b3c798edac27fdf6 | 16,642 | /**
* Copyright 2013-2014 Linagora, Université Joseph Fourier
*
* 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 net.roboconf.iaas.azure;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.util.Map;
import java.util.logging.Logger;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import net.roboconf.core.agents.DataHelpers;
import net.roboconf.core.utils.Utils;
import net.roboconf.iaas.api.IaasException;
import net.roboconf.iaas.api.IaasInterface;
import net.roboconf.iaas.azure.internal.AzureConstants;
import net.roboconf.iaas.azure.internal.AzureProperties;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* @author Linh-Manh Pham - LIG
*/
public class IaasAzure implements IaasInterface {
private Logger logger;
private AzureProperties azureProperties;
/**
* Constructor.
*/
public IaasAzure() {
this.logger = Logger.getLogger( getClass().getName());
}
/**
* @param logger the logger to set
*/
public void setLogger( Logger logger ) {
this.logger = logger;
}
private KeyStore getKeyStore(String keyStoreName, String password) throws IOException {
KeyStore ks = null;
FileInputStream fis = null;
try {
ks = KeyStore.getInstance("JKS");
char[] passwordArray = password.toCharArray();
fis = new java.io.FileInputStream(keyStoreName);
ks.load(fis, passwordArray);
} catch (Exception e) {
this.logger.severe( e.getMessage() );
}
finally {
if (fis != null) {
Utils.closeQuietly( fis );
}
}
return ks;
}
private SSLSocketFactory getSSLSocketFactory( String keyStoreName, String password )
throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, IOException {
KeyStore ks = this.getKeyStore(keyStoreName, password);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(ks, password.toCharArray());
SSLContext context = SSLContext.getInstance("TLS");
context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
return context.getSocketFactory();
}
private String getStringFromInputStream( InputStream in ) {
String result = "";
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
Utils.copyStream( in, os );
result = os.toString( "UTF-8" );
} catch( IOException e ) {
this.logger.severe( e.getMessage());
this.logger.finest( Utils.writeException( e ));
}
return result;
}
private static boolean getExistResutlFromXML(String xmlStr, String nameOfNode)
throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
DocumentBuilder b;
b = f.newDocumentBuilder();
Document doc;
doc = b.parse(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));
NodeList nodes = doc.getElementsByTagName(nameOfNode);
String result = "false";
for (int i = 0; i < nodes.getLength(); i++) {
Element node = (Element) nodes.item(i);
result = node.getTextContent();
}
return Boolean.parseBoolean( result );
}
private String processGetRequest(URL url, String keyStore, String keyStorePassword)
throws UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, IOException {
SSLSocketFactory sslFactory = this.getSSLSocketFactory(keyStore, keyStorePassword);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(sslFactory);
con.setRequestMethod("GET");
con.addRequestProperty("x-ms-version", "2014-04-01");
InputStream responseStream = (InputStream) con.getContent();
try {
return getStringFromInputStream(responseStream);
} finally {
Utils.closeQuietly( responseStream );
}
}
private int processPostRequest(URL url, byte[] data, String contentType, String keyStore, String keyStorePassword)
throws UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, IOException {
SSLSocketFactory sslFactory = this.getSSLSocketFactory(keyStore, keyStorePassword);
HttpsURLConnection con = null;
con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(sslFactory);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.addRequestProperty("x-ms-version", "2014-04-01");
con.setRequestProperty("Content-Length", String.valueOf(data.length));
con.setRequestProperty("Content-Type", contentType);
DataOutputStream requestStream = new DataOutputStream (con.getOutputStream());
requestStream.write(data);
requestStream.flush();
requestStream.close();
return con.getResponseCode();
}
private int processDeleteRequest(URL url, String keyStore, String keyStorePassword)
throws UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, IOException {
SSLSocketFactory sslFactory = this.getSSLSocketFactory(keyStore, keyStorePassword);
HttpsURLConnection con = null;
con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(sslFactory);
con.setRequestMethod("DELETE");
con.addRequestProperty("x-ms-version", "2014-04-01");
return con.getResponseCode();
}
private byte[] convertFileToByte(String xmlFilePath) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
Utils.copyStream ( new File(xmlFilePath), os );
} catch (IOException e) {
this.logger.severe( e.getMessage());
}
return os.toByteArray();
}
private void replaceValueOfTagInXMLFile(String filePath, String tagName, String replacingValue)
throws ParserConfigurationException, SAXException, IOException {
File fXmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName(tagName);
Node nNode = nList.item(0);
nNode.setTextContent(replacingValue);
// write the modified content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer;
try {
transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filePath));
transformer.transform(source, result);
} catch (TransformerException e) {
this.logger.severe( e.getMessage() );
}
}
/*
* (non-Javadoc)
* @see net.roboconf.iaas.api.IaasInterface
* #setIaasProperties(java.util.Properties)
*/
@Override
public void setIaasProperties(Map<String, String> iaasProperties) throws IaasException {
// Quick check
String[] properties = {
AzureConstants.AZURE_SUBSCRIPTION_ID,
AzureConstants.AZURE_KEY_STORE_FILE,
AzureConstants.AZURE_KEY_STORE_PASSWORD,
AzureConstants.AZURE_CREATE_CLOUD_SERVICE_TEMPLATE,
AzureConstants.AZURE_CREATE_DEPLOYMENT_TEMPLATE,
AzureConstants.AZURE_LOCATION,
AzureConstants.AZURE_VM_SIZE,
AzureConstants.AZURE_VM_TEMPLATE
};
for( String property : properties ) {
if( StringUtils.isBlank( iaasProperties.get( property )))
throw new IaasException( "The value for " + property + " cannot be null or empty." );
}
// Create a bean
this.azureProperties = new AzureProperties();
String s = iaasProperties.get( AzureConstants.AZURE_SUBSCRIPTION_ID );
if( s != null )
this.azureProperties.setSubscriptionId( s.trim());
s = iaasProperties.get( AzureConstants.AZURE_KEY_STORE_FILE );
if( s != null )
this.azureProperties.setKeyStoreFile( s.trim());
s = iaasProperties.get( AzureConstants.AZURE_KEY_STORE_PASSWORD );
if( s != null )
this.azureProperties.setKeyStoreFile( s.trim());
s = iaasProperties.get( AzureConstants.AZURE_CREATE_CLOUD_SERVICE_TEMPLATE );
if( s != null )
this.azureProperties.setKeyStoreFile( s.trim());
s = iaasProperties.get( AzureConstants.AZURE_CREATE_DEPLOYMENT_TEMPLATE );
if( s != null )
this.azureProperties.setKeyStoreFile( s.trim());
s = iaasProperties.get( AzureConstants.AZURE_LOCATION );
if( s != null )
this.azureProperties.setKeyStoreFile( s.trim());
s = iaasProperties.get( AzureConstants.AZURE_VM_SIZE );
if( s != null )
this.azureProperties.setKeyStoreFile( s.trim());
s = iaasProperties.get( AzureConstants.AZURE_VM_TEMPLATE );
if( s != null )
this.azureProperties.setKeyStoreFile( s.trim());
}
/*
* (non-Javadoc)
* @see net.roboconf.iaas.api.IaasInterface
* #createVM(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public String createVM(
String messagingIp,
String messagingUsername,
String messagingPassword,
String rootInstanceName,
String applicationName )
throws IaasException {
String instanceId = null;
try {
// The following part enables to transmit data to the VM.
// When the VM is up, it will be able to read this data.
// TODO: Azure does not allow a VM name with spaces whereas graph configuration of Roboconf supports it. It conflicts.
// channelName = channelName.replaceAll("\\s+","-").toLowerCase();
String userData = DataHelpers.writeIaasDataAsString( messagingIp, messagingUsername, messagingPassword, applicationName, rootInstanceName );
String encodedUserData = new String( Base64.encodeBase64( userData.getBytes( "UTF-8" )), "UTF-8" );
replaceValueOfTagInXMLFile(this.azureProperties.getCreateCloudServiceTemplate(), "ServiceName", rootInstanceName );
replaceValueOfTagInXMLFile(this.azureProperties.getCreateCloudServiceTemplate(), "Location", this.azureProperties.getLocation() );
replaceValueOfTagInXMLFile(this.azureProperties.getCreateDeploymentTemplate(), "CustomData", encodedUserData );
replaceValueOfTagInXMLFile(this.azureProperties.getCreateDeploymentTemplate(), "Name", rootInstanceName );
replaceValueOfTagInXMLFile(this.azureProperties.getCreateDeploymentTemplate(), "HostName", rootInstanceName );
replaceValueOfTagInXMLFile(this.azureProperties.getCreateDeploymentTemplate(), "RoleName", rootInstanceName );
replaceValueOfTagInXMLFile(this.azureProperties.getCreateDeploymentTemplate(), "RoleSize", this.azureProperties.getVMSize() );
replaceValueOfTagInXMLFile(this.azureProperties.getCreateDeploymentTemplate(), "SourceImageName", this.azureProperties.getVMTemplate() );
// Let send the request to Azure API to create a Cloud Service and a Deployment (a PersistentVMRole)
String baseURL = String.format("https://management.core.windows.net/%s/services", this.azureProperties.getSubscriptionId());
String requestHeaderContentType = "application/xml";
byte[] requestBodyCreateCloudService = convertFileToByte(this.azureProperties.getCreateCloudServiceTemplate());
byte[] requestBodyCreateDeployment = convertFileToByte(this.azureProperties.getCreateDeploymentTemplate());
String checkCloudServiceURL = baseURL+"/hostedservices/operations/isavailable/"+rootInstanceName;
String createCloudServiceURL = baseURL+"/hostedservices";
String createDeploymentURL = baseURL+"/hostedservices/"+rootInstanceName+"/deployments";
// check if Cloud Service exist
String responseCheckCloudService = processGetRequest(new URL(checkCloudServiceURL), this.azureProperties.getKeyStoreFile(), this.azureProperties.getKeyStorePassword());
boolean checkResult = getExistResutlFromXML(responseCheckCloudService, "Result"); // true means the name still available
this.logger.info( "Response Result: Cloud Service Name is still available: " + checkResult);
// create Cloud Service, Deployment & Add a Role (Linux VM), maybe add a second Role (another Linux VM)
int rescodeCreateCloudService = -1;
if (checkResult) {
rescodeCreateCloudService = processPostRequest(
new URL(createCloudServiceURL),
requestBodyCreateCloudService,
requestHeaderContentType,
this.azureProperties.getKeyStoreFile(),
this.azureProperties.getKeyStorePassword()); // rescode shoud be 201
}
this.logger.info( "Create Cloud Service: Response Code: " + rescodeCreateCloudService);
this.logger.info( "Creating Azure VM in progress: " + rootInstanceName);
if (rescodeCreateCloudService == 201) {
int rescodeCreateDeployment = processPostRequest(
new URL(createDeploymentURL),
requestBodyCreateDeployment,
requestHeaderContentType,
this.azureProperties.getKeyStoreFile(),
this.azureProperties.getKeyStorePassword()); // rescode shoud be 202
this.logger.info( "Create VM: Response Code: " + rescodeCreateDeployment);
}
instanceId = rootInstanceName; // instanceID in this context should be rootInstanceName
} catch( UnsupportedEncodingException e ) {
throw new IaasException( e );
} catch( ParserConfigurationException e ) {
throw new IaasException( e );
} catch( SAXException e ) {
throw new IaasException( e );
} catch( IOException e ) {
throw new IaasException( e );
} catch( UnrecoverableKeyException e ) {
throw new IaasException( e );
} catch( KeyManagementException e ) {
throw new IaasException( e );
} catch( KeyStoreException e ) {
throw new IaasException( e );
} catch( NoSuchAlgorithmException e ) {
throw new IaasException( e );
}
return instanceId;
}
/*
* (non-Javadoc)
* @see net.roboconf.iaas.api.IaasInterface
* #terminateVM(java.lang.String)
* instanceID is CloudServiceName
*/
@Override
public void terminateVM( String instanceId ) throws IaasException {
try {
String baseURL = String.format("https://management.core.windows.net/%s/services", this.azureProperties.getSubscriptionId());
String deleteCloudServiceURL = baseURL+"/hostedservices/"+instanceId+"?comp=media";
// Delete Cloud Service, and also delete all the related things
int rescodeDeleteCloudService = processDeleteRequest(
new URL(deleteCloudServiceURL),
this.azureProperties.getKeyStoreFile(),
this.azureProperties.getKeyStorePassword()); // rescode shoud be 202
this.logger.info("Response Code: Delete VM: " + rescodeDeleteCloudService);
} catch( UnrecoverableKeyException e ) {
throw new IaasException( e );
} catch( KeyManagementException e ) {
throw new IaasException( e );
} catch( KeyStoreException e ) {
throw new IaasException( e );
} catch( NoSuchAlgorithmException e ) {
throw new IaasException( e );
} catch( MalformedURLException e ) {
throw new IaasException( e );
} catch( IOException e ) {
throw new IaasException( e );
}
}
}
| 36.178261 | 171 | 0.748528 |
e0aec60e18023fa72dcc34390ca864149bdb66f6 | 5,419 | 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|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|plan
operator|.
name|mapper
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Optional
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|exec
operator|.
name|Operator
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|optimizer
operator|.
name|signature
operator|.
name|OpTreeSignature
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|optimizer
operator|.
name|signature
operator|.
name|RelTreeSignature
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|ql
operator|.
name|stats
operator|.
name|OperatorStats
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|cache
operator|.
name|Cache
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|cache
operator|.
name|CacheBuilder
import|;
end_import
begin_class
specifier|public
class|class
name|CachingStatsSource
implements|implements
name|StatsSource
block|{
specifier|private
specifier|final
name|Cache
argument_list|<
name|Object
argument_list|,
name|OperatorStats
argument_list|>
name|cache
decl_stmt|;
specifier|public
name|CachingStatsSource
parameter_list|(
name|int
name|cacheSize
parameter_list|)
block|{
name|cache
operator|=
name|CacheBuilder
operator|.
name|newBuilder
argument_list|()
operator|.
name|maximumSize
argument_list|(
name|cacheSize
argument_list|)
operator|.
name|build
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Override
specifier|public
name|Optional
argument_list|<
name|OperatorStats
argument_list|>
name|lookup
parameter_list|(
name|OpTreeSignature
name|treeSig
parameter_list|)
block|{
return|return
name|Optional
operator|.
name|ofNullable
argument_list|(
name|cache
operator|.
name|getIfPresent
argument_list|(
name|treeSig
argument_list|)
argument_list|)
return|;
block|}
annotation|@
name|Override
specifier|public
name|Optional
argument_list|<
name|OperatorStats
argument_list|>
name|lookup
parameter_list|(
name|RelTreeSignature
name|treeSig
parameter_list|)
block|{
return|return
name|Optional
operator|.
name|ofNullable
argument_list|(
name|cache
operator|.
name|getIfPresent
argument_list|(
name|treeSig
argument_list|)
argument_list|)
return|;
block|}
annotation|@
name|Override
specifier|public
name|boolean
name|canProvideStatsFor
parameter_list|(
name|Class
argument_list|<
name|?
argument_list|>
name|clazz
parameter_list|)
block|{
if|if
condition|(
name|cache
operator|.
name|size
argument_list|()
operator|>
literal|0
operator|&&
name|Operator
operator|.
name|class
operator|.
name|isAssignableFrom
argument_list|(
name|clazz
argument_list|)
condition|)
block|{
return|return
literal|true
return|;
block|}
return|return
literal|false
return|;
block|}
specifier|private
name|void
name|put
parameter_list|(
name|OpTreeSignature
name|sig
parameter_list|,
name|OperatorStats
name|opStat
parameter_list|)
block|{
name|cache
operator|.
name|put
argument_list|(
name|sig
argument_list|,
name|opStat
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
specifier|public
name|void
name|load
parameter_list|(
name|List
argument_list|<
name|PersistedRuntimeStats
argument_list|>
name|statMap
parameter_list|)
block|{
for|for
control|(
name|PersistedRuntimeStats
name|entry
range|:
name|statMap
control|)
block|{
if|if
condition|(
name|entry
operator|.
name|rSig
operator|!=
literal|null
condition|)
block|{
name|cache
operator|.
name|put
argument_list|(
name|entry
operator|.
name|rSig
argument_list|,
name|entry
operator|.
name|stat
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|entry
operator|.
name|sig
operator|!=
literal|null
condition|)
block|{
name|cache
operator|.
name|put
argument_list|(
name|entry
operator|.
name|sig
argument_list|,
name|entry
operator|.
name|stat
argument_list|)
expr_stmt|;
block|}
block|}
block|}
block|}
end_class
end_unit
| 14.374005 | 813 | 0.796826 |
96931257a724b986debfdac90ca4e7dc3b5d8a64 | 662 | package farmerthanos.mea;
import arc.Events;
import arc.util.Log;
import farmerthanos.mea.calls.BaseUnderAttack;
import farmerthanos.mea.calls.CoreUnderAttack;
import mindustry.Vars;
import mindustry.game.EventType;
import mindustry.mod.Mod;
public class MEA extends Mod{
public MEA() {
if(Vars.headless) {
Events.on(EventType.FileTreeInitEvent.class, e -> {
Announcements.load();
});
} else {
Announcements.load();
}
}
@Override
public void init(){
new BaseUnderAttack().load();
new CoreUnderAttack().load();
Log.info("MEA online");
}
}
| 22.066667 | 63 | 0.619335 |
af2299e0e340bfbc29c756f4e2de058841a75fb9 | 760 | public class Product
{
private final String productCode;
private int quantityInStock;
/** @return the code of this product
*/
public String getProductCode()
{
return productCode;
}
/** @return the current quantity in stock of this product. This should never be negative.
*/
public int getQuant()
{
return quantityInStock;
}
/** Sets the current quantity in stock of this product to the parameter value
*/
public void setQuant(int quantity)
{
quantityInStock = quantity;
}
/* CLASS MEMBERS FOR TESTING */
/* DO NOT MODIFY ANY OF THE CONSTRUCTORS OR METHODS BELOW */
public Product(String det)
{
productCode = det.split("/")[0];
quantityInStock = Integer.parseInt(det.split("/")[1]);
}
}
| 20 | 91 | 0.669737 |
0bf3e6dfc6bfef798faa092fd809eb1d81049071 | 738 | // Generated by Dagger (https://dagger.dev).
package com.stripe.android.core.networking;
import dagger.internal.DaggerGenerated;
import dagger.internal.Factory;
@DaggerGenerated
@SuppressWarnings({
"unchecked",
"rawtypes"
})
public final class RetryDelaySupplier_Factory implements Factory<RetryDelaySupplier> {
@Override
public RetryDelaySupplier get() {
return newInstance();
}
public static RetryDelaySupplier_Factory create() {
return InstanceHolder.INSTANCE;
}
public static RetryDelaySupplier newInstance() {
return new RetryDelaySupplier();
}
private static final class InstanceHolder {
private static final RetryDelaySupplier_Factory INSTANCE = new RetryDelaySupplier_Factory();
}
}
| 24.6 | 96 | 0.765583 |
42aba00e4eb1568d371e5a633ce7cdcab1e53537 | 7,435 | package org.jzy3d.maths;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Utils {
/**
* Convert a number into a string, with <code>precision</code> number of meaningfull digits.
*
* 'd' integral The result is formatted as a decimal integer 'o' integral The result is formatted
* as an octal integer 'x', 'X' integral The result is formatted as a hexadecimal integer 'e', 'E'
* floating point The result is formatted as a decimal number in computerized scientific notation
* 'f' floating point The result is formatted as a decimal number 'g', 'G' floating point The
* result is formatted using computerized scientific notation or decimal format, depending on the
* precision and the value after rounding.
*
* @see http ://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax
* @see String.format
*/
public static String num2str(char parseMode, double num, int precision) {
return String.format("%." + precision + parseMode, new Double(num));
}
/**
* Same as {@link num2str(char parseMode, double num, int precision)} but does not query
* precision.
*/
public static String num2str(char parseMode, double num) {
return String.format("%" + parseMode, new Double(num));
}
public static String num2str(double num, int precision) {
return num2str('g', num, precision);
}
/** Convert a number into a string. */
public static String num2str(double num) {
return Double.toString(num);
}
/*************************************************************/
/** Convert a date to the format "dd/MM/yyyy HH:mm:ss". */
public static String dat2str(Date date) {
return dat2str(date, "dd/MM/yyyy HH:mm:ss");
}
/**
* Some example format dd.MM.yy 09.04.98 yyyy.MM.dd G 'at' hh:mm:ss z 1998.04.09 AD at 06:15:55
* PDT EEE, MMM d, ''yy Thu, Apr 9, '98 h:mm a 6:15 PM H:mm 18:15 H:mm:ss:SSS 18:15:55:624 K:mm
* a,z 6:15 PM,PDT yyyy.MMMMM.dd GGG hh:mm aaa 1998.April.09 AD 06:15 PM
*
* @see http ://java.sun.com/docs/books/tutorial/i18n/format/simpleDateFormat. html
* @param date
* @param format
* @return
*/
public static String dat2str(Date date, String format) {
if (date == null)
return "";
SimpleDateFormat formatter;
formatter = new SimpleDateFormat(format, Locale.getDefault());
return formatter.format(date);
}
/*************************************************************/
public static long dat2num(Date date) {
if (date == null)
return 0;
return date.getTime();
}
public static Date num2dat(long value) {
return new Date(value);
}
public static String time2str(long milli) {
StringBuilder buf = new StringBuilder(20);
String sgn = "";
if (milli < 0) {
sgn = "-";
milli = Math.abs(milli);
}
append(buf, sgn, 0, (milli / 3600000));
append(buf, ":", 2, ((milli % 3600000) / 60000));
append(buf, ":", 2, ((milli % 60000) / 1000));
append(buf, ".", 3, (milli % 1000));
return buf.toString();
}
/**
* Append a right-aligned and zero-padded numeric value to a `StringBuilder`.
*/
private static void append(StringBuilder tgt, String pfx, int dgt, long val) {
tgt.append(pfx);
if (dgt > 1) {
int pad = (dgt - 1);
for (long xa = val; xa > 9 && pad > 0; xa /= 10) {
pad--;
}
for (int xa = 0; xa < pad; xa++) {
tgt.append('0');
}
}
tgt.append(val);
}
public static String blanks(int length) {
String b = "";
for (int i = 0; i < length; i++)
b += " ";
return b;
}
/*****************************************************************************/
/**
* Computes the absolute values of an array of doubles.
*
* @param values
* @return the sum of input values
*/
public static double[] abs(double[] values) {
double[] output = new double[values.length];
for (int i = 0; i < values.length; i++)
output[i] = Math.abs(values[i]);
return output;
}
/**
* Computes the sum of an array of doubles. NaN values are ignored during the computation.
*
* @param values
* @return the sum of input values
*/
public static double sum(double[] values) {
if (values.length == 0)
throw new IllegalArgumentException("Input array must have a length greater than 0");
double total = 0;
for (int i = 0; i < values.length; i++)
if (!Double.isNaN(values[i]))
total += values[i];
return total;
}
/**
* Computes the sum of an array of doubles. NaN values are ignored during the computation.
*
* @param values
* @return the sum of input values
*/
public static int sum(int[] values) {
if (values.length == 0)
throw new IllegalArgumentException("Input array must have a length greater than 0");
int total = 0;
for (int i = 0; i < values.length; i++)
total += values[i];
return total;
}
/**
* Generate a vector containing regular increasing values from min to max, with an offset of
* nstep.
*
* @param min
* @param max
* @param nstep
* @return
*/
public static double[] vector(double min, double max, int nstep) {
double step = (max - min) / (nstep - 1);
double[] grid = new double[nstep];
for (int i = 0; i < grid.length; i++) {
grid[i] = min + i * step;
}
return grid;
}
/**
* Generate a vector containing regular increasing values from min to max, with an offset 1.
*
* @param min
* @param max
* @return
*/
public static double[] vector(double min, double max) {
return vector(min, max, (int) Math.abs(max - min) + 1);
}
/**
* Generate a vector containing regular increasing values from min to max, with an offset of
* nstep.
*
* @param min
* @param max
* @param nstep
* @return
*/
public static int[] vector(int min, int max, int nstep) {
int step = (max - min) / (nstep - 1);
int[] grid = new int[nstep];
for (int i = 0; i < grid.length; i++) {
grid[i] = min + i * step;
}
return grid;
}
/**
* Generate a vector containing regular increasing values from min to max, with an offset 1.
*
* @param min
* @param max
* @return
*/
public static int[] vector(int min, int max) {
return vector(min, max, Math.abs(max - min) + 1);
}
/**
* Return the minimal date of an array
*
* @param dates
* @return
*/
public static Date min(Date[] dates) {
if (dates.length == 0)
throw new RuntimeException("input array is empty");
Date min = new Date(Long.MAX_VALUE);
for (int i = 0; i < dates.length; i++)
if (min.after(dates[i]))
min = dates[i];
return min;
}
/**
* Return the maximal date of an array
*
* @param dates
* @return
*/
public static Date max(Date[] dates) {
if (dates.length == 0)
throw new RuntimeException("input array is empty");
Date max = new Date(-Long.MAX_VALUE);
for (int i = 0; i < dates.length; i++)
if (max.before(dates[i]))
max = dates[i];
return max;
}
public static Date str2date(String string) throws ParseException {
DateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
Date date = format.parse(string);
return date;
}
}
| 27.435424 | 100 | 0.594217 |
4a0fb83c750c23304ad95df5153b5e39dee95629 | 337 | package org.nekostudio;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
*
*
* @author neko
*/
@SpringBootApplication
public class WechatApp
{
public static void main( String[] args )
{
SpringApplication.run(WechatApp.class, args);
}
}
| 17.736842 | 68 | 0.72997 |
63b074a04598501338be6830cb44271de88bb6ab | 385 |
package com.imt.service.dto;
import lombok.Data;
import java.sql.Timestamp;
import java.util.List;
import com.imt.annotation.Query;
@Data
public class LocalStorageQueryCriteria{
@Query(blurry = "name,suffix,type,createBy,size")
private String blurry;
@Query
private String createBy;
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> createTime;
} | 18.333333 | 53 | 0.735065 |
065e963111c86c2e635b9d3c3d3ad44cba021c21 | 4,818 | package net.jbock.convert.matching;
import com.squareup.javapoet.CodeBlock;
import net.jbock.Converter;
import net.jbock.common.Util;
import net.jbock.convert.Mapped;
import net.jbock.convert.ParameterScope;
import net.jbock.convert.matcher.Matcher;
import net.jbock.convert.reference.ReferenceTool;
import net.jbock.convert.reference.StringConverterType;
import net.jbock.either.Either;
import net.jbock.parameter.AbstractItem;
import net.jbock.parameter.SourceMethod;
import net.jbock.processor.SourceElement;
import net.jbock.validate.ParameterStyle;
import javax.inject.Inject;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Types;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import static javax.lang.model.element.Modifier.ABSTRACT;
import static net.jbock.either.Either.left;
@ParameterScope
public class ConverterValidator extends MatchValidator {
private final List<Matcher> matchers;
private final ReferenceTool referenceTool;
private final Util util;
private final SourceMethod sourceMethod;
private final SourceElement sourceElement;
private final Types types;
@Inject
ConverterValidator(
List<Matcher> matchers,
ReferenceTool referenceTool,
Util util,
SourceMethod sourceMethod,
SourceElement sourceElement,
ParameterStyle parameterStyle,
Types types) {
super(parameterStyle);
this.matchers = matchers;
this.referenceTool = referenceTool;
this.util = util;
this.sourceMethod = sourceMethod;
this.sourceElement = sourceElement;
this.types = types;
}
public <P extends AbstractItem> Either<String, Mapped<P>> validate(
P parameter,
TypeElement converter) {
Optional<String> maybeFailure = util.commonTypeChecks(converter)
.or(() -> checkNotAbstract(converter))
.or(() -> checkNoTypevars(converter))
.or(() -> checkConverterAnnotationPresent(converter));
return Either.unbalancedLeft(maybeFailure)
.flatMap(() -> referenceTool.getReferencedType(converter))
.flatMap(functionType -> tryAllMatchers(functionType, parameter, converter));
}
private <P extends AbstractItem> Either<String, Mapped<P>> tryAllMatchers(
StringConverterType functionType,
P parameter,
TypeElement converter) {
List<Match> matches = new ArrayList<>();
for (Matcher matcher : matchers) {
Optional<Match> match = matcher.tryMatch(parameter);
match.ifPresent(matches::add);
match = match.filter(m -> isValidMatch(m, functionType));
if (match.isPresent()) {
Match m = match.get();
return Either.unbalancedLeft(validateMatch(m))
.orElseRight(() -> CodeBlock.builder()
.add(".map(")
.add(getMapExpr(functionType, converter))
.add(")").build())
.map(mapExpr -> m.toConvertedParameter(mapExpr, parameter));
}
}
TypeMirror typeForErrorMessage = matches.stream()
.max(Comparator.comparing(Match::skew))
.map(Match::baseType)
.orElse(sourceMethod.returnType());
return left(noMatchError(typeForErrorMessage));
}
private Optional<String> checkConverterAnnotationPresent(TypeElement converter) {
Converter converterAnnotation = converter.getAnnotation(Converter.class);
boolean nestedMapper = util.getEnclosingElements(converter).contains(sourceElement.element());
if (converterAnnotation == null && !nestedMapper) {
return Optional.of("converter must be an inner class of the command class, or carry the @"
+ Converter.class.getSimpleName() + " annotation");
}
return Optional.empty();
}
private Optional<String> checkNotAbstract(TypeElement converter) {
if (converter.getModifiers().contains(ABSTRACT)) {
return Optional.of("converter class may not be abstract");
}
return Optional.empty();
}
private Optional<String> checkNoTypevars(TypeElement converter) {
if (!converter.getTypeParameters().isEmpty()) {
return Optional.of("type parameters are not allowed in converter class declaration");
}
return Optional.empty();
}
private CodeBlock getMapExpr(StringConverterType functionType, TypeElement converter) {
if (functionType.isSupplier()) {
return CodeBlock.of("new $T().get()", converter.asType());
}
return CodeBlock.of("new $T()", converter.asType());
}
private boolean isValidMatch(Match match, StringConverterType functionType) {
return types.isSameType(functionType.outputType(), match.baseType());
}
private String noMatchError(TypeMirror type) {
return "converter should extend StringConverter<" + util.typeToString(type) + ">";
}
}
| 35.688889 | 98 | 0.718763 |
ded9b23ab4e75eed97f59fa76b34fe1505f9ac46 | 109 | package com.pessetto.imap;
public enum IMAPState {
NOT_AUTHENTICATED,
AUTHENTICATED,
SELECTED,
LOGOUT
}
| 12.111111 | 26 | 0.779817 |
514302fcb58b27adaf688dd3f65ba4913830aaf0 | 2,415 | /*
* The FML Forge Mod Loader suite.
* Copyright (C) 2012 cpw
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package cpw.mods.fml.client;
import java.awt.Dimension;
import java.util.List;
import java.util.logging.Logger;
import cpw.mods.fml.common.FMLCommonHandler;
import net.minecraft.src.RenderEngine;
import net.minecraft.src.TextureFX;
import net.minecraft.src.TexturePackBase;
public class FMLTextureFX extends TextureFX implements ITextureFX
{
public int tileSizeBase = 16;
public int tileSizeSquare = 256;
public int tileSizeMask = 15;
public int tileSizeSquareMask = 255;
public boolean errored = false;
protected Logger log = FMLCommonHandler.instance().getFMLLogger();
public FMLTextureFX(int icon)
{
super(icon);
}
@Override public void setErrored(boolean err){ errored = err; }
@Override public boolean getErrored(){ return errored; }
@Override
public void onTexturePackChanged(RenderEngine engine, TexturePackBase texturepack, Dimension dimensions)
{
onTextureDimensionsUpdate(dimensions.width, dimensions.height);
}
@Override
public void onTextureDimensionsUpdate(int width, int height)
{
tileSizeBase = width >> 4;
tileSizeSquare = tileSizeBase * tileSizeBase;
tileSizeMask = tileSizeBase - 1;
tileSizeSquareMask = tileSizeSquare - 1;
setErrored(false);
setup();
}
protected void setup()
{
field_1127_a = new byte[tileSizeSquare << 2];
}
public boolean unregister(RenderEngine engine, List<TextureFX> effects)
{
effects.remove(this);
return true;
}
}
| 34.5 | 161 | 0.693996 |
e0b88f1b1572dec3b6a5b1265695e477f7504f2e | 5,633 | package io.practiceinsight.pinpayments.pojo;
import com.google.gson.*;
import com.google.gson.reflect.*;
import com.google.gson.stream.*;
import java.io.IOException;
import javax.annotation.Generated;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
/**
* A {@code TypeAdapterFactory} that handles all of the immutable types generated under {@code BankAccountResult}.
* @see ImmutableBankAccountResult
*/
@SuppressWarnings("all")
@Generated({"Gsons.generator", "io.practiceinsight.pinpayments.pojo.BankAccountResult"})
@ParametersAreNonnullByDefault
public final class GsonAdaptersBankAccountResult implements TypeAdapterFactory {
@SuppressWarnings({"unchecked", "raw"}) // safe unchecked, types are verified in runtime
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (BankAccountResultTypeAdapter.adapts(type)) {
return (TypeAdapter<T>) new BankAccountResultTypeAdapter(gson);
}
return null;
}
@Override
public String toString() {
return "GsonAdaptersBankAccountResult(BankAccountResult)";
}
@SuppressWarnings({"unchecked", "raw"}) // safe unchecked, types are verified in runtime
private static class BankAccountResultTypeAdapter extends TypeAdapter<BankAccountResult> {
final String tokenName;
final String bankNameName;
final String nameName;
final String bsbName;
final String numberName;
static class BankAccountResultNamingFields {
public String token;
public String bankName;
public String name;
public String bsb;
public String number;
}
BankAccountResultTypeAdapter(Gson gson) {
this.tokenName = translateName(gson, BankAccountResultNamingFields.class, "token");
this.bankNameName = "bank_name";
this.nameName = translateName(gson, BankAccountResultNamingFields.class, "name");
this.bsbName = translateName(gson, BankAccountResultNamingFields.class, "bsb");
this.numberName = translateName(gson, BankAccountResultNamingFields.class, "number");
}
static boolean adapts(TypeToken<?> type) {
return BankAccountResult.class == type.getRawType()
|| ImmutableBankAccountResult.class == type.getRawType();
}
@Override
public void write(JsonWriter out, BankAccountResult value) throws IOException {
if (value == null) {
out.nullValue();
} else {
writeBankAccountResult(out, value);
}
}
@Override
public BankAccountResult read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
return readBankAccountResult(in);
}
private void writeBankAccountResult(JsonWriter out, BankAccountResult instance)
throws IOException {
out.beginObject();
out.name(tokenName);
out.value(instance.token());
@Nullable String bankNameValue = instance.bankName();
if (bankNameValue != null) {
out.name(bankNameName);
out.value(bankNameValue);
} else if (out.getSerializeNulls()) {
out.name(bankNameName);
out.nullValue();
}
out.name(nameName);
out.value(instance.name());
out.name(bsbName);
out.value(instance.bsb());
out.name(numberName);
out.value(instance.number());
out.endObject();
}
private BankAccountResult readBankAccountResult(JsonReader in)
throws IOException {
ImmutableBankAccountResult.Builder builder = ImmutableBankAccountResult.builder();
in.beginObject();
while (in.hasNext()) {
eachAttribute(in, builder);
}
in.endObject();
return builder.build();
}
private void eachAttribute(JsonReader in, ImmutableBankAccountResult.Builder builder)
throws IOException {
String attributeName = in.nextName();
if (tokenName.equals(attributeName)) {
readInToken(in, builder);
return;
}
if (bankNameName.equals(attributeName)) {
readInBankName(in, builder);
return;
}
if (nameName.equals(attributeName)) {
readInName(in, builder);
return;
}
if (bsbName.equals(attributeName)) {
readInBsb(in, builder);
return;
}
if (numberName.equals(attributeName)) {
readInNumber(in, builder);
return;
}
in.skipValue();
}
private void readInToken(JsonReader in, ImmutableBankAccountResult.Builder builder)
throws IOException {
builder.token(in.nextString());
}
private void readInBankName(JsonReader in, ImmutableBankAccountResult.Builder builder)
throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
} else {
builder.bankName(in.nextString());
}
}
private void readInName(JsonReader in, ImmutableBankAccountResult.Builder builder)
throws IOException {
builder.name(in.nextString());
}
private void readInBsb(JsonReader in, ImmutableBankAccountResult.Builder builder)
throws IOException {
builder.bsb(in.nextString());
}
private void readInNumber(JsonReader in, ImmutableBankAccountResult.Builder builder)
throws IOException {
builder.number(in.nextString());
}
}
private static String translateName(Gson gson, Class<?> sampleClass, String fieldName) {
try {
return gson.fieldNamingStrategy().translateName(sampleClass.getField(fieldName));
} catch (NoSuchFieldException noSuchField) {
throw new AssertionError(noSuchField);
}
}
}
| 31.824859 | 114 | 0.680277 |
99fbd51a010b4ccaa688de1276dc14a703ecee9e | 5,169 | package com.lizy.retrofit;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import okhttp3.ResponseBody;
import okio.Buffer;
/**
* Created by lizy on 16-8-26.
*/
public class Utils {
private Utils() {
// No instance
}
static Class<?> getRawType(Type type) {
if (type == null) throw new NullPointerException("type == null");
if (type instanceof Class<?>) {
return (Class<?>)type;
}
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)type;
Type rawType = parameterizedType.getRawType();
if (!(rawType instanceof Class)) throw new IllegalArgumentException();
return (Class<?>)rawType;
}
if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType)type).getGenericComponentType();
return Array.newInstance(getRawType(componentType), 0).getClass();
}
if (type instanceof TypeVariable) {
return Object.class;
}
if (type instanceof WildcardType) {
return getRawType((((WildcardType) type).getUpperBounds()[0]));
}
throw new IllegalArgumentException("Excepted a Class, ParameterizedType, or "
+ "GeneracArrayType, but <" + type + "> is of type " + type.getClass().getName());
}
static Type getGenericSupertype(Type context, Class<?> rawType, Class<?> toResolve) {
if (toResolve == rawType) return context;
if (toResolve.isInterface()) {
Class<?>[] interfaces = rawType.getInterfaces();
for (int i = 0, length = interfaces.length; i < length; i++) {
if (interfaces[i] == toResolve) {
return rawType.getGenericInterfaces()[i];
} else if (toResolve.isAssignableFrom(interfaces[i])) {
return getGenericSupertype(rawType.getGenericInterfaces()[i], interfaces[i], toResolve);
}
}
}
if (!rawType.isInterface()) {
while (rawType != Object.class) {
Class<?> rawSupertype = rawType.getSuperclass();
if (rawSupertype == toResolve) {
return rawType.getGenericSuperclass();
} else if (toResolve.isAssignableFrom(rawSupertype)) {
return getGenericSupertype(rawType.getGenericSuperclass(), rawSupertype, toResolve);
}
rawType = rawSupertype;
}
}
return toResolve;
}
static Type getParameterUpperBound(int index, ParameterizedType type) {
Type[] types = type.getActualTypeArguments();
if (index < 0 || index >= types.length) {
throw new IllegalArgumentException("Index " + index + " not in range [0,"
+ types.length + ") for " + type);
}
Type paramType = types[index];
if (paramType instanceof WildcardType) {
return ((WildcardType)paramType).getUpperBounds()[0];
}
return paramType;
}
static Type getCallResponseType(Type returnType) {
if (!(returnType instanceof ParameterizedType)) {
throw new IllegalArgumentException(
"Call return type must be parameterized as Call<Foo> or Call<? extends Foo>");
}
return getParameterUpperBound(0, (ParameterizedType)returnType);
}
public static boolean hasUnresolvableType(Type type) {
if (type instanceof Class<?>) {
return false;
}
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)type;
for (Type typeArgument : parameterizedType.getActualTypeArguments()) {
if (hasUnresolvableType(typeArgument)) {
return true;
}
}
return false;
}
if (type instanceof GenericArrayType) {
return hasUnresolvableType(((GenericArrayType) type).getGenericComponentType());
}
if (type instanceof TypeVariable) {
return true;
}
if (type instanceof WildcardType) {
return true;
}
String className = type == null ? "null" : type.getClass().getName();
throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
+ "GenericArrayType, but <" + type + "> is of type " + className);
}
static <T> T checkNotNull(T object, String message) {
if (object == null) {
throw new NullPointerException(message);
}
return object;
}
static ResponseBody buffer(ResponseBody body) throws IOException {
Buffer buffer = new Buffer();
body.source().readAll(buffer);
return ResponseBody.create(body.contentType(), body.contentLength(), buffer);
}
}
| 36.401408 | 108 | 0.595086 |
073ff8a785d804e75f9425b131928a0f7d41704a | 2,400 | package com.github.lunatrius.ingameinfo.value;
import com.github.lunatrius.ingameinfo.value.registry.ValueRegistry;
public abstract class ValueSimple extends Value {
@Override
public Value setRawValue(String value, boolean isText) {
this.value = value.replaceAll("\\$(?=[0-9a-fk-or])", "\u00a7");
if (isText) {
this.value = this.value.replaceAll("\\\\([<>\\[/\\]\\\\])", "$1");
}
return this;
}
@Override
public String getRawValue(boolean isText) {
String str = this.value.replace("\u00a7", "$");
if (isText) {
str = str.replaceAll("([<>\\[/\\]\\\\])", "\\\\$1");
}
return str;
}
@Override
public boolean isSimple() {
return true;
}
@Override
public boolean isValidSize() {
return this.values.size() == 0;
}
public static class ValueString extends ValueSimple {
@Override
public String getType() {
if (this.value.matches("^-?\\d+(\\.\\d+)?$")) {
return ValueRegistry.INSTANCE.forClass(ValueNumber.class);
}
return super.getType();
}
@Override
public String getValue() {
return this.value;
}
}
public static class ValueNumber extends ValueSimple {
@Override
public String getValue() {
return this.value;
}
}
public static class ValueVariable extends ValueSimple {
@Override
public String getValue() {
return getVariableValue(this.value);
}
}
public static class ValueInvalid extends ValueComplex {
@Override
public boolean isValidSize() {
return true;
}
@Override
public String getValue() {
return "";
}
@Override
public boolean isValid() {
return false;
}
}
public static void register() {
ValueRegistry.INSTANCE.register(new ValueString().setName("str").setAliases("string"));
ValueRegistry.INSTANCE.register(new ValueNumber().setName("num").setAliases("number", "int", "integer", "float", "double"));
ValueRegistry.INSTANCE.register(new ValueVariable().setName("var").setAliases("variable"));
ValueRegistry.INSTANCE.register(new ValueInvalid().setName("invalid"));
}
}
| 27.586207 | 132 | 0.565417 |
616c7442a13c58f8f39d09e44d7074debb4cbbed | 15,352 | /*
* The Gemma project
*
* Copyright (c) 2010 University of British Columbia
*
* 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 ubic.gemma.core.analysis.expression.coexpression.links;
import org.apache.commons.dbcp2.BasicDataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import ubic.gemma.core.analysis.expression.coexpression.links.LinkAnalysisConfig.SingularThreshold;
import ubic.gemma.core.analysis.preprocess.filter.FilterConfig;
import ubic.gemma.core.genome.gene.service.GeneService;
import ubic.gemma.core.util.test.BaseSpringContextTest;
import ubic.gemma.core.util.test.category.SlowTest;
import ubic.gemma.model.analysis.expression.coexpression.CoexpressionAnalysis;
import ubic.gemma.model.association.coexpression.GeneCoexpressionNodeDegreeValueObject;
import ubic.gemma.model.expression.bioAssayData.RawExpressionDataVector;
import ubic.gemma.model.expression.designElement.CompositeSequence;
import ubic.gemma.model.expression.experiment.BioAssaySet;
import ubic.gemma.model.expression.experiment.ExpressionExperiment;
import ubic.gemma.model.genome.Gene;
import ubic.gemma.model.genome.Taxon;
import ubic.gemma.persistence.service.TableMaintenanceUtil;
import ubic.gemma.persistence.service.association.coexpression.CoexpressionCache;
import ubic.gemma.persistence.service.association.coexpression.CoexpressionService;
import ubic.gemma.persistence.service.association.coexpression.CoexpressionValueObject;
import ubic.gemma.persistence.service.expression.bioAssayData.ProcessedExpressionDataVectorService;
import ubic.gemma.persistence.service.expression.experiment.ExpressionExperimentService;
import ubic.gemma.persistence.util.EntityUtils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import static org.junit.Assert.*;
/**
* @author paul
*/
public class LinkAnalysisServiceTest extends BaseSpringContextTest {
private final FilterConfig filterConfig = new FilterConfig();
private final LinkAnalysisConfig linkAnalysisConfig = new LinkAnalysisConfig();
@Autowired
private BasicDataSource dataSource;
private ExpressionExperiment ee;
@Autowired
private ExpressionExperimentService eeService;
@Autowired
private CoexpressionCache gene2GeneCoexpressionCache;
@Autowired
private CoexpressionService geneCoexpressionService;
@Autowired
private GeneService geneService;
@Autowired
private LinkAnalysisPersister linkAnalysisPersisterService;
@Autowired
private LinkAnalysisService linkAnalysisService;
@Autowired
private ProcessedExpressionDataVectorService processedExpressionDataVectorService;
@Autowired
private TableMaintenanceUtil tableMaintenanceUtil;
@Before
public void setUp() throws Exception {
super.setUp();
super.setTestCollectionSize( 100 );
gene2GeneCoexpressionCache.shutdown();
}
@After
public void tearDown() {
super.resetTestCollectionSize();
}
@Test
@Category(SlowTest.class)
public void testLoadAnalyzeSaveAndCoexpSearch() {
ee = this.getTestPersistentCompleteExpressionExperimentWithSequences();
processedExpressionDataVectorService.computeProcessedExpressionData( ee );
tableMaintenanceUtil.disableEmail();
tableMaintenanceUtil.updateGene2CsEntries();
linkAnalysisConfig.setCdfCut( 0.1 );
linkAnalysisConfig.setSingularThreshold( SingularThreshold.cdfcut );
linkAnalysisConfig.setProbeDegreeThreshold( 25 );
linkAnalysisConfig.setCheckCorrelationDistribution( false );
linkAnalysisConfig.setCheckForBatchEffect( false );
filterConfig.setIgnoreMinimumSampleThreshold( true );
// first time.
//noinspection UnusedAssignment // we still want to do this for the testing sake
LinkAnalysis la = linkAnalysisService.process( ee, filterConfig, linkAnalysisConfig );
// test remove is clean; to check this properly requires checking the db.
linkAnalysisPersisterService.deleteAnalyses( ee );
this.checkUnsupportedLinksHaveNoSupport();
assertEquals( 0, geneCoexpressionService.getCoexpression( ee, true ).size() );
la = linkAnalysisService.process( ee, filterConfig, linkAnalysisConfig );
CoexpressionAnalysis analysisObj = la.getAnalysisObj();
assertEquals( 151, analysisObj.getNumberOfElementsAnalyzed().intValue() );
assertTrue( analysisObj.getNumberOfLinks() > 0 );
assertNotNull( analysisObj.getCoexpCorrelationDistribution() );
Collection<BioAssaySet> ees = new HashSet<>();
ees.add( ee );
this.updateNodeDegree();
int totalLinksFirstPass = this.checkResults( ees, 1 );
// should be ~1140.
assertTrue( totalLinksFirstPass > 1000 );
// test redo
linkAnalysisService.process( ee, filterConfig, linkAnalysisConfig );
this.updateNodeDegree();
int totalLinksRedo = this.checkResults( ees, 1 );
assertEquals( totalLinksFirstPass, totalLinksRedo );
// now add another experiment that has overlapping links (same data...
Map<CompositeSequence, byte[]> dataMap = new HashMap<>();
ee = eeService.thaw( ee );
for ( RawExpressionDataVector v : ee.getRawExpressionDataVectors() ) {
dataMap.put( v.getDesignElement(), v.getData() );
}
ExpressionExperiment ee2 = this.getTestPersistentCompleteExpressionExperimentWithSequences( ee );
//eeService.thawRawAndProcessed( ee2 );
for ( RawExpressionDataVector v : ee2.getRawExpressionDataVectors() ) {
assert dataMap.get( v.getDesignElement() ) != null;
v.setData( dataMap.get( v.getDesignElement() ) );
}
eeService.update( ee2 );
processedExpressionDataVectorService.computeProcessedExpressionData( ee2 );
linkAnalysisService.process( ee2, filterConfig, linkAnalysisConfig );
this.updateNodeDegree();
// expect to get at least one links with support >1
ees.add( ee2 );
this.checkResults( ees, 2 );
}
private void checkUnsupportedLinksHaveNoSupport() {
JdbcTemplate jt = new JdbcTemplate( dataSource );
// see SupportDetailsTest for validation that these strings represent empty byte arrays. I think the 1 at
// position 12 is important.
final Collection<Long> checkme = new HashSet<>();
// maybe these patterns aren't this reproducible.
jt.query(
// "SELECT ID from MOUSE_LINK_SUPPORT_DETAILS WHERE HEX(BYTES) in ('0000000200000001000000000000000200000000',"
// + " '000006AA00000001000000000000003600000000', '0000000000000001000000000000000000000000',"
// + "'0000003E00000001000000000000000200000000','0000003F00000001000000000000000200000000',"
// + "'0000000500000001000000000000000200000000')", new RowCallbackHandler() {
// 000002BB00000001000000000000001600000000
"SELECT ID FROM MOUSE_LINK_SUPPORT_DETAILS WHERE HEX(BYTES) LIKE '00000___0000000100000000000000%'",
new RowCallbackHandler() {
@Override
public void processRow( ResultSet rs ) throws SQLException {
Long id = rs.getLong( 1 );
checkme.add( id );
}
} );
// we should definitely have some of these
assertTrue( checkme.size() > 0 );
jt.query( "SELECT SUPPORT FROM MOUSE_GENE_COEXPRESSION WHERE SUPPORT_DETAILS_FK IN (?) AND SUPPORT > 0",
new Object[] { checkme.toArray() }, new RowCallbackHandler() {
@Override
public void processRow( ResultSet rs ) {
fail( "Should not have had any rows" );
}
} );
}
private void checkResult( CoexpressionValueObject coex ) {
assertNotNull( coex.toString(), coex.getQueryGeneId() );
assertNotNull( coex.toString(), coex.getCoexGeneId() );
assertNotNull( coex.toString(), coex.getSupportDetailsId() );
assertNotNull( coex.toString(), coex.getSupportingDatasets() );
assertTrue( coex.toString(), coex.getNumDatasetsSupporting() > 0 );
assertTrue( coex.toString(), coex.getNumDatasetsTestedIn() != 0 );
// assertNotNull( coex.toString(), coex.getTestedInDatasets() );
if ( coex.getNumDatasetsTestedIn() > 0 ) {
assertEquals( coex.toString(), coex.getNumDatasetsTestedIn().intValue(),
coex.getTestedInDatasets().size() );
assertTrue( coex.toString() + " testedin: " + coex.getTestedInDatasets() + " supportedin: " + coex
.getSupportingDatasets(), coex.getNumDatasetsSupporting() <= coex.getNumDatasetsTestedIn() );
}
assertEquals( coex.toString(), coex.getSupportingDatasets().size(),
coex.getNumDatasetsSupporting().intValue() );
assertTrue( coex.toString(), !coex.getSupportingDatasets().isEmpty() );
}
private int checkResults( Collection<BioAssaySet> ees, int expectedMinimumMaxSupport ) {
boolean foundOne = false;
int maxSupport = 0;
Taxon mouse = taxonService.findByCommonName( "mouse" );
Collection<Gene> genesWithLinks = new ArrayList<>();
int totalLinks = 0;
// numdatasetstesting will not be set so we won't bother checking.
assertTrue( !geneCoexpressionService.getCoexpression( ee, true ).isEmpty() );
Collection<CoexpressionValueObject> eeResults = geneCoexpressionService.getCoexpression( ee, false );
assertTrue( !eeResults.isEmpty() );
for ( CoexpressionValueObject coex : eeResults ) {
this.checkResult( coex );
}
Map<Long, GeneCoexpressionNodeDegreeValueObject> nodeDegrees = geneCoexpressionService
.getNodeDegrees( EntityUtils.getIds( geneService.loadAll() ) );
assertTrue( !nodeDegrees.isEmpty() );
// experiment-major query
Map<Long, List<CoexpressionValueObject>> allLinks = geneCoexpressionService
.findCoexpressionRelationships( mouse, new HashSet<Long>(), EntityUtils.getIds( ees ), ees.size(), 10,
false );
assertTrue( !allLinks.isEmpty() );
for ( Long g : allLinks.keySet() ) {
for ( CoexpressionValueObject coex : allLinks.get( g ) ) {
this.checkResult( coex );
}
}
for ( Gene gene : geneService.loadAll( mouse ) ) {
Collection<CoexpressionValueObject> links = geneCoexpressionService
.findCoexpressionRelationships( gene, EntityUtils.getIds( ees ), 1, 0, false );
if ( links == null || links.isEmpty() ) {
continue;
}
assertEquals( geneCoexpressionService
.findCoexpressionRelationships( gene, Collections.singleton( ee.getId() ), 0, false ).size(),
geneCoexpressionService.countLinks( ee, gene ).intValue() );
GeneCoexpressionNodeDegreeValueObject nodeDegree = geneCoexpressionService.getNodeDegree( gene );
if ( links.size() != nodeDegree.getLinksWithMinimumSupport( 1 ) ) {
log.info( nodeDegree );
assertEquals( "Node degree check failed for gene " + gene, links.size(),
nodeDegree.getLinksWithMinimumSupport( 1 ).intValue() );
}
assertTrue( nodeDegree.getLinksWithMinimumSupport( 1 ) >= nodeDegree.getLinksWithMinimumSupport( 2 ) );
totalLinks += links.size();
log.debug( links.size() + " hits for " + gene );
for ( CoexpressionValueObject coex : links ) {
this.checkResult( coex );
if ( coex.getNumDatasetsSupporting() > maxSupport ) {
maxSupport = coex.getNumDatasetsSupporting();
}
}
foundOne = true;
if ( genesWithLinks.size() == 5 ) {
// without specifying stringency
Map<Long, List<CoexpressionValueObject>> multiGeneResults = geneCoexpressionService
.findCoexpressionRelationships( mouse, EntityUtils.getIds( genesWithLinks ),
EntityUtils.getIds( ees ), 100, false );
if( !multiGeneResults.isEmpty() ) {
for ( Long id : multiGeneResults.keySet() ) {
for ( CoexpressionValueObject coex : multiGeneResults.get( id ) ) {
this.checkResult( coex );
}
}
// with stringency specified, quick.
Map<Long, List<CoexpressionValueObject>> multiGeneResults2 = geneCoexpressionService
.findCoexpressionRelationships( mouse, EntityUtils.getIds( genesWithLinks ), EntityUtils.getIds( ees ), ees.size(), 100, true );
if ( multiGeneResults.size() != multiGeneResults2.size() ) {
assertEquals( multiGeneResults.size(), multiGeneResults2.size() );
}
for ( Long id : multiGeneResults2.keySet() ) {
for ( CoexpressionValueObject coex : multiGeneResults2.get( id ) ) {
this.checkResult( coex );
}
}
}
}
genesWithLinks.add( gene );
}
assertTrue( foundOne );
Map<Long, List<CoexpressionValueObject>> mygeneresults = geneCoexpressionService
.findInterCoexpressionRelationships( mouse, EntityUtils.getIds( genesWithLinks ),
EntityUtils.getIds( ees ), 1, false );
if ( mygeneresults.isEmpty() ) {
//noinspection ConstantConditions // these strange structures are to help with debugger.
assertTrue( !mygeneresults.isEmpty() );
}
for ( Long id : mygeneresults.keySet() ) {
for ( CoexpressionValueObject coex : mygeneresults.get( id ) ) {
this.checkResult( coex );
}
}
assertTrue( maxSupport >= expectedMinimumMaxSupport );
return totalLinks;
}
private void updateNodeDegree() {
geneCoexpressionService.updateNodeDegrees( this.getTaxon( "mouse" ) );
}
}
| 42.060274 | 156 | 0.658807 |
a74934de52f1ee7962f5227bdc33c192384faf0d | 923 | // Generated automatically from android.content.pm.PermissionGroupInfo for testing purposes
package android.content.pm;
import android.content.pm.PackageItemInfo;
import android.content.pm.PackageManager;
import android.os.Parcel;
import android.os.Parcelable;
public class PermissionGroupInfo extends PackageItemInfo implements Parcelable
{
public CharSequence loadDescription(PackageManager p0){ return null; }
public CharSequence nonLocalizedDescription = null;
public PermissionGroupInfo(){}
public PermissionGroupInfo(PermissionGroupInfo p0){}
public String toString(){ return null; }
public int describeContents(){ return 0; }
public int descriptionRes = 0;
public int flags = 0;
public int priority = 0;
public static Parcelable.Creator<PermissionGroupInfo> CREATOR = null;
public static int FLAG_PERSONAL_INFO = 0;
public void writeToParcel(Parcel p0, int p1){}
}
| 36.92 | 91 | 0.775731 |
bf787f62e23dfa0f5838d325b1ecdfd020b121d5 | 12,409 | package hex.schemas;
import hex.glm.GLMModel;
import hex.maxrglm.MaxRGLM;
import hex.maxrglm.MaxRGLMModel;
import water.api.API;
import water.api.schemas3.KeyV3;
import water.api.schemas3.ModelParametersSchemaV3;
import water.api.schemas3.ModelSchemaV3;
import water.api.schemas3.StringPairV3;
public class MaxRGLMV3 extends ModelBuilderSchema<MaxRGLM, MaxRGLMV3, MaxRGLMV3.MaxRGLMParametersV3> {
public static final class MaxRGLMParametersV3 extends ModelParametersSchemaV3<MaxRGLMModel.MaxRGLMParameters,
MaxRGLMParametersV3> {
public static final String[] fields = new String[]{
"model_id",
"training_frame",
"validation_frame",
"nfolds",
"seed",
"fold_assignment",
"fold_column",
"response_column",
"ignored_columns",
"ignore_const_cols",
"score_each_iteration",
"score_iteration_interval",
"offset_column",
"weights_column",
"solver",
"alpha",
"lambda",
"lambda_search",
"early_stopping",
"nlambdas",
"standardize",
"missing_values_handling",
"plug_values",
"compute_p_values",
"remove_collinear_columns",
"intercept",
"non_negative",
"max_iterations",
"objective_epsilon",
"beta_epsilon",
"gradient_epsilon",
"startval", // initial starting values for fixed and randomized coefficients, double array
"prior",
"cold_start", // if true, will start GLM model from initial values and conditions
"lambda_min_ratio",
"beta_constraints",
"max_active_predictors",
"obj_reg",
"stopping_rounds",
"stopping_metric",
"stopping_tolerance",
// dead unused args forced here by backwards compatibility, remove in V4
"balance_classes",
"class_sampling_factors",
"max_after_balance_size",
"max_confusion_matrix_size",
"max_runtime_secs",
"custom_metric_func",
"nparallelism",
"max_predictor_number", // denote maximum number of predictors to build models for
};
@API(help = "Seed for pseudo random number generator (if applicable)", gridable = true)
public long seed;
@API(help = "AUTO will set the solver based on given data and the other parameters. IRLSM is fast on on " +
"problems with small number of predictors and for lambda-search with L1 penalty, L_BFGS scales " +
"better for datasets with many columns.", values = {"AUTO", "IRLSM", "L_BFGS",
"COORDINATE_DESCENT_NAIVE", "COORDINATE_DESCENT", "GRADIENT_DESCENT_LH", "GRADIENT_DESCENT_SQERR"},
level = API.Level.critical)
public GLMModel.GLMParameters.Solver solver;
@API(help = "Distribution of regularization between the L1 (Lasso) and L2 (Ridge) penalties. A value of 1 for" +
" alpha represents Lasso regression, a value of 0 produces Ridge regression, and anything in between" +
" specifies the amount of mixing between the two. Default value of alpha is 0 when SOLVER = 'L-BFGS';" +
" 0.5 otherwise.", level = API.Level.critical, gridable = true)
public double[] alpha;
@API(help = "Regularization strength", required = false, level = API.Level.critical, gridable = true)
public double[] lambda;
@API(help = "Use lambda search starting at lambda max, given lambda is then interpreted as lambda min",
level = API.Level.critical)
public boolean lambda_search;
@API(help="Stop early when there is no more relative improvement on train or validation (if provided)")
public boolean early_stopping;
@API(help = "Number of lambdas to be used in a search." +
" Default indicates: If alpha is zero, with lambda search" +
" set to True, the value of nlamdas is set to 30 (fewer lambdas" +
" are needed for ridge regression) otherwise it is set to 100.", level = API.Level.critical)
public int nlambdas;
@API(help = "Perform scoring for every score_iteration_interval iterations", level = API.Level.secondary)
public int score_iteration_interval;
@API(help = "Standardize numeric columns to have zero mean and unit variance", level = API.Level.critical)
public boolean standardize;
@API(help = "Only applicable to multiple alpha/lambda values. If false, build the next model for next set" +
" of alpha/lambda values starting from the values provided by current model. If true will start GLM" +
" model from scratch.", level = API.Level.critical)
public boolean cold_start;
@API(help = "Handling of missing values. Either MeanImputation, Skip or PlugValues.",
values = { "MeanImputation", "Skip", "PlugValues" }, level = API.Level.expert,
direction=API.Direction.INOUT, gridable = true)
public GLMModel.GLMParameters.MissingValuesHandling missing_values_handling;
@API(help = "Plug Values (a single row frame containing values that will be used to impute missing values of" +
" the training/validation frame, use with conjunction missing_values_handling = PlugValues)",
direction = API.Direction.INPUT)
public KeyV3.FrameKeyV3 plug_values;
@API(help = "Restrict coefficients (not intercept) to be non-negative")
public boolean non_negative;
@API(help = "Maximum number of iterations", level = API.Level.secondary)
public int max_iterations;
@API(help = "Converge if beta changes less (using L-infinity norm) than beta esilon, ONLY applies to IRLSM" +
" solver ", level = API.Level.expert)
public double beta_epsilon;
@API(help = "Converge if objective value changes less than this."+ " Default indicates: If lambda_search"+
" is set to True the value of objective_epsilon is set to .0001. If the lambda_search is set to False" +
" and lambda is equal to zero, the value of objective_epsilon is set to .000001, for any other value" +
" of lambda the default value of objective_epsilon is set to .0001.", level = API.Level.expert)
public double objective_epsilon;
@API(help = "Converge if objective changes less (using L-infinity norm) than this, ONLY applies to L-BFGS" +
" solver. Default indicates: If lambda_search is set to False and lambda is equal to zero, the" +
" default value of gradient_epsilon is equal to .000001, otherwise the default value is .0001. If " +
"lambda_search is set to True, the conditional values above are 1E-8 and 1E-6 respectively.",
level = API.Level.expert)
public double gradient_epsilon;
@API(help="Likelihood divider in objective value computation, default is 1/nobs")
public double obj_reg;
@API(help = "double array to initialize fixed and random coefficients for HGLM, coefficients for GLM.",
gridable=true)
public double[] startval;
@API(help = "if true, will return likelihood function value for HGLM.") // not gridable
public boolean calc_like;
@API(help="Include constant term in the model", level = API.Level.expert)
public boolean intercept;
@API(help = "Prior probability for y==1. To be used only for logistic regression iff the data has been " +
"sampled and the mean of response does not reflect reality.", level = API.Level.expert)
public double prior;
@API(help = "Minimum lambda used in lambda search, specified as a ratio of lambda_max (the smallest lambda" +
" that drives all coefficients to zero). Default indicates: if the number of observations is greater" +
" than the number of variables, then lambda_min_ratio is set to 0.0001; if the number of observations" +
" is less than the number of variables, then lambda_min_ratio is set to 0.01.",
level = API.Level.expert)
public double lambda_min_ratio;
@API(help = "Beta constraints", direction = API.Direction.INPUT /* Not required, to allow initial params validation: , required=true */)
public KeyV3.FrameKeyV3 beta_constraints;
@API(help="Maximum number of active predictors during computation. Use as a stopping criterion to prevent" +
" expensive model building with many predictors." + " Default indicates: If the IRLSM solver is used," +
" the value of max_active_predictors is set to 5000 otherwise it is set to 100000000.",
direction = API.Direction.INPUT, level = API.Level.expert)
public int max_active_predictors = -1;
// dead unused args, formely inherited from supervised model schema
/**
* For imbalanced data, balance training data class counts via
* over/under-sampling. This can result in improved predictive accuracy.
*/
@API(help = "Balance training data class counts via over/under-sampling (for imbalanced data).",
level = API.Level.secondary, direction = API.Direction.INOUT)
public boolean balance_classes;
/**
* Desired over/under-sampling ratios per class (lexicographic order).
* Only when balance_classes is enabled.
* If not specified, they will be automatically computed to obtain class balance during training.
*/
@API(help = "Desired over/under-sampling ratios per class (in lexicographic order). If not specified, " +
"sampling factors will be automatically computed to obtain class balance during training. Requires" +
" balance_classes.", level = API.Level.expert, direction = API.Direction.INOUT)
public float[] class_sampling_factors;
/**
* When classes are balanced, limit the resulting dataset size to the
* specified multiple of the original dataset size.
*/
@API(help = "Maximum relative size of the training data after balancing class counts (can be less than 1.0)." +
" Requires balance_classes.", /* dmin=1e-3, */ level = API.Level.expert,
direction = API.Direction.INOUT)
public float max_after_balance_size;
/** For classification models, the maximum size (in terms of classes) of
* the confusion matrix for it to be printed. This option is meant to
* avoid printing extremely large confusion matrices. */
@API(help = "[Deprecated] Maximum size (# classes) for confusion matrices to be printed in the Logs",
level = API.Level.secondary, direction = API.Direction.INOUT)
public int max_confusion_matrix_size;
@API(help="Request p-values computation, p-values work only with IRLSM solver and no regularization",
level = API.Level.secondary, direction = API.Direction.INPUT)
public boolean compute_p_values; // _remove_collinear_columns
@API(help="In case of linearly dependent columns, remove some of the dependent columns",
level = API.Level.secondary, direction = API.Direction.INPUT)
public boolean remove_collinear_columns; // _remove_collinear_columns
@API(help = "Maximum number of predictors to be considered when building GLM models. Defaiult to 1.",
level = API.Level.secondary, direction = API.Direction.INPUT)
public int max_predictor_number;
@API(help = "number of models to build in parallel. Default to 0.0 which is adaptive to the system capability",
level = API.Level.secondary, gridable = true)
public int nparallelism;
}
}
| 54.187773 | 144 | 0.634137 |
6b8f4d9072c5f283fead3495fbfed254d62d2855 | 1,268 | /*
* Copyright Terracotta, 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.ehcache.core.events;
import org.ehcache.Cache;
import org.ehcache.event.CacheEvent;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class CacheEventsTest {
@Test
public void testToString() throws Exception {
@SuppressWarnings("unchecked")
Cache<String, String> cache = mock(Cache.class);
when(cache.toString()).thenReturn("cache");
CacheEvent<String, String> event = CacheEvents.update("key", "old", "new", cache);
assertThat(event.toString()).isEqualTo("UPDATED on cache key,oldValue,newValue='key','old','new'");
}
}
| 33.368421 | 103 | 0.735016 |
1a3f50954a6de32431d446ad947bf6401a599f3c | 75 | simple test labeled statement testlabeledstatement main foo foo label label | 75 | 75 | 0.88 |
208ef2e0be1bbd21333eca1edb8fa7a5808a12cb | 36 | package b.o.v4;
public class i {
}
| 7.2 | 16 | 0.638889 |
5bb1ce82d8762489ba86b59ff7b856707fa9bfe6 | 538 | package org.diql.common.util;
import java.util.Collection;
import java.util.List;
/**
* Created by qinglian on 2018/5/7.
*/
public class CollectionUtil {
private CollectionUtil() {
// empty.
}
/**
* collection是否为空.
* @param collection
* @return
*/
public static boolean isEmpty(Collection collection) {
return collection == null || collection.isEmpty();
}
public static int size(Collection collection) {
return collection == null ? 0 : collection.size();
}
}
| 19.214286 | 58 | 0.620818 |
152f924e36be307bc3c58817acf526f2932b6547 | 1,929 | package java.practice.examples.datatypes;
public class JavaDataTypesByte {
public static void main(String[] args) {
byte b= 127;
System.out.println(b);
System.out.println();
byte b1= 10;
System.out.println(b1);
System.out.println();
// byte b2= 128; //Type mismatch: cannot convert from int to byte
// System.out.println(b2);
// System.out.println();
// byte b3= 10.5; //Type mismatch: cannot convert from double to byte
// System.out.println(b3);
// System.out.println();
// byte b4= true; //Type mismatch: cannot convert from boolean to byte
// System.out.println(b4);
// System.out.println();
// byte b5= "pooja"; //Type mismatch: cannot convert from String to byte
// System.out.println(b5);
// System.out.println();
}
}
/*
* In java every variables and expressions has some type, each and every data type is clearly defined, every assignment should be chekced by compiler for type compatibility, because of this we can conclude Java is strongly typed language
* Java is not considered as pure OOP language because several OOPS features are not satisfied by JAVA, like operator overloading and multiple inheritance
* Moreover we are depending on primitive data types which are non objects
*
* Primitive Data types:
* (Signed data types coz we can represnt both +ve and -ve number )Numeric Data Types:
* 1. Integral : Byte,short,int,long
* 2. Floating types : float,double
* Non-Numeric Data Types : char, boolean
*
* 1. byte :
* - 1 byte = 8 bits
* - range : -128 to 127
* - byte b =10; V
* - b=127;V
* - b=128 : Possible loss of precision, found int required byte
* - b =10.5 : PLP, found double, required byte
* - b = true : incompatible types found /: boolean, required : byte
* - b = "pooja"
*
* 1. byte is a best choice if you want to handle data in term of streams either from file or network.
* 2. File/Network supported form is byte
*
*
*/
| 35.722222 | 237 | 0.692587 |
870ab1f2db410978011d54a8d9cbf60af37b1f3f | 594 | package net.petrikainulainen.spring.batch;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* This configuration class enables the Spring MVC framework.
*/
@Configuration
@EnableWebMvc
public class SpringBatchWebAppConfig implements WebMvcConfigurer {
}
| 34.941176 | 89 | 0.855219 |
834bf5d8973faff9a2925f5d4b034af2dd185685 | 1,699 |
public class _410SplitArrayLargestSum {
public int splitArray(int[] nums, int m) {
if (nums == null ) return 0;
int max = 0;
long sum = 0;
for (int i=0; i< nums.length; i++){
sum += nums[i];
max = Math.max(max, nums[i]);
}//for
if ( m == 1) return (int)sum;
long low = max, high = sum;
while ( low <= high){
long mid = low + (high - low)/2;
if (isValid (nums, mid, m)){
low = mid +1;
}else{
high = mid -1;
}
}//while
return (int)low;
}
private boolean isValid(int[] nums, long target, int m) {
// TODO Auto-generated method stub
int count = 1;
int sum = 0;
for (int i=0; i < nums.length; i++){
sum += nums[i];
if (sum > target){
count++;
sum = nums[i];
}//if
if (count > m){
return true;
}//if
}//for
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
_410SplitArrayLargestSum A= new _410SplitArrayLargestSum ();
int nums[] = {7,2,5,10,8,12};
System.out.println(A.splitArray(nums, 3));
}
}
//question:
//Given an array which consists of non-negative integers and an integer m,
//you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.
//
//Note:
//If n is the length of array, assume the following constraints are satisfied:
//
//1 ≤ n ≤ 1000
//1 ≤ m ≤ min(50, n)
//Examples:
//
//Input:
//nums = [7,2,5,10,8]
//m = 2
//
//Output:
//18
//
//Explanation:
//There are four ways to split nums into two subarrays.
//The best way is to split it into [7,2,5] and [10,8],
//where the largest sum among the two subarrays is only 18. | 22.653333 | 137 | 0.59741 |
36894104f328787f42407c11c8997cdd07af51c5 | 420 | package net.shrimpworks.unreal.dependencies;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class NativePackagesTest {
@Test
public void loadNativePackages() {
NativePackages pkgs = new NativePackages();
assertNotNull(pkgs.get("Core"));
assertTrue(pkgs.get("Engine").contains("Level"));
}
}
| 24.705882 | 61 | 0.77619 |
ced2595439c27bcda4afc65aa654ba6a00d27abb | 1,964 | /**
* Copyright (C) 2016-2021 Expedia, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hotels.bdp.circustrain.extension;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;
import java.util.Iterator;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.env.ConfigurableEnvironment;
import com.google.common.collect.ImmutableSet;
@RunWith(MockitoJUnitRunner.class)
public class PropertyExtensionPackageProviderTest {
@Mock
private ConfigurableEnvironment env;
private final PropertyExtensionPackageProvider underTest = new PropertyExtensionPackageProvider();
@Test
public void noPackagesDeclared() {
when(env.getProperty("extension-packages", Set.class)).thenReturn(ImmutableSet.of());
Set<String> packages = underTest.getPackageNames(env);
assertThat(packages.size(), is(0));
}
@Test
public void twoPackagesDeclared() {
when(env.getProperty("extension-packages", Set.class)).thenReturn(ImmutableSet.of("com.foo", "com.bar"));
Set<String> packages = underTest.getPackageNames(env);
assertThat(packages.size(), is(2));
Iterator<String> iterator = packages.iterator();
assertThat(iterator.next(), is("com.foo"));
assertThat(iterator.next(), is("com.bar"));
}
}
| 32.196721 | 109 | 0.75611 |
6c04b84cebfc1974056874d245d762545737d3c1 | 4,465 | package com.dt.module.wx.service;
import org.springframework.stereotype.Service;
import com.dt.core.common.base.BaseService;
import com.dt.core.common.base.R;
import com.dt.core.dao.sql.Insert;
import com.dt.core.dao.sql.Update;
import com.dt.core.dao.util.TypedHashMap;
import com.dt.core.tool.util.DbUtil;
import com.dt.core.tool.util.ToolUtil;
/**
* @author: jinjie
* @date: 2018年5月7日 下午2:46:28
* @Description: TODO
*/
@Service
public class MessageService extends BaseService {
public R deleteMessage(String id) {
Update me = new Update("wx_msg_def");
me.setIf("dr", 1);
me.where().and("id=?", id);
db.execute(me);
return R.SUCCESS_OPER();
}
public R updateMessage(TypedHashMap<String, Object> ps) {
Update me = new Update("wx_msg_def");
me.setIf("mark", ps.getString("mark", ""));
me.setIf("code", ps.getString("code", ""));
me.setIf("name", ps.getString("name", ""));
me.setIf("funtype", ps.getString("funtype", ""));
me.setIf("msgtype", ps.getString("msgtype", ""));
me.setIf("value", ps.getString("value", ""));
me.where().and("id=?", ps.getString("id"));
db.execute(me);
return R.SUCCESS_OPER();
}
// funtype:reply(自动回复),action(动作),push(推送类)
// msgtype:text(普通消息),6(图文消息)
public R addMessage(TypedHashMap<String, Object> ps) {
Insert me = new Insert("wx_msg_def");
me.set("dr", 0);
me.set("id", db.getUUID());
me.set("group_id", db.getUUID());
me.setIf("mark", ps.getString("mark", ""));
me.setIf("code", ps.getString("code", ""));
me.setIf("funtype", ps.getString("funtype", ""));
me.setIf("name", ps.getString("name", ""));
me.setIf("msgtype", ps.getString("msgtype", ""));
me.setIf("value", ps.getString("value", ""));
db.execute(me);
return R.SUCCESS_OPER();
}
public R queryMessageById(String id) {
return R.SUCCESS_OPER(db.uniqueRecord("select * from wx_msg_def where id=?", id).toJsonObject());
}
public R queryMessages(String funtype) {
String sql = "select * from wx_msg_def where dr=0 ";
if (ToolUtil.isNotEmpty(funtype)) {
sql = sql + " and funtype='" + funtype + "'";
}
sql = sql + " order by msgtype";
return R.SUCCESS_OPER(db.query(sql).toJsonArrayWithJsonObject());
}
// 图文
public R queryImageTextMessagesGroup() {
return R.SUCCESS_OPER(
db.query("select * from wx_msg_def where dr=0 and msgtype='6'").toJsonArrayWithJsonObject());
}
public R queryImageTextMessages(String group_id) {
return R.SUCCESS_OPER(db.query("select * from wx_msg_imgitem where group_id=? and dr=0 order by rn", group_id)
.toJsonArrayWithJsonObject());
}
public R deleteImageTextMessage(String id) {
Update me = new Update("wx_msg_imgitem");
me.setIf("dr", 1);
me.where().and("id=?", id);
db.execute(me);
return R.SUCCESS_OPER();
}
public R updateImageTextMessage(TypedHashMap<String, Object> ps) {
Update me = new Update("wx_msg_imgitem");
me.setIf("title", ps.getString("title", ""));
me.setIf("msgdesc", ps.getString("msgdesc", ""));
me.setIf("docurl", ps.getString("docurl", ""));
me.setIf("imgurl", ps.getString("imgurl", ""));
me.setIf("rn", ps.getString("rn", ""));
me.setIf("mark", ps.getString("mark", ""));
me.where().and("id=?", ps.getString("id"));
db.execute(me);
return R.SUCCESS_OPER();
}
public R addImageTextMessage(TypedHashMap<String, Object> ps) {
Insert me = new Insert("wx_msg_imgitem");
me.set("dr", 0);
me.set("id", db.getUUID());
me.setIf("title", ps.getString("title", ""));
me.setIf("msgdesc", ps.getString("msgdesc", ""));
me.setIf("docurl", ps.getString("docurl", ""));
me.setIf("imgurl", ps.getString("imgurl", ""));
me.setIf("group_id", ps.getString("group_id", ""));
me.setIf("rn", ps.getString("rn", ""));
me.setIf("mark", ps.getString("mark", ""));
db.execute(me);
return R.SUCCESS_OPER();
}
public R queryImageTextMessageById(String id) {
return R.SUCCESS_OPER(db.uniqueRecord("select * from wx_msg_imgitem where id=?", id).toJsonObject());
}
//
public R addSc(TypedHashMap<String, Object> ps) {
Insert me = new Insert("wx_msg_sc");
me.set("dr", 0);
me.set("id", db.getUUID());
me.set("pic_id", ps.getString("pic_id", ""));
me.set("sctype", ps.getString("sctype", "image"));
me.setSE("ctime", DbUtil.getDbDateString(db.getDBType()));
db.execute(me);
return R.SUCCESS_OPER();
}
public R queryScs() {
return R.SUCCESS_OPER(
db.query("select * from wx_msg_sc where dr=0 order by ctime desc").toJsonArrayWithJsonObject());
}
}
| 31.892857 | 113 | 0.660246 |
8bb8c64867991b00ef1bab99a0c224ff6cec2230 | 273 | package com.zgrannan.crewandroid;
/**
* A building block of a {@link Platform}.
*
* @author Zack Grannan
* @version 0.96.
*
*/
public class PlatFrag extends PlatTypeFrag {
@Override
protected int getCrossbeams() {
return (int) (length.toDouble() / 40);
}
}
| 15.166667 | 44 | 0.663004 |
d21f73650d1ad9e6a54161a970533186c1626880 | 5,961 | package com.opd.therament.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.airbnb.lottie.LottieAnimationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.gson.Gson;
import com.opd.therament.R;
import com.opd.therament.adapters.AppointmentAdapter;
import com.opd.therament.datamodels.AppointmentDataModel;
import com.opd.therament.datamodels.HospitalDataModel;
import com.opd.therament.utilities.LoadingDialog;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;
public class PreviousAppointmentActivity extends AppCompatActivity implements AppointmentAdapter.ItemViewClick {
ImageView ivBack;
RecyclerView rvAppointments;
FirebaseAuth mAuth;
FirebaseFirestore firestore;
AppointmentAdapter appointmentAdapter;
LottieAnimationView emptyAnimation;
TextView tvNoAppointments;
@Override
protected void onResume() {
super.onResume();
LoadingDialog.showDialog(this);
getAppointments();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_previous_appointment);
ivBack = findViewById(R.id.iv_back);
ivBack.setOnClickListener(view -> {
onBackPressed();
});
emptyAnimation = findViewById(R.id.empty_animation);
tvNoAppointments = findViewById(R.id.tv_no_appointments);
rvAppointments = findViewById(R.id.rv_appointments);
rvAppointments.setLayoutManager(new LinearLayoutManager(this));
mAuth = FirebaseAuth.getInstance();
firestore = FirebaseFirestore.getInstance();
}
private void getAppointments() {
ArrayList<AppointmentDataModel> appointmentList = new ArrayList<>();
CollectionReference appColl = firestore.collection(getString(R.string.collection_users)).document(Objects.requireNonNull(mAuth.getCurrentUser()).getUid()).collection(getString(R.string.collection_history));
appColl.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
for (DocumentSnapshot doc : task.getResult()) {
AppointmentDataModel dataModel = doc.toObject(AppointmentDataModel.class);
appointmentList.add(dataModel);
}
if (appointmentList.isEmpty()) {
rvAppointments.setVisibility(View.INVISIBLE);
emptyAnimation.setVisibility(View.VISIBLE);
tvNoAppointments.setVisibility(View.VISIBLE);
} else {
emptyAnimation.setVisibility(View.INVISIBLE);
tvNoAppointments.setVisibility(View.INVISIBLE);
rvAppointments.setVisibility(View.VISIBLE);
try {
sortList(appointmentList);
} catch (ParseException e) {
e.printStackTrace();
}
}
LoadingDialog.dismissDialog();
} else {
LoadingDialog.dismissDialog();
Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
}
private void sortList(ArrayList<AppointmentDataModel> appointmentList) throws ParseException {
SimpleDateFormat formatDate = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
Date temp;
for (int i = 0; i < appointmentList.size(); i++) {
for (int j = i + 1; j < appointmentList.size(); j++) {
Date first = formatDate.parse(appointmentList.get(i).getSelectedDate());
Date second = formatDate.parse(appointmentList.get(j).getSelectedDate());
assert first != null;
if (first.compareTo(second) < 0) {
temp = first;
appointmentList.get(i).setSelectedDate(appointmentList.get(j).getSelectedDate());
appointmentList.get(j).setSelectedDate(formatDate.format(temp));
}
}
}
appointmentAdapter = new AppointmentAdapter(this, appointmentList, this, "History");
rvAppointments.setAdapter(appointmentAdapter);
}
@Override
public void onItemClicked(AppointmentDataModel dataModel) {
DocumentReference hospitalDoc = firestore.collection(getString(R.string.collection_hospitals)).document(dataModel.getHospitalId());
hospitalDoc.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
DocumentSnapshot doc = task.getResult();
if (doc.exists()) {
HospitalDataModel hospitalDataModel = doc.toObject(HospitalDataModel.class);
String hospitalDetails = new Gson().toJson(hospitalDataModel);
Intent intent = new Intent(this, HospitalActivity.class);
intent.putExtra("hospitalDetails", hospitalDetails);
startActivity(intent);
} else {
Toast.makeText(this, "Hospital Not found", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
}
} | 39.74 | 214 | 0.654756 |
351e7a65a297b783b9070bac5062380a241ffa32 | 871 | package com.zxf.lib_androidx.model;
import android.text.TextUtils;
import com.zxf.lib_androidx.utils.GsonUtils;
import org.json.JSONObject;
import org.xutils.http.app.ResponseParser;
import org.xutils.http.request.UriRequest;
import java.lang.reflect.Type;
/**
* 解析器,自动解析请求结果
* Created by zxf on 2018/10/10.
*/
public class JsonResponseParser implements ResponseParser {
public void checkResponse(UriRequest request) throws Throwable {
}
@Override
public Object parse(Type resultType, Class<?> resultClass, String result) throws Throwable {
try {
if (TextUtils.isEmpty(result)) {
return null;
}
new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return GsonUtils.parseJSON(result, resultClass);
}
} | 23.540541 | 96 | 0.660161 |
dcec94d147faefaa9d1a715cef7ae83002a12c86 | 12,034 | /*
GNU LESSER GENERAL PUBLIC LICENSE
Copyright (C) 2006 The Lobo Project
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact info: lobochief@users.sourceforge.net
*/
/*
* Created on Aug 28, 2005
*/
package org.cobraparser.html;
import java.awt.Cursor;
import java.net.URL;
import java.util.Optional;
import org.eclipse.jdt.annotation.NonNull;
import org.cobraparser.ua.UserAgentContext;
import org.w3c.dom.html.HTMLCollection;
import org.w3c.dom.html.HTMLElement;
import org.w3c.dom.html.HTMLLinkElement;
/**
* The <code>HtmlRendererContext</code> interface must be implemented in order
* to use the Cobra HTML renderer. An instance of this interface will be called
* back whenever the renderer needs to perform an action that it is not designed
* to know how to perform on its own, e.g. opening a browser window or a context
* menu. In many ways this interface parallers the Javascript
* <code>Window</code> class (which in reality represents a browser frame, not a
* window).
* <p>
* A simple implementation of this interface is provided in
* {@link org.cobraparser.html.test.SimpleHtmlRendererContext
* SimpleHtmlRendererContext}.
*
* @see org.cobraparser.html.gui.HtmlPanel#setDocument(org.w3c.dom.Document,
* HtmlRendererContext)
*/
public interface HtmlRendererContext {
/**
* Navigates to the location given. Implementations should retrieve the URL
* content, parse it and render it.
*
* @param url
* The destination URL.
* @param target
* Same as the target attribute in the HTML anchor tag, i.e. _top,
* _blank, etc.
*/
public void navigate(@NonNull URL url, String target);
/**
* Performs a link click. Implementations should invoke
* {@link #navigate(URL, String)}.
*
* @param linkNode
* The HTML node that was clicked.
* @param url
* The destination URL.
* @param target
* Same as the target attribute in the HTML anchor tag, i.e. _top,
* _blank, etc.
*/
public void linkClicked(HTMLElement linkNode, @NonNull URL url, String target);
/**
* Gets a collection of frames from the document currently in the context.
*/
public HTMLCollection getFrames();
/**
* Submits a HTML form. Note that when the the method is "GET", parameters are
* still expected to be part of <code>formInputs</code>.
*
* @param method
* The request method, GET or POST.
* @param action
* The destination URL.
* @param target
* Same as the target attribute in the FORM tag, i.e. _blank, _top,
* etc.
* @param enctype
* The encoding type.
* @param formInputs
* An array of {@link FormInput} instances.
*/
public void submitForm(String method, @NonNull URL action, String target, String enctype, FormInput[] formInputs);
/**
* Creates a {@link BrowserFrame} instance.
*/
public BrowserFrame createBrowserFrame();
/**
* Gets the user agent context.
*/
public UserAgentContext getUserAgentContext();
/**
* Gets a <code>HtmlObject</code> instance that implements a OBJECT tag from
* HTML.
*
* @param element
* The DOM element for the object, which may either represent an
* OBJECT, EMBED or an APPLET tag.
* @return Implementations of this method must return <code>null</code> if
* they have any problems producing a <code>HtmlObject</code>
* instance. This is particularly true of OBJECT tags, where inner
* HTML of the tag must be rendered if the OBJECT content cannot be
* handled.
*/
public HtmlObject getHtmlObject(HTMLElement element);
/**
* This method is called when a visual element is middle-clicked.
*
* @param element
* The narrowest element enclosing the mouse location.
* @param event
* The mouse event.
* @return The method should return true to continue propagating the event, or
* false to stop propagating it.
*/
public boolean onMiddleClick(HTMLElement element, java.awt.event.MouseEvent event);
/**
* This method is called when a visual element is right-clicked.
*
* @param element
* The narrowest element enclosing the mouse location.
* @param event
* The mouse event.
* @return The method should return true to continue propagating the event, or
* false to stop propagating it.
*/
public boolean onContextMenu(HTMLElement element, java.awt.event.MouseEvent event);
/**
* This method is called when there's a mouse click on an element.
*
* @param element
* The narrowest element enclosing the mouse location.
* @param event
* The mouse event.
* @return The method should return true to continue propagating the event, or
* false to stop propagating it.
*/
public boolean onMouseClick(HTMLElement element, java.awt.event.MouseEvent event);
/**
* This method is called when there's a mouse double-click on an element.
*
* @param element
* The narrowest element enclosing the mouse location.
* @param event
* The mouse event.
* @return The method should return true to continue propagating the event, or
* false to stop propagating it.
*/
public boolean onDoubleClick(HTMLElement element, java.awt.event.MouseEvent event);
/**
* This method is called when the mouse first hovers over an element.
*
* @param element
* The element that the mouse has just entered.
* @param event
* The mouse event.
*/
public void onMouseOver(HTMLElement element, java.awt.event.MouseEvent event);
/**
* This method is called when the mouse no longer hovers a given element.
*
* @param element
* The element that the mouse has just exited.
* @param event
* The mouse event.
*/
public void onMouseOut(HTMLElement element, java.awt.event.MouseEvent event);
/**
* This method should return true if and only if image loading needs to be
* enabled.
*/
public boolean isImageLoadingEnabled();
// ------ Methods useful for Window implementation:
/**
* Opens an alert dialog.
*
* @param message
* Message shown by the dialog.
*/
public void alert(String message);
/**
* Goes to the previous page in the browser's history.
*/
public void back();
/**
* Relinquishes focus.
*/
public void blur();
/**
* Closes the browser window, provided this is allowed for the current
* context.
*/
public void close();
/**
* Opens a confirmation dialog.
*
* @param message
* The message shown by the confirmation dialog.
* @return True if the user selects YES.
*/
public boolean confirm(String message);
/**
* Requests focus for the current window.
*/
public void focus();
/**
* Opens a separate browser window and renders a URL.
*
* @param absoluteUrl
* The URL to be rendered.
* @param windowName
* The name of the new window.
* @param windowFeatures
* The features of the new window (same as in Javascript open
* method).
* @param replace
* @return A new {@link HtmlRendererContext} instance.
* @deprecated Use {@link #open(URL, String, String, boolean)} instead.
*/
@Deprecated
public HtmlRendererContext open(String absoluteUrl, String windowName, String windowFeatures, boolean replace);
/**
* Opens a separate browser window and renders a URL.
*
* @param url
* The URL to be rendered.
* @param windowName
* The name of the new window.
* @param windowFeatures
* The features of the new window (same as in Javascript open
* method).
* @param replace
* @return A new {@link HtmlRendererContext} instance.
*/
public HtmlRendererContext open(@NonNull URL url, String windowName, String windowFeatures, boolean replace);
/**
* Shows a prompt dialog.
*
* @param message
* The message shown by the dialog.
* @param inputDefault
* The default input value.
* @return The user's input value.
*/
public String prompt(String message, String inputDefault);
/**
* Scrolls the client area.
*
* @param x
* Document's x coordinate.
* @param y
* Document's y coordinate.
*/
public void scroll(int x, int y);
/**
* Scrolls the client area.
*
* @param x
* Horizontal pixels to scroll.
* @param y
* Vertical pixels to scroll.
*/
public void scrollBy(int x, int y);
/**
* Resizes the window.
*
* @param width
* The new width.
* @param height
* The new height.
*/
public void resizeTo(int width, int height);
/**
* Resizes the window.
*
* @param byWidth
* The number of pixels to resize the width by.
* @param byHeight
* The number of pixels to resize the height by.
*/
public void resizeBy(int byWidth, int byHeight);
/**
* Gets a value indicating if the window is closed.
*/
public boolean isClosed();
public String getDefaultStatus();
public void setDefaultStatus(String value);
/**
* Gets the window name.
*/
public String getName();
/**
* Gets the parent of the frame/window in the current context.
*/
public HtmlRendererContext getParent();
/**
* Gets the opener of the frame/window in the current context.
*/
public HtmlRendererContext getOpener();
/**
* Sets the context that opened the current frame/window.
*
* @param opener
* A {@link HtmlRendererContext}.
*/
public void setOpener(HtmlRendererContext opener);
/**
* Gets the window status text.
*/
public String getStatus();
/**
* Sets the window status text.
*
* @param message
* A string.
*/
public void setStatus(String message);
/**
* Gets the top-most browser frame/window.
*/
public HtmlRendererContext getTop();
/**
* It should return true if the link provided has been visited.
*/
public boolean isVisitedLink(HTMLLinkElement link);
/**
* Reloads the current document.
*/
public void reload();
/**
* Gets the number of pages in the history list.
*/
public int getHistoryLength();
/**
* Gets the current URL in history.
*/
public String getCurrentURL();
/**
* Gets the next URL in the history.
*/
public Optional<String> getNextURL();
/**
* Gets the previous URL in the history.
*/
public Optional<String> getPreviousURL();
/**
* Goes forward one page.
*/
public void forward();
/**
* Navigates the history according to the given offset.
*
* @param offset
* A positive or negative number. -1 is equivalent to {@link #back()}
* . +1 is equivalent to {@link #forward()}.
*/
public void moveInHistory(int offset);
/**
* Navigates to a URL in the history list.
*/
public void goToHistoryURL(String url);
public void setCursor(Optional<Cursor> cursorOpt);
public void jobsFinished();
public void setJobFinishedHandler(Runnable runnable);
}
| 28.051282 | 116 | 0.649909 |
35b3021c17d8f81e34e0ff78a071e66e60ff0245 | 829 | package com.controllers;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/UpdateCookieLocale")
public class UpdateCookieLocale extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
if (request.getParameter("cookieLocale") != null)
{
Cookie cookie = new Cookie("lang", request.getParameter("cookieLocale"));
response.addCookie(cookie);
}
response.sendRedirect(request.getContextPath());
}
}
| 30.703704 | 116 | 0.763571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.