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
|
---|---|---|---|---|---|
d5fe781485dbe3eb03795244225de5bf893b9913 | 6,414 | /*
* 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.directory.studio.openldap.config.model;
import java.util.ArrayList;
import java.util.List;
/**
* Java bean for the 'OlcSchemaConfig' object class.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
public class OlcSchemaConfig extends OlcConfig
{
/**
* Field for the 'cn' attribute.
*/
@ConfigurationElement(attributeType = "cn", isRdn = true, version="2.4.0")
private List<String> cn = new ArrayList<>();
/**
* Field for the 'olcAttributeTypes' attribute.
*/
@ConfigurationElement(attributeType = "olcAttributeTypes", version="2.4.0")
private List<String> olcAttributeTypes = new ArrayList<>();
/**
* Field for the 'olcDitContentRules' attribute.
*/
@ConfigurationElement(attributeType = "olcDitContentRules", version="2.4.0")
private List<String> olcDitContentRules = new ArrayList<>();
/**
* Field for the 'olcLdapSyntaxes' attribute.
*/
@ConfigurationElement(attributeType = "olcLdapSyntaxes", version="2.4.12")
private List<String> olcLdapSyntaxes = new ArrayList<>();
/**
* Field for the 'olcObjectClasses' attribute.
*/
@ConfigurationElement(attributeType = "olcObjectClasses", version="2.4.0")
private List<String> olcObjectClasses = new ArrayList<>();
/**
* Field for the 'olcObjectIdentifier' attribute.
*/
@ConfigurationElement(attributeType = "olcObjectIdentifier", version="2.4.0")
private List<String> olcObjectIdentifier = new ArrayList<>();
public void clearCn()
{
cn.clear();
}
public void clearOlcAttributeTypes()
{
olcAttributeTypes.clear();
}
public void clearOlcDitContentRules()
{
olcDitContentRules.clear();
}
public void clearOlcLdapSyntaxes()
{
olcLdapSyntaxes.clear();
}
public void clearOlcObjectClasses()
{
olcObjectClasses.clear();
}
public void clearOlcObjectIdentifier()
{
olcObjectIdentifier.clear();
}
/**
* @param strings
*/
public void addCn( String... strings )
{
for ( String string : strings )
{
cn.add( string );
}
}
/**
* @param strings
*/
public void addOlcAttributeTypes( String... strings )
{
for ( String string : strings )
{
olcAttributeTypes.add( string );
}
}
/**
* @param strings
*/
public void addOlcDitContentRules( String... strings )
{
for ( String string : strings )
{
olcDitContentRules.add( string );
}
}
/**
* @param strings
*/
public void addOlcLdapSyntaxes( String... strings )
{
for ( String string : strings )
{
olcLdapSyntaxes.add( string );
}
}
/**
* @param strings
*/
public void addOlcObjectClasses( String... strings )
{
for ( String string : strings )
{
olcObjectClasses.add( string );
}
}
/**
* @param strings
*/
public void addOlcObjectIdentifier( String... strings )
{
for ( String string : strings )
{
olcObjectIdentifier.add( string );
}
}
/**
* @return the cn
*/
public List<String> getCn()
{
return copyListString( cn );
}
/**
* @return the olcAttributeTypes
*/
public List<String> getOlcAttributeTypes()
{
return copyListString( olcAttributeTypes );
}
/**
* @return the olcDitContentRules
*/
public List<String> getOlcDitContentRules()
{
return copyListString( olcDitContentRules );
}
/**
* @return the olcLdapSyntaxes
*/
public List<String> getOlcLdapSyntaxes()
{
return copyListString( olcLdapSyntaxes );
}
/**
* @return the olcObjectClasses
*/
public List<String> getOlcObjectClasses()
{
return copyListString( olcObjectClasses );
}
/**
* @return the olcObjectIdentifier
*/
public List<String> getOlcObjectIdentifier()
{
return copyListString( olcObjectIdentifier );
}
/**
* @param cn the cn to set
*/
public void setCn( List<String> cn )
{
this.cn = copyListString( cn );
}
/**
* @param olcAttributeTypes the olcAttributeTypes to set
*/
public void setOlcAttributeTypes( List<String> olcAttributeTypes )
{
this.olcAttributeTypes = copyListString( olcAttributeTypes );
}
/**
* @param olcDitContentRules the olcDitContentRules to set
*/
public void setOlcDitContentRules( List<String> olcDitContentRules )
{
this.olcDitContentRules = copyListString( olcDitContentRules );
}
/**
* @param olcLdapSyntaxes the olcLdapSyntaxes to set
*/
public void setOlcLdapSyntaxes( List<String> olcLdapSyntaxes )
{
this.olcLdapSyntaxes = copyListString( olcLdapSyntaxes );
}
/**
* @param olcObjectClasses the olcObjectClasses to set
*/
public void setOlcObjectClasses( List<String> olcObjectClasses )
{
this.olcObjectClasses = copyListString( olcObjectClasses );
}
/**
* @param olcObjectIdentifier the olcObjectIdentifier to set
*/
public void setOlcObjectIdentifier( List<String> olcObjectIdentifier )
{
this.olcObjectIdentifier = copyListString( olcObjectIdentifier );
}
}
| 22.426573 | 81 | 0.614437 |
38b98d50a5eced6ff54750daaf0e421cbe3eb522 | 746 | /** Write a program to input a number and check if it's magic or not */
import java.util.*;
public class Magic {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter the number");
int num = in.nextInt();
int sum = sumOfDigits(num);
while(sum>9){
num = sum;
sum = sumOfDigits(num);
}
if( sum==1 )
System.out.println("Number is a magic number.");
else
System.out.println("Number isn't a magic number.");
}
public static int sumOfDigits(int num){
int sum=0;
while(num!=0){
sum += num%10;
num/=10;
}
return sum;
}
}
| 27.62963 | 71 | 0.520107 |
cd31c90d9ef32b18be2ce484559ec290b665f770 | 866 | /*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.internal.util.privilegedactions;
import java.lang.reflect.Constructor;
import java.security.PrivilegedAction;
/**
* Returns the declared constructors of the specified class.
*
* @author Gunnar Morling
*/
public final class GetDeclaredConstructors implements PrivilegedAction<Constructor<?>[]> {
private final Class<?> clazz;
public static GetDeclaredConstructors action(Class<?> clazz) {
return new GetDeclaredConstructors( clazz );
}
private GetDeclaredConstructors(Class<?> clazz) {
this.clazz = clazz;
}
@Override
public Constructor<?>[] run() {
return clazz.getDeclaredConstructors();
}
}
| 26.242424 | 98 | 0.754042 |
e7c43bd9935a217d4147f3dc8f6f3f21b40919dc | 1,788 | package org.javaboy.vhr.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.javaboy.vhr.model.RespBean;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 验证码过滤器
*/
@Component
public class VerifyCodeConfig extends GenericFilterBean {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
//登录请求
if("POST".equals(request.getMethod())&&"/doLogin".equals(request.getServletPath())){
String code = request.getParameter("code");
String vercode = (String)request.getSession().getAttribute("ver_code");
if(code==null||"".equals(code)||!vercode.toLowerCase().equals(code.toLowerCase())){
//验证码不正确
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.write(new ObjectMapper().writeValueAsString(RespBean.error("验证码填写错误!")));
out.flush();
out.close();
return;
}else {
filterChain.doFilter(request,response);
}
}else {
filterChain.doFilter(request,response);
}
}
}
| 37.25 | 152 | 0.689038 |
dbe10b0afed312dc081e59914015d129f7ff413e | 291 | package edu.nyu.tandon.dss;
import edu.nyu.tandon.dss.entity.Broker;
import edu.nyu.tandon.dss.entity.Node;
import edu.nyu.tandon.dss.entity.Request;
/**
* @author [email protected]
*/
public interface DispatchingStrategy {
Node selectNode(Broker broker, Request request);
}
| 22.384615 | 52 | 0.762887 |
ce736ba59a6cefb5f2e0ae56b91e0d9353286df7 | 407 | package com.c0124.k9.c0124.exception;
public class GetPublicKeyFailedException extends SCPGPException {
private static final long serialVersionUID = 864141243739755680L;
public final com.c0124.GetPublicKeyResultEnum errorCode;
public GetPublicKeyFailedException(String message, com.c0124.GetPublicKeyResultEnum errorCode) {
super(message);
this.errorCode = errorCode;
}
}
| 33.916667 | 100 | 0.776413 |
17f6b7dfc1c3899f1d84be7c17de7ac3cdf77166 | 2,377 | /***********************************************************************************************************************
* Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu)
*
* 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 eu.stratosphere.runtime.io.api;
import java.io.IOException;
import eu.stratosphere.nephele.event.task.AbstractTaskEvent;
import eu.stratosphere.nephele.event.task.EventListener;
/**
*
*/
public interface ReaderBase {
boolean isInputClosed();
/**
* Subscribes the listener object to receive events of the given type.
*
* @param eventListener
* the listener object to register
* @param eventType
* the type of event to register the listener for
*/
void subscribeToEvent(EventListener eventListener, Class<? extends AbstractTaskEvent> eventType);
/**
* Removes the subscription for events of the given type for the listener object.
*
* @param eventListener
* the listener object to cancel the subscription for
* @param eventType
* the type of the event to cancel the subscription for
*/
void unsubscribeFromEvent(final EventListener eventListener, final Class<? extends AbstractTaskEvent> eventType);
/**
* Publishes an event.
*
* @param event
* the event to be published
* @throws IOException
* thrown if an error occurs while transmitting the event
* @throws InterruptedException
* thrown if the thread is interrupted while waiting for the event to be published
*/
void publishEvent(AbstractTaskEvent event) throws IOException, InterruptedException;
void setIterative(int numEventsUntilEndOfSuperstep);
void startNextSuperstep();
boolean hasReachedEndOfSuperstep();
}
| 34.955882 | 120 | 0.662179 |
ee5baa3e51d4a37e164d0eeddd3effbe6f49e0ee | 678 | package com.arrow.pegasus.dashboard.repo;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.arrow.pegasus.dashboard.data.Container;
@Repository
public interface ContainerRepository extends ContainerRepositoryExtension, MongoRepository<Container, String> {
// public Container findByNameAndUserId(String name, String userId);
public Container findByName(String name);
// public List<Container> findByUserId(String userId);
public List<Container> findByBoardId(String Id);
public Container findByDescription(String description);
} | 32.285714 | 112 | 0.784661 |
db515d65d30f985097ca6d34e58eb58e78ff0c0c | 223 | package com.dcxiaolou.tinyJD.manage.mapper;
import com.dcxiaolou.tinyJD.bean.PmsSkuSaleAttrValue;
import tk.mybatis.mapper.common.Mapper;
public interface PmsSkuSaleAttrValueMapper extends Mapper<PmsSkuSaleAttrValue> {
}
| 27.875 | 80 | 0.847534 |
56d6aff2974be08fbabed6fa8d2174ddcabbdaf8 | 5,049 | package org.multiverse.stms.gamma.benchmarks;
import org.benchy.BenchyUtils;
import org.junit.Ignore;
import org.junit.Test;
import org.multiverse.MultiverseConstants;
import org.multiverse.stms.gamma.GammaStm;
import org.multiverse.stms.gamma.transactionalobjects.GammaTxnLong;
import org.multiverse.utils.ToolUnsafe;
import sun.misc.Unsafe;
@Ignore
public class BasicPerformanceDriver {
public static void main(String[] args) {
BasicPerformanceDriver driver = new BasicPerformanceDriver();
driver.casPerformance();
}
@Test
public void test() {
GammaStm stm = new GammaStm();
GammaTxnLong ref = new GammaTxnLong(stm);
final long transactionCount = 1000 * 1000 * 1000;
final long startMs = System.currentTimeMillis();
for (long k = 0; k < transactionCount; k++) {
ref.arriveAndLock(1, MultiverseConstants.LOCKMODE_EXCLUSIVE);
//ref.orec = 0;
ref.departAfterUpdateAndUnlock();
}
long durationMs = System.currentTimeMillis() - startMs;
String s = BenchyUtils.operationsPerSecondPerThreadAsString(transactionCount, durationMs, 1);
System.out.printf("Performance is %s transactions/second/thread\n", s);
}
@Test
public void casPerformance() {
final long transactionCount = 1000 * 1000 * 1000;
final long startMs = System.currentTimeMillis();
Cas cas = new Cas();
final long t = transactionCount / 10;
for (long k = 0; k < t; k++) {
cas.atomicInc();
cas.atomicInc();
cas.atomicInc();
cas.atomicInc();
cas.atomicInc();
cas.atomicInc();
cas.atomicInc();
cas.atomicInc();
cas.atomicInc();
cas.atomicInc();
}
long durationMs = System.currentTimeMillis() - startMs;
String s = BenchyUtils.operationsPerSecondPerThreadAsString(transactionCount, durationMs, 1);
System.out.printf("Performance is %s transactions/second/thread\n", s);
}
@Test
public void volatileWritePerformance() {
final long transactionCount = 1000 * 1000 * 1000;
final long startMs = System.currentTimeMillis();
final Cas cas = new Cas();
final long t = transactionCount / 10;
for (long k = 0; k < t; k++) {
cas.volatile_value++;
cas.volatile_value++;
cas.volatile_value++;
cas.volatile_value++;
cas.volatile_value++;
cas.volatile_value++;
cas.volatile_value++;
cas.volatile_value++;
cas.volatile_value++;
cas.volatile_value++;
}
long durationMs = System.currentTimeMillis() - startMs;
String s = BenchyUtils.operationsPerSecondPerThreadAsString(transactionCount, durationMs, 1);
System.out.printf("Performance is %s transactions/second/thread\n", s);
}
@Test
public void basicWritePerformance() {
final long transactionCount = 1000 * 1000 * 1000;
final long startMs = System.currentTimeMillis();
final Cas cas = new Cas();
for (long k = 0; k < transactionCount; k++) {
cas.volatile_value++;//lock
cas.volatile_value++;//version
cas.volatile_value++;//value
cas.volatile_value++;//unlock
}
long durationMs = System.currentTimeMillis() - startMs;
String s = BenchyUtils.operationsPerSecondPerThreadAsString(transactionCount, durationMs, 1);
System.out.printf("Performance is %s transactions/second/thread\n", s);
}
@Test
public void basicWritePerformanceWithNonVolatileVersionAndValue() {
final long transactionCount = 1000 * 1000 * 1000;
final long startMs = System.currentTimeMillis();
final Cas cas = new Cas();
for (long k = 0; k < transactionCount; k++) {
cas.volatile_value++;//lock
cas.value++;//version
cas.value++;//value
cas.volatile_value++;//unlock
}
long durationMs = System.currentTimeMillis() - startMs;
String s = BenchyUtils.operationsPerSecondPerThreadAsString(transactionCount, durationMs, 1);
System.out.printf("Performance is %s transactions/second/thread\n", s);
}
class Cas {
protected final Unsafe ___unsafe = ToolUnsafe.getUnsafe();
protected final long valueOffset;
{
try {
valueOffset = ___unsafe.objectFieldOffset(
Cas.class.getDeclaredField("volatile_value"));
} catch (Exception ex) {
throw new Error(ex);
}
}
volatile long volatile_value;
long value;
void atomicInc() {
final long oldValue = volatile_value;
final long newValue = oldValue + 1;
___unsafe.compareAndSwapLong(this, valueOffset, oldValue, newValue);
}
}
}
| 30.233533 | 101 | 0.609031 |
6bc991d5f76606de6140e2b9d479d2adcf0ea99c | 5,811 | /*******************************************************************************
* Copyright 2015 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.rzo.yajsw.os.ms.win.w32;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executor;
import org.rzo.yajsw.os.Mouse;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.jna.platform.win32.BaseTSD.ULONG_PTR;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinDef.LRESULT;
import com.sun.jna.platform.win32.WinDef.POINT;
import com.sun.jna.platform.win32.WinDef.WPARAM;
import com.sun.jna.platform.win32.WinUser.HHOOK;
import com.sun.jna.platform.win32.WinUser.HOOKPROC;
import com.sun.jna.platform.win32.WinUser.MSG;
// TODO: Auto-generated Javadoc
/**
* The Class WindowsXPKeyboard.
*/
public class WindowsXPMouse implements Mouse
{
public final User32 USER32INST;
public final Kernel32 KERNEL32INST;
public WindowsXPMouse()
{
if (!Platform.isWindows())
{
throw new UnsupportedOperationException(
"Not supported on this platform.");
}
USER32INST = User32.INSTANCE;
KERNEL32INST = Kernel32.INSTANCE;
mouseHook = hookTheMouse();
Native.setProtected(true);
}
public static LowLevelMouseProc mouseHook;
public static Runnable action;
public static Mouse instance;
public HHOOK hhk;
public Thread thrd;
public boolean threadFinish = true;
public boolean isHooked = false;
public static final int WM_MOUSEMOVE = 512;
public static final int WM_LBUTTONDOWN = 513;
public static final int WM_LBUTTONUP = 514;
public static final int WM_RBUTTONDOWN = 516;
public static final int WM_RBUTTONUP = 517;
public static final int WM_MBUTTONDOWN = 519;
public static final int WM_MBUTTONUP = 520;
public static Mouse instance()
{
if (instance == null)
instance = new WindowsXPMouse();
return instance;
}
public synchronized void unregisterMouseUpListner()
{
if (thrd == null)
return;
// System.out.println("unregister ");
threadFinish = true;
if (thrd.isAlive())
{
thrd.interrupt();
thrd = null;
}
isHooked = false;
}
public boolean isIsHooked()
{
return isHooked;
}
public synchronized void registerMouseUpListner(Runnable action,
Executor executor)
{
if (thrd != null)
return;
this.action = action;
thrd = new Thread(new Runnable()
{
public void run()
{
try
{
if (!isHooked)
{
hhk = USER32INST.SetWindowsHookEx(14,
(HOOKPROC) mouseHook,
KERNEL32INST.GetModuleHandle(null), 0);
isHooked = true;
MSG msg = new MSG();
while ((USER32INST.GetMessage(msg, null, 0, 0)) != 0)
{
System.out.println("got message");
USER32INST.TranslateMessage(msg);
USER32INST.DispatchMessage(msg);
System.out.print(isHooked);
if (!isHooked)
break;
}
}
else
System.out.println("The Hook is already installed.");
}
catch (Exception e)
{
System.err.println(e.getMessage());
System.err.println("Caught exception in MouseHook!");
}
// System.out.println("terminated ");
USER32INST.UnhookWindowsHookEx(hhk);
hhk = null;
}
}, "Named thread");
threadFinish = false;
thrd.start();
}
private interface LowLevelMouseProc extends HOOKPROC
{
LRESULT callback(int nCode, WPARAM wParam, MOUSEHOOKSTRUCT lParam);
}
public LowLevelMouseProc hookTheMouse()
{
return new LowLevelMouseProc()
{
public LRESULT callback(int nCode, WPARAM wParam,
MOUSEHOOKSTRUCT info)
{
LRESULT result = USER32INST.CallNextHookEx(hhk, nCode, wParam,
new WinDef.LPARAM(Pointer.nativeValue(info.getPointer())));
if (nCode >= 0)
{
int action = wParam.intValue();
// System.out.println(action);
switch (action)
{
case WM_LBUTTONDOWN:
// do stuff
break;
case WM_RBUTTONDOWN:
WindowsXPMouse.action.run();
break;
case WM_MBUTTONDOWN:
// do other stuff
break;
case WM_LBUTTONUP:
WindowsXPMouse.action.run();
break;
case WM_MOUSEMOVE:
break;
default:
break;
}
/**************************** DO NOT CHANGE, this code unhooks mouse *********************************/
if (threadFinish == true)
{
// System.out.println("post quit");
USER32INST.PostQuitMessage(0);
}
/*************************** END OF UNCHANGABLE *******************************************************/
}
return result;
}
};
}
public static class MOUSEHOOKSTRUCT extends Structure
{
public static class ByReference extends MOUSEHOOKSTRUCT implements
Structure.ByReference
{
};
public POINT pt;
public HWND hwnd;
public int wHitTestCode;
public ULONG_PTR dwExtraInfo;
@Override
protected List getFieldOrder()
{
return Arrays.asList(new String[] { "pt", "hwnd", "wHitTestCode",
"dwExtraInfo" });
}
}
public static void main(String[] args)
{
}
}
| 25.047414 | 109 | 0.652728 |
e6222d205e7207c74c02757b740f9ed4de235f6c | 175 | package cc.bitky.featurelab.casperlab.tools.modelmapper.resp;
import lombok.Data;
/**
* @author liMingLiang
* @date 2019-05-03
*/
@Data
public class ModelMapperResp {
}
| 13.461538 | 61 | 0.731429 |
fc0be6af6332fd32dd35200ed6e95db8b74ed760 | 620 | package org.v8LogScanner.cmdScanner;
import org.v8LogScanner.cmdAppl.CmdCommand;
import org.v8LogScanner.rgx.RegExp;
import org.v8LogScanner.rgx.ScanProfile;
public class CmdResetAll implements CmdCommand {
public String getTip() {
return "";
}
public void execute() {
V8LogScannerAppl appl = V8LogScannerAppl.instance();
ScanProfile.RgxOpTypes opType = appl.profile.getRgxOp();
appl.clientsManager.reset();
appl.profile = appl.clientsManager.localClient().getProfile();
appl.profile.setRgxOp(opType);
appl.profile.addRegExp(new RegExp());
}
}
| 28.181818 | 70 | 0.701613 |
80e2f9cc6738a605fa37c0dd8acc97bb1dc7343c | 1,462 | package com.nuven.socketio.androidchat.controller;
import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Uri;
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
import com.nuven.socketio.androidchat.model.ChatUser;
import com.nuven.socketio.androidchat.model.Constants;
import io.socket.client.IO;
import io.socket.client.Socket;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ChatApplication extends Application {
public static Uri link;
public static String mUsername;
public static String mPrivUsername;
public static String mPrivSocketId;
public static List<ChatUser> chatUsers= new ArrayList<>();
@Override
public void onCreate() {
super.onCreate();
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
}
private Socket mSocket;
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
public boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
}
| 26.107143 | 102 | 0.722982 |
8ae86708652b64f1fa591671c59e92240508e93b | 685 | package com.poterliu.bigdemo.service.impl;
import com.poterliu.bigdemo.mapper.UserMapper;
import com.poterliu.bigdemo.model.User;
import com.poterliu.bigdemo.service.UserService;
public class UserServiceImpl implements UserService {
private UserMapper userMapper;
@Override
public User login(User user) {
userMapper.getUserByName(user.getName());
return null;
}
@Override
public User updateUser(User user) {
userMapper.updateUser(user);
return null;
}
@Override
public User addUser(User user) {
userMapper.addUser(user);
return null;
}
@Override
public void deleteUserById(String id) {
userMapper.deleteUser(id);
}
}
| 20.147059 | 54 | 0.724088 |
6c4fad79e3d3fc1fa96cd6463fda1935270ff87a | 995 | /*
Problem Name: 690. Employee Importance
Problem Link: https://leetcode.com/problems/employee-importance/
*/
/*
// Definition for Employee.
class Employee {
public int id;
public int importance;
public List<Integer> subordinates;
};
*/
class Solution {
public int getImportance(List<Employee> employees, int id) {
Queue<Employee> q = new LinkedList<Employee>();
int imp = 0;
for(int i=0;i<employees.size();i++)
if(employees.get(i).id == id){
q.add(employees.get(i));
break;
}
while(!q.isEmpty()){
Employee emp = q.remove();
imp += emp.importance;
List<Integer> e = emp.subordinates;
for(int i=0;i<e.size();i++){
for(int j=0;j<employees.size();j++){
if(employees.get(j).id == e.get(i))
q.add(employees.get(j));
}
}
}
return imp;
}
}
| 26.184211 | 64 | 0.507538 |
59a0c9ef3291ffb7f9a296cb7739a9534601676f | 521 | /*
* Copyright (c) 2016 Yahoo Inc.
* Licensed under the terms of the Apache version 2.0 license.
* See LICENSE file for terms.
*/
package com.yahoo.yqlplus.engine.java;
import com.yahoo.yqlplus.engine.api.Record;
import java.util.Iterator;
public class Records {
static int getRecordSize(Record record) {
Iterator<String> iter = record.getFieldNames().iterator();
int num = 0;
while (iter.hasNext()) {
num++;
iter.next();
}
return num;
}
}
| 20.84 | 66 | 0.618042 |
d12e904e72bef027c1fc26aa443cf18a0d6ce7e8 | 2,427 | package org.gradle.test.performance.mediummonolithicjavaproject.p124;
import org.gradle.test.performance.mediummonolithicjavaproject.p123.Production2471;
import org.gradle.test.performance.mediummonolithicjavaproject.p123.Production2475;
import org.gradle.test.performance.mediummonolithicjavaproject.p123.Production2479;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test2480 {
Production2480 objectUnderTest = new Production2480();
@Test
public void testProperty0() {
Production2471 value = new Production2471();
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
Production2475 value = new Production2475();
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
Production2479 value = new Production2479();
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
} | 29.240964 | 83 | 0.678204 |
8744332fbd0f51e6a6e142985af94dc42b5ff427 | 4,336 | /*
* Copyright @ 2015 AT&T
*
* 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.jitsi.hammer;
/**
* The class contains an number of information about the host server.
*
* @author Thomas Kuntz
*/
public class HostInfo
{
/**
* The domain name of the XMPP server.
*/
private String XMPPdomain;
private String ProxyXMPPdomain;
/**
* The hostname used to access the XMPP server.
*/
private String XMPPhost;
private String ProxyXMPPhost;
/**
* The hostname used by the XMPP server (used to access to the MUC).
*/
private String MUCdomain;
private String ProxyMUCdomain;
/**
* The name of the MUC room that we'll use.
*/
private String roomName;
/**
* The port used by the XMPP server.
*/
private int port;
/**
* Instantiates a new <tt>HostInfo</tt> instance with default attribut.
*/
public HostInfo() {}
/**
* @arg XMPPdomain the domain name of the XMPP server.
* @arg XMPPhost the hostname of the XMPP server
* @arg port the port number of the XMPP server
* @arg MUCdomain the domain of the MUC server
* @arg roomName the room name used for the MUC
* Instantiates a new <tt>HostInfo</tt> instance
* with all the informations needed.
*/
public HostInfo(
String XMPPdomain,
String XMPPhost,
int port,
String MUCdomain,
String roomName)
{
this.XMPPdomain = XMPPdomain;
this.port = port;
this.XMPPhost = XMPPhost;
this.MUCdomain = MUCdomain;
this.roomName = roomName;
}
public HostInfo(
String XMPPdomain,
String ProxyXMPPdomain,
String XMPPhost,
String ProxyXMPPhost,
int port,
String MUCdomain,
String ProxyMUCdomain,
String roomName)
{
this.XMPPdomain = XMPPdomain;
this.ProxyXMPPdomain = ProxyXMPPdomain;
this.port = port;
this.XMPPhost = XMPPhost;
this.ProxyXMPPhost = ProxyXMPPhost;
this.MUCdomain = MUCdomain;
this.ProxyMUCdomain = ProxyMUCdomain;
this.roomName = roomName;
}
/**
* Get the domain of the XMPP server of this <tt>HostInfo</tt>
* (in lower case).
* @return the domain of the XMPP server (in lower case).
*/
public String getXMPPDomain()
{
return this.XMPPdomain.toLowerCase();
}
public String getXMPPProxy(){
return this.ProxyXMPPdomain.toLowerCase();
}
/**
* Get the domain of the MUC server of this <tt>HostInfo</tt>
* (in lower case).
* @return the domain of the MUC server (in lower case).
*/
public String getMUCDomain()
{
return this.MUCdomain.toLowerCase();
}
public String getProxyMUCDomain()
{
return this.ProxyMUCdomain.toLowerCase();
}
/**
* Get the hostname of the XMPP server of this <tt>HostInfo</tt>
* (in lower case).
* @return the hostname of the XMPP server (in lower case).
*/
public String getXMPPHostname()
{
return this.XMPPhost.toLowerCase();
}
public String getProxyXMPPHostname()
{
return this.ProxyXMPPhost.toLowerCase();
}
/**
* Get the room name (to access a MUC) of this <tt>HostInfo</tt>
* (in lower case).
* @return the room name of a MUC (in lower case).
*/
public String getRoomName()
{
return this.roomName.toLowerCase();
}
/**
* Get the port number of the XMPP server of this <tt>HostInfo</tt>.
* @return the port number of the XMPP server.
*/
public int getPort()
{
return this.port;
}
}
| 26.120482 | 76 | 0.605858 |
9076921315d93d1cd5b58af0491041382f303194 | 420 | package com.ragavan;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
public class DiscoveryServerApplicationWAR extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(DiscoveryServerApplicationJAR.class);
}
}
| 32.307692 | 86 | 0.857143 |
de84d011f7cf2df07eb7b7d5e5711cc4add42de7 | 16,816 | package cn.edu.hust.engine.api;
import cn.edu.hust.engine.utils.Bytes;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* ClassFile结构定义:
* <p>
* 若用u1,u2,u4,u8分别代表1,2,4,8字节无符号整数,则ClassFile(可形式上)定义如下
* <p>
* cp_info {
* u1 tag;
* u1 info[];
* }
* <p>
* field_info {
* u2 access_flags;
* u2 name_index;
* u2 descriptor_index;
* u2 attributes_count;
* attribute_info attributes[attributes_count];
* }
* <p>
* method_info {
* u2 access_flags;
* u2 name_index;
* u2 descriptor_index;
* u2 attributes_count;
* attribute_info attributes[attributes_count];
* }
* <p>
* attribute_info {
* u2 attribute_name_index;
* u4 attribute_length;
* u1 info[attribute_length];
* }
* <p>
* ClassFile {
* u4 magic;
* u2 minor_version;
* u2 major_version;
* constant_pool_zone {
* u2 constant_pool_count;
* cp_info constant_pool[constant_pool_count-1];
* }
* u2 access_flags;
* u2 this_class;
* u2 super_class;
* interfaces_zone {
* u2 interfaces_count;
* u2 interfaces[interfaces_count];
* }
* fields_zone {
* u2 fields_count;
* field_info fields[fields_count];
* }
* methods_zone {
* u2 methods_count;
* method_info methods[methods_count];
* }
* attributes_zone {
* u2 attributes_count;
* attribute_info attributes[attributes_count];
* }
* }
*/
public class ClassFile {
private static final int MAGIC_START_OFFSET = 0;
private static final int MINOR_VERSION_START_OFFSET = 4;
private static final int MAJOR_VERSION_START_OFFSET = 6;
private static final int CONSTANT_POOL_SIZE_OFFSET = 8;
private static final int CONSTANT_POOL_START_OFFSET = 10;
/**
* 从class文件转的byte数组中读取前4个字节转换成long即魔数
*
* @param data class文件转的数组,下通
*
* @return 魔数
*/
public static long getMagic( byte[] data ) {
return Bytes.toLong(data, MAGIC_START_OFFSET);
}
/**
* 从class文件转的byte数组中从第4个字节开始(前4个是魔数),读取两个字节为次版本号
*
* @param data
*
* @return 次版本号
*/
public static int getMinorVersion( byte[] data ) {
return Bytes.toInt(data, MINOR_VERSION_START_OFFSET);
}
/**
* @param data
*
* @return
*
* @code 参见getMinorVersion
*/
public static int getMajorVersion( byte[] data ) {
return Bytes.toInt(data, MAJOR_VERSION_START_OFFSET);
}
public static int getConstantPoolSize( byte[] data ) {
return Bytes.toInt(data, CONSTANT_POOL_SIZE_OFFSET);
}
public static int[] getConstantPool( byte[] data ) {
// 常量池始于文件的第11字节处,其元素数个数(用U2格式)存放在文件的第9-10字节处,共为c-1个
int constantPoolSize = getConstantPoolSize(data);
int tag = data[CONSTANT_POOL_START_OFFSET];
// 常量池里的项在data数组中的索引位置
int constantOffset = CONSTANT_POOL_START_OFFSET;
// 数组的值是常量在data数组中的offset
int[] pool = new int[constantPoolSize];
int i = 1;
while (i < constantPoolSize) {
pool[i] = constantOffset;
switch (tag) {
case Tag.CONSTANT_UTF8:
// 吃掉一个CONSTANT_UTF8类型的常量,索引位置指向下一个常量的开始
// 以下每个case都类似
// poolIndex加上utf8字符串长度再加3(tag+length)
constantOffset += Bytes.toInt(data, constantOffset + 1) + 3;
break;
case Tag.CONSTANT_STRING:
case Tag.CONSTANT_CLASS:
case Tag.CONSTANT_METHOD_TYPE:// TODO 暂时未分析
constantOffset += 1 + 2;
break;
case Tag.CONSTANT_METHOD_HANDLE:// TODO 暂时未分析
constantOffset += 1 + 1 + 2;
break;
case Tag.CONSTANT_INTEGER:
case Tag.CONSTANT_FLOAT:
case Tag.CONSTANT_FIELD_REF:
case Tag.CONSTANT_METHOD_REF:
case Tag.CONSTANT_INTERFACE_METHOD_REF:
case Tag.CONSTANT_NAME_AND_TYPE:
case Tag.CONSTANT_INVOKE_DYNAMIC:// TODO 暂时未分析
constantOffset += 1 + 2 + 2;
break;
case Tag.CONSTANT_LONG:
case Tag.CONSTANT_DOUBLE:
constantOffset += 1 + 4 + 4;
// double和long会占用两个常量池slot,故跳过一个常量池项
i++;
break;
}
// 获取下一个常量的tag
tag = data[constantOffset];
i++;
}
// 这里将常量的个数存放在常量池第一个位置出,因为这个位置没有存放常量项
pool[0] = constantOffset;
// pool常量池记录的是某个常量在data字节数组里的offset
return pool;
}
public static int getAccessFlagsToInt(byte [] data, int [] pool){
return Bytes.toInt(data, pool[0]);
}
/**
* access_flags是16位通过不同位上是否有1来决定是否有权限的
* 故通过与操作可以得到分别有什么权限
*
* @param access_flags
* @param keyValues
*
* @return
*/
public static String getAccessFlagSet( int access_flags, KeyValue[] keyValues) {
String accessFlags = "";
KeyValue[] values = keyValues;
for (KeyValue value : values) {
if ((value.value & access_flags) == value.value) {
if (!accessFlags.isEmpty())
accessFlags += " ";
accessFlags += value.key;
}
}
return accessFlags;
}
/**
* pool[0]存储的是常量池的总长度即pool[0]后就是access_flags的offset
* 再往后顺延两个就是this_class的offset
* 再往后顺延两个就是super_class的offset
* 再往后顺延两个就是interface_count
*
* @param data
* @param pool 常量池里存的是每个类型常量开始的offset
*
* @return
*/
public static int getThisClassIndexInConstantPool( byte[] data, int[] pool ) {
// pool[0] + 2 是this_class在data里的offset
// 其值是常量池一个索引指向一个CONSTANT_CLASS类型
return Bytes.toInt(data, pool[0] + 2);
}
/**
* getThisClassOffset方法返回this_class在data数组中的offset,该值又是一个指针指向常量池
* 中的一项该项是constant_utf8,可从中获取类名的字面量
*
* @param data
* @param pool
*
* @return
*/
public static String getThisClassName( byte[] data, int[] pool ) {
// index表示在常量池中的索引
// 从data数组中获取this_class的索引,即pool的数组下标
int thisClassIndex = getThisClassIndexInConstantPool(data, pool);
// offset表示在data数组中的偏移量
int thisClassOffset = pool[thisClassIndex];
int utf8Index = Bytes.toInt(data, thisClassOffset + 1);
if (utf8Index > 0) {
int classNameStartOffset = pool[utf8Index];
return new String(data, classNameStartOffset + 3, Bytes.toInt(data, classNameStartOffset + 1));
}
return "";
}
public static int getSuperClassIndexInConstantPool( byte[] data, int[] pool ) {
return Bytes.toInt(data, pool[0] + 4);
}
/**
* @param data
* @param pool
*
* @return 例:java/lang/Object
*/
public static String getSuperClassName( byte[] data, int[] pool ) {
int superClassIndex = getSuperClassIndexInConstantPool(data, pool);
int superClassOffset = pool[superClassIndex];
int utf8Index = Bytes.toInt(data, superClassOffset + 1);
if (utf8Index > 0) {
int superClassStartOffset = pool[utf8Index];
return new String(data, superClassStartOffset + 3, Bytes.toInt(data, superClassStartOffset + 1));
}
return "";
}
/**
* @param data
* @param pool
*
* @return interface_count开始的offset
*/
public static int getInterfaceZoneOffset( byte[] data, int[] pool ) {
// 每个2分别代表吃掉access_flags,this_class,super_class
return pool[0] + 2 + 2 + 2;
}
/**
* pool[0]表示常量池结束的offset
* 向后移6表示super_class结束的offset
* 向后移2表示interface_count结束的offset
* 每个interface占用2个字节,所以乘以2
*
* @param data
* @param pool
*
* @return fields_count开始的offset
*/
public static int getFieldsZoneOffset( byte[] data, int[] pool ) {
// 2代表吃掉interface_count
// 每个interface占用2个字节故再加上一个乘法
return getInterfaceZoneOffset(data, pool) + 2 + Bytes.toInt(data, getInterfaceZoneOffset(data, pool)) * 2;
}
public static int getMethodsZoneOffset( byte[] data, int[] pool ) {
/*
* field_info {
* u2 access_flags;
* u2 name_index;
* u2 descriptor_index;
* u2 attributes_count;
* attribute_info attributes[attributes_count];
* }
* attribute_info {
* u2 attribute_name_index;
* u4 attribute_length;
* u1 info[attribute_length];
* }
*/
int fieldsZoneIndex = getFieldsZoneOffset(data, pool);
int fieldsCount = Bytes.toInt(data, fieldsZoneIndex);
int methodsZoneOffset = fieldsZoneIndex + 2;
for (int i = 0; i < fieldsCount; i++) {
// 分别吃掉field_info结构里的access_flags,name_index,descriptor_index,attributes_count
methodsZoneOffset += 2 + 2 + 2 + 2;
int fieldsAttributesCount = Bytes.toInt(data, methodsZoneOffset - 2);
for (int j = 0; j < fieldsAttributesCount; j++) {
methodsZoneOffset += Bytes.toInt(data, methodsZoneOffset + 2, 4) + 2 + 4;
}
}
return methodsZoneOffset;
}
public static int getAttributesZoneOffset( byte[] data, int[] pool ) {
/*
* method_info {
* u2 access_flags;
* u2 name_index;
* u2 descriptor_index;
* u2 attributes_count;
* attribute_info attributes[attributes_count];
* }
* attribute_info {
* u2 attribute_name_index;
* u4 attribute_length;
* u1 info[attribute_length];
* }
*/
int methodsZoneOffset = getMethodsZoneOffset(data, pool);
int methodsCount = Bytes.toInt(data, methodsZoneOffset);
int attributeZoneOffset = methodsZoneOffset + 2;
for (int i = 0; i < methodsCount; i++) {
attributeZoneOffset += 2 + 2 + 2 + 2;
int attributesCount = Bytes.toInt(data, attributeZoneOffset - 2);
for (int j = 0; j < attributesCount; j++) {
attributeZoneOffset += Bytes.toInt(data, attributeZoneOffset + 2, 4) + 2 + 4;
}
}
return attributeZoneOffset;
}
public static void printConstantPool( byte[] data, int[] pool ) {
System.out.println("==========constant pool===========");
int poolSize = pool.length;
int tag = 0;
int offset = 0;
System.out.println("size is : " + poolSize);
System.out.printf("%4s|%5s|%2s|%s\n", "oft", "idx", "tg", "content");
System.out.println("---------------------");
for (int index = 1; index < poolSize; index++) {
offset = pool[index];
tag = data[offset];
switch (tag) {
case Tag.CONSTANT_UTF8:
String utf8InfoStr = new String(data, offset + 3, Bytes.toInt(data, offset + 1));
// data中从0开始计算
System.out.printf("%04d|#%04d|%02d|%s\n", offset, index, tag, utf8InfoStr);
break;
case Tag.CONSTANT_CLASS:
case Tag.CONSTANT_STRING:
case Tag.CONSTANT_METHOD_TYPE:
int indexInConstant = Bytes.toInt(data, offset + 1);
System.out.printf("%04d|#%04d|%02d|#%04d\n", offset, index, tag, indexInConstant);
break;
case Tag.CONSTANT_METHOD_HANDLE:
int kind = data[offset + 1];
int reference_index = Bytes.toInt(data, offset + 2);
System.out.printf("%04d|#%04d|%02d|%02d|#%04d\n", offset, index, tag, kind, reference_index);
break;
case Tag.CONSTANT_INTEGER:
int h2 = Bytes.toInt(data, offset + 1);
int l2 = Bytes.toInt(data, offset + 3);
int v4 = (h2 << 16) + l2;
System.out.printf("%04d|#%04d|%02d|%d(h2:%04d, l2:%04d)\n", offset, index, tag, v4, h2, l2);
break;
case Tag.CONSTANT_FLOAT:
h2 = Bytes.toInt(data, offset + 1);
l2 = Bytes.toInt(data, offset + 3);
float f4 = 0;
try {
f4 = Bytes.toFloat(data, offset + 1);
} catch (Exception e) {
}
System.out.printf("%04d|#%04d|%02d|%ff(h2:%04d,l2:%04d)\n", offset, index, tag, f4, h2, l2);
case Tag.CONSTANT_FIELD_REF:
case Tag.CONSTANT_METHOD_REF:
case Tag.CONSTANT_INTERFACE_METHOD_REF:
case Tag.CONSTANT_NAME_AND_TYPE:
case Tag.CONSTANT_INVOKE_DYNAMIC:
long index1 = Bytes.toInt(data, offset + 1);
long index2 = Bytes.toInt(data, offset + 3);
System.out.printf("%04d|#%04d|%02d|#%04d,#%04d\n", offset, index, tag, index1, index2);
break;
case Tag.CONSTANT_LONG:
long h4 = Bytes.toLong(data, offset + 1, 4);
long l4 = Bytes.toLong(data, offset + 5, 4);
long v8 = (h4 << 32) + l4;
System.out.printf("%04d|#%04d|%02d|%dl(h4:%08d,l4:%08d)\n", offset, index, tag, v8, h4, l4);
// 吃掉一个空白的slot
index++;
break;
case Tag.CONSTANT_DOUBLE:
h4 = Bytes.toLong(data, offset + 1, 4);
l4 = Bytes.toLong(data, offset + 5, 4);
double d8 = 0;
try {
d8 = Bytes.toDouble(data, offset + 1);
} catch (Exception e) {
}
System.out.printf("%04d|#%04d|%02d|%fd(h4:%d,l4:%d)\n", d8, index, tag, d8, h4, l4);
index++;
break;
}
}
}
/**
* @return 属性名字与属性对象映射
*/
public static Map<String, Attribute> getAttributesMap( byte[] data, int[] pool, int zoneOffset) {
Map<String, Attribute> attributesMap = new HashMap<>();
Map<String, Integer> offsetsMap = getAttributesOffsetMap(data, pool, zoneOffset);
for (String name: offsetsMap.keySet()) {
attributesMap.put(name, Attribute.getInstance(name, data, pool, offsetsMap.get(name)));
}
return attributesMap;
}
/**
* @param zoneOffset-属性区段偏移(实际指向attributes_count处)(下同)
* @return 属性名字与属性偏移映射
*/
public static Map<String, Integer> getAttributesOffsetMap(byte[] data, int[] pool, int zoneOffset) {
Map<String, Integer> offsetsMap = new HashMap<String, Integer>();
int c = Bytes.toInt(data, zoneOffset);
for (int i = zoneOffset + 2, j = 0; j < c; i += Bytes.toInt(data, i + 2, 4) + 6, j++) {
int p = pool[Bytes.toInt(data, i)];
String name = new String(data, p + 3, Bytes.toInt(data, p + 1));
offsetsMap.put(name, i);
}
return offsetsMap;
}
public static void main( String[] args ) throws IOException {
// FileInputStream stream = new FileInputStream(new File("/Users/yuyu/Desktop/MyFreeDemo/ClassParsers/test/C.class"));
FileInputStream stream = new FileInputStream(new File("/Users/yuyu/Desktop/space/my/ClassParserRefactor/out/production/ClassParserRefactor/cn/edu/hust/classparser/api/ClassFile.class"));
byte[] data = new byte[1024 * 10];
stream.read(data);
long magic = ClassFile.getMagic(data);
int minor = ClassFile.getMinorVersion(data);
int major = ClassFile.getMajorVersion(data);
int poolSize = ClassFile.getConstantPoolSize(data);
// System.out.println(magic);
// System.out.println(minor);
// System.out.println(major);
// System.out.println(poolSize);
int[] pool = ClassFile.getConstantPool(data);
// System.out.println(pool[0]);
//
// for (int poolItem :
// pool) {
// System.out.println(poolItem);
// }
// String thisClassName = ClassFile.getThisClassName(data, ClassFile.getConstantPool(data));
// System.out.println(thisClassName);
// String superClass = ClassFile.getSuperClassName(data, ClassFile.getConstantPool(data));
// System.out.println(superClass);
// String accessFlags = ClassFile.getAccessFlagSet(data, pool);
// System.out.println(accessFlags);
ClassFile.printConstantPool(data, pool);
}
}
| 34.743802 | 194 | 0.561311 |
f0ca76675c2ef15b8acfd22d9820357a27a60281 | 13,778 | /*
* Copyright 2010-2016 Sander Verdonschot <sander.verdonschot at 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 rectangularcartogram.algos.ga;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import rectangularcartogram.algos.ga.crossover.UniformCrossover;
import rectangularcartogram.algos.ga.mutation.BitFlipMutation;
import rectangularcartogram.algos.ga.selection.RankSelection;
import rectangularcartogram.data.Pair;
import rectangularcartogram.data.RegularEdgeColoring;
import rectangularcartogram.data.RegularEdgeLabeling;
import rectangularcartogram.data.graph.CycleGraph;
import rectangularcartogram.data.graph.Edge;
import rectangularcartogram.data.graph.Graph;
import rectangularcartogram.data.graph.Graph.Labeling;
import rectangularcartogram.data.graph.Vertex;
import rectangularcartogram.exceptions.IncorrectGraphException;
import rectangularcartogram.measures.QualityMeasure;
public class SimpleLabelingGA extends GeneticAlgorithm {
private CycleGraph graph;
private QualityMeasure measure;
private HashMap<Edge, Labeling> fixed;
public SimpleLabelingGA(Graph graph, QualityMeasure measure) {
this.graph = new CycleGraph(graph);
this.measure = measure;
setElitistFraction(0.01);
setCrossoverChance(0.8);
setCrossover(new UniformCrossover());
setMutation(new BitFlipMutation(0.01));
setSelection(new RankSelection(0.8));
fixEdges();
}
public void initialize(int populationSize) {
initialize(graph.getEdges().size() - fixed.size(), populationSize);
}
public void findBestLabeling(int maxGenerations) throws IncorrectGraphException {
Pair<boolean[], Double> result = getBestAfter(maxGenerations);
if (result.getSecond() >= graph.getVertices().size()) {
System.out.println("All " + graph.getVertices().size() + " vertex constraints satisfied.");
} else {
System.out.println(result.getSecond() + " of " + graph.getVertices().size() + " vertex constraints satisfied.");
}
RegularEdgeLabeling bestLabeling = new RegularEdgeLabeling(getColoring(result.getFirst()));
System.out.println("Quality: " + measure.getQuality(bestLabeling));
graph.setRegularEdgeLabeling(bestLabeling);
}
@Override
protected double computeQuality(boolean[] individual) {
// return the number of vertices that satisfy the local constraints
// if all vertices satisfy the constraints, add the quality obtained from the quality measure
RegularEdgeColoring coloring = getColoring(individual);
int correctVertices = 4;
for (Vertex vertex : graph.getVertices()) {
if (!graph.getExteriorVertices().contains(vertex)) {
if (checkVertexLabeling(vertex, coloring)) {
correctVertices++;
}
}
}
if (correctVertices == graph.getVertices().size()) {
try {
double q = measure.getQuality(new RegularEdgeLabeling(coloring));
if (measure.higherIsBetter()) {
return correctVertices + q;
} else {
return correctVertices + 1 / q;
}
} catch (IncorrectGraphException ex) {
Logger.getLogger(SimpleLabelingGA.class.getName()).log(Level.SEVERE, null, ex);
return correctVertices;
}
} else {
return correctVertices;
}
}
private void fixEdges() {
fixed = new HashMap<Edge, Labeling>(graph.getEdges().size());
List<Pair<Vertex, Edge>> boundary = new ArrayList<Pair<Vertex, Edge>>();
for (Edge edge : graph.getEdges()) {
boolean aIsNS = edge.getVA() == graph.getVN() || edge.getVA() == graph.getVS();
boolean bIsNS = edge.getVB() == graph.getVN() || edge.getVB() == graph.getVS();
boolean aIsEW = edge.getVA() == graph.getVE() || edge.getVA() == graph.getVW();
boolean bIsEW = edge.getVB() == graph.getVE() || edge.getVB() == graph.getVW();
boolean incidentNS = aIsNS || bIsNS;
boolean incidentEW = aIsEW || bIsEW;
if (incidentNS && !incidentEW) {
fixed.put(edge, Labeling.RED);
} else if (incidentEW && !incidentNS) {
fixed.put(edge, Labeling.BLUE);
} else if (incidentNS && incidentEW) { // Exterior edge
fixed.put(edge, Labeling.NONE);
}
// Add the non-exterior vertex to the boundary for further processing
if (!(incidentEW && incidentNS)) {
if (aIsNS || aIsEW) {
boundary.add(new Pair<Vertex, Edge>(edge.getVB(), edge));
} else if (bIsNS || bIsEW) {
boundary.add(new Pair<Vertex, Edge>(edge.getVA(), edge));
}
}
}
for (Pair<Vertex, Edge> p : boundary) {
Vertex v = p.getFirst();
List<Edge> edges = v.getEdges();
int exteriorEdgeIndex = edges.indexOf(p.getSecond());
Labeling l = fixed.get(p.getSecond());
if (edges.size() == 4) {
// All edges around this vertex are fixed
fixed.put(edges.get((exteriorEdgeIndex + 2) % 4), l);
}
Labeling ll = (l == Labeling.RED ? Labeling.BLUE : Labeling.RED);
fixed.put(edges.get((exteriorEdgeIndex + 1) % edges.size()), ll);
fixed.put(edges.get((exteriorEdgeIndex - 1 + edges.size()) % edges.size()), ll);
}
}
private RegularEdgeColoring getColoring(boolean[] individual) {
RegularEdgeColoring coloring = new RegularEdgeColoring(graph);
int i = 0;
for (Edge edge : graph.getEdges()) {
Labeling l = fixed.get(edge);
if (l == null) {
coloring.put(edge, individual[i] ? Labeling.RED : Labeling.BLUE);
i++;
} else {
coloring.put(edge, l);
}
}
return coloring;
}
/**
* A vertex should have blue incoming edges, red outgoing edges, blue outgoing edges and red incoming edges, in clockwise direction around itself.
* This method only checks the colours, ignoring the directions. Unlabeled edges are ignored as well.
* @param v
* @return true if it is possible to label the unlabeled edges such that this vertex satisfies constraint C1 with respect to the edge colours (not the orientations)
*/
private boolean checkVertexLabeling(Vertex v, HashMap<Edge, Labeling> labeling) {
List<Edge> edges = v.getEdges();
// If there are less than 4 edges, this is never going to work
if (edges.size() < 4) {
return false;
}
// See what intervals we have
List<Labeling> intervals = new ArrayList<Labeling>();
int redIntervals = 0;
int blueIntervals = 0;
int unlabeledIntervals = 0;
for (Edge edge : edges) {
Labeling label = labeling.get(edge);
// Skip this label if it fits into the current interval
if (intervals.isEmpty() || label != intervals.get(intervals.size() - 1)) {
intervals.add(label);
switch (label) {
case RED:
redIntervals++;
break;
case BLUE:
blueIntervals++;
break;
case NONE:
unlabeledIntervals++;
break;
}
}
}
// If the first and last interval are the same, merge them
if (intervals.size() > 1 && intervals.get(0) == intervals.get(intervals.size() - 1)) {
intervals.remove(intervals.size() - 1);
switch (intervals.get(0)) {
case RED:
redIntervals--;
break;
case BLUE:
blueIntervals--;
break;
case NONE:
unlabeledIntervals--;
break;
}
}
if (redIntervals == 0 && blueIntervals == 0) {
// All unlabeled edges, so they can still be labeled correctly
return true;
} else if (blueIntervals == 0) {
// If there is only one interval of red edges, we need at least three unlabeled edges
if (redIntervals == 1) {
int nUnlabeled = 0;
for (Edge edge : edges) {
Labeling label = labeling.get(edge);
if (label == Labeling.NONE) {
nUnlabeled++;
}
}
return nUnlabeled >= 3;
} else {
// If there are more, there must also be at least two unlabeled intervals separating them
// so these can be coloured blue, which satiesfies the vertex constraint
return true;
}
} else if (redIntervals == 0) {
// If there is only one interval of blue edges, we need at least three unlabeled edges
if (blueIntervals == 1) {
int nUnlabeled = 0;
for (Edge edge : edges) {
Labeling label = labeling.get(edge);
if (label == Labeling.NONE) {
nUnlabeled++;
}
}
return nUnlabeled >= 3;
} else {
// If there are more, there must also be at least two unlabeled intervals separating them
// so these can be coloured red, which satiesfies the vertex constraint
return true;
}
} else {
// We have both red and blue intervals
if (unlabeledIntervals == 0) {
return redIntervals == 2 && blueIntervals == 2;
} else if (redIntervals == 1 && blueIntervals == 1) {
int nUnlabeled = 0;
for (Edge edge : edges) {
Labeling label = labeling.get(edge);
if (label == Labeling.NONE) {
nUnlabeled++;
}
}
if (unlabeledIntervals == 1) {
// if there are at least two unlabeled edges between the red and blue intervals, it can be labeled, otherwise it's impossible
return nUnlabeled >= 2;
} else {
// there are two unlabeled intervals between the red and blue intervals,
// if one of those has at least 2 edges, we can separate the intervals and create a valid labeling
// this is the case iff there are at least 3 unlabeled edges
return nUnlabeled >= 3;
}
} else if (redIntervals == 1 || blueIntervals == 1) {
// the multiple intervals of the other colour must be separated on one side by a NONE interval. This interval can be given the opposite colour, to produce a valid labeling
return true;
} else {
// let's see what we have left if we omit the unlabeled edges
List<Labeling> realIntervals = new ArrayList<Labeling>();
int realRedIntervals = 0;
int realBlueIntervals = 0;
for (Edge edge : edges) {
Labeling label = labeling.get(edge);
// Skip this label if it fits into the current interval or if its NONE
if (label != Labeling.NONE && (realIntervals.isEmpty() || label != realIntervals.get(realIntervals.size() - 1))) {
realIntervals.add(label);
switch (label) {
case RED:
realRedIntervals++;
break;
case BLUE:
realBlueIntervals++;
break;
}
}
}
// If the first and last interval are the same, merge them
if (realIntervals.size() > 1 && realIntervals.get(0) == realIntervals.get(realIntervals.size() - 1)) {
realIntervals.remove(realIntervals.size() - 1);
switch (realIntervals.get(0)) {
case RED:
realRedIntervals--;
break;
case BLUE:
realBlueIntervals--;
break;
}
}
if (realRedIntervals <= 2 && realBlueIntervals <= 2) {
return true;
} else {
return false;
}
}
}
}
}
| 38.811268 | 187 | 0.543911 |
c24aaadda88b9c58d73130db83af2ab11fce85d2 | 373 | package org.logstash.secret.password;
import java.util.Optional;
/**
* A validator interface for password validation policies.
*/
public interface Validator {
/**
* Validates the input password.
* @param password a password string
* @return optional empty if succeeds or value for reasoning.
*/
Optional<String> validate(String password);
}
| 23.3125 | 65 | 0.705094 |
9c8d9da229f2b5af4560b168ef924e278b73e28a | 3,156 | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.resource;
import java.util.List;
import java.util.concurrent.Callable;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
/**
* A {@code VersionStrategy} that handles unique, static, application-wide version strings
* as prefixes in the request path.
*
* <p>Enables inserting a unique and static version String (e.g. reduced SHA, version name,
* release date) at the beginning of resource paths so that when a new version of the application
* is released, clients are forced to reload application resources.
*
* <p>This is useful when changing resource names is not an option (e.g. when
* using JavaScript module loaders). If that's not the case, the use of
* {@link ContentBasedVersionStrategy} provides more optimal performance since
* version is generated on a per-resource basis: only actually modified resources are reloaded
* by the client.
*
* @author Brian Clozel
* @author Sam Brannen
* @since 4.1
* @see VersionResourceResolver
*/
public class FixedVersionStrategy extends AbstractVersionStrategy {
private final String version;
/**
* Create a new FixedVersionStrategy with the given version string.
* @param fixedVersion the fixed version string to use
*/
public FixedVersionStrategy(String fixedVersion) {
Assert.hasText(fixedVersion, "version must not be null or empty");
this.version = fixedVersion.endsWith("/") ? fixedVersion : fixedVersion + "/";
}
/**
* Create a new FixedVersionStrategy and get the version string to use by
* calling the given {@code Callable} instance.
*/
public FixedVersionStrategy(Callable<String> versionInitializer) throws Exception {
String fixedVersion = versionInitializer.call();
Assert.hasText(fixedVersion, "version must not be null or empty");
this.version = fixedVersion.endsWith("/") ? fixedVersion : fixedVersion + "/";
}
@Override
public String extractVersionFromPath(String requestPath) {
return extractVersionAsPrefix(requestPath, this.version);
}
@Override
public String deleteVersionFromPath(String requestPath, String candidateVersion) {
return deleteVersionAsPrefix(requestPath, candidateVersion);
}
@Override
public boolean resourceVersionMatches(Resource baseResource, String candidateVersion) {
return this.version.equals(candidateVersion);
}
@Override
public String addVersionToUrl(String baseUrl, List<? extends Resource> locations,
ResourceResolverChain chain) {
return addVersionAsPrefix(baseUrl, this.version);
}
}
| 35.066667 | 97 | 0.764259 |
7e4cf58b49134ee13d1e11f41efbf37d209687a9 | 499 | package com.github.sofn.trpc.core;
import com.github.sofn.trpc.core.config.RegistryConfig;
import com.github.sofn.trpc.core.monitor.RegistryConfigListener;
import java.util.List;
/**
* Authors: sofn
* Version: 1.0 Created at 2016-09-20 22:40.
*/
public abstract class AbstractMonitor {
/**
* 返回remoteKey下所有节点数据,并监控变化
*
* @param monitor 消息listener
* @return 返回现在的数据
*/
public abstract List<RegistryConfig> monitorRemoteKey(RegistryConfigListener monitor);
}
| 21.695652 | 90 | 0.719439 |
6074531f93ac73a605d3ef32a92b2615233af95f | 3,141 | package com.shenjinxiang.spb.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @Author: ShenJinXiang
* @Date: 2020/4/20 09:00
*/
@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {
@Autowired
private RedisTemplate redisTemplate;
@Override
@Bean
public KeyGenerator keyGenerator() {
// 当没有指定缓存的 key时来根据类名、方法名和方法参数来生成key
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName())
.append(':')
.append(method.getName());
if (params.length > 0) {
sb.append('[');
for (Object obj : params) {
if (obj != null) {
sb.append(obj.toString());
}
}
sb.append(']');
}
return sb.toString();
};
}
@Override
@Bean
public CacheManager cacheManager() {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getKeySerializer())) //key序列化方式
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer())) //value序列化方式
.entryTtl(Duration.ofHours(1)) // 设置缓存有效期一小时
.disableCachingNullValues(); //不缓存null值
// 设置一个初始化的缓存名称set集合
Set<String> cacheNames = new HashSet<>();
cacheNames.add("user");
// 对每个缓存名称应用不同的配置,自定义过期时间
Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
configMap.put("user", redisCacheConfiguration.entryTtl(Duration.ofSeconds(120)));
RedisCacheManager redisCacheManager = RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory()))
// .builder(redisConnectionFactory)
.cacheDefaults(redisCacheConfiguration)
// .initialCacheNames(cacheNames)
// .withInitialCacheConfigurations(configMap)
.build();
return redisCacheManager;
}
}
| 37.392857 | 148 | 0.675899 |
585db3cac331515f35fd3b895d1d1d7d06a11c0c | 17,745 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
package com.microsoft.azure.toolkit.lib.appservice.function;
import com.azure.resourcemanager.appservice.AppServiceManager;
import com.azure.resourcemanager.appservice.models.FunctionApp.DefinitionStages;
import com.azure.resourcemanager.appservice.models.FunctionApp.Update;
import com.azure.resourcemanager.appservice.models.WebSiteBase;
import com.microsoft.azure.toolkit.lib.appservice.model.DiagnosticConfig;
import com.microsoft.azure.toolkit.lib.appservice.model.DockerConfiguration;
import com.microsoft.azure.toolkit.lib.appservice.model.JavaVersion;
import com.microsoft.azure.toolkit.lib.appservice.model.OperatingSystem;
import com.microsoft.azure.toolkit.lib.appservice.model.Runtime;
import com.microsoft.azure.toolkit.lib.appservice.plan.AppServicePlan;
import com.microsoft.azure.toolkit.lib.appservice.utils.AppServiceUtils;
import com.microsoft.azure.toolkit.lib.common.bundle.AzureString;
import com.microsoft.azure.toolkit.lib.common.exception.AzureToolkitRuntimeException;
import com.microsoft.azure.toolkit.lib.common.messager.AzureMessager;
import com.microsoft.azure.toolkit.lib.common.messager.IAzureMessager;
import com.microsoft.azure.toolkit.lib.common.model.AzResource;
import com.microsoft.azure.toolkit.lib.common.operation.AzureOperation;
import com.microsoft.azure.toolkit.lib.common.telemetry.AzureTelemetry;
import lombok.Data;
import lombok.Getter;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
public class FunctionAppDraft extends FunctionApp implements AzResource.Draft<FunctionApp, WebSiteBase> {
private static final String CREATE_NEW_FUNCTION_APP = "isCreateNewFunctionApp";
public static final String FUNCTIONS_EXTENSION_VERSION = "FUNCTIONS_EXTENSION_VERSION";
public static final JavaVersion DEFAULT_JAVA_VERSION = JavaVersion.JAVA_8;
private static final String UNSUPPORTED_OPERATING_SYSTEM = "Unsupported operating system %s";
public static final String CAN_NOT_UPDATE_EXISTING_APP_SERVICE_OS = "Can not update the operation system of an existing app";
public static final String APP_SETTING_MACHINEKEY_DECRYPTION_KEY = "MACHINEKEY_DecryptionKey";
public static final String APP_SETTING_WEBSITES_ENABLE_APP_SERVICE_STORAGE = "WEBSITES_ENABLE_APP_SERVICE_STORAGE";
public static final String APP_SETTING_DISABLE_WEBSITES_APP_SERVICE_STORAGE = "false";
public static final String APP_SETTING_FUNCTION_APP_EDIT_MODE = "FUNCTION_APP_EDIT_MODE";
public static final String APP_SETTING_FUNCTION_APP_EDIT_MODE_READONLY = "readOnly";
@Getter
@Nullable
private final FunctionApp origin;
@Nullable
private Config config;
FunctionAppDraft(@Nonnull String name, @Nonnull String resourceGroupName, @Nonnull FunctionAppModule module) {
super(name, resourceGroupName, module);
this.origin = null;
}
FunctionAppDraft(@Nonnull FunctionApp origin) {
super(origin);
this.origin = origin;
}
@Override
public void reset() {
this.config = null;
}
@Nonnull
private synchronized Config ensureConfig() {
this.config = Optional.ofNullable(this.config).orElseGet(Config::new);
return this.config;
}
@Nonnull
@Override
@AzureOperation(
name = "resource.create_resource.resource|type",
params = {"this.getName()", "this.getResourceTypeName()"},
type = AzureOperation.Type.SERVICE)
public com.azure.resourcemanager.appservice.models.FunctionApp createResourceInAzure() {
AzureTelemetry.getContext().getActionParent().setProperty(CREATE_NEW_FUNCTION_APP, String.valueOf(true));
final String name = getName();
final Runtime newRuntime = Objects.requireNonNull(getRuntime(), "'runtime' is required to create a Azure Functions app");
final AppServicePlan newPlan = Objects.requireNonNull(getAppServicePlan(), "'service plan' is required to create a Azure Functions app");
final Map<String, String> newAppSettings = getAppSettings();
final DiagnosticConfig newDiagnosticConfig = getDiagnosticConfig();
final String funcExtVersion = Optional.ofNullable(newAppSettings).map(map -> map.get(FUNCTIONS_EXTENSION_VERSION)).orElse(null);
final AppServiceManager manager = Objects.requireNonNull(this.getParent().getRemote());
final DefinitionStages.Blank blank = manager.functionApps().define(name);
final DefinitionStages.WithCreate withCreate;
if (newRuntime.getOperatingSystem() == OperatingSystem.LINUX) {
withCreate = blank.withExistingLinuxAppServicePlan(newPlan.getRemote())
.withExistingResourceGroup(getResourceGroupName())
.withBuiltInImage(AppServiceUtils.toFunctionRuntimeStack(newRuntime, funcExtVersion));
} else if (newRuntime.getOperatingSystem() == OperatingSystem.WINDOWS) {
withCreate = (DefinitionStages.WithCreate) blank
.withExistingAppServicePlan(newPlan.getRemote())
.withExistingResourceGroup(getResourceGroupName())
.withJavaVersion(AppServiceUtils.toJavaVersion(newRuntime.getJavaVersion()))
.withWebContainer(null);
} else if (newRuntime.getOperatingSystem() == OperatingSystem.DOCKER) {
withCreate = createDockerApp(blank, newPlan);
} else {
throw new AzureToolkitRuntimeException(String.format(UNSUPPORTED_OPERATING_SYSTEM, newRuntime.getOperatingSystem()));
}
if (MapUtils.isNotEmpty(newAppSettings)) {
// todo: support remove app settings
withCreate.withAppSettings(newAppSettings);
}
if (Objects.nonNull(newDiagnosticConfig)) {
AppServiceUtils.defineDiagnosticConfigurationForWebAppBase(withCreate, newDiagnosticConfig);
}
final IAzureMessager messager = AzureMessager.getMessager();
messager.info(AzureString.format("Start creating Azure Functions app({0})...", name));
com.azure.resourcemanager.appservice.models.FunctionApp functionApp = (com.azure.resourcemanager.appservice.models.FunctionApp)
Objects.requireNonNull(this.doModify(() -> withCreate.create(), Status.CREATING));
messager.success(AzureString.format("Azure Functions app({0}) is successfully created", name));
return functionApp;
}
DefinitionStages.WithCreate createDockerApp(@Nonnull DefinitionStages.Blank blank, @Nonnull AppServicePlan plan) {
// check service plan, consumption is not supported
final String message = "Docker configuration is required to create a docker based Azure Functions app";
final DockerConfiguration config = Objects.requireNonNull(this.getDockerConfiguration(), message);
if (StringUtils.equalsIgnoreCase(plan.getPricingTier().getTier(), "Dynamic")) {
throw new AzureToolkitRuntimeException("Docker function is not supported in consumption service plan");
}
final DefinitionStages.WithDockerContainerImage withLinuxAppFramework = blank
.withExistingLinuxAppServicePlan(plan.getRemote())
.withExistingResourceGroup(getResourceGroupName());
final DefinitionStages.WithCreate draft;
if (StringUtils.isAllEmpty(config.getUserName(), config.getPassword())) {
draft = withLinuxAppFramework
.withPublicDockerHubImage(config.getImage());
} else if (StringUtils.isEmpty(config.getRegistryUrl())) {
draft = withLinuxAppFramework
.withPrivateDockerHubImage(config.getImage())
.withCredentials(config.getUserName(), config.getPassword());
} else {
draft = withLinuxAppFramework
.withPrivateRegistryImage(config.getImage(), config.getRegistryUrl())
.withCredentials(config.getUserName(), config.getPassword());
}
final String decryptionKey = generateDecryptionKey();
return (DefinitionStages.WithCreate) draft.withAppSetting(APP_SETTING_MACHINEKEY_DECRYPTION_KEY, decryptionKey)
.withAppSetting(APP_SETTING_WEBSITES_ENABLE_APP_SERVICE_STORAGE, APP_SETTING_DISABLE_WEBSITES_APP_SERVICE_STORAGE)
.withAppSetting(APP_SETTING_FUNCTION_APP_EDIT_MODE, APP_SETTING_FUNCTION_APP_EDIT_MODE_READONLY);
}
protected String generateDecryptionKey() {
// Refers https://github.com/Azure/azure-cli/blob/dev/src/azure-cli/azure/cli/command_modules/appservice/custom.py#L2300
return Hex.encodeHexString(RandomUtils.nextBytes(32)).toUpperCase();
}
@Nonnull
@Override
@AzureOperation(name = "resource.update_resource.resource|type", params = {"this.getName()", "this.getResourceTypeName()"}, type = AzureOperation.Type.SERVICE)
public com.azure.resourcemanager.appservice.models.FunctionApp updateResourceInAzure(@Nonnull WebSiteBase base) {
com.azure.resourcemanager.appservice.models.FunctionApp remote = (com.azure.resourcemanager.appservice.models.FunctionApp) base;
assert origin != null : "updating target is not specified.";
final Map<String, String> settingsToAdd = this.getAppSettings();
final Set<String> settingsToRemove = this.getAppSettingsToRemove();
final DiagnosticConfig newDiagnosticConfig = this.getDiagnosticConfig();
final Runtime newRuntime = this.getRuntime();
final AppServicePlan newPlan = this.getAppServicePlan();
final DockerConfiguration newDockerConfig = getDockerConfiguration();
final Runtime oldRuntime = Objects.requireNonNull(origin.getRuntime());
final AppServicePlan oldPlan = origin.getAppServicePlan();
final boolean planModified = Objects.nonNull(newPlan) && !Objects.equals(newPlan, oldPlan);
final boolean runtimeModified = !oldRuntime.isDocker() && Objects.nonNull(newRuntime) && !Objects.equals(newRuntime, oldRuntime);
final boolean dockerModified = oldRuntime.isDocker() && Objects.nonNull(newDockerConfig);
boolean modified = planModified || runtimeModified || dockerModified ||
MapUtils.isNotEmpty(settingsToAdd) || CollectionUtils.isNotEmpty(settingsToRemove) || Objects.nonNull(newDiagnosticConfig);
final String funcExtVersion = Optional.ofNullable(settingsToAdd).map(map -> map.get(FUNCTIONS_EXTENSION_VERSION)).orElse(null);
if (modified) {
final Update update = remote.update();
Optional.ofNullable(newPlan).ifPresent(p -> updateAppServicePlan(update, p));
Optional.ofNullable(newRuntime).ifPresent(p -> updateRuntime(update, p, funcExtVersion));
Optional.ofNullable(settingsToAdd).ifPresent(update::withAppSettings);
Optional.ofNullable(settingsToRemove).ifPresent(s -> s.forEach(update::withoutAppSetting));
Optional.ofNullable(newDockerConfig).ifPresent(p -> updateDockerConfiguration(update, p));
Optional.ofNullable(newDiagnosticConfig).ifPresent(c -> AppServiceUtils.updateDiagnosticConfigurationForWebAppBase(update, newDiagnosticConfig));
final IAzureMessager messager = AzureMessager.getMessager();
messager.info(AzureString.format("Start updating Azure Functions App({0})...", remote.name()));
remote = update.apply();
messager.success(AzureString.format("Azure Functions App({0}) is successfully updated", remote.name()));
}
return remote;
}
private void updateAppServicePlan(@Nonnull Update update, @Nonnull AppServicePlan newPlan) {
Objects.requireNonNull(newPlan.getRemote(), "Target app service plan doesn't exist");
update.withExistingAppServicePlan(newPlan.getRemote());
}
private void updateRuntime(@Nonnull Update update, @Nonnull Runtime newRuntime, String funcExtVersion) {
final Runtime oldRuntime = Objects.requireNonNull(Objects.requireNonNull(origin).getRuntime());
if (newRuntime.getOperatingSystem() != null && oldRuntime.getOperatingSystem() != newRuntime.getOperatingSystem()) {
throw new AzureToolkitRuntimeException(CAN_NOT_UPDATE_EXISTING_APP_SERVICE_OS);
}
final OperatingSystem operatingSystem = ObjectUtils.firstNonNull(newRuntime.getOperatingSystem(), oldRuntime.getOperatingSystem());
if (operatingSystem == OperatingSystem.LINUX) {
update.withBuiltInImage(AppServiceUtils.toFunctionRuntimeStack(newRuntime, funcExtVersion));
} else if (operatingSystem == OperatingSystem.WINDOWS) {
if (Objects.equals(oldRuntime.getJavaVersion(), JavaVersion.OFF)) {
final JavaVersion javaVersion = Optional.ofNullable(newRuntime.getJavaVersion()).orElse(DEFAULT_JAVA_VERSION);
update.withJavaVersion(AppServiceUtils.toJavaVersion(javaVersion)).withWebContainer(null);
} else if (ObjectUtils.notEqual(newRuntime.getJavaVersion(), JavaVersion.OFF) &&
ObjectUtils.notEqual(newRuntime.getJavaVersion(), oldRuntime.getJavaVersion())) {
update.withJavaVersion(AppServiceUtils.toJavaVersion(newRuntime.getJavaVersion())).withWebContainer(null);
}
} else {
throw new AzureToolkitRuntimeException(String.format(UNSUPPORTED_OPERATING_SYSTEM, newRuntime.getOperatingSystem()));
}
}
private void updateDockerConfiguration(@Nonnull Update update, @Nonnull DockerConfiguration newConfig) {
if (StringUtils.isAllEmpty(newConfig.getUserName(), newConfig.getPassword())) {
update.withPublicDockerHubImage(newConfig.getImage());
} else if (StringUtils.isEmpty(newConfig.getRegistryUrl())) {
update.withPrivateDockerHubImage(newConfig.getImage())
.withCredentials(newConfig.getUserName(), newConfig.getPassword());
} else {
update.withPrivateRegistryImage(newConfig.getImage(), newConfig.getRegistryUrl())
.withCredentials(newConfig.getUserName(), newConfig.getPassword());
}
}
public void setRuntime(Runtime runtime) {
this.ensureConfig().setRuntime(runtime);
}
@Nullable
@Override
public Runtime getRuntime() {
return Optional.ofNullable(config).map(Config::getRuntime).orElseGet(super::getRuntime);
}
public void setAppServicePlan(AppServicePlan plan) {
this.ensureConfig().setPlan(plan);
}
@Nullable
@Override
public AppServicePlan getAppServicePlan() {
return Optional.ofNullable(config).map(Config::getPlan).orElseGet(super::getAppServicePlan);
}
public void setDiagnosticConfig(DiagnosticConfig config) {
this.ensureConfig().setDiagnosticConfig(config);
}
@Nullable
public DiagnosticConfig getDiagnosticConfig() {
return Optional.ofNullable(config).map(Config::getDiagnosticConfig).orElse(null);
}
public void setAppSettings(Map<String, String> appSettings) {
this.ensureConfig().setAppSettings(appSettings);
}
public void setAppSetting(String key, String value) {
this.ensureConfig().getAppSettings().put(key, value);
}
@Nullable
@Override
public Map<String, String> getAppSettings() {
return Optional.ofNullable(config).map(Config::getAppSettings).orElseGet(super::getAppSettings);
}
public void removeAppSetting(String key) {
this.ensureConfig().getAppSettingsToRemove().add(key);
}
@Nullable
public Set<String> getAppSettingsToRemove() {
return Optional.ofNullable(config).map(Config::getAppSettingsToRemove).orElse(new HashSet<>());
}
public void setDockerConfiguration(DockerConfiguration dockerConfiguration) {
this.ensureConfig().setDockerConfiguration(dockerConfiguration);
}
@Nullable
public DockerConfiguration getDockerConfiguration() {
return Optional.ofNullable(config).map(Config::getDockerConfiguration).orElse(null);
}
@Override
public boolean isModified() {
final boolean notModified = Objects.isNull(this.config) ||
Objects.isNull(this.config.getRuntime()) || Objects.equals(this.config.getRuntime(), super.getRuntime()) ||
Objects.isNull(this.config.getPlan()) || Objects.equals(this.config.getPlan(), super.getAppServicePlan()) ||
Objects.isNull(this.config.getDiagnosticConfig()) ||
CollectionUtils.isEmpty(this.config.getAppSettingsToRemove()) ||
Objects.isNull(this.config.getAppSettings()) || Objects.equals(this.config.getAppSettings(), super.getAppSettings()) ||
Objects.isNull(this.config.getDockerConfiguration());
return !notModified;
}
/**
* {@code null} means not modified for properties
*/
@Data
@Nullable
private static class Config {
private Runtime runtime;
private AppServicePlan plan = null;
private DiagnosticConfig diagnosticConfig = null;
private Set<String> appSettingsToRemove = new HashSet<>();
private Map<String, String> appSettings = new HashMap<>();
private DockerConfiguration dockerConfiguration = null;
}
} | 53.772727 | 163 | 0.730121 |
72ddfb3676eff151324dff3de8b9be664eeadec4 | 2,764 | package org.ohdsi.webapi.tagging;
import org.ohdsi.analysis.Utils;
import org.ohdsi.webapi.cohortcharacterization.CcController;
import org.ohdsi.webapi.cohortcharacterization.domain.CohortCharacterizationEntity;
import org.ohdsi.webapi.cohortcharacterization.dto.CcExportDTO;
import org.ohdsi.webapi.cohortcharacterization.dto.CohortCharacterizationDTO;
import org.ohdsi.webapi.cohortcharacterization.repository.CcRepository;
import org.ohdsi.webapi.cohortcharacterization.specification.CohortCharacterizationImpl;
import org.ohdsi.webapi.cohortdefinition.CohortDefinitionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
public class CcTaggingTest extends BaseTaggingTest<CohortCharacterizationDTO, Long> {
private static final String JSON_PATH = "/tagging/characterization.json";
@Autowired
private CcController service;
@Autowired
private CcRepository repository;
@Autowired
private CohortDefinitionRepository cohortRepository;
@Override
public void doCreateInitialData() throws IOException {
String expression = getExpression(getExpressionPath());
CohortCharacterizationImpl characterizationImpl =
Utils.deserialize(expression, CohortCharacterizationImpl.class);
CohortCharacterizationEntity entity = conversionService.convert(characterizationImpl, CohortCharacterizationEntity.class);
CcExportDTO exportDTO = conversionService.convert(entity, CcExportDTO.class);
exportDTO.setName("test dto name");
initialDTO = service.doImport(exportDTO);
}
@Override
protected void doClear() {
repository.deleteAll();
cohortRepository.deleteAll();
}
@Override
protected String getExpressionPath() {
return JSON_PATH;
}
@Override
protected void assignTag(Long id, boolean isPermissionProtected) {
service.assignTag(id, getTag(isPermissionProtected).getId());
}
@Override
protected void unassignTag(Long id, boolean isPermissionProtected) {
service.unassignTag(id, getTag(isPermissionProtected).getId());
}
@Override
protected void assignProtectedTag(Long id, boolean isPermissionProtected) {
service.assignPermissionProtectedTag(id, getTag(isPermissionProtected).getId());
}
@Override
protected void unassignProtectedTag(Long id, boolean isPermissionProtected) {
service.unassignPermissionProtectedTag(id, getTag(isPermissionProtected).getId());
}
@Override
protected CohortCharacterizationDTO getDTO(Long id) {
return service.getDesign(id);
}
@Override
protected Long getId(CohortCharacterizationDTO dto) {
return dto.getId();
}
}
| 34.123457 | 130 | 0.758321 |
ba73d341bacd89019aee39c9eff07542d8cfd149 | 2,804 | package ghidra.app.cmd.data.rtti.gcc.typeinfo;
import ghidra.app.cmd.data.rtti.ClassTypeInfo;
import ghidra.app.cmd.data.rtti.gcc.factory.TypeInfoFactory;
import ghidra.program.model.address.Address;
import ghidra.program.model.data.DataType;
import ghidra.program.model.data.DataTypeComponent;
import ghidra.program.model.data.DataTypeManager;
import ghidra.program.model.data.Structure;
import ghidra.program.model.data.StructureDataType;
import ghidra.program.model.listing.Program;
import static ghidra.app.util.datatype.microsoft.MSDataTypeUtils.getAbsoluteAddress;
/**
* Model for the __pointer_to_member_type_info class.
*/
public final class PointerToMemberTypeInfoModel extends AbstractPBaseTypeInfoModel {
public static final String STRUCTURE_NAME = "__pointer_to_member_type_info";
private static final String DESCRIPTION = "Model for Pointer To Member Type Info";
public static final String ID_STRING = "N10__cxxabiv129__pointer_to_member_type_infoE";
private static final int CONTEXT_ORDINAL = 1;
private DataType typeInfoDataType;
public PointerToMemberTypeInfoModel(Program program, Address address) {
super(program, address);
}
@Override
public String getIdentifier() {
return ID_STRING;
}
/**
* Gets the __pointer_to_member_type_info datatype
*/
@Override
public DataType getDataType() {
if (typeInfoDataType == null) {
typeInfoDataType = getDataType(program.getDataTypeManager());
}
return typeInfoDataType;
}
/**
* Gets the __pointer_to_member_type_info datatype.
* @param dtm
* @return
*/
public static DataType getDataType(DataTypeManager dtm) {
DataType superDt = getPBase(dtm);
DataType existingDt = dtm.getDataType(superDt.getCategoryPath(), STRUCTURE_NAME);
if (existingDt != null && existingDt.getDescription().equals(DESCRIPTION)) {
return existingDt;
}
StructureDataType struct = new StructureDataType(superDt.getCategoryPath(), STRUCTURE_NAME, 0, dtm);
struct.add(superDt, SUPER_NAME, null);
struct.add(ClassTypeInfoModel.getPointer(dtm), "__context", null);
struct.setDescription(DESCRIPTION);
return alignDataType(struct, dtm);
}
/**
* Gets the ClassTypeInfo containing the member being pointed to.
* @return the ClassTypeInfo containing the member being pointed to.
*/
public ClassTypeInfo getContext() {
Structure struct = (Structure) getDataType();
DataTypeComponent comp = struct.getComponent(CONTEXT_ORDINAL);
Address pointee = getAbsoluteAddress(program, address.add(comp.getOffset()));
return (ClassTypeInfo) TypeInfoFactory.getTypeInfo(program, pointee);
}
}
| 36.415584 | 108 | 0.724679 |
f9496250ede6a0158a115ae2b4312e631dcc1a7e | 1,076 | /*
* Copyright © 2014-2017 EntIT Software LLC, a Micro Focus company (L.P.)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.cloudslang.engine.partitions.services;
/**
* Date: 4/27/12
*
*/
public class PartitionUtils {
public String tableName(String groupName, int partition){
return groupName + "_" + partition;
}
public int partitionBefore(int partition, int groupSize) {
return partition == 1? groupSize: partition-1;
}
public int partitionAfter(int partition, int groupSize) {
return partition == groupSize? 1: partition+1;
}
}
| 29.888889 | 75 | 0.728625 |
37cda25cfd1ec56ddbed6cb15efccdb24f12fd18 | 97 | /**
* This package contains Events used by the Alpine event framework.
*/
package alpine.event; | 24.25 | 67 | 0.742268 |
424542186cc89fb1bf74a2505889947b28ee705a | 5,022 | /*
* 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.mycompany.gui;
import com.codename1.charts.ChartComponent;
import com.codename1.charts.ChartComponent;
import com.codename1.charts.models.CategorySeries;
import com.codename1.charts.renderers.DefaultRenderer;
import com.codename1.charts.renderers.SimpleSeriesRenderer;
import com.codename1.charts.util.ColorUtil;
import com.codename1.charts.views.PieChart;
import com.codename1.ui.Form;
import com.codename1.ui.Label;
import com.codename1.ui.TextField;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.util.Resources;
import com.mycompany.services.ServiceQuestion;
import com.mycompany.entities.Question;
import java.util.ArrayList;
/**
*
* @author Lenovo
*/
public class StatQ extends BaseForm {
private ArrayList<Question> questions;
Form current;
public StatQ(Resources res)
{ super.addSideMenu (res);
/**************************/
Label al = new Label("SVT");
Label ed = new Label("POO");
Label st = new Label("MATHS");
Label ph = new Label("PHYSIQUE");
Form f=createPieChartForm();
this.addAll(ed,st,al,ph);
this.add(f);
// this.addSideMenu (res);
/*******************************************************************/
}
/*******************/
/**
* Creates a renderer for the specified colors.
*/
private DefaultRenderer buildCategoryRenderer(int[] colors) {
DefaultRenderer renderer = new DefaultRenderer();
renderer.setLabelsTextSize(50);
renderer.setLegendTextSize(50);
int[] colo = new int[]{ColorUtil.BLACK};
renderer.setMargins(new int[]{20, 30, 15, 0});
for (int color : colors) {
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(color);
renderer.addSeriesRenderer(r);
}
return renderer;
}
/**
* Builds a category series using the provided values.
*
* @param titles the series titles
* @param values the values
* @return the category series
*/
protected CategorySeries buildCategoryDataset(String title, double[] values) {
CategorySeries series = new CategorySeries(title);
series.add("SVT" ,values[0]);
series.add("POO" ,values[1]);
series.add("MATHS" ,values[2]);
series.add("PHYSIQUE" ,values[3]);
return series;
}
public Form createPieChartForm() {
int svt=0;
int phys =0;
int poo=0;
int MATHS=0;
/*String s1="str";
String s2="str";
if(s1.equals(s2))
*/
questions = new ServiceQuestion().afficherQuestion();
for (Question p : questions) {
if(p.getNameT().equals("SVT"))
{
svt ++;
System.out.println("svt"+svt+p.getNameT());
}
else if (p.getNameT().equals("POO"))
{
poo++;
System.out.println("poo"+poo+p.getNameT() );
}
else if (p.getNameT().equals("MATHS"))
{
MATHS++;
System.out.println("MATHS"+MATHS+p.getNameT() );
} else{
phys++;
System.out.println("phys"+phys+p.getNameT());}
}
// Generate the values
// double[] values = new double[]{12, 14, 11, 10, 19};
double[] values = new double[]{svt,poo,MATHS,phys};
// Set up the renderer
int[] colors = new int[]{ColorUtil.BLUE, ColorUtil.GREEN, ColorUtil.MAGENTA, ColorUtil.YELLOW, ColorUtil.CYAN};
DefaultRenderer renderer = buildCategoryRenderer(colors);
renderer.setZoomButtonsVisible(true);
renderer.setZoomEnabled(true);
renderer.setChartTitleTextSize(20);
renderer.setDisplayValues(true);
renderer.setShowLabels(true);
SimpleSeriesRenderer r = renderer.getSeriesRendererAt(0);
r.setGradientEnabled(true);
r.setGradientStart(0, ColorUtil.BLUE);
r.setGradientStop(0, ColorUtil.GREEN);
r.setHighlighted(true);
// Create the chart ... pass the values and renderer to the chart object.
// PieChart chart = new PieChart(buildCategoryDataset("Project budget", values), renderer);
PieChart chart = new PieChart(buildCategoryDataset("Project budget", values), renderer);
// Wrap the chart in a Component so we can add it to a form
ChartComponent c = new ChartComponent(chart);
// Create a form and show it.
Form f = new Form("Budget");
f.setLayout(new BorderLayout());
f.addComponent(BorderLayout.CENTER, c);
return f;
}
/****************/
/*
protected CategorySeries buildCategoryDataset(String title, double[] values) {
CategorySeries series = new CategorySeries(title);
/*
int k = 0;
for (double value : values) {
series.add("Nombre " + ++k, value);
}
*/
/* series.add("non traite" ,values[0]);
series.add("traite" ,values[1]);
return series;
*/
}
| 27.9 | 115 | 0.626842 |
c950ca37502f94483310a79d678d6b3ad5c6d0bb | 3,899 | /*
* Copyright 2015 The CHOReVOLUTION project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.chorevolution.studio.eclipse.core;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.osgi.service.prefs.BackingStoreException;
public class ChorevolutionCorePreferences {
private final String propertyNamespace;
private final IEclipsePreferences preferences;
private ChorevolutionCorePreferences(IProject project, String qualifier, boolean viewMonitor) {
this.propertyNamespace = qualifier + '.';
this.preferences = getEclipsePreferences(project, qualifier, viewMonitor);
}
public static ChorevolutionCorePreferences getProjectOrWorkspacePreferences(IProject project, String qualifier) {
return new ChorevolutionCorePreferences(project, qualifier, false);
}
public static ChorevolutionCorePreferences getProjectOrWorkspacePreferences(IProject project, String qualifier, boolean viewMonitor) {
return new ChorevolutionCorePreferences(project, qualifier, viewMonitor);
}
private IEclipsePreferences getEclipsePreferences(IProject project, String qualifier, boolean viewMonitor) {
if (project != null){
//get project preference
IScopeContext context = new ProjectScope(project);
return context.getNode(qualifier);
}else{
//get workspace preference
if(viewMonitor) {
//get the workbench preferences
return InstanceScope.INSTANCE.getNode("org.eclipse.ui.workbench");
}
else {
//get the instantiated preference
return InstanceScope.INSTANCE.getNode(ChorevolutionCorePlugin.PLUGIN_ID);
}
}
}
public void putString(String key, String value) {
if (key == null || value == null) {
return;
}
try {
this.preferences.put(propertyNamespace + key, value);
this.preferences.flush();
} catch (BackingStoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, ChorevolutionCorePlugin.PLUGIN_ID,
"An error occurred updating preferences", e));
}
}
public void putStringWithoutNamespace(String key, String value) {
if (key == null || value == null) {
return;
}
try {
this.preferences.put(key, value);
this.preferences.flush();
} catch (BackingStoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, ChorevolutionCorePlugin.PLUGIN_ID,
"An error occurred updating preferences", e));
}
}
public void putBoolean(String key, boolean value) {
if (key == null) {
return;
}
try {
this.preferences.putBoolean(propertyNamespace + key, value);
this.preferences.flush();
} catch (BackingStoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, ChorevolutionCorePlugin.PLUGIN_ID,
"An error occurred updating preferences", e));
}
}
public String getString(String key, String defaultValue) {
return this.preferences.get(propertyNamespace + key, defaultValue);
}
public boolean getBoolean(String key, boolean defaultValue) {
return this.preferences.getBoolean(propertyNamespace + key, defaultValue);
}
public IEclipsePreferences getProjectPreferences() {
return this.preferences;
}
}
| 33.612069 | 135 | 0.758656 |
9e823e483b2995dcef307ebebf28da3d22c45cb9 | 667 | package com.italankin.lnch.feature.settings.base;
import com.italankin.lnch.model.repository.prefs.Preferences;
import androidx.annotation.StringRes;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
public abstract class BasePreferenceFragment extends PreferenceFragmentCompat {
@SuppressWarnings("unchecked")
protected <T extends Preference> T findPreference(@StringRes int key) {
return (T) findPreference(getString(key));
}
@SuppressWarnings("unchecked")
protected <T extends Preference> T findPreference(Preferences.Pref<?> pref) {
return (T) findPreference(pref.key());
}
}
| 31.761905 | 81 | 0.766117 |
8c6461b7d35d61665c9c55b4ce3912714122ff9c | 8,023 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.fasterxml.jackson.core.util;
import com.fasterxml.jackson.core.JsonGenerator;
import java.io.IOException;
public class DefaultIndenter extends DefaultPrettyPrinter.NopIndenter
{
public DefaultIndenter()
{
this(" ", SYS_LF);
// 0 0:aload_0
// 1 1:ldc1 #35 <String " ">
// 2 3:getstatic #33 <Field String SYS_LF>
// 3 6:invokespecial #39 <Method void DefaultIndenter(String, String)>
// 4 9:return
}
public DefaultIndenter(String s, String s1)
{
// 0 0:aload_0
// 1 1:invokespecial #46 <Method void DefaultPrettyPrinter$NopIndenter()>
charsPerLevel = s.length();
// 2 4:aload_0
// 3 5:aload_1
// 4 6:invokevirtual #52 <Method int String.length()>
// 5 9:putfield #54 <Field int charsPerLevel>
indents = new char[s.length() * 16];
// 6 12:aload_0
// 7 13:aload_1
// 8 14:invokevirtual #52 <Method int String.length()>
// 9 17:bipush 16
// 10 19:imul
// 11 20:newarray char[]
// 12 22:putfield #56 <Field char[] indents>
int j = 0;
// 13 25:iconst_0
// 14 26:istore 4
for(int i = 0; i < 16; i++)
//* 15 28:iconst_0
//* 16 29:istore_3
//* 17 30:iload_3
//* 18 31:bipush 16
//* 19 33:icmpge 67
{
s.getChars(0, s.length(), indents, j);
// 20 36:aload_1
// 21 37:iconst_0
// 22 38:aload_1
// 23 39:invokevirtual #52 <Method int String.length()>
// 24 42:aload_0
// 25 43:getfield #56 <Field char[] indents>
// 26 46:iload 4
// 27 48:invokevirtual #60 <Method void String.getChars(int, int, char[], int)>
j += s.length();
// 28 51:iload 4
// 29 53:aload_1
// 30 54:invokevirtual #52 <Method int String.length()>
// 31 57:iadd
// 32 58:istore 4
}
// 33 60:iload_3
// 34 61:iconst_1
// 35 62:iadd
// 36 63:istore_3
//* 37 64:goto 30
eol = s1;
// 38 67:aload_0
// 39 68:aload_2
// 40 69:putfield #62 <Field String eol>
// 41 72:return
}
public String getEol()
{
return eol;
// 0 0:aload_0
// 1 1:getfield #62 <Field String eol>
// 2 4:areturn
}
public String getIndent()
{
return new String(indents, 0, charsPerLevel);
// 0 0:new #48 <Class String>
// 1 3:dup
// 2 4:aload_0
// 3 5:getfield #56 <Field char[] indents>
// 4 8:iconst_0
// 5 9:aload_0
// 6 10:getfield #54 <Field int charsPerLevel>
// 7 13:invokespecial #68 <Method void String(char[], int, int)>
// 8 16:areturn
}
public boolean isInline()
{
return false;
// 0 0:iconst_0
// 1 1:ireturn
}
public DefaultIndenter withIndent(String s)
{
if(s.equals(((Object) (getIndent()))))
//* 0 0:aload_1
//* 1 1:aload_0
//* 2 2:invokevirtual #74 <Method String getIndent()>
//* 3 5:invokevirtual #78 <Method boolean String.equals(Object)>
//* 4 8:ifeq 13
return this;
// 5 11:aload_0
// 6 12:areturn
else
return new DefaultIndenter(s, eol);
// 7 13:new #2 <Class DefaultIndenter>
// 8 16:dup
// 9 17:aload_1
// 10 18:aload_0
// 11 19:getfield #62 <Field String eol>
// 12 22:invokespecial #39 <Method void DefaultIndenter(String, String)>
// 13 25:areturn
}
public DefaultIndenter withLinefeed(String s)
{
if(s.equals(((Object) (eol))))
//* 0 0:aload_1
//* 1 1:aload_0
//* 2 2:getfield #62 <Field String eol>
//* 3 5:invokevirtual #78 <Method boolean String.equals(Object)>
//* 4 8:ifeq 13
return this;
// 5 11:aload_0
// 6 12:areturn
else
return new DefaultIndenter(getIndent(), s);
// 7 13:new #2 <Class DefaultIndenter>
// 8 16:dup
// 9 17:aload_0
// 10 18:invokevirtual #74 <Method String getIndent()>
// 11 21:aload_1
// 12 22:invokespecial #39 <Method void DefaultIndenter(String, String)>
// 13 25:areturn
}
public void writeIndentation(JsonGenerator jsongenerator, int i)
throws IOException
{
jsongenerator.writeRaw(eol);
// 0 0:aload_1
// 1 1:aload_0
// 2 2:getfield #62 <Field String eol>
// 3 5:invokevirtual #89 <Method void JsonGenerator.writeRaw(String)>
if(i > 0)
//* 4 8:iload_2
//* 5 9:ifle 63
{
for(i *= charsPerLevel; i > indents.length; i -= indents.length)
//* 6 12:iload_2
//* 7 13:aload_0
//* 8 14:getfield #54 <Field int charsPerLevel>
//* 9 17:imul
//* 10 18:istore_2
//* 11 19:iload_2
//* 12 20:aload_0
//* 13 21:getfield #56 <Field char[] indents>
//* 14 24:arraylength
//* 15 25:icmple 53
jsongenerator.writeRaw(indents, 0, indents.length);
// 16 28:aload_1
// 17 29:aload_0
// 18 30:getfield #56 <Field char[] indents>
// 19 33:iconst_0
// 20 34:aload_0
// 21 35:getfield #56 <Field char[] indents>
// 22 38:arraylength
// 23 39:invokevirtual #91 <Method void JsonGenerator.writeRaw(char[], int, int)>
// 24 42:iload_2
// 25 43:aload_0
// 26 44:getfield #56 <Field char[] indents>
// 27 47:arraylength
// 28 48:isub
// 29 49:istore_2
//* 30 50:goto 19
jsongenerator.writeRaw(indents, 0, i);
// 31 53:aload_1
// 32 54:aload_0
// 33 55:getfield #56 <Field char[] indents>
// 34 58:iconst_0
// 35 59:iload_2
// 36 60:invokevirtual #91 <Method void JsonGenerator.writeRaw(char[], int, int)>
}
// 37 63:return
}
private static final int INDENT_LEVELS = 16;
public static final DefaultIndenter SYSTEM_LINEFEED_INSTANCE;
public static final String SYS_LF;
private static final long serialVersionUID = 1L;
private final int charsPerLevel;
private final String eol;
private final char indents[];
static
{
String s;
try
{
s = System.getProperty("line.separator");
// 0 0:ldc1 #25 <String "line.separator">
// 1 2:invokestatic #31 <Method String System.getProperty(String)>
// 2 5:astore_0
}
//* 3 6:aload_0
//* 4 7:putstatic #33 <Field String SYS_LF>
//* 5 10:new #2 <Class DefaultIndenter>
//* 6 13:dup
//* 7 14:ldc1 #35 <String " ">
//* 8 16:getstatic #33 <Field String SYS_LF>
//* 9 19:invokespecial #39 <Method void DefaultIndenter(String, String)>
//* 10 22:putstatic #41 <Field DefaultIndenter SYSTEM_LINEFEED_INSTANCE>
//* 11 25:return
catch(Throwable throwable)
//* 12 26:astore_0
{
throwable = "\n";
// 13 27:ldc1 #43 <String "\n">
// 14 29:astore_0
}
SYS_LF = s;
SYSTEM_LINEFEED_INSTANCE = new DefaultIndenter(" ", SYS_LF);
//* 15 30:goto 6
}
}
| 33.152893 | 89 | 0.50779 |
65097fab8ce691ec31bcb7b508fe1c2e079ba089 | 149 | package com.david.dto;
public enum PublicKeyTypeEnum {
PB_API_795045_29302,
PB_API_795048_29307,
PB_DCP_795045_30666,
PB_DCP_795048_30667
}
| 11.461538 | 31 | 0.812081 |
1134dcc61a7acd3f58f5ad1319df094e66465942 | 21,726 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.avdmanager;
import com.android.annotations.NonNull;
import com.android.ide.common.rendering.HardwareConfigHelper;
import com.android.sdklib.devices.Device;
import com.android.tools.adtui.common.ColoredIconGenerator;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.JBMenuItem;
import com.intellij.openapi.ui.JBPopupMenu;
import com.intellij.ui.SearchTextField;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.table.TableView;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.ListTableModel;
import com.intellij.util.ui.accessibility.AccessibleContextUtil;
import icons.StudioIcons;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Lists the available device definitions by category
*/
public class DeviceDefinitionList extends JPanel implements ListSelectionListener, DocumentListener, DeviceUiAction.DeviceProvider {
private static final String SEARCH_RESULTS = "Search Results";
private static final String PHONE_TYPE = "Phone";
private static final String TABLET_TYPE = "Tablet";
private static final String DEFAULT_PHONE = "Pixel 2";
private static final String DEFAULT_TABLET = "Pixel C";
private static final String DEFAULT_WEAR = "Wear OS Square";
private static final String DEFAULT_TV = "Android TV (1080p)";
private static final String DEFAULT_AUTOMOTIVE = "Automotive (1024p landscape)";
private static final String TV = "TV";
private static final String WEAR = "Wear OS";
private static final String AUTOMOTIVE = "Automotive";
private Map<String, List<Device>> myDeviceCategoryMap = Maps.newHashMap();
private static final Map<String, Device> myDefaultCategoryDeviceMap = Maps.newHashMap();
private static final DecimalFormat ourDecimalFormat = new DecimalFormat(".##");
private final ListTableModel<Device> myModel = new ListTableModel<>();
private TableView<Device> myTable;
private final ListTableModel<String> myCategoryModel = new ListTableModel<>();
private TableView<String> myCategoryList;
private JButton myCreateProfileButton;
private JButton myImportProfileButton;
private JButton myRefreshButton;
private JPanel myPanel;
private SearchTextField mySearchTextField;
private List<DeviceDefinitionSelectionListener> myListeners = new ArrayList<>();
private List<DeviceCategorySelectionListener> myCategoryListeners = new ArrayList<>();
private List<Device> myDevices;
private Device myDefaultDevice;
public DeviceDefinitionList() {
super(new BorderLayout());
// List of columns present in our table. Each column is represented by a ColumnInfo which tells the table how to get
// the cell value in that column for a given row item.
ColumnInfo[] columnInfos = new ColumnInfo[]{new DeviceColumnInfo("Name") {
@NonNull
@Override
public String valueOf(Device device) {
return device.getDisplayName();
}
@NonNull
@Override
public String getPreferredStringValue() {
// Long string so that preferred column width is set appropriately
return "4.65\" 720 (Galaxy Nexus)";
}
@NonNull
@Override
public Comparator<Device> getComparator() {
return (o1, o2) -> {
String name1 = valueOf(o1);
String name2 = valueOf(o2);
if (name1 == name2) {
return 0;
}
if (name1.isEmpty() || name2.isEmpty()) {
return -1;
}
char firstChar1 = name1.charAt(0);
char firstChar2 = name2.charAt(0);
// Prefer letters to anything else
if (Character.isLetter(firstChar1) && !Character.isLetter(firstChar2)) {
return 1;
}
else if (Character.isLetter(firstChar2) && !Character.isLetter(firstChar1)) {
return -1;
}
// Fall back to string comparison
return name1.compareTo(name2);
};
}
}, new PlayStoreColumnInfo("Play Store") {
}, new DeviceColumnInfo("Size") {
@NonNull
@Override
public String valueOf(Device device) {
return getDiagonalSize(device);
}
@NonNull
@Override
public Comparator<Device> getComparator() {
return (o1, o2) -> {
if (o1 == null) {
return -1;
}
else if (o2 == null) {
return 1;
}
else {
return Double.compare(o1.getDefaultHardware().getScreen().getDiagonalLength(),
o2.getDefaultHardware().getScreen().getDiagonalLength());
}
};
}
}, new DeviceColumnInfo("Resolution") {
@NonNull
@Override
public String valueOf(Device device) {
return getDimensionString(device);
}
@NonNull
@Override
public Comparator<Device> getComparator() {
return (o1, o2) -> {
if (o1 == null) {
return -1;
}
else if (o2 == null) {
return 1;
}
else {
Dimension d1 = o1.getScreenSize(o1.getDefaultState().getOrientation());
Dimension d2 = o2.getScreenSize(o2.getDefaultState().getOrientation());
if (d1 == null) {
return -1;
}
else if (d2 == null) {
return 1;
}
else {
return Integer.compare(d1.width * d1.height, d2.width * d2.height);
}
}
};
}
}, new DeviceColumnInfo("Density") {
@NonNull
@Override
public String valueOf(Device device) {
return getDensityString(device);
}
}};
myModel.setColumnInfos(columnInfos);
myModel.setSortable(true);
refreshDeviceProfiles();
setDefaultDevices();
myTable.setModelAndUpdateColumns(myModel);
myTable.getRowSorter().toggleSortOrder(0);
myTable.getRowSorter().toggleSortOrder(0);
myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myTable.setRowSelectionAllowed(true);
myRefreshButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
refreshDeviceProfiles();
}
});
myTable.getSelectionModel().addListSelectionListener(this);
// The singular column that serves as the header for our category list
ColumnInfo[] categoryInfo = new ColumnInfo[]{new ColumnInfo<String, String>("Category") {
@Nullable
@Override
public String valueOf(String category) {
return category;
}
@NonNull
@Override
public TableCellRenderer getRenderer(String s) {
return myRenderer;
}
}};
myCategoryModel.setColumnInfos(categoryInfo);
myCategoryList.setModelAndUpdateColumns(myCategoryModel);
myCategoryList.getSelectionModel().addListSelectionListener(this);
mySearchTextField.addDocumentListener(this);
add(myPanel, BorderLayout.CENTER);
myCreateProfileButton.setAction(new CreateDeviceAction(this));
myCreateProfileButton.setText("New Hardware Profile");
myImportProfileButton.setAction(new ImportDevicesAction(this));
myImportProfileButton.setText("Import Hardware Profiles");
myTable.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
possiblyShowPopup(e);
}
@Override
public void mousePressed(MouseEvent e) {
possiblyShowPopup(e);
}
@Override
public void mouseReleased(MouseEvent e) {
possiblyShowPopup(e);
}
});
}
private void setDefaultDevices() {
myDefaultDevice = updateDefaultDevice(PHONE_TYPE, DEFAULT_PHONE);
updateDefaultDevice(TABLET_TYPE, DEFAULT_TABLET);
updateDefaultDevice(TV, DEFAULT_TV);
updateDefaultDevice(WEAR, DEFAULT_WEAR);
updateDefaultDevice(AUTOMOTIVE, DEFAULT_AUTOMOTIVE);
}
private Device updateDefaultDevice(String type, String deviceDisplayName) {
List<Device> devices = myDeviceCategoryMap.get(type);
if (devices != null) {
for (Device d : devices) {
if (d.getDisplayName().equals(deviceDisplayName)) {
myDefaultCategoryDeviceMap.put(type, d);
return d;
}
}
}
return null;
}
@NotNull
private static JBMenuItem createMenuItem(@NotNull DeviceUiAction action) {
JBMenuItem item = new JBMenuItem(action);
item.setText(action.getText());
return item;
}
private void possiblyShowPopup(MouseEvent e) {
if (!e.isPopupTrigger()) {
return;
}
Point p = e.getPoint();
int row = myTable.rowAtPoint(p);
int col = myTable.columnAtPoint(p);
if (row != -1 && col != -1) {
JBPopupMenu menu = new JBPopupMenu();
menu.add(createMenuItem(new CloneDeviceAction(this)));
menu.add(createMenuItem(new EditDeviceAction(this)));
menu.add(createMenuItem(new ExportDeviceAction(this)));
menu.add(createMenuItem(new DeleteDeviceAction(this)));
menu.show(myTable, p.x, p.y);
}
}
@Override
public void valueChanged(ListSelectionEvent e) {
if (e.getSource().equals(myCategoryList.getSelectionModel())) {
setCategory(myCategoryList.getSelectedObject());
} else if (e.getSource().equals(myTable.getSelectionModel())){
onSelectionSet(myTable.getSelectedObject());
}
}
public void addSelectionListener(@NotNull DeviceDefinitionSelectionListener listener) {
myListeners.add(listener);
}
public void addCategoryListener(@NotNull DeviceCategorySelectionListener listener) {
myCategoryListeners.add(listener);
}
public void removeSelectionListener(@NotNull DeviceDefinitionSelectionListener listener) {
myListeners.remove(listener);
}
@Override
public void selectDefaultDevice() {
setSelectedDevice(myDefaultDevice);
}
@Nullable
@Override
public Project getProject() {
return null;
}
/**
* Set the list's selection to the given device, or clear the selection if the
* given device is null. The category list will also select the category to which the
* given device belongs.
*/
public void setSelectedDevice(@Nullable Device device) {
if (Objects.equals(device, myTable.getSelectedObject())) {
return;
}
onSelectionSet(device);
if (device != null) {
String category = getCategory(device);
for (Device listItem : myModel.getItems()) {
if (listItem.getId().equals(device.getId())) {
myTable.setSelection(ImmutableSet.of(listItem));
}
}
myCategoryList.setSelection(ImmutableSet.of(category));
setCategory(category);
}
}
/**
* Update our listeners
*/
private void onSelectionSet(@Nullable Device selectedObject) {
if (selectedObject != null) {
myDefaultCategoryDeviceMap.put(getCategory(selectedObject), selectedObject);
}
for (DeviceDefinitionSelectionListener listener : myListeners) {
listener.onDeviceSelectionChanged(selectedObject);
}
}
/**
* Update our list to display the given category.
*/
public void setCategory(@Nullable String selectedCategory) {
if (myDeviceCategoryMap.containsKey(selectedCategory)) {
List<Device> newItems = myDeviceCategoryMap.get(selectedCategory);
if (!myModel.getItems().equals(newItems)) {
myModel.setItems(newItems);
setSelectedDevice(myDefaultCategoryDeviceMap.get(selectedCategory));
notifyCategoryListeners(selectedCategory, newItems);
}
}
}
private void notifyCategoryListeners(@Nullable String selectedCategory, @Nullable List<Device> items) {
for (DeviceCategorySelectionListener listener : myCategoryListeners) {
listener.onCategorySelectionChanged(selectedCategory, items);
}
}
private void refreshDeviceProfiles() {
myDevices = DeviceManagerConnection.getDefaultDeviceManagerConnection().getDevices();
myDeviceCategoryMap.clear();
for (Device d : myDevices) {
String category = getCategory(d);
if (!myDeviceCategoryMap.containsKey(category)) {
myDeviceCategoryMap.put(category, new ArrayList<>(1));
}
myDeviceCategoryMap.get(category).add(d);
}
Set<String> categories = myDeviceCategoryMap.keySet();
String[] categoryArray = ArrayUtil.toStringArray(categories);
myCategoryModel.setItems(Lists.newArrayList(categoryArray));
}
/**
* @return the category of the specified device. One of:
* Automotive TV, Wear, Tablet, and Phone, or Other if the category
* cannot be determined.
*/
@VisibleForTesting
public static String getCategory(@NotNull Device d) {
if (HardwareConfigHelper.isAutomotive(d)) {
return AUTOMOTIVE;
} else if (HardwareConfigHelper.isTv(d) || hasTvSizedScreen(d)) {
return TV;
} else if (HardwareConfigHelper.isWear(d)) {
return WEAR;
} else if (isTablet(d)) {
return TABLET_TYPE;
} else {
return PHONE_TYPE;
}
}
/*
* A mobile device is considered a tablet if its screen is at least
* {@link #MINIMUM_TABLET_SIZE} and the screen is not foldable.
*/
@VisibleForTesting
public static boolean isTablet(@NotNull Device d) {
return (d.getDefaultHardware().getScreen().getDiagonalLength() >= Device.MINIMUM_TABLET_SIZE
&& !d.getDefaultHardware().getScreen().isFoldable());
}
private static boolean hasTvSizedScreen(@NotNull Device d) {
return d.getDefaultHardware().getScreen().getDiagonalLength() >= Device.MINIMUM_TV_SIZE;
}
/**
* @return the diagonal screen size of the given device
*/
public static String getDiagonalSize(@NotNull Device device) {
return ourDecimalFormat.format(device.getDefaultHardware().getScreen().getDiagonalLength()) + '"';
}
/**
* @return a string of the form [width]x[height] in pixel units representing the screen resolution of the given device
*/
public static String getDimensionString(@NotNull Device device) {
Dimension size = device.getScreenSize(device.getDefaultState().getOrientation());
return size == null ? "Unknown Resolution" : String.format(Locale.getDefault(), "%dx%d", size.width, size.height);
}
/**
* @return a string representing the density bucket of the given device
*/
public static String getDensityString(@NotNull Device device) {
return device.getDefaultHardware().getScreen().getPixelDensity().getResourceValue();
}
private void createUIComponents() {
myCategoryList = new TableView<>();
myTable = new TableView<>();
myRefreshButton = new JButton(AllIcons.Actions.Refresh);
}
@Override
public void insertUpdate(DocumentEvent e) {
updateSearchResults(getText(e.getDocument()));
}
@Override
public void removeUpdate(DocumentEvent e) {
updateSearchResults(getText(e.getDocument()));
}
@Override
public void changedUpdate(DocumentEvent e) {
updateSearchResults(getText(e.getDocument()));
}
private static String getText(Document d) {
try {
return d.getText(0, d.getLength());
}
catch (BadLocationException e) {
return "";
}
}
/**
* Set the "Search Results" category to the set of devices whose names match the given search string
*/
private void updateSearchResults(@NotNull final String searchString) {
if (searchString.isEmpty()) {
if (myCategoryModel.getItem(myCategoryModel.getRowCount() - 1).equals(SEARCH_RESULTS)) {
myCategoryModel.removeRow(myCategoryModel.getRowCount() - 1);
setCategory(myCategoryList.getRow(0));
}
return;
} else if (!myCategoryModel.getItem(myCategoryModel.getRowCount() - 1).equals(SEARCH_RESULTS)) {
myCategoryModel.addRow(SEARCH_RESULTS);
myCategoryList.setSelection(ImmutableSet.of(SEARCH_RESULTS));
}
List<Device> items = Lists.newArrayList(Iterables.filter(myDevices,
(input) -> input.getDisplayName().toLowerCase(Locale.getDefault())
.contains(searchString.toLowerCase(Locale.getDefault()))));
myModel.setItems(items);
notifyCategoryListeners(null, items);
}
@Nullable
@Override
public Device getDevice() {
return myTable.getSelectedObject();
}
@Override
public void setDevice(@Nullable Device device) {
setSelectedDevice(device);
}
@Override
public void refreshDevices() {
refreshDeviceProfiles();
}
private final Border myBorder = JBUI.Borders.empty(10);
/**
* Renders a simple text field.
*/
private final TableCellRenderer myRenderer = new TableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JBLabel label = new JBLabel((String)value);
label.setBorder(myBorder);
if (table.getSelectedRow() == row) {
label.setBackground(table.getSelectionBackground());
label.setForeground(table.getSelectionForeground());
label.setOpaque(true);
}
return label;
}
};
private abstract class DeviceColumnInfo extends ColumnInfo<Device, String> {
private final int myWidth;
@Nullable
@Override
public Comparator<Device> getComparator() {
return (o1, o2) -> {
if (o1 == null || valueOf(o1) == null) {
return -1;
}
else if (o2 == null || valueOf(o2) == null) {
return 1;
}
else {
//noinspection ConstantConditions
return valueOf(o1).compareTo(valueOf(o2));
}
};
}
DeviceColumnInfo(@NotNull String name, int width) {
super(name);
myWidth = width;
}
DeviceColumnInfo(String name) {
this(name, -1);
}
@Nullable
@Override
public TableCellRenderer getRenderer(Device device) {
return myRenderer;
}
@Override
public int getWidth(JTable table) {
return myWidth;
}
}
private static class PlayStoreColumnInfo extends ColumnInfo<Device, Icon> {
public static final Icon highlightedPlayStoreIcon = ColoredIconGenerator.INSTANCE.generateWhiteIcon(StudioIcons.Avd.DEVICE_PLAY_STORE);
private static final TableCellRenderer ourIconRenderer = new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Icon theIcon = (Icon)value;
JBLabel label = new JBLabel(theIcon);
if (theIcon != null) {
AccessibleContextUtil.setName(label, "Play Store");
}
if (table.getSelectedRow() == row) {
label.setBackground(table.getSelectionBackground());
label.setForeground(table.getSelectionForeground());
label.setOpaque(true);
if (theIcon != null) {
label.setIcon(highlightedPlayStoreIcon);
}
}
return label;
}
};
PlayStoreColumnInfo(String name) {
super(name);
}
@NotNull
@Override
public TableCellRenderer getRenderer(Device device) {
return ourIconRenderer;
}
@Override
public int getWidth(JTable table) {
return -1; // Re-sizable
}
@Nullable
@Override
public Icon valueOf(@NonNull Device device) {
return (device.hasPlayStore() ? StudioIcons.Avd.DEVICE_PLAY_STORE : null);
}
@NotNull
@Override
public Comparator<Device> getComparator() {
return (o1, o2) -> Boolean.compare(o2.hasPlayStore(), o1.hasPlayStore());
}
}
public interface DeviceDefinitionSelectionListener {
void onDeviceSelectionChanged(@Nullable Device selectedDevice);
}
public interface DeviceCategorySelectionListener {
void onCategorySelectionChanged(@Nullable String category, @Nullable List<Device> devices);
}
}
| 33.068493 | 141 | 0.681948 |
444040267da07ade0f2f91450ef13955f141fa0f | 278 | package my.company.web.requirements;
import net.thucydides.core.annotations.Feature;
/**
* @author Artem Eroshenko eroshenkoam
* 5/6/13, 5:18 PM
*/
public class Application {
@Feature
public class Search {
public class SearchByRequest {}
}
}
| 15.444444 | 47 | 0.661871 |
375375454e6041773b4b36058d5bb8649a27b6f2 | 2,168 | /*
* Copyright (c) 2015 Spotify AB.
*
* 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 com.spotify.heroic.aggregation.simple;
import static java.util.stream.Collectors.toList;
import com.spotify.heroic.ObjectHasher;
import com.spotify.heroic.metric.MetricCollection;
import com.spotify.heroic.metric.MetricType;
import com.spotify.heroic.metric.Point;
import java.util.List;
import lombok.Data;
@Data
public class FilterPointsThresholdStrategy implements MetricMappingStrategy {
private final FilterKThresholdType filterType;
private final double threshold;
@Override
public MetricCollection apply(MetricCollection metrics) {
if (metrics.getType() == MetricType.POINT) {
return MetricCollection.build(MetricType.POINT,
filterWithThreshold(metrics.getDataAs(Point.class)));
} else {
return metrics;
}
}
@Override
public void hashTo(final ObjectHasher hasher) {
hasher.putObject(getClass(), () -> {
hasher.putField("filterType", filterType, hasher.enumValue());
hasher.putField("threshold", threshold, hasher.doubleValue());
});
}
private List<Point> filterWithThreshold(List<Point> points) {
return points
.stream()
.filter(point -> filterType.predicate(point.getValue(), threshold))
.collect(toList());
}
}
| 34.412698 | 79 | 0.707103 |
2230d9e85dffa382d0900786f9f4bbc4f690069e | 565 | package pro.friendlyted.mvnsh.core.api;
import java.util.List;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
/**
*
* @author Fedor Resnyanskiy
*/
public interface MsUpload {
void setArtifactId(String artifactId);
void setGroupId(String groupId);
void setRepoSession(RepositorySystemSession repoSession);
void setRepoSystem(RepositorySystem repoSystem);
void setScriptsList(List<FilesProvider> scriptsList);
void setVersion(String version);
void upload() throws MsException;
}
| 20.925926 | 61 | 0.768142 |
3dd2058d58c0b5ef7ff9a23d9de88d327b17bd3c | 3,678 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.roots.impl;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.roots.SourceFolder;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author nik
*/
public class DirectoryInfoImpl extends DirectoryInfo {
protected final VirtualFile myRoot;//original project root for which this information is calculated
private final Module module; // module to which content it belongs or null
private final VirtualFile libraryClassRoot; // class root in library
private final VirtualFile contentRoot;
private final VirtualFile sourceRoot;
private final SourceFolder sourceRootFolder;
protected final boolean myInModuleSource;
protected final boolean myInLibrarySource;
protected final boolean myExcluded;
private final String myUnloadedModuleName;
DirectoryInfoImpl(@NotNull VirtualFile root, Module module, VirtualFile contentRoot,
VirtualFile sourceRoot, @Nullable SourceFolder sourceRootFolder, VirtualFile libraryClassRoot,
boolean inModuleSource, boolean inLibrarySource, boolean isExcluded, @Nullable String unloadedModuleName) {
myRoot = root;
this.module = module;
this.libraryClassRoot = libraryClassRoot;
this.contentRoot = contentRoot;
this.sourceRoot = sourceRoot;
this.sourceRootFolder = sourceRootFolder;
myInModuleSource = inModuleSource;
myInLibrarySource = inLibrarySource;
myExcluded = isExcluded;
myUnloadedModuleName = unloadedModuleName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return myRoot.equals(((DirectoryInfoImpl)o).myRoot);
}
@Override
public int hashCode() {
return myRoot.hashCode();
}
@SuppressWarnings({"HardCodedStringLiteral"})
public String toString() {
return "DirectoryInfo{" +
"module=" + getModule() +
", isInModuleSource=" + myInModuleSource +
", rootType=" + (sourceRootFolder == null ? null : sourceRootFolder.getRootType()) +
", isExcludedFromModule=" + myExcluded +
", libraryClassRoot=" + getLibraryClassRoot() +
", contentRoot=" + getContentRoot() +
", sourceRoot=" + getSourceRoot() +
"}";
}
@Override
public boolean isInProject(@NotNull VirtualFile file) {
return !isExcluded(file);
}
public boolean isIgnored() {
return false;
}
@Nullable
public VirtualFile getSourceRoot() {
return sourceRoot;
}
@Nullable
public SourceFolder getSourceRootFolder() {
return sourceRootFolder;
}
public VirtualFile getLibraryClassRoot() {
return libraryClassRoot;
}
@Nullable
public VirtualFile getContentRoot() {
return contentRoot;
}
public boolean isInModuleSource() {
return myInModuleSource;
}
public boolean isInLibrarySource(@NotNull VirtualFile file) {
return myInLibrarySource;
}
public boolean isExcluded() {
return myExcluded;
}
@Override
public boolean isExcluded(@NotNull VirtualFile file) {
return myExcluded;
}
@Override
public boolean isInModuleSource(@NotNull VirtualFile file) {
return myInModuleSource;
}
public Module getModule() {
return module;
}
@Override
public String getUnloadedModuleName() {
return myUnloadedModuleName;
}
@NotNull
public VirtualFile getRoot() {
return myRoot;
}
}
| 28.076336 | 140 | 0.713703 |
5339b7667bb5964e942c000aa21479d00dfafb9b | 2,756 | /* Copyright (c) 2011 Danish Maritime Authority.
*
* 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.maritimecloud.mms.server.rest;
import net.maritimecloud.core.id.MaritimeId;
import net.maritimecloud.internal.net.endpoint.EndpointMirror;
import net.maritimecloud.message.Message;
import net.maritimecloud.mms.server.connection.client.Client;
import net.maritimecloud.mms.server.connection.client.ClientManager;
import net.maritimecloud.mms.server.security.AuthenticationException;
import net.maritimecloud.mms.server.security.ClientVerificationException;
import net.maritimecloud.mms.server.security.MmsSecurityManager;
import net.maritimecloud.mms.server.security.Subject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
/**
*
* @author Kasper Nielsen
*/
@Path("/endpoint")
public class EndpointInvoke extends ProtectedResource {
final ClientManager clientManager;
/**
* Constructor
* @param clientManager the client manager
* @param securityManager the security manager
*/
public EndpointInvoke(ClientManager clientManager, MmsSecurityManager securityManager) {
super(securityManager);
this.clientManager = clientManager;
}
/**
* Returns a list of source IDs in the source. This one is hard coded for now
*
* @param mmsi
* the mmsi number
* @param endpoint
* the endpoint
* @return a list of source IDs in the source
*/
@GET
@Path("/invoke/{mmsi}/{endpoint}")
public Message invoke(@PathParam("mmsi") String mmsi, @PathParam("endpoint") String endpoint) throws AuthenticationException, ClientVerificationException {
MaritimeId id = MaritimeId.create("mmsi:" + mmsi);
// Instantiate a subject according to the current security configuration
Subject subject = initializeSubject();
subject.checkClient(id.toString());
String ep = EndpointMirror.stripEndpointMethod(endpoint);
Client client = clientManager.get(id);
if (client != null) {
if (client.getEndpointManager().hasService(ep)) {
// Vi skal lave en "Fake" sources
}
}
return null;
}
}
| 34.024691 | 159 | 0.709361 |
22330d5d4641584c15555d5f9434d983fb6f01d2 | 8,340 | /*
* Copyright 2015 MovingBlocks
*
* 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.teraslogy.simpleliquids.block.entity;
import com.google.common.collect.Lists;
import com.google.common.collect.Queues;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.entitySystem.entity.EntityRef;
import org.terasology.entitySystem.event.EventPriority;
import org.terasology.entitySystem.event.ReceiveEvent;
import org.terasology.entitySystem.systems.BaseComponentSystem;
import org.terasology.entitySystem.systems.RegisterMode;
import org.terasology.entitySystem.systems.RegisterSystem;
import org.terasology.entitySystem.systems.UpdateSubscriberSystem;
import org.terasology.logic.health.DoDestroyEvent;
import org.terasology.math.Side;
import org.terasology.math.geom.Vector3i;
import org.terasology.registry.In;
import org.terasology.world.OnChangedBlock;
import org.terasology.world.WorldProvider;
import org.terasology.world.block.Block;
import org.terasology.world.block.BlockComponent;
import org.terasology.world.block.BlockManager;
import org.terasology.world.chunks.ChunkConstants;
import org.terasology.world.chunks.event.OnChunkGenerated;
import org.terasology.world.chunks.event.OnChunkLoaded;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Event handler for events affecting block entities related to liquids such as water or lava.
*/
@RegisterSystem(RegisterMode.AUTHORITY)
public class LiquidEntitySystem extends BaseComponentSystem implements UpdateSubscriberSystem {
private static Logger logger = LoggerFactory.getLogger(LiquidEntitySystem.class);
private static final int MAX_BLOCK_UPDATES = 500;
@In
private WorldProvider worldProvider;
@In
private BlockManager blockManager;
private Block water;
private Block air;
private ConcurrentLinkedQueue<Vector3i> waterPositions;
private float timeSinceLastUpdate;
@Override
public void initialise() {
super.initialise();
waterPositions = Queues.newConcurrentLinkedQueue();
water = blockManager.getBlock("CoreBlocks:Water");
air = blockManager.getBlock(BlockManager.AIR_ID);
}
@ReceiveEvent(priority = EventPriority.PRIORITY_NORMAL)
public void doDestroy(DoDestroyEvent event, EntityRef entity, BlockComponent blockComponent) {
Vector3i blockLocation = blockComponent.getPosition();
Vector3i neighborLocation;
neighborLocation = new Vector3i(blockLocation);
neighborLocation.add(Side.TOP.getVector3i());
if (worldProvider.isBlockRelevant(neighborLocation)) {
Block neighborBlock = worldProvider.getBlock(neighborLocation);
if (neighborBlock == water) {
if (!waterPositions.contains(blockLocation)) {
waterPositions.add(blockLocation);
}
return;
}
}
for (Side side : Side.horizontalSides()) {
neighborLocation = new Vector3i(blockLocation);
neighborLocation.add(side.getVector3i());
if (worldProvider.isBlockRelevant(neighborLocation)) {
Block neighborBlock = worldProvider.getBlock(neighborLocation);
if (neighborBlock == water) {
if (!waterPositions.contains(blockLocation)) {
waterPositions.add(blockLocation);
}
return;
}
}
}
}
@ReceiveEvent(priority = EventPriority.PRIORITY_NORMAL)
public void blockUpdate(OnChangedBlock event, EntityRef blockEntity) {
Vector3i blockLocation = event.getBlockPosition();
Vector3i neighborLocation;
Block neighborBlock;
if (event.getNewType().isLiquid()) {
neighborLocation = new Vector3i(blockLocation);
neighborLocation.add(Side.BOTTOM.getVector3i());
if (worldProvider.isBlockRelevant(neighborLocation)) {
neighborBlock = worldProvider.getBlock(neighborLocation);
if ((neighborBlock == air || neighborBlock.isSupportRequired()) && !waterPositions.contains(neighborLocation)) {
// propagate down
waterPositions.add(neighborLocation);
} else if (!neighborBlock.isLiquid() && neighborBlock != air) {
// spread to the sites
for (Side side : Side.horizontalSides()) {
neighborLocation = new Vector3i(blockLocation);
neighborLocation.add(side.getVector3i());
if (worldProvider.isBlockRelevant(neighborLocation)) {
neighborBlock = worldProvider.getBlock(neighborLocation);
if (neighborBlock == blockManager.getBlock(BlockManager.AIR_ID) || neighborBlock.isSupportRequired()) {
Vector3i neighborBottomLocation = new Vector3i(neighborLocation);
neighborBottomLocation.add(Side.BOTTOM.getVector3i());
if (!waterPositions.contains(neighborLocation)) {
waterPositions.add(neighborLocation);
}
}
}
}
}
}
}
}
@Override
public void update(float delta) {
timeSinceLastUpdate += delta;
if (timeSinceLastUpdate >= 0.3f) {
for (int i = 0; i < Math.min(waterPositions.size(), MAX_BLOCK_UPDATES); i++) {
worldProvider.setBlock(waterPositions.poll(), water);
}
timeSinceLastUpdate -= 0.3f;
}
}
@ReceiveEvent(priority = EventPriority.PRIORITY_NORMAL)
public void onChunkGenerated(OnChunkGenerated chunkGenerated, EntityRef entity) {
processChunk(chunkGenerated.getChunkPos(), entity);
}
@ReceiveEvent(priority = EventPriority.PRIORITY_NORMAL)
public void onChunkLoaded(OnChunkLoaded chunkLoaded, EntityRef entity) {
processChunk(chunkLoaded.getChunkPos(), entity);
}
public void processChunk(Vector3i chunkPos, EntityRef entity) {
Vector3i worldPos = new Vector3i(chunkPos);
worldPos.mul(ChunkConstants.SIZE_X, ChunkConstants.SIZE_Y, ChunkConstants.SIZE_Z);
Vector3i blockPos = new Vector3i();
Vector3i testPos = new Vector3i();
// scan the chunk, looking for liquid
for (int y = ChunkConstants.SIZE_Y - 1; y >= 0; y--) {
for (int z = 0; z < ChunkConstants.SIZE_Z; z++) {
for (int x = 0; x < ChunkConstants.SIZE_X; x++) {
blockPos.set(x + worldPos.x, y + worldPos.y, z + worldPos.z);
if (worldProvider.getBlock(blockPos).isLiquid()) {
// scan the neighboring blocks
List<Side> scanSides = Lists.newArrayList(Side.LEFT, Side.RIGHT, Side.FRONT, Side.BACK, Side.BOTTOM);
for (Side side : scanSides) {
testPos.set(blockPos.x, blockPos.y, blockPos.z);
testPos.add(side.getVector3i());
// we only do this if we have air next to our liquid
if (worldProvider.getBlock(testPos) == air) {
blockUpdate(new OnChangedBlock(blockPos, water, water), worldProvider.getBlock(blockPos).getEntity());
break; // GET TO THE CHOPPAH!
}
}
// ___.___
// c00D`=--/
}
}
}
}
}
}
| 42.55102 | 134 | 0.630096 |
c267558d91ffc2ced5723e08888b9946db70c5ae | 2,438 | /*
* 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 oop.demo;
/**
*
* @author kmhasan
*/
public class RationalNumber {
private long numerator;
private long denominator;
// Default constructor
public RationalNumber() {
numerator = 0;
denominator = 1;
}
// Constructor
public RationalNumber(long n, long d) {
numerator = n;
denominator = d;
}
public RationalNumber add(RationalNumber b) {
RationalNumber a = this;
RationalNumber c = new RationalNumber();
c.denominator = a.denominator * b.denominator;
c.numerator = a.numerator * b.denominator + a.denominator * b.numerator;
return c;
}
public RationalNumber subtract(RationalNumber b) {
RationalNumber a = this;
RationalNumber c = new RationalNumber();
c.denominator = a.denominator * b.denominator;
c.numerator = a.numerator * b.denominator - a.denominator * b.numerator;
return c;
}
public RationalNumber subtractAlternateApproach(RationalNumber b) {
return add(new RationalNumber(-b.numerator, b.denominator));
}
public RationalNumber multiply(RationalNumber b) {
RationalNumber a = this;
RationalNumber c = new RationalNumber();
c.numerator = a.numerator * b.numerator;
c.denominator = a.denominator * b.denominator;
return c;
}
public RationalNumber divide(RationalNumber b) {
RationalNumber a = this;
RationalNumber c = new RationalNumber();
c.numerator = a.numerator * b.denominator;
c.denominator = a.denominator * b.numerator;
return c;
}
public RationalNumber divideAlternateApproach(RationalNumber b) {
return multiply(new RationalNumber(b.denominator, b.numerator));
}
public String toString() {
return numerator + "/" + denominator;
}
public long gcd(long a, long b) {
if (a == 0)
return b;
else return gcd(b % a, a);
}
public RationalNumber reduce() {
long d = gcd(this.numerator, this.denominator);
this.numerator = this.numerator / d;
this.denominator = this.denominator / d;
return this;
}
}
| 28.682353 | 80 | 0.61854 |
1ff92ee91a5a1bedf0549ea50d9e2ad8c7edeab5 | 802 | package ru.local.betback.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import ru.local.betback.model.Match;
import java.util.List;
public interface MatchRepository extends CrudRepository<Match, Long> {
List<Match> findAllByOrderByIdAsc();
@Query(value = "select *\n" +
"from appbet.match m\n" +
" inner join appbet.team t1\n" +
" on m.team1_id = t1.id\n" +
" inner join appbet.team t2\n" +
" on m.team2_id = t2.id\n" +
"where t1.group_id = :groupId and t2.group_id = :groupId",
nativeQuery = true)
List<Match> getMatchesByGroupId(@Param("groupId") int id);
}
| 34.869565 | 70 | 0.657107 |
72a52d1d6bca83520e13f9196654811143d5b173 | 4,466 | package cn.imppp.knowlege.base;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.ViewModelProvider;
import cn.imppp.knowlege.R;
import cn.imppp.knowlege.listener.ClickProxy;
import cn.imppp.knowlege.state.TitleViewModel;
import static androidx.constraintlayout.widget.Constraints.TAG;
/**
* A simple {@link Fragment} subclass.
*/
public abstract class BaseLazyFragment extends Fragment implements ClickProxy {
private boolean isLoadedData; // 是否加载数据
private View mRootView; // 布局
private boolean mViewInflateFinished; // 表示找控件完成, 给控件们设置数据不会报空指针了
private Lifecycle lifecycle; // 生命周期
private DefaultLifecycleObserver observer; // 观察者
private TitleViewModel titleViewModel;
private QMUITipDialog tipDialog;
public BaseLazyFragment() {
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
Log.d(TAG, "onCreateView");
if (mRootView != null) {
return mRootView;
}
mRootView = initRootView(inflater, container, savedInstanceState);
mViewInflateFinished = true;
if (titleViewModel == null) {
// 统一处理标题栏绑定返回操作
titleViewModel = new ViewModelProvider(this).get(TitleViewModel.class);
titleViewModel.setClickProxy(this);
}
lifecycle = requireActivity().getLifecycle();
return mRootView;
}
@Override
public void onResume() {
super.onResume();
if (observer != null) {
lifecycle.removeObserver(observer);
}
observer = new DefaultLifecycleObserver() {
@Override
public void onResume(@NonNull LifecycleOwner owner) {
if (!isLoadedData) {
loadData();
isLoadedData = true;
} else {
refreshData();
}
}
@Override
public void onPause(@NonNull LifecycleOwner owner) {
}
@Override
public void onStop(@NonNull LifecycleOwner owner) {
}
};
lifecycle.addObserver(observer);
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
}
@Override
public void menu() {
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onDestroyView() {
super.onDestroyView();
lifecycle.removeObserver(observer);
}
@Override
public void onStop() {
super.onStop();
}
@Override
public void onDetach() {
super.onDetach();
}
private void showDialog() {
if (tipDialog == null) {
tipDialog = new QMUITipDialog.Builder(getActivity())
.setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
.setTipWord(getResources().getString(R.string.loading))
.create();
}
tipDialog.show();
}
private void hideDialog() {
if (tipDialog != null)
tipDialog.dismiss();
}
// 网络加载动画观察者
public void loadAnimation(BaseRequestViewModel requestViewModel) {
requestViewModel.getIsLoading().observe(this, aBoolean -> {
if (aBoolean) {
showDialog();
} else {
hideDialog();
}
});
}
// 加载数据
public abstract void loadData();
// 刷新数据
public abstract void refreshData();
// 加载布局
public abstract View initRootView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState);
}
| 26.742515 | 93 | 0.608822 |
1920928773403414a76810c674c14dd8a158a143 | 3,656 | package com.csbunlimited.ctse_csb_alarm_services;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import com.csbunlimited.ctse_csb_alarm.StopAlarmActivity;
import com.csbunlimited.ctse_csb_alarm_consts.AlarmApplication;
import com.csbunlimited.ctse_csb_alarm_models.Alarm;
import com.csbunlimited.ctse_csb_db.AlarmDBHandler;
public class RingAlarmService extends Service {
private AlarmDBHandler _alarmDBHandler;
// @androidx.annotation.Nullable
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
_alarmDBHandler = new AlarmDBHandler(getApplicationContext());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// return super.onStartCommand(intent, flags, startId);
int alarmId = intent.getIntExtra(AlarmApplication.ALARM_ID, 0);
if (alarmId > 0) {
Alarm alarm = _alarmDBHandler.getAlarmById(alarmId);
if (alarm != null) {
Intent ringAlarmIntent = new Intent(this, StopAlarmActivity.class);
ringAlarmIntent.putExtra(AlarmApplication.ALARM_ID, alarmId);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, ringAlarmIntent, 0);
NotificationManagerService notificationManagerService = new NotificationManagerService(this);
Notification notification = notificationManagerService.getRingAlarmNofication(alarm, pendingIntent);
try {
final AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && 1 == 0) {
Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), alarm.getRingtoneUri());
ringtone.setLooping(true);
ringtone.setStreamType(AudioManager.STREAM_ALARM);
ringtone.play();
}
else {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(this, alarm.getRingtoneUri());
mediaPlayer.setLooping(true);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mediaPlayer.prepare();
mediaPlayer.start();
}
}
alarm.setIsActive(false);
_alarmDBHandler.updateAlarm(alarm);
}
catch (Exception ex) {
}
startForeground(alarm.getId(), notification);
}
// Intent i = new Intent();
// i.setClass(this, MainActivity.class);
// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// startActivity(i);
}
// return super.onStartCommand(intent, flags, startId);
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
| 34.490566 | 125 | 0.617068 |
9ce3e72c3d821939e3ee6f8607a97cff9807ff69 | 8,055 | // Copyright 2011 Google 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.google.enterprise.secmgr.common;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.enterprise.secmgr.testing.CallableTest;
import com.google.enterprise.secmgr.testing.EqualValueExpectation;
import com.google.enterprise.secmgr.testing.Expectation;
import com.google.enterprise.secmgr.testing.FunctionTest;
import com.google.enterprise.secmgr.testing.IdenticalValueExpectation;
import com.google.enterprise.secmgr.testing.RunnableTest;
import com.google.enterprise.secmgr.testing.SecurityManagerTestCase;
import com.google.enterprise.secmgr.testing.SimpleExceptionExpectation;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.Callable;
/**
* Unit tests for {@link Chain}.
*/
public class ChainTest extends SecurityManagerTestCase {
private static final String A = "A";
private static final String B = "B";
private final Chain<String> chain1 = Chain.empty();
private final Chain<String> chain2 = chain1.add(A);
private final Chain<String> chain3 = chain2.add(B);
private final Chain<String> chain4 = chain1.add(B);
private final Chain<String> chain5 = chain4.add(A);
private final String[] array1 = new String[] {};
private final String[] array2 = new String[] { A };
private final String[] array3 = new String[] { A, B };
private final String[] array4 = new String[] { B };
private final String[] array5 = new String[] { B, A };
private final List<Chain<String>> chains =
ImmutableList.of(chain1, chain2, chain3, chain4, chain5);
@SuppressWarnings("unchecked")
private final List<Chain<String>> rests =
Lists.newArrayList(null, chain1, chain2, chain1, chain4);
private final List<String[]> arrays =
ImmutableList.of(array1, array2, array3, array4, array5);
private final List<Chain<String>> altChains =
ImmutableList.copyOf(
Iterables.transform(arrays,
new Function<String[], Chain<String>>() {
@Override
public Chain<String> apply(String[] array) {
return makeChain(array);
}
}));
public void testBasic() {
for (Chain<String> c1 : chains) {
for (Chain<String> c2 : chains) {
if (c1 == c2) {
assertEquals(c1, c2);
} else {
assertFalse(c1.equals(c2));
}
}
}
List<RunnableTest> tests = Lists.newArrayList();
for (int i = 0; i < chains.size(); i += 1) {
assertEquals(chains.get(i), altChains.get(i));
assertEquals(chains.get(i).hashCode(), altChains.get(i).hashCode());
addBasicTests(tests, chains.get(i), rests.get(i), arrays.get(i));
}
runTests(tests);
}
private void addBasicTests(List<RunnableTest> tests, Chain<String> chain, Chain<String> rest,
String... elements) {
tests.add(
CallableTest.make(makeSizeCallable(chain), EqualValueExpectation.make(elements.length)));
tests.add(
CallableTest.make(makeIsEmptyCallable(chain),
EqualValueExpectation.make(elements.length == 0)));
tests.add(
CallableTest.make(makeGetLastCallable(chain),
(elements.length == 0)
? badGetLastExpectation
: EqualValueExpectation.make(elements[elements.length - 1])));
tests.add(
CallableTest.make(makeGetRestCallable(chain),
(rest == null)
? badGetRestExpectation
: IdenticalValueExpectation.make(rest)));
Function<Integer, String> function = makeGetFunction(chain);
for (int i = 0; i < elements.length; i += 1) {
tests.add(FunctionTest.make(function, i, EqualValueExpectation.make(elements[i])));
}
tests.add(FunctionTest.make(function, Integer.valueOf(-1), badGetExpectation));
tests.add(FunctionTest.make(function, Integer.valueOf(elements.length), badGetExpectation));
}
public void testToList() {
List<RunnableTest> tests = Lists.newArrayList();
for (int i = 0; i < chains.size(); i += 1) {
addToListTests(tests, chains.get(i), arrays.get(i));
}
runTests(tests);
}
private void addToListTests(List<RunnableTest> tests, Chain<String> chain, String... elements) {
List<String> fullValue = ImmutableList.copyOf(elements);
tests.add(
CallableTest.make(makeToListCallable(chain), EqualValueExpectation.make(fullValue)));
Function<Chain<String>, List<String>> function = makeToListFunction(chain);
Chain<String> ancestor = chain;
int i = elements.length;
while (true) {
tests.add(
FunctionTest.make(function, ancestor,
EqualValueExpectation.make(fullValue.subList(i, elements.length))));
if (ancestor.isEmpty()) {
break;
}
ancestor = ancestor.getRest();
i -= 1;
}
tests.add(FunctionTest.make(function, null, badToListExpectation));
}
private Chain<String> makeChain(String... elements) {
Chain<String> c = Chain.empty();
for (String element : elements) {
c = c.add(element);
}
return c;
}
private static Callable<Integer> makeSizeCallable(final Chain<String> chain) {
return new Callable<Integer>() {
@Override
public Integer call() {
return chain.size();
}
};
}
private static Callable<Boolean> makeIsEmptyCallable(final Chain<String> chain) {
return new Callable<Boolean>() {
@Override
public Boolean call() {
return chain.isEmpty();
}
};
}
private static Callable<String> makeGetLastCallable(final Chain<String> chain) {
return new Callable<String>() {
@Override
public String call()
throws NoSuchElementException {
return chain.getLast();
}
};
}
private static Callable<Chain<String>> makeGetRestCallable(final Chain<String> chain) {
return new Callable<Chain<String>>() {
@Override
public Chain<String> call()
throws NoSuchElementException {
return chain.getRest();
}
};
}
private static Function<Integer, String> makeGetFunction(final Chain<String> chain) {
return new Function<Integer, String>() {
@Override
public String apply(Integer index) {
return chain.get(index);
}
};
}
private static Function<Chain<String>, List<String>> makeToListFunction(
final Chain<String> chain) {
return new Function<Chain<String>, List<String>>() {
@Override
public List<String> apply(Chain<String> ancestor) {
return chain.toList(ancestor);
}
};
}
private static Callable<List<String>> makeToListCallable(final Chain<String> chain) {
return new Callable<List<String>>() {
@Override
public List<String> call() {
return chain.toList();
}
};
}
private static Expectation<String> badGetExpectation =
SimpleExceptionExpectation.make(IllegalArgumentException.class);
private static Expectation<String> badGetLastExpectation =
SimpleExceptionExpectation.make(UnsupportedOperationException.class);
private static Expectation<Chain<String>> badGetRestExpectation =
SimpleExceptionExpectation.make(UnsupportedOperationException.class);
private static Expectation<List<String>> badToListExpectation =
SimpleExceptionExpectation.make(NullPointerException.class);
}
| 33.5625 | 98 | 0.676847 |
2ac947c41c657638d3b24795a2a5d3b901f3388c | 4,351 | // VeriBlock Blockchain Project
// Copyright 2017-2018 VeriBlock, Inc
// Copyright 2018-2019 Xenios SEZC
// All rights reserved.
// https://www.veriblock.org
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
package org.veriblock.protoservice;
import java.math.BigDecimal;
import java.util.List;
import org.veriblock.integrations.rewards.PopPayoutRound;
import org.veriblock.integrations.rewards.PopRewardCalculator;
import org.veriblock.integrations.rewards.PopRewardCalculatorConfig;
import org.veriblock.integrations.rewards.PopRewardEndorsements;
import org.veriblock.protoconverters.CalculatorConfigProtoConverter;
import org.veriblock.protoconverters.RewardEndorsementProtoConverter;
import org.veriblock.protoconverters.RewardOutputProtoConverter;
import org.veriblock.sdk.ValidationResult;
import integration.api.grpc.VeriBlockMessages;
import integration.api.grpc.VeriBlockMessages.GeneralReply;
public class VeriBlockRewardsProtoService {
private VeriBlockRewardsProtoService() { }
public static GeneralReply resetRewards() {
PopRewardCalculator.setCalculatorConfig(new PopRewardCalculatorConfig());
ValidationResult result = ValidationResult.success();
return VeriBlockServiceCommon.validationResultToProto(result);
}
public static VeriBlockMessages.GetCalculatorReply getCalculator() {
VeriBlockMessages.CalculatorConfig config = CalculatorConfigProtoConverter.toProto(PopRewardCalculator.getCalculatorConfig());
ValidationResult result = ValidationResult.success();
GeneralReply replyResult = VeriBlockServiceCommon.validationResultToProto(result);
VeriBlockMessages.GetCalculatorReply reply = VeriBlockMessages.GetCalculatorReply.newBuilder()
.setCalculator(config)
.setResult(replyResult)
.build();
return reply;
}
public static GeneralReply setCalculator(VeriBlockMessages.CalculatorConfig protoConfig) {
PopRewardCalculatorConfig config = CalculatorConfigProtoConverter.fromProto(protoConfig);
PopRewardCalculator.setCalculatorConfig(config);
ValidationResult result = ValidationResult.success();
return VeriBlockServiceCommon.validationResultToProto(result);
}
public static VeriBlockMessages.RewardsCalculateScoreReply rewardsCalculateScore(VeriBlockMessages.RewardsCalculateScoreRequest request) {
PopRewardEndorsements endorsements = RewardEndorsementProtoConverter.fromProto(request.getEndorsementsForBlockList());
BigDecimal score = PopRewardCalculator.calculatePopScoreFromEndorsements(endorsements);
ValidationResult result = ValidationResult.success();
GeneralReply replyResult = VeriBlockServiceCommon.validationResultToProto(result);
VeriBlockMessages.RewardsCalculateScoreReply reply = VeriBlockMessages.RewardsCalculateScoreReply.newBuilder()
.setResult(replyResult)
.setScore(score.toPlainString())
.build();
return reply;
}
public static VeriBlockMessages.RewardsCalculateOutputsReply rewardsCalculateOutputs(VeriBlockMessages.RewardsCalculateOutputsRequest request) {
PopRewardEndorsements endorsements = RewardEndorsementProtoConverter.fromProto(request.getEndorsementsForBlockList());
PopPayoutRound payout = PopRewardCalculator.calculatePopPayoutRound(request.getBlockAltHeight(),
endorsements,
new BigDecimal(request.getDifficulty()));
List<VeriBlockMessages.RewardOutput> outputsProto = RewardOutputProtoConverter.toProto(payout.getOutputsToPopMiners());
ValidationResult result = ValidationResult.success();
GeneralReply replyResult = VeriBlockServiceCommon.validationResultToProto(result);
VeriBlockMessages.RewardsCalculateOutputsReply reply = VeriBlockMessages.RewardsCalculateOutputsReply.newBuilder()
.setResult(replyResult)
.addAllOutputs(outputsProto)
.setBlockReward(Long.toString(payout.getPopBlockReward()))
.setTotalReward(Long.toString(payout.getTotalRewardPaidOut()))
.build();
return reply;
}
}
| 51.188235 | 148 | 0.763962 |
1b4c51b11b5508c9c0a92e00097b777f6bafd7cf | 319 | /*
Author: Romain DALICHAMP
Github: https://github.com/fukakai
Portfolio: http://romain.dalichamp.fr
Contact: [email protected]
*/
// Write your overridden getNumberOfTeamMembers method here
@Override
void getNumberOfTeamMembers(){
System.out.println( "Each team has 11 players in " + getName() );
} | 29 | 74 | 0.739812 |
7f9b34d5448cfe667f8e0d3fa96c58e4c43c8310 | 296 | package com.canyinghao.canshare.demo.wxapi;
/**
* Created by echo on 10/11/14.
*/
//import com.liulishuo.share.wechat.WechatHandlerActivity;
import com.canyinghao.canshare.weixin.WeiXinHandlerActivity;
/** 微信客户端回调activity */
public class WXEntryActivity extends WeiXinHandlerActivity {
} | 18.5 | 60 | 0.780405 |
b7ebf1005ddf1ae5a587f2fce7733867e61065bd | 2,429 | package ru.job4j.list;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class ConvertList2ArrayTest {
@Test
public void when7ElementsThen9() {
ConvertList2Array list = new ConvertList2Array();
int[][] result = list.toArray(
Arrays.asList(1, 2, 3, 4, 5, 6, 7),
3
);
int[][] expect = {
{1, 2, 3},
{4, 5, 6},
{7, 0, 0}
};
assertThat(result, is(expect));
}
@Test
public void when3ElementsThen11() {
ConvertList2Array list = new ConvertList2Array();
int[][] result = list.toArray(
Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11),
3
);
int[][] expect = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 0}
};
assertThat(result, is(expect));
}
@Test
public void when2ElementsThen9() {
ConvertList2Array list = new ConvertList2Array();
int[][] result = list.toArray(
Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9),
2
);
int[][] expect = {
{1, 2},
{3, 4},
{5, 6},
{7, 8},
{9, 0}
};
assertThat(result, is(expect));
}
@Test
public void when2ArraysThen1List() {
ConvertList2Array convertList2Array = new ConvertList2Array();
List<int[]> arrays = new ArrayList<>();
arrays.add(new int[]{1, 2});
arrays.add(new int[]{3, 4, 5, 6});
List<Integer> result = convertList2Array.convert(arrays);
List<Integer> expect = Arrays.asList(1, 2, 3, 4, 5, 6);
assertThat(result, is(expect));
}
@Test
public void when3ArraysThen1List() {
ConvertList2Array convertList2Array = new ConvertList2Array();
List<int[]> arrays = new ArrayList<>();
arrays.add(new int[]{1, 2, 3});
arrays.add(new int[]{4, 5, 6});
arrays.add(new int[]{11, 22, 33, 44});
List<Integer> result = convertList2Array.convert(arrays);
List<Integer> expect = Arrays.asList(1, 2, 3, 4, 5, 6, 11, 22, 33, 44);
assertThat(result, is(expect));
}
}
| 28.576471 | 79 | 0.501029 |
fe2e57b31df5eadfdc554218a22f426f12e942cf | 1,366 | package com.jbm.cluster.logs.controllers;
import com.jbm.cluster.logs.entity.GatewayLogs;
import com.jbm.cluster.logs.form.GatewayLogsForm;
import com.jbm.cluster.logs.service.GatewayLogsService;
import com.jbm.framework.metadata.bean.ResultBody;
import com.jbm.framework.usage.paging.DataPaging;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "日志接口")
@RestController
@RequestMapping("/GatewayLogs")
public class GatewayLogsController {
/**
* 临时存放减少io
*/
@Autowired
private GatewayLogsService gatewayLogsService;
@ApiOperation(value = "获取多表查询分页列表")
@PostMapping({"/findLogs"})
public ResultBody<DataPaging<GatewayLogs>> findLogs(@RequestBody(required = false) GatewayLogsForm gatewayLogsForm) {
try {
DataPaging<GatewayLogs> dataPaging = gatewayLogsService.findLogs(gatewayLogsForm);
return ResultBody.success(dataPaging, "查询分页列表成功");
} catch (Exception e) {
return ResultBody.error(null, "查询日志失败", e);
}
}
}
| 34.15 | 121 | 0.758419 |
406777431a0abdc525dca1c92d38d8b518672015 | 457 | package org.labun.springframework.data.repository.events.support;
import lombok.Data;
import lombok.EqualsAndHashCode;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Data
@EqualsAndHashCode(of = "id")
@Entity
@Table(name = "person")
public class Person {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
}
| 20.772727 | 65 | 0.770241 |
a463bc9679b1f6b536dabf9a8017da2a2992c7d8 | 3,395 | /*******************************************************************************
* Copyright (c) 2022 Eclipse RDF4J contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*******************************************************************************/
package org.eclipse.rdf4j.sail.lmdb.benchmark;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.eclipse.rdf4j.common.transaction.IsolationLevels;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
/**
* Benchmarks insertion performance with extended FOAF data.
*/
@State(Scope.Benchmark)
@Warmup(iterations = 2)
@BenchmarkMode({ Mode.Throughput })
@Fork(value = 1, jvmArgs = { "-Xms2G", "-Xmx2G", "-XX:+UseG1GC" })
@Measurement(iterations = 5)
@OutputTimeUnit(TimeUnit.SECONDS)
public class TransactionsPerSecondBenchmarkFoaf extends BenchmarkBaseFoaf {
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include("TransactionsPerSecondBenchmarkFoaf") // adapt to control which benchmark tests to run
// .addProfiler("stack", "lines=20;period=1;top=20")
.forks(1)
.build();
new Runner(opt).run();
}
@Setup(Level.Iteration)
public void setup() throws IOException {
super.setup();
}
@TearDown(Level.Iteration)
public void tearDown() throws IOException {
super.tearDown();
}
@Benchmark
public void transaction1x() {
connection.begin();
addPersonNameOnly();
connection.commit();
}
@Benchmark
public void transaction1xLevelNone() {
connection.begin(IsolationLevels.NONE);
addPersonNameOnly();
connection.commit();
}
@Benchmark
public void transaction10x() {
connection.begin();
addPerson();
connection.commit();
}
@Benchmark
public void transaction10xLevelNone() {
connection.begin(IsolationLevels.NONE);
addPerson();
connection.commit();
}
@Benchmark
public void transaction10kx() {
connection.begin();
for (int k = 0; k < 1000; k++) {
addPerson();
}
connection.commit();
}
@Benchmark
public void transaction10kxLevelNone() {
connection.begin(IsolationLevels.NONE);
for (int k = 0; k < 1000; k++) {
addPerson();
}
connection.commit();
}
@Benchmark
public void transaction100kx() {
connection.begin();
for (int k = 0; k < 10000; k++) {
addPerson();
}
connection.commit();
}
@Benchmark
public void transaction100kxLevelNone() {
connection.begin(IsolationLevels.NONE);
for (int k = 0; k < 10000; k++) {
addPerson();
}
connection.commit();
}
}
| 26.732283 | 99 | 0.702798 |
dccc914b3fcbd91a645268f37ba3d45eff641c28 | 3,316 |
package com.mindbodyonline.clients.api._0_5_1.client_service;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for UpcomingAutopayEvent complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="UpcomingAutopayEvent">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ScheduleDate" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
* <element name="ChargeAmount" type="{http://www.w3.org/2001/XMLSchema}decimal"/>
* <element name="PaymentMethod" type="{http://clients.mindbodyonline.com/api/0_5_1}EPaymentMethod"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "UpcomingAutopayEvent", propOrder = {
"scheduleDate",
"chargeAmount",
"paymentMethod"
})
public class UpcomingAutopayEvent {
@XmlElement(name = "ScheduleDate", required = true, nillable = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar scheduleDate;
@XmlElement(name = "ChargeAmount", required = true, nillable = true)
protected BigDecimal chargeAmount;
@XmlElement(name = "PaymentMethod", required = true)
@XmlSchemaType(name = "string")
protected EPaymentMethod paymentMethod;
/**
* Gets the value of the scheduleDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getScheduleDate() {
return scheduleDate;
}
/**
* Sets the value of the scheduleDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setScheduleDate(XMLGregorianCalendar value) {
this.scheduleDate = value;
}
/**
* Gets the value of the chargeAmount property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getChargeAmount() {
return chargeAmount;
}
/**
* Sets the value of the chargeAmount property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setChargeAmount(BigDecimal value) {
this.chargeAmount = value;
}
/**
* Gets the value of the paymentMethod property.
*
* @return
* possible object is
* {@link EPaymentMethod }
*
*/
public EPaymentMethod getPaymentMethod() {
return paymentMethod;
}
/**
* Sets the value of the paymentMethod property.
*
* @param value
* allowed object is
* {@link EPaymentMethod }
*
*/
public void setPaymentMethod(EPaymentMethod value) {
this.paymentMethod = value;
}
}
| 26.741935 | 112 | 0.629674 |
cefd2616be938c22bb86643bef2c3b5b2d3e38ed | 4,692 | package at.yawk.valda.ir;
import at.yawk.valda.ir.annotation.AnnotationHolder;
import at.yawk.valda.ir.code.MethodBody;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import org.objectweb.asm.Type;
/**
* @author yawkat
*/
public final class LocalMethodMirror extends MethodMirror implements LocalMember {
@Nullable private TypeReference.MethodReturnType returnType;
@NonNull @Getter @Setter private String name;
private final List<Parameter> parameters = new ArrayList<>();
/**
* @see LocalMember#isDeclared()
*/
@Getter private final boolean declared;
@Nullable @Getter private MethodBody body = null;
@Getter @Setter @NonNull private Access access = Access.PUBLIC;
@NonNull private TriState isStatic = TriState.MAYBE;
@Getter @Setter private boolean isFinal = false;
@Getter @Setter private boolean isSynchronized = false;
@Getter @Setter private boolean isBridge = false;
@Getter @Setter private boolean isVarargs = false;
@Getter @Setter private boolean isNative = false;
@Getter @Setter private boolean isAbstract = false;
@Getter @Setter private boolean isStrictfp = false;
@Getter @Setter private boolean isSynthetic = false;
@Getter @Setter private boolean isDeclaredSynchronized = false;
@Getter
private final AnnotationHolder.MethodAnnotationHolder annotations =
new AnnotationHolder.MethodAnnotationHolder(this);
LocalMethodMirror(Classpath classpath, LocalClassMirror declaringType, @NonNull String name, boolean declared) {
super(classpath, declaringType);
this.name = name;
this.declared = declared;
}
@Override
public boolean isStatic() {
return isStatic.asBoolean();
}
public void setStatic(boolean isStatic) {
this.isStatic = TriState.valueOf(isStatic);
}
@Override
public LocalClassMirror getDeclaringType() {
return (LocalClassMirror) super.getDeclaringType();
}
public void setReturnType(@Nullable TypeMirror returnType) {
if (this.returnType != null) {
this.returnType.getReferencedType().getReferences().remove(this.returnType);
}
if (returnType == null) {
this.returnType = null;
} else {
this.returnType = new TypeReference.MethodReturnType(returnType, this);
returnType.getReferences().add(this.returnType);
}
}
public boolean isStaticInitializer() {
return name.equals("<clinit>");
}
@Nullable
public TypeMirror getReturnType() {
return returnType == null ? null : returnType.getReferencedType();
}
@Override
public Type getType() {
TypeMirror returnType = getReturnType();
return Type.getMethodType(returnType == null ? Type.VOID_TYPE : returnType.getType(),
parameters.stream().map(p -> p.getType().getType()).toArray(Type[]::new));
}
@Override
public String toString() {
return "LocalMethodMirror{" + getDebugDescriptor() + " declared=" + declared +
" body=" + body + "}";
}
@Override
public boolean isPrivate() {
return getAccess() == Access.PRIVATE;
}
@SuppressWarnings("deprecation")
public void setBody(@Nullable MethodBody body) {
if (this.body != null) {
this.body._linkClasspath(Secrets.SECRETS, false);
}
this.body = body;
if (this.body != null) {
this.body._linkClasspath(Secrets.SECRETS, true);
}
}
public Parameter addParameter(TypeMirror type, int index) {
Parameter parameter = new Parameter(type);
parameters.add(index, parameter);
return parameter;
}
public Parameter addParameter(TypeMirror type) {
Parameter parameter = new Parameter(type);
parameters.add(parameter);
return parameter;
}
public List<Parameter> getParameters() {
return Collections.unmodifiableList(parameters);
}
public class Parameter extends MethodMirror.Parameter {
@Getter
private final AnnotationHolder.ParameterAnnotationHolder annotations =
new AnnotationHolder.ParameterAnnotationHolder(this);
Parameter(TypeMirror type) {
super(type);
}
public void remove() {
if (!parameters.remove(this)) {
throw new IllegalStateException();
}
annotations.set(null);
removeRef();
}
}
}
| 31.489933 | 116 | 0.654305 |
72de0fb42394707b2a99ece38bbe553f18a643c3 | 305 | package org.onosproject.incubator.net.resource.label;
import com.google.common.annotations.Beta;
import org.onosproject.event.EventListener;
/**
* Entity capable of receiving label resource related events.
*/
@Beta
public interface LabelResourceListener extends EventListener<LabelResourceEvent> {
}
| 23.461538 | 82 | 0.813115 |
8b9b27de9e418076f9602161ec71bf8531eea05b | 2,693 | package com.gail.sps.model;
import java.util.Date;
import java.util.List;
/**
* 订单
*
* @author pxuxian
*/
public class Order extends BaseModel {
private static final long serialVersionUID = -7894012960696879502L;
private Integer id;
private String number;
private Date createTime;
private User user;
private String receiver; // 收货人
private String address;
private String mobile;
private String telphone;
private List<OrderProduct> orderProducts;
private int count;
private double amount; // 商品金额
private double postage; // 邮费
private double discount; // 优惠
private double total; // 总计
private Integer status;
private String statusStr;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void setId(Integer id) {
this.id = id;
}
public List<OrderProduct> getOrderProducts() {
return orderProducts;
}
public void setOrderProducts(List<OrderProduct> orderProducts) {
this.orderProducts = orderProducts;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getTelphone() {
return telphone;
}
public void setTelphone(String telphone) {
this.telphone = telphone;
}
public double getPostage() {
return postage;
}
public void setPostage(double postage) {
this.postage = postage;
}
public double getDiscount() {
return discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getStatusStr() {
return statusStr;
}
public void setStatusStr(String statusStr) {
this.statusStr = statusStr;
}
}
| 16.420732 | 68 | 0.704419 |
4a9c183a910dac1a1ffd5dd00a4423298d28fc40 | 4,249 | /*Copyright [2018] [Kürsat Aydinli & Remo Schenker]
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 ase.rsse.app;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import ase.rsse.apirec.transactions.ITransactionConstants;
import ase.rsse.apirec.transactions.MethodMatch;
import ase.rsse.apirec.transactions.TransactionUtility;
import ase.rsse.utilities.IoUtility;
import cc.kave.commons.model.events.completionevents.CompletionEvent;
import cc.kave.commons.model.events.completionevents.ICompletionEvent;
import cc.kave.commons.model.ssts.impl.SST;
public class TransactionUtilityTest {
public static File TRANSACTION_DIRECTORY;
public static List<ICompletionEvent> TEST_COMPLETION_EVENTS;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
TRANSACTION_DIRECTORY= new File(ITransactionConstants.TRANSACTION_DIRECTORY);
TEST_COMPLETION_EVENTS = IoUtility.readEvent("C:\\workspaces\\ase_rsse\\apirec\\Events-170301-2\\2016-08-06\\2.zip");
Assert.assertTrue(TEST_COMPLETION_EVENTS.size() > 200);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
File testTransactionDirectory = new File(ITransactionConstants.TRANSACTION_DIRECTORY);
for (File f: testTransactionDirectory.listFiles()) {
if (f.getName().startsWith("test_")) {
f.delete();
}
}
}
@Test
public void testCreateMatch() {
List<ICompletionEvent> ceSorted = TEST_COMPLETION_EVENTS.stream()
.filter(Objects::nonNull)
.sorted(Comparator.comparing(ICompletionEvent::getTriggeredAt, Comparator.reverseOrder()))
.collect(Collectors.toList());
// test case: everything stays the same -> no transaction created
SST oldSST = (SST) ceSorted.get(0).getContext().getSST();
SST newSST = oldSST;
ArrayList<MethodMatch> matching = TransactionUtility.matchMethods(oldSST.getMethods(), newSST.getMethods());
Assert.assertNotNull(matching);
Assert.assertEquals(1, matching.get(0).getSimilarity(), 0.01);
TransactionUtility.createTransaction((CompletionEvent) ceSorted.get(0), (CompletionEvent) ceSorted.get(0), 1);
File[] testFiles = TRANSACTION_DIRECTORY.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if (name.startsWith("test_")) {
return true;
}
return false;
}
});
// we do not persist empty transactions
Assert.assertEquals(0, testFiles.length);
}
@Test
public void testMatchWithDifferences() {
List<ICompletionEvent> ceSorted = TEST_COMPLETION_EVENTS.stream()
.filter(Objects::nonNull)
.sorted(Comparator.comparing(ICompletionEvent::getTriggeredAt, Comparator.reverseOrder()))
.collect(Collectors.toList());
SST oldSST = (SST) ceSorted.get(185).getContext().getSST();
SST newSST = (SST) ceSorted.get(192).getContext().getSST();
ArrayList<MethodMatch> matching = TransactionUtility.matchMethods(oldSST.getMethods(), newSST.getMethods());
Assert.assertNotNull(matching);
TransactionUtility.createTransaction((CompletionEvent) ceSorted.get(185), (CompletionEvent) ceSorted.get(192), -100);
File[] testFiles = TRANSACTION_DIRECTORY.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if (name.endsWith("-100.json")) {
return true;
}
return false;
}
});
// we do not persist empty transactions
Assert.assertTrue(testFiles.length > 0);
}
}
| 36.008475 | 120 | 0.738762 |
3e1fc37fa0ebd60cf3b447c594ee734fa72dd5e2 | 321 | package com.google.sps;
import java.util.Comparator;
/**
* A comparator for sorting ranges by their start time in ascending order.
*/
public final class TimeRangeComparator implements Comparator<TimeRange> {
public int compare(TimeRange a, TimeRange b) {
return Long.compare(a.start(), b.start());
}
} | 26.75 | 74 | 0.719626 |
31ab3b7e3053dcfcbace5e6973975534f05268aa | 5,082 | package eventos.com.br.eventos.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by HP-HP on 03-07-2015.
*/
public class ImageCompression {
private Context context;
private static final float maxHeight = 1280.0f;
private static final float maxWidth = 1280.0f;
//private static final float maxHeight = 800.0f;
//private static final float maxWidth = 800.0f;
public ImageCompression(Context context) {
this.context = context;
}
public String compressImage(String imagemOriginal, String imagemNova) {
Bitmap scaledBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(imagemOriginal, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
float imgRatio = (float) actualWidth / (float) actualHeight;
float maxRatio = maxWidth / maxHeight;
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
bmp = BitmapFactory.decodeFile(imagemOriginal, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.RGB_565);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
if (bmp != null) {
bmp.recycle();
}
ExifInterface exif;
try {
exif = new ExifInterface(imagemOriginal);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream out = null;
try {
out = new FileOutputStream(imagemNova);
//write the compressed bitmap at the destination specified by filename.
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return imagemNova;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
}
| 35.048276 | 132 | 0.621409 |
d5b7e312ccb6d78c10b06ca2f753866f32e4136b | 335 | package lsm.helpers.IO.write.text;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class TextWriter {
public static BufferedWriter getWriter(String filename, boolean overwrite) throws IOException {
return new BufferedWriter(new FileWriter(filename, !overwrite));
}
} | 25.769231 | 99 | 0.761194 |
07a5e477f16611db66675bb695dcd5130262ad76 | 220 | package criterioDeBusqueda;
import java.util.List;
import encuesta.Encuesta;
import proyecto.Proyecto;
public interface CriterioDeBusqueda {
public List<Encuesta> filtrarPorCriterio(List<Proyecto> proyectos);
}
| 15.714286 | 68 | 0.804545 |
fcaf64787db2579d2ef80c144e8a8ef18abfc05b | 4,803 | /*
* 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.stanbol.enhancer.engines.htmlextractor.impl;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
*
* @author <a href="mailto:[email protected]">Walter Kasper</a>
*
*/
public final class DOMBuilder {
/**
* Restrict instantiation
*/
private DOMBuilder() {}
/**
* Returns a W3C DOM that exposes the same content as the supplied Jsoup document into a W3C DOM.
* @param jsoupDocument The Jsoup document to convert.
* @return A W3C Document.
*/
public static Document jsoup2DOM(org.jsoup.nodes.Document jsoupDocument) {
Document document = null;
try {
/* Obtain the document builder for the configured XML parser. */
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
/* Create a document to contain the content. */
document = docBuilder.newDocument();
createDOM(jsoupDocument, document, document, new HashMap<String,String>());
} catch (ParserConfigurationException pce) {
throw new RuntimeException(pce);
}
return document;
}
/**
* The internal helper that copies content from the specified Jsoup <tt>Node</tt> into a W3C {@link Node}.
* @param node The Jsoup node containing the content to copy to the specified W3C {@link Node}.
* @param out The W3C {@link Node} that receives the DOM content.
*/
private static void createDOM(org.jsoup.nodes.Node node, Node out, Document doc, Map<String,String> ns) {
if (node instanceof org.jsoup.nodes.Document) {
org.jsoup.nodes.Document d = ((org.jsoup.nodes.Document) node);
for (org.jsoup.nodes.Node n : d.childNodes()) {
createDOM(n, out,doc,ns);
}
} else if (node instanceof org.jsoup.nodes.Element) {
org.jsoup.nodes.Element e = ((org.jsoup.nodes.Element) node);
org.w3c.dom.Element _e = doc.createElement(e.tagName());
out.appendChild(_e);
org.jsoup.nodes.Attributes atts = e.attributes();
for(org.jsoup.nodes.Attribute a : atts){
String attName = a.getKey();
//omit xhtml namespace
if (attName.equals("xmlns")) {
continue;
}
String attPrefix = getNSPrefix(attName);
if (attPrefix != null) {
if (attPrefix.equals("xmlns")) {
ns.put(getLocalName(attName), a.getValue());
}
else if (!attPrefix.equals("xml")) {
String namespace = ns.get(attPrefix);
if (namespace == null) {
//fix attribute names looking like qnames
attName = attName.replace(':','_');
}
}
}
_e.setAttribute(attName, a.getValue());
}
for (org.jsoup.nodes.Node n : e.childNodes()) {
createDOM(n, _e, doc,ns);
}
} else if (node instanceof org.jsoup.nodes.TextNode) {
org.jsoup.nodes.TextNode t = ((org.jsoup.nodes.TextNode) node);
if (!(out instanceof Document)) {
out.appendChild(doc.createTextNode(t.text()));
}
}
}
// some hacks for handling namespace in jsoup2DOM conversion
private static String getNSPrefix(String name) {
if (name != null) {
int pos = name.indexOf(':');
if (pos > 0) {
return name.substring(0,pos);
}
}
return null;
}
private static String getLocalName(String name) {
if (name != null) {
int pos = name.lastIndexOf(':');
if (pos > 0) {
return name.substring(pos+1);
}
}
return name;
}
}
| 32.89726 | 109 | 0.622736 |
19c44d13e0b4a2f308914f3792c32ed0b8a78cd1 | 516 | package com.github.prbpedro.ctf.repositorios;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.github.prbpedro.ctf.entidades.Account;
import com.github.prbpedro.ctf.util.Constantes;
@Repository
public interface AccountRepository extends JpaRepository<Account, Long>{
@Query(Constantes.QUERY_EXIST_ACCOUNT_BY_DOCUMENT_NUMBER)
boolean existsByDocumentNumber(Long documentNumber);
}
| 30.352941 | 72 | 0.848837 |
0dfa0df754e107205c9e695c97ed1562bd5ec10d | 2,363 | package com.softib.core.entities;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.softib.core.entities.codes.ContactType;
@Entity
public class Contact {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Enumerated(EnumType.STRING)
private ContactType contactType;
String contact ;
@ManyToOne
@JoinColumn(name = "userId", referencedColumnName = "userId", insertable=false, updatable=false)
User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ContactType getContactType() {
return contactType;
}
public void setContactType(ContactType contactType) {
this.contactType = contactType;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((contact == null) ? 0 : contact.hashCode());
result = prime * result + ((contactType == null) ? 0 : contactType.hashCode());
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Contact other = (Contact) obj;
if (contact == null) {
if (other.contact != null)
return false;
} else if (!contact.equals(other.contact))
return false;
if (contactType != other.contactType)
return false;
if (id != other.id)
return false;
return true;
}
@Override
public String toString() {
return "Contact [id=" + id + ", contactType=" + contactType + ", contact=" + contact + "]";
}
public Contact() {
super();
}
public Contact(int id, ContactType contactType, String contact) {
super();
this.id = id;
this.contactType = contactType;
this.contact = contact;
}
}
| 20.547826 | 98 | 0.656369 |
f8129e35c738b09b806014a4f31d448bc962d2d8 | 1,852 | package it.kamaladafrica.cdi.axonframework.extension.impl;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Set;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InjectionPoint;
import org.axonframework.eventsourcing.eventstore.EventStore;
import it.kamaladafrica.cdi.axonframework.support.CdiUtils;
public class EventSchedulerInfo {
private final Type type;
private final Set<Annotation> qualifiers;
private EventSchedulerInfo(final Type type, final Set<Annotation> qualifiers) {
this.type = type;
this.qualifiers = CdiUtils.normalizedQualifiers(qualifiers);
}
public Type getType() {
return type;
}
public Set<Annotation> getQualifiers() {
return qualifiers;
}
public EventStore getEventStoreReference(final BeanManager bm) {
return (EventStore) CdiUtils.getReference(bm, EventStore.class, qualifiers);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((qualifiers == null) ? 0 : qualifiers.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EventSchedulerInfo other = (EventSchedulerInfo) obj;
if (qualifiers == null) {
if (other.qualifiers != null)
return false;
} else if (!qualifiers.equals(other.qualifiers))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
public static EventSchedulerInfo of(final InjectionPoint injectionPoint) {
return new EventSchedulerInfo(injectionPoint.getType(),
injectionPoint.getQualifiers());
}
}
| 25.027027 | 80 | 0.726782 |
5bc78172a7489ddc9f5059104230d64abeb7727d | 603 | package com.nacid.bl.exceptions;
public class NotAuthorizedException extends Exception {
public NotAuthorizedException() {
super();
// TODO Auto-generated constructor stub
}
public NotAuthorizedException(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
public NotAuthorizedException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public NotAuthorizedException(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
}
| 23.192308 | 64 | 0.660033 |
6be77dd646c6d1b191b7a43020b718f04aaf35f2 | 1,387 | package umd.twittertools.kde;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
import umontreal.iro.lecuyer.gof.KernelDensity;
import umontreal.iro.lecuyer.probdist.EmpiricalDist;
import umontreal.iro.lecuyer.probdist.NormalDist;
public class WeightKDEExample {
private final static int LENGTH = 100;
private static Random random = new Random();
private static double points[] = new double[LENGTH];
private static double weights[] = new double[LENGTH];
public static void main(String[] args) throws IOException {
// Points are random generated by Normal Gaussian Distribution
// Each point is assigned a weight in the range of [0, 1]
int i = 0;
String line;
BufferedReader br = new BufferedReader(new FileReader("points.txt"));
while((line = br.readLine()) != null) {
String groups[] = line.split(" ");
points[i] = Double.parseDouble(groups[0]);
weights[i] = Double.parseDouble(groups[1]);
i++;
}
// Weighted Kernel Density Estimates
Data data = new Data(points, weights);
data.computeStatistics();
NormalDist kernel = new NormalDist();
double[] estimateValues = WeightKDE.computeDensity(data, kernel, points);
for (double value: estimateValues) {
System.out.println(value);
}
}
}
| 30.152174 | 76 | 0.734679 |
0a733a65eb7fc6f28d062b661cd83c153fa96591 | 548 | package com.example.demo.service;
import java.util.List;
import com.example.demo.model.Note;
//@Service
public interface NoteService {
/*
* public Note create(@Valid Note note) {
*
* Note tempNote = new Note(1, note.getTopic(), note.getSubject(),
* note.getBody());
*
* return tempNote; }
*/
Note create(Note note) throws Exception;
Note update(Note note) throws Exception;
String delete(Integer noteId) throws Exception;
List<Note> findNotes(String createdBy, Integer id) throws Exception;
}
| 20.296296 | 70 | 0.675182 |
d76d6d5855dc28b8efbf8d96a1f669ce9d412462 | 1,294 | package org.ei.opensrp.service.intentservices;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
/**
* Created by onamacuser on 18/03/2016.
*/
public class ReplicationIntentService extends IntentService {
private static final String TAG = ReplicationIntentService.class.getCanonicalName();
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public ReplicationIntentService(String name) {
super(name);
}
public ReplicationIntentService() {
super("ReplicationIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
try {
// CloudantSyncHandler mCloudantSyncHandler = CloudantSyncHandler.getInstance(Context.getInstance().applicationContext());
// CountDownLatch mCountDownLatch = new CountDownLatch(2);
// mCloudantSyncHandler.setCountDownLatch(mCountDownLatch);
// mCloudantSyncHandler.startPullReplication();
// mCloudantSyncHandler.startPushReplication();
//
// mCountDownLatch.await();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
}
| 28.755556 | 133 | 0.680062 |
d2cda9b48498e680639453a10827b333adc543bc | 5,875 | package com.huawei.mops.components.retrofit.retrofitrxcache;
import android.util.Log;
import java.util.concurrent.CountDownLatch;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
/**
* 缓存+网络请求
* User: cpoopc
* Date: 2016-01-18
* Time: 10:19
* Ver.: 0.1
*/
public class AsyncOnSubscribeCacheNet<T> implements Observable.OnSubscribe<T> {
private final boolean debug = true;
private final String TAG = "OnSubscribeCacheNet:";
// 读取缓存
protected ObservableWrapper<T> cacheObservable;
// 读取网络
protected ObservableWrapper<T> netObservable;
// 网络读取完毕,缓存动作
protected Action1<T> storeCacheAction;
protected CountDownLatch cacheLatch = new CountDownLatch(1);
protected CountDownLatch netLatch = new CountDownLatch(1);
public AsyncOnSubscribeCacheNet(Observable<T> cacheObservable, Observable<T> netObservable, Action1<T> storeCacheAction) {
this.cacheObservable = new ObservableWrapper<T>(cacheObservable);
this.netObservable = new ObservableWrapper<T>(netObservable);
this.storeCacheAction = storeCacheAction;
}
@Override
public void call(Subscriber<? super T> subscriber) {
cacheObservable.getObservable().subscribeOn(Schedulers.io()).unsafeSubscribe(new CacheObserver<T>(cacheObservable, subscriber, storeCacheAction));
netObservable.getObservable().subscribeOn(Schedulers.io()).unsafeSubscribe(new NetObserver<T>(netObservable, subscriber, storeCacheAction));
}
class ObservableWrapper<T> {
Observable<T> observable;
T data;
public ObservableWrapper(Observable<T> observable) {
this.observable = observable;
}
public Observable<T> getObservable() {
return observable;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
class NetObserver<T> extends Subscriber<T> {
ObservableWrapper<T> observableWrapper;
Subscriber<? super T> subscriber;
Action1<T> storeCacheAction;
public NetObserver(ObservableWrapper<T> observableWrapper, Subscriber<? super T> subscriber, Action1<T> storeCacheAction) {
this.observableWrapper = observableWrapper;
this.subscriber = subscriber;
this.storeCacheAction = storeCacheAction;
}
@Override
public void onCompleted() {
if (debug) Log.i(TAG, "net onCompleted ");
try {
if (storeCacheAction != null) {
logThread("保存到本地缓存 ");
storeCacheAction.call(observableWrapper.getData());
}
} catch (Exception e) {
onError(e);
}
if (subscriber != null && !subscriber.isUnsubscribed()) {
subscriber.onCompleted();
}
netLatch.countDown();
}
@Override
public void onError(Throwable e) {
if (debug) Log.e(TAG, "net onError ");
try {
if (debug) Log.e(TAG, "net onError await if cache not completed.");
cacheLatch.await();
if (debug) Log.e(TAG, "net onError await over.");
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (subscriber != null && !subscriber.isUnsubscribed()) {
subscriber.onError(e);
}
}
@Override
public void onNext(T o) {
if (debug) Log.i(TAG, "net onNext o:" + o);
observableWrapper.setData(o);
logThread("");
if (debug) Log.e(TAG, " check subscriber :" + subscriber + " isUnsubscribed:" + subscriber.isUnsubscribed());
if (subscriber != null && !subscriber.isUnsubscribed()) {
subscriber.onNext(o);// FIXME: issue A:外面如果ObservableOn 其他线程,将会是异步操作,如果在实际的onNext调用之前,发生了onComplete或者onError,将会unsubscribe,导致onNext没有被调用
}
}
}
class CacheObserver<T> extends Subscriber<T> {
ObservableWrapper<T> observableWrapper;
Subscriber<? super T> subscriber;
Action1<T> storeCacheAction;
public CacheObserver(ObservableWrapper<T> observableWrapper, Subscriber<? super T> subscriber, Action1<T> storeCacheAction) {
this.observableWrapper = observableWrapper;
this.subscriber = subscriber;
this.storeCacheAction = storeCacheAction;
}
@Override
public void onCompleted() {
if (debug) Log.i(TAG, "cache onCompleted");
cacheLatch.countDown();
}
@Override
public void onError(Throwable e) {
if (debug) Log.e(TAG, "cache onError");
Log.e(TAG, "read cache error:" + e.getMessage());
if (debug) e.printStackTrace();
cacheLatch.countDown();
}
@Override
public void onNext(T o) {
if (debug) Log.i(TAG, "cache onNext o:" + o);
observableWrapper.setData(o);
logThread("");
if (netLatch.getCount() > 0) {
if (debug) Log.e(TAG, " check subscriber :" + subscriber + " isUnsubscribed:" + subscriber.isUnsubscribed());
if (subscriber != null && !subscriber.isUnsubscribed()) {
subscriber.onNext(o);// FIXME: issue A:外面如果ObservableOn 其他线程,将会是异步操作,如果在实际的onNext调用之前,发生了onComplete或者onError,将会unsubscribe,导致onNext没有被调用
}
} else {
if (debug) Log.e(TAG, "net result had been load,so cache is not need to load");
}
}
}
public void logThread(String tag) {
if (debug) Log.i(TAG, tag + " : " + Thread.currentThread().getName());
}
}
| 33.764368 | 156 | 0.599149 |
8efa9852cd1e63ed22282fc9487967947524949e | 2,551 | /*
* Copyright (c) 2018. University of Applied Sciences and Arts Northwestern Switzerland FHNW.
* All rights reserved.
*/
package ch.fhnw.digibp.examples.message;
import java.io.IOException;
import ch.fhnw.digibp.examples.api.ChoreographyEndpoints;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
@EnableBinding(Sink.class)
public class MessageListenersChoreography {
@Autowired
private MessageSender messageSender;
private static Logger logger = LoggerFactory.getLogger(ChoreographyEndpoints.class);
@StreamListener(target = Sink.INPUT,
condition="payload.messageType.toString()=='CheckoutDone'")
@Transactional
public void payment(String messageJson) throws IOException {
Message<String> message = new ObjectMapper().readValue(messageJson, new TypeReference<Message<String>>(){});
String payload = message.getPayload();
logger.info("Payload received: "+payload+". Payment done. Payload sent: " + payload + ".");
messageSender.send(new Message<String>("PaymentDone", payload));
}
@StreamListener(target = Sink.INPUT,
condition="payload.messageType.toString()=='PaymentDone'")
@Transactional
public void inventory(String messageJson) throws IOException {
Message<String> message = new ObjectMapper().readValue(messageJson, new TypeReference<Message<String>>(){});
String payload = message.getPayload();
logger.info("Payload received: "+payload+". Inventory done. Payload sent: " + payload + ".");
messageSender.send(new Message<String>("InventoryDone", payload));
}
@StreamListener(target = Sink.INPUT,
condition="payload.messageType.toString()=='InventoryDone'")
@Transactional
public void shipping(String messageJson) throws IOException {
Message<String> message = new ObjectMapper().readValue(messageJson, new TypeReference<Message<String>>(){});
String payload = message.getPayload();
logger.info("Payload received: "+payload+". Shipping done.");
}
}
| 37.514706 | 116 | 0.736966 |
f5dce412a3d0162d05c5485aa3c36aea149e8dbc | 1,902 | package com.baidu.beidou.navi.codec.protobuf;
import com.baidu.beidou.navi.codec.Codec;
import com.baidu.beidou.navi.util.ReflectionUtil;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
/**
* ClassName: ProtobufCodec <br/>
* Function: 运行时Protobuf编码器
*
* @author Zhang Xu
*/
public class ProtobufCodec implements Codec {
/**
* 初始化一些参数
*/
static {
System.setProperty("protostuff.runtime.collection_schema_on_repeated_fields", "true");
System.setProperty("protostuff.runtime.morph_collection_interfaces", "true");
System.setProperty("protostuff.runtime.morph_map_interfaces", "true");
}
/**
* buffer
*/
private ThreadLocal<LinkedBuffer> linkedBuffer = new ThreadLocal<LinkedBuffer>() {
@Override
protected LinkedBuffer initialValue() {
return LinkedBuffer.allocate(500);
}
};
/**
* @see com.baidu.beidou.navi.codec.Codec#decode(java.lang.Class, byte[])
*/
@Override
public <T> T decode(Class<T> clazz, byte[] bytes) throws Exception {
Schema<T> schema = RuntimeSchema.getSchema(clazz);
T content = ReflectionUtil.newInstance(clazz);
ProtobufUtils.mergeFrom(bytes, content, schema);
return content;
}
/**
* @see com.baidu.beidou.navi.codec.Codec#encode(java.lang.Class, java.lang.Object)
*/
@Override
public <T> byte[] encode(Class<T> clazz, T object) throws Exception {
try {
Schema<T> schema = RuntimeSchema.getSchema(clazz);
byte[] protostuff = ProtobufUtils.toByteArray(object, schema, linkedBuffer.get());
return protostuff;
} finally {
linkedBuffer.get().clear();
}
}
}
| 30.677419 | 95 | 0.634069 |
e9d7424b9d6a3e9ae29feb5885d92cf415f9ea28 | 2,513 | package com.github.conversations.sample.webapp.configuration;
import com.github.conversations.sample.webapp.users.SampleUserRepository;
import com.github.conversations.sample.webapp.users.SampleUserService;
import com.github.maximilientyc.conversations.domain.ConversationFactory;
import com.github.maximilientyc.conversations.domain.ParticipantFactory;
import com.github.maximilientyc.conversations.domain.repositories.ConversationRepository;
import com.github.maximilientyc.conversations.domain.repositories.MessageRepository;
import com.github.maximilientyc.conversations.domain.repositories.mongodb.MongoDbConversationRepository;
import com.github.maximilientyc.conversations.domain.repositories.mongodb.MongoDbMessageRepository;
import com.github.maximilientyc.conversations.domain.services.ConversationService;
import com.github.maximilientyc.conversations.domain.services.UserService;
import com.github.maximilientyc.conversations.restadapter.ConversationController;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.UnknownHostException;
/**
* Created by @maximilientyc on 10/05/2016.
*/
@Configuration
public class ConversationsConfiguration {
private final MongoDatabase mongoDatabase;
private final ConversationRepository conversationRepository;
private final ParticipantFactory participantFactory;
private final UserService userService;
private final ConversationService conversationService;
private final ConversationFactory conversationFactory;
private final MessageRepository messageRepository;
public ConversationsConfiguration() {
MongoClient mongo = new MongoClient("localhost");
this.mongoDatabase = mongo.getDatabase("conversations");
this.conversationRepository = new MongoDbConversationRepository(mongoDatabase);
this.participantFactory = new ParticipantFactory(new SampleUserRepository());
this.userService = new SampleUserService();
this.messageRepository = new MongoDbMessageRepository(mongoDatabase);
this.conversationService = new ConversationService(conversationRepository, messageRepository);
this.conversationFactory = new ConversationFactory(conversationService);
}
@Bean
public ConversationController conversationController() throws UnknownHostException {
return new ConversationController(
participantFactory,
conversationRepository,
conversationFactory,
userService);
}
}
| 44.875 | 104 | 0.853561 |
fc56195c85e265cd72c6ce4beef61270108a6365 | 1,708 | /**
* Copyright 2020 lambdaprime
*
* Email: [email protected]
* Website: https://github.com/lambdaprime
*
*/
package id.fireguard.net;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import id.xfunction.ObjectStore;
public class NetworkStore {
private ObjectStore<HashSet<NetworkEntity>> store;
private HashSet<NetworkEntity> set;
public NetworkStore(Path file) {
this(new ObjectStore<>(file));
}
public NetworkStore(ObjectStore<HashSet<NetworkEntity>> store) {
this.store = store;
this.set = store.load().orElse(new HashSet<>());
}
public void add(NetworkEntity entity) {
if (findAll().stream().map(NetworkEntity::getSubnet)
.anyMatch(Predicate.isEqual(entity.getSubnet())))
throw new RuntimeException("Net with such subnet already exist");
set.add(entity);
save();
}
public void update(NetworkEntity entity) {
set.remove(entity);
set.add(entity);
save();
}
public void save() {
store.save(set);
}
public Set<NetworkEntity> findAll() {
return set;
}
public Optional<NetworkEntity> findNet(String netId) {
return set.stream()
.filter(net -> net.getId().equals(netId))
.findFirst();
}
public Optional<NetworkInterfaceEntity> findIface(String ifaceId) {
return set.stream()
.map(NetworkEntity::getIfaces)
.flatMap(Set::stream)
.filter(iface -> iface.getId().equals(ifaceId))
.findFirst();
}
}
| 25.117647 | 77 | 0.614169 |
d02d0501935e83193efb53f6dcaca1a390688eb2 | 4,559 | /*
* Copyright 2006-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.core.step.item;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.repeat.RepeatContext;
import org.springframework.batch.repeat.exception.ExceptionHandler;
import org.springframework.batch.repeat.support.RepeatSynchronizationManager;
import org.springframework.classify.BinaryExceptionClassifier;
import org.springframework.retry.RetryCallback;
import org.springframework.retry.RetryContext;
import org.springframework.retry.RetryPolicy;
import org.springframework.retry.listener.RetryListenerSupport;
import java.util.Collection;
/**
* An {@link ExceptionHandler} that is aware of the retry context so that it can
* distinguish between a fatal exception and one that can be retried. Delegates the actual
* exception handling to another {@link ExceptionHandler}.
*
* @author Dave Syer
*
*/
public class SimpleRetryExceptionHandler extends RetryListenerSupport implements ExceptionHandler {
/**
* Attribute key, whose existence signals an exhausted retry.
*/
private static final String EXHAUSTED = SimpleRetryExceptionHandler.class.getName() + ".RETRY_EXHAUSTED";
private static final Log logger = LogFactory.getLog(SimpleRetryExceptionHandler.class);
final private RetryPolicy retryPolicy;
final private ExceptionHandler exceptionHandler;
final private BinaryExceptionClassifier fatalExceptionClassifier;
/**
* Create an exception handler from its mandatory properties.
* @param retryPolicy the retry policy that will be under effect when an exception is
* encountered
* @param exceptionHandler the delegate to use if an exception actually needs to be
* handled
* @param fatalExceptionClasses exceptions
*/
public SimpleRetryExceptionHandler(RetryPolicy retryPolicy, ExceptionHandler exceptionHandler,
Collection<Class<? extends Throwable>> fatalExceptionClasses) {
this.retryPolicy = retryPolicy;
this.exceptionHandler = exceptionHandler;
this.fatalExceptionClassifier = new BinaryExceptionClassifier(fatalExceptionClasses);
}
/**
* Check if the exception is going to be retried, and veto the handling if it is. If
* retry is exhausted or the exception is on the fatal list, then handle using the
* delegate.
*
* @see ExceptionHandler#handleException(org.springframework.batch.repeat.RepeatContext,
* java.lang.Throwable)
*/
@Override
public void handleException(RepeatContext context, Throwable throwable) throws Throwable {
// Only bother to check the delegate exception handler if we know that
// retry is exhausted
if (fatalExceptionClassifier.classify(throwable) || context.hasAttribute(EXHAUSTED)) {
logger.debug("Handled fatal exception");
exceptionHandler.handleException(context, throwable);
}
else {
logger.debug("Handled non-fatal exception", throwable);
}
}
/**
* If retry is exhausted set up some state in the context that can be used to signal
* that the exception should be handled.
*
* @see org.springframework.retry.RetryListener#close(org.springframework.retry.RetryContext,
* org.springframework.retry.RetryCallback, java.lang.Throwable)
*/
@Override
public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback,
Throwable throwable) {
if (!retryPolicy.canRetry(context)) {
if (logger.isDebugEnabled()) {
logger.debug("Marking retry as exhausted: " + context);
}
getRepeatContext().setAttribute(EXHAUSTED, "true");
}
}
/**
* Get the parent context (the retry is in an inner "chunk" loop and we want the
* exception to be handled at the outer "step" level).
* @return the {@link RepeatContext} that should hold the exhausted flag.
*/
private RepeatContext getRepeatContext() {
RepeatContext context = RepeatSynchronizationManager.getContext();
if (context.getParent() != null) {
return context.getParent();
}
return context;
}
}
| 37.368852 | 106 | 0.770783 |
a721c2a9dafaf702517a7983d268638a84da884d | 603 | package net.javavatutorial.tutorials;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class RestControllerExample {
@RequestMapping("/hellorest")
String helloRest() {
return("Hello World. This is produced by the rest conntroller method");
}
public static void main(String[] args) {
SpringApplication.run(RestControllerExample.class, args);
}
}
| 27.409091 | 73 | 0.814262 |
9e2d6919b71724d9ebe3a5acfe36b9620f68d4fe | 4,776 | /*
* @(#)AbstractProjectAction.java 1.0 October 9, 2005
*
* Copyright (c) 1996-2006 by the original authors of JHotDraw
* and all its contributors ("JHotDraw.org")
* All rights reserved.
*
* This software is the confidential and proprietary information of
* JHotDraw.org ("Confidential Information"). You shall not disclose
* such Confidential Information and shall use it only in accordance
* with the terms of the license agreement you entered into with
* JHotDraw.org.
*/
package org.jhotdraw.app.action;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.event.*;
import org.jhotdraw.app.Application;
import org.jhotdraw.app.Project;
/**
* An Action that acts on on the current <code>Project</code> of an
* <code>Application</code>.
* If the current Project object is disabled or is null, the
* AbstractProjectAction is disabled as well.
*
* @author Werner Randelshofer
* @version 1.0 October 9, 2005 Created.
* @see org.jhotdraw.app.Project
* @see org.jhotdraw.app.Application
*/
public abstract class AbstractProjectAction extends AbstractAction {
private Application app;
private PropertyChangeListener applicationListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName() == "currentProject") { // Strings get interned
updateProject((Project) evt.getOldValue(), (Project) evt.getNewValue());
}
}
};
private PropertyChangeListener projectListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName() == "enabled") { // Strings get interned
updateEnabled((Boolean) evt.getOldValue(), (Boolean) evt.getNewValue());
}
}
};
/** Creates a new instance. */
public AbstractProjectAction(Application app) {
this.app = app;
if (app != null) {
app.addPropertyChangeListener(applicationListener);
updateProject(null, app.getCurrentProject());
}
}
/**
* Updates the project of this action depending on the current project
* of the application.
*/
protected void updateProject(Project oldValue, Project newValue) {
if (oldValue != null) {
uninstallProjectListeners(oldValue);
}
if (newValue != null) {
installProjectListeners(newValue);
}
firePropertyChange("project", oldValue, newValue);
updateEnabled(oldValue != null && oldValue.isEnabled(),
newValue != null && newValue.isEnabled());
}
/**
* Installs listeners on the project object.
*/
protected void installProjectListeners(Project p) {
p.addPropertyChangeListener(projectListener);
}
/**
* Installs listeners on the project object.
*/
protected void uninstallProjectListeners(Project p) {
p.removePropertyChangeListener(projectListener);
}
/**
* Updates the enabled state of this action depending on the new enabled
* state of the project.
*/
protected void updateEnabled(boolean oldValue, boolean newValue) {
setEnabled(super.isEnabled());
firePropertyChange("projectEnabled", oldValue, newValue);
}
public Application getApplication() {
return app;
}
public Project getCurrentProject() {
return app.getCurrentProject();
}
/**
* Returns true if the action is enabled.
* The enabled state of the action depends on the state that has been set
* using setEnabled() and on the enabled state of the application.
*
* @return true if the action is enabled, false otherwise
* @see Action#isEnabled
*/
@Override public boolean isEnabled() {
return getCurrentProject() != null && getCurrentProject().isEnabled() || super.isEnabled();
}
/**
* Enables or disables the action. The enabled state of the action
* depends on the value that is set here and on the enabled state of
* the application.
*
* @param newValue true to enable the action, false to
* disable it
* @see Action#setEnabled
*/
@Override public void setEnabled(boolean newValue) {
boolean oldValue = this.enabled;
this.enabled = newValue;
boolean projIsEnabled = getCurrentProject() != null && getCurrentProject().isEnabled();
firePropertyChange("enabled",
Boolean.valueOf(oldValue && projIsEnabled),
Boolean.valueOf(newValue && projIsEnabled)
);
}
}
| 33.633803 | 99 | 0.645729 |
9746a81fa0cd3c8ddaf74a05d9790c3bf560c4b3 | 842 | import java.util.HashMap;
import java.util.Map;
public class LeetCode138 {
class Node {
public int val;
public Node next;
public Node random;
public Node() {}
public Node(int _val,Node _next,Node _random) {
val = _val;
next = _next;
random = _random;
}
};
public Node copyRandomList(Node head) {
if(head == null) return null;
Node p = head;
Node p2 = head;
Map<Node, Node> map = new HashMap();
while(p != null){
map.put(p, new Node(p.val,null,null));
p = p.next;
}
while(p2 != null){
map.get(p2).next = map.get(p2.next);
map.get(p2).random = map.get(p2.random);
p2 = p2.next;
}
return map.get(head);
}
}
| 22.157895 | 55 | 0.488124 |
6def976db7625d925465867ca4328790c6d1491d | 1,648 | /*
* 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.giraph.io.formats;
import org.apache.giraph.bsp.BspInputSplit;
import org.apache.hadoop.mapreduce.InputSplit;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Utility methods for PseudoRandom input formats
*/
public class PseudoRandomUtils {
/** Do not instantiate */
private PseudoRandomUtils() { }
/**
* Create desired number of {@link BspInputSplit}s
*
* @param numSplits How many splits to create
* @return List of {@link BspInputSplit}s
*/
public static List<InputSplit> getSplits(int numSplits) throws IOException,
InterruptedException {
List<InputSplit> inputSplitList = new ArrayList<InputSplit>();
for (int i = 0; i < numSplits; ++i) {
inputSplitList.add(new BspInputSplit(i, numSplits));
}
return inputSplitList;
}
}
| 32.96 | 77 | 0.73301 |
4f758bb01e416740a428faf7b50dfa93899a3a00 | 429 | /*
* This file is part of ResselChain.
* Copyright Center for Secure Energy Informatics 2018
* Fabian Knirsch, Andreas Unterweger, Clemens Brunner
* This code is licensed under a modified 3-Clause BSD License. See LICENSE file for details.
*/
package at.entrust.resselchain.communication;
import java.io.PrintWriter;
public interface IncomingMessageHandler {
void processMessage(String message, PrintWriter output);
}
| 28.6 | 92 | 0.785548 |
040e2dcbec7fd75ecded5e58477cf35b4e412566 | 808 | package com.team1458.turtleshell2.movement;
import com.team1458.turtleshell2.util.TurtleMaths;
import com.team1458.turtleshell2.util.types.MotorValue;
import edu.wpi.first.wpilibj.TalonSRX;
/**
* Implementation for control of a TalonSRX over PWM
* @author mehnadnerd
*
*/
public class TurtleTalonSRXPWM implements TurtleMotor {
private final TalonSRX v;
private final boolean isReversed;
public TurtleTalonSRXPWM(int port, boolean isReversed) {
v = new TalonSRX(port);
this.isReversed = isReversed;
}
public TurtleTalonSRXPWM(int port) {
this(port, false);
}
@Override
public void set(MotorValue val) {
v.set(TurtleMaths.reverseBool(isReversed)*val.getValue());
}
@Override
public MotorValue get() {
return new MotorValue(TurtleMaths.reverseBool(isReversed)*v.get());
}
}
| 21.263158 | 69 | 0.757426 |
e3238f5cd45fc6e094f75b9b7eb1efbdb70984a6 | 1,451 |
package mage.cards.m;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.common.TurnedFaceUpSourceTriggeredAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.continuous.BoostControlledEffect;
import mage.abilities.keyword.MorphAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Duration;
import static mage.filter.StaticFilters.FILTER_PERMANENT_CREATURES;
/**
*
* @author LevelX2
*/
public final class MasterOfPearls extends CardImpl {
public MasterOfPearls(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{W}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.MONK);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// Morph {3}{W}{W}
this.addAbility(new MorphAbility(this, new ManaCostsImpl("{3}{W}{W}")));
// When Master of Pearls is turned face up, creatures you control get +2/+2 until end of turn.
this.addAbility(new TurnedFaceUpSourceTriggeredAbility(new BoostControlledEffect(2, 2, Duration.EndOfTurn, FILTER_PERMANENT_CREATURES)));
}
private MasterOfPearls(final MasterOfPearls card) {
super(card);
}
@Override
public MasterOfPearls copy() {
return new MasterOfPearls(this);
}
}
| 31.543478 | 145 | 0.727085 |
ae46207b57c34c78fc8b220ccbef3c6fa39a4c68 | 7,795 | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is "SMS Library for the Java platform".
*
* The Initial Developer of the Original Code is Markus Eriksson.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.marre.sms;
import java.util.Iterator;
import java.util.LinkedList;
/**
* Represents a "Message Waiting" sms.
*
* As described in TS 23.040-650 section 9.2.3.24.2 "Special SMS Message Indication".
*
* On a Sony-Ericsson T610 these messages can be used to display different types of icons in the
* notification bar.
*
* @author Markus Eriksson
* @version $Id$
*/
public class SmsMwiMessage extends SmsTextMessage
{
/**
* Represents one message waiting udh.
*/
private static class MsgWaiting
{
private final MwiType type_;
private final int count_;
private final MwiProfile profile_;
private final boolean storeMessage_;
private MsgWaiting(MwiType type, int count, MwiProfile profile, boolean storeMessage)
{
this.type_ = type;
this.count_ = count;
this.profile_ = profile;
this.storeMessage_ = storeMessage;
}
int getCount()
{
return count_;
}
MwiType getType()
{
return type_;
}
public MwiProfile getProfile() {
return profile_;
}
public boolean storeMessage() {
return storeMessage_;
}
}
/**
* List of MsgWaiting "objects".
*/
protected final LinkedList<MsgWaiting> messages_ = new LinkedList<MsgWaiting>();
/**
* Creates an empty message.
*/
public SmsMwiMessage()
{
this("", SmsAlphabet.LATIN1);
}
/**
* Creates an message with the supplied text (GSM charset).
*
* @param text Description of this message.
*/
public SmsMwiMessage(String text)
{
this(text, SmsAlphabet.ASCII);
}
/**
* Creates an message with the supplied text and alphabet.
*
* @param text Description of this message
* @param alphabet Alphabet to use. Valid values are SmsDcs.ALPHABET_*.
*/
public SmsMwiMessage(String text, SmsAlphabet alphabet)
{
super(text, SmsDcs.getGeneralDataCodingDcs(alphabet, SmsMsgClass.CLASS_UNKNOWN));
}
/**
* Adds a message waiting.
*
* @param type Type of message that is waiting. Can be any of TYPE_*.
* @param count Number of messages waiting for retrieval.
*/
public void addMsgWaiting(MwiType type, int count)
{
addMsgWaiting(type, count, MwiProfile.ID_1, false);
}
/**
* Adds a message waiting.
*
* @param type Type of message that is waiting. Can be any of TYPE_*.
* @param count Number of messages waiting for retrieval.
* @param profile
* @param storeMessage
*/
public void addMsgWaiting(MwiType type, int count, MwiProfile profile, boolean storeMessage)
{
// count can be at most 255.
if (count > 255)
{
count = 255;
}
messages_.add(new MsgWaiting(type, count, profile, storeMessage));
}
/**
* Creates a "Message waiting" UDH element using UDH_IEI_SPECIAL_MESSAGE.
* <p>
* If more than one type of message is required to be indicated within
* one SMS message, then multiple "Message waiting" UDH elements must
* be used.
* <p>
* <b>Special handling in concatenated messages:</b><br>
* <i>
* "In the case where this IEI is to be used in a concatenated SM then the
* IEI, its associated IEI length and IEI data shall be contained in the
* first segment of the concatenated SM. The IEI, its associated IEI length
* and IEI data should also be contained in every subsequent segment of the
* concatenated SM although this is not mandatory. However, in the case
* where these elements are not contained in every subsequent segment of
* the concatenated SM and where an out of sequence segment delivery
* occurs or where the first segment is not delivered then processing
* difficulties may arise at the receiving entity which may result in
* the concatenated SM being totally or partially discarded."
* </i>
*
* @param msgWaiting The MsgWaiting to convert
* @return A SmsUdhElement
*/
protected SmsUdhElement getMessageWaitingUdh(MsgWaiting msgWaiting)
{
byte[] udh = new byte[2];
// Bit 0 and 1 indicate the basic indication type.
// Bit 4, 3 and 2 indicate the extended message indication type.
switch (msgWaiting.getType())
{
case VOICE: udh[0] = 0x00; break;
case FAX: udh[0] = 0x01; break;
case EMAIL: udh[0] = 0x02; break;
case VIDEO: udh[0] = 0x07; break;
}
// Bit 6 and 5 indicates the profile ID of the Multiple Subscriber Profile.
switch (msgWaiting.getProfile())
{
case ID_1: udh[0] |= 0x00; break;
case ID_2: udh[0] |= 0x20; break;
case ID_3: udh[0] |= 0x40; break;
case ID_4: udh[0] |= 0x60; break;
}
// Bit 7 indicates if the message shall be stored.
if (msgWaiting.storeMessage())
{
udh[0] |= (byte) (0x80);
}
// Octet 2 contains the number of messages waiting
udh[1] = (byte) (msgWaiting.getCount() & 0xff);
return new SmsUdhElement(SmsUdhIei.SPECIAL_MESSAGE, udh);
}
/**
* Builds a udh element for this message.
*
* @see org.marre.sms.SmsTextMessage#getUdhElements()
*/
public SmsUdhElement[] getUdhElements()
{
SmsUdhElement udhElements[] = null;
int msgCount = messages_.size();
if (msgCount > 0)
{
udhElements = new SmsUdhElement[messages_.size()];
int i = 0;
for(Iterator j = messages_.iterator(); j.hasNext(); i++)
{
MsgWaiting msgWaiting = (MsgWaiting) j.next();
udhElements[i] = getMessageWaitingUdh(msgWaiting);
}
}
return udhElements;
}
}
| 32.615063 | 96 | 0.623861 |
7626e7585f84d6b6d02f742ee6efd3db85fa0fdd | 2,646 | public class Coordinate{
public static final int MAX_COL = 3;
public static final int MAX_ROW = 3;
private int r;
private int c;
public Coordinate(int r, int c){
this.r = r;
this.c = c;
}
public int getRow(){
return r;
}
public int getCol(){
return c;
}
public boolean isCorner(){
if(
(r == 0 && c == 0) ||
(r == 0 && c == MAX_COL) ||
(r == MAX_ROW && c == 0) ||
(r == MAX_ROW && c == MAX_COL)
){
return true;
} else {
return false;
}
}
public boolean isSide(){
if(r == 0 || r == MAX_ROW || c == 0 || c == MAX_COL){
return true;
} else {
return false;
}
}
public boolean isCentral(){
if(isCorner() == false && isSide() == false){
return true;
} else {
return false;
}
}
public String toString(){
return "r = " + r
+ " , c = " + c;
}
// int arr[][] = {
// {1,2,3,4},
// {5,6,7,8},
// {9,10,11,12},
// {13,14,15,16}
// };
// public void swapButton(){
// arr[3][3] = arr[r][c] + arr[3][3];
// arr[r][c] = arr[3][3] - arr[r][c];
// arr[3][3] = arr[3][3] - arr[r][c];
// }
// // public void getCoordsCorner(){
// if(arr[r][c] == [0][0]){
// System.out.println("" + arr[0][1]);
// System.out.println("" + arr[1][0]);
// }
// if(arr[0][1] == arr[3][3] || arr[1][0] == arr[3][3]){
// swapButton();
// }
// }
// // public void getCoordsCorner()
// // // public int getCoordsMid(){
// // // if(arr[r][c] == [1][1] || arr[r][c] == [1][2] ||
// // // arr[r][c] == [2][1] || arr[r][c] == [2][2]){
// // // System.out.println("" + arr[1][1]);
// // // System.out.println("" + arr[1][2]);
// // // System.out.println("" + arr[2][1]);
// // // System.out.println("" + arr[2][2]);
// // // }
// // // if(arr[1][1] == arr[3][3] || arr[1][2] == arr[3][3]
// // // || arr[2][1] == arr[3][3] || arr[2][2] == arr[3][3]){
// // // swapButton();
// // // }
// // // }
// // public String swap(){
// // if(arr[0][1] == arr[3][3] || arr[1][0] == arr[3][3]){
// // swapButton();
// // }
// // }
// // public String swapButtonMid(){
// // if(arr[][])
// // // if(arr[1][1] == arr[3][3]){
// // // arr[1][1] = arr[0][0] + arr[1][1];
// // // arr[0][0] = arr[1][1] - arr[0][0];
// // // arr[1][1] = arr[1][1] - arr[0][0];
// // // }
// // // if else(arr[1][2] == arr[3][3]){
// // // arr[1][2] = arr[0][0] + arr[1][2];
// // // arr[0][0] = arr[1][2] - arr[0][0];
// // arr[1][2] = arr[1][2] - arr[0][0];
// // }
// // || ||
// // arr[2][1] instanceof " " || arr[2][2] instanceof " " )
// // }
} | 16.333333 | 65 | 0.406652 |
28b00e6e2fa23257600278236482b5e984501095 | 1,327 | package org.knowm.xchange.bx;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.knowm.xchange.exceptions.ExchangeException;
class BxProperties {
private String apiKey;
private String secretKey;
private final String fileName = "bx-secret.keys";
private final String API = "api-key";
private final String SECRET = "secret-key";
public BxProperties() throws IOException {
File file = new File(fileName);
if (!file.exists()) {
throw new ExchangeException(String.format("Properties file %s doesn't exists", fileName));
}
Properties properties = new Properties();
InputStream input = new FileInputStream(fileName);
properties.load(input);
apiKey = properties.getProperty(API);
secretKey = properties.getProperty(SECRET);
input.close();
}
private ExchangeException createException(String source) {
return new ExchangeException(
String.format("Please specify %s in the file %s", source, fileName));
}
public String getApiKey() {
if (apiKey.isEmpty()) {
throw createException(API);
}
return apiKey;
}
public String getSecretKey() {
if (secretKey.isEmpty()) {
throw createException(SECRET);
}
return secretKey;
}
}
| 26.54 | 96 | 0.703843 |
2f6e9a13577e213aeed7a85ce813e70391c45ff0 | 4,126 | /*
* 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.lucene.codecs.customcompression;
import java.io.IOException;
import java.util.Objects;
import org.apache.lucene.codecs.StoredFieldsFormat;
import org.apache.lucene.codecs.StoredFieldsReader;
import org.apache.lucene.codecs.StoredFieldsWriter;
import org.apache.lucene.codecs.compressing.CompressionMode;
import org.apache.lucene.codecs.lucene90.compressing.Lucene90CompressingStoredFieldsFormat;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.SegmentInfo;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
/** Stored field format used by plugaable codec */
public class Lucene90CustomCompressionStoredFieldsFormat extends StoredFieldsFormat {
// chunk size for zstandard
private static final int ZSTD_BLOCK_LENGTH = 10 * 48 * 1024;
public static final String MODE_KEY =
Lucene90CustomCompressionStoredFieldsFormat.class.getSimpleName() + ".mode";
final Lucene90CustomCompressionCodec.Mode mode;
private int compressionLevel;
/** default constructor */
public Lucene90CustomCompressionStoredFieldsFormat() {
this(
Lucene90CustomCompressionCodec.Mode.ZSTD_DICT,
Lucene90CustomCompressionCodec.defaultCompressionLevel);
}
/** Stored fields format with specified compression algo. */
public Lucene90CustomCompressionStoredFieldsFormat(
Lucene90CustomCompressionCodec.Mode mode, int compressionLevel) {
this.mode = Objects.requireNonNull(mode);
this.compressionLevel = compressionLevel;
}
@Override
public StoredFieldsReader fieldsReader(
Directory directory, SegmentInfo si, FieldInfos fn, IOContext context) throws IOException {
String value = si.getAttribute(MODE_KEY);
if (value == null) {
throw new IllegalStateException("missing value for " + MODE_KEY + " for segment: " + si.name);
}
Lucene90CustomCompressionCodec.Mode mode = Lucene90CustomCompressionCodec.Mode.valueOf(value);
return impl(mode).fieldsReader(directory, si, fn, context);
}
@Override
public StoredFieldsWriter fieldsWriter(Directory directory, SegmentInfo si, IOContext context)
throws IOException {
String previous = si.putAttribute(MODE_KEY, mode.name());
if (previous != null && previous.equals(mode.name()) == false) {
throw new IllegalStateException(
"found existing value for "
+ MODE_KEY
+ " for segment: "
+ si.name
+ "old="
+ previous
+ ", new="
+ mode.name());
}
return impl(mode).fieldsWriter(directory, si, context);
}
StoredFieldsFormat impl(Lucene90CustomCompressionCodec.Mode mode) {
switch (mode) {
case ZSTD:
return new Lucene90CompressingStoredFieldsFormat(
"CustomCompressionStoredFieldsZSTD", ZSTD_MODE_NO_DICT, ZSTD_BLOCK_LENGTH, 4096, 10);
case ZSTD_DICT:
return new Lucene90CompressingStoredFieldsFormat(
"CustomCompressionStoredFieldsZSTD", ZSTD_MODE_DICT, ZSTD_BLOCK_LENGTH, 4096, 10);
default:
throw new AssertionError();
}
}
public final CompressionMode ZSTD_MODE_NO_DICT = new ZstdCompressionMode(compressionLevel);
public final CompressionMode ZSTD_MODE_DICT = new ZstdDictCompressionMode(compressionLevel);
}
| 40.058252 | 100 | 0.741396 |
3408adf85415a7f44de1da8973d9239b765bd3b4 | 432 | package dev.wittek.tc.jakarta.time;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.time.LocalTime;
@Produces(MediaType.APPLICATION_JSON)
@Path("time")
public class TimeController {
@Inject
private TimeService timeService;
@GET
public LocalTime now() {
return timeService.now();
}
}
| 18 | 37 | 0.729167 |
fc653997cb356b341d5a988649598b833c02d045 | 334 | package no.nav.registre.inntekt.provider.rs.v1;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NoArgsConstructor;
import lombok.Value;
import java.time.LocalDateTime;
@Value
@Builder
@AllArgsConstructor
@NoArgsConstructor(force = true)
class Token {
LocalDateTime expires_in;
String access_token;
}
| 18.555556 | 47 | 0.802395 |
8e07e0df61476bc8d0e5ee62d3f6e561f51f62f8 | 1,077 | /*
* Copyright 2000-2020 Vaadin 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 com.vaadin.flow.server;
/**
* Exception thrown for failures in the generation of a deployment configuration
* object.
*/
public class VaadinConfigurationException extends Exception {
/**
* Exception constructor.
*
* @param message
* exception message
* @param exception
* exception cause
*/
public VaadinConfigurationException(String message, Exception exception) {
super(message, exception);
}
}
| 29.916667 | 80 | 0.703807 |
b516e5903a14e2a74d20cebd2b9f77f54b802250 | 661 | package ru.sdroman.carsales.repository;
import org.junit.Test;
import ru.sdroman.carsales.models.Car;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* @author sdroman
* @since 07.2018
*/
public class CarRepositoryTest {
/**
* CarRepository class test.
*/
@Test
public void carRepositoryTest() {
CarRepository repository = new CarRepository();
Car car = new Car();
car.setYear("2016");
int actualId = repository.addCar(car);
Car actualCar = repository.getCarById(1);
assertThat(actualId, is(1));
assertThat(actualCar, is(car));
}
}
| 21.322581 | 55 | 0.649017 |
4cd01c14c033392e3361028422965f66af118854 | 565 | package com.cdut.b2p.modules.shop.po;
/**
* @desc ShopCommentVo是ShopComment的扩展类
* @author zsb
*
*/
public class ShopCommentVo extends ShopComment{
private static final long serialVersionUID = 1L;
private String userNickname;//评论人的昵称
private String userImage;//评论人的头像
public String getUserNickname() {
return userNickname;
}
public void setUserNickname(String userNickname) {
this.userNickname = userNickname;
}
public String getUserImage() {
return userImage;
}
public void setUserImage(String userImage) {
this.userImage = userImage;
}
}
| 21.730769 | 51 | 0.755752 |
3fdfa9c36e31d930c0113f445a8d2d4d634f6bda | 280 | package org.sfm.beans;
public class CGS2 {
private final String val0;
private int val1;
public CGS2(String val0) {
this.val0 = val0;
}
public String getVal0() {
return val0;
}
public int getVal1() {
return val1;
}
public void setVal1(int v) {
this.val1 = v;
}
}
| 14.736842 | 29 | 0.664286 |
d8418cf0a4179abba2ff8e752e45f2e65547e270 | 3,547 | /*
Copyright (C) 2001, 2008 United States Government as represented by
the Administrator of the National Aeronautics and Space Administration.
All Rights Reserved.
*/
package gov.nasa.worldwind.data;
import gov.nasa.worldwind.util.Logging;
/**
* @author dcollins
* @version $Id: AbstractDataRasterWriter.java 8321 2009-01-05 17:06:14Z dcollins $
*/
public abstract class AbstractDataRasterWriter implements DataRasterWriter
{
private final String[] mimeTypes;
private final String[] suffixes;
public AbstractDataRasterWriter(String[] mimeTypes, String[] suffixes)
{
this.mimeTypes = copyOf(mimeTypes);
this.suffixes = copyOf(suffixes);
}
public String[] getMimeTypes()
{
String[] copy = new String[this.mimeTypes.length];
System.arraycopy(this.mimeTypes, 0, copy, 0, this.mimeTypes.length);
return copy;
}
public String[] getSuffixes()
{
String[] copy = new String[this.suffixes.length];
System.arraycopy(this.suffixes, 0, copy, 0, this.suffixes.length);
return copy;
}
public boolean canWrite(DataRaster raster, String formatSuffix, java.io.File file)
{
if (formatSuffix == null)
return false;
formatSuffix = stripLeadingPeriod(formatSuffix);
boolean matchesAny = false;
for (String suffix : this.suffixes)
{
if (suffix.equalsIgnoreCase(formatSuffix))
{
matchesAny = true;
break;
}
}
//noinspection SimplifiableIfStatement
if (!matchesAny)
return false;
return this.doCanWrite(raster, formatSuffix, file);
}
public void write(DataRaster raster, String formatSuffix, java.io.File file) throws java.io.IOException
{
if (raster == null)
{
String message = Logging.getMessage("nullValue.RasterIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
if (formatSuffix == null)
{
String message = Logging.getMessage("nullValue.FormatSuffixIsNull");
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
formatSuffix = stripLeadingPeriod(formatSuffix);
if (!this.canWrite(raster, formatSuffix, file))
{
String message = Logging.getMessage("DataRaster.CannotWrite", raster, formatSuffix, file);
Logging.logger().severe(message);
throw new IllegalArgumentException(message);
}
this.doWrite(raster, formatSuffix, file);
}
protected abstract boolean doCanWrite(DataRaster raster, String formatSuffix, java.io.File file);
protected abstract void doWrite(DataRaster raster, String formatSuffix, java.io.File file) throws java.io.IOException;
//**************************************************************//
//******************** Utilities *****************************//
//**************************************************************//
private static String[] copyOf(String[] array)
{
String[] copy = new String[array.length];
for (int i = 0; i < array.length; i++)
copy[i] = array[i].toLowerCase();
return copy;
}
private static String stripLeadingPeriod(String s)
{
if (s.startsWith("."))
return s.substring(Math.min(1, s.length()), s.length());
return s;
}
}
| 31.669643 | 122 | 0.595151 |
4f381518702f0b69587ab722d62e7188e66f4c62 | 4,854 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.resourcemover.v2021_01_01.implementation;
import com.microsoft.azure.management.resourcemover.v2021_01_01.MoveResource;
import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl;
import rx.Observable;
import com.microsoft.azure.management.resourcemover.v2021_01_01.MoveResourceProperties;
import java.util.List;
import rx.functions.Func1;
class MoveResourceImpl extends CreatableUpdatableImpl<MoveResource, MoveResourceInner, MoveResourceImpl> implements MoveResource, MoveResource.Definition, MoveResource.Update {
private final ResourceMoverManager manager;
private String resourceGroupName;
private String moveCollectionName;
private String moveResourceName;
private MoveResourceProperties cproperties;
private MoveResourceProperties uproperties;
MoveResourceImpl(String name, ResourceMoverManager manager) {
super(name, new MoveResourceInner());
this.manager = manager;
// Set resource name
this.moveResourceName = name;
//
this.cproperties = new MoveResourceProperties();
this.uproperties = new MoveResourceProperties();
}
MoveResourceImpl(MoveResourceInner inner, ResourceMoverManager manager) {
super(inner.name(), inner);
this.manager = manager;
// Set resource name
this.moveResourceName = inner.name();
// set resource ancestor and positional variables
this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups");
this.moveCollectionName = IdParsingUtils.getValueFromIdByName(inner.id(), "moveCollections");
this.moveResourceName = IdParsingUtils.getValueFromIdByName(inner.id(), "moveResources");
//
this.cproperties = new MoveResourceProperties();
this.uproperties = new MoveResourceProperties();
}
@Override
public ResourceMoverManager manager() {
return this.manager;
}
@Override
public Observable<MoveResource> createResourceAsync() {
MoveResourcesInner client = this.manager().inner().moveResources();
return client.createAsync(this.resourceGroupName, this.moveCollectionName, this.moveResourceName, this.cproperties)
.map(new Func1<MoveResourceInner, MoveResourceInner>() {
@Override
public MoveResourceInner call(MoveResourceInner resource) {
resetCreateUpdateParameters();
return resource;
}
})
.map(innerToFluentMap(this));
}
@Override
public Observable<MoveResource> updateResourceAsync() {
MoveResourcesInner client = this.manager().inner().moveResources();
return client.createAsync(this.resourceGroupName, this.moveCollectionName, this.moveResourceName, this.uproperties)
.map(new Func1<MoveResourceInner, MoveResourceInner>() {
@Override
public MoveResourceInner call(MoveResourceInner resource) {
resetCreateUpdateParameters();
return resource;
}
})
.map(innerToFluentMap(this));
}
@Override
protected Observable<MoveResourceInner> getInnerAsync() {
MoveResourcesInner client = this.manager().inner().moveResources();
return client.getAsync(this.resourceGroupName, this.moveCollectionName, this.moveResourceName);
}
@Override
public boolean isInCreateMode() {
return this.inner().id() == null;
}
private void resetCreateUpdateParameters() {
this.cproperties = new MoveResourceProperties();
this.uproperties = new MoveResourceProperties();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public String name() {
return this.inner().name();
}
@Override
public MoveResourceProperties properties() {
return this.inner().properties();
}
@Override
public String type() {
return this.inner().type();
}
@Override
public MoveResourceImpl withExistingMoveCollection(String resourceGroupName, String moveCollectionName) {
this.resourceGroupName = resourceGroupName;
this.moveCollectionName = moveCollectionName;
return this;
}
@Override
public MoveResourceImpl withProperties(MoveResourceProperties properties) {
if (isInCreateMode()) {
this.cproperties = properties;
} else {
this.uproperties = properties;
}
return this;
}
}
| 35.430657 | 176 | 0.68356 |
83372c5b33dc4a799e45deb73b5bb4431d3e19c1 | 349 | package bluegreen.manager.utils;
import org.springframework.stereotype.Component;
/**
* Invokes Thread.sleep.
* <p/>
* Pulling this into its own class makes the client classes more testable.
*/
@Component
public class ThreadSleeper
{
public void sleep(long milliseconds) throws InterruptedException
{
Thread.sleep(milliseconds);
}
}
| 19.388889 | 74 | 0.750716 |
505b54d97d7380b69d04e37c7b7e7a4b965be210 | 1,249 | package com.cjm721.overloaded.network.handler;
import com.cjm721.overloaded.Overloaded;
import com.cjm721.overloaded.item.functional.armor.ArmorEventHandler;
import com.cjm721.overloaded.network.packets.KeyBindPressedMessage;
import com.cjm721.overloaded.network.packets.NoClipStatusMessage;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.network.PacketDistributor;
import java.util.function.BiConsumer;
import java.util.function.Supplier;
public class KeyBindPressedHandler
implements BiConsumer<KeyBindPressedMessage, Supplier<NetworkEvent.Context>> {
@Override
public void accept(KeyBindPressedMessage message, Supplier<NetworkEvent.Context> ctx) {
ServerPlayerEntity player = ctx.get().getSender();
switch (message.getBind()) {
case NO_CLIP:
ctx.get()
.enqueueWork(
() -> {
boolean result = ArmorEventHandler.toggleNoClip(player);
Overloaded.proxy.networkWrapper.send(
PacketDistributor.PLAYER.with(() -> player), new NoClipStatusMessage(result));
});
break;
}
ctx.get().setPacketHandled(true);
}
}
| 34.694444 | 100 | 0.721377 |
1e51077eedcc2eae0306d1698722e89c238f8e92 | 717 | package aa.aggregators.sab;
public enum SabInfoType {
ROLE(
"urn:mace:surfnet.nl:surfnet.nl:sab:role:",
"urn:oid:1.3.6.1.4.1.5923.1.1.1.7"),
ORGANIZATION(
"urn:mace:surfnet.nl:surfnet.nl:sab:organizationCode:",
"urn:oid:1.3.6.1.4.1.1076.20.100.10.50.1"),
GUID(
"urn:mace:surfnet.nl:surfnet.nl:sab:organizationGUID:",
"urn:oid:1.3.6.1.4.1.1076.20.100.10.50.2");
private final String prefix;
private final String urn;
SabInfoType(String prefix, String urn) {
this.prefix = prefix;
this.urn = urn;
}
public String getPrefix() {
return prefix;
}
public String getUrn() {
return urn;
}
}
| 20.485714 | 63 | 0.584379 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.