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
3620823323037e21496bcc9957ec23cb5932c124
3,515
package org.InnovativeProducts.ipmusicplayer; import android.Manifest; import android.content.Intent; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.example.ipmusicplayer.R; import com.karumi.dexter.Dexter; import com.karumi.dexter.PermissionToken; import com.karumi.dexter.listener.PermissionDeniedResponse; import com.karumi.dexter.listener.PermissionGrantedResponse; import com.karumi.dexter.listener.PermissionRequest; import com.karumi.dexter.listener.single.PermissionListener; import java.io.File; import java.util.ArrayList; public class HomeActivity extends AppCompatActivity { ListView myListViewForSongs; String[] items; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); myListViewForSongs = (ListView) findViewById(R.id.mySongListView); runtimePermission(); } public void runtimePermission(){ Dexter.withActivity(this) .withPermission(Manifest.permission.READ_EXTERNAL_STORAGE) .withListener(new PermissionListener() { @Override public void onPermissionGranted(PermissionGrantedResponse response) { display(); } @Override public void onPermissionDenied(PermissionDeniedResponse response) { } @Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) { token.continuePermissionRequest(); } }).check(); } public ArrayList<File> findSong(File file){ ArrayList<File> arrayList = new ArrayList<>(); File[] files = file.listFiles(); for(File singleFile: files){ if(singleFile.isDirectory() && !singleFile.isHidden()){ arrayList.addAll(findSong(singleFile)); } else{ if(singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".wav")){ arrayList.add(singleFile); } } } return arrayList; } void display(){ final ArrayList<File> mySongs = findSong(Environment.getExternalStorageDirectory()); items = new String[mySongs.size()]; for(int i=0 ; i < mySongs.size(); i++){ items[i] = mySongs.get(i).getName().toString().replace(".mp3", "").replace(".wav", ""); } ArrayAdapter<String> myAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items); myListViewForSongs.setAdapter(myAdapter); myListViewForSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String songName = myListViewForSongs.getItemAtPosition(position).toString(); startActivity(new Intent(getApplicationContext(), PlayerActivity.class) .putExtra("songs", mySongs).putExtra("songname", songName) .putExtra("pos", position)); } }); } }
33.47619
121
0.634993
88677bc1ee18e094b8e07eb0407625af5652fb75
243
package com.secret.marketprovider.generic; import java.util.List; import com.secret.model.marketprovider.MarketProviderData; abstract public class Parser { abstract public List<MarketProviderData> parse(String content) throws Exception; }
24.3
81
0.82716
095634b207a91fdb21c28100261895ca66e06897
219
package org.bc.crypto; public class MaxBytesExceededException extends RuntimeCryptoException { public MaxBytesExceededException() { } public MaxBytesExceededException(String var1) { super(var1); } }
19.909091
71
0.748858
d95a0580bff2c9623f2ac7b5278a7ce8a8c80daf
776
package com.xuecheng.api.search; import com.xuecheng.framework.domain.search.CourseSearchParam; import com.xuecheng.framework.domain.search.EsCoursePub; import com.xuecheng.framework.domain.search.EsTeachplanMediaPub; import com.xuecheng.framework.model.response.QueryResponseResult; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import java.util.Map; @Api(value = "课程搜索", description = "课程搜索", tags = {"课程搜索"}) public interface EsCourseControllerApi { @ApiOperation("课程搜索") QueryResponseResult list(int page, int size, CourseSearchParam courseSearchParam); @ApiOperation("根据id查询课程信息") Map<String, EsCoursePub> getAll(String id); @ApiOperation("根据课程计划查询媒资信息") EsTeachplanMediaPub getMedia(String teachplanId); }
31.04
86
0.78866
d3e3f4fa5eb572545d29ced27c1d4abe8690b37f
3,594
package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseFailure; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseSuccess; import java.util.Arrays; import org.junit.Test; import seedu.address.logic.commands.FindCommand; import seedu.address.model.person.ContainsKeywordsPredicate; public class FindCommandParserTest { private FindCommandParser parser = new FindCommandParser(); @Test public void parse_emptyArg_throwsParseException() { assertParseFailure(parser, " ", String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); assertParseFailure(parser, FindCommand.KEYWORD_NAME, FindCommand.MESSAGE_NO_KEYWORD); assertParseFailure(parser, "abc", String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } @Test public void parse_validArgs_returnsFindCommand() { // find name, no leading and trailing whitespaces FindCommand expectedFindCommand = new FindCommand(new ContainsKeywordsPredicate(Arrays.asList("Alice", "Bob"), FindCommand.KEYWORD_NAME)); assertParseSuccess(parser, FindCommand.KEYWORD_NAME + " Alice Bob", expectedFindCommand); // find name, multiple whitespaces between keywords assertParseSuccess(parser, FindCommand.KEYWORD_NAME + "\n Alice \n \t Bob \t", expectedFindCommand); // find address, no leading and trailing whitespaces expectedFindCommand = new FindCommand(new ContainsKeywordsPredicate(Arrays.asList("Serangoon"), FindCommand.KEYWORD_ADDRESS)); assertParseSuccess(parser, FindCommand.KEYWORD_ADDRESS + " Serangoon", expectedFindCommand); // find address, multiple whitespaces between keywords assertParseSuccess(parser, FindCommand.KEYWORD_ADDRESS + "\n Serangoon \n \t", expectedFindCommand); // find email, no leading and trailing whitespaces expectedFindCommand = new FindCommand(new ContainsKeywordsPredicate(Arrays.asList("example1", "example2"), FindCommand.KEYWORD_EMAIL)); assertParseSuccess(parser, FindCommand.KEYWORD_EMAIL + " example1 example2", expectedFindCommand); // find email, multiple whitespaces between keywords assertParseSuccess(parser, FindCommand.KEYWORD_EMAIL + "\n example1 \n \t example2 \t", expectedFindCommand); // find phone, no leading and trailing whitespaces expectedFindCommand = new FindCommand(new ContainsKeywordsPredicate(Arrays.asList("123456789"), FindCommand.KEYWORD_PHONE)); assertParseSuccess(parser, FindCommand.KEYWORD_PHONE + " 123456789", expectedFindCommand); // find phone, multiple whitespaces between keywords assertParseSuccess(parser, FindCommand.KEYWORD_PHONE + "\n 123456789 \t", expectedFindCommand); // find organisation, no leading and trailing whitespaces expectedFindCommand = new FindCommand( new ContainsKeywordsPredicate(Arrays.asList("Apple"), FindCommand.KEYWORD_ORGANISATION)); assertParseSuccess(parser, FindCommand.KEYWORD_ORGANISATION + " Apple", expectedFindCommand); // find phone, multiple whitespaces between keywords assertParseSuccess(parser, FindCommand.KEYWORD_ORGANISATION + "\n Apple \t", expectedFindCommand); } }
47.289474
118
0.72148
d9194429584fac61e3498559ff51b3b1eb2cd076
433
package com.wy.abstracfactory; /** * 日语青空 * * @author 飞花梦影 * @date 2021-11-03 15:39:09 * @git {@link https://github.com/dreamFlyingFlower } */ public class AbstractJapanAir extends AbstractAir { @Override public String country() { return "中文"; } @Override public String name() { return "Air"; } @Override public String chineseName() { return "青空"; } @Override public String type() { return "恋爱,悲剧"; } }
13.967742
53
0.65127
d6437b1cff2bf889d16ad26263f5ac27aa85c909
2,618
package com.example.writeo.model; import com.example.writeo.enums.ArticleStatus; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.jupiter.api.Assertions.*; @RunWith(SpringRunner.class) @SpringBootTest class ArticleTest { long id = 0; String title = "asd"; String content = "asd-content"; Boolean published = false; ArticleStatus articleStatus = ArticleStatus.FreeToUse; double articlePrice = 10; User author = new User(); Article article = new Article( id, title, content, published, articleStatus, articlePrice, author ); @Test void getId() { assertEquals(0, article.getId()); } @Test void setId() { article.setId((long) 6); assertEquals(6, article.getId()); } @Test void getArticleTitle() { assertEquals("asd", article.getArticleTitle()); } @Test void setArticleTitle() { article.setArticleTitle("asd-changed"); assertEquals("asd-changed", article.getArticleTitle()); } @Test void getArticleContent() { assertEquals("asd-content", article.getArticleContent()); } @Test void setArticleContent() { article.setArticleContent("asd-content-changed"); assertEquals("asd-content-changed", article.getArticleContent()); } @Test void getArticlePublished() { assertEquals(false, article.getArticlePublished()); } @Test void setArticlePublished() { article.setArticlePublished(true); assertEquals(true, article.getArticlePublished()); } @Test void getStatus() { assertEquals(ArticleStatus.FreeToUse, article.getArticleStatus()); } @Test void setStatus() { article.setArticleStatus(ArticleStatus.ForSale); assertEquals(ArticleStatus.ForSale, article.getArticleStatus()); } @Test void getPrice() { assertEquals(10, article.getArticlePrice()); } @Test void setPrice() { article.setArticlePrice(15); assertEquals(15, article.getArticlePrice()); } @Test void getAuthor() { assertEquals(new User(), article.getAuthor()); } @Test void setAuthor() { User user = new User(); user.setId((long) 8); article.setAuthor(user); assertEquals(user.getId(), article.getAuthor().getId()); } }
24.240741
74
0.62605
0aee324e180f78b88115047c69ed7b70307bb439
14,026
/* * Copyright (C) 2012 Google Inc. * Copyright (C) 2015 Keith M. Hughes. * * 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.robotbrains.support.web.server.netty; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.util.SelfSignedCertificate; import io.smartspaces.SimpleSmartSpacesException; import io.smartspaces.SmartSpacesException; import io.smartspaces.util.web.MimeResolver; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.config.ConfigurationSource; import org.apache.logging.log4j.core.config.Configurator; import org.robotbrains.support.web.server.HttpAuthProvider; import org.robotbrains.support.web.server.HttpDynamicPostRequestHandler; import org.robotbrains.support.web.server.HttpDynamicRequestHandler; import org.robotbrains.support.web.server.HttpRequest; import org.robotbrains.support.web.server.HttpResponse; import org.robotbrains.support.web.server.HttpStaticContentRequestHandler; import org.robotbrains.support.web.server.WebResourceAccessManager; import org.robotbrains.support.web.server.WebServer; import org.robotbrains.support.web.server.WebServerWebSocketHandlerFactory; import com.google.common.collect.Lists; /** * A web server based on Netty. * * @author Keith M. Hughes */ public class NettyWebServer implements WebServer { static final boolean SSL = false; static final int PORT = Integer.parseInt(System.getProperty("port", SSL ? "8443" : "8080")); public static void main(String[] args) throws Exception { Configurator.initialize(null, new ConfigurationSource(NettyWebServer.class.getClassLoader() .getResourceAsStream("log4j.xml"))); NettyWebServer server = new NettyWebServer(8095, LogManager.getFormatterLogger("HelloWorld")); server.startup(); server.addDynamicContentHandler("/foo", true, new HttpDynamicRequestHandler() { @Override public void handle(HttpRequest request, HttpResponse response) { try { response.getOutputStream().write("Hello, world".getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } /** * Name of the server. */ private String serverName; /** * The port for the server. */ private int port; /** * HTTP headers to be sent on all responses. */ private Map<String, String> globalHttpContentHeaders = new HashMap<>(); /** * The handler for all web server requests. */ private NettyWebServerHandler serverHandler; /** * The group for handling boss events. */ private EventLoopGroup bossGroup; /** * The group for handling worker events. */ private EventLoopGroup workerGroup; /** * {@code true} if running in debug mode. */ private boolean debugMode; /** * {@code true} if support being a secure server. */ private boolean secureServer; /** * The certificate chain file for an SSL connection. Can be {@code null}. */ private File sslCertChainFile; /** * The key file for an SSL connection. Can be {@code null}. */ private File sslKeyFile; /** * The SSL context for HTTPS connections. Will be {@code null} if the server * is not labeled secure. */ private SslContext sslContext; /** * The default MIME resolver to use. */ private MimeResolver defaultMimeResolver; /** * The complete collection of static content handlers. */ private List<HttpStaticContentRequestHandler> staticContentRequestHandlers = new ArrayList<>(); /** * The complete collection of dynamic GET request handlers. */ private List<HttpDynamicRequestHandler> dynamicGetRequestHandlers = new ArrayList<>(); /** * The complete collection of dynamic POST request handlers. */ private List<HttpDynamicPostRequestHandler> dynamicPostRequestHandlers = new ArrayList<>(); /** * All GET request handlers handled by this instance. */ private List<NettyHttpGetRequestHandler> httpGetRequestHandlers = new ArrayList<>(); /** * All POST request handlers handled by this instance. */ private List<NettyHttpPostRequestHandler> httpPostRequestHandlers = new ArrayList<>(); /** * The logger to use. */ private Logger log; /** * Construct a new web server. * * @param log * the logger to use */ public NettyWebServer(int port, Logger log) { this.log = log; this.port = port; } @Override public void startup() { try { // Configure SSL. SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } serverHandler = new NettyWebServerHandler(this); bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(ServerChannelWithId.class) .childHandler(new NettyWebServerInitializer(sslCtx, this, serverHandler)); b.bind(port).sync(); } catch (Throwable e) { throw SmartSpacesException.newFormattedException(e, "Could not create web server"); } } @Override public void shutdown() { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } @Override public void addStaticContentHandler(String uriPrefix, File baseDir) { addStaticContentHandler(uriPrefix, baseDir, null); } @Override public void addStaticContentHandler(String uriPrefix, File baseDir, Map<String, String> extraHttpContentHeaders) { addStaticContentHandler(uriPrefix, baseDir, extraHttpContentHeaders, null); } @Override public void addStaticContentHandler(String uriPrefix, File baseDir, Map<String, String> extraHttpContentHeaders, HttpDynamicRequestHandler fallbackHandler) { if (!baseDir.exists()) { throw new SmartSpacesException(String.format("Cannot find web folder %s", baseDir.getAbsolutePath())); } NettyHttpDynamicGetRequestHandlerHandler fallbackNettyHandler = fallbackHandler == null ? null : new NettyHttpDynamicGetRequestHandlerHandler( serverHandler, uriPrefix, false, fallbackHandler, extraHttpContentHeaders); NettyStaticContentHandler staticContentHandler = new NettyStaticContentHandler(serverHandler, uriPrefix, baseDir, extraHttpContentHeaders, fallbackNettyHandler); staticContentHandler.setAllowLinks(isDebugMode()); if (isDebugMode()) { getLog().warn("Enabling web-server link following because of debug mode -- not secure."); } staticContentHandler.setMimeResolver(defaultMimeResolver); addHttpGetRequestHandler(staticContentHandler); staticContentRequestHandlers.add(staticContentHandler); } @Override public void addDynamicContentHandler(String uriPrefix, boolean usePath, HttpDynamicRequestHandler handler) { addDynamicContentHandler(uriPrefix, usePath, handler, null); } @Override public void addDynamicContentHandler(String uriPrefix, boolean usePath, HttpDynamicRequestHandler handler, Map<String, String> extraHttpContentHeaders) { addHttpGetRequestHandler(new NettyHttpDynamicGetRequestHandlerHandler(serverHandler, uriPrefix, usePath, handler, extraHttpContentHeaders)); dynamicGetRequestHandlers.add(handler); } @Override public void addDynamicPostRequestHandler(String uriPrefix, boolean usePath, HttpDynamicPostRequestHandler handler) { addDynamicPostRequestHandler(uriPrefix, usePath, handler, null); } @Override public void addDynamicPostRequestHandler(String uriPrefix, boolean usePath, HttpDynamicPostRequestHandler handler, Map<String, String> extraHttpContentHeaders) { addHttpPostRequestHandler(new NettyHttpDynamicPostRequestHandlerHandler(serverHandler, uriPrefix, usePath, handler, extraHttpContentHeaders)); dynamicPostRequestHandlers.add(handler); } @Override public List<HttpStaticContentRequestHandler> getStaticContentRequestHandlers() { return Lists.newArrayList(staticContentRequestHandlers); } @Override public List<HttpDynamicRequestHandler> getDynamicRequestHandlers() { return Lists.newArrayList(dynamicGetRequestHandlers); } @Override public List<HttpDynamicPostRequestHandler> getDynamicPostRequestHandlers() { return Lists.newArrayList(dynamicPostRequestHandlers); } @Override public void setWebSocketHandlerFactory(String webSocketUriPrefix, WebServerWebSocketHandlerFactory webSocketHandlerFactory) { serverHandler.setWebSocketHandlerFactory(webSocketUriPrefix, webSocketHandlerFactory); } @Override public String getServerName() { return serverName; } @Override public void setServerName(String serverName) { this.serverName = serverName; } @Override public void setPort(int port) { this.port = port; } @Override public int getPort() { return port; } @Override public void addContentHeader(String name, String value) { globalHttpContentHeaders.put(name, value); } @Override public void addContentHeaders(Map<String, String> headers) { globalHttpContentHeaders.putAll(headers); } @SuppressWarnings("unchecked") @Override public <T extends MimeResolver> T getDefaultMimeResolver() { return (T) defaultMimeResolver; } @Override public void setDefaultMimeResolver(MimeResolver resolver) { defaultMimeResolver = resolver; } @Override public void setDebugMode(boolean debugMode) { this.debugMode = debugMode; } /** * Check if this server is running in debug mode. * * @return {@code true} if this server is running in debug mode */ public boolean isDebugMode() { return debugMode; } @Override public boolean isSecureServer() { return secureServer; } @Override public void setSecureServer(boolean secureServer) { this.secureServer = secureServer; } @Override public void setSslCertificates(File sslCertChainFile, File sslKeyFile) { if (((sslCertChainFile == null) && (sslKeyFile != null)) || (sslCertChainFile != null) && (sslKeyFile == null)) { throw new SimpleSmartSpacesException( "Both a certificate chain file and a private key file must be supplied"); } if (sslCertChainFile != null && !sslCertChainFile.isFile()) { throw new SimpleSmartSpacesException(String.format( "The certificate chain file %s does not exist", sslCertChainFile.getAbsolutePath())); } if (sslKeyFile != null && !sslKeyFile.isFile()) { throw new SimpleSmartSpacesException(String.format("The private key file %s does not exist", sslKeyFile.getAbsolutePath())); } this.sslCertChainFile = sslCertChainFile; this.sslKeyFile = sslKeyFile; } @Override public void setAuthProvider(HttpAuthProvider authProvider) { serverHandler.setAuthProvider(authProvider); } @Override public void setAccessManager(WebResourceAccessManager accessManager) { serverHandler.setAccessManager(accessManager); } /** * Get the content headers which should go onto every HTTP response. * * @return the globalHttpContentHeaders */ public Map<String, String> getGlobalHttpContentHeaders() { return globalHttpContentHeaders; } /** * Get the logger for the web server. * * @return the logger */ public Logger getLog() { return log; } /** * Register a new GET request handler to the server. * * @param handler * the handler to add */ private void addHttpGetRequestHandler(NettyHttpGetRequestHandler handler) { httpGetRequestHandlers.add(handler); } /** * Locate a registered GET request handler that can handle the given request. * * @param nettyRequest * the Netty request * * @return the first handler that handles the request, or {@code null} if none */ NettyHttpGetRequestHandler locateGetRequestHandler( io.netty.handler.codec.http.HttpRequest nettyRequest) { for (NettyHttpGetRequestHandler handler : httpGetRequestHandlers) { if (handler.isHandledBy(nettyRequest)) { return handler; } } return null; } /** * Register a new POST request handler to the server. * * @param handler * the handler to add */ private void addHttpPostRequestHandler(NettyHttpPostRequestHandler handler) { httpPostRequestHandlers.add(handler); } /** * Locate a registered POST request handler that can handle the given request. * * @param nettyRequest * the Netty request * * @return the first handler that handles the request, or {@code null} if none */ NettyHttpPostRequestHandler locatePostRequestHandler( io.netty.handler.codec.http.HttpRequest nettyRequest) { for (NettyHttpPostRequestHandler handler : httpPostRequestHandlers) { if (handler.isHandledBy(nettyRequest)) { return handler; } } return null; } }
29.343096
99
0.722016
bd5e754d2e935f2a58337c196ed483105a7225e5
12,978
package com.gemteks.merc.service.layout.service; import java.io.IOException; import java.util.Base64; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.cloudant.client.api.views.ViewResponse; import com.cloudant.client.api.views.ViewResponse.Row; import com.gemteks.merc.service.layout.common.MERCUtils; import com.gemteks.merc.service.layout.common.MERCValidator; import com.gemteks.merc.service.layout.common.MercException; import com.gemteks.merc.service.layout.model.ActionInfo; import com.gemteks.merc.service.layout.repo.AmMicroService; import com.gemteks.merc.service.layout.repo.cloudant.CloudantDB; import com.google.gson.JsonObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; @Service @Scope(value="prototype") public class CorpInfoService{ private String dbName = "cp_info"; private String docName = "iotPlan"; private String viewName = "by-cpId"; /*@Autowired private MERCUtils mercUtils;*/ @Autowired private CloudantDB cloudantDBInstance; public Integer insertOrUpdateCorpInfo(MultipartFile file, HttpServletRequest request) throws MercException { String id = request.getParameter("id"); String token = request.getParameter("token"); JsonObject doc = new JsonObject(); Integer putDocStatus = 1; MERCValidator.validateParam(id); MERCValidator.validateParam(token); MERCValidator.validateParam(request.getParameter("cpName")); MERCValidator.validateParam(request.getParameter("name_en")); MERCValidator.validateParam(request.getParameter("name_zh")); MERCValidator.validateParam(request.getParameter("name_zh-Hans")); MERCValidator.validateParam(request.getParameter("url")); MERCValidator.validateParam(request.getParameter("welcome_en")); MERCValidator.validateParam(request.getParameter("welcome_zh")); MERCValidator.validateParam(request.getParameter("welcome_zh-Hans")); MERCValidator.validateParam(request.getParameter("title_en")); MERCValidator.validateParam(request.getParameter("title_zh")); MERCValidator.validateParam(request.getParameter("title_zh-Hans")); MERCValidator.validateParam(request.getParameter("isEnable")); doc.addProperty("cpName", request.getParameter("cpName")); doc.addProperty("name_en", request.getParameter("name_en")); doc.addProperty("name_zh", request.getParameter("name_zh")); doc.addProperty("name_zh-Hans", request.getParameter("name_zh-Hans")); doc.addProperty("url", request.getParameter("url")); doc.addProperty("welcome_en", request.getParameter("welcome_en")); doc.addProperty("welcome_zh", request.getParameter("welcome_zh")); doc.addProperty("welcome_zh-Hans", request.getParameter("welcome_zh-Hans")); doc.addProperty("title_en", request.getParameter("title_en")); doc.addProperty("title_zn", request.getParameter("title_zn")); doc.addProperty("title_zh-Hans", request.getParameter("title_zh-Hans")); doc.addProperty("isEnable", request.getParameter("isEnable")); doc.addProperty("token", token); // ActionInfo actionInfo = mercUtils.checkValidToken(token); ActionInfo actionInfo = AmMicroService.getDataFromAmServiceWithToken(token); doc.addProperty("cpId", actionInfo.getCpID()); doc.addProperty("userId", actionInfo.getUserID()); if (file != null && !file.isEmpty()) { try { String imageBase64Content = Base64.getEncoder().encodeToString(file.getBytes()); JsonObject dataContent = new JsonObject(); dataContent.addProperty("content_type", file.getContentType()); dataContent.addProperty("data", imageBase64Content); JsonObject fileAttachment = new JsonObject(); fileAttachment.add(file.getOriginalFilename(), dataContent); doc.add("_attachments", fileAttachment); } catch (IOException e){ } } //Create document if (id.equals("-1")) { if (cloudantDBInstance.putDocs(dbName, doc) == false) { throw new MercException("999", "Insert company info fail"); } } else { List<JsonObject> docs = cloudantDBInstance.getDocsById(dbName, id); if (docs.size() == 0) { throw new MercException("404", "No exist data"); } JsonObject existedDoc = docs.get(0); //Update document doc.addProperty("_id", existedDoc.get("_id").getAsString()); doc.addProperty("_rev", existedDoc.get("_rev").getAsString()); if (cloudantDBInstance.updateDocs(dbName, doc) == false) { throw new MercException("999", "Update company info fail"); } putDocStatus = 2; } return putDocStatus; } public byte[] getLogoImage(String id) throws MercException { MERCValidator.validateParam(id); byte[] logoRawImage = cloudantDBInstance.getImage(dbName, id); if (logoRawImage == null) { new MercException("999", "Get attatchment fail"); } Integer imageSize = logoRawImage.length; if (imageSize == 0) { throw new MercException("404", "No exist data"); } return logoRawImage; } public byte[] getLogoImageFromToken(String token) throws MercException { MERCValidator.validateParam(token); // ActionInfo actionInfo = mercUtils.checkValidToken(token); ActionInfo actionInfo = AmMicroService.getDataFromAmServiceWithToken(token); cloudantDBInstance.setCloudantDBName(dbName); List<Row<String, JsonObject>> docList = cloudantDBInstance.getDocsUsingViewByKey(dbName, docName, viewName, actionInfo.getCpID()); if (docList.size() == 0) { throw new MercException("404", "no exist data"); } ViewResponse.Row<String, JsonObject> cpInfoObject = docList.get(0); byte[] logoRawImage = cloudantDBInstance.getImage(dbName, cpInfoObject.getId()); if (logoRawImage == null) { new MercException("999", "Get attatchment fail"); } Integer imageSize = logoRawImage.length; if (imageSize == 0) { throw new MercException("404", "No exist data"); } return logoRawImage; } public JsonObject getCpInfo(Map<String, String> queryMap) throws MercException { String locale = queryMap.get("locale"); String token = queryMap.get("token"); String cpId = "1"; if(token != null && token.length() > 0 ){ ActionInfo actionInfo = AmMicroService.getDataFromAmServiceWithToken(token); cpId = actionInfo.getCpID(); } cloudantDBInstance.setCloudantDBName(dbName); List<Row<String, JsonObject>> docList = cloudantDBInstance.getDocsUsingViewByKey(dbName, this.docName, this.viewName, cpId); if (docList == null) { System.out.println("docList is null: no document been found "); //Create view for searching document JsonObject jobj = new JsonObject(); JsonObject viewObj = new JsonObject(); JsonObject mapObj = new JsonObject(); mapObj.addProperty("map", "function (doc) {\n if(doc.cpId){\n emit(doc.cpId, doc); \n }\n}"); viewObj.add(this.viewName, mapObj); jobj.addProperty("_id", String.format("_design/%s", this.docName)); jobj.add("views", viewObj); jobj.addProperty("language", "javascript"); if (cloudantDBInstance.putDocs(dbName, jobj) == false) { throw new MercException("999", "create view error"); } //Get document by cpId docList = cloudantDBInstance.getDocsUsingViewByKey(dbName, this.docName, viewName, "1"); } if (docList.size() == 0) { throw new MercException("404", "no exist data"); } JsonObject vObject = docList.get(0).getValue(); JsonObject doc = addCpInfoProperty(vObject, locale); System.out.printf("docList size:%d\n", docList.size()); return doc; } public JsonObject getCpInfoById(Map<String, String> queryMap) throws MercException { String token = queryMap.get("token"); String locale = queryMap.get("locale"); String id = queryMap.get("id"); MERCValidator.validateParam(token); //mercUtils.checkValidToken(token); AmMicroService.getDataFromAmServiceWithToken(token); List<JsonObject> docList = cloudantDBInstance.getDocsById(dbName, id); if (docList == null) { System.out.println("docList is null: no document been found "); //Create view for searching document JsonObject jobj = new JsonObject(); JsonObject viewObj = new JsonObject(); JsonObject mapObj = new JsonObject(); mapObj.addProperty("map", "function (doc) {\n if(doc.cpId){\n emit(doc.cpId, doc); \n }\n}"); viewObj.add(this.viewName, mapObj); jobj.addProperty("_id", String.format("_design/%s", this.docName)); jobj.add("views", viewObj); jobj.addProperty("language", "javascript"); if (cloudantDBInstance.putDocs(dbName, jobj) == false) { throw new MercException("999", "create view error"); } //Get document by cpId docList = cloudantDBInstance.getDocsById(dbName, id); } if (docList.size() == 0) { throw new MercException("404", "no exist data"); } JsonObject vObject = docList.get(0); JsonObject doc = addCpInfoProperty(vObject, locale); System.out.printf("docList size:%d\n", docList.size()); return doc; } public JsonObject addCpInfoProperty(JsonObject vObject, String locale){ JsonObject docTmp = new JsonObject(); if (locale == null || locale.equals("")){ docTmp.addProperty("title_en", vObject.get("title_en") == null?"NA":vObject.get("title_en").getAsString()); docTmp.addProperty("title_zh", vObject.get("title_zh") == null?"NA":vObject.get("title_zh").getAsString()); docTmp.addProperty("title_zh-Hans", vObject.get("title_zh-Hans") == null?"NA":vObject.get("title_zh-Hans").getAsString()); docTmp.addProperty("welcome_en", vObject.get("welcome_en") == null?"NA":vObject.get("welcome_en").getAsString()); docTmp.addProperty("welcome_zh", vObject.get("welcome_zh") == null?"NA":vObject.get("welcome_zh").getAsString()); docTmp.addProperty("welcome_zh-Hans", vObject.get("welcome_zh-Hans") == null?"NA":vObject.get("welcome_zh-Hans").getAsString()); docTmp.addProperty("name_en", vObject.get("name_en") == null?"NA":vObject.get("name_en").getAsString()); docTmp.addProperty("name_zh", vObject.get("name_zh") == null?"NA":vObject.get("name_zh").getAsString()); docTmp.addProperty("name_zh-Hans", vObject.get("name_zh-Hans") == null?"NA":vObject.get("name_zh-Hans").getAsString()); docTmp.addProperty("id", vObject.get("_id") == null?"NA":vObject.get("_id").getAsString()); docTmp.addProperty("isEnable", vObject.get("isEnable") == null?"NA":vObject.get("isEnable").getAsString()); docTmp.addProperty("cpName", vObject.get("cpName") == null?"NA":vObject.get("cpName").getAsString()); docTmp.addProperty("url", vObject.get("url") == null?"NA":vObject.get("url").getAsString()); } else { String tileKey = "title_".concat(locale); String welcomeKey = "welcome_".concat(locale); String nameKey = "name_".concat(locale); docTmp.addProperty("title", vObject.get(tileKey) == null?"NA":vObject.get(tileKey).getAsString()); docTmp.addProperty("welcome", vObject.get(welcomeKey) == null?"NA":vObject.get(welcomeKey).getAsString()); docTmp.addProperty("name", vObject.get(nameKey) == null?"NA":vObject.get(nameKey).getAsString()); docTmp.addProperty("id", vObject.get("_id") == null?"NA":vObject.get("_id").getAsString()); docTmp.addProperty("isEnable", vObject.get("isEnable") == null?"NA":vObject.get("isEnable").getAsString()); docTmp.addProperty("cpName", vObject.get("cpName") == null?"NA":vObject.get("cpName").getAsString()); docTmp.addProperty("url", vObject.get("url") == null?"NA":vObject.get("url").getAsString()); } return docTmp; } }
43.69697
140
0.642241
bd5349793ce103fe1efe8bec98cd8c7eea22a538
3,185
package com.github.baserecycleradapter.activity; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageButton; import com.github.baserecycleradapter.R; import com.github.library.BaseQuickAdapter; import com.github.library.BaseViewHolder; import java.util.ArrayList; import java.util.List; /** * Created by boby on 2017/1/22. */ public class TaoBaoActivity extends AppCompatActivity implements View.OnClickListener { RecyclerView mRecyclerView; ImageButton mButton; boolean mIsLinearManager; BaseQuickAdapter<String, BaseViewHolder> mAdapter; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_taobao); mRecyclerView = (RecyclerView) findViewById(R.id.recycler); mButton = (ImageButton) findViewById(R.id.btn_change); mButton.setOnClickListener(this); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setAdapter(mAdapter = new BaseQuickAdapter<String, BaseViewHolder>(getDatas(), new int[]{R.layout.layout_linear, R.layout.layout_grid}) { @Override protected void convert(BaseViewHolder helper, String item) { helper.setText(R.id.tv_name, item); } }); mAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN); mAdapter.isFirstOnly(false); mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() { @Override public void onLoadMoreRequested() { new Handler().postDelayed(new Runnable() { @Override public void run() { mAdapter.addData(addDatas()); mAdapter.loadMoreComplete(); } }, 1500); } }); } @Override public void onClick(View v) { //线性 if (mIsLinearManager) { mAdapter.setLayoutType(BaseQuickAdapter.TRANS_0_VIEW); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); } else { //网格 mAdapter.setLayoutType(BaseQuickAdapter.TRANS_1_VIEW); mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2)); //需要显示加载更多则加上下面这句 从新关联recycler mAdapter.onAttachedToRecyclerView(mRecyclerView); } mIsLinearManager = !mIsLinearManager; } public List<String> getDatas() { List<String> datas = new ArrayList<>(); for (int i = 0; i < 66; i++) { datas.add("苹果超薄游戏本" + i); } return datas; } public List<String> addDatas() { List<String> datas = new ArrayList<>(); for (int i = 0; i < 3; i++) { datas.add("苹果超薄游戏本" + i); } return datas; } }
30.92233
159
0.643328
2d4a85b5e7e91784b4769e0a4dcee3d7b2370e7e
7,799
package com.github.rod1andrade.states; import com.github.rod1andrade.commands.simulation.StartRandomTrashsCommand; import com.github.rod1andrade.commands.vacuumcleaner.*; import com.github.rod1andrade.entities.*; import com.github.rod1andrade.entities.Window; import com.github.rod1andrade.models.VacuumCleanerModel; import com.github.rod1andrade.render.Render; import com.github.rod1andrade.ui.infos.Hud; import com.github.rod1andrade.util.GlobalConfig; import java.awt.*; /** * @author Rodrigo Andrade */ public final class SimulationState extends State { // Controle de movimentacao do aspirador em decorrer do tempo. private long deltaCollisionTime = 0; private long countTimeToChangeDirection = System.currentTimeMillis(); public static final int RANDOM_MOVEMENT_COOLDOWN = 2000; private Hud hud; private final VacuumCleanerRenderEntity vacuumCleanerRenderEntity; private final VacuumCleanerModel vacuumCleanerModel; // Commands do aspirador de po private MakeMovementVacuumCleanerCommand makeMovementVacuumCleanerCommand; private RandomMovemenVacuumCleanertCommand randomMovemenVacuumCleanertCommand; private MoveToOppositeDirectionVacuumCleanerCommand moveToOppositeDirectionVacuumCleanerCommand; private BoundsCollisionVacuumCleanerCommand boundsCollisionVacuumCleanerCommand; private EntityRenderColisionVacuumCleanerCommand entityRenderColisionVacuumCleanerCommand; private CollectTrashVacuumCleanerCommand collectTrashVacuumCleanerCommand; // Commands da sujeiras private StartRandomTrashsCommand startRandomTrashsCommand; private final RenderEntity[] collidablesRenderEntities = new RenderEntity[6]; private final Render render = new Render(GlobalConfig.WINDOW_WIDTH, GlobalConfig.WINDOW_HEIGHT); public SimulationState(String name, int actualState, GlobalConfig globalConfig, VacuumCleanerModel vacuumCleanerModel) { super(name, actualState, globalConfig); this.vacuumCleanerModel = vacuumCleanerModel; vacuumCleanerRenderEntity = new VacuumCleanerRenderEntity(GlobalConfig.WINDOW_WIDTH / 2, GlobalConfig.WINDOW_HEIGHT / 2, 16, 16, globalConfig.isDebugMode()); } @Override public void initializeResources() { hud = new Hud(0, GlobalConfig.WINDOW_HEIGHT - 130, GlobalConfig.WINDOW_WIDTH, 130, globalConfig); collidablesRenderEntities[0] = new Table(88, GlobalConfig.WINDOW_HEIGHT / 2, 30, 22, globalConfig.isDebugMode()); collidablesRenderEntities[1] = new Lamp(GlobalConfig.WINDOW_WIDTH - 64, 128 - 80, 13, 27, globalConfig.isDebugMode()); collidablesRenderEntities[2] = new Shelf((GlobalConfig.WINDOW_WIDTH / 2) + 64, 128 - 80, 16, 27, globalConfig.isDebugMode()); collidablesRenderEntities[3] = new MiniTable(32, (128 + 32), 16, 16, globalConfig.isDebugMode()); collidablesRenderEntities[4] = new Television(32, 128, 16, 16, globalConfig.isDebugMode()); collidablesRenderEntities[5] = new Plant(GlobalConfig.WINDOW_WIDTH / 2 + 130, 128 - 60, 16, 20, globalConfig.isDebugMode()); makeMovementVacuumCleanerCommand = new MakeMovementVacuumCleanerCommand(vacuumCleanerModel, vacuumCleanerRenderEntity); randomMovemenVacuumCleanertCommand = new RandomMovemenVacuumCleanertCommand(vacuumCleanerModel,vacuumCleanerRenderEntity); moveToOppositeDirectionVacuumCleanerCommand = new MoveToOppositeDirectionVacuumCleanerCommand(vacuumCleanerModel, vacuumCleanerRenderEntity); boundsCollisionVacuumCleanerCommand = new BoundsCollisionVacuumCleanerCommand(vacuumCleanerModel, vacuumCleanerRenderEntity, 0, 130, GlobalConfig.WINDOW_WIDTH, GlobalConfig.WINDOW_HEIGHT - 130); entityRenderColisionVacuumCleanerCommand = new EntityRenderColisionVacuumCleanerCommand(vacuumCleanerModel, vacuumCleanerRenderEntity, collidablesRenderEntities); startRandomTrashsCommand = new StartRandomTrashsCommand( collidablesRenderEntities, GlobalConfig.QUANTITY_THRASH_LIMIT, 0, 130, GlobalConfig.WINDOW_WIDTH, GlobalConfig.WINDOW_HEIGHT - hud.getHeight() ); collectTrashVacuumCleanerCommand = new CollectTrashVacuumCleanerCommand( vacuumCleanerModel, vacuumCleanerRenderEntity, startRandomTrashsCommand.getTrashModels(), startRandomTrashsCommand.getTrashRenderEntities() ); // Define a posicao de renderizacao das paredes for (int x = 0; x < GlobalConfig.WINDOW_WIDTH; x += 64) { render.addEntityToRender(new StripedWall(x, 0, 16, 32)); } // Define a posicao de renderizcao do chao for (int y = 128; y < GlobalConfig.WINDOW_HEIGHT - hud.getHeight(); y += 64) { for (int x = 0; x < GlobalConfig.WINDOW_WIDTH; x += 64) { render.addEntityToRender(new Floor(x, y, 16, 16)); } } // Objetos render.addEntityToRender(new Window(48, (64 - 16) / 2, 14, 14)); render.addEntityToRender(new Mat(GlobalConfig.WINDOW_WIDTH / 2, GlobalConfig.WINDOW_HEIGHT / 2, 48, 32)); render.addEntityToRender(new OilPaint((GlobalConfig.WINDOW_WIDTH / 2) - 16, (64 - 16) / 2, 16, 16)); render.addEntityToRender(collidablesRenderEntities[5]); render.addEntityToRender(collidablesRenderEntities[2]); render.addEntityToRender(collidablesRenderEntities[3]); render.addEntityToRender(collidablesRenderEntities[4]); render.addEntityToRender(collidablesRenderEntities[1]); render.addEntityToRender(collidablesRenderEntities[0]); // Adiciona cada Trash para a render pipeline... startRandomTrashsCommand.execute(); for(TrashRenderEntity trashRenderEntity : startRandomTrashsCommand.getTrashRenderEntities()) { render.addEntityToRender(trashRenderEntity); } render.addEntityToRender(vacuumCleanerRenderEntity); hud.setHudVacuumCleanerInfo(vacuumCleanerModel); vacuumCleanerRenderEntity.initResources(); } @Override public void update(float deltaTime) { if (actualState == State.RUNNING) { hud.update(deltaTime); vacuumCleanerModel.setHasCollision(false); entityRenderColisionVacuumCleanerCommand.execute(); boundsCollisionVacuumCleanerCommand.execute(); collectTrashVacuumCleanerCommand.execute(); makeMovementVacuumCleanerCommand.execute(); if(vacuumCleanerModel.hasCollision() && deltaCollisionTime > vacuumCleanerModel.getVelocity()) { moveToOppositeDirectionVacuumCleanerCommand.execute(); deltaCollisionTime = 0; } if (System.currentTimeMillis() - countTimeToChangeDirection > RANDOM_MOVEMENT_COOLDOWN) { randomMovemenVacuumCleanertCommand.execute(); countTimeToChangeDirection = System.currentTimeMillis(); } vacuumCleanerRenderEntity.update(deltaTime); deltaCollisionTime += deltaTime; } } @Override public void render(Graphics graphics) { if (actualState == State.RUNNING) { render.clear(graphics); render.render(graphics); hud.render(graphics); } } @Override public void dispose() { for (RenderEntity renderEntity : collidablesRenderEntities) renderEntity.updateConfig(globalConfig); vacuumCleanerRenderEntity.updateConfig(globalConfig); vacuumCleanerModel.setVelocity(globalConfig.getVacuumCleanerVelocity()); for(TrashRenderEntity trashRenderEntity : startRandomTrashsCommand.getTrashRenderEntities()) trashRenderEntity.updateConfig(globalConfig); } }
47.554878
202
0.730991
a2d867c7f9c7fd5f1c89c75176e44c86387a5d7a
865
package com.master.keymanagementserver.kms.helpers; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * UserStates Tester. * * @author <Authors name> * @version 1.0 * @since <pre>Oct 10, 2017</pre> */ public class UserStatesTest { @Before public void before() throws Exception { } @After public void after() throws Exception { } /** * Method: toString() */ @Test public void testToString() throws Exception { assertEquals("", "SENDPUBKEY", UserStates.SENDPUBKEY.toString()); assertEquals("", "ACCESSWRAPPEDKEY", UserStates.ACCESSWRAPPEDKEY.toString()); assertEquals("", "SENDWRAPPEDKEY", UserStates.SENDWRAPPEDKEY.toString()); assertEquals("", "SOLVECHALL", UserStates.SOLVECHALL.toString()); } }
22.179487
85
0.663584
a20c00f6ad30ce179a7d2df4da8330c08edf3122
551
package org.keycloak.social.streamlabs; import org.keycloak.broker.oidc.mappers.AbstractJsonUserAttributeMapper; /** * Streamlabs user attribute mapper. */ public class StreamlabsUserAttributeMapper extends AbstractJsonUserAttributeMapper { private static final String[] cp = new String[]{ StreamlabsIdentityProviderFactory.PROVIDER_ID, }; @Override public String[] getCompatibleProviders() { return cp; } @Override public String getId() { return "streamlabs-user-attribute-mapper"; } }
22.04
84
0.716878
8148428e3b97f6d87a97514e528fc6da551ef4f7
995
package io.github.code10ftn.monumentum.model; import java.util.Date; public class Comment { private long id; private String comment; private Monument monument; private Date timestamp; public Comment() { } public Comment(String comment, Monument monument, Date timestamp) { this.comment = comment; this.monument = monument; this.timestamp = timestamp; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public Monument getMonument() { return monument; } public void setMonument(Monument monument) { this.monument = monument; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } }
17.767857
71
0.61005
0c7ec78ed7bdc2aa3cd31a84759687eda5e92dd9
340
package cn.aixuxi.ossp.common.annotatioin; import java.lang.annotation.*; /** * 请求否方法参数上添加该注解,则注入当前登录账号的应用id * 例子:public void test(@LoginClient String clientId) // 则注入webApp * @author ruozhuliufeng * @date 2021-07-17 */ @Target(ElementType.PARAMETER) @Documented @Retention(RetentionPolicy.RUNTIME) public @interface LoginClient { }
21.25
65
0.767647
3263f54b05fdf9e6f485726761e33ae09f443a26
448
package vn.aptech.springboot.amazingtoy.service; import vn.aptech.springboot.amazingtoy.model.subcategory.Subcategory; import java.util.List; public interface SubcategoryService { List<Subcategory> findAllSubcat(); void create(Subcategory subcategory); void update(Subcategory subcategory); Subcategory findPk(int id); Subcategory findBySlug(String slug); boolean checkSlugExists(String slug); void delete(int id); }
28
69
0.772321
c15e59bd76e9f9d6d1635d80f7d9eb4958286e0b
2,878
package org.gridkit.jvmtool.gcmon; import org.gridkit.jvmtool.event.SimpleCounterCollection; import org.gridkit.jvmtool.event.SimpleTagCollection; public class MemoryInfoEventPojo implements MemoryPoolInfoEvent { private long timestamp; private SimpleTagCollection tags = new SimpleTagCollection(); private SimpleCounterCollection counters = new SimpleCounterCollection(); @Override public long timestamp() { return timestamp; } public void timestamp(long timestamp) { this.timestamp = timestamp; } @Override public SimpleCounterCollection counters() { return counters; } @Override public SimpleTagCollection tags() { return tags; } @Override public String name() { return tags.firstTagFor(MEM_POOL_NAME); } public void name(String value) { tags.put(MEM_POOL_NAME, value); } @Override public boolean nonHeap() { return tags.firstTagFor(MEM_POOL_NON_HEAP) != null; } public void nonHeap(boolean nonHeap) { if (nonHeap) { tags.put(MEM_POOL_NON_HEAP, ""); } } @Override public Iterable<String> memoryManagers() { return tags.tagsFor(MEM_POOL_MEMORY_MANAGER); } @Override public MemoryUsageBean peakUsage() { return readMemUsage(MEM_POOL_MEMORY_PEAK); } public void peakUsage(MemoryUsageBean usage) { storeMemUsage(MEM_POOL_MEMORY_PEAK, usage); } @Override public MemoryUsageBean currentUsage() { return readMemUsage(MEM_POOL_MEMORY_USAGE); } public void currentUsage(MemoryUsageBean usage) { storeMemUsage(MEM_POOL_MEMORY_USAGE, usage); } @Override public MemoryUsageBean collectionUsage() { return readMemUsage(MEM_POOL_COLLECTION_USAGE); } public void collectionUsage(MemoryUsageBean usage) { storeMemUsage(MEM_POOL_COLLECTION_USAGE, usage); } private MemoryUsageBean readMemUsage(String name) { if (counters.getValue(name + "." + MEM_USAGE_INIT) >= 0) { return new MemoryUsageBean( counters.getValue(name + "." + MEM_USAGE_INIT), counters.getValue(name + "." + MEM_USAGE_USED), counters.getValue(name + "." + MEM_USAGE_COMMITTED), counters.getValue(name + "." + MEM_USAGE_MAX)); } else { return null; } } private void storeMemUsage(String name, MemoryUsageBean bean) { counters.set(name + "." + MEM_USAGE_INIT, bean.init()); counters.set(name + "." + MEM_USAGE_USED, bean.used()); counters.set(name + "." + MEM_USAGE_COMMITTED, bean.committed()); counters.set(name + "." + MEM_USAGE_MAX, bean.max()); } }
27.673077
77
0.627172
0ed1483818ae139af7988cbb9e4f2ecf2b1d1d5a
1,166
package se.arbetsformedlingen.matchning.portability.builder; import se.arbetsformedlingen.matchning.portability.dto.PhoneType; public class PhoneTypeBuilder { private PhoneType phoneType = new PhoneType(); public PhoneTypeBuilder setCountryDialingCode(String countryDialingCode) { phoneType.setCountryDialingCode(countryDialingCode); return this; } public PhoneTypeBuilder setAreaDialingCode(String areaDialingCode) { phoneType.setAreaDialingCode(areaDialingCode); return this; } public PhoneTypeBuilder setDialNumber(String dialNumber) { phoneType.setDialNumber(dialNumber); return this; } public PhoneTypeBuilder setPhoneExtension(String phoneExtension) { phoneType.setPhoneExtension(phoneExtension); return this; } public PhoneTypeBuilder setAccess(String access) { phoneType.setAccess(access); return this; } public PhoneTypeBuilder setFormattedNumber(String formattedNumber) { phoneType.setFormattedNumber(formattedNumber); return this; } public PhoneType build() { return phoneType; } }
27.761905
78
0.721269
44d364a92846acd8c722a8494a130b9011f93c7b
2,109
/** * Copyright (c) 2002-2013 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.kernel.impl.util; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Path; import org.neo4j.graphdb.PropertyContainer; import org.neo4j.graphdb.Relationship; public class SingleNodePath implements Path { private final Node node; public SingleNodePath( Node node ) { this.node = node; } @Override public Node startNode() { return node; } @Override public Node endNode() { return node; } @Override public Relationship lastRelationship() { return null; } @Override public Iterable<Relationship> relationships() { return Collections.emptyList(); } @Override public Iterable<Relationship> reverseRelationships() { return relationships(); } @Override public Iterable<Node> nodes() { return Arrays.asList( node ); } @Override public Iterable<Node> reverseNodes() { return nodes(); } @Override public int length() { return 0; } @Override public Iterator<PropertyContainer> iterator() { return Arrays.<PropertyContainer>asList( node ).iterator(); } }
22.43617
72
0.661451
546cb5f829eb1d3b75c029f671a4122b812648c4
600
package me.ianhe.security.model; /** * @author iHelin * @date 2018-12-17 17:37 */ public class RolePath { private String pathPattern; private String role; public RolePath(String pathPattern, String role) { this.pathPattern = pathPattern; this.role = role; } public String getPathPattern() { return pathPattern; } public void setPathPattern(String pathPattern) { this.pathPattern = pathPattern; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } }
18.181818
54
0.62
90f14e0a7b080b39285be2c4097220e7e6bab99e
3,481
/* GNU LESSER GENERAL PUBLIC LICENSE Copyright (C) 2006 The Lobo Project This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Contact info: lobochief@users.sourceforge.net */ /* * Created on Jan 15, 2006 */ package org.cobraparser.html.renderer; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import org.cobraparser.html.domimpl.HTMLBaseInputElement; import org.cobraparser.html.domimpl.HTMLInputElementImpl; import org.cobraparser.util.gui.WrapperLayout; class InputButtonControl extends BaseInputControl { private static final long serialVersionUID = -8399402892016789567L; private final JButton widget; public InputButtonControl(final HTMLBaseInputElement modelNode) { super(modelNode); this.setLayout(WrapperLayout.getInstance()); final JButton widget = new JButton(); widget.setContentAreaFilled(false); this.widget = widget; this.add(widget); widget.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent event) { HtmlController.getInstance().onPressed(InputButtonControl.this.controlElement, null, 0, 0); } }); } @Override public void reset(final int availWidth, final int availHeight) { super.reset(availWidth, availHeight); final RUIControl ruiControl = this.ruicontrol; final JButton button = this.widget; button.setContentAreaFilled(!ruiControl.hasBackground()); final java.awt.Color foregroundColor = ruiControl.getForegroundColor(); if (foregroundColor != null) { button.setForeground(foregroundColor); } final HTMLInputElementImpl element = (HTMLInputElementImpl) this.controlElement; String text = element.getAttribute("value"); if ((text == null) || (text.length() == 0)) { final String type = element.getType(); if ("submit".equalsIgnoreCase(type)) { text = " "; } else if ("reset".equalsIgnoreCase(type)) { text = " "; } else { text = ""; } } button.setText(text); } /* * (non-Javadoc) * * @see org.xamjwg.html.domimpl.InputContext#click() */ @Override public void click() { this.widget.doClick(); } /* * (non-Javadoc) * * @see org.xamjwg.html.domimpl.InputContext#getValue() */ @Override public String getValue() { return this.widget.getText(); } @Override public void setDisabled(final boolean disabled) { super.setDisabled(disabled); this.widget.setEnabled(!disabled); } /* * (non-Javadoc) * * @see org.xamjwg.html.domimpl.InputContext#setValue(java.lang.String) */ @Override public void setValue(final String value) { this.widget.setText(value); } public void resetInput() { // nop } }
29.5
99
0.699799
c51ffa8a490d0d178a976250eb9950c9654d59ca
18,023
/** * Copyright 2011-2021 Asakusa Framework Team. * * 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.asakusafw.compiler.operator.util; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import com.asakusafw.compiler.common.Precondition; import com.asakusafw.compiler.operator.OperatorCompilingEnvironment; import com.asakusafw.compiler.operator.OperatorPortDeclaration; import com.asakusafw.utils.java.jsr269.bridge.Jsr269; import com.asakusafw.utils.java.model.syntax.AnnotationElement; import com.asakusafw.utils.java.model.syntax.Expression; import com.asakusafw.utils.java.model.syntax.FormalParameterDeclaration; import com.asakusafw.utils.java.model.syntax.Literal; import com.asakusafw.utils.java.model.syntax.ModelFactory; import com.asakusafw.utils.java.model.syntax.NamedType; import com.asakusafw.utils.java.model.syntax.SimpleName; import com.asakusafw.utils.java.model.syntax.Type; import com.asakusafw.utils.java.model.syntax.TypeParameterDeclaration; import com.asakusafw.utils.java.model.util.AttributeBuilder; import com.asakusafw.utils.java.model.util.ImportBuilder; import com.asakusafw.utils.java.model.util.Models; import com.asakusafw.utils.java.model.util.TypeBuilder; import com.asakusafw.vocabulary.flow.In; import com.asakusafw.vocabulary.flow.Out; import com.asakusafw.vocabulary.flow.Source; import com.asakusafw.vocabulary.flow.graph.ShuffleKey; import com.asakusafw.vocabulary.operator.KeyInfo; import com.asakusafw.vocabulary.operator.OperatorInfo; /** * Utilities about building Java DOM. * @since 0.1.0 * @version 0.5.0 */ public class GeneratorUtil { private final OperatorCompilingEnvironment environment; private final ModelFactory factory; private final ImportBuilder importer; /** * Creates a new instance. * @param environment the current environment * @param factory the Java DOM factory * @param importer the current import declaration builder * @throws IllegalArgumentException if the parameter is {@code null} */ public GeneratorUtil( OperatorCompilingEnvironment environment, ModelFactory factory, ImportBuilder importer) { Precondition.checkMustNotBeNull(environment, "environment"); //$NON-NLS-1$ Precondition.checkMustNotBeNull(factory, "factory"); //$NON-NLS-1$ Precondition.checkMustNotBeNull(importer, "importer"); //$NON-NLS-1$ this.environment = environment; this.factory = factory; this.importer = importer; } /** * Returns a simple name of the operator factory class for the specified type. * @param type the target type * @return the corresponded simple name * @throws IllegalArgumentException if the parameter is {@code null} */ public final SimpleName getFactoryName(TypeElement type) { Precondition.checkMustNotBeNull(type, "type"); //$NON-NLS-1$ return factory.newSimpleName(MessageFormat.format( "{0}{1}", //$NON-NLS-1$ type.getSimpleName(), "Factory")); //$NON-NLS-1$ } /** * Returns a simple name of the operator implementation class for the specified type. * @param type the target type * @return the corresponded simple name * @throws IllegalArgumentException if the parameter is {@code null} */ public final SimpleName getImplementorName(TypeElement type) { Precondition.checkMustNotBeNull(type, "type"); //$NON-NLS-1$ return factory.newSimpleName(getImplmentorName( type.getSimpleName().toString())); } /** * Returns a simple name of the operator factory class for the specified type. * @param typeName the target type name * @return the corresponded simple name * @throws IllegalArgumentException if the parameter is {@code null} */ public static final String getImplmentorName(String typeName) { Precondition.checkMustNotBeNull(typeName, "typeName"); //$NON-NLS-1$ return MessageFormat.format( "{0}{1}", //$NON-NLS-1$ typeName, "Impl"); //$NON-NLS-1$ } /** * Returns the type model for the specified type. * @param type the target type * @return the type model * @throws IllegalArgumentException if the parameter is {@code null} */ public final Type t(TypeMirror type) { Precondition.checkMustNotBeNull(type, "type"); //$NON-NLS-1$ return importer.resolve(new Jsr269(factory).convert(type)); } /** * Returns the type model for the specified type. * @param type the target type * @return the type model * @throws IllegalArgumentException if the parameter is {@code null} */ public final Type t(TypeElement type) { Precondition.checkMustNotBeNull(type, "type"); //$NON-NLS-1$ DeclaredType t = environment.getTypeUtils().getDeclaredType(type); return importer.resolve(new Jsr269(factory).convert(t)); } /** * Returns the type model for the specified type. * @param type the target type * @return the type model * @throws IllegalArgumentException if the parameter is {@code null} */ public final Type t(java.lang.reflect.Type type) { Precondition.checkMustNotBeNull(type, "type"); //$NON-NLS-1$ return importer.toType(type); } /** * Returns the literal model for the specified value. * @param value the target value * @return the literal model * @throws IllegalArgumentException if the parameter is {@code null} */ public Literal v(String value) { Precondition.checkMustNotBeNull(value, "value"); //$NON-NLS-1$ return Models.toLiteral(factory, value); } /** * Returns the literal model for the specified value. * @param pattern the string patter ({@link MessageFormat} style) * @param arguments the pattern arguments ({@link MessageFormat} style) * @return the literal model * @throws IllegalArgumentException if the parameter is {@code null} */ public Literal v(String pattern, Object... arguments) { Precondition.checkMustNotBeNull(pattern, "pattern"); //$NON-NLS-1$ Precondition.checkMustNotBeNull(arguments, "arguments"); //$NON-NLS-1$ return Models.toLiteral(factory, MessageFormat.format(pattern, arguments)); } /** * Returns the {@link Source operator output} for the corresponding data type. * @param type the target data type * @return the corresponded operator output type * @throws IllegalArgumentException if the parameter is {@code null} */ public Type toSourceType(TypeMirror type) { Precondition.checkMustNotBeNull(type, "type"); //$NON-NLS-1$ Type source = t(Source.class); Type modelType = t(type); return factory.newParameterizedType(source, Collections.singletonList(modelType)); } /** * Returns the {@link In flow input} for the corresponding data type. * @param type the target data type * @return the corresponded flow input type * @throws IllegalArgumentException if the parameter is {@code null} */ public Type toInType(TypeMirror type) { Precondition.checkMustNotBeNull(type, "type"); //$NON-NLS-1$ Type source = t(In.class); Type modelType = t(type); return factory.newParameterizedType(source, Collections.singletonList(modelType)); } /** * Returns the {@link Out flow output type} for the corresponding data type. * @param type the target data type * @return the corresponded flow output type * @throws IllegalArgumentException if the parameter is {@code null} */ public Type toOutType(TypeMirror type) { Precondition.checkMustNotBeNull(type, "type"); //$NON-NLS-1$ Type source = t(Out.class); Type modelType = t(type); return factory.newParameterizedType(source, Collections.singletonList(modelType)); } /** * Returns the representation for type parameter declarations of the executable element. * @param element target element * @return the corresponded representation * @throws IllegalArgumentException if the parameter is {@code null} */ public List<TypeParameterDeclaration> toTypeParameters(ExecutableElement element) { Precondition.checkMustNotBeNull(element, "element"); //$NON-NLS-1$ return toTypeParameters(element.getTypeParameters()); } /** * Returns the representation for type parameter declarations of the type element. * @param element target element * @return the corresponded representation * @throws IllegalArgumentException if the parameter is {@code null} */ public List<TypeParameterDeclaration> toTypeParameters(TypeElement element) { Precondition.checkMustNotBeNull(element, "element"); //$NON-NLS-1$ return toTypeParameters(element.getTypeParameters()); } private List<TypeParameterDeclaration> toTypeParameters( List<? extends TypeParameterElement> typeParameters) { assert typeParameters != null; List<TypeParameterDeclaration> results = new ArrayList<>(); for (TypeParameterElement typeParameter : typeParameters) { SimpleName name = factory.newSimpleName(typeParameter.getSimpleName().toString()); List<Type> typeBounds = new ArrayList<>(); for (TypeMirror typeBound : typeParameter.getBounds()) { typeBounds.add(t(typeBound)); } results.add(factory.newTypeParameterDeclaration(name, typeBounds)); } return results; } /** * Returns the representation for type variables of the executable element. * @param element target element * @return the corresponded representation * @throws IllegalArgumentException if the parameter is {@code null} */ public List<Type> toTypeVariables(ExecutableElement element) { Precondition.checkMustNotBeNull(element, "element"); //$NON-NLS-1$ return toTypeVariables(element.getTypeParameters()); } /** * Returns the representation for type variables of the type element. * @param element target element * @return the corresponded representation * @throws IllegalArgumentException if the parameter is {@code null} */ public List<Type> toTypeVariables(TypeElement element) { Precondition.checkMustNotBeNull(element, "element"); //$NON-NLS-1$ return toTypeVariables(element.getTypeParameters()); } private List<Type> toTypeVariables(List<? extends TypeParameterElement> typeParameters) { List<Type> results = new ArrayList<>(); for (TypeParameterElement typeParameter : typeParameters) { SimpleName name = factory.newSimpleName(typeParameter.getSimpleName().toString()); results.add(factory.newNamedType(name)); } return results; } /** * Converts {@link OperatorPortDeclaration} into an operator factory method parameter. * @param var target port declaration * @param name the actual parameter name * @return related parameter declaration * @throws IllegalArgumentException if some parameters were {@code null} */ public FormalParameterDeclaration toFactoryMethodInput(OperatorPortDeclaration var, SimpleName name) { Precondition.checkMustNotBeNull(var, "var"); //$NON-NLS-1$ Precondition.checkMustNotBeNull(name, "name"); //$NON-NLS-1$ AttributeBuilder attributes = new AttributeBuilder(factory); ShuffleKey key = var.getShuffleKey(); if (key != null) { List<Expression> group = new ArrayList<>(); for (String entry : key.getGroupProperties()) { group.addAll(new AttributeBuilder(factory) .annotation( t(KeyInfo.Group.class), "expression", //$NON-NLS-1$ Models.toLiteral(factory, entry)) .toAnnotations()); } List<Expression> order = new ArrayList<>(); for (ShuffleKey.Order entry : key.getOrderings()) { order.addAll(new AttributeBuilder(factory) .annotation( t(KeyInfo.Order.class), "direction", new TypeBuilder(factory, t(KeyInfo.Direction.class)) //$NON-NLS-1$ .field(entry.getDirection().name()) .toExpression(), "expression", Models.toLiteral(factory, entry.getProperty())) //$NON-NLS-1$ .toAnnotations()); } attributes.annotation( t(KeyInfo.class), "group", factory.newArrayInitializer(group), //$NON-NLS-1$ "order", factory.newArrayInitializer(order)); //$NON-NLS-1$ } return factory.newFormalParameterDeclaration( attributes.toAttributes(), toSourceType(var.getType().getRepresentation()), false, name, 0); } /** * Converts {@link OperatorPortDeclaration} into a member of {@link OperatorInfo}. * @param var target port declaration * @param position the factory parameter position * @return related meta-data * @throws IllegalArgumentException if some parameters were {@code null} */ public Expression toMetaData(OperatorPortDeclaration var, int position) { Precondition.checkMustNotBeNull(var, "var"); //$NON-NLS-1$ NamedType type; TypeMirror representation = var.getType().getRepresentation(); List<AnnotationElement> members = new ArrayList<>(); members.add(factory.newAnnotationElement( factory.newSimpleName("name"), //$NON-NLS-1$ Models.toLiteral(factory, var.getName()))); members.add(factory.newAnnotationElement( factory.newSimpleName("type"), //$NON-NLS-1$ factory.newClassLiteral(t(environment.getErasure(representation))))); if (var.getKind() == OperatorPortDeclaration.Kind.INPUT) { type = (NamedType) t(OperatorInfo.Input.class); members.add(factory.newAnnotationElement( factory.newSimpleName("position"), //$NON-NLS-1$ Models.toLiteral(factory, position))); String typeVariable = getTypeVariableName(representation); if (typeVariable != null) { members.add(factory.newAnnotationElement( factory.newSimpleName("typeVariable"), //$NON-NLS-1$ Models.toLiteral(factory, typeVariable))); } } else if (var.getKind() == OperatorPortDeclaration.Kind.OUTPUT) { type = (NamedType) t(OperatorInfo.Output.class); String typeVariable = getTypeVariableName(representation); if (typeVariable != null) { members.add(factory.newAnnotationElement( factory.newSimpleName("typeVariable"), //$NON-NLS-1$ Models.toLiteral(factory, typeVariable))); } } else if (var.getKind() == OperatorPortDeclaration.Kind.CONSTANT) { type = (NamedType) t(OperatorInfo.Parameter.class); members.add(factory.newAnnotationElement( factory.newSimpleName("position"), //$NON-NLS-1$ Models.toLiteral(factory, position))); String typeVariable = getTypeVariableNameInClass(representation); if (typeVariable != null) { members.add(factory.newAnnotationElement( factory.newSimpleName("typeVariable"), //$NON-NLS-1$ Models.toLiteral(factory, typeVariable))); } } else { throw new AssertionError(var); } return factory.newNormalAnnotation( type, members); } private String getTypeVariableName(TypeMirror representation) { if (representation.getKind() == TypeKind.TYPEVAR) { return ((TypeVariable) representation).asElement().getSimpleName().toString(); } return null; } private String getTypeVariableNameInClass(TypeMirror representation) { if (representation.getKind() != TypeKind.DECLARED) { return null; } List<? extends TypeMirror> typeArgs = ((DeclaredType) representation).getTypeArguments(); if (typeArgs.size() != 1) { return null; } DeclaredType raw = (DeclaredType) environment.getErasure(representation); if (environment.getTypeUtils().isSameType(raw, environment.getDeclaredType(Class.class)) == false) { return null; } return getTypeVariableName(typeArgs.get(0)); } }
43.220624
111
0.655163
5c4fabb0798d3eef7a78e7070c4396d2c83d0a85
8,111
package ru.nivanov; import java.util.*; /** * Created by Nikolay Ivanov on 26.05.2017. */ class OrderBook { private String name; private TreeMap<Float, Order> buyOrders; private TreeMap<Float, Order> sellOrders; private String sep = System.getProperty("line.separator"); private Set<OrderBook> orderBooksSet; /** * Constructor. */ OrderBook(String name) { this.name = name; this.buyOrders = new TreeMap<>(new Comparator<Float>() { @Override public int compare(Float o1, Float o2) { return -o1.compareTo(o2); } }); this.sellOrders = new TreeMap<>(new Comparator<Float>() { @Override public int compare(Float o1, Float o2) { return o1.compareTo(o2); } }); } /** * New order book generator. * @param name .. * @return .. */ private OrderBook newOrderBook(String name) { return new OrderBook(name); } /** * Filling books with sell and buy orders. * @param unsort .. * @param bookNamesSet .. */ void fillBooksNew(HashMap<Integer, Order> unsort, Set<String> bookNamesSet) { bookSetupNew(bookNamesSet); Collection<Order> ordersList = unsort.values(); Iterator<Order> iter = ordersList.iterator(); while (iter.hasNext()) { Order current = iter.next(); for (OrderBook currentBook : orderBooksSet) { if (current.getBook().equals(currentBook.name)) { if (current.getOrderType().equals("BUY")) { if (currentBook.buyOrders.containsKey(current.getPrice())) { int newVolume = current.getVolume() + currentBook.buyOrders.get( current.getPrice()).getVolume(); current.setVolume(newVolume); currentBook.buyOrders.put(current.getPrice(), current); break; } else { currentBook.buyOrders.put(current.getPrice(), current); break; } } else { if (currentBook.sellOrders.containsKey(current.getPrice())) { int newVolume = current.getVolume() + currentBook.sellOrders.get( current.getPrice()).getVolume(); current.setVolume(newVolume); currentBook.sellOrders.put(current.getPrice(), current); break; } else { currentBook.sellOrders.put(current.getPrice(), current); break; } } } } } } /** * Setting up sell orders and buy ordres collections. * @param bookSet .. */ private void bookSetupNew(Set<String> bookSet) { orderBooksSet = new TreeSet<>(new Comparator<OrderBook>() { @Override public int compare(OrderBook o1, OrderBook o2) { return o1.name.compareTo(o2.name); } }); for (String value : bookSet) { orderBooksSet.add(newOrderBook(value)); } } /** * Executing matching logic. */ void bookExecuteNew() { for (OrderBook book : orderBooksSet) { Iterator<Map.Entry<Float, Order>> buyIter = book.buyOrders.entrySet().iterator(); Iterator<Map.Entry<Float, Order>> sellIter = book.sellOrders.entrySet().iterator(); while (buyIter.hasNext() && sellIter.hasNext()) { Map.Entry<Float, Order> currentBuy = buyIter.next(); Map.Entry<Float, Order> currentSell = sellIter.next(); while (currentBuy.getKey() >= currentSell.getKey()) { int newVolume = currentBuy.getValue().getVolume() - currentSell.getValue().getVolume(); if (newVolume > 0) { currentBuy.getValue().setVolume(newVolume); sellIter.remove(); if (sellIter.hasNext()) { currentSell = sellIter.next(); } else { break; } } else if (newVolume < 0) { currentSell.getValue().setVolume(-newVolume); buyIter.remove(); if (buyIter.hasNext()) { currentBuy = buyIter.next(); } else { break; } } else if (newVolume == 0) { buyIter.remove(); sellIter.remove(); if (buyIter.hasNext() && sellIter.hasNext()) { currentBuy = buyIter.next(); currentSell = sellIter.next(); } else if (!buyIter.hasNext() || !sellIter.hasNext()) { break; } } } } } } /** * Printing books. */ void printBooksNew() { for (OrderBook book : orderBooksSet) { Iterator<Map.Entry<Float, Order>> buyIter = book.buyOrders.entrySet().iterator(); Iterator<Map.Entry<Float, Order>> sellIter = book.sellOrders.entrySet().iterator(); StringBuilder sb = new StringBuilder(); sb.append(String.format("Order book: %s", book.name)); sb.append(sep); sb.append("BID ASK"); sb.append(sep); sb.append("Volume@Price - Volume@Price"); sb.append(sep); while (buyIter.hasNext() && sellIter.hasNext()) { Map.Entry<Float, Order> currentBuy = buyIter.next(); Map.Entry<Float, Order> currentSell = sellIter.next(); sb.append(String.format("%,9d", currentBuy.getValue().getVolume())); sb.append("@"); sb.append(String.format("%5.1f", currentBuy.getKey())); sb.append(" - "); sb.append(String.format("%,9d", currentSell.getValue().getVolume())); sb.append("@"); sb.append(String.format("%5.1f", currentSell.getKey())); sb.append(sep); } if (buyIter.hasNext()) { while (buyIter.hasNext()) { Map.Entry<Float, Order> currentBuy = buyIter.next(); sb.append(String.format("%,9d", currentBuy.getValue().getVolume())); sb.append("@"); sb.append(String.format("%5.1f", currentBuy.getKey())); sb.append(" - "); sb.append(String.format("%13s", "------")); sb.append(sep); } } else if (sellIter.hasNext()) { while (sellIter.hasNext()) { Map.Entry<Float, Order> currentSell = sellIter.next(); sb.append(String.format("%18s", "------ ")); sb.append(String.format("%,9d", currentSell.getValue().getVolume())); sb.append("@"); sb.append(String.format("%5.1f", currentSell.getKey())); sb.append(sep); } } System.out.println(sb); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OrderBook orderBook = (OrderBook) o; return name.equals(orderBook.name); } @Override public int hashCode() { return name.hashCode(); } }
35.574561
107
0.467267
02bce3db399ca3d3f1850eafe452547e9b73252a
1,138
package simulations; import gameparts.RangedWeapon; import gameparts.Weapon; public class WeaponSims { Weapon weapon; int simulations; public WeaponSims(Weapon weapon) { this.weapon = weapon; } public void runRawDamageSimulation(int simulations) { int totalDamage = 0; ////Just calculates raw damage done by a weapon based on X simulations, this doesn't include saving throws of the defense for(int i = 0; i < simulations; i++) { this.weapon.attack(); totalDamage = totalDamage + this.weapon.getDamage(); } System.out.println("Total damage done over " + simulations + " was " + totalDamage); float averageDamagePerTurn = ((float) totalDamage) / ((float) simulations); System.out.println("Avreage raw damage per turn before defense with weapon is " + averageDamagePerTurn); } public static void main(String args[]) { RangedWeapon lasergun = new RangedWeapon(4,3,2,3); WeaponSims testSim = new WeaponSims(lasergun); testSim.runRawDamageSimulation(10000); } }
35.5625
130
0.644991
2ca5163205b4fb25cf56a9bc587e37aa5ff42c06
481
// Code generated by lark suite oapi sdk gen package com.larksuite.oapi.service.sheets.v2.model; import com.google.gson.annotations.SerializedName; public class SpreadsheetsValuesImageResult { @SerializedName("spreadsheetToken") private String spreadsheetToken; public String getSpreadsheetToken() { return this.spreadsheetToken; } public void setSpreadsheetToken(String spreadsheetToken) { this.spreadsheetToken = spreadsheetToken; } }
26.722222
62
0.756757
f0c4bd777c8eb3ab9bc7237646c66bdbcb0eb49c
197
package fr.rss.download.api.constantes; public class Const { public static final String DEFAULT_VALUE = "defaultValue"; public static final String TV_SHOW_LIST_FILE = "myTvShowList_test.xml"; }
28.142857
72
0.796954
919c97951f604457ef5029b1d734a85c1199ed2b
2,048
/* * Copyright 2019-2021 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 cool.houge.logic.grpc; import io.grpc.stub.StreamObserver; import javax.inject.Inject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import reactor.core.publisher.Flux; import reactor.core.scheduler.Schedulers; import cool.houge.grpc.UserGroupPb.ListGidsRequest; import cool.houge.grpc.UserGroupPb.ListGidsResponse; import cool.houge.grpc.UserGroupGrpc; import cool.houge.storage.query.GroupQueryDao; /** * 用户群组gRPC服务实现. * * @author KK (kzou227@qq.com) */ public class UserGroupGrpcImpl extends UserGroupGrpc.UserGroupImplBase { private static final Logger log = LogManager.getLogger(); private final GroupQueryDao groupQueryDao; /** @param groupQueryDao */ @Inject public UserGroupGrpcImpl(GroupQueryDao groupQueryDao) { this.groupQueryDao = groupQueryDao; } @Override public void listGids(ListGidsRequest request, StreamObserver<ListGidsResponse> responseObserver) { Flux.defer(() -> groupQueryDao.queryGidByUid(request.getUid())) .subscribeOn(Schedulers.parallel()) .collectList() .subscribe( gids -> { responseObserver.onNext(ListGidsResponse.newBuilder().addAllGid(gids).build()); responseObserver.onCompleted(); }, ex -> { log.error("查询用户[{}]的群组IDs错误", request.getUid(), ex); responseObserver.onError(ex); }); } }
33.57377
100
0.717773
117cc90598106aecc98deea7b1288fea01545868
538
package game.item; import static java.lang.Math.*; import static util.MathUtil.*; import util.BmpRes; public class IronHammer extends HammerType{ private static final long serialVersionUID=1844677L; static BmpRes bmp=new BmpRes("Item/IronHammer"); public BmpRes getBmp(){return bmp;} protected double toolVal(){return 4;} public int maxDamage(){return 25000;} public void onBroken(double x,double y){ new Iron().drop(x,y,rndi(4,6)); super.onBroken(x,y); } public double hardness(){return game.entity.NormalAttacker.IRON;} }
26.9
66
0.754647
dd67cdfb2062721dc92a1db2eb1a3ea07ef7f41e
3,928
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.curve.interestrate; import java.util.Collections; import java.util.Set; import org.threeten.bp.Instant; import org.threeten.bp.LocalTime; import org.threeten.bp.ZoneOffset; import org.threeten.bp.ZonedDateTime; import com.opengamma.core.config.ConfigSource; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.CompiledFunctionDefinition; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.target.ComputationTargetType; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.OpenGammaExecutionContext; import com.opengamma.financial.analytics.ircurve.calcconfig.ConfigDBCurveCalculationConfigSource; import com.opengamma.financial.analytics.ircurve.calcconfig.MultiCurveCalculationConfig; /** * */ public class MultiCurveCalculationConfigFunction extends AbstractFunction { @Override public void init(final FunctionCompilationContext context) { ConfigDBCurveCalculationConfigSource.reinitOnChanges(context, this); } @Override public CompiledFunctionDefinition compile(final FunctionCompilationContext context, final Instant atInstant) { final ZonedDateTime atZDT = ZonedDateTime.ofInstant(atInstant, ZoneOffset.UTC); return new AbstractInvokingCompiledFunction(atZDT.with(LocalTime.MIDNIGHT), atZDT.plusDays(1).with(LocalTime.MIDNIGHT).minusNanos(1000000)) { @Override public ComputationTargetType getTargetType() { return ComputationTargetType.NULL; } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext compilationContext, final ComputationTarget target) { final ValueProperties properties = createValueProperties() .withAny(ValuePropertyNames.CURVE_CALCULATION_CONFIG).get(); final ValueSpecification spec = new ValueSpecification(ValueRequirementNames.CURVE_CALCULATION_CONFIG, target.toSpecification(), properties); return Collections.singleton(spec); } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext compilationContext, final ComputationTarget target, final ValueRequirement desiredValue) { return Collections.emptySet(); } @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { final ConfigSource configSource = OpenGammaExecutionContext.getConfigSource(executionContext); final ConfigDBCurveCalculationConfigSource source = new ConfigDBCurveCalculationConfigSource(configSource); final ValueRequirement desiredValue = desiredValues.iterator().next(); final String curveConfigName = desiredValue.getConstraint(ValuePropertyNames.CURVE_CALCULATION_CONFIG); final MultiCurveCalculationConfig config = source.getConfig(curveConfigName); final ValueProperties properties = createValueProperties() .with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveConfigName).get(); return Collections.singleton(new ComputedValue(new ValueSpecification(ValueRequirementNames.CURVE_CALCULATION_CONFIG, target.toSpecification(), properties), config)); } }; } }
47.325301
194
0.805754
fa328c1b323e928e558bfdb73681ffa3cbb9af7e
115
package com.codurance.domain.io; public interface UserInput { boolean hasNextLine(); String nextLine(); }
16.428571
32
0.721739
6062c2b476e441bc0aee03a431892436077ff7d0
5,540
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.jmsra.bean; import java.rmi.RemoteException; import java.util.*; import javax.ejb.SessionBean; import javax.ejb.SessionContext; import javax.ejb.EJBException; import javax.naming.*; import javax.jms.*; public class TopicPublisherBean implements SessionBean { static org.apache.log4j.Category log = org.apache.log4j.Category.getInstance(TopicPublisherBean.class); private static final String CONNECTION_JNDI = "java:comp/env/jms/MyTopicConnection"; private static final String TOPIC_JNDI = "java:comp/env/jms/TopicName"; private static final String BEAN_JNDI = "java:comp/env/ejb/PublisherCMP"; private SessionContext ctx = null; private Topic topic = null; private TopicConnection topicConnection = null; public TopicPublisherBean() { } public void setSessionContext(SessionContext ctx) { this.ctx = ctx; } public void ejbCreate() { try { Context context = new InitialContext(); topic = (Topic)context.lookup(TOPIC_JNDI); TopicConnectionFactory factory = (TopicConnectionFactory)context.lookup(CONNECTION_JNDI); topicConnection = factory.createTopicConnection(); } catch (Exception ex) { // JMSException or NamingException could be thrown log.debug("failed", ex); throw new EJBException(ex.toString()); } } /** * Send a message with a message nr in property MESSAGE_NR */ public void simple(int messageNr) { sendMessage(messageNr); } /** * Try send a message with a message nr in property MESSAGE_NR, * but set rollback only */ public void simpleFail(int messageNr) { sendMessage(messageNr); // Roll it back, no message should be sent if transactins work log.debug("DEBUG: Setting rollbackOnly"); ctx.setRollbackOnly(); log.debug("DEBUG rollback set: " + ctx.getRollbackOnly()); } public void beanOk(int messageNr) { // DO JMS - First transaction sendMessage(messageNr); PublisherCMPHome h = null; try { // DO entity bean - Second transaction h = (PublisherCMPHome) new InitialContext().lookup(BEAN_JNDI); PublisherCMP b = h.create(new Integer(messageNr)); b.ok(messageNr); }catch(Exception ex) { throw new EJBException("OPS exception in ok: " + ex); } finally { try { h.remove(new Integer(messageNr)); }catch(Exception e) { log.debug("failed", e); } } } public void beanError(int messageNr) { // DO JMS - First transaction sendMessage(messageNr); PublisherCMPHome h = null; try { // DO entity bean - Second transaction h = (PublisherCMPHome) new InitialContext().lookup(BEAN_JNDI); PublisherCMP b = h.create(new Integer(messageNr)); b.error(messageNr); } catch(Exception ex) { throw new EJBException("Exception in erro: " + ex); }finally { try { h.remove(new Integer(messageNr)); }catch(Exception ex) { log.debug("failed", ex); } } } public void ejbRemove() throws RemoteException { if(topicConnection != null) { try { topicConnection.close(); } catch (Exception e) { log.debug("failed", e); } } } public void ejbActivate() {} public void ejbPassivate() {} private void sendMessage(int messageNr) { TopicSession topicSession = null; try { TopicPublisher topicPublisher = null; TextMessage message = null; topicSession = topicConnection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE); topicPublisher = topicSession.createPublisher(topic); message = topicSession.createTextMessage(); message.setText(String.valueOf(messageNr)); message.setIntProperty(Publisher.JMS_MESSAGE_NR, messageNr); topicPublisher.publish(message); } catch (JMSException ex) { log.debug("failed", ex); ctx.setRollbackOnly(); throw new EJBException(ex.toString()); } finally { if (topicSession != null) { try { topicSession.close(); } catch (Exception e) { log.debug("failed", e); } } } } }
31.83908
100
0.633032
1a0403bccbc0a215cfb44e04ab5088843a000d40
3,127
/*********************************************************************************************************************** * 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.test.iterative.nephele.customdanglingpagerank; import eu.stratosphere.api.common.functions.AbstractFunction; import eu.stratosphere.api.common.functions.GenericCollectorMap; import eu.stratosphere.configuration.Configuration; import eu.stratosphere.test.iterative.nephele.ConfigUtils; import eu.stratosphere.test.iterative.nephele.customdanglingpagerank.types.VertexWithRankAndDangling; import eu.stratosphere.test.iterative.nephele.danglingpagerank.PageRankStats; import eu.stratosphere.util.Collector; import java.util.Set; public class CustomCompensatingMap extends AbstractFunction implements GenericCollectorMap<VertexWithRankAndDangling, VertexWithRankAndDangling> { private static final long serialVersionUID = 1L; private boolean isFailureIteration; private boolean isFailingWorker; private double uniformRank; private double rescaleFactor; @Override public void open(Configuration parameters) throws Exception { int currentIteration = getIterationRuntimeContext().getSuperstepNumber(); int failingIteration = ConfigUtils.asInteger("compensation.failingIteration", parameters); isFailureIteration = currentIteration == failingIteration + 1; int workerIndex = getRuntimeContext().getIndexOfThisSubtask(); Set<Integer> failingWorkers = ConfigUtils.asIntSet("compensation.failingWorker", parameters); isFailingWorker = failingWorkers.contains(workerIndex); long numVertices = ConfigUtils.asLong("pageRank.numVertices", parameters); if (currentIteration > 1) { PageRankStats stats = (PageRankStats) getIterationRuntimeContext().getPreviousIterationAggregate(CustomCompensatableDotProductCoGroup.AGGREGATOR_NAME); uniformRank = 1d / (double) numVertices; double lostMassFactor = (numVertices - stats.numVertices()) / (double) numVertices; rescaleFactor = (1 - lostMassFactor) / stats.rank(); } } @Override public void map(VertexWithRankAndDangling pageWithRank, Collector<VertexWithRankAndDangling> out) throws Exception { if (isFailureIteration) { double rank = pageWithRank.getRank(); if (isFailingWorker) { pageWithRank.setRank(uniformRank); } else { pageWithRank.setRank(rank * rescaleFactor); } } out.collect(pageWithRank); } }
41.144737
154
0.731692
0095e75d5f9f0b9944889b603ab700dfc10edb4b
372
package demo; public class Main { public static void main(String[] args) { Student student = new Student("Pesho", 15); student.getGrades().add(5.5); student.getGrades().add(6d); student.getGrades().add(4.5); System.out.println(student.getGrades().stream().mapToDouble(g -> g).average().getAsDouble()); } }
24.8
102
0.58871
a096941183c85f95ff426881fc6d15e1c052484f
397
package steps; import cucumber.api.PendingException; import cucumber.api.java8.En; /** * Created by petrash on 1/24/18. */ public class Java8VersionStep implements En { public Java8VersionStep() { And("^I just wanjt to see how step looks for Cucumber-Java(\\d+)$", (Integer arg0) -> { System.out.println("The value from new step class is " + arg0); }); } }
24.8125
95
0.644836
06c956559685ba850771e7e1fb06dd913e781bfb
3,729
package io.recode.decompile; import io.recode.classfile.Method; import io.recode.model.Expression; import io.recode.model.ModelFactory; import io.recode.util.Sequence; import io.recode.model.Statement; import io.recode.util.Stack; import java.lang.reflect.Type; import java.util.List; public interface DecompilationContext { int getStartPC(); ProgramCounter getProgramCounter(); LineNumberCounter getLineNumberCounter(); Decompiler getDecompiler(); Method getMethod(); Type resolveType(String internalName); int getStackSize(); boolean isStackCompliantWithComputationalCategories(int... computationalCategories); Stack<Expression> getStack(); /** * Returns the expressions currently available on the stack. The last pushed element will be the last element * in the list. * * @return A list of the currently stacked expressions. */ List<Expression> getStackedExpressions(); /** * Reduces the stack, i.e. pops the stack and puts the stacked statement on in the * statement list. The element on the stack must be a valid statement. * * @return Whether or not any element was reduced. * @throws java.lang.IllegalStateException Thrown if there's no expression on the stack * or the stacked expression is not a valid statement. */ boolean reduce() throws IllegalStateException; /** * Reduces the stack until empty. All elements must be statements. * * @return Whether or not any element was reduced. * @throws IllegalStateException Thrown if any element is not a statement. */ boolean reduceAll() throws IllegalStateException; /** * Called by the decompiler when a statements has been reduced and needs to be enlisted. * This will add the statement to the statement list. * * @param statement The statement that should be enlisted. */ void enlist(Statement statement); /** * Pushes an expression onto the stack. * * @param expression The expression that should be pushed onto the stack. */ void push(Expression expression); /** * Inserts a value into the stack. Used by e.g. dup_x1 that inserts a value beneath the top of * the stack. * * @param offset The offset from the top (0=top, -1=beneath top etc). * @param expression The expression that should be inserted. */ void insert(int offset, Expression expression); /** * Pops an expression from the stack. If there's no expression available no the stack, * an <code>IllegalStateException</code> will be thrown. * * @return The popped statement. * @throws java.lang.IllegalStateException Thrown if there's no expression on the stack. */ Expression pop() throws IllegalStateException; Expression peek() throws IllegalStateException; /** * The statements that have been enlisted thus far in the context. * * @return The enlisted statements. */ Sequence<Statement> getStatements(); boolean hasStackedExpressions(); void removeStatement(int index); /** * Aborts the decompilation. The decompiler will attempt to complete the decompilation by reducing the * stack and returning completed decompilation. */ void abort(); /** * Returns whether or not decompilation has been aborted. If so, the decompiler should not proceed * with reading any more byte codes, but rather abort immediately and attempt to reduce the stack. * * @return Whether or not the decompilation has been aborted. */ boolean isAborted(); ModelFactory getModelFactory(); }
30.818182
113
0.685438
4f4597683d4319c03bc6b91d395fcc39f4d2ab7a
1,382
package com.pwc.logging; import com.pwc.logging.service.LoggerService; import org.junit.Test; public class ButTest extends LoggerBaseTest { @Test public void butBlankTest() { LoggerService.BUT(""); verifyLogOutput("But"); } @Test public void butNullTest() { LoggerService.BUT(null); verifyLogOutput("But null"); } @Test public void butNullArgTest() { LoggerService.BUT("Login Test for user=%s but password=%s", null); verifyLogOutput("But Login Test for user=null but password=null"); } @Test public void butMismatchArgTest() { LoggerService.BUT("Login Test for user=%s but password=%s", "foobar"); verifyLogOutput("But Login Test for user= but password=foobar"); } @Test public void butTooManyArgTest() { LoggerService.BUT("Login Test for user=%s but password=%s", "foobar", "password", true); verifyLogOutput("But Login Test for user=foobar but password="); } @Test public void butWithArgsTest() { LoggerService.BUT("Login Test for user=%s but password=%s", "anthony", "foobar"); verifyLogOutput("But Login Test for user=anthony but password=foobar"); } @Test public void butTest() { LoggerService.BUT("Login Test for user"); verifyLogOutput("But Login Test for user"); } }
27.098039
96
0.639653
0d0f5dcac857e2e5fdd1648e74992282c36e7292
8,073
package financial; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Portfolio { private Double mTotalFunds; // 投资资金总规模(单位:万元) private Double mCashLowerLimit; // 空仓规模下限(单位:万元) private Double mTotalPosition; // 实际仓位总金额(单位:万元) private Double mTotalFees; // 管理费用总金额(单位:万元) private Double mTotalCash; // 空仓规模(单位:万元) private Double mTotalEarning; // 投资组合预期回报(单位:万元) private Double mTotalEAR; // 投资组合预期年化收益率(单位:%) private Double mTotalPrivateFund; // 私募基金类产品投入金额(单位:万元) private Double mTotalPublicFund; // 公募基金类产品投入金额(单位:万元) private Double mTotalFixedIncome; // 固定收益类产品投入金额(单位:万元) private Double mTotalCommodity; // 大宗商品类产品投入金额(单位:万元) private Double mTotalCurrency; // 货币类产品投入金额(单位:万元) private Double mTotalOther; // 另类产品投入金额(单位:万元) // private List<InstrumentFinancial> mAllAssets; // 投资产品列表 private Map<String, InstrumentFinancial> mAssetMap; // 投资产品检索 public Portfolio(double inTotalFunds, double inCashLowerLimit) { this.mTotalFunds = inTotalFunds; this.mCashLowerLimit = inCashLowerLimit; this.mTotalPosition = 0.00; this.mTotalFees = 0.00; this.mTotalEarning = 0.00; this.mTotalPrivateFund = 0.00; this.mTotalPublicFund = 0.00; this.mTotalFixedIncome = 0.00; this.mTotalCommodity = 0.00; this.mTotalCurrency = 0.00; this.mTotalOther = 0.00; // this.mAllAssets = new ArrayList<InstrumentFinancial>(); this.mAssetMap = new HashMap<String, InstrumentFinancial>(); this.updateMemebrs(); } private void updateMemebrs() { this.updateTotalCash(); this.updateTotalEAR(); } private void updateTotalCash() { // 空仓规模 = 投入规模 - 持仓规模 - 管理费用 this.mTotalCash = mTotalFunds - mTotalPosition - mTotalFees; } private void updateTotalEAR() { if (mTotalFunds == (double)0) { this.mTotalEAR = 0.00; } else { // 组合年化收益率 = (持仓规模 + 空仓规模 + 组合预期回报)/(投入本金)- 1 this.mTotalEAR = ((mTotalPosition + mTotalCash + mTotalEarning) / mTotalFunds - 1) * 100.00; } } public void setTotalFunds(double inTotalFunds) { this.mTotalFunds = inTotalFunds; this.updateMemebrs(); } public void setCashLowerLimit(double inCashLowerLimit) { this.mCashLowerLimit = inCashLowerLimit; this.updateMemebrs(); } public boolean add(InstrumentFinancial newAsset) { // this.mAllAssets.add(newAsset); if (mAssetMap.containsKey(newAsset.getCode())) { return false; } this.mAssetMap.put(newAsset.getCode(), newAsset); this.mTotalPosition += newAsset.getPosition(); this.mTotalFees += newAsset.getFee(); this.mTotalEarning += newAsset.getEarning(); this.updateMemebrs(); if (newAsset instanceof PrivateFund) { this.mTotalPrivateFund += newAsset.getTotal(); } else if (newAsset instanceof PublicFund) { this.mTotalPublicFund += newAsset.getTotal(); } else if (newAsset instanceof FixedIncome) { this.mTotalFixedIncome += newAsset.getTotal(); } else if (newAsset instanceof Commodity) { this.mTotalCommodity += newAsset.getTotal(); } else if (newAsset instanceof Currency) { this.mTotalCurrency += newAsset.getTotal(); } else if (newAsset instanceof Other) { this.mTotalOther += newAsset.getTotal(); } return true; } public boolean remove(String inCode) { InstrumentFinancial oldAsset = mAssetMap.remove(inCode); if (oldAsset == null) { return false; } this.mTotalPosition -= oldAsset.getPosition(); this.mTotalFees -= oldAsset.getFee(); this.mTotalEarning -= oldAsset.getEarning(); this.updateMemebrs(); if (oldAsset instanceof PrivateFund) { this.mTotalPrivateFund -= oldAsset.getTotal(); } else if (oldAsset instanceof PublicFund) { this.mTotalPublicFund -= oldAsset.getTotal(); } else if (oldAsset instanceof FixedIncome) { this.mTotalFixedIncome -= oldAsset.getTotal(); } else if (oldAsset instanceof Commodity) { this.mTotalCommodity -= oldAsset.getTotal(); } else if (oldAsset instanceof Currency) { this.mTotalCurrency -= oldAsset.getTotal(); } else if (oldAsset instanceof Other) { this.mTotalOther -= oldAsset.getTotal(); } return true; } // public boolean remove(int index) { // InstrumentFinancial oldAsset = mAllAssets.remove(index); // this.mTotalPosition -= oldAsset.getPosition(); // this.mTotalFees -= oldAsset.getFee(); // this.mTotalEarning -= oldAsset.getEarning(); // this.updateMemebrs(); // if (oldAsset instanceof PrivateFund) { // this.mTotalPrivateFund -= oldAsset.getTotal(); // } // else if (oldAsset instanceof PublicFund) { // this.mTotalPublicFund -= oldAsset.getTotal(); // } // else if (oldAsset instanceof FixedIncome) { // this.mTotalFixedIncome -= oldAsset.getTotal(); // } // else if (oldAsset instanceof Commodity) { // this.mTotalCommodity -= oldAsset.getTotal(); // } // else if (oldAsset instanceof Currency) { // this.mTotalCurrency -= oldAsset.getTotal(); // } // else if (oldAsset instanceof Other) { // this.mTotalOther -= oldAsset.getTotal(); // } // return true; // } // public boolean remove(InstrumentFinancial oldAsset) { // if (this.mAllAssets.remove(oldAsset)) { // this.mTotalPosition -= oldAsset.getPosition(); // this.mTotalFees -= oldAsset.getFee(); // this.mTotalEarning -= oldAsset.getEarning(); // this.updateMemebrs(); // if (oldAsset instanceof PrivateFund) { // this.mTotalPrivateFund -= oldAsset.getTotal(); // } // else if (oldAsset instanceof PublicFund) { // this.mTotalPublicFund -= oldAsset.getTotal(); // } // else if (oldAsset instanceof FixedIncome) { // this.mTotalFixedIncome -= oldAsset.getTotal(); // } // else if (oldAsset instanceof Commodity) { // this.mTotalCommodity -= oldAsset.getTotal(); // } // else if (oldAsset instanceof Currency) { // this.mTotalCurrency -= oldAsset.getTotal(); // } // else if (oldAsset instanceof Other) { // this.mTotalOther -= oldAsset.getTotal(); // } // return true; // } // return false; // } public void removeAll() { this.mTotalPosition = 0.00; this.mTotalFees = 0.00; this.mTotalEarning = 0.00; // this.mAllAssets.clear(); this.mAssetMap.clear(); this.updateMemebrs(); } public double getTotalFunds() { return mTotalFunds; } public double getCashLowerLimit() { return mCashLowerLimit; } public double getTotalPosition() { return mTotalPosition; } public double getTotalFees() { return mTotalFees; } public double getTotalCash() { return mTotalCash; } public double getTotalEAR() { return mTotalEAR; } public double getPrivateFundPercentage() { if (mTotalPosition + mTotalFees == 0) { return 0.00; } else { double percentage = mTotalPrivateFund / (mTotalPosition + mTotalFees); return percentage * 100.00; } } public double getPublicFundPercentage() { if (mTotalPosition + mTotalFees == 0) { return 0.00; } else { double percentage = mTotalPublicFund / (mTotalPosition + mTotalFees); return percentage * 100.00; } } public double getFixedIncomePercentage() { if (mTotalPosition + mTotalFees == 0) { return 0.00; } else { double percentage = mTotalFixedIncome / (mTotalPosition + mTotalFees) ; return percentage * 100.00; } } public double getCommodityPercentage() { if (mTotalPosition + mTotalFees == 0) { return 0.00; } else { double percentage = mTotalCommodity / (mTotalPosition + mTotalFees); return percentage * 100.00; } } public double getCurrencyPercentage() { if (mTotalPosition + mTotalFees == 0) { return 0.00; } else { double percentage = mTotalCurrency / (mTotalPosition + mTotalFees); return percentage * 100.00; } } public double getOtherPercentage() { if (mTotalPosition + mTotalFees == 0) { return 0.00; } else { double percentage = mTotalOther / (mTotalPosition + mTotalFees); return percentage * 100.00; } } // public List<InstrumentFinancial> getAllAssets() { // return mAllAssets; // } public Map<String, InstrumentFinancial> getAssetMap() { return mAssetMap; } }
27.742268
95
0.690821
8fa97bcb622fe6201680f13184166ea1c241e646
898
package io.github.toquery.framework.front.connfig; import io.github.toquery.framework.core.security.AppSecurityConfigurer; import io.github.toquery.framework.core.security.AppSecurityIgnoring; import lombok.extern.slf4j.Slf4j; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; @Slf4j public class AppFrontSecurityConfig implements AppSecurityConfigurer, AppSecurityIgnoring { public AppFrontSecurityConfig() { log.info("AppFrontSecurityConfig"); } public String[] ignoring() { return new String[]{"/manifest.webapp", "/index.html", "/static/**"}; } @Override public void configure(HttpSecurity http) throws Exception { } @Override public void configure(WebSecurity web) { web.ignoring().antMatchers(ignoring()); } }
29.933333
91
0.750557
0d48fa1ca7c823bcecd970e161ce627af6e35f44
1,255
package si.vilfa.junglechronicles.Utils; import com.badlogic.gdx.physics.box2d.Body; import si.vilfa.junglechronicles.Component.GameComponent; import si.vilfa.junglechronicles.Component.Loggable; import java.lang.reflect.InvocationTargetException; /** * @author luka * @date 27/11/2021 * @package si.vilfa.junglechronicles.Utils **/ public class GameObjectFactory implements Loggable { private static GameObjectFactory INSTANCE; private GameObjectFactory() { } public static GameObjectFactory getInstance() { if (INSTANCE == null) { INSTANCE = new GameObjectFactory(); } return INSTANCE; } public <T extends GameComponent, U> T createWithBody(Body body, Class<T> objectType, Class<U> ctorParamType) { T gameObject = null; try { gameObject = objectType.getDeclaredConstructor(ctorParamType).newInstance(body); } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) { error(e.getMessage(), e); } return gameObject; } }
27.888889
119
0.61992
fc1b91a073359144dad4a973172b8bc31e825140
1,387
/** * Copyright © 2021 Yusuf Aytas. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.yusufaytas.leetcode; import java.util.Arrays; /* Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Example 2: Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4 Note: You may assume k is always valid, 1 ≤ k ≤ array's length. */ public class KthLargestElement { public static void main(String[] args) { final int[] nums = {3, 2, 1, 5, 6, 4}; System.out.println(new KthLargestElement().findKthLargest(nums, 2)); } public int findKthLargest(int[] nums, int k) { if (nums == null || nums.length == 0) { return -1; } Arrays.sort(nums); return nums[nums.length - k]; } }
25.685185
90
0.687815
2e12e4c40bab0d119e50dae348b6557469f08832
136
package quarter01.level01.lesson08; public class Main { public static void main(String[] args) { new GameWindow(); } }
17
44
0.654412
9b2b3df51f229993ced286d75b7ed78ec385c3f7
777
package jpl.ch03.ex01; import static org.junit.Assert.*; import org.junit.Test; public class PassengerVehicleTest { @Test public void testPassengerVehicle_1() { PassengerVehicle obj = new PassengerVehicle(); obj.setPassengers(1); assertEquals(1, obj.getPassengers()); } @Test public void testPassengerVehicle_2() { PassengerVehicle obj = new PassengerVehicle(); obj.setPassengers(2); assertEquals(2, obj.getPassengers()); } @Test public void testPassengerVehicle_4() { PassengerVehicle obj = new PassengerVehicle(); obj.setPassengers(4); assertEquals(4, obj.getPassengers()); } @Test public void testPassengerVehicle_5() { PassengerVehicle obj = new PassengerVehicle(); obj.setPassengers(5); assertEquals(4, obj.getPassengers()); } }
21
48
0.737452
f268b25fe106d88bbb9e60ce76160ccbfe887e25
525
package iot.technology.coap; import org.eclipse.californium.core.CoapResource; import org.eclipse.californium.core.server.resources.CoapExchange; import static org.eclipse.californium.core.coap.CoAP.ResponseCode.DELETED; /** * @author james mu * @date 2020/5/9 09:38 */ public class RemovableResource extends CoapResource { public RemovableResource() { super("remove"); } @Override public void handleDELETE(CoapExchange exchange) { delete(); exchange.respond(DELETED); } }
21.875
74
0.714286
8e6eda7f772c44e56a1f0ac112e053d90ce9efad
2,210
/* * Copyright 2017 Department of Biomedical Informatics, University of Utah * <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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 edu.utah.bmi.nlp.compiler; import org.apache.commons.io.FileUtils; import javax.tools.SimpleJavaFileObject; import java.io.*; import java.util.Map; import static edu.utah.bmi.nlp.compiler.MemoryJavaFileManager.toURI; /** * Created by u0876964 on 11/3/16. */ public class ClassOutputBuffer extends SimpleJavaFileObject { private String name; private Map<String, byte[]> classBytes; private File rootDir; ClassOutputBuffer(String name, Map<String, byte[]> classBytes, File rootDir) { super(toURI(name), Kind.CLASS); this.name = name; this.classBytes = classBytes; this.rootDir = rootDir; } public OutputStream openOutputStream() { return new FilterOutputStream(new ByteArrayOutputStream()) { public void close() throws IOException { out.close(); ByteArrayOutputStream bos = (ByteArrayOutputStream) out; classBytes.put(name, bos.toByteArray()); if (rootDir != null) { File outputFile = new File(rootDir, name.replace(".", "/") + ".class"); if (!outputFile.getParentFile().exists()) FileUtils.forceMkdir(outputFile.getParentFile()); FileOutputStream outputStream = new FileOutputStream(outputFile); bos.writeTo(outputStream); outputStream.close(); } } }; } public Map<String, byte[]> getClassBytes() { return classBytes; } }
34
91
0.645249
a80d6339aeb5e35c64dc05218e8cab55564f589e
114
package com.nattguld.util.chrono; /** * * @author randqm * */ public enum Clock { HOUR_12, HOUR_24; }
7.6
33
0.605263
42db07acf3ee8a630515fc7794837d18dc5694be
2,546
/** * Copyright 2013 Netflix, 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.netflix.suro; import com.google.common.base.Throwables; import com.google.inject.Inject; import com.google.inject.Singleton; import com.netflix.suro.input.InputManager; import com.netflix.suro.input.thrift.MessageSetProcessor; import com.netflix.suro.server.StatusServer; import com.netflix.suro.input.thrift.ThriftServer; import com.netflix.suro.sink.SinkManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; /** * Main service for suro to control all subsystems including * {@link StatusServer}, {@link ThriftServer}, {@link MessageSetProcessor}, and * {@link SinkManager} * * @author elandau */ @Singleton public class SuroService { static Logger log = LoggerFactory.getLogger(SuroServer.class); private final StatusServer statusServer; private final InputManager inputManager; private final SinkManager sinkManager; @Inject private SuroService(StatusServer statusServer, InputManager inputManager, SinkManager sinkManager) { this.statusServer = statusServer; this.inputManager = inputManager; this.sinkManager = sinkManager; } @PostConstruct public void start() { try { statusServer.start(); sinkManager.initialStart(); inputManager.initialStart(); } catch (Exception e) { log.error("Exception while starting up server: " + e.getMessage(), e); Throwables.propagate(e); } } @PreDestroy public void shutdown() { try { inputManager.shutdown(); statusServer.shutdown(); sinkManager .shutdown(); } catch (Exception e) { //ignore every exception while shutting down but loggign should be done for debugging log.error("Exception while shutting down SuroServer: " + e.getMessage(), e); } } }
32.227848
104
0.698743
146a50a287f9e958379565520c5ee7a58b9a97b8
25,750
/* * Copyright 2017-present Facebook, 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.facebook.buck.jvm.java; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.jvm.common.ResourceValidator; import com.facebook.buck.jvm.core.HasJavaAbi; import com.facebook.buck.jvm.java.JavaBuckConfig.SourceAbiVerificationMode; import com.facebook.buck.jvm.java.JavaBuckConfig.UnusedDependenciesAction; import com.facebook.buck.jvm.java.JavaLibraryDescription.CoreArg; import com.facebook.buck.jvm.java.abi.AbiGenerationMode; import com.facebook.buck.jvm.java.abi.source.api.SourceOnlyAbiRuleInfo; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.rules.BuildDeps; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.CellPathResolver; import com.facebook.buck.rules.DefaultSourcePathResolver; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.SourcePathRuleFinder; import com.facebook.buck.toolchain.ToolchainProvider; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedSet; import java.nio.file.Path; import java.util.Optional; import java.util.SortedSet; import java.util.function.Supplier; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.immutables.value.Value; @Value.Immutable @Value.Style( overshadowImplementation = true, init = "set*", visibility = Value.Style.ImplementationVisibility.PACKAGE ) public abstract class DefaultJavaLibraryRules { public interface DefaultJavaLibraryConstructor { DefaultJavaLibrary newInstance( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildDeps buildDeps, SourcePathResolver resolver, JarBuildStepsFactory jarBuildStepsFactory, Optional<SourcePath> proguardConfig, SortedSet<BuildRule> firstOrderPackageableDeps, ImmutableSortedSet<BuildRule> fullJarExportedDeps, ImmutableSortedSet<BuildRule> fullJarProvidedDeps, ImmutableSortedSet<BuildRule> fullJarExportedProvidedDeps, @Nullable BuildTarget abiJar, @Nullable BuildTarget sourceOnlyAbiJar, Optional<String> mavenCoords, ImmutableSortedSet<BuildTarget> tests, boolean requiredForSourceOnlyAbi, UnusedDependenciesAction unusedDependenciesAction, Optional<UnusedDependenciesFinderFactory> unusedDependenciesFinderFactory); } @org.immutables.builder.Builder.Parameter abstract BuildTarget getInitialBuildTarget(); @Value.Lazy BuildTarget getLibraryTarget() { BuildTarget initialBuildTarget = getInitialBuildTarget(); return HasJavaAbi.isLibraryTarget(initialBuildTarget) ? initialBuildTarget : HasJavaAbi.getLibraryTarget(initialBuildTarget); } @org.immutables.builder.Builder.Parameter abstract ProjectFilesystem getProjectFilesystem(); @org.immutables.builder.Builder.Parameter abstract ToolchainProvider getToolchainProvider(); @org.immutables.builder.Builder.Parameter abstract BuildRuleParams getInitialParams(); @org.immutables.builder.Builder.Parameter abstract BuildRuleResolver getBuildRuleResolver(); @org.immutables.builder.Builder.Parameter abstract CellPathResolver getCellPathResolver(); @Value.Lazy SourcePathRuleFinder getSourcePathRuleFinder() { return new SourcePathRuleFinder(getBuildRuleResolver()); } @Value.Lazy SourcePathResolver getSourcePathResolver() { return DefaultSourcePathResolver.from(getSourcePathRuleFinder()); } @org.immutables.builder.Builder.Parameter abstract ConfiguredCompilerFactory getConfiguredCompilerFactory(); @org.immutables.builder.Builder.Parameter abstract UnusedDependenciesAction getUnusedDependenciesAction(); @org.immutables.builder.Builder.Parameter @Nullable abstract JavaBuckConfig getJavaBuckConfig(); @Value.Default DefaultJavaLibraryConstructor getConstructor() { return DefaultJavaLibrary::new; } @Value.NaturalOrder abstract ImmutableSortedSet<SourcePath> getSrcs(); @Value.NaturalOrder abstract ImmutableSortedSet<SourcePath> getResources(); @Value.Check void validateResources() { ResourceValidator.validateResources( getSourcePathResolver(), getProjectFilesystem(), getResources()); } abstract Optional<SourcePath> getProguardConfig(); abstract ImmutableList<String> getPostprocessClassesCommands(); abstract Optional<Path> getResourcesRoot(); abstract Optional<SourcePath> getManifestFile(); abstract Optional<String> getMavenCoords(); @Value.NaturalOrder abstract ImmutableSortedSet<BuildTarget> getTests(); @Value.Default RemoveClassesPatternsMatcher getClassesToRemoveFromJar() { return RemoveClassesPatternsMatcher.EMPTY; } @Value.Default boolean getSourceOnlyAbisAllowed() { return true; } abstract JavacOptions getJavacOptions(); @Nullable abstract JavaLibraryDeps getDeps(); @org.immutables.builder.Builder.Parameter @Nullable abstract JavaLibraryDescription.CoreArg getArgs(); public DefaultJavaLibrary buildLibrary() { buildAllRules(); return (DefaultJavaLibrary) getBuildRuleResolver().getRule(getLibraryTarget()); } public BuildRule buildAbi() { buildAllRules(); return getBuildRuleResolver().getRule(getInitialBuildTarget()); } private void buildAllRules() { // To guarantee that all rules in a source-ABI pipeline are working off of the same settings, // we want to create them all from the same instance of this builder. To ensure this, we force // a request for whichever rule is closest to the root of the graph (regardless of which rule // was actually requested) and then create all of the rules inside that request. We're // requesting the rootmost rule because the rules are created from leafmost to rootmost and // we want any requests to block until all of the rules are built. BuildTarget rootmostTarget = getLibraryTarget(); if (willProduceCompareAbis()) { rootmostTarget = HasJavaAbi.getVerifiedSourceAbiJar(rootmostTarget); } else if (willProduceClassAbi()) { rootmostTarget = HasJavaAbi.getClassAbiJar(rootmostTarget); } BuildRuleResolver buildRuleResolver = getBuildRuleResolver(); buildRuleResolver.computeIfAbsent( rootmostTarget, target -> { CalculateSourceAbi sourceOnlyAbiRule = buildSourceOnlyAbiRule(); CalculateSourceAbi sourceAbiRule = buildSourceAbiRule(); DefaultJavaLibrary libraryRule = buildLibraryRule(sourceAbiRule); CalculateClassAbi classAbiRule = buildClassAbiRule(libraryRule); CompareAbis compareAbisRule; if (sourceOnlyAbiRule != null) { compareAbisRule = buildCompareAbisRule(sourceAbiRule, sourceOnlyAbiRule); } else { compareAbisRule = buildCompareAbisRule(classAbiRule, sourceAbiRule); } if (HasJavaAbi.isLibraryTarget(target)) { return libraryRule; } else if (HasJavaAbi.isClassAbiTarget(target)) { return classAbiRule; } else if (HasJavaAbi.isVerifiedSourceAbiTarget(target)) { return compareAbisRule; } throw new AssertionError(); }); } @Nullable private <T extends BuildRule & CalculateAbi, U extends BuildRule & CalculateAbi> CompareAbis buildCompareAbisRule(@Nullable T correctAbi, @Nullable U experimentalAbi) { if (!willProduceCompareAbis()) { return null; } Preconditions.checkNotNull(correctAbi); Preconditions.checkNotNull(experimentalAbi); BuildTarget compareAbisTarget = HasJavaAbi.getVerifiedSourceAbiJar(getLibraryTarget()); return getBuildRuleResolver() .addToIndex( new CompareAbis( compareAbisTarget, getProjectFilesystem(), getInitialParams() .withDeclaredDeps(ImmutableSortedSet.of(correctAbi, experimentalAbi)) .withoutExtraDeps(), getSourcePathResolver(), correctAbi.getSourcePathToOutput(), experimentalAbi.getSourcePathToOutput(), Preconditions.checkNotNull(getJavaBuckConfig()).getSourceAbiVerificationMode())); } @Value.Lazy @Nullable BuildTarget getAbiJar() { if (willProduceCompareAbis()) { return HasJavaAbi.getVerifiedSourceAbiJar(getLibraryTarget()); } else if (willProduceSourceAbi()) { return HasJavaAbi.getSourceAbiJar(getLibraryTarget()); } else if (willProduceClassAbi()) { return HasJavaAbi.getClassAbiJar(getLibraryTarget()); } return null; } @Value.Lazy @Nullable BuildTarget getSourceOnlyAbiJar() { if (willProduceSourceOnlyAbi()) { return HasJavaAbi.getSourceOnlyAbiJar(getLibraryTarget()); } return null; } private boolean willProduceAbiJar() { return !getSrcs().isEmpty() || !getResources().isEmpty() || getManifestFile().isPresent(); } @Value.Lazy AbiGenerationMode getAbiGenerationMode() { AbiGenerationMode result = null; CoreArg args = getArgs(); if (args != null) { result = args.getAbiGenerationMode().orElse(null); } if (result == null) { result = Preconditions.checkNotNull(getJavaBuckConfig()).getAbiGenerationMode(); } if (result == AbiGenerationMode.CLASS) { return result; } if (!shouldBuildSourceAbi()) { return AbiGenerationMode.CLASS; } if (result != AbiGenerationMode.SOURCE && (!getSourceOnlyAbisAllowed() || !pluginsSupportSourceOnlyAbis())) { return AbiGenerationMode.SOURCE; } if (result == AbiGenerationMode.MIGRATING_TO_SOURCE_ONLY && !getConfiguredCompilerFactory().shouldMigrateToSourceOnlyAbi()) { return AbiGenerationMode.SOURCE; } if (result == AbiGenerationMode.SOURCE_ONLY && !getConfiguredCompilerFactory().shouldGenerateSourceOnlyAbi()) { return AbiGenerationMode.SOURCE; } return result; } @Value.Lazy SourceAbiVerificationMode getSourceAbiVerificationMode() { JavaBuckConfig javaBuckConfig = getJavaBuckConfig(); CoreArg args = getArgs(); SourceAbiVerificationMode result = null; if (args != null) { result = args.getSourceAbiVerificationMode().orElse(null); } if (result == null) { result = javaBuckConfig != null ? javaBuckConfig.getSourceAbiVerificationMode() : SourceAbiVerificationMode.OFF; } return result; } private boolean willProduceSourceAbi() { return willProduceAbiJar() && getAbiGenerationMode().isSourceAbi(); } private boolean willProduceSourceOnlyAbi() { return willProduceSourceAbi() && !getAbiGenerationMode().usesDependencies(); } private boolean willProduceClassAbi() { return willProduceAbiJar() && (!willProduceSourceAbi() || willProduceCompareAbis()); } private boolean willProduceCompareAbis() { return willProduceSourceAbi() && getSourceAbiVerificationMode() != JavaBuckConfig.SourceAbiVerificationMode.OFF; } private boolean shouldBuildSourceAbi() { return getConfiguredCompilerFactory().shouldGenerateSourceAbi() && !getSrcs().isEmpty() && getPostprocessClassesCommands().isEmpty(); } private boolean pluginsSupportSourceOnlyAbis() { ImmutableList<ResolvedJavacPluginProperties> annotationProcessors = Preconditions.checkNotNull(getJavacOptions()) .getAnnotationProcessingParams() .getAnnotationProcessors(getProjectFilesystem(), getSourcePathResolver()); for (ResolvedJavacPluginProperties annotationProcessor : annotationProcessors) { if (!annotationProcessor.getDoesNotAffectAbi() && !annotationProcessor.getSupportAbiGenerationFromSource()) { // Processor is ABI-affecting but cannot run during ABI generation from source; disallow return false; } } return true; } private DefaultJavaLibrary buildLibraryRule(@Nullable CalculateSourceAbi sourceAbiRule) { BuildDeps buildDeps = getFinalBuildDeps(); if (sourceAbiRule != null) { buildDeps = new BuildDeps(buildDeps, ImmutableSortedSet.of(sourceAbiRule)); } DefaultJavaLibraryClasspaths classpaths = getClasspaths(); UnusedDependenciesAction unusedDependenciesAction = getUnusedDependenciesAction(); Optional<UnusedDependenciesFinderFactory> unusedDependenciesFinderFactory = Optional.empty(); if (unusedDependenciesAction != UnusedDependenciesAction.IGNORE) { ProjectFilesystem projectFilesystem = getProjectFilesystem(); BuildTarget buildTarget = getLibraryTarget(); SourcePathResolver sourcePathResolver = getSourcePathResolver(); BuildRuleResolver buildRuleResolver = getBuildRuleResolver(); unusedDependenciesFinderFactory = Optional.of( () -> UnusedDependenciesFinder.of( buildTarget, projectFilesystem, buildRuleResolver, getCellPathResolver(), CompilerParameters.getDepFilePath(buildTarget, projectFilesystem), Preconditions.checkNotNull(getDeps()), sourcePathResolver, unusedDependenciesAction)); } DefaultJavaLibrary libraryRule = getConstructor() .newInstance( getLibraryTarget(), getProjectFilesystem(), buildDeps, getSourcePathResolver(), getJarBuildStepsFactory(), getProguardConfig(), classpaths.getFirstOrderPackageableDeps(), Preconditions.checkNotNull(getDeps()).getExportedDeps(), Preconditions.checkNotNull(getDeps()).getProvidedDeps(), Preconditions.checkNotNull(getDeps()).getExportedProvidedDeps(), getAbiJar(), getSourceOnlyAbiJar(), getMavenCoords(), getTests(), getRequiredForSourceOnlyAbi(), unusedDependenciesAction, unusedDependenciesFinderFactory); if (sourceAbiRule != null) { libraryRule.setSourceAbi(sourceAbiRule); } getBuildRuleResolver().addToIndex(libraryRule); return libraryRule; } private boolean getRequiredForSourceOnlyAbi() { return getArgs() != null && getArgs().getRequiredForSourceOnlyAbi(); } @Value.Lazy Supplier<SourceOnlyAbiRuleInfo> getSourceOnlyAbiRuleInfoSupplier() { return () -> new DefaultSourceOnlyAbiRuleInfo( getSourcePathRuleFinder(), getLibraryTarget(), getRequiredForSourceOnlyAbi(), getClasspaths(), getClasspathsForSourceOnlyAbi()); } @Nullable private CalculateSourceAbi buildSourceOnlyAbiRule() { if (!willProduceSourceOnlyAbi()) { return null; } BuildDeps buildDeps = getFinalBuildDepsForSourceOnlyAbi(); JarBuildStepsFactory jarBuildStepsFactory = getJarBuildStepsFactoryForSourceOnlyAbi(); BuildTarget sourceAbiTarget = HasJavaAbi.getSourceOnlyAbiJar(getLibraryTarget()); return getBuildRuleResolver() .addToIndex( new CalculateSourceAbi( sourceAbiTarget, getProjectFilesystem(), buildDeps, getSourcePathRuleFinder(), jarBuildStepsFactory)); } @Nullable private CalculateSourceAbi buildSourceAbiRule() { if (!willProduceSourceAbi()) { return null; } BuildDeps buildDeps = getFinalBuildDeps(); JarBuildStepsFactory jarBuildStepsFactory = getJarBuildStepsFactory(); BuildTarget sourceAbiTarget = HasJavaAbi.getSourceAbiJar(getLibraryTarget()); return getBuildRuleResolver() .addToIndex( new CalculateSourceAbi( sourceAbiTarget, getProjectFilesystem(), buildDeps, getSourcePathRuleFinder(), jarBuildStepsFactory)); } @Nullable private CalculateClassAbi buildClassAbiRule(DefaultJavaLibrary libraryRule) { if (!willProduceClassAbi()) { return null; } BuildTarget classAbiTarget = HasJavaAbi.getClassAbiJar(getLibraryTarget()); return getBuildRuleResolver() .addToIndex( CalculateClassAbi.of( classAbiTarget, getSourcePathRuleFinder(), getProjectFilesystem(), getInitialParams(), libraryRule.getSourcePathToOutput(), getAbiCompatibilityMode())); } @Value.Lazy AbiGenerationMode getAbiCompatibilityMode() { return getJavaBuckConfig() == null || getJavaBuckConfig().getSourceAbiVerificationMode() == SourceAbiVerificationMode.OFF ? AbiGenerationMode.CLASS // Use the BuckConfig version (rather than the inferred one) because if any // targets are using source_only it can affect the output of other targets // in ways that are hard to simulate : getJavaBuckConfig().getAbiGenerationMode(); } @Value.Lazy DefaultJavaLibraryClasspaths getClasspaths() { return DefaultJavaLibraryClasspaths.builder(getBuildRuleResolver()) .setBuildRuleParams(getInitialParams()) .setConfiguredCompiler(getConfiguredCompiler()) .setDeps(Preconditions.checkNotNull(getDeps())) .setCompileAgainstLibraryType(getCompileAgainstLibraryType()) .build(); } @Value.Lazy DefaultJavaLibraryClasspaths getClasspathsForSourceOnlyAbi() { return DefaultJavaLibraryClasspaths.builder() .from(getClasspaths()) .setShouldCreateSourceOnlyAbi(true) .build(); } @Value.Lazy ConfiguredCompiler getConfiguredCompiler() { return getConfiguredCompilerFactory() .configure( getSourcePathResolver(), getSourcePathRuleFinder(), getProjectFilesystem(), getArgs(), getJavacOptions(), getBuildRuleResolver(), getToolchainProvider()); } @Value.Lazy ConfiguredCompiler getConfiguredCompilerForSourceOnlyAbi() { return getConfiguredCompilerFactory() .configure( getSourcePathResolver(), getSourcePathRuleFinder(), getProjectFilesystem(), getArgs(), getJavacOptionsForSourceOnlyAbi(), getBuildRuleResolver(), getToolchainProvider()); } @Value.Lazy JavacOptions getJavacOptionsForSourceOnlyAbi() { JavacOptions javacOptions = getJavacOptions(); return javacOptions.withAnnotationProcessingParams( abiProcessorsOnly(javacOptions.getAnnotationProcessingParams())); } private AnnotationProcessingParams abiProcessorsOnly( AnnotationProcessingParams annotationProcessingParams) { Preconditions.checkArgument(annotationProcessingParams.getLegacyProcessors().isEmpty()); return AnnotationProcessingParams.builder() .from(annotationProcessingParams) .setModernProcessors( annotationProcessingParams .getModernProcessors() .stream() .filter(processor -> !processor.getDoesNotAffectAbi()) .collect(Collectors.toList())) .build(); } @Value.Lazy BuildDeps getFinalBuildDeps() { return buildBuildDeps(getClasspaths()); } @Value.Lazy BuildDeps getFinalBuildDepsForSourceOnlyAbi() { return buildBuildDeps(getClasspathsForSourceOnlyAbi()); } private BuildDeps buildBuildDeps(DefaultJavaLibraryClasspaths classpaths) { ImmutableSortedSet.Builder<BuildRule> depsBuilder = ImmutableSortedSet.naturalOrder(); depsBuilder // We always need the non-classpath deps, whether directly specified or specified via // query .addAll(classpaths.getNonClasspathDeps()) // It's up to the compiler to use an ABI jar for these deps if appropriate, so we can // add them unconditionally .addAll(getConfiguredCompiler().getBuildDeps(getSourcePathRuleFinder())) // We always need the ABI deps (at least for rulekey computation) // TODO(jkeljo): It's actually incorrect to use ABIs for rulekey computation for languages // that can't compile against them. Generally the reason they can't compile against ABIs // is that the ABI generation for that language isn't fully correct. .addAll(classpaths.getCompileTimeClasspathAbiDeps()); if (getCompileAgainstLibraryType() == CompileAgainstLibraryType.FULL) { depsBuilder.addAll(classpaths.getCompileTimeClasspathFullDeps()); } return new BuildDeps(depsBuilder.build()); } @Value.Lazy CompileAgainstLibraryType getCompileAgainstLibraryType() { CoreArg args = getArgs(); CompileAgainstLibraryType result = CompileAgainstLibraryType.SOURCE_ONLY_ABI; if (args != null) { result = args.getCompileAgainst().orElse(result); } if (!getConfiguredCompilerFactory().shouldCompileAgainstAbis()) { result = CompileAgainstLibraryType.FULL; } return result; } @Value.Lazy JarBuildStepsFactory getJarBuildStepsFactory() { DefaultJavaLibraryClasspaths classpaths = getClasspaths(); return new JarBuildStepsFactory( getProjectFilesystem(), getSourcePathRuleFinder(), getLibraryTarget(), getConfiguredCompiler(), getSrcs(), getResources(), getResourcesRoot(), getManifestFile(), getPostprocessClassesCommands(), classpaths.getAbiClasspath(), getConfiguredCompilerFactory().trackClassUsage(getJavacOptions()), classpaths.getCompileTimeClasspathSourcePaths(), getClassesToRemoveFromJar(), getAbiGenerationMode(), getAbiCompatibilityMode(), getSourceOnlyAbiRuleInfoSupplier()); } @Value.Lazy JarBuildStepsFactory getJarBuildStepsFactoryForSourceOnlyAbi() { DefaultJavaLibraryClasspaths classpaths = getClasspathsForSourceOnlyAbi(); return new JarBuildStepsFactory( getProjectFilesystem(), getSourcePathRuleFinder(), getLibraryTarget(), getConfiguredCompilerForSourceOnlyAbi(), getSrcs(), getResources(), getResourcesRoot(), getManifestFile(), getPostprocessClassesCommands(), classpaths.getAbiClasspath(), getConfiguredCompilerFactory().trackClassUsage(getJavacOptions()), classpaths.getCompileTimeClasspathSourcePaths(), getClassesToRemoveFromJar(), getAbiGenerationMode(), getAbiCompatibilityMode(), getSourceOnlyAbiRuleInfoSupplier()); } private static UnusedDependenciesAction getUnusedDependenciesAction( @Nullable JavaBuckConfig javaBuckConfig, @Nullable JavaLibraryDescription.CoreArg args) { if (args != null && args.getOnUnusedDependencies().isPresent()) { return args.getOnUnusedDependencies().get(); } if (javaBuckConfig == null) { return UnusedDependenciesAction.IGNORE; } return javaBuckConfig.getUnusedDependenciesAction(); } @org.immutables.builder.Builder.AccessibleFields public static class Builder extends ImmutableDefaultJavaLibraryRules.Builder { public Builder( BuildTarget initialBuildTarget, ProjectFilesystem projectFilesystem, ToolchainProvider toolchainProvider, BuildRuleParams initialParams, BuildRuleResolver buildRuleResolver, CellPathResolver cellPathResolver, ConfiguredCompilerFactory configuredCompilerFactory, @Nullable JavaBuckConfig javaBuckConfig, @Nullable JavaLibraryDescription.CoreArg args) { super( initialBuildTarget, projectFilesystem, toolchainProvider, initialParams, buildRuleResolver, cellPathResolver, configuredCompilerFactory, getUnusedDependenciesAction(javaBuckConfig, args), javaBuckConfig, args); this.buildRuleResolver = buildRuleResolver; if (args != null) { setSrcs(args.getSrcs()) .setResources(args.getResources()) .setResourcesRoot(args.getResourcesRoot()) .setProguardConfig(args.getProguardConfig()) .setPostprocessClassesCommands(args.getPostprocessClassesCommands()) .setDeps(JavaLibraryDeps.newInstance(args, buildRuleResolver)) .setTests(args.getTests()) .setManifestFile(args.getManifestFile()) .setMavenCoords(args.getMavenCoords()) .setClassesToRemoveFromJar(new RemoveClassesPatternsMatcher(args.getRemoveClasses())); } } Builder() { throw new UnsupportedOperationException(); } @Nullable public JavaLibraryDeps getDeps() { return deps; } } }
34.938942
98
0.70532
69d6625d66d5b1334acb95ffa570679f746e714f
414
package com.marchnetworks.security.authentication; import com.marchnetworks.command.api.security.UserInformation; public abstract interface SessionService { public abstract UserInformation veryifyUser( String paramString ); public abstract void deleteAllSessions( boolean paramBoolean ); public abstract void deleteSessionsByPrincipalName( String paramString ); public abstract int getTotalSessions(); }
25.875
74
0.833333
d0102931a334b07b478d61ff6f68f0341ab95a19
1,053
package com.firstdata.payeezy.models.transaction; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by FA7G14Q on 9/1/2015. */ @JsonAutoDetect(getterVisibility= JsonAutoDetect.Visibility.DEFAULT,setterVisibility= JsonAutoDetect.Visibility.DEFAULT,fieldVisibility= JsonAutoDetect.Visibility.ANY) @JsonIgnoreProperties(ignoreUnknown = true) //@JsonInclude(JsonInclude.Include.NON_EMPTY) public class GiftRegistry { @JsonProperty("gift_registry_flag") private String giftRegistryFlag; @JsonProperty("gift_reg_address") private Address address; public String getGiftRegistryFlag() { return giftRegistryFlag; } public void setGiftRegistryFlag(String giftRegistryFlag) { this.giftRegistryFlag = giftRegistryFlag; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
28.459459
167
0.761633
1b91ad955058d38f3a7d1c289db42e2a2d7d6251
1,756
package com.kidand.algorithms.and.data.structures.algorithms.sort.shellsort; /** * ██╗ ██╗██╗██████╗ █████╗ ███╗ ██╗██████╗ * ██║ ██╔╝██║██╔══██╗██╔══██╗████╗ ██║██╔══██╗ * █████╔╝ ██║██║ ██║███████║██╔██╗ ██║██║ ██║ * ██╔═██╗ ██║██║ ██║██╔══██║██║╚██╗██║██║ ██║ * ██║ ██╗██║██████╔╝██║ ██║██║ ╚████║██████╔╝ * ╚═╝ ╚═╝╚═╝╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝╚═════╝ * * @description: ShellSort 希尔排序 * @author: Kidand * @date: 2020/12/3 10:57 * Copyright © 2019-Kidand. */ public class ShellSort { /** * 私有构造方法 */ private ShellSort() { } /** * 希尔排序 * * @param data * @param <E> */ public static <E extends Comparable<E>> void sort(E[] data) { int h = data.length / 2; while (h >= 1) { // 对 data[h, n),进行插入排序 for (int i = h; i < data.length; i++) { E t = data[i]; int j; for (j = i; j - h >= 0 && t.compareTo(data[j - h]) < 0; j -= h) { data[j] = data[j - h]; } data[j] = t; } h /= 2; } } /** * 希尔排序优化 * * @param data * @param <E> */ public static <E extends Comparable<E>> void sort2(E[] data) { int h = 1; while (h < data.length) { h = h * 3 + 1; } while (h >= 1) { // 对 data[h, n),进行插入排序 for (int i = h; i < data.length; i++) { E t = data[i]; int j; for (j = i; j - h >= 0 && t.compareTo(data[j - h]) < 0; j -= h) { data[j] = data[j - h]; } data[j] = t; } h /= 3; } } }
24.732394
81
0.308087
34a22ded0355ba54acf957153729da397b916f69
599
package com.bkc.event.dao; import java.util.List; import org.springframework.stereotype.Repository; import com.bkc.event.vo.EventVO; import com.bkc.event.vo.StoreVO; @Repository public interface EventDAO { //게시글 조회 public List<EventVO> getEventList(EventVO event); //게시글 상세조회 public EventVO getEvent(EventVO event); //진행중 이벤트 조회 public List<EventVO> getEventConList(EventVO event); //종료 이벤트 조회 public List<EventVO> getEventEndList(EventVO event); //신규매장 이벤트 조회 public List<StoreVO>getStoreNewList(StoreVO store); //신규매장 이벤트 상세조회 public StoreVO getStore(StoreVO store); }
19.322581
53
0.75793
b50e6da6c6ac9f2cc6985fca5d2c2319282d8aa5
1,194
package pruefungsvorbereitung; import java.util.*; class Example1 { public void example() { Set set = new TreeSet(); set.add(new Integer(2)); set.add(new Integer(1)); System.out.println(set); } } class Example2 { public void example() { Set set = new HashSet(); set.add(new Integer(2)); set.add(new Integer(1)); System.out.println(set); } } class Example3 { public void example() { // Set set = new SortedSet(); // set.add(new Integer(2)); // set.add(new Integer(1)); // System.out.println(set); } } class Example4 { public void example() { // List set = new SortedList(); // set.add(new Integer(2)); // set.add(new Integer(1)); // System.out.println(set); } } class Example5 { public void example() { Set set = new LinkedHashSet(); set.add(new Integer(2)); set.add(new Integer(1)); System.out.println(set); } } public class VCE2014ExamCQuestion150 { public static void main(String[] args) { Example1 example1 = new Example1(); example1.example(); Example2 example2 = new Example2(); example2.example(); Example5 example5 = new Example5(); example5.example(); } }
19.57377
42
0.618928
f68884319294900d51d3bca36826c4b5c52a2f39
2,507
package tmt.tcs; import csw.util.config.Configurations.ConfigKey; import csw.util.config.DoubleKey; import csw.util.config.StringKey; /** * This class contains all the configurations specific to TCS Assembly */ public class TcsConfig { public static final String tcsPrefix = "tcs"; public static final String mcsPrefix = "tcs.mcs"; public static final String ecsPrefix = "tcs.ecs"; public static final String m3Prefix = "tcs.m3"; public static final String tpkPrefix = "tcs.tpk"; public static final String tcsTpkPrefix = "tcs.str"; public static final String initPrefix = tcsPrefix + ".init"; public static final String movePrefix = tcsPrefix + ".move"; public static final String offsetPrefix = tcsPrefix + ".offset"; public static final String followPrefix = tcsPrefix + ".follow"; public static final String tcsStatePrefix = tcsPrefix + ".tcsState"; public static final String positionDemandPrefix = tcsTpkPrefix + ".positiondemands"; public static final String offsetDemandPrefix = tcsTpkPrefix + ".offsetdemands"; public static final String currentPosPrefix = tcsPrefix + ".currentposition"; public static final String mcsPositionPrefix = mcsPrefix + ".position"; public static final String ecsPositionPrefix = ecsPrefix + ".position"; public static final String m3PositionPrefix = m3Prefix + ".position"; public static final ConfigKey dummyCK = new ConfigKey(tcsPrefix); public static final ConfigKey initCK = new ConfigKey(initPrefix); public static final ConfigKey moveCK = new ConfigKey(movePrefix); public static final ConfigKey offsetCK = new ConfigKey(offsetPrefix); public static final ConfigKey followCK = new ConfigKey(followPrefix); public static final ConfigKey tcsStateCK = new ConfigKey(tcsStatePrefix); public static final ConfigKey positionDemandCK = new ConfigKey(positionDemandPrefix); public static final ConfigKey offsetDemandCK = new ConfigKey(offsetDemandPrefix); public static final ConfigKey currentPosCK = new ConfigKey(currentPosPrefix); public static final ConfigKey mcsPositionCK = new ConfigKey(mcsPositionPrefix); public static final ConfigKey ecsPositionCK = new ConfigKey(ecsPositionPrefix); public static final ConfigKey m3PositionCK = new ConfigKey(m3PositionPrefix); public static final StringKey target = new StringKey("tcs.target"); public static final DoubleKey ra = new DoubleKey("tcs.ra"); public static final DoubleKey dec = new DoubleKey("tcs.dec"); public static final StringKey frame = new StringKey("tcs.frame"); }
51.163265
86
0.788592
6c745bc0e8dc08ab5193a3096999046998cfd748
904
package org.nico.codegenerator.consts; public enum MailType { REGISTER(1, "注册"), ; private int code; private String msg; private MailType(int code, String msg) { this.code = code; this.msg = msg; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public static boolean contains(int code) { for(MailType t: values()) { if(t.code == code) { return true; } } return false; } public static MailType parse(int code) { for(MailType t: values()) { if(t.code == code) { return t; } } return null; } }
17.384615
46
0.47677
3c5e6f737092461f7fc16dd9f8ce4535c282208e
5,349
package com.callforcode.greenfarm.controller.impl; import com.callforcode.greenfarm.consts.GreenFarmConst; import com.callforcode.greenfarm.controller.api.GFPlantTaskController; import com.callforcode.greenfarm.entity.*; import com.callforcode.greenfarm.exception.SeedNotFoundException; import com.callforcode.greenfarm.service.api.GFFarmService; import com.callforcode.greenfarm.service.api.GFLandService; import com.callforcode.greenfarm.service.api.GFPlantTaskService; import com.callforcode.greenfarm.service.api.GFSeedService; import com.callforcode.greenfarm.util.BeanUtils; import com.callforcode.greenfarm.vo.*; import lombok.AllArgsConstructor; import org.springframework.web.bind.annotation.RestController; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import java.util.Objects; @AllArgsConstructor @RestController public class GFPlantTaskControllerImpl implements GFPlantTaskController { private GFPlantTaskService service; private GFLandService landService; private GFFarmService farmService; private GFSeedService seedService; @Override public ResultVo<List<GFPlantTaskVo>> queryPlantTask(String userName) { List<GFPlantTask> plantTasks = service.queryByUserName(userName); List<GFPlantTaskVo> plantTaskVos = new ArrayList<>(); for (GFPlantTask plantTask : plantTasks) { Integer landId = plantTask.getLandId(); GFLand gfLand = landService.queryLandByLandId(landId); int farmId = gfLand.getFarmId(); GFFarmWithBLOBs gfFarm = farmService.queryFarmByFarmId(farmId); String farmName = gfFarm.getFarmName(); GFPlantTaskVo gfPlantTaskVo = BeanUtils.copyBean(plantTask, GFPlantTaskVo.class); List<GFTaskStep> taskSteps = service.queryTaskStep(plantTask.getTaskId()); int length = taskSteps.size(); int totalSteps = length + 1; int count = 0; String status = plantTask.getStatus(); if (GreenFarmConst.GRF_TASK_STATUS_COMPLETE.equals(status)) { count = totalSteps; } else { for (int i = 0; i < length; i++) { GFTaskStep taskStep = taskSteps.get(i); if (status.equals(taskStep.getPlantStep())) { count = i + 1; } } } double res = (double) count / (double) totalSteps; String percentage = getPercentage(res); gfPlantTaskVo.setFarmName(farmName); gfPlantTaskVo.setFarmId(Integer.toString(farmId)); gfPlantTaskVo.setPercentage(percentage); String imageUrl = gfFarm.getImageUrl(); String iconUrl = gfFarm.getIconUrl(); gfPlantTaskVo.setImageUrl(imageUrl); gfPlantTaskVo.setIconUrl(iconUrl); int seedId = plantTask.getSeedId(); GFSeed gfSeed = seedService.querySeedBySeedId(seedId); if (Objects.isNull(gfSeed)) { throw new SeedNotFoundException("the seed info not found.seedId=" + seedId); } gfPlantTaskVo.setSeedName(gfSeed.getSeedName()); plantTaskVos.add(gfPlantTaskVo); } return BeanUtils.createResultVo(plantTaskVos); } @Override public ResultVo<List<GFPlantTaskStepVo>> queryPlantTaskStep(String taskId) { List<GFTaskStep> taskSteps = service.queryTaskStep(Integer.parseInt(taskId)); return BeanUtils.createResultVo(BeanUtils.copyListBean(taskSteps, GFPlantTaskStepVo.class)); } @Override public ResultVo<GFPlantTaskDetailVo> queryPlantTaskDetail(String stepId) { GFTaskDetail taskDetail = service.queryTaskDetail(Integer.parseInt(stepId)); GFStepTemplate stepTemplate = service.queryStepTemplateByStepId(Integer.parseInt(stepId)); GFPlantTaskDetailVo vo = BeanUtils.copyBean(taskDetail, GFPlantTaskDetailVo.class); if (Objects.nonNull(stepTemplate)) { vo.setVideoUrl(BeanUtils.splitToArray(stepTemplate.getVedioUrl(), ";")); } else { vo.setVideoUrl(BeanUtils.convertStringWithCommaToArray(null)); } return BeanUtils.createResultVo(vo); } @Override public ResultVo updatePlantTaskDetail(RevisePlantTaskVo revisePlantTaskVo) { String operateRecord = BeanUtils.convertJson(revisePlantTaskVo.getOperRecord()); GFTaskDetail gfTaskDetail = service.queryTaskDetail(revisePlantTaskVo.getStepId()); gfTaskDetail.setOperRecord(operateRecord); gfTaskDetail.setStatus(GreenFarmConst.GRF_TASK_DETAIL_STATUS_APPROVED); service.reviseTaskDetail(gfTaskDetail); return new ResultVo(); } @Override public ResultVo<GFPlantTaskVo> queryPlantTaskByProductId(Integer productId) { GFPlantTask plantTask = service.queryPlantTaskByProductId(productId); return BeanUtils.createResultVo(BeanUtils.copyBean(plantTask, GFPlantTaskVo.class)); } private String getPercentage(double i) { NumberFormat nt = NumberFormat.getPercentInstance(); nt.setMinimumFractionDigits(2); return nt.format(i); } }
43.487805
101
0.67994
68979d0aa1d73ac6fa1e9eddb473f5aad0c1a06a
2,013
package com.xresch.cfw.features.dashboard.parameters; import java.util.HashSet; import java.util.LinkedHashMap; import javax.servlet.http.HttpServletRequest; import com.xresch.cfw._main.CFW; import com.xresch.cfw.datahandling.CFWField; import com.xresch.cfw.datahandling.CFWField.FormFieldType; import com.xresch.cfw.features.dashboard.parameters.DashboardParameter.DashboardParameterFields; public class ParameterDefinitionSelect extends ParameterDefinition { public static final String LABEL = "Select"; /*************************************************************** * ***************************************************************/ @Override public String getParamLabel() { return LABEL; } /*************************************************************** * ***************************************************************/ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public CFWField getFieldForSettings(HttpServletRequest request, String dashboardid, Object fieldValue) { CFWField settingsField = CFWField.newValueLabel("JSON_VALUE"); if(fieldValue != null) { settingsField.setValueConvert(fieldValue); } return settingsField; } /*************************************************************** * ***************************************************************/ @SuppressWarnings({ "rawtypes" }) @Override public CFWField getFieldForWidget(HttpServletRequest request, String dashboardid, Object fieldValue) { CFWField settingsField = CFWField.newString(FormFieldType.SELECT, DashboardParameterFields.VALUE); if(fieldValue !=null) { LinkedHashMap<String, String> options = CFW.JSON.fromJsonLinkedHashMap(fieldValue.toString()); settingsField.setOptions(options); } return settingsField; } /*************************************************************** * ***************************************************************/ @Override public boolean isAvailable(HashSet<String> widgetTypesArray) { return true; } }
31.453125
105
0.573274
4225df793d6d869c4cc96da964a52716990f5aa2
881
package com.fermedu.iterative.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.util.Map; /** * @Program: iterative-calculation * @Create: 2020-01-27 23:20 * @Author: JustThink * @Description: * @Include: **/ @Controller @Slf4j @RequestMapping(value = {"/calculation/sample"}) public class CalculatedSampleController { @GetMapping(value = {"/all"}) public ModelAndView sampleAll(Map<String, Object> map) { return new ModelAndView("page/sampleAll", map); } @GetMapping(value = {"/one"}) public ModelAndView sampleOne(Map<String, Object> map) { return new ModelAndView("page/sampleOne", map); } }
25.171429
62
0.729852
10c56385d144ba42e39df488419fb055c6f79ee7
1,297
package sarf.verb.quadriliteral.unaugmented.passive; import sarf.Word; import sarf.util.*; import sarf.verb.quadriliteral.unaugmented.*; /** * الفعل الماضي الرباعي المجرد المبني للمجهول * <p>Title: Sarf</p> * <p>Description: برنامج التصريف</p> * <p>Copyright: Copyright (c) 2006</p> * <p>Company: </p> * @author Haytham Mohtasseb Billah * @version 1.0 */ public class PassivePastVerb extends Word { private final UnaugmentedQuadrilateralRoot root; //حركة لام الفعل حسب الضمير private final String lastDpa; //الأحرف المضافة لنهاية الفعل حسب الضمير private final String connectedPronoun; PassivePastVerb(UnaugmentedQuadrilateralRoot root, String lastDpa, String connectedPronoun) { this.root = root; this.lastDpa = lastDpa; this.connectedPronoun = connectedPronoun; } public String getConnectedPronoun() { return connectedPronoun; } public UnaugmentedQuadrilateralRoot getRoot() { return root; } public String getLastDpa() { return lastDpa; } public String toString() { return root.getC1()+ArabCharUtil.DAMMA+root.getC2()+ArabCharUtil.SKOON+root.getC3()+ArabCharUtil.KASRA+root.getC4()+lastDpa+connectedPronoun; } }
26.469388
150
0.673863
7f71d8de7933f299833ecd63707ceb59769c8df4
221
package example.service; import example.repo.Customer293Repository; import org.springframework.stereotype.Service; @Service public class Customer293Service { public Customer293Service(Customer293Repository repo) {} }
20.090909
57
0.837104
8a190b3a78428a4a86de75b31adfe92aa7df5180
666
package org.gaussian.supersonic.session.validation; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.UUID; public class SessionIdValidator implements ConstraintValidator<ValidSessionId, String> { @Override public void initialize(ValidSessionId constraintAnnotation) {} @Override public boolean isValid(String value, ConstraintValidatorContext context) { if (value == null) { return false; } try { UUID.fromString(value); } catch (IllegalArgumentException e) { return false; } return true; } }
26.64
88
0.686186
c93f53e6da396abf90ce89dbce3b257f2be4272d
15,261
/* * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.hazelcast.jet.impl.processor; import com.hazelcast.internal.metrics.Probe; import com.hazelcast.jet.JetException; import com.hazelcast.jet.Traverser; import com.hazelcast.jet.Traversers; import com.hazelcast.jet.aggregate.AggregateOperation; import com.hazelcast.jet.config.ProcessingGuarantee; import com.hazelcast.jet.core.AbstractProcessor; import com.hazelcast.jet.core.BroadcastKey; import com.hazelcast.jet.core.Watermark; import com.hazelcast.jet.function.KeyedWindowResultFunction; import com.hazelcast.jet.impl.execution.init.JetInitDataSerializerHook; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import com.hazelcast.util.QuickMath; import javax.annotation.Nonnull; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.StringJoiner; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.ToLongFunction; import java.util.stream.Stream; import static com.hazelcast.jet.Traversers.traverseStream; import static com.hazelcast.jet.Util.entry; import static com.hazelcast.jet.config.ProcessingGuarantee.EXACTLY_ONCE; import static com.hazelcast.jet.core.BroadcastKey.broadcastKey; import static com.hazelcast.jet.impl.util.LoggingUtil.logFine; import static com.hazelcast.jet.impl.util.Util.lazyAdd; import static com.hazelcast.jet.impl.util.Util.lazyIncrement; import static com.hazelcast.jet.impl.util.Util.logLateEvent; import static com.hazelcast.jet.impl.util.Util.toLocalDateTime; import static com.hazelcast.util.Preconditions.checkTrue; import static java.lang.Math.min; import static java.lang.System.arraycopy; import static java.util.Collections.emptyList; import static java.util.Objects.requireNonNull; /** * Session window processor. See {@link * com.hazelcast.jet.core.processor.Processors#aggregateToSessionWindowP * Processors.aggregateToSessionWindowP()} for documentation. * * @param <K> type of the extracted grouping key * @param <A> type of the accumulator object * @param <R> type of the finished result */ public class SessionWindowP<K, A, R, OUT> extends AbstractProcessor { private static final Watermark COMPLETING_WM = new Watermark(Long.MAX_VALUE); // exposed for testing, to check for memory leaks final Map<K, Windows<A>> keyToWindows = new HashMap<>(); final SortedMap<Long, Set<K>> deadlineToKeys = new TreeMap<>(); long currentWatermark = Long.MIN_VALUE; private final long sessionTimeout; @Nonnull private final List<ToLongFunction<Object>> timestampFns; @Nonnull private final List<Function<Object, K>> keyFns; @Nonnull private final AggregateOperation<A, R> aggrOp; @Nonnull private final BiConsumer<? super A, ? super A> combineFn; @Nonnull private final KeyedWindowResultFunction<? super K, ? super R, OUT> mapToOutputFn; @Nonnull private final FlatMapper<Watermark, OUT> closedWindowFlatmapper; private ProcessingGuarantee processingGuarantee; @Probe private AtomicLong lateEventsDropped = new AtomicLong(); @Probe private AtomicLong totalKeys = new AtomicLong(); @Probe private AtomicLong totalWindows = new AtomicLong(); private Traverser snapshotTraverser; private long minRestoredCurrentWatermark = Long.MAX_VALUE; // extracted lambdas to reduce GC litter private final Function<K, Windows<A>> newWindowsFunction = k -> { lazyIncrement(totalKeys); return new Windows<>(); }; @SuppressWarnings("unchecked") public SessionWindowP( long sessionTimeout, @Nonnull List<? extends ToLongFunction<?>> timestampFns, @Nonnull List<? extends Function<?, ? extends K>> keyFns, @Nonnull AggregateOperation<A, R> aggrOp, @Nonnull KeyedWindowResultFunction<? super K, ? super R, OUT> mapToOutputFn ) { checkTrue(keyFns.size() == aggrOp.arity(), keyFns.size() + " key functions " + "provided for " + aggrOp.arity() + "-arity aggregate operation"); this.timestampFns = (List<ToLongFunction<Object>>) timestampFns; this.keyFns = (List<Function<Object, K>>) keyFns; this.aggrOp = aggrOp; this.combineFn = requireNonNull(aggrOp.combineFn()); this.mapToOutputFn = mapToOutputFn; this.sessionTimeout = sessionTimeout; this.closedWindowFlatmapper = flatMapper(this::traverseClosedWindows); } @Override protected void init(@Nonnull Context context) { processingGuarantee = context.processingGuarantee(); } @Override protected boolean tryProcess(int ordinal, @Nonnull Object item) { @SuppressWarnings("unchecked") final long timestamp = timestampFns.get(ordinal).applyAsLong(item); if (timestamp < currentWatermark) { logLateEvent(getLogger(), currentWatermark, item); lazyIncrement(lateEventsDropped); return true; } K key = keyFns.get(ordinal).apply(item); addItem(ordinal, keyToWindows.computeIfAbsent(key, newWindowsFunction), key, timestamp, item); return true; } @Override public boolean tryProcessWatermark(@Nonnull Watermark wm) { currentWatermark = wm.timestamp(); assert totalWindows.get() == deadlineToKeys.values().stream().mapToInt(Set::size).sum() : "unexpected totalWindows. Expected=" + deadlineToKeys.values().stream().mapToInt(Set::size).sum() + ", actual=" + totalWindows.get(); return closedWindowFlatmapper.tryProcess(wm); } @Override public boolean complete() { return closedWindowFlatmapper.tryProcess(COMPLETING_WM); } private Traverser<OUT> traverseClosedWindows(Watermark wm) { SortedMap<Long, Set<K>> windowsToClose = deadlineToKeys.headMap(wm.timestamp()); Stream<OUT> closedWindows = windowsToClose .values().stream() .flatMap(Set::stream) .map(key -> closeWindows(keyToWindows.get(key), key, wm.timestamp())) .flatMap(List::stream); return traverseStream(closedWindows) .onFirstNull(() -> { lazyAdd(totalWindows, -windowsToClose.values().stream().mapToInt(Set::size).sum()); windowsToClose.clear(); }); } private void addToDeadlines(K key, long deadline) { if (deadlineToKeys.computeIfAbsent(deadline, x -> new HashSet<>()).add(key)) { lazyIncrement(totalWindows); } } private void removeFromDeadlines(K key, long deadline) { Set<K> ks = deadlineToKeys.get(deadline); ks.remove(key); lazyAdd(totalWindows, -1); if (ks.isEmpty()) { deadlineToKeys.remove(deadline); } } @Override public boolean saveToSnapshot() { if (snapshotTraverser == null) { snapshotTraverser = Traversers.<Object>traverseIterable(keyToWindows.entrySet()) .append(entry(broadcastKey(Keys.CURRENT_WATERMARK), currentWatermark)) .onFirstNull(() -> snapshotTraverser = null); } return emitFromTraverserToSnapshot(snapshotTraverser); } @Override @SuppressWarnings("unchecked") protected void restoreFromSnapshot(@Nonnull Object key, @Nonnull Object value) { if (key instanceof BroadcastKey) { BroadcastKey bcastKey = (BroadcastKey) key; if (!Keys.CURRENT_WATERMARK.equals(bcastKey.key())) { throw new JetException("Unexpected broadcast key: " + bcastKey.key()); } long newCurrentWatermark = (long) value; assert processingGuarantee != EXACTLY_ONCE || minRestoredCurrentWatermark == Long.MAX_VALUE || minRestoredCurrentWatermark == newCurrentWatermark : "different values for currentWatermark restored, before=" + minRestoredCurrentWatermark + ", new=" + newCurrentWatermark; minRestoredCurrentWatermark = Math.min(newCurrentWatermark, minRestoredCurrentWatermark); return; } if (keyToWindows.put((K) key, (Windows) value) != null) { throw new JetException("Duplicate key in snapshot: " + key); } } @Override public boolean finishSnapshotRestore() { assert deadlineToKeys.isEmpty(); // populate deadlineToKeys for (Entry<K, Windows<A>> entry : keyToWindows.entrySet()) { for (long end : entry.getValue().ends) { addToDeadlines(entry.getKey(), end); } } currentWatermark = minRestoredCurrentWatermark; totalKeys.set(keyToWindows.size()); logFine(getLogger(), "Restored currentWatermark from snapshot to: %s", currentWatermark); return true; } private void addItem(int ordinal, Windows<A> w, K key, long timestamp, Object item) { aggrOp.accumulateFn(ordinal).accept(resolveAcc(w, key, timestamp), item); } private List<OUT> closeWindows(Windows<A> w, K key, long wm) { if (w == null) { return emptyList(); } List<OUT> results = new ArrayList<>(); int i = 0; for (; i < w.size && w.ends[i] < wm; i++) { OUT out = mapToOutputFn.apply(w.starts[i], w.ends[i], key, aggrOp.finishFn().apply(w.accs[i])); if (out != null) { results.add(out); } } if (i != w.size) { w.removeHead(i); } else { keyToWindows.remove(key); totalKeys.set(keyToWindows.size()); } return results; } private A resolveAcc(Windows<A> w, K key, long timestamp) { long eventEnd = timestamp + sessionTimeout; int i = 0; for (; i < w.size && w.starts[i] <= eventEnd; i++) { // the window `i` is not after the event interval if (w.ends[i] < timestamp) { // the window `i` is before the event interval continue; } if (w.starts[i] <= timestamp && w.ends[i] >= eventEnd) { // the window `i` fully covers the event interval return w.accs[i]; } // the window `i` overlaps the event interval if (i + 1 == w.size || w.starts[i + 1] > eventEnd) { // the window `i + 1` doesn't overlap the event interval w.starts[i] = min(w.starts[i], timestamp); if (w.ends[i] < eventEnd) { removeFromDeadlines(key, w.ends[i]); w.ends[i] = eventEnd; addToDeadlines(key, w.ends[i]); } return w.accs[i]; } // both `i` and `i + 1` windows overlap the event interval removeFromDeadlines(key, w.ends[i]); w.ends[i] = w.ends[i + 1]; combineFn.accept(w.accs[i], w.accs[i + 1]); w.removeWindow(i + 1); return w.accs[i]; } addToDeadlines(key, eventEnd); return insertWindow(w, i, timestamp, eventEnd); } private A insertWindow(Windows<A> w, int idx, long windowStart, long windowEnd) { w.expandIfNeeded(); w.copy(idx, idx + 1, w.size - idx); w.size++; w.starts[idx] = windowStart; w.ends[idx] = windowEnd; w.accs[idx] = aggrOp.createFn().get(); return w.accs[idx]; } public static class Windows<A> implements IdentifiedDataSerializable { private int size; private long[] starts = new long[2]; private long[] ends = new long[2]; private A[] accs = (A[]) new Object[2]; private void removeWindow(int idx) { size--; copy(idx + 1, idx, size - idx); } private void removeHead(int count) { copy(count, 0, size - count); size -= count; } private void copy(int from, int to, int length) { arraycopy(starts, from, starts, to, length); arraycopy(ends, from, ends, to, length); arraycopy(accs, from, accs, to, length); } private void expandIfNeeded() { if (size == starts.length) { starts = Arrays.copyOf(starts, 2 * starts.length); ends = Arrays.copyOf(ends, 2 * ends.length); accs = Arrays.copyOf(accs, 2 * accs.length); } } @Override public int getFactoryId() { return JetInitDataSerializerHook.FACTORY_ID; } @Override public int getId() { return JetInitDataSerializerHook.SESSION_WINDOW_P_WINDOWS; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeInt(size); for (int i = 0; i < size; i++) { out.writeLong(starts[i]); out.writeLong(ends[i]); out.writeObject(accs[i]); } } @Override public void readData(ObjectDataInput in) throws IOException { size = in.readInt(); if (size > starts.length) { int newSize = QuickMath.nextPowerOfTwo(size); starts = new long[newSize]; ends = new long[newSize]; accs = (A[]) new Object[newSize]; } for (int i = 0; i < size; i++) { starts[i] = in.readLong(); ends[i] = in.readLong(); accs[i] = in.readObject(); } } @Override public String toString() { StringJoiner sj = new StringJoiner(", ", getClass().getSimpleName() + '{', "}"); for (int i = 0; i < size; i++) { sj.add("[s=" + toLocalDateTime(starts[i]).toLocalTime() + ", e=" + toLocalDateTime(ends[i]).toLocalTime() + ", a=" + accs[i] + ']'); } return sj.toString(); } } // package-visible for test enum Keys { CURRENT_WATERMARK } }
37.681481
115
0.617718
288d21851aea17c1456f013bcfdac15d45a7b9d9
6,043
package com.pushtorefresh.storio.sqlite.annotations.processor.generate; import com.pushtorefresh.storio.sqlite.annotations.processor.ProcessingException; import com.pushtorefresh.storio.sqlite.annotations.processor.introspection.JavaType; import com.pushtorefresh.storio.sqlite.annotations.processor.introspection.StorIOSQLiteColumnMeta; import com.pushtorefresh.storio.sqlite.annotations.processor.introspection.StorIOSQLiteTypeMeta; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import org.jetbrains.annotations.NotNull; import static com.pushtorefresh.storio.sqlite.annotations.processor.generate.Common.ANDROID_NON_NULL_ANNOTATION_CLASS_NAME; import static com.pushtorefresh.storio.sqlite.annotations.processor.generate.Common.INDENT; import static com.pushtorefresh.storio.sqlite.annotations.processor.introspection.JavaType.BOOLEAN; import static com.pushtorefresh.storio.sqlite.annotations.processor.introspection.JavaType.BOOLEAN_OBJECT; import static com.pushtorefresh.storio.sqlite.annotations.processor.introspection.JavaType.BYTE_ARRAY; import static com.pushtorefresh.storio.sqlite.annotations.processor.introspection.JavaType.DOUBLE; import static com.pushtorefresh.storio.sqlite.annotations.processor.introspection.JavaType.DOUBLE_OBJECT; import static com.pushtorefresh.storio.sqlite.annotations.processor.introspection.JavaType.FLOAT; import static com.pushtorefresh.storio.sqlite.annotations.processor.introspection.JavaType.FLOAT_OBJECT; import static com.pushtorefresh.storio.sqlite.annotations.processor.introspection.JavaType.INTEGER; import static com.pushtorefresh.storio.sqlite.annotations.processor.introspection.JavaType.INTEGER_OBJECT; import static com.pushtorefresh.storio.sqlite.annotations.processor.introspection.JavaType.LONG; import static com.pushtorefresh.storio.sqlite.annotations.processor.introspection.JavaType.LONG_OBJECT; import static com.pushtorefresh.storio.sqlite.annotations.processor.introspection.JavaType.SHORT; import static com.pushtorefresh.storio.sqlite.annotations.processor.introspection.JavaType.SHORT_OBJECT; import static com.pushtorefresh.storio.sqlite.annotations.processor.introspection.JavaType.STRING; import static javax.lang.model.element.Modifier.PUBLIC; public class GetResolverGenerator { @NotNull public JavaFile generateJavaFile(@NotNull StorIOSQLiteTypeMeta storIOSQLiteTypeMeta) { final ClassName storIOSQLiteTypeClassName = ClassName.get(storIOSQLiteTypeMeta.packageName, storIOSQLiteTypeMeta.simpleName); final TypeSpec getResolver = TypeSpec.classBuilder(storIOSQLiteTypeMeta.simpleName + "StorIOSQLiteGetResolver") .addJavadoc("Generated resolver for Get Operation\n") .addModifiers(PUBLIC) .superclass(ParameterizedTypeName.get(ClassName.get("com.pushtorefresh.storio.sqlite.operations.get", "DefaultGetResolver"), storIOSQLiteTypeClassName)) .addMethod(createMapFromCursorMethodSpec(storIOSQLiteTypeMeta, storIOSQLiteTypeClassName)) .build(); return JavaFile .builder(storIOSQLiteTypeMeta.packageName, getResolver) .indent(INDENT) .build(); } @NotNull MethodSpec createMapFromCursorMethodSpec(@NotNull StorIOSQLiteTypeMeta storIOSQLiteTypeMeta, @NotNull ClassName storIOSQLiteTypeClassName) { final MethodSpec.Builder builder = MethodSpec.methodBuilder("mapFromCursor") .addJavadoc("{@inheritDoc}\n") .addAnnotation(Override.class) .addAnnotation(ANDROID_NON_NULL_ANNOTATION_CLASS_NAME) .addModifiers(PUBLIC) .returns(storIOSQLiteTypeClassName) .addParameter(ParameterSpec.builder(ClassName.get("android.database", "Cursor"), "cursor") .addAnnotation(ANDROID_NON_NULL_ANNOTATION_CLASS_NAME) .build()) .addStatement("$T object = new $T()", storIOSQLiteTypeClassName, storIOSQLiteTypeClassName) .addCode("\n"); for (final StorIOSQLiteColumnMeta columnMeta : storIOSQLiteTypeMeta.columns.values()) { final String columnIndex = "cursor.getColumnIndex(\"" + columnMeta.storIOSQLiteColumn.name() + "\")"; final String getFromCursor; final JavaType javaType = columnMeta.javaType; if (javaType == BOOLEAN || javaType == BOOLEAN_OBJECT) { getFromCursor = "getInt(" + columnIndex + ") == 1"; } else if (javaType == SHORT || javaType == SHORT_OBJECT) { getFromCursor = "getShort(" + columnIndex + ")"; } else if (javaType == INTEGER || javaType == INTEGER_OBJECT) { getFromCursor = "getInt(" + columnIndex + ")"; } else if (javaType == LONG || javaType == LONG_OBJECT) { getFromCursor = "getLong(" + columnIndex + ")"; } else if (javaType == FLOAT || javaType == FLOAT_OBJECT) { getFromCursor = "getFloat(" + columnIndex + ")"; } else if (javaType == DOUBLE || javaType == DOUBLE_OBJECT) { getFromCursor = "getDouble(" + columnIndex + ")"; } else if (javaType == STRING) { getFromCursor = "getString(" + columnIndex + ")"; } else if (javaType == BYTE_ARRAY) { getFromCursor = "getBlob(" + columnIndex + ")"; } else { throw new ProcessingException(columnMeta.element, "Can not generate GetResolver for field"); } builder .addStatement("object.$L = cursor.$L", columnMeta.fieldName, getFromCursor); } return builder .addCode("\n") .addStatement("return object") .build(); } }
57.552381
168
0.714877
aafba173424dfa7a2d6ab74856ae52972a288dcd
3,694
package io.chat.menuchat; import io.chat.ouput.Output; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Objects; import static io.chat.menuchat.Bot.getDataBotFile; /** * MenuTracker. * * @author Maxim Vanny * @version 5.0 * @since 4/11/2019 */ public class MenuChat { /** * field output. */ private final Output out; /** * field flag for stop input chat side dialog. */ private boolean isStop = false; /** * field map action with choice action bot. */ private Map<String, UserAction> action = new HashMap<>(); /** * Constructor. * * @param aOut output */ public MenuChat(final Output aOut) { this.out = aOut; } /** * Method fill map for action. */ public final void fillAction() { this.action = Map.of( "stop", new Stop(), "continue", new Continue(), "end", new End(), "any", new Any()); } /** * Method open log file for write. * * @throws IOException exception */ public final void openLogFile() throws IOException { this.out.openFile(); } /** * Method get data chat file. * * @param pathBot path chat file * @throws IOException exception */ public final void getBotFile(final String pathBot) throws IOException { getDataBotFile(pathBot); } /** * Method select key for execute. * * @param key user input * @throws IOException exception */ public final void select(final String key) throws IOException { Objects.requireNonNull(key, "must not be null"); UserAction userAction = this.action .getOrDefault(key, this.action.get("any")); userAction.execute(this.out, key); } /** * Inner class Stop. */ public class Stop extends BaseAction { @Override public final void execute(final Output pOut, final String pUserKey) throws IOException { isStop = true; pOut.writeData("." + pUserKey); } } /** * Inner class Continue. */ public class Continue extends BaseAction { @Override public final void execute(final Output pOut, final String pUserKey) throws IOException { isStop = false; pOut.writeData("." + pUserKey); String botAnswer = Bot.getBotAnswer(); System.out.println(botAnswer); pOut.writeData("." + botAnswer); } } /** * Inner class End. */ public class End extends BaseAction { @Override public final void execute(final Output pOut, final String pUserKey) throws IOException { pOut.writeData("." + pUserKey); pOut.closeFile(); } } /** * Inner class Any. */ public class Any extends BaseAction { @Override public final void execute(final Output pOut, final String pUserKey) throws IOException { if (isStop) { pOut.writeData("." + pUserKey); } else { pOut.writeData("." + pUserKey); String botAnswer = Bot.getBotAnswer(); System.out.println(botAnswer); pOut.writeData("." + botAnswer); } } } }
25.832168
79
0.514889
a063230b4c791997d1ca038193764398ba8ff698
207
package com.artemis.component; import com.artemis.Component; import com.artemis.annotations.PackedWeaver; @PackedWeaver public class IllegalComponent extends Component { public Object ImNotAllowedHere; }
20.7
49
0.835749
a43146f3f2e7bc66e85d11e3da464ec1e18b24ac
610
package com.os7blue.pl.gnmr.utils; import java.text.SimpleDateFormat; import java.util.Date; /** * @Description: 处理日期格式的工具类 * @Author: os7blue * @CreateDate: Create by 18-8-25 下午8:16 * @UpdateUser: os7blue * @UpdateDate: Update by 18-8-25 下午8:16 * @UpdateRemark: 修改内容:无 * @Version: 1.0 */ public class DateUtil { public static String getDateNow(){ return new SimpleDateFormat("yyyy-MM-dd-EEE-HH:mm").format(new Date()); } public static String getDateNowByPattern(String pattern){ return new SimpleDateFormat(pattern).format(new Date()); } }
23.461538
79
0.662295
629d93302e8da34b4c6b08d5e44e4094b0648eee
145
package com.book.controller; import org.springframework.web.bind.annotation.RestController; @RestController public class BookController { }
14.5
62
0.813793
d08ee178344ea16d0f8db780f012cefc5a957e76
6,909
package ca.uwo.csd.ai.nlp.libsvm.ex; import ca.uwo.csd.ai.nlp.libsvm.svm; import ca.uwo.csd.ai.nlp.libsvm.svm_model; import ca.uwo.csd.ai.nlp.libsvm.svm_node; import ca.uwo.csd.ai.nlp.libsvm.svm_parameter; import ca.uwo.csd.ai.nlp.libsvm.svm_problem; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * <code>SVMTrainer</code> performs training of an SVM. * @author Syeed Ibn Faiz */ public class SVMTrainer { private static svm_problem prepareProblem(List<Instance> instances) { Instance[] array = new Instance[instances.size()]; array = instances.toArray(array); return prepareProblem(array); } private static svm_problem prepareProblem(Instance[] instances) { return prepareProblem(instances, 0, instances.length - 1); } private static svm_problem prepareProblem(Instance[] instances, int begin, int end) { svm_problem prob = new svm_problem(); prob.l = (end - begin) + 1; prob.y = new double[prob.l]; prob.x = new svm_node[prob.l]; for (int i = begin; i <= end; i++) { prob.y[i-begin] = instances[i].getLabel(); prob.x[i-begin] = new svm_node(instances[i].getData()); } return prob; } /** * Builds an SVM model * @param instances * @param param * @return */ public static svm_model train(Instance[] instances, svm_parameter param) { //prepare svm_problem svm_problem prob = prepareProblem(instances); String error_msg = svm.svm_check_parameter(prob, param); if (error_msg != null) { System.err.print("ERROR: " + error_msg + "\n"); System.exit(1); } return svm.svm_train(prob, param); } public static svm_model train(List<Instance> instances, svm_parameter param) { Instance[] array = new Instance[instances.size()]; array = instances.toArray(array); return train(array, param); } /** * Performs N-fold cross validation * @param instances * @param param parameters * @param nr_fold number of folds (N) * @param binary whether doing binary classification */ public static void doCrossValidation(Instance[] instances, svm_parameter param, int nr_fold, boolean binary) { svm_problem prob = prepareProblem(instances); int i; int total_correct = 0; double total_error = 0; double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0; double[] target = new double[prob.l]; svm.svm_cross_validation(prob, param, nr_fold, target); if (param.svm_type == svm_parameter.EPSILON_SVR || param.svm_type == svm_parameter.NU_SVR) { for (i = 0; i < prob.l; i++) { double y = prob.y[i]; double v = target[i]; total_error += (v - y) * (v - y); sumv += v; sumy += y; sumvv += v * v; sumyy += y * y; sumvy += v * y; } System.out.print("Cross Validation Mean squared error = " + total_error / prob.l + "\n"); System.out.print("Cross Validation Squared correlation coefficient = " + ((prob.l * sumvy - sumv * sumy) * (prob.l * sumvy - sumv * sumy)) / ((prob.l * sumvv - sumv * sumv) * (prob.l * sumyy - sumy * sumy)) + "\n"); } else { int tp = 0; int fp = 0; int fn = 0; for (i = 0; i < prob.l; i++) { if (target[i] == prob.y[i]) { ++total_correct; if (prob.y[i] > 0) { tp++; } } else if (prob.y[i] > 0) { fn++; } else if (prob.y[i] < 0) { fp++; } } System.out.print("Cross Validation Accuracy = " + 100.0 * total_correct / prob.l + "%\n"); if (binary) { double precision = (double) tp / (tp + fp); double recall = (double) tp / (tp + fn); System.out.println("Precision: " + precision); System.out.println("Recall: " + recall); System.out.println("FScore: " + 2 * precision * recall / (precision + recall)); } } } public static void doInOrderCrossValidation(Instance[] instances, svm_parameter param, int nr_fold, boolean binary) { int size = instances.length; int chunkSize = size/nr_fold; int begin = 0; int end = chunkSize - 1; int tp = 0; int fp = 0; int fn = 0; int total = 0; for (int i = 0; i < nr_fold; i++) { System.out.println("Iteration: " + (i+1)); List<Instance> trainingInstances = new ArrayList<Instance>(); List<Instance> testingInstances = new ArrayList<Instance>(); for (int j = 0; j < size; j++) { if (j >= begin && j <= end) { testingInstances.add(instances[j]); } else { trainingInstances.add(instances[j]); } } svm_model trainModel = train(trainingInstances, param); double[] predictions = SVMPredictor.predict(testingInstances, trainModel); for (int k = 0; k < predictions.length; k++) { if (predictions[k] == testingInstances.get(k).getLabel()) { //if (Math.abs(predictions[k] - testingInstances.get(k).getLabel()) < 0.00001) { if (testingInstances.get(k).getLabel() > 0) { tp++; } } else if (testingInstances.get(k).getLabel() > 0) { fn++; } else if (testingInstances.get(k).getLabel() < 0) { //System.out.println(testingInstances.get(k).getData()); fp++; } total++; } //update begin = end+1; end = begin + chunkSize - 1; if (end >= size) { end = size-1; } } double precision = (double) tp / (tp + fp); double recall = (double) tp / (tp + fn); System.out.println("Precision: " + precision); System.out.println("Recall: " + recall); System.out.println("FScore: " + 2 * precision * recall / (precision + recall)); } public static void saveModel(svm_model model, String filePath) throws IOException { svm.svm_save_model(filePath, model); } }
36.946524
129
0.505717
1fb2f7bab1d0e2e6243c93d3f8bcf545ab777a93
1,356
package com.restdocs.action.util; import com.intellij.psi.PsiAnnotation; import com.intellij.psi.PsiModifierList; import com.restdocs.action.common.SpringAnnotations; import java.util.stream.Stream; import static com.restdocs.action.common.SpringAnnotations.*; public class SpringUtil { public static boolean containsSpringAnnotation(SpringAnnotations springAnnotation, PsiModifierList modifierList) { if (modifierList != null) { PsiAnnotation[] annotations = modifierList.getAnnotations(); return Stream.of(annotations) .map(a -> a.getQualifiedName()) .anyMatch(name -> name.equalsIgnoreCase(springAnnotation.getQualifiedName())); } return false; } public static boolean isRestMethod(PsiModifierList modifierList) { return containsSpringAnnotation(REQUEST_MAPPING_QUALIFIED_NAME, modifierList) || containsSpringAnnotation(GET_MAPPING_QUALIFIED_NAME, modifierList) || containsSpringAnnotation(POST_MAPPING_QUALIFIED_NAME, modifierList) || containsSpringAnnotation(PUT_MAPPING_QUALIFIED_NAME, modifierList) || containsSpringAnnotation(DELETE_MAPPING_QUALIFIED_NAME, modifierList) || containsSpringAnnotation(PATCH_MAPPING_QUALIFIED_NAME, modifierList); } }
39.882353
118
0.721976
a719ee9f813c518ded42d9d1260ccc7819ec4ad3
35,700
package net.mcreator.minerustaddonsmod; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.common.registry.EntityEntry; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.IGuiHandler; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.IWorldGenerator; import net.minecraftforge.fml.common.IFuelHandler; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraft.world.gen.IChunkGenerator; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.biome.Biome; import net.minecraft.world.World; import net.minecraft.util.ResourceLocation; import net.minecraft.potion.Potion; import net.minecraft.item.ItemStack; import net.minecraft.item.Item; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.block.Block; import java.util.function.Supplier; import java.util.Random; import java.util.List; import java.util.ArrayList; @Mod(modid = minerustaddonsmod.MODID, version = minerustaddonsmod.VERSION) public class minerustaddonsmod implements IFuelHandler, IWorldGenerator { public static final String MODID = "minerustaddonsmod"; public static final String VERSION = "2.0"; @SidedProxy(clientSide = "net.mcreator.minerustaddonsmod.ClientProxyminerustaddonsmod", serverSide = "net.mcreator.minerustaddonsmod.CommonProxyminerustaddonsmod") public static CommonProxyminerustaddonsmod proxy; @Instance(MODID) public static minerustaddonsmod instance; public final List<ModElement> elements = new ArrayList<>(); public final List<Supplier<Block>> blocks = new ArrayList<>(); public final List<Supplier<Item>> items = new ArrayList<>(); public final List<Supplier<Biome>> biomes = new ArrayList<>(); public final List<Supplier<EntityEntry>> entities = new ArrayList<>(); public final List<Supplier<Potion>> potions = new ArrayList<>(); public minerustaddonsmod() { FluidRegistry.enableUniversalBucket(); elements.add(new MCreatorBuildingBlock(this)); elements.add(new MCreatorDecorationsTAB(this)); elements.add(new MCreatorToolsTab(this)); elements.add(new MCreatorArmorsandClothesTAB(this)); elements.add(new MCreatorGameplayTAB(this)); elements.add(new MCreatorOtherTab(this)); elements.add(new MCreatorIconmod(this)); elements.add(new MCreatorHayfloor(this)); elements.add(new MCreatorHayWall(this)); elements.add(new MCreatorWoodfloor(this)); elements.add(new MCreatorWoodwall(this)); elements.add(new MCreatorStonefloor(this)); elements.add(new MCreatorStoneWall(this)); elements.add(new MCreatorMetalfloor(this)); elements.add(new MCreatorMetalwall(this)); elements.add(new MCreatorArmoredfloor(this)); elements.add(new MCreatorArmoredwall(this)); elements.add(new MCreatorAsphalt(this)); elements.add(new MCreatorDecorbox(this)); elements.add(new MCreatorBluecontainer(this)); elements.add(new MCreatorDecorbrick(this)); elements.add(new MCreatorStonebrick(this)); elements.add(new MCreatorGarbage(this)); elements.add(new MCreatorGarage(this)); elements.add(new MCreatorTerraingrass1(this)); elements.add(new MCreatorTerraingrass2(this)); elements.add(new MCreatorTerraingrass3(this)); elements.add(new MCreatorTerraingravel(this)); elements.add(new MCreatorMetal1(this)); elements.add(new MCreatorMetal2(this)); elements.add(new MCreatorMetal3(this)); elements.add(new MCreatorMetal4(this)); elements.add(new MCreatorMetal5(this)); elements.add(new MCreatorMetal6(this)); elements.add(new MCreatorMetal7(this)); elements.add(new MCreatorMetal8(this)); elements.add(new MCreatorMetal9(this)); elements.add(new MCreatorMetal10(this)); elements.add(new MCreatorMetal11(this)); elements.add(new MCreatorMetal12(this)); elements.add(new MCreatorMetal13(this)); elements.add(new MCreatorMetal14(this)); elements.add(new MCreatorMetal15(this)); elements.add(new MCreatorMetal16(this)); elements.add(new MCreatorMetal17(this)); elements.add(new MCreatorMetal18(this)); elements.add(new MCreatorMetal19(this)); elements.add(new MCreatorMetal20(this)); elements.add(new MCreatorMetal21(this)); elements.add(new MCreatorMetal22(this)); elements.add(new MCreatorMetal23(this)); elements.add(new MCreatorMetal24(this)); elements.add(new MCreatorMetal25(this)); elements.add(new MCreatorMetal26(this)); elements.add(new MCreatorMetal27(this)); elements.add(new MCreatorTile(this)); elements.add(new MCreatorPlank(this)); elements.add(new MCreatorRedcontainer(this)); elements.add(new MCreatorTerrainsand(this)); elements.add(new MCreatorTerrainsnow(this)); elements.add(new MCreatorBrokenasphalt(this)); elements.add(new MCreatorTerrainstone1(this)); elements.add(new MCreatorTerrainstone2(this)); elements.add(new MCreatorTerrainstone3(this)); elements.add(new MCreatorTerrainstone4(this)); elements.add(new MCreatorDarkwoodplank(this)); elements.add(new MCreatorOakwoodplank(this)); elements.add(new MCreatorPlankbroken(this)); elements.add(new MCreatorYellowcontainer(this)); elements.add(new MCreatorFoodapple(this)); elements.add(new MCreatorBuildWood(this)); elements.add(new MCreatorBrokeWood(this)); elements.add(new MCreatorBuildStone(this)); elements.add(new MCreatorBrokeStone(this)); elements.add(new MCreatorBuildMetal(this)); elements.add(new MCreatorBrokeMetal(this)); elements.add(new MCreatorBuildArmored(this)); elements.add(new MCreatorEat(this)); elements.add(new MCreatorMedicalsTAB(this)); elements.add(new MCreatorFoodsTab(this)); elements.add(new MCreatorUseSyringe(this)); elements.add(new MCreatorSyringe(this)); elements.add(new MCreatorUseBandage(this)); elements.add(new MCreatorBandage(this)); elements.add(new MCreatorHorsemeatcooked(this)); elements.add(new MCreatorInfectedEAT(this)); elements.add(new MCreatorHorsemeatraw(this)); elements.add(new MCreatorBlueberries(this)); elements.add(new MCreatorOtherpaper(this)); elements.add(new MCreatorResourcesTab(this)); elements.add(new MCreatorSulfur(this)); elements.add(new MCreatorSulfurore(this)); elements.add(new MCreatorResbone(this)); elements.add(new MCreatorBookwithblueprints(this)); elements.add(new MCreatorFishcanempty(this)); elements.add(new MCreatorScrap(this)); elements.add(new MCreatorBuildingplan(this)); elements.add(new MCreatorBeanscanempty(this)); elements.add(new MCreatorMushroom(this)); elements.add(new MCreatorWoodcoal(this)); elements.add(new MCreatorChickenmeatcooked(this)); elements.add(new MCreatorChickenmeatraw(this)); elements.add(new MCreatorPiecestone(this)); elements.add(new MCreatorPiecewood(this)); elements.add(new MCreatorMetalore(this)); elements.add(new MCreatorChocolatebar(this)); elements.add(new MCreatorMhq(this)); elements.add(new MCreatorFlq(this)); elements.add(new MCreatorExplosive(this)); elements.add(new MCreatorPipe(this)); elements.add(new MCreatorFhq(this)); elements.add(new MCreatorSewingkit(this)); elements.add(new MCreatorGears(this)); elements.add(new MCreatorOilRaw(this)); elements.add(new MCreatorSmgbody(this)); elements.add(new MCreatorSemiautomaticbody(this)); elements.add(new MCreatorRope(this)); elements.add(new MCreatorMetalSheet(this)); elements.add(new MCreatorResleather(this)); elements.add(new MCreatorRoadsign(this)); elements.add(new MCreatorCLoth(this)); elements.add(new MCreatorAnimalfat(this)); elements.add(new MCreatorHolographicsight(this)); elements.add(new MCreatorMetalfragments(this)); elements.add(new MCreatorMhqore(this)); elements.add(new MCreatorFishmeatcooked(this)); elements.add(new MCreatorBarkcactus(this)); elements.add(new MCreatorFishmeatraw(this)); elements.add(new MCreatorSilencer(this)); elements.add(new MCreatorGlue(this)); elements.add(new MCreatorRiflebody(this)); elements.add(new MCreatorResgunpowder(this)); elements.add(new MCreatorHumanmeatcooked(this)); elements.add(new MCreatorHumanmeatraw(this)); elements.add(new MCreatorBlackberryinfected(this)); elements.add(new MCreatorBlueberriesinfected(this)); elements.add(new MCreatorMuzzleaccelerator(this)); elements.add(new MCreatorSniperriflex8(this)); elements.add(new MCreatorLargemedkit(this)); elements.add(new MCreatorTank(this)); elements.add(new MCreatorLog(this)); elements.add(new MCreatorLock(this)); elements.add(new MCreatorCamera(this)); elements.add(new MCreatorMaplocation(this)); elements.add(new MCreatorPumpkin(this)); elements.add(new MCreatorCodelock(this)); elements.add(new MCreatorFishcan(this)); elements.add(new MCreatorFishcanuse(this)); elements.add(new MCreatorBearmeatcooked(this)); elements.add(new MCreatorBearmeatraw(this)); elements.add(new MCreatorMuzzlebrake(this)); elements.add(new MCreatorMuq(this)); elements.add(new MCreatorBlueprint(this)); elements.add(new MCreatorPlanksitem(this)); elements.add(new MCreatorBoarmeatcooked(this)); elements.add(new MCreatorBoardmeatraw(this)); elements.add(new MCreatorBlackberry(this)); elements.add(new MCreatorCrackers(this)); elements.add(new MCreatorAppleinfected(this)); elements.add(new MCreatorSnipersightx4(this)); elements.add(new MCreatorChip(this)); elements.add(new MCreatorCorn(this)); elements.add(new MCreatorShotgunbody(this)); elements.add(new MCreatorWolfmeatcooked(this)); elements.add(new MCreatorPistolbody(this)); elements.add(new MCreatorWolfmeatraw(this)); elements.add(new MCreatorBeanscanuse(this)); elements.add(new MCreatorBeanscan(this)); elements.add(new MCreatorBlades(this)); elements.add(new MCreatorTarp(this)); elements.add(new MCreatorMuqpre(this)); elements.add(new MCreatorLaser(this)); elements.add(new MCreatorLaptop(this)); elements.add(new MCreatorSmallstashitem(this)); elements.add(new MCreatorHammer(this)); elements.add(new MCreatorPieceblueprint(this)); elements.add(new MCreatorBigstonewall(this)); elements.add(new MCreatorWoodenkit(this)); elements.add(new MCreatorWolfkit(this)); elements.add(new MCreatorBuckethelmet(this)); elements.add(new MCreatorMhqkit(this)); elements.add(new MCreatorRedjacketkit(this)); elements.add(new MCreatorRoadsignkit(this)); elements.add(new MCreatorClothkit(this)); elements.add(new MCreatorBonekit(this)); elements.add(new MCreatorMetalaxe(this)); elements.add(new MCreatorMetalpickaxe(this)); elements.add(new MCreatorMetalsword(this)); elements.add(new MCreatorBonetool(this)); elements.add(new MCreatorKnife(this)); elements.add(new MCreatorHatchet(this)); elements.add(new MCreatorIronpickaxe(this)); elements.add(new MCreatorMachete(this)); elements.add(new MCreatorRoadsignbaton(this)); elements.add(new MCreatorMace(this)); elements.add(new MCreatorStoneaxe(this)); elements.add(new MCreatorStonepickaxe(this)); elements.add(new MCreatorLongsword(this)); elements.add(new MCreatorStonespear(this)); elements.add(new MCreatorWarhammer(this)); elements.add(new MCreatorBoneknife(this)); elements.add(new MCreatorWhiteblock(this)); elements.add(new MCreatorStone1(this)); elements.add(new MCreatorRoadblockline(this)); elements.add(new MCreatorRoadblock(this)); elements.add(new MCreatorStone2(this)); elements.add(new MCreatorStone3(this)); elements.add(new MCreatorStone4(this)); elements.add(new MCreatorStone5(this)); elements.add(new MCreatorCactus(this)); elements.add(new MCreatorGarageblock(this)); elements.add(new MCreatorTerraingrass4(this)); elements.add(new MCreatorTerrainGrass5(this)); elements.add(new MCreatorTerrainGrass6(this)); elements.add(new MCreatorGravel2(this)); elements.add(new MCreatorGravelsnow(this)); elements.add(new MCreatorGreenboxs(this)); elements.add(new MCreatorGreenstonebrick(this)); elements.add(new MCreatorJunglewood(this)); elements.add(new MCreatorLeaves1(this)); elements.add(new MCreatorLeaves2(this)); elements.add(new MCreatorLootboxdecor(this)); elements.add(new MCreatorMetal28(this)); elements.add(new MCreatorMetal29(this)); elements.add(new MCreatorMetal30(this)); elements.add(new MCreatorJungleleaves(this)); elements.add(new MCreatorMetal31(this)); elements.add(new MCreatorMetal32(this)); elements.add(new MCreatorMetal33(this)); elements.add(new MCreatorMetal34(this)); elements.add(new MCreatorMetal35(this)); elements.add(new MCreatorMetal36(this)); elements.add(new MCreatorMetal37(this)); elements.add(new MCreatorMetal38(this)); elements.add(new MCreatorStone6(this)); elements.add(new MCreatorMetal39(this)); elements.add(new MCreatorTile2(this)); elements.add(new MCreatorTile3(this)); elements.add(new MCreatorTerrainsanddark(this)); elements.add(new MCreatorSandlight(this)); elements.add(new MCreatorSandstone(this)); elements.add(new MCreatorTerrainstone5(this)); elements.add(new MCreatorTerrainstone6(this)); elements.add(new MCreatorSandlodark(this)); elements.add(new MCreatorLeavessnow(this)); elements.add(new MCreatorSnowlog(this)); elements.add(new MCreatorStone7(this)); elements.add(new MCreatorStone8(this)); elements.add(new MCreatorStone9(this)); elements.add(new MCreatorStone10(this)); elements.add(new MCreatorStone11(this)); elements.add(new MCreatorStone12(this)); elements.add(new MCreatorTerrainsandraw(this)); elements.add(new MCreatorTerraingrass7(this)); elements.add(new MCreatorTerrainstone7(this)); elements.add(new MCreatorTerraingrass8(this)); elements.add(new MCreatorTerrainstone8(this)); elements.add(new MCreatorTerrainstone9(this)); elements.add(new MCreatorStoneterrain10(this)); elements.add(new MCreatorTerrainstone11(this)); elements.add(new MCreatorTerrainstone12(this)); elements.add(new MCreatorTerraingrass9(this)); elements.add(new MCreatorTerraingrass10(this)); elements.add(new MCreatorWood1(this)); elements.add(new MCreatorWood2(this)); elements.add(new MCreatorWood3(this)); elements.add(new MCreatorBigchest(this)); elements.add(new MCreatorSmallchest(this)); elements.add(new MCreatorPlaceCHest(this)); elements.add(new MCreatorSmallstash(this)); elements.add(new MCreatorSmallStashgui(this)); elements.add(new MCreatorSmallstashOpen(this)); elements.add(new MCreatorSmallchestgui(this)); elements.add(new MCreatorBigchestgui(this)); elements.add(new MCreatorSmallchestopen(this)); elements.add(new MCreatorBigchestopen(this)); elements.add(new MCreatorStoneblock(this)); elements.add(new MCreatorMetaloreblock(this)); elements.add(new MCreatorSulfuroreblock(this)); elements.add(new MCreatorMhqoreblock(this)); elements.add(new MCreatorMuqoreblock(this)); elements.add(new MCreatorBuildingplanuse(this)); elements.add(new MCreatorSmallchestplace(this)); elements.add(new MCreatorBigstonewallplace(this)); elements.add(new MCreatorStone15(this)); elements.add(new MCreatorMetal40(this)); elements.add(new MCreatorMetal41(this)); elements.add(new MCreatorMetal42(this)); elements.add(new MCreatorGreenwoodplank1(this)); elements.add(new MCreatorMetal43(this)); elements.add(new MCreatorWhitewood(this)); elements.add(new MCreatorMetal44(this)); elements.add(new MCreatorMetal45(this)); elements.add(new MCreatorStone16(this)); elements.add(new MCreatorHaydetails1(this)); elements.add(new MCreatorMetal46(this)); elements.add(new MCreatorMetal47(this)); elements.add(new MCreatorStone17(this)); elements.add(new MCreatorHaydetails2(this)); elements.add(new MCreatorMetal48(this)); elements.add(new MCreatorMetal49(this)); elements.add(new MCreatorMetal50(this)); elements.add(new MCreatorTerraingrass11(this)); elements.add(new MCreatorWhitewoodplank(this)); elements.add(new MCreatorMetal51(this)); elements.add(new MCreatorMetal52(this)); elements.add(new MCreatorMetal53(this)); elements.add(new MCreatorTerraingrass12(this)); elements.add(new MCreatorWooddeafult(this)); elements.add(new MCreatorMetal54(this)); elements.add(new MCreatorMetal55(this)); elements.add(new MCreatorMetal56(this)); elements.add(new MCreatorTerraingravel1(this)); elements.add(new MCreatorStone18(this)); elements.add(new MCreatorMetal57(this)); elements.add(new MCreatorMetal58(this)); elements.add(new MCreatorTerrain(this)); elements.add(new MCreatorStone19(this)); elements.add(new MCreatorMetal59(this)); elements.add(new MCreatorMetal60(this)); elements.add(new MCreatorWoodplankgray(this)); elements.add(new MCreatorTerrain2(this)); elements.add(new MCreatorStone20(this)); elements.add(new MCreatorGarageblock2(this)); elements.add(new MCreatorMetal61(this)); elements.add(new MCreatorStone21(this)); elements.add(new MCreatorMetal62(this)); elements.add(new MCreatorMetal63(this)); elements.add(new MCreatorRocktool(this)); elements.add(new MCreatorMetal64(this)); elements.add(new MCreatorMetal65(this)); elements.add(new MCreatorMetal66(this)); elements.add(new MCreatorMetal67(this)); elements.add(new MCreatorWheel(this)); elements.add(new MCreatorStone22(this)); elements.add(new MCreatorStone23(this)); elements.add(new MCreatorGarbage2(this)); elements.add(new MCreatorGarbage3(this)); elements.add(new MCreatorRecycler(this)); elements.add(new MCreatorWoodBrokenExp(this)); elements.add(new MCreatorStoneBrokenExp(this)); elements.add(new MCreatorMetalBrokenEXP(this)); elements.add(new MCreatorArmoredBrokenEXP(this)); elements.add(new MCreatorUpinwood(this)); elements.add(new MCreatorUpinstone(this)); elements.add(new MCreatorUpinmetal(this)); elements.add(new MCreatorUpinmhq(this)); elements.add(new MCreatorHayfloorupinwood(this)); elements.add(new MCreatorHayWallupwood(this)); elements.add(new MCreatorWoodfloorupstone(this)); elements.add(new MCreatorWoodwallupstone(this)); elements.add(new MCreatorStonefloorupmetal(this)); elements.add(new MCreatorStoneWallupstone(this)); elements.add(new MCreatorMetalflooruparmored(this)); elements.add(new MCreatorMetalwalluparmored(this)); elements.add(new MCreatorStone13(this)); elements.add(new MCreatorStone14(this)); elements.add(new MCreatorBlood(this)); elements.add(new MCreatorMetalspring(this)); elements.add(new MCreatorBlueprint2(this)); elements.add(new MCreatorBiggift(this)); elements.add(new MCreatorHighgift(this)); elements.add(new MCreatorEmptybucket(this)); elements.add(new MCreatorFlare(this)); elements.add(new MCreatorSupplysignalgrenade(this)); elements.add(new MCreatorSticks(this)); elements.add(new MCreatorRawfish(this)); elements.add(new MCreatorScullhuman(this)); elements.add(new MCreatorKey(this)); elements.add(new MCreatorSeedpumpkin(this)); elements.add(new MCreatorSeedhemp(this)); elements.add(new MCreatorSmallgift(this)); elements.add(new MCreatorNote(this)); elements.add(new MCreatorCoal2(this)); elements.add(new MCreatorSeedcorn(this)); elements.add(new MCreatorStone24(this)); elements.add(new MCreatorBotabag(this)); elements.add(new MCreatorCandycane(this)); elements.add(new MCreatorCandyweapon(this)); elements.add(new MCreatorCornplant(this)); elements.add(new MCreatorHemp(this)); elements.add(new MCreatorPumpkinplant(this)); elements.add(new MCreatorGingerbreadmen(this)); elements.add(new MCreatorDucttape(this)); elements.add(new MCreatorGuitar(this)); elements.add(new MCreatorZombieflesh(this)); elements.add(new MCreatorSkullanimal(this)); elements.add(new MCreatorBinoculars(this)); elements.add(new MCreatorPhotocamera(this)); elements.add(new MCreatorCustomsight(this)); elements.add(new MCreatorAssemblychips(this)); elements.add(new MCreatorAveragerustcase(this)); elements.add(new MCreatorBearskull(this)); elements.add(new MCreatorBigrustcase(this)); elements.add(new MCreatorBlueelectricaltape(this)); elements.add(new MCreatorBolts(this)); elements.add(new MCreatorBronzeegg(this)); elements.add(new MCreatorEmptyrustycan(this)); elements.add(new MCreatorFewchip(this)); elements.add(new MCreatorSmallfishs(this)); elements.add(new MCreatorGoldegg(this)); elements.add(new MCreatorButt(this)); elements.add(new MCreatorImprovedsewingkit(this)); elements.add(new MCreatorJunkdetails(this)); elements.add(new MCreatorMuzzleCompensatorMedium(this)); elements.add(new MCreatorMuzzleflashhider(this)); elements.add(new MCreatorMuzzleCompensators(this)); elements.add(new MCreatorMuzzleCompensatorlight(this)); elements.add(new MCreatorMuzzleFlashHiderlight(this)); elements.add(new MCreatorMuzzleFlashHidersmall(this)); elements.add(new MCreatorNails(this)); elements.add(new MCreatorNippers(this)); elements.add(new MCreatorSilveregg(this)); elements.add(new MCreatorSmallrustcase(this)); elements.add(new MCreatorStrongrope(this)); elements.add(new MCreatorTacticalstockcapture(this)); elements.add(new MCreatorVerticalhandle(this)); elements.add(new MCreatorZombiebearflesh(this)); elements.add(new MCreatorZombiechickenflesh(this)); elements.add(new MCreatorZombiehorseflesh(this)); elements.add(new MCreatorZombiewolfflesh(this)); elements.add(new MCreatorHumanskulldestroyinbone(this)); elements.add(new MCreatorAnimalskulldestroyinbone(this)); elements.add(new MCreatorBearskulldestroyinbone(this)); elements.add(new MCreatorAmmobox(this)); elements.add(new MCreatorBoxammopistol(this)); elements.add(new MCreatorBox12Guages(this)); elements.add(new MCreatorBoxammo556(this)); elements.add(new MCreatorAngledForeGrip(this)); elements.add(new MCreatorUziStock(this)); elements.add(new MCreatorProjectTAB(this)); elements.add(new MCreatorMrcoin(this)); elements.add(new MCreatorMrdiamond(this)); elements.add(new MCreatorBronzekey(this)); elements.add(new MCreatorSilverkey(this)); elements.add(new MCreatorGoldkey(this)); elements.add(new MCreatorMapopengui(this)); elements.add(new MCreatorMapopen(this)); elements.add(new MCreatorCreativeupgradehammer(this)); elements.add(new MCreatorWoodplanksblock(this)); elements.add(new MCreatorWoodbarricade(this)); elements.add(new MCreatorStonebarricade(this)); elements.add(new MCreatorSandbags(this)); elements.add(new MCreatorEasyclothes(this)); elements.add(new MCreatorBeans(this)); elements.add(new MCreatorBeansinfected(this)); elements.add(new MCreatorGeologicalcharge(this)); elements.add(new MCreatorSmallstones(this)); elements.add(new MCreatorTurquoiseclothesskirt(this)); elements.add(new MCreatorBlackclothesskirt(this)); elements.add(new MCreatorSpecialforceshelmet(this)); elements.add(new MCreatorAntiradFoodEatenUSE(this)); elements.add(new MCreatorAntirad(this)); elements.add(new MCreatorSupplySignalairdrop(this)); elements.add(new MCreatorFuq(this)); elements.add(new MCreatorOldcloth(this)); elements.add(new MCreatorBeangrenadefragment(this)); elements.add(new MCreatorJunk(this)); elements.add(new MCreatorQualitydetails(this)); elements.add(new MCreatorJunkcan(this)); elements.add(new MCreatorGreenkeycard(this)); elements.add(new MCreatorRedkeycard(this)); elements.add(new MCreatorBluekeycard(this)); elements.add(new MCreatorYellowkeycard(this)); elements.add(new MCreatorLightgreenkeycard(this)); elements.add(new MCreatorCarbattery(this)); elements.add(new MCreatorElectricFuse(this)); elements.add(new MCreatorOnefullassemblychip(this)); elements.add(new MCreatorSuperglue(this)); elements.add(new MCreatorWheels(this)); elements.add(new MCreatorWires(this)); elements.add(new MCreatorWirestool(this)); elements.add(new MCreatorSleepingbag(this)); elements.add(new MCreatorWeaponbox(this)); elements.add(new MCreatorSleepingbagsetspawnpoint(this)); elements.add(new MCreatorBuildCloth(this)); elements.add(new MCreatorBrokeCloth(this)); elements.add(new MCreatorBuildSandbags(this)); elements.add(new MCreatorBuildWoodBarricade(this)); elements.add(new MCreatorBuildStoneBarricade(this)); elements.add(new MCreatorAssemblyblueprints(this)); elements.add(new MCreatorClothesskirt(this)); elements.add(new MCreatorLeatherarmor(this)); elements.add(new MCreatorLeathergloves(this)); elements.add(new MCreatorBlackjacketsnow(this)); elements.add(new MCreatorShirtclothes(this)); elements.add(new MCreatorGreenclothesskirt(this)); elements.add(new MCreatorHeavyarmor(this)); elements.add(new MCreatorHeavyarmorEffect(this)); elements.add(new MCreatorFlashlight(this)); elements.add(new MCreatorSpinnerwheel(this)); elements.add(new MCreatorPookiebear(this)); } @Override public int getBurnTime(ItemStack fuel) { for (ModElement element : elements) { int ret = element.addFuel(fuel); if (ret != 0) return ret; } return 0; } @Override public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator cg, IChunkProvider cp) { elements.forEach(element -> element.generateWorld(random, chunkX * 16, chunkZ * 16, world, world.provider.getDimension(), cg, cp)); } @SubscribeEvent public void registerBlocks(RegistryEvent.Register<Block> event) { event.getRegistry().registerAll(blocks.stream().map(Supplier::get).toArray(Block[]::new)); } @SubscribeEvent public void registerItems(RegistryEvent.Register<Item> event) { event.getRegistry().registerAll(items.stream().map(Supplier::get).toArray(Item[]::new)); } @SubscribeEvent public void registerBiomes(RegistryEvent.Register<Biome> event) { event.getRegistry().registerAll(biomes.stream().map(Supplier::get).toArray(Biome[]::new)); } @SubscribeEvent public void registerEntities(RegistryEvent.Register<EntityEntry> event) { event.getRegistry().registerAll(entities.stream().map(Supplier::get).toArray(EntityEntry[]::new)); } @SubscribeEvent public void registerPotions(RegistryEvent.Register<Potion> event) { event.getRegistry().registerAll(potions.stream().map(Supplier::get).toArray(Potion[]::new)); } @SubscribeEvent public void registerSounds(RegistryEvent.Register<net.minecraft.util.SoundEvent> event) { ResourceLocation sound0 = new ResourceLocation("minerustaddonsmod", "broke.wood"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound0).setRegistryName(sound0)); ResourceLocation sound1 = new ResourceLocation("minerustaddonsmod", "broke.stone"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound1).setRegistryName(sound1)); ResourceLocation sound2 = new ResourceLocation("minerustaddonsmod", "build.wood1"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound2).setRegistryName(sound2)); ResourceLocation sound3 = new ResourceLocation("minerustaddonsmod", "eat.food"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound3).setRegistryName(sound3)); ResourceLocation sound4 = new ResourceLocation("minerustaddonsmod", "build.metal"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound4).setRegistryName(sound4)); ResourceLocation sound5 = new ResourceLocation("minerustaddonsmod", "eat.infected"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound5).setRegistryName(sound5)); ResourceLocation sound6 = new ResourceLocation("minerustaddonsmod", "build.stone"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound6).setRegistryName(sound6)); ResourceLocation sound7 = new ResourceLocation("minerustaddonsmod", "use.syringe"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound7).setRegistryName(sound7)); ResourceLocation sound8 = new ResourceLocation("minerustaddonsmod", "build.armored"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound8).setRegistryName(sound8)); ResourceLocation sound9 = new ResourceLocation("minerustaddonsmod", "broke.metal"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound9).setRegistryName(sound9)); ResourceLocation sound10 = new ResourceLocation("minerustaddonsmod", "use.bandage"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound10).setRegistryName(sound10)); ResourceLocation sound11 = new ResourceLocation("minerustaddonsmod", "chest.place"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound11).setRegistryName(sound11)); ResourceLocation sound12 = new ResourceLocation("minerustaddonsmod", "smallstash.open"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound12).setRegistryName(sound12)); ResourceLocation sound13 = new ResourceLocation("minerustaddonsmod", "chest.open"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound13).setRegistryName(sound13)); ResourceLocation sound14 = new ResourceLocation("minerustaddonsmod", "smallchestopen"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound14).setRegistryName(sound14)); ResourceLocation sound15 = new ResourceLocation("minerustaddonsmod", "smallstash.place"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound15).setRegistryName(sound15)); ResourceLocation sound16 = new ResourceLocation("minerustaddonsmod", "smallchest.place"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound16).setRegistryName(sound16)); ResourceLocation sound17 = new ResourceLocation("minerustaddonsmod", "broken.structure"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound17).setRegistryName(sound17)); ResourceLocation sound18 = new ResourceLocation("minerustaddonsmod", "bigstonewall.place"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound18).setRegistryName(sound18)); ResourceLocation sound19 = new ResourceLocation("minerustaddonsmod", "broken.stone"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound19).setRegistryName(sound19)); ResourceLocation sound20 = new ResourceLocation("minerustaddonsmod", "broken.wood"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound20).setRegistryName(sound20)); ResourceLocation sound21 = new ResourceLocation("minerustaddonsmod", "metal.broken"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound21).setRegistryName(sound21)); ResourceLocation sound22 = new ResourceLocation("minerustaddonsmod", "armored.broken"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound22).setRegistryName(sound22)); ResourceLocation sound23 = new ResourceLocation("minerustaddonsmod", "build.wood2"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound23).setRegistryName(sound23)); ResourceLocation sound24 = new ResourceLocation("minerustaddonsmod", "click.interact"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound24).setRegistryName(sound24)); ResourceLocation sound25 = new ResourceLocation("minerustaddonsmod", "broke.cloth"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound25).setRegistryName(sound25)); ResourceLocation sound26 = new ResourceLocation("minerustaddonsmod", "place.stonebarricade"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound26).setRegistryName(sound26)); ResourceLocation sound27 = new ResourceLocation("minerustaddonsmod", "place.woodbarricade"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound27).setRegistryName(sound27)); ResourceLocation sound28 = new ResourceLocation("minerustaddonsmod", "place.window"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound28).setRegistryName(sound28)); ResourceLocation sound29 = new ResourceLocation("minerustaddonsmod", "place.sleepingbag"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound29).setRegistryName(sound29)); ResourceLocation sound30 = new ResourceLocation("minerustaddonsmod", "place.sandbags"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound30).setRegistryName(sound30)); ResourceLocation sound31 = new ResourceLocation("minerustaddonsmod", "place.metalwindow2"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound31).setRegistryName(sound31)); ResourceLocation sound32 = new ResourceLocation("minerustaddonsmod", "place.metalwindow"); event.getRegistry().register(new net.minecraft.util.SoundEvent(sound32).setRegistryName(sound32)); } @SubscribeEvent @SideOnly(Side.CLIENT) public void registerModels(ModelRegistryEvent event) { elements.forEach(element -> element.registerModels(event)); } @EventHandler public void preInit(FMLPreInitializationEvent event) { MinecraftForge.EVENT_BUS.register(this); GameRegistry.registerFuelHandler(this); GameRegistry.registerWorldGenerator(this, 5); NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler()); elements.forEach(element -> element.preInit(event)); proxy.preInit(event); } @EventHandler public void init(FMLInitializationEvent event) { elements.forEach(element -> element.init(event)); proxy.init(event); } @EventHandler public void serverLoad(FMLServerStartingEvent event) { elements.forEach(element -> element.serverLoad(event)); } public static class GuiHandler implements IGuiHandler { @Override public Object getServerGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) { if (id == MCreatorSmallStashgui.GUIID) return new MCreatorSmallStashgui.GuiContainerMod(world, x, y, z, player); if (id == MCreatorSmallchestgui.GUIID) return new MCreatorSmallchestgui.GuiContainerMod(world, x, y, z, player); if (id == MCreatorBigchestgui.GUIID) return new MCreatorBigchestgui.GuiContainerMod(world, x, y, z, player); if (id == MCreatorMapopengui.GUIID) return new MCreatorMapopengui.GuiContainerMod(world, x, y, z, player); return null; } @Override public Object getClientGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) { if (id == MCreatorSmallStashgui.GUIID) return new MCreatorSmallStashgui.GuiWindow(world, x, y, z, player); if (id == MCreatorSmallchestgui.GUIID) return new MCreatorSmallchestgui.GuiWindow(world, x, y, z, player); if (id == MCreatorBigchestgui.GUIID) return new MCreatorBigchestgui.GuiWindow(world, x, y, z, player); if (id == MCreatorMapopengui.GUIID) return new MCreatorMapopengui.GuiWindow(world, x, y, z, player); return null; } } public static class ModElement { public static minerustaddonsmod instance; public ModElement(minerustaddonsmod instance) { this.instance = instance; } public void init(FMLInitializationEvent event) { } public void preInit(FMLPreInitializationEvent event) { } public void generateWorld(Random random, int posX, int posZ, World world, int dimID, IChunkGenerator cg, IChunkProvider cp) { } public void serverLoad(FMLServerStartingEvent event) { } public void registerModels(ModelRegistryEvent event) { } public int addFuel(ItemStack fuel) { return 0; } } }
47.855228
164
0.785826
85dc266de3f9c4fe62678f9ca5f981fdf942fe69
58
/** * JPA domain objects. */ package mark.quinn.domain;
11.6
26
0.655172
8c146afe2e8c964fc5a41f03d31ee73767fd5ac8
1,955
package top.codemc.liveappuidemo.fragment; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import top.codemc.liveappuidemo.R; /** * * Created by xiyoumc on 16/8/22. */ public class LiveFragment extends Fragment implements View.OnClickListener { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_create_live, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initView(view); } public void initView(View view) { LinearLayout location_layout = (LinearLayout) view.findViewById(R.id.location_layout); location_layout.setOnClickListener(this); ImageView close_bt = (ImageView) view.findViewById(R.id.close_bt); close_bt.setOnClickListener(this); EditText edit_room_name = (EditText) view.findViewById(R.id.edit_room_name); edit_room_name.setOnClickListener(this); LinearLayout layout_topic = (LinearLayout) view.findViewById(R.id.layout_topic); layout_topic.setOnClickListener(this); Button create_live_bt = (Button) view.findViewById(R.id.create_live_bt); create_live_bt.setOnClickListener(this); } @Override public void onClick(View v) { int id = v.getId(); if (R.id.location_layout == id) { } else if (R.id.close_bt == id) { } else if (R.id.edit_room_name == id) { } else if (R.id.layout_topic == id) { } else if (R.id.create_live_bt == id) { } } }
29.179104
103
0.703836
2154de01861f2534719d70559f56180fcd9bbc9d
408
package frc.robot.commands.shooter; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.Shooter; public class StopShooter extends CommandBase { private Shooter shooter; public StopShooter(Shooter shooter) { this.shooter = shooter; addRequirements(this.shooter); } @Override public void execute() { this.shooter.setSpeed(0); } }
20.4
50
0.698529
98c506d197890958da8de78b61df2f39ab8bd2d7
3,048
/******************************************************************************* * Copyright 2013 Ednovo d/b/a Gooru. All rights reserved. * * http://www.goorulearning.org/ * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ package org.ednovo.gooru.client.mvp.play.collection.share.email; import org.ednovo.gooru.client.uc.PlayerBundle; import org.ednovo.gooru.shared.util.MessageProperties; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.Widget; public class SentEmailSuccessVc extends PopupPanel implements MessageProperties{ private static SentEmailSuccessVcUiBinder uiBinder = GWT .create(SentEmailSuccessVcUiBinder.class); interface SentEmailSuccessVcUiBinder extends UiBinder<Widget, SentEmailSuccessVc> { } @UiField Label okLbl,toEmailLbl; @UiField HTMLPanel emailToFriendText,thanksEmailText; /** * Class constructor , create a new pop up * @param toEmail */ public SentEmailSuccessVc(String toEmail) { setWidget(uiBinder.createAndBindUi(this)); toEmailLbl.setText(toEmail); this.setGlassEnabled(true); this.setGlassStyleName(PlayerBundle.INSTANCE.getPlayerStyle().setGlassPanelStyle()); this.getElement().getStyle().setZIndex(99999); this.show(); this.center(); emailToFriendText.getElement().setInnerHTML(GL0222); thanksEmailText.getElement().setInnerHTML(GL0648); okLbl.setText(GL0190); } /** * Hide {@link SentEmailSuccessVc} popup * @param clickEvent instOLance of {@link ClickEvent} */ @UiHandler("okLbl") public void onBtnClick(ClickEvent clickEvent) { hide(); } }
36.285714
86
0.725722
8f9693f2685588f47e73963897f57ef6e1ae2a7d
5,728
package com.sigma.dao.blockchain; import com.google.protobuf.ByteString; import com.sigma.dao.constant.TendermintQuery; import com.sigma.dao.constant.TendermintTransaction; import com.sigma.dao.service.NetworkConfigService; import io.grpc.stub.StreamObserver; import lombok.extern.slf4j.Slf4j; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.stereotype.Component; import tendermint.abci.Types; import java.util.Base64; @Slf4j @Component public class TendermintBlockchain extends tendermint.abci.ABCIApplicationGrpc.ABCIApplicationImplBase { private final NetworkConfigService networkConfigService; private final TendermintTransactionHandler tendermintTransactionHandler; private final TendermintQueryHandler tendermintQueryHandler; public TendermintBlockchain(NetworkConfigService networkConfigService, TendermintTransactionHandler tendermintTransactionHandler, TendermintQueryHandler tendermintQueryHandler) { this.networkConfigService = networkConfigService; this.tendermintTransactionHandler = tendermintTransactionHandler; this.tendermintQueryHandler = tendermintQueryHandler; } @Override public void initChain(Types.RequestInitChain req, StreamObserver<Types.ResponseInitChain> responseObserver) { var resp = Types.ResponseInitChain.newBuilder().build(); final JSONObject appState = new JSONObject(req.getAppStateBytes().toStringUtf8()); networkConfigService.initializeNetworkConfig(appState); responseObserver.onNext(resp); responseObserver.onCompleted(); } @Override public void info(Types.RequestInfo request, StreamObserver<tendermint.abci.Types.ResponseInfo> responseObserver) { var resp = Types.ResponseInfo.newBuilder().build(); responseObserver.onNext(resp); responseObserver.onCompleted(); } @Override public void echo(Types.RequestEcho request, StreamObserver<tendermint.abci.Types.ResponseEcho> responseObserver) { var resp = Types.ResponseEcho.newBuilder().build(); responseObserver.onNext(resp); responseObserver.onCompleted(); } @Override public void checkTx(Types.RequestCheckTx req, StreamObserver<Types.ResponseCheckTx> responseObserver) { var resp = Types.ResponseCheckTx.newBuilder() .setCode(0) .setGasWanted(1) .build(); responseObserver.onNext(resp); responseObserver.onCompleted(); } @Override public void beginBlock(Types.RequestBeginBlock req, StreamObserver<Types.ResponseBeginBlock> responseObserver) { var resp = Types.ResponseBeginBlock.newBuilder().build(); networkConfigService.setTimestamp(req.getHeader().getTime().getSeconds()); responseObserver.onNext(resp); responseObserver.onCompleted(); } @Override public void deliverTx(Types.RequestDeliverTx req, StreamObserver<Types.ResponseDeliverTx> responseObserver) { var tx = req.getTx(); Types.ResponseDeliverTx.Builder builder = Types.ResponseDeliverTx.newBuilder(); Types.ResponseDeliverTx resp; try { JSONObject jsonObject = new JSONObject(new String(Base64.getDecoder().decode(tx.toStringUtf8()))); TendermintTransaction transaction = TendermintTransaction.valueOf(jsonObject.getString("tx")); ByteString data = tendermintTransactionHandler.process(transaction, jsonObject); resp = builder.setCode(0).setData(data).build(); } catch(Exception e) { resp = builder.setCode(1).setData(ByteString.copyFromUtf8( new JSONObject().put("error", e.getMessage()).toString())).build(); } responseObserver.onNext(resp); responseObserver.onCompleted(); } @Override public void commit(Types.RequestCommit req, StreamObserver<Types.ResponseCommit> responseObserver) { var resp = Types.ResponseCommit.newBuilder() .setData(ByteString.copyFrom(new byte[8])) // TODO - this should hash the entire app state (dump from all DB tables sorted by UUID) .build(); responseObserver.onNext(resp); responseObserver.onCompleted(); } @Override public void endBlock(Types.RequestEndBlock req, StreamObserver<Types.ResponseEndBlock> responseObserver) { var resp = Types.ResponseEndBlock.newBuilder().build(); // TODO - scheduled stuff can happen here at the end of the block responseObserver.onNext(resp); responseObserver.onCompleted(); } @Override public void query(Types.RequestQuery req, StreamObserver<Types.ResponseQuery> responseObserver) { var data = req.getData(); Types.ResponseQuery.Builder builder = Types.ResponseQuery.newBuilder(); Types.ResponseQuery resp; try { JSONObject jsonObject = new JSONObject(new String(Base64.getDecoder().decode(data.toStringUtf8()))); TendermintQuery query = TendermintQuery.valueOf(jsonObject.getString("query")); String result = tendermintQueryHandler.process(query, jsonObject); try { resp = builder.setCode(0).setLog(new JSONObject(result).toString()).build(); } catch(Exception e) { resp = builder.setCode(0).setLog(new JSONArray(result).toString()).build(); } } catch(Exception e) { resp = builder.setCode(1).setLog(new JSONObject().put("error", e.getMessage()).toString()).build(); } responseObserver.onNext(resp); responseObserver.onCompleted(); } }
44.75
147
0.70007
a6ebf1eac2accb8ae5e5512ff01bd5ec54c31b5c
371
package com.rabbit.samples.springreactivewebsocket; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringReactiveWebSocketApplication { public static void main(String[] args) { SpringApplication.run(SpringReactiveWebSocketApplication.class, args); } }
23.1875
72
0.84097
62daefebf6971734fc6dae5cae8620136fefe240
7,026
/******************************************************************************** * * Copyright FUJITSU LIMITED 2020 * *******************************************************************************/ package org.oscm.app.connector.activity; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.oscm.app.connector.framework.Activity; import org.oscm.app.connector.framework.ProcessException; import org.oscm.app.connector.util.SpringBeanSupport; import java.sql.*; import java.util.Map; import java.util.Properties; public class DatabaseReader extends Activity { private static Logger logger = LogManager.getLogger(DatabaseReader.class); String statement = null; String url, driver, username, password, namespace = ""; /** * Just calls the base class constructor. */ public DatabaseReader() { super(); } /** * Implements the abstract method from the base class. This method will be * called from the base class when the configuration is passed down the * chain. How configuration works is described in bean definition file. A * configuration parameter is described in the javadoc of the class that * uses the configuration parameter. * * @param props the configuration paramters * @see Activity */ @Override public void doConfigure(java.util.Properties props) throws ProcessException { logger.debug("beanName: " + getBeanName()); url = SpringBeanSupport.getProperty(props, SpringBeanSupport.URL, null); driver = SpringBeanSupport.getProperty(props, SpringBeanSupport.DRIVER, null); username = SpringBeanSupport.getProperty(props, SpringBeanSupport.USER, null); password = SpringBeanSupport.getProperty(props, SpringBeanSupport.PASSWORD, null); if (url == null) { throwProcessException(SpringBeanSupport.URL); } if (driver == null) { throwProcessException(SpringBeanSupport.DRIVER); } if (username == null) { throwProcessException(SpringBeanSupport.USER); } if (password == null) { throwProcessException(SpringBeanSupport.PASSWORD); } } public void setStatement(String statement) { this.statement = statement; } public void setNamespace(String namespace) { this.namespace = namespace + "."; } /** * Overrides the base class method. * * @see Activity */ @Override public Map<String, String> transmitReceiveData( Map<String, String> transmitData) throws ProcessException { logger.debug("beanName: " + getBeanName() + " statement: " + statement); if (statement == null) { logger.error("beanName: " + getBeanName() + " missing SQL statement in bean configuration"); throw new ProcessException( "beanName: " + getBeanName() + " missing SQL statement in bean configuration", ProcessException.CONFIG_ERROR); } while (statement.indexOf("$(") >= 0) { int beginIndex = statement.indexOf("$("); String first = statement.substring(0, beginIndex); String rest = statement.substring(beginIndex + 2); String key = rest.substring(0, rest.indexOf(")")); if (!transmitData.containsKey(key)) { logger.error("beanName: " + getBeanName() + " key " + key + " from SQL statement is not defined as property"); throw new ProcessException( "beanName: " + getBeanName() + " key " + key + " from SQL statement is not defined as property", ProcessException.CONFIG_ERROR); } statement = first + transmitData.get(key) + rest.substring(rest.indexOf(")") + 1, rest.length()); } Connection conn = null; Statement stmt = null; ResultSet resultSet = null; try { Class.forName(driver); Properties props = new Properties(); props.setProperty("user", username); props.setProperty("password", password); conn = DriverManager.getConnection(url, props); conn.setAutoCommit(false); stmt = conn.createStatement(); resultSet = stmt.executeQuery(statement); ResultSetMetaData metadata = resultSet.getMetaData(); int columnCount = metadata.getColumnCount(); String[] columnNames = new String[columnCount]; for (int i = 0; i < columnCount; i++) { columnNames[i] = metadata.getColumnName(i + 1); } while (resultSet.next()) { for (int i = 0; i < columnCount; i++) { String value = resultSet.getString(i + 1); logger.debug(columnNames[i] + ": " + value); transmitData.put(namespace + columnNames[i], value); } } } catch (ClassNotFoundException e) { logger.error( String.format("beanName: %s Failed to load database driver class %s", getBeanName(), driver), e); throw new ProcessException( "beanName: " + getBeanName() + " Failed to load database driver class " + driver, ProcessException.CONFIG_ERROR); } catch (SQLException e) { logger.error("beanName: " + getBeanName() + " Failed to execute statement " + statement, e); throw new ProcessException( "beanName: " + getBeanName() + " Failed to execute statement " + statement, ProcessException.ERROR); } finally { try { if (resultSet != null) { resultSet.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { } } if (getNextActivity() == null) { return transmitData; } else { return getNextActivity().transmitReceiveData(transmitData); } } private void throwProcessException(String configurableProperty) throws ProcessException { logger.error(String.format("beanName: %s The property \"%s\" is not set.", getBeanName(), configurableProperty)); throw new ProcessException( "beanName: " + getBeanName() + " The property \"" + configurableProperty + "\" is not set.", ProcessException.CONFIG_ERROR); } }
37.174603
121
0.54583
2d384690a5595d1081388d4818ffbe89a198aeb0
5,473
/* * Copyright (c) 2019 by Andrew Charneski. * * The author 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.simiacryptus.mindseye.texture_generation; import com.simiacryptus.mindseye.ImageScript; import com.simiacryptus.mindseye.applications.ArtistryUtil; import com.simiacryptus.mindseye.applications.ColorTransfer; import com.simiacryptus.mindseye.applications.ImageArtUtil; import com.simiacryptus.mindseye.applications.TextureGeneration; import com.simiacryptus.mindseye.lang.Tensor; import com.simiacryptus.mindseye.lang.cudnn.Precision; import com.simiacryptus.mindseye.models.CVPipe_Inception; import com.simiacryptus.mindseye.test.TestUtil; import com.simiacryptus.mindseye.util.ImageUtil; import com.simiacryptus.notebook.NotebookOutput; import javax.annotation.Nonnull; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; public abstract class HiDef extends ImageScript { public final double coeff_style_mean; public final double coeff_style_cov; public final String[] styleSources; public final int resolution; public final double dreamCoeff; public HiDef( final double coeff_style_mean, final double coeff_style_cov, final double dreamCoeff, final int resolution, final String... styleSources ) { this.coeff_style_mean = coeff_style_mean; this.coeff_style_cov = coeff_style_cov; this.dreamCoeff = dreamCoeff; this.resolution = resolution; this.styleSources = styleSources; } public void accept(@Nonnull NotebookOutput log) { TextureGeneration.Inception textureGeneration = new TextureGeneration.Inception(); Precision precision = Precision.Float; textureGeneration.parallelLossFunctions = true; textureGeneration.setTiling(3); log.p("Style Source:"); for (final CharSequence styleSource : styleSources) { log.p(log.png(ArtistryUtil.load(styleSource, resolution), "Style Image")); } final Map<List<CharSequence>, TextureGeneration.StyleCoefficients<CVPipe_Inception.Strata>> styles = TestUtil.buildMap(x -> { TextureGeneration.StyleCoefficients<CVPipe_Inception.Strata> styleCoefficients = new TextureGeneration.StyleCoefficients<>( TextureGeneration.CenteringMode.Origin); for (final CVPipe_Inception.Strata layer : getLayers()) { styleCoefficients.set( layer, coeff_style_mean, coeff_style_cov, dreamCoeff ); } x.put( Arrays.asList(styleSources), styleCoefficients ); }); final AtomicReference<Tensor> canvas = new AtomicReference<>(ArtistryUtil.paint_Plasma(3, 1000.0, 1.1, resolution)); canvas.set(log.subreport(sublog -> { ColorTransfer<CVPipe_Inception.Strata, CVPipe_Inception> contentColorTransform = new ColorTransfer.Inception() { }.setOrtho(false); //colorSyncContentCoeffMap.set(CVPipe_Inception.Strata.Layer_1a, 1e-1); int colorSyncResolution = 600; Tensor resizedCanvas = Tensor.fromRGB(ImageUtil.resize(canvas.get().toImage(), colorSyncResolution)); final ColorTransfer.StyleSetup<CVPipe_Inception.Strata> styleSetup = ImageArtUtil.getColorAnalogSetup( Arrays.asList(styleSources), precision, resizedCanvas, ImageArtUtil.getStyleImages( colorSyncResolution, styleSources ), CVPipe_Inception.Strata.Layer_1 ); contentColorTransform.transfer( sublog, resizedCanvas, styleSetup, getTrainingMinutes(), contentColorTransform.measureStyle(styleSetup), getMaxIterations(), isVerbose() ); return contentColorTransform.forwardTransform(canvas.get()); }, log.getName() + "_" + "Color_Space_Analog")); TextureGeneration.StyleSetup<CVPipe_Inception.Strata> styleSetup = new TextureGeneration.StyleSetup<>( precision, TestUtil.buildMap(y -> y.putAll( styles.keySet().stream().flatMap( x -> x.stream()) .collect(Collectors.toMap( x -> x, file -> ArtistryUtil.load( file, resolution ) )))), styles ); log.p("Input Parameters:"); log.eval(() -> { return ArtistryUtil.toJson(styleSetup); }); textureGeneration.optimize( log, textureGeneration.measureStyle(styleSetup), canvas.get(), getTrainingMinutes(), getMaxIterations(), isVerbose(), styleSetup.precision ); } @Nonnull public abstract List<CVPipe_Inception.Strata> getLayers(); }
36.731544
130
0.676777
f85c317704aa99285df7ed450aff5fb140f14485
1,016
package g0101_0200.s0150_evaluate_reverse_polish_notation; // #Medium #Top_Interview_Questions #Array #Math #Stack #Programming_Skills_II_Day_3 // #2022_02_23_Time_12_ms_(29.56%)_Space_44.8_MB_(8.19%) import java.util.Stack; @SuppressWarnings("java:S1149") public class Solution { public int evalRPN(String[] tokens) { Stack<Integer> st = new Stack<>(); for (String token : tokens) { if (!Character.isDigit(token.charAt(token.length() - 1))) { st.push(eval(st.pop(), st.pop(), token)); } else { st.push(Integer.parseInt(token)); } } return st.pop(); } private int eval(int second, int first, String operator) { switch (operator) { case "+": return first + second; case "-": return first - second; case "*": return first * second; default: return first / second; } } }
29.028571
84
0.545276
ae5321368e46a0035bfec7917b3144eb16ee18f5
144
package de.hswhameln.typetogether.networking.api; public interface User { int getId(); String getName(); Document getDocument(); }
18
49
0.708333
59d0cdc9cd1f395d6acd35ffe2fe845d320aa640
635
import java.util.Scanner; public class Aula0010 { public static void main(String[] args) { // int num; // num = 11; // // if(num == 10){ // System.out.println("sim, é igual"); // }else{ // System.out.println("não, o número não é"); // // } int num; System.out.println("Digite o número 1: "); Scanner in = new Scanner( System.in ); num = in.nextInt(); if(num==1){ System.out.println("Obrigado por digitar o número 1"); }else{ System.out.println("O número digitado não é igual a 1"); } } }
24.423077
68
0.497638
933a93a40932f8c9e8e3c4e38609ba33c51dba13
13,194
/* * Serposcope - SEO rank checker https://serposcope.serphacker.com/ * * Copyright (c) 2016 SERP Hacker * @author Pierre Nogues <support@serphacker.com> * @license https://opensource.org/licenses/MIT MIT License */ package serposcope.controllers.admin; import com.google.inject.Inject; import com.google.inject.Singleton; import com.serphacker.serposcope.db.base.BaseDB; import com.serphacker.serposcope.db.base.RunDB; import com.serphacker.serposcope.db.google.GoogleDB; import com.serphacker.serposcope.di.TenantResolver; import com.serphacker.serposcope.models.base.Group; import static com.serphacker.serposcope.models.base.Group.Module.GOOGLE; import com.serphacker.serposcope.models.base.Run; import com.serphacker.serposcope.models.base.User; import com.serphacker.serposcope.models.base.Run.Mode; import com.serphacker.serposcope.models.base.Run.Status; import com.serphacker.serposcope.models.google.GoogleSearch; import com.serphacker.serposcope.models.google.GoogleTarget; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; import java.util.Set; import ninja.Context; import ninja.FilterWith; import ninja.Result; import ninja.Results; import ninja.Router; import ninja.params.Param; import ninja.session.FlashScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import serposcope.controllers.BaseController; import serposcope.filters.AdminFilter; import serposcope.filters.AuthFilter; import serposcope.filters.MaintenanceFilter; import serposcope.filters.XSRFFilter; import com.serphacker.serposcope.task.TaskManager; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import ninja.params.PathParam; import serposcope.controllers.HomeController; @Singleton @FilterWith(AuthFilter.class) public class TaskController extends BaseController { private static final Logger LOG = LoggerFactory.getLogger(TaskController.class); @Inject TaskManager taskManager; @Inject GoogleDB googleDB; @Inject BaseDB baseDB; @Inject Router router; @Inject TenantResolver resolver; public Result debug() { return Results .ok(); } public Result myTasks(Context context, @Param("page") Integer page ) { User user = context.getAttribute("user", User.class); List<Run> running = taskManager.listRunningTasks(user); List<Run> waiting = baseDB.run.listByStatus(Arrays.asList(Status.WAITING), null, null, user); if (page == null) { page = 0; } long limit = 50; long offset = page * limit; List<Run> done = baseDB.run.listByStatus(RunDB.STATUSES_DONE, limit, offset, user); Integer previousPage = page > 0 ? (page - 1) : null; Integer nextPage = done.size() == limit ? (page + 1) : null; return Results.ok() .template("serposcope/views/admin/TaskController/tasks.ftl.html") .render("previousPage", previousPage) .render("nextPage", nextPage) .render("running", running) .render("waiting", waiting) .render("done", done); } public Result tasks(Context context, @Param("page") Integer page ) { List<Run> running = taskManager.listRunningTasks(null); List<Run> waiting = baseDB.run.listByStatus(Arrays.asList(Status.WAITING), null, null, null); if (page == null) { page = 0; } long limit = 50; long offset = page * limit; List<Run> done = baseDB.run.listByStatus(RunDB.STATUSES_DONE, limit, offset, null); Integer previousPage = page > 0 ? (page - 1) : null; Integer nextPage = done.size() == limit ? (page + 1) : null; return Results.ok() .render("previousPage", previousPage) .render("nextPage", nextPage) .render("running", running) .render("waiting", waiting) .render("done", done); } public Result task(Context context, @PathParam("runId") Integer runId ) { List<Run> running = new ArrayList<>(); List<Run> waiting = new ArrayList<>(); List<Run> done = new ArrayList<>(); Run run = baseDB.run.find(runId); if (run != null) { switch (run.getStatus()) { case RUNNING: case RETRYING: running.add(run); break; case WAITING: waiting.add(run); break; default: done.add(run); } } return Results.ok() .template("serposcope/views/admin/TaskController/tasks.ftl.html") .render("previousPage", null) .render("nextPage", null) .render("running", running) .render("waiting", waiting) .render("done", done); } @FilterWith({ MaintenanceFilter.class, AdminFilter.class, XSRFFilter.class }) public Result startTask( Context context, @Param("module") Integer moduleId, @Param("update") Boolean update ) { Group group = context.getAttribute("group", Group.class); FlashScope flash = context.getFlashScope(); // Module module = Module.getByOrdinal(moduleId); // if (module == null || module != Module.GOOGLE) { // flash.error("error.invalidModule"); // return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); // } Run run = null; if(Boolean.TRUE.equals(update)){ run = baseDB.run.findLast(GOOGLE, null, null); } if(run == null){ run = new Run( Run.Mode.MANUAL, Group.Module.GOOGLE, resolver.get() == null ? group.getTenant() : resolver.get(), LocalDateTime.now()); } else { run.setStatus(Run.Status.RUNNING); run.setStarted(LocalDateTime.now()); } User user = context.getAttribute("user", User.class); if (!taskManager.startGoogleTask(run, user, null)) { flash.error("admin.task.errGoogleAlreadyRunning"); // return Results.redirect(router.getReverseRoute(HomeController.class, "home")); flash.success("admin.task.tasksAccepted"); } else { flash.success("admin.task.tasksStarted"); } return Results.redirect(router.getReverseRoute(HomeController.class, "home")); } @FilterWith(XSRFFilter.class) public Result abortTask( Context context, @Param("id") Integer runId ) { FlashScope flash = context.getFlashScope(); if (runId == null) { flash.error("error.invalidId"); return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); } Run run = baseDB.run.find(runId); if (run == null) { flash.error("error.invalidRun"); return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); } if (run.getStatus() != Run.Status.RUNNING) { flash.error("error.invalidRun"); return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); } switch (run.getModule()) { case GOOGLE: if (taskManager.abortGoogleTask(true, run.getId())) { flash.success("admin.task.abortingTask"); } else { flash.error("admin.task.failAbort"); } break; default: flash.error("error.invalidModule"); } // run.sets return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); } @FilterWith({ MaintenanceFilter.class, AdminFilter.class, XSRFFilter.class }) public Result deleteRun( Context context, @PathParam("runId") Integer runId, @Param("id") Integer id ) { FlashScope flash = context.getFlashScope(); if (id == null) { flash.error("error.invalidId"); return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); } if (!id.equals(runId)) { flash.error("error.invalidId"); return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); } Run run = baseDB.run.find(runId); if (run == null) { flash.error("error.invalidId"); return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); } if (run.getStatus() != Status.WAITING && run.getFinished() == null) { flash.error("error.invalidId"); return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); } switch (run.getModule()) { case GOOGLE: googleDB.targetSummary.deleteByRun(run.getId()); googleDB.rank.deleteByRunId(run.getId()); googleDB.serp.deleteByRun(run.getId()); baseDB.run.delete(run.getId()); flash.put("warning", "admin.task.googleRunDeleted"); break; default: flash.error("error.notImplemented"); return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); } return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); } @FilterWith({ MaintenanceFilter.class, AdminFilter.class, XSRFFilter.class }) public Result retryRun(Context context, @PathParam("runId") Integer runId) { FlashScope flash = context.getFlashScope(); Run run = baseDB.run.find(runId); if (run == null || run.isRunning()) { flash.error("error.invalidId"); return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); } switch (run.getModule()) { case GOOGLE: break; default: flash.error("error.notImplemented"); return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); } Group group = run.getGroup(); LocalDate day = run.getDay(); DayOfWeek dayOfWeek = null; List<Integer> days = null; if (run.getMode() == Mode.CRON) { dayOfWeek = day.getDayOfWeek(); days = new ArrayList<>(); days.add(day.getDayOfMonth()); if (day.getDayOfMonth() == day.lengthOfMonth() && day.getDayOfMonth() < 31) { for (int i = day.getDayOfMonth(); i < 31; i++) { days.add(i + 1); } } } if (googleDB.search.listByGroup(group == null ? null : Arrays.asList(group.getId()), dayOfWeek, days).size() == 0) { flash.error("admin.google.keywordEmpty"); return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); } Run retry = new Run(run.getMode(), run.getModule(), run.getTenant(), LocalDateTime.now()); // set previous day and retry status retry.setDay(run.getDay()); retry.setStatus(Status.RETRYING); User user = run.getUser(); if (!taskManager.startGoogleTask(retry, user, group)) { // flash.error("admin.task.errGoogleAlreadyRunning"); // return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); flash.success("admin.task.tasksAccepted"); } else { flash.success("admin.task.tasksStarted"); } return Results.redirect(router.getReverseRoute(TaskController.class, "tasks")); } @FilterWith({ MaintenanceFilter.class, AdminFilter.class, XSRFFilter.class }) public Result rescanSerp( Context context, @Param("runId") Integer runId ) { FlashScope flash = context.getFlashScope(); Run run = baseDB.run.find(runId); if (run == null || run.getFinished() == null) { flash.error("error.invalidId"); return Results.redirect(router.getReverseRoute(AdminController.class, "rescans")); } switch (run.getModule()) { case GOOGLE: // delete google ranks googleDB.targetSummary.deleteByRun(run.getId()); googleDB.rank.deleteByRunId(run.getId()); Set<Group> groups = new HashSet<>(); if (run.getGroup() == null) { groups.addAll(baseDB.group.list(run.getMode() == Mode.CRON ? run.getDay().getDayOfWeek() : null)); } else { groups.add(run.getGroup()); } for (Group group : groups) { List<GoogleTarget> targets = googleDB.target.list(Arrays.asList(group.getId())); List<GoogleSearch> searches = googleDB.search.listByGroup(Arrays.asList(group.getId())); taskManager.rescan(run.getId(), group, targets, searches, true); } flash.success("admin.task.serpRescanDone"); break; default: flash.error("error.notImplemented"); return Results.redirect(router.getReverseRoute(AdminController.class, "rescans")); } return Results.redirect(router.getReverseRoute(AdminController.class, "rescans")); } }
33.318182
102
0.618008
1e9390e01df4c1127ce2d566f3399dca126d1cec
5,091
package de.techfak.gse.mbaig; import uk.co.caprica.vlcj.factory.MediaPlayerFactory; import uk.co.caprica.vlcj.player.base.MediaPlayer; import uk.co.caprica.vlcj.player.base.MediaPlayerEventAdapter; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; public class MPlayer { // static private static final int ERROR_MFILES = 100; private static final String ERROR_DIALOG = "No Music Files found!"; // obj Playlist playlist; PropertyChangeSupport support; // gloabl consts private String options; private MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory(); private MediaPlayer mediaPlayer = mediaPlayerFactory.mediaPlayers().newMediaPlayer(); /** * MPlayer struct 1 - Laucnh normally for GUI operations. * @param path - The path to construct the playlist with */ protected MPlayer(String path) { support = new PropertyChangeSupport(this); try { this.playlist = new Playlist(); this.playlist.parseFiles(path); } catch (NoMusicFilesFoundException e) { System.err.println(ERROR_DIALOG); GSERadio.exitWithCode(ERROR_MFILES); } mediaPlayer.events().addMediaPlayerEventListener(new MediaPlayerEventAdapter() { @Override public void finished(final MediaPlayer mediaPlayer) { mediaPlayer.submit(() -> { support.firePropertyChange("SetNewSong", null, 1); mediaPlayer.media().play(playlist.getSong(0).getFilepath()); support.firePropertyChange("UpdateView", null, 1); }); } }); } /** * MPlayer (2nd struct) - Load MPlayer in NoGUI-Mode. * @param path - The path to search music files for * @param noGUI - Indicator that we are using the 2nd struct */ protected MPlayer(String path, int noGUI) { try { this.playlist = new Playlist(); this.playlist.parseFiles(path); } catch (NoMusicFilesFoundException e) { System.err.println(ERROR_DIALOG); GSERadio.exitWithCode(ERROR_MFILES); } mediaPlayer.events().addMediaPlayerEventListener(new MediaPlayerEventAdapter() { @Override public void finished(final MediaPlayer mediaPlayer) { mediaPlayer.submit(() -> mediaPlayer.media().play(playlist.getSong(0).getFilepath())); playlist.updatePlaylist(); } }); } /** * MPlayer struct 3 - Laucnh in Server-Mode. * @param path - Path to music files * @param noGUI - Identifier for noGUI * @param port - THe port to stream over */ protected MPlayer(String path, int noGUI, int port) { try { this.playlist = new Playlist(); this.playlist.parseFiles(path); } catch (NoMusicFilesFoundException e) { System.err.println(ERROR_DIALOG); GSERadio.exitWithCode(ERROR_MFILES); } options = ":sout=#rtp{dst=127.0.0.1,port=" + port + ",mux=ts}"; mediaPlayer.events().addMediaPlayerEventListener(new MediaPlayerEventAdapter() { @Override public void finished(final MediaPlayer mediaPlayer) { mediaPlayer.submit(() -> mediaPlayer.media().play(playlist.getSong(0).getFilepath(), options)); playlist.updatePlaylist(); } }); } //Hinzufügen eines Observers bzw. PropertyChangeListeners public void addPropertyChangeListener(PropertyChangeListener observer) { support.addPropertyChangeListener(observer); } /////////////////////////////////////////////////////////////////////////// // PLAYER CONTROLS /////////////////////////////////////////////////////////////////////////// /** * playMusic - Play Music from a specific index of the playlist. * @param pos - Position to play from */ void playMusic(int pos) { mediaPlayer.submit(() -> mediaPlayer.media().play(playlist.getSong(pos).getFilepath())); } /** * playMusic (struct 2) - Playback music for Server-Mode. * @param pos - position of the song * @param isServer - identifier for server */ void playMusic(int pos, int isServer) { mediaPlayer.submit(() -> mediaPlayer.media().play(playlist.getSong(pos).getFilepath(), options)); } /** * fullstopMusic - Completely stop playback. */ private void fullstopMusic() { mediaPlayer.controls().stop(); } /** * pauseMusic - Pause the playback. */ private void pauseMusic() { mediaPlayer.controls().pause(); } /** * resumeMusic - Resume the playback. */ private void resumeMusic() { mediaPlayer.controls().play(); } /** * stopPlayer - Prepare the MPlayer for a shutdown. */ void stopPlayer() { fullstopMusic(); mediaPlayer.release(); mediaPlayerFactory.release(); } }
34.167785
111
0.5989
7654efdb3c4151df0b1e255cfa003adaebe9d5b4
3,277
package com.google.android.gms.auth.api.signin; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable.Creator; import com.google.android.gms.common.internal.safeparcel.zzb; public class zza implements Creator<EmailSignInOptions> { static void zza(EmailSignInOptions emailSignInOptions, Parcel parcel, int i) { int zzav = zzb.zzav(parcel); zzb.zzc(parcel, 1, emailSignInOptions.versionCode); zzb.zza(parcel, 2, emailSignInOptions.zzmo(), i, false); zzb.zza(parcel, 3, emailSignInOptions.zzmq(), false); zzb.zza(parcel, 4, emailSignInOptions.zzmp(), i, false); zzb.zzI(parcel, zzav); } public /* synthetic */ Object createFromParcel(Parcel x0) { return zzP(x0); } public /* synthetic */ Object[] newArray(int x0) { return zzaK(x0); } public EmailSignInOptions zzP(Parcel parcel) { Uri uri = null; int zzau = com.google.android.gms.common.internal.safeparcel.zza.zzau(parcel); int i = 0; String str = null; Uri uri2 = null; while (parcel.dataPosition() < zzau) { String str2; Uri uri3; int zzg; Uri uri4; int zzat = com.google.android.gms.common.internal.safeparcel.zza.zzat(parcel); Uri uri5; switch (com.google.android.gms.common.internal.safeparcel.zza.zzcc(zzat)) { case 1: uri5 = uri; str2 = str; uri3 = uri2; zzg = com.google.android.gms.common.internal.safeparcel.zza.zzg(parcel, zzat); uri4 = uri5; break; case 2: zzg = i; String str3 = str; uri3 = (Uri) com.google.android.gms.common.internal.safeparcel.zza.zza(parcel, zzat, Uri.CREATOR); uri4 = uri; str2 = str3; break; case 3: uri3 = uri2; zzg = i; uri5 = uri; str2 = com.google.android.gms.common.internal.safeparcel.zza.zzp(parcel, zzat); uri4 = uri5; break; case 4: uri4 = (Uri) com.google.android.gms.common.internal.safeparcel.zza.zza(parcel, zzat, Uri.CREATOR); str2 = str; uri3 = uri2; zzg = i; break; default: com.google.android.gms.common.internal.safeparcel.zza.zzb(parcel, zzat); uri4 = uri; str2 = str; uri3 = uri2; zzg = i; break; } i = zzg; uri2 = uri3; str = str2; uri = uri4; } if (parcel.dataPosition() == zzau) { return new EmailSignInOptions(i, uri2, str, uri); } throw new com.google.android.gms.common.internal.safeparcel.zza.zza("Overread allowed size end=" + zzau, parcel); } public EmailSignInOptions[] zzaK(int i) { return new EmailSignInOptions[i]; } }
36.411111
121
0.508392
f41eda207a54cd20be598f3c77040ce22b95a49d
722
package org.ovirt.engine.ui.userportal.section.main.view.popup.vm; import org.ovirt.engine.ui.common.view.popup.AbstractModelBoundWidgetPopupView; import org.ovirt.engine.ui.common.widget.uicommon.popup.vm.VmDiskAttachPopupWidget; import org.ovirt.engine.ui.uicommonweb.models.vms.AttachDiskModel; import com.google.gwt.event.shared.EventBus; public class BaseVmDiskAttachPopupView extends AbstractModelBoundWidgetPopupView<AttachDiskModel> { public BaseVmDiskAttachPopupView(EventBus eventBus, boolean allowMultipleSelection) { super(eventBus, new VmDiskAttachPopupWidget(false, allowMultipleSelection), "815px", "615px"); //$NON-NLS-1$ //$NON-NLS-2$ asWidget().enableResizeSupport(true); } }
45.125
130
0.801939
ead0af5e1b4ea53b105e14a064cdb485bd9b01ff
241
package org.xzhi.af.impl; import org.xzhi.af.Color; /** * Red * * @author Xzhi * @date 2021-07-12 17:17 */ public class Red implements Color { @Override public void fill() { System.out.println("[--- 红色 ---]"); } }
14.176471
43
0.572614
1b90ee5037a64fdaea516ca582e247655d7f169a
8,664
package io.github.geniusv.dao; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.PluginAdapter; import org.mybatis.generator.api.dom.java.*; import org.mybatis.generator.api.dom.xml.Attribute; import org.mybatis.generator.api.dom.xml.Document; import org.mybatis.generator.api.dom.xml.TextElement; import org.mybatis.generator.api.dom.xml.XmlElement; import java.util.List; /** * Created by GeniusV on 8/6/17. */ public class SelectPrimaryKeyByExamplePlugin extends PluginAdapter { public static Method generateMethod(String methodName, JavaVisibility visibility, FullyQualifiedJavaType returnType, Parameter... parameters) { Method method = new Method(methodName); method.setVisibility(visibility); method.setReturnType(returnType); if (parameters != null) { for (Parameter parameter : parameters) { method.addParameter(parameter); } } return method; } @Override public boolean validate(List<String> list) { return true; } @Override public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) { // <select id="selectPrimaryKeyByExample" parameterType="dao.model.RoleExample" resultType="java.lang.Long"> XmlElement select = new XmlElement("select"); select.addElement(new TextElement("<!-- WARNING - @mbg.generated -->")); select.addAttribute(new Attribute("id", "selectPrimaryKeyByExample")); select.addAttribute(new Attribute("resultType", introspectedTable.getPrimaryKeyColumns().get(0).getFullyQualifiedJavaType().toString())); select.addAttribute(new Attribute("parameterType", introspectedTable.getExampleType())); // select select.addElement(new TextElement("select")); // <if test = "distinct" > // distinct // </if> XmlElement ifDinstinct = new XmlElement("if"); ifDinstinct.addAttribute(new Attribute("test", "distinct != null")); ifDinstinct.addElement(new TextElement("distinct")); select.addElement(ifDinstinct); // id from v_role select.addElement(new TextElement(introspectedTable.getPrimaryKeyColumns().get(0).getActualColumnName() + " from " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime())); // <if test = "_parameter != null" > // <include refid = "Example_Where_Clause" / > // </if> XmlElement ifElement = new XmlElement("if"); ifElement.addAttribute(new Attribute("test", "_parameter != null")); XmlElement includeElement = new XmlElement("include"); includeElement.addAttribute(new Attribute("refid", introspectedTable.getExampleWhereClauseId())); ifElement.addElement(includeElement); select.addElement(ifElement); // <if test="orderByClause != null"> // order by ${orderByClause} // </if> ifElement = new XmlElement("if"); ifElement.addAttribute(new Attribute("test", "orderByClause != null")); //$NON-NLS-2$ ifElement.addElement(new TextElement("order by ${orderByClause}")); select.addElement(ifElement); // <cache type="org.mybatis.caches.redis.RedisCache" /> XmlElement cacheElement = new XmlElement("cache"); cacheElement.addAttribute(new Attribute("type", "org.mybatis.caches.redis.RedisCache")); cacheElement.addElement(new TextElement("<!-- WARNING - @mbg.generated -->")); // selectPrimaryKeyLimitedByExample XmlElement selectPrimaryKeyLimitedByExample = generateSelectLimitedPrimaryKeyByExample(introspectedTable); //add all elements XmlElement parentElement = document.getRootElement(); parentElement.addElement(select); parentElement.addElement(cacheElement); parentElement.addElement(selectPrimaryKeyLimitedByExample); return super.sqlMapDocumentGenerated(document, introspectedTable); } @Override public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { // add selectPrimaryKeyByExample FullyQualifiedJavaType returnType = new FullyQualifiedJavaType("java.util.List<" + introspectedTable.getPrimaryKeyColumns().get(0).getFullyQualifiedJavaType() + ">"); Method method = generateMethod("selectPrimaryKeyByExample", JavaVisibility.DEFAULT, returnType, new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example")); method.addJavaDocLine("/**"); method.addJavaDocLine("* @mbg.generated"); method.addJavaDocLine("*/"); interfaze.addMethod(method); // selectPrimaryKeyLimitedByExample Method selectPrimaryKeyLimitedByExample = new Method(); selectPrimaryKeyLimitedByExample.setName("selectPrimaryKeyLimitedByExample"); selectPrimaryKeyLimitedByExample.setVisibility(JavaVisibility.DEFAULT); selectPrimaryKeyLimitedByExample.setReturnType(returnType); Parameter offset = new Parameter(new FullyQualifiedJavaType("Long"), "offset", "@Param(\"offset\")"); Parameter num = new Parameter(new FullyQualifiedJavaType("Long"), "num", "@Param(\"num\")"); Parameter example = new Parameter(new FullyQualifiedJavaType(introspectedTable.getExampleType()), "example", "@Param(\"example\")"); selectPrimaryKeyLimitedByExample.addParameter(offset); selectPrimaryKeyLimitedByExample.addParameter(num); selectPrimaryKeyLimitedByExample.addParameter(example); selectPrimaryKeyLimitedByExample.addJavaDocLine("/**"); selectPrimaryKeyLimitedByExample.addJavaDocLine("* @mbg.generated"); selectPrimaryKeyLimitedByExample.addJavaDocLine("*/"); interfaze.addMethod(selectPrimaryKeyLimitedByExample); //add @Repository interfaze.addImportedType(new FullyQualifiedJavaType("org.springframework.stereotype.Repository")); interfaze.addAnnotation("@Repository"); return true; } public XmlElement generateSelectLimitedPrimaryKeyByExample(IntrospectedTable introspectedTable) { // <select id="selectPrimaryKeyLimitedByExample" parameterType="map" resultType="java.lang.Long"> XmlElement select = new XmlElement("select"); select.addElement(new TextElement("<!-- WARNING - @mbg.generated -->")); select.addAttribute(new Attribute("id", "selectPrimaryKeyLimitedByExample")); select.addAttribute(new Attribute("parameterType", "map")); select.addAttribute(new Attribute("resultType", introspectedTable.getPrimaryKeyColumns().get(0).getFullyQualifiedJavaType().toString())); // select select.addElement(new TextElement("select")); // <if test="example.distinct != null"> // distinct // </if> XmlElement ifDinstinct = new XmlElement("if"); ifDinstinct.addAttribute(new Attribute("test", "example.distinct != null")); ifDinstinct.addElement(new TextElement("distinct")); select.addElement(ifDinstinct); // id from v_role select.addElement(new TextElement(introspectedTable.getPrimaryKeyColumns().get(0).getActualColumnName() + " from " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime())); // <if test="_parameter != null"> // <include refid="Update_By_Example_Where_Clause" /> // </if> XmlElement ifElement = new XmlElement("if"); ifElement.addAttribute(new Attribute("test", "_parameter != null")); XmlElement includeElement = new XmlElement("include"); includeElement.addAttribute(new Attribute("refid", introspectedTable.getMyBatis3UpdateByExampleWhereClauseId())); ifElement.addElement(includeElement); select.addElement(ifElement); // <if test="example.orderByClause != null"> // order by ${example.orderByClause} // </if> ifElement = new XmlElement("if"); ifElement.addAttribute(new Attribute("test", "example.orderByClause != null")); //$NON-NLS-2$ ifElement.addElement(new TextElement("order by ${example.orderByClause}")); select.addElement(ifElement); // <if test="offset != null and num != null"> // limit #{offset}, #{num} // </if> ifElement = new XmlElement("if"); ifElement.addAttribute(new Attribute("test", "offset != null and num != null")); //$NON-NLS-2$ ifElement.addElement(new TextElement("limit #{offset}, #{num}")); select.addElement(ifElement); return select; } }
47.086957
194
0.691367
1423ab25939e4b5b752c1a4158f96f9ca355427c
2,273
/* * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.measure.fx; import java.util.Optional; import com.opengamma.strata.basics.ReferenceData; import com.opengamma.strata.basics.currency.FxRate; import com.opengamma.strata.calc.marketdata.MarketDataConfig; import com.opengamma.strata.calc.marketdata.MarketDataFunction; import com.opengamma.strata.calc.marketdata.MarketDataRequirements; import com.opengamma.strata.data.FxRateId; import com.opengamma.strata.data.scenario.MarketDataBox; import com.opengamma.strata.data.scenario.ScenarioMarketData; import com.opengamma.strata.market.observable.QuoteId; /** * Function which builds {@link FxRate} instances from observable market data. * <p> * {@link FxRateConfig} defines which market data is used to build the FX rates. */ public class FxRateMarketDataFunction implements MarketDataFunction<FxRate, FxRateId> { @Override public MarketDataRequirements requirements(FxRateId id, MarketDataConfig marketDataConfig) { FxRateConfig fxRateConfig = marketDataConfig.get(FxRateConfig.class, id.getObservableSource()); Optional<QuoteId> optional = fxRateConfig.getObservableRateKey(id.getPair()); return optional.map(key -> MarketDataRequirements.of(key)).orElse(MarketDataRequirements.empty()); } @Override public MarketDataBox<FxRate> build( FxRateId id, MarketDataConfig marketDataConfig, ScenarioMarketData marketData, ReferenceData refData) { FxRateConfig fxRateConfig = marketDataConfig.get(FxRateConfig.class, id.getObservableSource()); Optional<QuoteId> optional = fxRateConfig.getObservableRateKey(id.getPair()); return optional.map(key -> buildFxRate(id, key, marketData)) .orElseThrow(() -> new IllegalArgumentException("No FX rate configuration available for " + id.getPair())); } private MarketDataBox<FxRate> buildFxRate( FxRateId id, QuoteId key, ScenarioMarketData marketData) { MarketDataBox<Double> quote = marketData.getValue(key); return quote.map(rate -> FxRate.of(id.getPair(), rate)); } @Override public Class<FxRateId> getMarketDataIdType() { return FxRateId.class; } }
36.66129
115
0.767708
70092f7ba17ecd62c0654837aa8ae58a00f67986
716
package de.embl.schwab.crosshair.legacy; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import static org.junit.jupiter.api.Assertions.*; class OldFormatSettingsReaderTest { private OldFormatSettingsReader oldFormatSettingsReader; @BeforeEach public void setUp() { oldFormatSettingsReader = new OldFormatSettingsReader(); } @Test void readSettings() { ClassLoader classLoader = this.getClass().getClassLoader(); File oldJson = new File(classLoader.getResource("legacy/exampleBlock.json").getFile()); oldFormatSettingsReader.readSettings( oldJson.getAbsolutePath() ); } }
26.518519
95
0.73743
3adb166f070586772395f8c1f4996459ad9dddba
15,157
/* * 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.jena.sparql.algebra.optimize; import static org.apache.jena.atlas.lib.CollectionUtils.disjoint; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.jena.atlas.lib.Pair; import org.apache.jena.query.ARQ ; import org.apache.jena.sparql.algebra.* ; import org.apache.jena.sparql.algebra.op.* ; import org.apache.jena.sparql.core.Var ; import org.apache.jena.sparql.core.VarExprList ; import org.apache.jena.sparql.engine.binding.BindingFactory ; import org.apache.jena.sparql.engine.binding.BindingMap ; import org.apache.jena.sparql.expr.* ; import org.apache.jena.sparql.util.Context ; /** * A transform that aims to optimize queries where there is an inequality * constraint on a variable in an attempt to speed up evaluation e.g * * <pre> * PREFIX rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt; * SELECT * * WHERE * { * ?s rdf:type &lt;http://type&gt; ; * ?p ?o . * FILTER(?p != rdf:type) * } * </pre> * * Would transform to the following: * * <pre> * PREFIX rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt; * SELECT * * WHERE * { * ?s rdf:type &lt;http://type&gt; ; * ?p ?o . * MINUS { VALUES ?p { rdf:type } } * } * </pre> * * <h3>Status</h3> * <p> * Performance testing has shown that often this gives minimal performance * benefit so this optimization is not enabled by default. It may be explicitly * enabled by setting the {@link ARQ#optFilterInequality} symbol in your * {@link Context} or the ARQ global context ({@link ARQ#getContext()} to * {@code true} * </p> * * <h3>Applicability</h3> * <p> * This optimizer is conservative in that it only makes the optimization where * the inequality constraint is against a non-literal as otherwise substituting * the value changes the query semantics because it switches from value equality * to the more restrictive term equality. The optimization is safe for * non-literals because for those value and term equality are equivalent (in * fact value equality is defined to be term equality). * </p> * <p> * There are also various nested algebra structures that can make the * optimization unsafe and so it does not take place if any of those situations * is detected. * </p> */ public class TransformFilterInequality extends TransformCopy { /** * Creates a new transform */ public TransformFilterInequality() { } @Override public Op transform(OpFilter opFilter, Op subOp) { Op op = apply(opFilter.getExprs(), subOp); if (op == null) return super.transform(opFilter, subOp); return op; } private static Op apply(ExprList exprs, Op subOp) { // ---- Find and extract any inequality filters. Pair<List<Pair<Var, NodeValue>>, ExprList> p = preprocessFilterInequality(exprs); if (p == null || p.getLeft().size() == 0) return null; List<Pair<Var, NodeValue>> inequalities = p.getLeft(); Collection<Var> varsMentioned = varsMentionedInInequalityFilters(inequalities); ExprList remaining = p.getRight(); // If any of the conditions overlap the optimization is unsafe // (the query is also likely incorrect but that isn't our problem) // TODO There is actually a special case here, if the inequality // constraints are conflicting then we can special case to table empty. // ---- Check if the subOp is the right shape to transform. Op op = subOp; // Special case : deduce that the filter will always "eval unbound" // hence eliminate all rows. Return the empty table. if (testSpecialCaseUnused(subOp, inequalities, remaining)) return OpTable.empty(); // Special case: the deep left op of a OpConditional/OpLeftJoin is unit // table. // This is // { OPTIONAL{P1} OPTIONAL{P2} ... FILTER(?x = :x) } if (testSpecialCase1(subOp, inequalities, remaining)) { // Find backbone of ops List<Op> ops = extractOptionals(subOp); ops = processSpecialCase1(ops, inequalities); // Put back together op = rebuild((Op2) subOp, ops); // Put all filters - either we optimized, or we left alone. // Either way, the complete set of filter expressions. op = OpFilter.filter(exprs, op); return op; } // ---- Transform if (!safeToTransform(varsMentioned, op)) return null; op = processFilterWorker(op, inequalities); // ---- Place any filter expressions around the processed sub op. if (remaining.size() > 0) op = OpFilter.filter(remaining, op); return op; } // --- find and extract private static Pair<List<Pair<Var, NodeValue>>, ExprList> preprocessFilterInequality(ExprList exprs) { List<Pair<Var, NodeValue>> exprsFilterInequality = new ArrayList<>(); ExprList exprsOther = new ExprList(); for (Expr e : exprs.getList()) { Pair<Var, NodeValue> p = preprocess(e); if (p != null) exprsFilterInequality.add(p); else exprsOther.add(e); } if (exprsFilterInequality.size() == 0) return null; return Pair.create(exprsFilterInequality, exprsOther); } private static Pair<Var, NodeValue> preprocess(Expr e) { if (!(e instanceof E_NotEquals)) return null; ExprFunction2 eq = (ExprFunction2) e; Expr left = eq.getArg1(); Expr right = eq.getArg2(); Var var = null; NodeValue constant = null; if (left.isVariable() && right.isConstant()) { var = left.asVar(); constant = right.getConstant(); } else if (right.isVariable() && left.isConstant()) { var = right.asVar(); constant = left.getConstant(); } if (var == null || constant == null) return null; // Final check for "!=" where a FILTER != can do value matching when the // graph does not. // Value based? if (!ARQ.isStrictMode() && constant.isLiteral()) return null; return Pair.create(var, constant); } private static Collection<Var> varsMentionedInInequalityFilters(List<Pair<Var, NodeValue>> inequalities) { Set<Var> vars = new HashSet<>(); for (Pair<Var, NodeValue> p : inequalities) vars.add(p.getLeft()); return vars; } private static boolean safeToTransform(Collection<Var> varsEquality, Op op) { // TODO This may actually be overly conservative, since we aren't going // to perform substitution we can potentially remove much of this method // Structure as a visitor? if (op instanceof OpBGP || op instanceof OpQuadPattern) return true; if (op instanceof OpFilter) { OpFilter opf = (OpFilter) op; // Expressions are always safe transform by substitution. return safeToTransform(varsEquality, opf.getSubOp()); } // This will be applied also in sub-calls of the Transform but queries // are very rarely so deep that it matters. if (op instanceof OpSequence) { OpN opN = (OpN) op; for (Op subOp : opN.getElements()) { if (!safeToTransform(varsEquality, subOp)) return false; } return true; } if (op instanceof OpJoin || op instanceof OpUnion) { Op2 op2 = (Op2) op; return safeToTransform(varsEquality, op2.getLeft()) && safeToTransform(varsEquality, op2.getRight()); } // Not safe unless filter variables are mentioned on the LHS. if (op instanceof OpConditional || op instanceof OpLeftJoin) { Op2 opleftjoin = (Op2) op; if (!safeToTransform(varsEquality, opleftjoin.getLeft()) || !safeToTransform(varsEquality, opleftjoin.getRight())) return false; // Not only must the left and right be safe to transform, // but the equality variable must be known to be always set. // If the varsLeft are disjoint from assigned vars, // we may be able to push assign down right // (this generalises the unit table case specialcase1) // Needs more investigation. Op opLeft = opleftjoin.getLeft(); Set<Var> varsLeft = OpVars.visibleVars(opLeft); if (varsLeft.containsAll(varsEquality)) return true; return false; } if (op instanceof OpGraph) { OpGraph opg = (OpGraph) op; return safeToTransform(varsEquality, opg.getSubOp()); } // Subquery - assume scope rewriting has already been applied. if (op instanceof OpModifier) { // ORDER BY? OpModifier opMod = (OpModifier) op; if (opMod instanceof OpProject) { OpProject opProject = (OpProject) op; // Writing "SELECT ?var" for "?var" -> a value would need // AS-ification. for (Var v : opProject.getVars()) { if (varsEquality.contains(v)) return false; } } return safeToTransform(varsEquality, opMod.getSubOp()); } if (op instanceof OpGroup) { OpGroup opGroup = (OpGroup) op; VarExprList varExprList = opGroup.getGroupVars(); return safeToTransform(varsEquality, varExprList) && safeToTransform(varsEquality, opGroup.getSubOp()); } if (op instanceof OpTable) { OpTable opTable = (OpTable) op; if (opTable.isJoinIdentity()) return true; } // Op1 - OpGroup // Op1 - OpOrder // Op1 - OpAssign, OpExtend // Op1 - OpFilter - done. // Op1 - OpLabel - easy // Op1 - OpService - no. return false; } private static boolean safeToTransform(Collection<Var> varsEquality, VarExprList varsExprList) { // If the named variable is used, unsafe to rewrite. return disjoint(varsExprList.getVars(), varsEquality); } // -- A special case private static boolean testSpecialCaseUnused(Op op, List<Pair<Var, NodeValue>> equalities, ExprList remaining) { // If the op does not contain the var at all, for some equality // then the filter expression will be "eval unbound" i.e. false. // We can return empty table. Set<Var> patternVars = OpVars.visibleVars(op); for (Pair<Var, NodeValue> p : equalities) { if (!patternVars.contains(p.getLeft())) return true; } return false; } // If a sequence of OPTIONALS, and nothing prior to the first, we end up // with a unit table on the left side of a next of LeftJoin/conditionals. private static boolean testSpecialCase1(Op op, List<Pair<Var, NodeValue>> equalities, ExprList remaining) { while (op instanceof OpConditional || op instanceof OpLeftJoin) { Op2 opleftjoin2 = (Op2) op; op = opleftjoin2.getLeft(); } return isUnitTable(op); } private static List<Op> extractOptionals(Op op) { List<Op> chain = new ArrayList<>(); while (op instanceof OpConditional || op instanceof OpLeftJoin) { Op2 opleftjoin2 = (Op2) op; chain.add(opleftjoin2.getRight()); op = opleftjoin2.getLeft(); } return chain; } private static List<Op> processSpecialCase1(List<Op> ops, List<Pair<Var, NodeValue>> inequalities) { List<Op> ops2 = new ArrayList<>(); Collection<Var> vars = varsMentionedInInequalityFilters(inequalities); for (Op op : ops) { Op op2 = op; if (safeToTransform(vars, op)) { op2 = processFilterWorker(op, inequalities); } ops2.add(op2); } return ops2; } private static Op rebuild(Op2 subOp, List<Op> ops) { Op chain = OpTable.unit(); for (Op op : ops) { chain = subOp.copy(chain, op); } return chain; } private static boolean isUnitTable(Op op) { if (op instanceof OpTable) { if (((OpTable) op).isJoinIdentity()) return true; } return false; } private static Op processFilterWorker(Op op, List<Pair<Var, NodeValue>> inequalities) { // Firstly find all the possible values for each variable Map<Var, Set<NodeValue>> possibleValues = new HashMap<>(); for (Pair<Var, NodeValue> inequalityTest : inequalities) { if (!possibleValues.containsKey(inequalityTest.getLeft())) { possibleValues.put(inequalityTest.getLeft(), new HashSet<NodeValue>()); } possibleValues.get(inequalityTest.getLeft()).add(inequalityTest.getRight()); } // Then combine them into all possible rows to be eliminated Table table = buildTable(possibleValues); // Then apply the MINUS return OpMinus.create(op, OpTable.create(table)); } private static Table buildTable(Map<Var, Set<NodeValue>> possibleValues) { if (possibleValues.size() == 0) return TableFactory.createEmpty(); Table table = TableFactory.create(); // Although each filter condition must apply for a row to be accepted // they are actually independent since only one condition needs to fail // for the filter to reject the row. Thus for each unique variable/value // combination a single row must be produced for (Var v : possibleValues.keySet()) { for (NodeValue value : possibleValues.get(v)) { BindingMap b = BindingFactory.create(); b.add(v, value.asNode()); table.addBinding(b); } } return table; } }
36.347722
126
0.612984
8f159f4ff2e59c55777bffc42fa6f81c4b1f247e
12,107
package com.redhat.fuse.boosters.rest.http; import javax.annotation.Generated; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.model.rest.CollectionFormat; import org.apache.camel.model.rest.RestParamType; import org.springframework.stereotype.Component; /** * Generated from Swagger specification by Camel REST DSL generator. */ @Generated("org.apache.camel.generator.swagger.PathGenerator") @Component public final class SwaggerPetstore extends RouteBuilder { /** * Defines Apache Camel routes using REST DSL fluent API. */ public void configure() { rest("/v2") .put("/pet") .id("updatePet") .consumes("application/json,application/xml") .produces("application/xml,application/json") .param() .name("body") .type(RestParamType.body) .required(true) .description("Pet object that needs to be added to the store") .endParam() .to("direct:updatePet") .post("/pet") .id("addPet") .consumes("application/json,application/xml") .produces("application/xml,application/json") .param() .name("body") .type(RestParamType.body) .required(true) .description("Pet object that needs to be added to the store") .endParam() .to("direct:addPet") .get("/pet/findByStatus") .id("findPetsByStatus") .description("Multiple status values can be provided with comma separated strings") .produces("application/xml,application/json") .param() .name("status") .type(RestParamType.query) .dataType("array") .collectionFormat(CollectionFormat.multi) .arrayType("string") .required(true) .description("Status values that need to be considered for filter") .endParam() .to("direct:findPetsByStatus") .get("/pet/findByTags") .id("findPetsByTags") .description("Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.") .produces("application/xml,application/json") .param() .name("tags") .type(RestParamType.query) .dataType("array") .collectionFormat(CollectionFormat.multi) .arrayType("string") .required(true) .description("Tags to filter by") .endParam() .to("direct:findPetsByTags") .get("/pet/{petId}") .id("getPetById") .description("Returns a single pet") .produces("application/xml,application/json") .param() .name("petId") .type(RestParamType.path) .dataType("integer") .required(true) .description("ID of pet to return") .endParam() .to("direct:getPetById") .post("/pet/{petId}") .id("updatePetWithForm") .consumes("application/x-www-form-urlencoded") .produces("application/xml,application/json") .param() .name("petId") .type(RestParamType.path) .dataType("integer") .required(true) .description("ID of pet that needs to be updated") .endParam() .param() .name("name") .type(RestParamType.formData) .dataType("string") .required(false) .description("Updated name of the pet") .endParam() .param() .name("status") .type(RestParamType.formData) .dataType("string") .required(false) .description("Updated status of the pet") .endParam() .to("direct:updatePetWithForm") .delete("/pet/{petId}") .id("deletePet") .produces("application/xml,application/json") .param() .name("api_key") .type(RestParamType.header) .dataType("string") .required(false) .endParam() .param() .name("petId") .type(RestParamType.path) .dataType("integer") .required(true) .description("Pet id to delete") .endParam() .to("direct:deletePet") .post("/pet/{petId}/uploadImage") .id("uploadFile") .consumes("multipart/form-data") .produces("application/json") .param() .name("petId") .type(RestParamType.path) .dataType("integer") .required(true) .description("ID of pet to update") .endParam() .param() .name("additionalMetadata") .type(RestParamType.formData) .dataType("string") .required(false) .description("Additional data to pass to server") .endParam() .param() .name("file") .type(RestParamType.formData) .dataType("file") .required(false) .description("file to upload") .endParam() .to("direct:uploadFile") .get("/store/inventory") .id("getInventory") .description("Returns a map of status codes to quantities") .produces("application/json") .to("direct:getInventory") .post("/store/order") .id("placeOrder") .produces("application/xml,application/json") .param() .name("body") .type(RestParamType.body) .required(true) .description("order placed for purchasing the pet") .endParam() .to("direct:placeOrder") .get("/store/order/{orderId}") .id("getOrderById") .description("For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions") .produces("application/xml,application/json") .param() .name("orderId") .type(RestParamType.path) .dataType("integer") .required(true) .description("ID of pet that needs to be fetched") .endParam() .to("direct:getOrderById") .delete("/store/order/{orderId}") .id("deleteOrder") .description("For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors") .produces("application/xml,application/json") .param() .name("orderId") .type(RestParamType.path) .dataType("integer") .required(true) .description("ID of the order that needs to be deleted") .endParam() .to("direct:deleteOrder") .post("/user") .id("createUser") .description("This can only be done by the logged in user.") .produces("application/xml,application/json") .param() .name("body") .type(RestParamType.body) .required(true) .description("Created user object") .endParam() .to("direct:createUser") .post("/user/createWithArray") .id("createUsersWithArrayInput") .produces("application/xml,application/json") .param() .name("body") .type(RestParamType.body) .required(true) .description("List of user object") .endParam() .to("direct:createUsersWithArrayInput") .post("/user/createWithList") .id("createUsersWithListInput") .produces("application/xml,application/json") .param() .name("body") .type(RestParamType.body) .required(true) .description("List of user object") .endParam() .to("direct:createUsersWithListInput") .get("/user/login") .id("loginUser") .produces("application/xml,application/json") .param() .name("username") .type(RestParamType.query) .dataType("string") .required(true) .description("The user name for login") .endParam() .param() .name("password") .type(RestParamType.query) .dataType("string") .required(true) .description("The password for login in clear text") .endParam() .to("direct:loginUser") .get("/user/logout") .id("logoutUser") .produces("application/xml,application/json") .to("direct:logoutUser") .get("/user/{username}") .id("getUserByName") .produces("application/xml,application/json") .param() .name("username") .type(RestParamType.path) .dataType("string") .required(true) .description("The name that needs to be fetched. Use user1 for testing. ") .endParam() .to("direct:getUserByName") .put("/user/{username}") .id("updateUser") .description("This can only be done by the logged in user.") .produces("application/xml,application/json") .param() .name("username") .type(RestParamType.path) .dataType("string") .required(true) .description("name that need to be updated") .endParam() .param() .name("body") .type(RestParamType.body) .required(true) .description("Updated user object") .endParam() .to("direct:updateUser") .delete("/user/{username}") .id("deleteUser") .description("This can only be done by the logged in user.") .produces("application/xml,application/json") .param() .name("username") .type(RestParamType.path) .dataType("string") .required(true) .description("The name that needs to be deleted") .endParam() .to("direct:deleteUser"); } }
42.332168
159
0.455522
716cd6f0bd9b144c5fcd48c9b64135f78a33c0c2
3,019
/* * Copyright (c) 2009-2012 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package minicraft.frontend; import com.jme3.app.Application; import com.jme3.app.state.AbstractAppState; import com.jme3.app.state.AppStateManager; import com.jme3.input.FlyByCamera; /** * Manages a FlyByCamera. * * @author Paul Speed */ public class FlyCamAppState extends AbstractAppState { private Application app; private FlyByCamera flyCam; public FlyCamAppState() { } /** * This is called by SimpleApplication during initialize(). */ public void setCamera( FlyByCamera cam ) { this.flyCam = cam; } public FlyByCamera getCamera() { return flyCam; } @Override public void initialize(AppStateManager stateManager, Application app) { super.initialize(stateManager, app); this.app = app; if (app.getInputManager() != null) { if (flyCam == null) { flyCam = new FlyByCamera(app.getCamera()); } flyCam.registerWithInput(app.getInputManager()); } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); flyCam.setEnabled(enabled); } @Override public void cleanup() { super.cleanup(); if (app.getInputManager() != null) { flyCam.unregisterInput(); } } }
31.123711
77
0.671414
817e54cb6aabae5a99f719e363a0bf274a2a3fb8
2,617
package build_a_game; import java.util.Random; public class Spawn { private Handler handler; private HUD hud; private int scoreKeep=0; private Random r= new Random(); private GameObject player; public Spawn(Handler handler, HUD hud) { this.handler=handler; this.hud=hud; for (int i=0; i < handler.object.size(); i++) { if (handler.object.get(i).getID()==ID.Player) { this.player=handler.object.get(i); } } } public void tick() { scoreKeep++; if (scoreKeep >= 200) { scoreKeep=0; hud.setLevel(hud.getLevel()+1); if (hud.getLevel()==2) { handler.addObject(new BasicEnemy(r.nextInt(Game.WIDTH-64)+32, r.nextInt(Game.HEIGHT-64)+32, ID.BasicEnemy, handler)); handler.addObject(new SmartEnemy(r.nextInt(Game.WIDTH-64)+32, r.nextInt(Game.HEIGHT-64)+32, ID.SmartEnemy, handler)); } if (hud.getLevel()==3) { handler.addObject(new FastEnemy(r.nextInt(Game.WIDTH-64)+32, r.nextInt(Game.HEIGHT-64)+32, ID.FastEnemy, handler)); } if (hud.getLevel()>2 && scoreKeep%50==0) { for (int i=0; i < handler.object.size(); i++) { if (handler.object.get(i).getID()==ID.Player) { this.player=handler.object.get(i); } } int tx = Math.min(player.getX(), Game.WIDTH-player.getX()); int ty = Math.min(player.getY(), Game.HEIGHT-player.getY()); if (tx < ty) { if (player.getX()<=Game.WIDTH-player.getX()) { handler.addObject(new SpikesEnemy(0, player.getY(), ID.SpikesEnemy, handler)); }else { handler.addObject(new SpikesEnemy(Game.WIDTH, player.getY(), ID.SpikesEnemy, handler)); } }else if(player.getY()<=Game.HEIGHT-player.getY()) { handler.addObject(new SpikesEnemy(player.getX(), 0, ID.SpikesEnemy, handler)); }else { handler.addObject(new SpikesEnemy(player.getX(), Game.HEIGHT, ID.SpikesEnemy, handler)); } } if (hud.getLevel()==5) { handler.addObject(new BasicEnemy(r.nextInt(Game.WIDTH-64)+32, r.nextInt(Game.HEIGHT-64)+32, ID.BasicEnemy, handler)); handler.addObject(new BasicEnemy(r.nextInt(Game.WIDTH-64)+32, r.nextInt(Game.HEIGHT-64)+32, ID.BasicEnemy, handler)); } if (hud.getLevel()==7) { handler.addObject(new BossEnemy(Game.WIDTH/2-48, -120, ID.BossEnemy, handler)); } if (hud.getLevel()==10) { for (int i=0; i < handler.object.size(); i++) { if (handler.object.get(i).getID()==ID.BossEnemy) { handler.removeObject(handler.object.get(i)); } } } if (hud.getLevel()==11) { handler.clearObjects(); } } } }
32.308642
124
0.620558
03d22b4b47f80ca575d43b408dd8ac7625a1fead
5,227
/*L * Copyright Georgetown University, Washington University. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cab2b/LICENSE.txt for details. */ package edu.common.dynamicextensions.ui.webui.actionform; import java.util.HashMap; import java.util.List; import java.util.Map; import edu.common.dynamicextensions.domaininterface.userinterface.ContainerInterface; import edu.common.dynamicextensions.ui.webui.util.WebUIManagerConstants; import edu.wustl.common.actionForm.AbstractActionForm; import edu.wustl.common.domain.AbstractDomainObject; /** * @author sujay_narkar * */ public class DataEntryForm extends AbstractActionForm { /** * */ private static final long serialVersionUID = -7828307676065035418L; /** * */ protected String entitySaved; /** * */ protected String showFormPreview = "false"; /** * */ protected ContainerInterface containerInterface; /** * */ protected String recordIdentifier; /** * */ protected List<String> errorList; /** * */ protected String mode = WebUIManagerConstants.EDIT_MODE; /** * */ protected Map<String, Object> valueMap = new HashMap<String, Object>(); /** * */ protected String childContainerId; /** * */ protected String childRowId; /** * */ protected String dataEntryOperation = ""; /* * */ protected boolean isTopLevelEntity = true; protected String previewBack; /** * * @param key * @param value */ public void setValue(String key, Object value) { valueMap.put(key, value); } /** * * @param key * @return */ public Object getValue(String key) { return valueMap.get(key); } /** * @return Returns the valueMap. */ public Map<String, Object> getValueMap() { return valueMap; } /** * @param valueMap The valueMap to set. */ public void setValueMap(Map<String, Object> valueMap) { this.valueMap = valueMap; } /** * @return int formId */ public int getFormId() { return 0; } /** * @param arg0 abstractDomainObject */ public void setAllValues(AbstractDomainObject arg0) { } /** * */ protected void reset() { } /** * @return Returns the container. */ public ContainerInterface getContainerInterface() { return containerInterface; } /** * @param containerInterface The container to set. */ public void setContainerInterface(ContainerInterface containerInterface) { this.containerInterface = containerInterface; } /** * * @return entitySaved */ public String getEntitySaved() { return entitySaved; } /** * * @param entitySaved entitySaved */ public void setEntitySaved(String entitySaved) { this.entitySaved = entitySaved; } /** * * @return String showFormPreview */ public String getShowFormPreview() { return showFormPreview; } /** * * @param showFormPreview String showFormPreview */ public void setShowFormPreview(String showFormPreview) { this.showFormPreview = showFormPreview; } public String getRecordIdentifier() { return recordIdentifier; } public void setRecordIdentifier(String recordIdentifier) { this.recordIdentifier = recordIdentifier; } /** * @return the errorList */ public List<String> getErrorList() { return errorList; } /** * @param errorList the errorList to set */ public void setErrorList(List<String> errorList) { this.errorList = errorList; } /** * @return Returns the mode. */ public String getMode() { return mode; } /** * @param mode The mode to set. */ public void setMode(String mode) { this.mode = mode; } /** * * @return */ public String getChildContainerId() { return childContainerId; } /** * * @param childContainerId */ public void setChildContainerId(String childContainerId) { this.childContainerId = childContainerId; } /** * * @return */ public String getChildRowId() { return childRowId; } /** * * @param childRowId */ public void setChildRowId(String childRowId) { this.childRowId = childRowId; } /** * * @return */ public String getDataEntryOperation() { return dataEntryOperation; } /** * * @param dataEntryOperation */ public void setDataEntryOperation(String dataEntryOperation) { this.dataEntryOperation = dataEntryOperation; } /** * @return Returns the isTopLevelEntity. */ public boolean getIsTopLevelEntity() { return isTopLevelEntity; } /** * @param isTopLevelEntity The isTopLevelEntity to set. */ public void setIsTopLevelEntity(boolean isTopLevelEntity) { this.isTopLevelEntity = isTopLevelEntity; } /** * @return the previewBack */ public String getPreviewBack() { return previewBack; } /** * @param previewBack the previewBack to set */ public void setPreviewBack(String previewBack) { this.previewBack = previewBack; } }
16.437107
86
0.635164
b14edd4fb7263bd5ffbaf30a95059c00b720c420
509
// you can also use imports, for example: import java.util.*; // you can write to stdout for debugging purposes, e.g. // System.out.println("this is a debug message"); class Solution { public int solution(int[] A) { Map<Integer, Integer> map = new HashMap<>(); for(int a : A){ map.put(a, a); } for(int k=1; k< A.length+1; k++){ if(!map.containsKey(k)){ return k; } } return A.length+1; } }
23.136364
55
0.502947
f9534ce55d0ceafd8340a343afabb49955312731
1,552
/* * Copyright 2013-2014 Amazon Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.services.dynamodb.datamodeling; import java.util.List; import com.amazonaws.services.dynamodb.model.Key; /** * Container for a page of scan results. * @deprecated Use {@link com.amazonaws.services.dynamodbv2.datamodeling.ScanResultPage} instead. */ @Deprecated public class ScanResultPage<T> { private List<T> results; private Key lastEvaluatedKey; /** * Returns all matching items for this page of scan results, which may be * empty. */ public List<T> getResults() { return results; } public void setResults(List<T> results) { this.results = results; } /** * Returns the last evaluated key, which can be used as the * exclusiveStartKey to fetch the next page of results. Returns null if this * is the last page of results. */ public Key getLastEvaluatedKey() { return lastEvaluatedKey; } public void setLastEvaluatedKey(Key lastEvaluatedKey) { this.lastEvaluatedKey = lastEvaluatedKey; } }
27.22807
97
0.693943
2032ed2abf7ea5f2b86be2125b72fb624a1b5c35
514
package controllers.annotation; import actions.AnonymousCheckAction; import play.mvc.With; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * */ @With(AnonymousCheckAction.class) @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface AnonymousCheck { boolean requiresLogin() default false; boolean displaysFlashMessage() default false; }
24.47619
49
0.803502
219fe6e4e444def9f4eafa3e712c3caa3915882c
5,249
package com.asus.zenbodialogsample; import android.content.Intent; import android.os.Bundle; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.asus.robotframework.API.RobotCallback; import com.asus.robotframework.API.RobotCmdState; import com.asus.robotframework.API.RobotErrorCode; import com.robot.asus.robotactivity.RobotActivity; import org.json.JSONException; import org.json.JSONObject; import android.view.View; public class EquipmentIntro extends RobotActivity{ public final static String TAG = "ZenboDialogSample"; public final static String DOMAIN = "9EF85697FF064D54B32FF06D21222BA2"; static EquipmentIntro facilityClass; static String faci_name; static int faci_floor; static String faci_introduce; static int faci_number; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_equip); faci_introduce = ""; faci_floor = 0; robotAPI.vision.cancelDetectFace(); System.out.println("sucess to change to facility"); //backButton 初始化 Button backButton = findViewById(R.id.backButton); backButton.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { Intent backIT = new Intent(); backIT.setClass(EquipmentIntro.this,Guest.class); startActivity(backIT); } }); //layout資訊初始化 facilityClass = EquipmentIntro.this; Intent it = this.getIntent(); String resJsonString = it.getStringExtra("resJson"); System.out.println("facility success receive: " + resJsonString); try { final JSONObject[] resJson = {new JSONObject(resJsonString)}; System.out.println("resfacilityJson:" + resJson); faci_name = resJson[0].getString("faci_name"); faci_floor = resJson[0].getInt("floor"); faci_introduce = resJson[0].getString("introduce"); faci_number = resJson[0].getInt("number"); System.out.println("facility_name: " + faci_name + " floor: " + faci_floor + " introduce: " + faci_introduce); } catch (JSONException e) { System.out.println("error in change string into json"); e.printStackTrace(); } if(faci_name==""||faci_floor==0){ Intent failIt = new Intent(); failIt.setClass(EquipmentIntro.this,Guest.class); startActivity(failIt); robotAPI.robot.speak("不好意思,請重試一次"); }else{ TextView faci_name_tv = (TextView) findViewById(R.id.faci_name_textView); faci_name_tv.setText(faci_name); TextView faci_intro_tv = (TextView) findViewById(R.id.faci_intro_textView); faci_intro_tv.setText(faci_introduce); ImageView floor_image = (ImageView) findViewById(R.id.floor_image); if(faci_floor == 1){ floor_image.setImageResource(R.drawable.t1); }else if(faci_floor == 2){ floor_image.setImageResource(R.drawable.t2); }else if(faci_floor == 3){ floor_image.setImageResource(R.drawable.t3); }else if(faci_floor == 4){ floor_image.setImageResource(R.drawable.t4); }else if(faci_floor == 5){ floor_image.setImageResource(R.drawable.t5); }else if(faci_floor == 7){ floor_image.setImageResource(R.drawable.t7); }else if(faci_floor == 8){ floor_image.setImageResource(R.drawable.t8); } robotAPI.robot.speak(faci_name+"在達賢"+faci_floor+"樓的"+faci_number+"號唷"); } } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } @Override protected void onDestroy() { super.onDestroy(); } public static RobotCallback robotCallback = new RobotCallback() { @Override public void onResult(int cmd, int serial, RobotErrorCode err_code, Bundle result) { super.onResult(cmd, serial, err_code, result); } @Override public void onStateChange(int cmd, int serial, RobotErrorCode err_code, RobotCmdState state) { super.onStateChange(cmd, serial, err_code, state); } @Override public void initComplete() { super.initComplete(); } }; public static RobotCallback.Listen robotListenCallback = new RobotCallback.Listen() { @Override public void onFinishRegister() { } @Override public void onVoiceDetect(JSONObject jsonObject) { } @Override public void onSpeakComplete(String s, String s1) { } @Override public void onEventUserUtterance(JSONObject jsonObject) { } @Override public void onResult(JSONObject jsonObject) { } @Override public void onRetry(JSONObject jsonObject) { } }; public EquipmentIntro() { super(robotCallback, robotListenCallback); } }
30.34104
122
0.633073
527efd5c92bb0a03206c94115cee4aa90a116c21
774
package com.artirigo.kontaktio; import android.Manifest; import android.content.pm.PackageManager; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.WritableMap; import com.facebook.react.modules.core.DeviceEventManagerModule; public class KontaktModule extends ReactContextBaseJavaModule { KontaktModule(ReactApplicationContext context) { super(context); } @Override public String getName() { return "KontaktModule"; } }
29.769231
64
0.803618
1cbbeecd314098f0de0461e0c0ef80e25345dbeb
500
package app.services.interfaces; import app.models.dtos.binding.CreateCarDto; import app.models.dtos.view.CarsPartListDto; import app.models.dtos.view.FindByMakerCarDto; import org.springframework.stereotype.Service; import java.util.List; @Service public interface CarService { void createCar(CreateCarDto createCarDto); void createAllCars(List<CreateCarDto> createCarDtos); List<FindByMakerCarDto> findCarsByMaker(String maker); List<CarsPartListDto> getCarsAndTheirParts(); }
26.315789
58
0.808
fddee1098ee835eacbf4076673a038f3a8054e58
1,547
package me.pbox.site.web.page; import com.google.inject.Inject; import me.pbox.site.dao.PackageDao; import me.pbox.site.model.Package; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.nocturne.annotation.Parameter; import org.nocturne.link.Link; /** * @author Mike Mirzayanov (mirzayanovmr@gmail.com) */ @Link("onDownload/{packageName}/{version};onDownload/{packageName}/{version}/{key}") public class DownloadListenerPage extends WebPage { @Parameter private String packageName; @Parameter private String version; @Parameter private String key; @Inject private PackageDao packageDao; @Override public void action() { final String sessionKeyName = packageName + "#key"; if (StringUtils.isBlank(key)) { String value = RandomStringUtils.randomAlphanumeric(10); putSession(sessionKeyName, value); put("key", value); } else { String value = getSession(sessionKeyName, String.class); if (key.equals(value)) { handle(); put("key", "OK"); } else { put("key", "FAILED"); } removeSession(sessionKeyName); } } private void handle() { Package p = packageDao.find(packageName, version); if (p != null) { packageDao.onDownload(p); } } @Override public String getTitle() { return "DownloadListenerPage"; } }
25.783333
84
0.617324