label
int64
0
10
text
stringlengths
210
2.04k
10
extern alias v090; using System; using System.Collections.Generic; using System.Linq; using System.Text; using v090::LiteDB; namespace LiteDB.Shell { class ShellEngine_090 : IShellEngine { private LiteEngine _db; public Version Version { get { return typeof(LiteEngine).Assembly.GetName().Version; } } public bool Detect(string filename) { try { new LiteEngine(filename); return true; } catch { return false; } } public void Open(string connectionString) { _db = new LiteEngine(connectionString); } public void Dispose() { _db.Dispose(); } public void Debug(bool enabled) { throw new NotImplementedException("Debug does not work in this version"); } public void Run(string command, Display display) { throw new NotImplementedException("This command does not work in this version"); } } }
4
package org.basex.query.xpath.internal; import static org.basex.query.xpath.XPText.*; import org.basex.BaseX; import org.basex.data.Serializer; import org.basex.index.RangeToken; import org.basex.query.xpath.XPContext; import org.basex.query.xpath.values.NodeSet; import org.basex.util.Token; /** * This index class retrieves range values from the index. * * @author Workgroup DBIS, University of Konstanz 2005-08, ISC License * @author Christian Gruen */ public final class RangeAccess extends InternalExpr { /** Index type. */ private final RangeToken index; /** * Constructor. * @param ind index terms */ public RangeAccess(final RangeToken ind) { index = ind; } @Override public NodeSet eval(final XPContext ctx) { ctx.local = new NodeSet(ctx.local.data.ids(index)[0], ctx); return ctx.local; } @Override public void plan(final Serializer ser) throws Exception { ser.emptyElement(this, Token.token(TYPE), Token.token( index.type.toString()), Token.token(MIN), Token.token(index.min), Token.token(MAX), Token.token(index.max)); } @Override public String color() { return "CC99FF"; } @Override public String toString() { return BaseX.info("%(%, %-%)", name(), index.type, index.min, index.max); } }
10
using System; using System.ComponentModel; using System.Threading; namespace ApprovalTests.Namers { public class NamerFactory { public static ApprovalResults ApprovalResults = new ApprovalResults(); static AsyncLocal<string> additionalInformation = new AsyncLocal<string>(); public static string AdditionalInformation { get => additionalInformation.Value; set => additionalInformation.Value = value; } [Obsolete("Use ApprovalResults.UniqueForMachineName instead.")] public static void AsMachineSpecificTest() { ApprovalResults.UniqueForMachineName(); } [Obsolete("Use AsEnvironmentSpecificTest instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public static void AsMachineSpecificTest(Func<string> environmentLabeler) { AsEnvironmentSpecificTest(environmentLabeler); } public static IDisposable AsEnvironmentSpecificTest(Func<string> environmentLabeler) { if (AdditionalInformation == null) { AdditionalInformation = environmentLabeler(); } else { AdditionalInformation += "." + environmentLabeler(); } return new EnviromentSpecificCleanUp(); } public static void Clear() { AdditionalInformation = null; } } }
4
using System.Collections.Generic; using System.Linq; public partial class ModuleWeaver { void CheckForWarnings(List<TypeNode> notifyNodes) { foreach (var node in notifyNodes) { foreach (var propertyData in node.PropertyDatas.ToList()) { var warning = CheckForWarning(propertyData, node.EventInvoker.InvokerType); if (warning != null) { LogDebug($"\t{propertyData.PropertyDefinition.GetName()} {warning} Property will be ignored."); node.PropertyDatas.Remove(propertyData); } } CheckForWarnings(node.Nodes); } } public string CheckForWarning(PropertyData propertyData, InvokerTypes invokerType) { var propertyDefinition = propertyData.PropertyDefinition; var setMethod = propertyDefinition.SetMethod; if (setMethod.Name == "set_Item" && setMethod.Parameters.Count == 2 && setMethod.Parameters[1].Name == "value") { return "Property is an indexer."; } if (setMethod.Parameters.Count > 1) { return "Property takes more than one parameter."; } if (setMethod.IsAbstract) { return "Property is abstract."; } if ((propertyData.BackingFieldReference == null) && (propertyDefinition.GetMethod == null)) { return "Property has no field set logic or it contains multiple sets and the names cannot be mapped to a property."; } if (invokerType == InvokerTypes.BeforeAfter && (propertyDefinition.GetMethod == null)) { return "When using a before/after invoker the property have a 'get'."; } return null; } public void CheckForWarnings() { CheckForWarnings(NotifyNodes); } }
1
using System; using SaintCoinach.IO; using YamlDotNet.Serialization; namespace SaintCoinach.Ex.Relational.ValueConverters { public class IconConverter : IValueConverter { #region IValueConverter Members [YamlIgnore] public string TargetTypeName { get { return "Image"; } } [YamlIgnore] public Type TargetType { get { return typeof(Imaging.ImageFile); } } public object Convert(IDataRow row, object rawValue) { const string IconFileFormat = "ui/icon/{0:D3}000/{1}{2:D6}.tex"; var nr = System.Convert.ToInt32(rawValue); if (nr < 0 || nr > 999999) return null; var sheet = row.Sheet; var type = sheet.Language.GetCode(); if (type.Length > 0) type = type + "/"; var filePath = string.Format(IconFileFormat, nr / 1000, type, nr); var pack = sheet.Collection.PackCollection; File file; if (pack.TryGetFile(filePath, out file)) return file; // Couldn't get language specific, try for generic version. filePath = string.Format(IconFileFormat, nr / 1000, string.Empty, nr); if (!pack.TryGetFile(filePath, out file)) { // Couldn't get generic version either, that's a shame. file = null; } return file; } #endregion } }
2
package org.sfm.benchmark.sfm; import java.sql.Connection; import java.sql.SQLException; import org.sfm.beans.SmallBenchmarkObject; import org.sfm.benchmark.AllBenchmark; import org.sfm.benchmark.BenchmarkConstants; import org.sfm.benchmark.QueryExecutor; import org.sfm.jdbc.DbHelper; import org.sfm.jdbc.JdbcMapperFactory; public class DynamicJdbcMapperForEachBenchmark<T> extends ForEachMapperQueryExecutor<T> implements QueryExecutor { public DynamicJdbcMapperForEachBenchmark(Connection conn, Class<T> target) throws NoSuchMethodException, SecurityException, SQLException { super(JdbcMapperFactory.newInstance().newMapper(target), conn, target); } public static void main(String[] args) throws SQLException, Exception { AllBenchmark.runBenchmark(DbHelper.mockDb(), SmallBenchmarkObject.class, DynamicJdbcMapperForEachBenchmark.class, BenchmarkConstants.SINGLE_QUERY_SIZE, BenchmarkConstants.SINGLE_NB_ITERATION); } }
4
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QuicNet.Infrastructure.Packets { public class Unpacker { private Dictionary<byte, PacketType> _typeMap = new Dictionary<byte, PacketType>() { { 0xFF, PacketType.InitialPacket }, { 0xFE, PacketType.RetryPacket }, { 0x8E, PacketType.ShortHeaderPacket }, { 0x77, PacketType.LongHeaderPacket }, { 0x80, PacketType.VersionNegotiationPacket }, { 0x7D, PacketType.HandshakePacket } }; public Unpacker() { } public Packet Unpack(byte[] data) { Packet result = null; PacketType type = GetPacketType(data); switch(type) { case PacketType.InitialPacket: result = new InitialPacket(); break; } result.Decode(data); return result; } public PacketType GetPacketType(byte[] data) { if (data == null || data.Length <= 0) return PacketType.BrokenPacket; byte type = data[0]; if (_typeMap.ContainsKey(type) == false) return PacketType.BrokenPacket; return _typeMap[type]; } } }
7
using System; using SabberStoneCore.Model; namespace SabberStoneCore.Tasks.PlayerTasks { public class ConcedeTask : PlayerTask { public static ConcedeTask Any(Controller controller) { return new ConcedeTask(controller); } private ConcedeTask(Controller controller) { PlayerTaskType = PlayerTaskType.CONCEDE; Game = controller.Game; Controller = controller; } public override TaskState Process() { Controller.Game.MainEnd(); throw new NotImplementedException(); } } }
2
package net.lingala.zip4j.tasks; import lombok.AllArgsConstructor; import net.lingala.zip4j.io.inputstream.SplitInputStream; import net.lingala.zip4j.io.inputstream.ZipInputStream; import net.lingala.zip4j.model.FileHeader; import net.lingala.zip4j.model.ZipModel; import net.lingala.zip4j.progress.ProgressMonitor; import net.lingala.zip4j.tasks.ExtractFileTask.ExtractFileTaskParameters; import java.io.IOException; public class ExtractFileTask extends AbstractExtractFileTask<ExtractFileTaskParameters> { private char[] password; public ExtractFileTask(ProgressMonitor progressMonitor, boolean runInThread, ZipModel zipModel, char[] password) { super(progressMonitor, runInThread, zipModel); this.password = password; } @Override protected void executeTask(ExtractFileTaskParameters taskParameters, ProgressMonitor progressMonitor) throws IOException { try(ZipInputStream zipInputStream = createZipInputStream(taskParameters.fileHeader)) { extractFile(zipInputStream, taskParameters.fileHeader, taskParameters.outputPath, taskParameters.newFileName, progressMonitor); } } @Override protected long calculateTotalWork(ExtractFileTaskParameters taskParameters) { return taskParameters.fileHeader.getCompressedSize(); } protected ZipInputStream createZipInputStream(FileHeader fileHeader) throws IOException { SplitInputStream splitInputStream = new SplitInputStream(getZipModel().getZipFile(), getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk()); splitInputStream.prepareExtractionForFileHeader(fileHeader); return new ZipInputStream(splitInputStream, password); } @AllArgsConstructor public static class ExtractFileTaskParameters { private String outputPath; private FileHeader fileHeader; private String newFileName; } }
4
/* * Copyright 2013 OmniFaces. * * 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.omnifaces.application; import javax.faces.component.UIViewRoot; import javax.faces.event.AbortProcessingException; import javax.faces.event.PreDestroyViewMapEvent; import javax.faces.event.SystemEvent; import javax.faces.event.ViewMapListener; import org.omnifaces.cdi.viewscope.ViewScopeManager; import org.omnifaces.config.BeanManager; /** * Listener for JSF view scope destroy events so that view scope manager can be notified. * * @author Bauke Scholtz * @see ViewScopeManager * @since 1.6 */ public class ViewScopeEventListener implements ViewMapListener { // Actions -------------------------------------------------------------------------------------------------------- /** * Returns <code>true</code> if given source is an instance of {@link UIViewRoot}. */ @Override public boolean isListenerForSource(Object source) { return (source instanceof UIViewRoot); } /** * If the event is an instance of {@link PreDestroyViewMapEvent}, which means that the JSF view scope is about to * be destroyed, then find the current instance of {@link ViewScopeManager} and invoke its * {@link ViewScopeManager#preDestroyView()} method. */ @Override public void processEvent(SystemEvent event) throws AbortProcessingException { if (event instanceof PreDestroyViewMapEvent) { BeanManager.INSTANCE.getReference(ViewScopeManager.class).preDestroyView(); } } }
2
package io.bootique.test.junit; import com.google.inject.Inject; import io.bootique.BQCoreModule; import io.bootique.cli.Cli; import io.bootique.command.CommandOutcome; import io.bootique.command.CommandWithMetadata; import io.bootique.log.BootLogger; import io.bootique.meta.application.CommandMetadata; import io.bootique.test.BQTestRuntime; import io.bootique.test.TestIO; import org.junit.Rule; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class BQTestFactoryIT { @Rule public BQTestFactory testFactory = new BQTestFactory(); @Test public void testCreateRuntime_Injection() { BQTestRuntime runtime = testFactory.app("-x").autoLoadModules().createRuntime(); assertArrayEquals(new String[]{"-x"}, runtime.getRuntime().getArgs()); } @Test public void testCreateRuntime_Streams_NoTrace() { TestIO io = TestIO.noTrace(); BQTestRuntime runtime = testFactory.app("-x") .autoLoadModules() .module(b -> BQCoreModule.extend(b).addCommand(XCommand.class)) .bootLogger(io.getBootLogger()) .createRuntime(); CommandOutcome result = runtime.run(); assertTrue(result.isSuccess()); assertEquals("--out--", io.getStdout().trim()); assertEquals("--err--", io.getStderr().trim()); } public static class XCommand extends CommandWithMetadata { private BootLogger logger; @Inject public XCommand(BootLogger logger) { super(CommandMetadata.builder(XCommand.class)); this.logger = logger; } @Override public CommandOutcome run(Cli cli) { logger.stderr("--err--"); logger.stdout("--out--"); return CommandOutcome.succeeded(); } } }
10
using System.Net.Http; namespace Flurl.Http.Configuration { /// <summary> /// Default implementation of IHttpClientFactory used by FlurlHttp. The created HttpClient includes hooks /// that enable FlurlHttp's testing features and respect its configuration settings. Therefore, custom factories /// should inherit from this class, rather than implementing IHttpClientFactory directly. /// </summary> public class DefaultHttpClientFactory : IHttpClientFactory { /// <summary> /// Override in custom factory to customize the creation of HttpClient used in all Flurl HTTP calls. /// In order not to lose Flurl.Http functionality, it is recommended to call base.CreateClient and /// customize the result. /// </summary> public virtual HttpClient CreateHttpClient(HttpMessageHandler handler) { return new HttpClient(new FlurlMessageHandler(handler)); } /// <summary> /// Override in custom factory to customize the creation of HttpClientHandler used in all Flurl HTTP calls. /// In order not to lose Flurl.Http functionality, it is recommended to call base.CreateMessageHandler and /// customize the result. /// </summary> public virtual HttpMessageHandler CreateMessageHandler() { return new HttpClientHandler(); } } }
2
/* * 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.ratis.datastream; import org.apache.ratis.RaftConfigKeys; import org.apache.ratis.client.DisabledDataStreamClientFactory; import org.apache.ratis.client.impl.DataStreamClientImpl; import org.apache.ratis.conf.RaftProperties; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class TestDataStreamDisabled extends DataStreamBaseTest { @Rule public final ExpectedException exception = ExpectedException.none(); @Before public void setup() { properties = new RaftProperties(); RaftConfigKeys.DataStream.setType(properties, SupportedDataStreamType.DISABLED); } @Test public void testDataStreamDisabled() throws Exception { try { setup(1); final DataStreamClientImpl client = newDataStreamClientImpl(); exception.expect(UnsupportedOperationException.class); exception.expectMessage(DisabledDataStreamClientFactory.class.getName() + "$1 does not support streamAsync"); // stream() will create a header request, thus it will hit UnsupportedOperationException due to // DisabledDataStreamFactory. client.stream(); } finally { shutdown(); } } }
2
/* * Copyright 2002-2016 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 com.zuoxiaolong.niubi.job.example; import com.zuoxiaolong.niubi.job.cluster.node.Node; import com.zuoxiaolong.niubi.job.cluster.node.StandbyNode; import com.zuoxiaolong.niubi.job.core.config.Configuration; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author Xiaolong Zuo * @since 16/1/9 15:08 */ public class StandbyNodeTest { @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode(new Configuration("com.zuoxiaolong.niubi.job.jobs"), "localhost:2181,localhost:3181,localhost:4181"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } }
10
namespace Nancy.Tests.Specifications { using System.Collections.Generic; using System.IO; using Nancy.Routing; public abstract class RequestSpec { protected static INancyEngine engine; protected static IRequest request; protected static Response response; protected RequestSpec() { engine = new NancyEngine(new AppDomainModuleLocator(), new RouteResolver()); } protected static IRequest ManufactureGETRequestForRoute(string route) { return new Request("GET", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); } protected static IRequest ManufacturePOSTRequestForRoute(string route) { return new Request("POST", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); } protected static IRequest ManufactureDELETERequestForRoute(string route) { return new Request("DELETE", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); } protected static IRequest ManufacturePUTRequestForRoute(string route) { return new Request("PUT", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); } protected static IRequest ManufactureHEADRequestForRoute(string route) { return new Request("HEAD", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); } } }
1
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace Eff.Core { public struct EffTaskAwaiter<TResult> : ICriticalNotifyCompletion { private readonly EffTask<TResult> eff; internal EffTaskAwaiter(EffTask<TResult> eff) { this.eff = eff; } public bool IsCompleted => eff.IsCompleted; public TResult GetResult() => eff.Result; public void OnCompleted(Action continuation) { eff.AsTask().ConfigureAwait(continueOnCapturedContext: true).GetAwaiter().OnCompleted(continuation); } public void UnsafeOnCompleted(Action continuation) { eff.AsTask().ConfigureAwait(continueOnCapturedContext: true).GetAwaiter().UnsafeOnCompleted(continuation); } } }
2
package io.github.kingschan1204.istock.common.util.file; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileOutputStream; import java.util.Arrays; /** * 文件常用操作工具类 * @author chenguoxiang * @create 2018-01-24 12:38 **/ public class FileCommonOperactionTool { private static Logger log = LoggerFactory.getLogger(FileCommonOperactionTool.class); /** * 通过指定的文件下载URL以及下载目录下载文件 * @param url 下载url路径 * @param dir 存放目录 * @param filename 文件名 * @throws Exception */ public static String downloadFile(String url, String dir, String filename) throws Exception { log.info("start download file :{}",url); //Open a URL Stream Connection.Response resultResponse = Jsoup.connect(url) .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3346.9 Safari/537.36") .ignoreContentType(true).execute(); String defaultFileName=""; if(resultResponse.contentType().contains("name")){ String[] list =resultResponse.contentType().split(";"); defaultFileName = Arrays.stream(list) .filter(s -> s.startsWith("name")).findFirst().get().replaceAll("name=|\"", ""); } // output here String path = dir + (null == filename ? defaultFileName : filename); FileOutputStream out = (new FileOutputStream(new java.io.File(path))); out.write(resultResponse.bodyAsBytes()); out.close(); return path; } }
10
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; namespace CodeLibraryForDotNetCore.UseEF { public static class SqlServerUseEFDemo { private static string connectionString = ""; public static void Run() { string tableName = ""; DataTable dt = new DataTable(); SqlBulkCopyByDatatable(tableName, dt); } /// <summary> /// sql server批量数据录入 /// </summary> /// <param name="tableName"></param> /// <param name="dt"></param> private static void SqlBulkCopyByDatatable(string tableName, DataTable dt) { using (var conn = new SqlConnection(connectionString)) { //SqlBulkCopy:大容量加载带有来自其他源的数据的 SQL Server 表 //https://docs.microsoft.com/zh-cn/dotnet/api/system.data.sqlclient.sqlbulkcopy?view=netframework-4.8&WT.mc_id=DT-MVP-5003010 //SqlBulkCopyOptions:加载方式 using (var sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction)) { try { //超时 sqlbulkcopy.BulkCopyTimeout = 600; //数据库目标表名 sqlbulkcopy.DestinationTableName = tableName; for (int i = 0; i < dt.Columns.Count; i++) { //列名映射:源列名-目标列名 sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName); } //数据写入目标表 sqlbulkcopy.WriteToServer(dt); } catch (System.Exception ex) { throw ex; } } } } } }
10
using Inotify.Data; using Inotify.Sends; using Microsoft.AspNetCore.Mvc; namespace Inotify.Controllers { [ApiController] [Route("api")] public class SendController : BaseControlor { [HttpGet, Route("send")] public JsonResult Send(string token, string title, string? data, string? key) { if (DBManager.Instance.IsToken(token, out bool hasActive)) { if (!hasActive) { return Fail(400, "you have no tunnel is acitve"); } if (!string.IsNullOrEmpty(key)) { if (DBManager.Instance.IsSendKey(key, out bool isActive)) { if (!isActive) { return Fail(400, $"device:{key} tunnel is not acitve"); } } else { return Fail(400, $"device:{key} is not registered"); } } var message = new SendMessage() { Token = token, Title = title, Data = data, Key = key, }; if (SendTaskManager.Instance.SendMessage(message)) { return OK(); } } return Fail(400, $"token:{token} is not registered"); } } }
4
package us.codecraft.webmagic.downloader; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import us.codecraft.webmagic.Page; import us.codecraft.webmagic.Request; import us.codecraft.webmagic.Site; /** * Author: code4crafer@gmail.com * Date: 13-6-18 * Time: 上午8:22 */ public class HttpClientDownloaderTest { @Ignore @Test public void testCookie() { Site site = Site.me().setDomain("www.diandian.com").addCookie("t", "yct7q7e6v319wpg4cpxqduu5m77lcgix"); HttpClientDownloader httpClientDownloader = new HttpClientDownloader(); Page download = httpClientDownloader.download(new Request("http://www.diandian.com"), site); Assert.assertTrue(download.getHtml().toString().contains("flashsword30")); } }
4
package io.nuls.consensus.service.impl; import io.nuls.consensus.service.intf.DownloadService; import io.nuls.consensus.service.intf.SystemService; import io.nuls.consensus.thread.ConsensusMeetingRunner; import io.nuls.core.context.NulsContext; import io.nuls.core.utils.date.TimeService; import io.nuls.core.utils.log.Log; import io.nuls.ledger.service.intf.LedgerService; import io.nuls.network.service.NetworkService; /** * Created by ln on 2018/4/11. */ public class SystemServiceImpl implements SystemService { private static final long INTERVAL_TIME = 60000L; private long lastResetTime; /** * 重置系统,包括重置网络、同步、共识 * Reset the system, including resetting the network, synchronization, consensus * * @return boolean */ @Override public boolean resetSystem(String reason) { if ((TimeService.currentTimeMillis() - lastResetTime) <= INTERVAL_TIME) { Log.info("system reset interrupt!"); return true; } Log.info("---------------reset start----------------"); Log.info("Received a reset system request, reason: 【" + reason + "】"); NetworkService networkService = NulsContext.getServiceBean(NetworkService.class); networkService.reset(); DownloadService downloadService = NulsContext.getServiceBean(DownloadService.class); downloadService.reset(); NulsContext.getServiceBean(LedgerService.class).resetLedgerCache(); ConsensusMeetingRunner consensusMeetingRunner = ConsensusMeetingRunner.getInstance(); consensusMeetingRunner.resetConsensus(); Log.info("---------------reset end----------------"); this.lastResetTime = TimeService.currentTimeMillis(); return true; } }
2
package com.xxg.jdeploy.util; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; /** * Created by xxg on 15-8-18. */ public class ShellUtil { public static String exec(String cmd) throws IOException { Process process = Runtime.getRuntime().exec(cmd); InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); try { String err = IOUtils.toString(errorStream, "UTF-8"); String out = IOUtils.toString(inputStream, "UTF-8"); return err + "\n" + out; } finally { inputStream.close(); errorStream.close(); } } }
2
/* * Sonar Python Plugin * Copyright (C) 2011 Waleri Enns * dev@sonar.codehaus.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.python; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.List; import org.apache.commons.io.IOUtils; import org.sonar.api.utils.SonarException; public final class Utils { public static List<String> callCommand(String command, String[] environ) { List<String> lines = new LinkedList<String>(); PythonPlugin.LOG.debug("Calling command: '{}'", command); BufferedReader stdInput = null; try { Process p = null; if(environ == null){ p = Runtime.getRuntime().exec(command); } else { p = Runtime.getRuntime().exec(command, environ); } stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); String s = null; while ((s = stdInput.readLine()) != null) { lines.add(s); } } catch (IOException e) { throw new SonarException("Error calling command '" + command + "', details: '" + e + "'"); } finally { IOUtils.closeQuietly(stdInput); } return lines; } private Utils() { } }
2
package io.jenkins.jenkinsfile.runner.bootstrap; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class Util { public static File explodeWar(String jarPath) throws IOException { JarFile jarfile = new JarFile(new File(jarPath)); Enumeration<JarEntry> enu = jarfile.entries(); // Get current working directory path Path currentPath = FileSystems.getDefault().getPath("").toAbsolutePath(); //Create Temporary directory Path path = Files.createTempDirectory(currentPath.toAbsolutePath(), "jenkinsfile-runner"); File destDir = path.toFile(); while(enu.hasMoreElements()) { JarEntry je = enu.nextElement(); File file = new File(destDir, je.getName()); if (!file.exists()) { file.getParentFile().mkdirs(); file = new File(destDir, je.getName()); } if (je.isDirectory()) { continue; } InputStream is = jarfile.getInputStream(je); try (FileOutputStream fo = new FileOutputStream(file)) { while (is.available() > 0) { fo.write(is.read()); } fo.close(); is.close(); } } return destDir; } }
2
/* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vafer.jdeb.ar; import java.io.File; import java.io.FileInputStream; import junit.framework.TestCase; public final class ArInputStreamTestCase extends TestCase { public void testRead() throws Exception { final File archive = new File(getClass().getResource("data.ar").toURI()); final ArInputStream ar = new ArInputStream(new FileInputStream(archive)); final ArEntry entry1 = ar.getNextEntry(); assertEquals("data.tgz", entry1.getName()); assertEquals(148, entry1.getLength()); for (int i = 0; i < entry1.getLength(); i++) { ar.read(); } final ArEntry entry2 = ar.getNextEntry(); assertNull(entry2); } }
2
package de.matrixweb.jreact; import java.io.File; import java.io.FileNotFoundException; public class FilebasedFilesystem implements Filesystem { private String fileBase; public FilebasedFilesystem() { this("."); } public FilebasedFilesystem(final String fileBase) { this.fileBase = fileBase; } @Override public boolean isFile(final String fileName) { return new File(this.fileBase, fileName.toString()).isFile(); } @Override public String readFile(final String path) throws FileNotFoundException { return new java.util.Scanner(new java.io.File(this.fileBase, path), "UTF-8").useDelimiter("\\Z").next().toString(); } @Override public String getDirectory(final String path) throws FileNotFoundException { final File dir = new File(this.fileBase, path); return dir.isDirectory() ? dir.getName() : dir.getParent(); } @Override public String getFilename(final String path) throws FileNotFoundException { return new File(this.fileBase, path).getName(); } @Override public boolean exists(final String fileName) { return new File(fileName).exists(); } }
10
using GraphQL.TestServer; using LinqQL.Core; namespace LinqQL.TestApp { public class Program { public static void Stub() { } public static void Main() { var httpClient = new HttpClient { BaseAddress = new("http://localhost:10000/") }; var qlClient = new GraphQLClient<Query>(httpClient); // place for query } } public record User(string FirstName, string LastName, string Role); }
10
using Terminal.Gui; using TerminalGuiDesigner.UI.Windows; using static Terminal.Gui.TabView; namespace TerminalGuiDesigner.Operations; public class AddTabOperation : Operation { private Tab? _tab; private readonly TabView _tabView; public Design Design { get; } public AddTabOperation(Design design) { Design = design; // somehow user ran this command for a non tab view if (Design.View is not TabView) throw new ArgumentException($"Design must be for a {nameof(TabView)} to support {nameof(AddTabOperation)}"); _tabView = (TabView)Design.View; } public override bool Do() { if (_tab != null) { throw new Exception("This command has already been performed once. Use Redo instead of Do"); } if (Modals.GetString("Add Tab", "Tab Name", "MyTab", out string? newTabName)) { _tabView.AddTab(_tab = new Tab(newTabName ?? "Unamed Tab",new View{Width = Dim.Fill(),Height=Dim.Fill()}),true); _tabView.SetNeedsDisplay(); } return true; } public override void Redo() { // cannot redo (maybe user hit redo twice thats fine) if (_tab == null || _tabView.Tabs.Contains(_tab)) { return; } _tabView.AddTab(_tab,true); _tabView.SetNeedsDisplay(); } public override void Undo() { // cannot undo if (_tab == null || !_tabView.Tabs.Contains(_tab)) { return; } _tabView.RemoveTab(_tab); _tabView.SetNeedsDisplay(); } }
10
using Bittrex.Net.Interfaces; using System; using System.Net; using System.Threading.Tasks; using Microsoft.AspNet.SignalR.Client; namespace Bittrex.Net.Sockets { public class BittrexHubConnection: IHubConnection { HubConnection connection; public BittrexHubConnection(HubConnection connection) { this.connection = connection; } public ConnectionState State => connection.State; public event Action<StateChange> StateChanged { add => connection.StateChanged += value; remove => connection.StateChanged -= value; } public event Action Closed { add => connection.Closed += value; remove => connection.Closed -= value; } public event Action<Exception> Error { add => connection.Error += value; remove => connection.Error -= value; } public event Action ConnectionSlow { add => connection.ConnectionSlow += value; remove => connection.ConnectionSlow -= value; } public CookieContainer Cookies { get => connection.CookieContainer; set => connection.CookieContainer = value; } public string UserAgent { get => connection.Headers["User-Agent"]; set => connection.Headers["User-Agent"] = value; } public IHubProxy CreateHubProxy(string hubName) { return connection.CreateHubProxy(hubName); } public Task Start() { return connection.Start(WebSocketTransportFactory.Create()); } public void Stop(TimeSpan timeout) { connection.Stop(timeout); } } }
4
using System.Xml.Linq; using DefaultDocumentation.Writers; namespace DefaultDocumentation.Markdown.Elements { public sealed class NoteWriter : IElementWriter { public string Name => "note"; public void Write(IWriter writer, XElement element) { if (writer.GetDisplayAsSingleLine()) { return; } string type = element.GetTypeAttribute()?.ToLower(); string notePrefix = type switch { "note" or "tip" or "caution" or "warning" or "important" => char.ToUpper(type[0]) + type.Substring(1), "security" or "security note" => "Security Note", "implement" => "Notes to Implementers", "inherit" => "Notes to Inheritors", "caller" => "Notes to Callers", "cs" or "csharp" or "c#" or "visual c#" or "visual c# note" => "C# Note", "vb" or "vbnet" or "vb.net" or "visualbasic" or "visual basic" or "visual basic note" => "VB.NET Note", "fs" or "fsharp" or "f#" => "F# Note", // Legacy languages; SandCastle supported "cpp" or "c++" or "visual c++" or "visual c++ note" => "C++ Note", "jsharp" or "j#" or "visual j#" or "visual j# note" => "J# Note", _ => string.Empty }; writer.EnsureLineStart(); IWriter prefixedWriter = writer.ToPrefixedWriter("> "); if (!string.IsNullOrEmpty(notePrefix)) { prefixedWriter .Append("**") .Append(notePrefix) .AppendLine(":**"); } prefixedWriter.Append(element); writer .EnsureLineStart() .AppendLine(); } } }
10
using System.IO; using System.Threading.Tasks; namespace Downloader { public class FileStorage : IStorage { private readonly string _fileName; public FileStorage(string directory, string fileExtension = "") { _fileName = FileHelper.GetTempFile(directory, fileExtension); } public Stream Read() { return new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Delete | FileShare.ReadWrite); } public async Task Write(byte[] data, int offset, int count) { using var writer = new FileStream(_fileName, FileMode.Append, FileAccess.Write, FileShare.Delete | FileShare.ReadWrite); await writer.WriteAsync(data, 0, count); } public void Clear() { if (File.Exists(_fileName)) { File.Delete(_fileName); } } public long GetLength() { return Read()?.Length ?? 0; } } }
2
package com.notnoop.apns.internal; import static com.notnoop.apns.internal.MockingUtils.*; import java.io.ByteArrayOutputStream; import javax.net.SocketFactory; import org.junit.Assert; import org.junit.Test; import com.notnoop.apns.ApnsNotification; public class ApnsConnectionTest { ApnsNotification msg = new ApnsNotification ("a87d8878d878a79", "{\"aps\":{}}"); @Test public void simpleSocket() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); SocketFactory factory = mockSocketFactory(baos, null); packetSentRegardless(factory, baos); } @Test public void closedSocket() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); SocketFactory factory = mockClosedThenOpenSocket(baos, null, true, 1); packetSentRegardless(factory, baos); } @Test public void errorOnce() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); SocketFactory factory = mockClosedThenOpenSocket(baos, null, false, 1); packetSentRegardless(factory, baos); } @Test public void errorTwice() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); SocketFactory factory = mockClosedThenOpenSocket(baos, null, false, 2); packetSentRegardless(factory, baos); } /** * Connection fails after three retries */ @Test(expected = Exception.class) public void errorThrice() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); SocketFactory factory = mockClosedThenOpenSocket(baos, null, false, 3); packetSentRegardless(factory, baos); } private void packetSentRegardless(SocketFactory sf, ByteArrayOutputStream baos) { ApnsConnection connection = new ApnsConnection(sf, "localhost", 80); connection.DELAY_IN_MS = 0; connection.sendMessage(msg); Assert.assertArrayEquals(msg.marshall(), baos.toByteArray()); } }
2
package de.codecentric.notifications; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoCollection; public class DocumentProducer { public static void main(String[] args) throws Exception { MongoCollection<Document> eventCollection = new MongoClient( new MongoClientURI("mongodb://localhost:27001,localhost:27002,localhost:27003/test?replicatSet=demo-dev") ).getDatabase("test").getCollection("events"); long i = 0; while (true) { Document doc = new Document(); doc.put("i", i++); doc.put("even", i % 2); eventCollection.insertOne(doc); //System.out.println("inserted: " + doc); Thread.sleep(2000L + (long)(1000*Math.random())); } } }
10
using System.Data; using System.Data.SqlClient; using System.Diagnostics.CodeAnalysis; namespace Evolve.Tests.Infrastructure { public class SQLServerContainer : IDbContainer { public const string ExposedPort = "1433"; public const string HostPort = "1433"; public const string DbName = "master"; public const string DbPwd = "Password12!"; public const string DbUser = "sa"; private DockerContainer _container; private bool _disposedValue = false; public string Id => _container?.Id; public string CnxStr => $"Server=127.0.0.1;Database={DbName};User Id={DbUser};Password={DbPwd};"; public int TimeOutInSec => 60; [SuppressMessage("Qualité du code", "IDE0068: Utilisez le modèle de suppression recommandé")] public bool Start(bool fromScratch = false) { _container = new DockerContainerBuilder(new DockerContainerBuilderOptions { FromImage = "mcr.microsoft.com/mssql/server", Tag = "latest", Name = "mssql-evolve", Env = new[] { $"ACCEPT_EULA=Y", $"SA_PASSWORD={DbPwd}" }, ExposedPort = $"{ExposedPort}/tcp", HostPort = HostPort, RemovePreviousContainer = fromScratch }).Build(); return _container.Start(); } public IDbConnection CreateDbConnection() => new SqlConnection(CnxStr); protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { _container?.Dispose(); } _disposedValue = true; } } public void Dispose() { Dispose(true); } } }
2
/** * */ package oshi.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; /** * @author alessandro[at]perucchi[dot]org */ public class ExecutingCommand { public static ArrayList<String> runNative(String cmdToRun) { Process p = null; try { p = Runtime.getRuntime().exec(cmdToRun); p.waitFor(); } catch (IOException e) { return null; } catch (InterruptedException e) { return null; } BufferedReader reader = new BufferedReader(new InputStreamReader( p.getInputStream())); String line = ""; ArrayList<String> sa = new ArrayList<String>(); try { while ((line = reader.readLine()) != null) { sa.add(line); } } catch (IOException e) { return null; } return sa; } public static String getFirstAnswer(String cmd2launch) { ArrayList<String> sa = ExecutingCommand .runNative(cmd2launch); if (sa != null) return sa.get(0); else return null; } }
4
package com.nepxion.discovery.plugin.framework.decorator; /** * <p>Title: Nepxion Discovery</p> * <p>Description: Nepxion Discovery</p> * <p>Copyright: Copyright (c) 2017-2050</p> * <p>Company: Nepxion</p> * @author Haojun Ren * @version 1.0 */ import java.util.List; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import com.nepxion.discovery.common.entity.WeightFilterEntity; import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter; import com.nepxion.discovery.plugin.framework.loadbalance.WeightRandomLoadBalance; import com.netflix.loadbalancer.PredicateBasedRule; import com.netflix.loadbalancer.Server; public abstract class PredicateBasedRuleDecorator extends PredicateBasedRule { @Autowired private PluginAdapter pluginAdapter; private WeightRandomLoadBalance weightRandomLoadBalance; @PostConstruct private void initialize() { weightRandomLoadBalance = new WeightRandomLoadBalance(); weightRandomLoadBalance.setPluginAdapter(pluginAdapter); } @Override public Server choose(Object key) { WeightFilterEntity weightFilterEntity = weightRandomLoadBalance.getWeightFilterEntity(); if (!weightFilterEntity.hasWeight()) { return super.choose(key); } List<Server> eligibleServers = getPredicate().getEligibleServers(getLoadBalancer().getAllServers(), key); try { return weightRandomLoadBalance.choose(eligibleServers, weightFilterEntity); } catch (Exception e) { return super.choose(key); } } }
3
/* * IK 中文分词 版本 7.0 * IK Analyzer release 7.0 * update by 高志成(magese@live.cn) */ package org.wltea.analyzer.lucene; import java.io.IOException; import java.util.Vector; public class UpdateKeeper implements Runnable { private static final long INTERVAL = 60000L; private static UpdateKeeper singleton; private Vector<UpdateJob> filterFactorys; private UpdateKeeper() { this.filterFactorys = new Vector<>(); Thread worker = new Thread(this); worker.setDaemon(true); worker.start(); } static UpdateKeeper getInstance() { if (singleton == null) { synchronized (UpdateKeeper.class) { if (singleton == null) { singleton = new UpdateKeeper(); return singleton; } } } return singleton; } void register(UpdateJob filterFactory) { this.filterFactorys.add(filterFactory); } @Override public void run() { //noinspection InfiniteLoopStatement while (true) { try { Thread.sleep(INTERVAL); } catch (InterruptedException e) { e.printStackTrace(); } if (!this.filterFactorys.isEmpty()) { for (UpdateJob factory : this.filterFactorys) { try { factory.update(); } catch (IOException e) { e.printStackTrace(); } } } } } public interface UpdateJob { void update() throws IOException; } }
4
/** * Copyright (c) 2015-2017, Michael Yang 杨福海 (fuhai999@gmail.com). * <p> * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.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.gnu.org/licenses/lgpl-3.0.txt * <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 io.jboot.core.rpc.motan; import com.weibo.api.motan.codec.Serialization; import com.weibo.api.motan.core.extension.SpiMeta; import io.jboot.Jboot; import java.io.IOException; @SpiMeta(name = "jboot") public class JbootMotanSerialization implements Serialization { @Override public byte[] serialize(Object obj) throws IOException { return Jboot.me().getSerializer().serialize(obj); } @Override public <T> T deserialize(byte[] bytes, Class<T> clz) throws IOException { return (T) Jboot.me().getSerializer().deserialize(bytes); } }
7
using System; using System.Collections.Generic; using System.Linq; using Geo.Abstractions.Interfaces; using Geo.Geometries; using Geo.Gps.Metadata; using Geo.Measure; namespace Geo.Gps { public class Track : IHasLength { public Track() { Metadata = new TrackMetadata(); Segments = new List<TrackSegment>(); } public TrackMetadata Metadata { get; private set; } public List<TrackSegment> Segments { get; set; } public LineString ToLineString() { return new LineString(Segments.SelectMany(x=>x.Fixes).Select(x => x.Coordinate)); } public TrackSegment GetFirstSegment() { return Segments.Count == 0 ? default(TrackSegment) : Segments[0]; } public TrackSegment GetLastSegment() { return Segments.Count == 0 ? default(TrackSegment) : Segments[Segments.Count - 1]; } public IEnumerable<Fix> GetAllFixes() { return Segments.SelectMany(x => x.Fixes); } public Fix GetFirstFix() { var segment = GetFirstSegment(); return segment == null ? default(Fix) : segment.GetFirstFix(); } public Fix GetLastFix() { var segment = GetLastSegment(); return segment == null ? default(Fix) : segment.GetLastFix(); } public Speed GetAverageSpeed() { return new Speed(GetLength().SiValue, GetDuration()); } public TimeSpan GetDuration() { return GetLastFix().TimeUtc - GetFirstFix().TimeUtc; } public void Quantize(double seconds = 0) { foreach (var segment in Segments) segment.Quantize(seconds); } public Distance GetLength() { return ToLineString().GetLength(); } } }
2
/* * 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.commons.csv.bugs; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.junit.Assert; import org.junit.Test; public class JiraCsv198Test { private static final CSVFormat CSV_FORMAT = CSVFormat.EXCEL.withDelimiter('^').withFirstRecordAsHeader(); @Test public void test() throws UnsupportedEncodingException, IOException { InputStream pointsOfReference = getClass().getResourceAsStream("/CSV-198/optd_por_public.csv"); Assert.assertNotNull(pointsOfReference); CSVParser parser = CSV_FORMAT.parse(new InputStreamReader(pointsOfReference, "UTF-8")); for (CSVRecord record : parser) { String locationType = record.get("location_type"); Assert.assertNotNull(locationType); } } }
7
using System; using System.Collections.Generic; using System.Linq; using Geo.Abstractions.Interfaces; using Geo.Geometries; using Geo.Measure; namespace Geo.Gps { public class TrackSegment : IHasLength { public TrackSegment() { Fixes = new List<Fix>(); } public List<Fix> Fixes { get; set; } public LineString ToLineString() { return new LineString(Fixes.Select(x => x.Coordinate)); } public bool IsEmpty() { return Fixes.Count == 0; } public Fix GetFirstFix() { return IsEmpty() ? default(Fix) : Fixes[0]; } public Fix GetLastFix() { return IsEmpty() ? default(Fix) : Fixes[Fixes.Count - 1]; } public Speed GetAverageSpeed() { return new Speed(GetLength().SiValue, GetDuration()); } public TimeSpan GetDuration() { return GetLastFix().TimeUtc - GetFirstFix().TimeUtc; } public Distance GetLength() { return ToLineString().GetLength(); } public void Quantize(double seconds = 0) { var fixes = new List<Fix>(); Fix lastFix = null; foreach (var fix in Fixes) { if (lastFix == null || Math.Abs((fix.TimeUtc - lastFix.TimeUtc).TotalSeconds) >= seconds) { lastFix = fix; fixes.Add(fix); } } Fixes = fixes; } } }
4
/* * 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.logging.log4j.core.helpers; import java.nio.charset.Charset; import org.apache.logging.log4j.status.StatusLogger; /** * Charset utilities. */ public final class Charsets { private static final String UTF_8 = "UTF-8"; private Charsets() { } /** * Gets a Charset, starting with the preferred {@code charsetName} if supported, if not, use UTF-8. * * @param charsetName * the preferred charset name * @return a Charset, not null. */ public static Charset getSupportedCharset(final String charsetName) { Charset charset = null; if (charsetName != null) { if (Charset.isSupported(charsetName)) { charset = Charset.forName(charsetName); } } if (charset == null) { charset = Charset.forName(UTF_8); if (charsetName != null) { StatusLogger.getLogger().error("Charset " + charsetName + " is not supported for layout, using " + charset.displayName()); } } return charset; } }
4
package io.github.biezhi.wechat.handler.msg; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import io.github.biezhi.wechat.model.xml.AppMsgInfo; public class AppMsgXmlHandlerTest { AppMsgXmlHandler handler; @Before public void setUp() throws Exception { String content = File2String.read("appmsg-file.xml"); handler = new AppMsgXmlHandler(content); } @Test public void testGetRecents() { AppMsgInfo info = handler.decode(); Assert.assertEquals("南京abc.xlsx", info.title); System.out.println(info); handler = new AppMsgXmlHandler( File2String.read("appmsg-publisher.xml")); info = handler.decode(); Assert.assertEquals("谷歌开发者", info.appName); System.out.println(info); } }
10
using System; using System.Collections.Generic; using System.Data.SqlClient; using HangFire.Server; using HangFire.Server.Components; using HangFire.SqlServer.Components; using HangFire.Storage; using HangFire.Storage.Monitoring; namespace HangFire.SqlServer { public class SqlServerStorage : JobStorage { private readonly SqlServerStorageOptions _options; private readonly string _connectionString; public SqlServerStorage(string connectionString) : this(connectionString, new SqlServerStorageOptions()) { } public SqlServerStorage(string connectionString, SqlServerStorageOptions options) { if (connectionString == null) throw new ArgumentNullException("connectionString"); if (options == null) throw new ArgumentNullException("options"); _options = options; _connectionString = connectionString; } public override IMonitoringApi CreateMonitoring() { return new SqlServerMonitoringApi(new SqlConnection(_connectionString)); } public override IStorageConnection CreateConnection() { return CreatePooledConnection(); } public override IStorageConnection CreatePooledConnection() { return new SqlStorageConnection(this, new SqlConnection(_connectionString)); } public override IEnumerable<IThreadWrappable> GetComponents() { yield return new SchedulePoller(CreateConnection(), _options.PollInterval); yield return new ServerWatchdog(CreateConnection()); yield return new ExpirationManager(new SqlConnection(_connectionString)); } } }
4
package com.naturalprogrammer.spring.boot.security; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; import org.springframework.stereotype.Component; import com.fasterxml.jackson.databind.ObjectMapper; import com.naturalprogrammer.spring.boot.SaUtil; @Component public class AuthSuccess extends SimpleUrlAuthenticationSuccessHandler { private Log log = LogFactory.getLog(getClass()); @Autowired private ObjectMapper objectMapper; public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { // instead of this, the statement below is introduced: handle(request, response, authentication); response.setStatus(HttpServletResponse.SC_OK); response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getSessionUser().getUserDto())); clearAuthenticationAttributes(request); log.info("AuthenticationSuccess: " + SaUtil.getSessionUser().getUserDto()); } }
4
/* * Copyright 2010 Henry Coles * * 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.pitest.mutationtest.instrument; import java.io.File; import java.util.regex.Pattern; import org.pitest.functional.Option; import org.pitest.util.JavaAgent; public class JavaAgentJarFinder implements JavaAgent { private static final Pattern JAR_REGEX = Pattern .compile(".*pitest-[\\w-\\.]*.jar"); private final String location; public JavaAgentJarFinder() { String pitJar = findPathToJarFileFromClasspath(); if (pitJar == null) { pitJar = "pitest-agent.jar"; } this.location = pitJar; } private String findPathToJarFileFromClasspath() { final String[] classPath = System.getProperty("java.class.path").split( File.pathSeparator); for (final String root : classPath) { if (JAR_REGEX.matcher(root).matches()) { return root; } } return null; } public Option<String> getJarLocation() { // TODO Auto-generated method stub return Option.some(this.location); } }
10
using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Tau.Objects; using osu.Game.Rulesets.Tau.UI; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Tau.Mods { public class TauModHidden : ModHidden, IApplicableToDrawableRuleset<TauHitObject> { public override string Description => @"Play with no beats and fading sliders."; public override double ScoreMultiplier => 1.06; public virtual void ApplyToDrawableRuleset(DrawableRuleset<TauHitObject> drawableRuleset) { TauPlayfield tauPlayfield = (TauPlayfield)drawableRuleset.Playfield; var HOC = tauPlayfield.HitObjectContainer; Container HOCParent = (Container)tauPlayfield.HitObjectContainer.Parent; HOCParent.Remove(HOC); HOCParent.Add(new PlayfieldMaskingContainer(HOC, Mode) { Coverage = InitialCoverage, }); } protected override void ApplyIncreasedVisibilityState(DrawableHitObject hitObject, ArmedState state) { } protected override void ApplyNormalVisibilityState(DrawableHitObject hitObject, ArmedState state) { } protected virtual MaskingMode Mode => MaskingMode.FadeOut; protected virtual float InitialCoverage => 0.4f; } }
10
using System; using Xunit; using FluentAssertions; using System.Collections.Generic; using Microsoft.Data.SqlClient.Server; namespace EasyData.EntityFrameworkCore.Relational.Tests { public class DbContextMetaDataLoaderTests { /// <summary> /// Test getting all entities. /// </summary> [Fact] public void LoadFromDbContextTest() { var dbContext = TestDbContext.Create(); var meta = new MetaData(); meta.LoadFromDbContext(dbContext); meta.EntityRoot.SubEntities.Should().HaveCount(8); var entityAttrCount = new Dictionary<string, int>() { ["Category"] = 4, ["Customer"] = 11, ["Employee"] = 19, ["Order"] = 16, ["Order Detail"] = 7, ["Product"] = 12, ["Shipper"] = 3, ["Supplier"] = 12 }; foreach (var entity in meta.EntityRoot.SubEntities) { entity.Attributes.Should().HaveCount(entityAttrCount[entity.Name]); } } } }
2
package com.github.jsoniter; import com.alibaba.fastjson.parser.JSONReaderScanner; import com.alibaba.fastjson.parser.JSONScanner; import com.alibaba.fastjson.parser.JSONToken; import org.openjdk.jmh.Main; import org.openjdk.jmh.annotations.Benchmark; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; public class JsoniterBenchmark { @Benchmark public void fastjson() { JSONScanner scanner = new JSONScanner(JsoniterBenchmarkState.inputString); scanner.nextToken(); do { scanner.nextToken(); scanner.intValue(); scanner.nextToken(); } while (scanner.token() == JSONToken.COMMA); } @Benchmark public void jsoniter() throws IOException { Jsoniter iter = Jsoniter.parseBytes(JsoniterBenchmarkState.inputBytes); while (iter.ReadArray()) { iter.ReadUnsignedInt(); } } public static void main(String[] args) throws Exception { Main.main(args); } }
2
package org.javaswift.joss.command.impl.core; import org.javaswift.joss.command.impl.identity.AuthenticationCommand; import org.javaswift.joss.exception.CommandException; import org.apache.http.client.methods.HttpRequestBase; import org.junit.Before; import org.junit.Test; import java.io.IOException; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; public class AbstractCommandTest extends BaseCommandTest { @Before public void setup() throws IOException { super.setup(); } @Test(expected = CommandException.class) public void httpClientThrowsAnException() throws IOException { when(httpClient.execute(any(HttpRequestBase.class))).thenThrow(new IOException("Mocked HTTP client error")); new AuthenticationCommand(httpClient, "http://some.url", "some-tenant", "some-user", "some-pwd").call(); } @Test(expected = CommandException.class) public void httpClientThrowsAnExceptionWithRootCause() throws IOException { IOException exc = new IOException("Mocked HTTP client error"); when(httpClient.execute(any(HttpRequestBase.class))).thenThrow(new CommandException("Something went wrong", exc)); new AuthenticationCommand(httpClient, "http://some.url", "some-tenant", "some-user", "some-pwd").call(); } }
2
/* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vafer.jdeb.ar; import java.io.File; import java.io.FileInputStream; import junit.framework.TestCase; public final class ArInputStreamTestCase extends TestCase { public void testRead() throws Exception { final File archive = new File(getClass().getResource("data.ar").toURI()); final ArInputStream ar = new ArInputStream(new FileInputStream(archive)); final ArEntry entry1 = ar.getNextEntry(); assertEquals("data.tgz", entry1.getName()); assertEquals(148, entry1.getLength()); for (int i = 0; i < entry1.getLength(); i++) { ar.read(); } final ArEntry entry2 = ar.getNextEntry(); assertNull(entry2); ar.close(); } }
10
using System.Net.Http; using System.Text; using Flux.Client; using Flux.Flux.Options; using Newtonsoft.Json.Linq; namespace Flux.Flux.Client { public class FluxService { public static HttpRequestMessage Query(string query) { return new HttpRequestMessage(new HttpMethod(HttpMethodKind.Post.Name()), "v2/query") { Content = new StringContent(query) }; } public static HttpRequestMessage Ping() { return new HttpRequestMessage(new HttpMethod(HttpMethodKind.Get.Name()), "ping"); } public static JObject GetDefaultDialect() { JObject json = new JObject(); json.Add("header", true); json.Add("delimiter", ","); json.Add("quoteChar", "\""); json.Add("commentPrefix", "#"); json.Add("annotations", new JArray("datatype", "group", "default")); return json; } public static string CreateBody(JObject dialect, string query) { Preconditions.CheckNonEmptyString(query, "Flux query"); JObject json = new JObject(); json.Add("query", query); if (dialect != null) { json.Add("dialect", dialect); } return json.ToString(); } } }
10
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Moq; using NUnit.Framework; using SendGridMail; namespace Tests { [TestFixture] public class TestHeader { [Test] public void TestAddTo() { var foo = new Mock<IHeader>(); foo.Setup(m => m.Enable("foo")); var bar = new SendGrid(foo.Object); Assert.AreEqual(1, 2, "I suck"); } } }
4
package hudson.plugins.swarm; import hudson.Extension; import hudson.Plugin; import hudson.model.UnprotectedRootAction; import java.io.IOException; import javax.servlet.ServletException; import jenkins.model.Jenkins; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; @Extension public class DownloadClientAction implements UnprotectedRootAction { @Override public String getIconFileName() { return null; } @Override public String getDisplayName() { return null; } @Override public String getUrlName() { return "swarm"; } // serve static resources @Restricted(NoExternalUse.class) public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { Plugin plugin = Jenkins.getInstance().getPlugin("swarm"); if (plugin != null) { plugin.doDynamic(req, rsp); } } }
7
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using NetMQ; using zmq; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Context context = Context.Create(); PublisherSocket pub = context.CreatePublisherSocket(); SubscriberSocket sub = context.CreateSubscriberSocket(); pub.Bind("tcp://127.0.0.1:8000"); sub.Connect("tcp://127.0.0.1:8000"); sub.Subscribe("hello"); Thread.Sleep(2000); //while (true) //{ // pub.SendTopic("hello").Send("message"); // Console.WriteLine("Done"); //} bool isMore ; string message = sub.ReceiveString(out isMore); Console.WriteLine(message); message = sub.ReceiveString(out isMore); Console.WriteLine(message); Console.ReadLine(); } } }
10
using System; using Serilog.Configuration; using Serilog.Events; using Serilog.Sinks.Async; namespace Serilog { /// <summary> /// Extends <see cref="LoggerConfiguration"/> with methods for configuring asynchronous logging. /// </summary> public static class LoggerConfigurationAsyncExtensions { /// <summary> /// Configure a sink to be invoked asynchronously, on a background worker thread. /// </summary> /// <param name="loggerSinkConfiguration">The <see cref="LoggerSinkConfiguration"/> being configured.</param> /// <param name="configure">An action that configures the wrapped sink.</param> /// <param name="bufferSize">The size of the concurrent queue used to feed the background worker thread. If /// the thread is unable to process events quickly enough and the queue is filled, subsequent events will be /// dropped until room is made in the queue.</param> /// <returns>A <see cref="LoggerConfiguration"/> allowing configuration to continue.</returns> public static LoggerConfiguration Async( this LoggerSinkConfiguration loggerSinkConfiguration, Action<LoggerSinkConfiguration> configure, int bufferSize = 10000) { var sublogger = new LoggerConfiguration(); sublogger.MinimumLevel.Is(LevelAlias.Minimum); configure(sublogger.WriteTo); var wrapper = new BackgroundWorkerSink(sublogger.CreateLogger(), bufferSize); return loggerSinkConfiguration.Sink(wrapper); } } }
3
package us.codecraft.webmagic.selector.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * @author code4crafer@gmail.com * @since 0.5.0 */ public class ThreadPool { private int threadNum; private int threadAlive; private ReentrantLock reentrantLock = new ReentrantLock(); private Condition condition = reentrantLock.newCondition(); public ThreadPool(int threadNum) { this.threadNum = threadNum; this.executorService = Executors.newFixedThreadPool(threadNum); } public ThreadPool(int threadNum, ExecutorService executorService) { this.threadNum = threadNum; this.executorService = executorService; } public void setExecutorService(ExecutorService executorService) { this.executorService = executorService; } public int getThreadAlive() { return threadAlive; } public int getThreadNum() { return threadNum; } private ExecutorService executorService; public void execute(Runnable runnable) { try { reentrantLock.lock(); while (threadAlive >= threadNum) { try { condition.await(); } catch (InterruptedException e) { } } threadAlive++; System.out.println(threadAlive); executorService.execute(runnable); } finally { threadAlive--; condition.signal(); reentrantLock.unlock(); } } public boolean isShutdown() { return executorService.isShutdown(); } public void shutdown() { executorService.shutdown(); } }
10
using System; using System.Collections.Generic; namespace HttpMock { public class HttpServerFactory { private readonly Dictionary<int, IHttpServer> _httpServers = new Dictionary<int, IHttpServer>(); public IHttpServer Get(Uri uri) { if (_httpServers.ContainsKey(uri.Port)) { IHttpServer httpServer = _httpServers[uri.Port]; if (httpServer.IsAvailable()) return httpServer; } return Create(uri); } public IHttpServer Create(Uri uri) { IHttpServer httpServer = BuildServer(uri); _httpServers[uri.Port] = httpServer; return _httpServers[uri.Port]; } private IHttpServer BuildServer(Uri uri) { IHttpServer httpServer = new HttpServer(uri); httpServer.Start(); return httpServer; } } }
10
/* * 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. */ using System; using System.Security.Cryptography; using System.Text; using Aliyun.Acs.Core.Auth; namespace Aliyun.Acs.Core { public class HmacSHA1Signer : Signer { private const String ALGORITHM_NAME = "HmacSHA1"; public const String ENCODING = "UTF-8"; public override String SignString(String stringToSign, String accessKeySecret) { HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(accessKeySecret)); byte[] hashValue = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)); return Convert.ToBase64String(hashValue); } public override String SignString(String stringToSign, AlibabaCloudCredentials credentials) { return SignString(stringToSign, credentials.GetAccessKeySecret()); } public override String GetSignerName() { return "HMAC-SHA1"; } public override String GetSignerVersion() { return "1.0"; } public override String GetSignerType() { return null; } } }
2
package com.mtons.mblog.web.menu; import com.alibaba.fastjson.JSONArray; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.List; /** * 加载后台Menu菜单 * * @author - langhsu * @create - 2018/5/18 */ public class MenuJsonUtils { private static String config = "/scripts/menu.json"; private static List<Menu> menus; /** * 将配置文件转换成 List 对象 * * @return */ private static synchronized List<Menu> loadJson() throws IOException { InputStream inStream = MenuJsonUtils.class.getResourceAsStream(config); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, Charset.forName("UTF-8"))); StringBuilder json = new StringBuilder(); String tmp; while ((tmp = reader.readLine()) != null) { json.append(tmp); } List<Menu> menus = JSONArray.parseArray(json.toString(), Menu.class); return menus; } public static List<Menu> getMenus() { if (null == menus) { try { menus = loadJson(); } catch (IOException e) { e.printStackTrace(); } } return menus; } }
10
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.IO; using LibOrbisPkg; using System.Windows.Forms; namespace PkgEditor { public partial class MainWin : Form { public MainWin() { InitializeComponent(); } private void ShowOpenFileDialog(string title, string filetypes, Action<string> successCb) { var ofd = new OpenFileDialog(); ofd.Title = title; ofd.Filter = filetypes; if(ofd.ShowDialog() == DialogResult.OK) { successCb(ofd.FileName); } } private void openGp4(string filename) { using (var fs = File.OpenRead(filename)) { var proj = LibOrbisPkg.GP4.Gp4Project.ReadFrom(fs); OpenTab(new Views.ObjectView(proj), Path.GetFileName(filename)); } } private void openPkg(string filename) { using (var fs = File.OpenRead(filename)) { var pkg = new LibOrbisPkg.PKG.PkgReader(fs).ReadHeader(); OpenTab(new Views.ObjectView(pkg), Path.GetFileName(filename)); } } public void OpenTab(UserControl c, string name) { var x = new TabPage(name); c.Name = name; x.Controls.Add(c); //c.SetBrowser(this); c.Dock = DockStyle.Fill; tabs.TabPages.Add(x); tabs.SelectedTab = x; } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void openGP4ToolStripMenuItem_Click(object sender, EventArgs e) { ShowOpenFileDialog("Open GP4 Project", "GP4 Projects|*.gp4", openGp4); } private void openPKGToolStripMenuItem_Click(object sender, EventArgs e) { ShowOpenFileDialog("Open PKG Package", "PKG|*.pkg", openPkg); } } }
2
package de.codecentric.notifications; import static java.util.Arrays.asList; import org.bson.Document; import com.mongodb.Block; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.ChangeStreamIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.model.Aggregates; import static com.mongodb.client.model.Filters.*; import com.mongodb.client.model.changestream.ChangeStreamDocument; public class EventListener { public static void main(String[] args) throws Exception { MongoCollection<Document> eventCollection = new MongoClient( new MongoClientURI("mongodb://localhost:27001,localhost:27002,localhost:27003/test?replicatSet=demo-dev") ).getDatabase("test").getCollection("events"); ChangeStreamIterable<Document> changes = eventCollection.watch(asList( Aggregates.match( and( asList( in("operationType", asList("insert")), eq("fullDocument.even", 1L))) ))); changes.forEach(new Block<ChangeStreamDocument<Document>>() { @Override public void apply(ChangeStreamDocument<Document> t) { System.out.println("received: " + t.getFullDocument()); } }); } }
4
package com.maxmind.geoip2; import java.lang.*; import java.util.*; import java.io.*; import org.apache.http.*; import org.apache.http.client.*; import org.apache.http.client.methods.*; import org.apache.http.impl.client.*; import org.apache.http.impl.auth.*; import org.apache.http.auth.*; import org.json.*; /** * Hello world! * */ public class App { public static void main( String[] args ) { try { String user_id = args[0]; String license_key = args[1]; String ip_address = args[2]; Client cl = new Client(user_id,license_key); JSONObject o = cl.Country(ip_address); o = o.getJSONObject("country"); o = o.getJSONObject("name"); String name = o.getString("en"); System.out.println(name); } catch (JSONException e) { e.printStackTrace(); } } }
4
using RPGCore.Behaviour; using RPGCore.Demo.BoardGame.Models; namespace RPGCore.Demo.BoardGame { public class BuildBuildingProcedure : GameViewProcedure { public LocalId Player { get; set; } public string BuildingIdentifier { get; set; } public Integer2 Offset { get; set; } public Integer2 BuildingPosition { get; set; } public BuildingOrientation Orientation { get; set; } public override ProcedureResult Apply(GameView view) { var buildingTemplate = new BuildingTemplate() { Recipe = new string[,] { { "x", "x", "x" }, { "x", null, null }, } }; var rotatedBuilding = new RotatedBuilding(buildingTemplate, Orientation); var ownerPlayer = view.GetPlayerForOwner(Player); for (int x = 0; x < rotatedBuilding.Width; x++) { for (int y = 0; y < rotatedBuilding.Height; y++) { var position = Offset + new Integer2(x, y); string recipeTile = rotatedBuilding[x, y]; var tile = ownerPlayer.Board[position]; if (recipeTile != null) { tile.Resource = "x"; } } } var placeTile = ownerPlayer.Board[BuildingPosition]; placeTile.Building = new Building(buildingTemplate, placeTile); return ProcedureResult.Success; } } }
10
using System.IO; using Camelot.FileSystemWatcherWrapper.Configuration; using Camelot.FileSystemWatcherWrapper.Interfaces; using Camelot.Services.Abstractions; namespace Camelot.FileSystemWatcherWrapper.Implementations { public class FileSystemWatcherFactory : IFileSystemWatcherFactory { private readonly IPathService _pathService; private readonly FileSystemWatcherConfiguration _fileSystemWatcherConfiguration; public FileSystemWatcherFactory( IPathService pathService, FileSystemWatcherConfiguration fileSystemWatcherConfiguration) { _pathService = pathService; _fileSystemWatcherConfiguration = fileSystemWatcherConfiguration; } public IFileSystemWatcher Create(string directory) { var fileSystemWatcher = new FileSystemWatcher { Path = directory, NotifyFilter = NotifyFilters.Attributes | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size }; var wrapper = new FileSystemWatcherAdapter(fileSystemWatcher); return new AggregatingFileSystemWatcherDecorator(_pathService, wrapper, _fileSystemWatcherConfiguration); } } }
10
using Microsoft.EntityFrameworkCore; using Store.Common; using Store.Core; using Store.Core.BusinessLayer; using Store.Core.BusinessLayer.Contracts; using Store.Core.DataLayer; namespace Store.Mocker { public static class ServiceMocker { private static readonly string ConnectionString; static ServiceMocker() { // todo: Load connection string from appsettings.json file ConnectionString = "server=(local);database=Store;integrated security=yes;MultipleActiveResultSets=True;"; } public static IHumanResourcesService GetHumanResourcesService() => new HumanResourcesService( LogHelper.GetLogger<HumanResourcesService>(), new UserInfo { Name = "mocker" }, new StoreDbContext(new DbContextOptionsBuilder<StoreDbContext>().UseSqlServer(ConnectionString).Options) ); public static IProductionService GetProductionService() => new ProductionService( LogHelper.GetLogger<ProductionService>(), new UserInfo { Name = "mocker" }, new StoreDbContext(new DbContextOptionsBuilder<StoreDbContext>().UseSqlServer(ConnectionString).Options) ); public static ISalesService GetSalesService() => new SalesService( LogHelper.GetLogger<SalesService>(), new UserInfo { Name = "mocker" }, new StoreDbContext(new DbContextOptionsBuilder<StoreDbContext>().UseSqlServer(ConnectionString).Options) ); } }
2
package com.itlong.whatsmars.base.tmp; import java.io.BufferedReader; import java.io.FileReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; /** * Created by shenhongxi on 2015/11/9. * javahongxi */ public class T { public static void main(String[] args) throws Exception { String path = "E:/btdata/bt_cumulation.txt"; BufferedReader br = new BufferedReader(new FileReader(path)); String line = null; br.readLine(); PrintWriter pw = new PrintWriter("E:/btdata/bt_cumulation2.txt"); int i = 0; while ((line = br.readLine()) != null) { //System.out.println("'" + line + "',"); String[] ss = line.split(","); String pin = ss[1]; pw.println(pin); if (i++ % 10 == 0) { pw.flush(); System.out.println(i); } } br.close(); pw.close(); } }
4
using Humanizer; using System; using System.Linq; using System.Reflection; namespace Atata { public static class EnumExtensions { public static string ToTitleString(this Enum value) { return value.ToString(LetterCasing.Title); } public static string ToSentenceString(this Enum value) { return value.ToString(LetterCasing.Sentence); } public static string ToString(this Enum value, LetterCasing casing) { Type type = value.GetType(); MemberInfo memberInfo = type.GetMember(value.ToString())[0]; TermAttribute termAttribute = memberInfo.GetCustomAttribute<TermAttribute>(false); string term = (termAttribute != null && termAttribute.Values != null && termAttribute.Values.Any()) ? termAttribute.Values.First() : value.ToString(); return (termAttribute.Format != TermFormat.Inherit) ? termAttribute.Format.ApplyTo(term) : term.Humanize(casing); } } }
2
package hivemall.knn.distance; import java.util.Arrays; import java.util.List; import org.apache.hadoop.io.FloatWritable; import org.junit.Assert; import org.junit.Test; public class EuclidDistanceUDFTest { @Test public void test1() { EuclidDistanceUDF udf = new EuclidDistanceUDF(); List<String> ftvec1 = Arrays.asList("1:1.0", "2:2.0", "3:3.0"); List<String> ftvec2 = Arrays.asList("1:2.0", "2:4.0", "3:6.0"); FloatWritable d = udf.evaluate(ftvec1, ftvec2); Assert.assertEquals((float) Math.sqrt(1.0 + 4.0 + 9.0), d.get(), 0.f); } @Test public void test2() { EuclidDistanceUDF udf = new EuclidDistanceUDF(); List<String> ftvec1 = Arrays.asList("1:1.0", "2:3.0", "3:3.0"); List<String> ftvec2 = Arrays.asList("1:2.0", "3:6.0"); FloatWritable d = udf.evaluate(ftvec1, ftvec2); Assert.assertEquals((float) Math.sqrt(1.0 + 9.0 + 9.0), d.get(), 0.f); } }
4
package org.imixs.workflow.util; import java.io.InputStream; import java.text.ParseException; import java.util.List; import junit.framework.Assert; import org.imixs.workflow.ItemCollection; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Test class test the parsing of a json file used by the workflowRestService * method postWorkitemJSON(InputStream requestBodyStream) * * * @author rsoika */ public class TestJSONParser { @Before public void setup() { } @After public void teardown() { } @Test public void testSimple() throws ParseException { InputStream inputStream = getClass() .getResourceAsStream("/json/simple.json"); ItemCollection itemCol = JSONParser.parseWorkitem(inputStream); Assert.assertNotNull(itemCol); Assert.assertEquals("Anna", itemCol.getItemValueString("$readaccess")); List<?> list=itemCol.getItemValue("txtLog"); Assert.assertEquals(3, list.size()); Assert.assertEquals("C", list.get(2)); Assert.assertEquals(10, itemCol.getItemValueInteger("$ActivityID")); } @Test(expected = ParseException.class) public void testCorrupted() throws ParseException { InputStream inputStream = getClass() .getResourceAsStream("/json/corrupted.json"); ItemCollection itemCol = JSONParser.parseWorkitem(inputStream); Assert.assertNull(itemCol); } @Test public void testComplexWorkitem() throws ParseException { InputStream inputStream = getClass() .getResourceAsStream("/json/workitem.json"); ItemCollection itemCol = JSONParser.parseWorkitem(inputStream); Assert.assertNotNull(itemCol); Assert.assertEquals("worklist", itemCol.getItemValueString("txtworkflowresultmessage")); Assert.assertEquals("14194929161-1003e42a", itemCol.getItemValueString("$UniqueID")); List<?> list=itemCol.getItemValue("txtworkflowpluginlog"); Assert.assertEquals(7, list.size()); } }
10
using System; namespace Eto.Forms { public partial interface IActionItem { void Generate(ISubMenuWidget menu); } public abstract partial class ActionItemBase { public abstract void Generate(ISubMenuWidget menu); } public partial class ActionItemSeparator : ActionItemBase { public override void Generate(ISubMenuWidget menu) { menu.MenuItems.Add(new SeparatorMenuItem(menu.Generator)); } } public partial class ActionItemSubMenu : ActionItemBase { public override void Generate(ISubMenuWidget menu) { if (actions.Count > 0) { var item = new ImageMenuItem(menu.Generator); item.Text = SubMenuText; actions.Generate(item); menu.MenuItems.Add(item); } } } public partial class ActionItem : ActionItemBase { public override void Generate(ISubMenuWidget menu) { var item = this.Action.Generate(this, menu); if (item != null) menu.MenuItems.Add (item); } } }
10
using System; using System.Collections.Generic; using System.Text; using Microsoft.EntityFrameworkCore; using TestDatabase; using Xunit; namespace Threenine.Data.Tests { public class RepositoryAddTestsSQLLite { [Fact] public void ShouldAddNewProduct() { var uow = new UnitOfWork<TestDbContext>(GetSqlLiteInMemoryContext()); var repo = uow.GetRepository<TestProduct>(); var newProduct = new TestProduct() { Name = "Test Product", Category = new TestCategory() { Id = 1, Name = "UNi TEtS" } }; repo.Add(newProduct); uow.SaveChanges(); Assert.Equal(1, newProduct.Id); } private TestDbContext GetSqlLiteInMemoryContext() { var options = new DbContextOptionsBuilder<TestDbContext>() .UseSqlite("DataSource=:memory:") .Options; var context = new TestDbContext(options); context.Database.OpenConnection(); context.Database.EnsureCreated(); var testCat = new TestCategory(){ Id = 1, Name = "UNi TEtS"}; context.TestCategories.Add(testCat); context.SaveChanges(); return context; } } }
10
using System; using System.Collections.Generic; using System.IO; using System.Runtime.CompilerServices; using SDG.Unturned; #if NUGET_BOOTSTRAP using OpenMod.Bootstrapper; using OpenMod.NuGet; #else using System.Reflection; using Microsoft.Extensions.Hosting; using OpenMod.API; #endif namespace OpenMod.Unturned.Module { public class OpenModInitializer { [MethodImpl(MethodImplOptions.NoInlining)] public static void Initialize() { string openModDirectory = Path.GetFullPath($"Servers/{Dedicator.serverID}/OpenMod/"); if (!Directory.Exists(openModDirectory)) { Directory.CreateDirectory(openModDirectory); } #if NUGET_BOOTSTRAP Console.WriteLine("Bootstrapping OpenMod for Unturned, this might take a while..."); var bootrapper = new OpenModDynamicBootstrapper(); bootrapper.Bootstrap( openModDirectory, Environment.GetCommandLineArgs(), new List<string> { "OpenMod.Unturned" }, false, new NuGetConsoleLogger()); #else var hostBuilder = new HostBuilder(); var parameters = new RuntimeInitParameters { CommandlineArgs = Environment.GetCommandLineArgs(), WorkingDirectory = openModDirectory }; var assemblies = new List<Assembly> { typeof(OpenMod.UnityEngine.UnityMainThreadDispatcher).Assembly, typeof(OpenMod.Unturned.OpenModUnturnedHost).Assembly }; var runtime = new Runtime.Runtime(); runtime.Init(assemblies, hostBuilder, parameters); #endif } } }
4
using System; using System.IO; using System.Linq; using System.Text; using UniversalDownloaderPlatform.Common.Enums; using UniversalDownloaderPlatform.Common.Helpers; namespace PatreonDownloader.Implementation { /// <summary> /// Helper used to generate name for post subdirectories /// </summary> internal class PostSubdirectoryHelper { /// <summary> /// Create a sanitized directory name based on supplied name pattern /// </summary> /// <param name="crawledUrl">Crawled url with published date, post title and post id</param> /// <param name="pattern">Pattern for directory name</param> /// <returns></returns> public static string CreateNameFromPattern(PatreonCrawledUrl crawledUrl, string pattern) { string postTitle = crawledUrl.Title.Trim(); while (postTitle.Length > 1 && postTitle[^1] == '.') postTitle = postTitle.Remove(postTitle.Length - 1).Trim(); string retString = pattern.ToLowerInvariant() .Replace("%publishedat%", crawledUrl.PublishedAt.ToString("yyyy-MM-dd")) .Replace("%posttitle%", postTitle) .Replace("%postid%", crawledUrl.PostId); return PathSanitizer.SanitizePath(retString); } } }
4
/* * Copyright (c) 2017 Villu Ruusmann * * This file is part of JPMML-SkLearn * * JPMML-SkLearn is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-SkLearn 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-SkLearn. If not, see <http://www.gnu.org/licenses/>. */ package sklearn_pandas; import java.util.Collections; import java.util.List; import numpy.core.Scalar; import org.dmg.pmml.MissingValueTreatmentMethod; import org.jpmml.converter.Feature; import org.jpmml.sklearn.ClassDictUtil; import org.jpmml.sklearn.SkLearnEncoder; import sklearn.Transformer; import sklearn.preprocessing.ImputerUtil; public class CategoricalImputer extends Transformer { public CategoricalImputer(String module, String name){ super(module, name); } @Override public List<Feature> encodeFeatures(List<Feature> features, SkLearnEncoder encoder){ Object fill = getFill(); Object missingValues = getMissingValues(); ClassDictUtil.checkSize(1, features); if(("NaN").equals(missingValues)){ missingValues = null; } Feature feature = features.get(0); return Collections.<Feature>singletonList(ImputerUtil.encodeFeature(feature, missingValues, fill, MissingValueTreatmentMethod.AS_MODE, encoder)); } public Object getFill(){ return asJavaObject(get("fill_")); } public Object getMissingValues(){ return asJavaObject(get("missing_values")); } static private Object asJavaObject(Object object){ if(object instanceof Scalar){ Scalar scalar = (Scalar)object; return scalar.getOnlyElement(); } return object; } }
10
using System.IO; namespace LECommonLibrary { public enum PEType { X32, X64, Unknown, } public static class PEFileReader { public static PEType GetPEType(string path) { if (string.IsNullOrEmpty(path)) return PEType.Unknown; var br = new BinaryReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite )); br.BaseStream.Seek(0x3C, SeekOrigin.Begin); br.BaseStream.Seek(br.ReadInt32() + 4, SeekOrigin.Begin); ushort machine = br.ReadUInt16(); br.Close(); if (machine == 0x014C) return PEType.X32; if (machine == 0x8664) return PEType.X64; return PEType.Unknown; } } }
10
namespace Nancy.Tests.Specifications { using System.Collections.Generic; using System.IO; using Nancy.Routing; public abstract class RequestSpec { protected static INancyEngine engine; protected static IRequest request; protected static Response response; protected RequestSpec() { engine = new NancyEngine(new AppDomainModuleLocator(), new RouteResolver()); } protected static IRequest ManufactureGETRequestForRoute(string route) { return new Request("GET", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); } protected static IRequest ManufacturePOSTRequestForRoute(string route) { return new Request("POST", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); } protected static IRequest ManufactureDELETERequestForRoute(string route) { return new Request("DELETE", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); } protected static IRequest ManufacturePUTRequestForRoute(string route) { return new Request("PUT", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); } protected static IRequest ManufactureHEADRequestForRoute(string route) { return new Request("HEAD", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); } } }
10
namespace Nancy.Tests.Specifications { using System.Collections.Generic; using System.IO; using Nancy.Routing; public abstract class RequestSpec { protected static INancyEngine engine; protected static IRequest request; protected static Response response; protected RequestSpec() { engine = new NancyEngine(new AppDomainModuleLocator(new DefaultModuleActivator()), new RouteResolver()); } protected static IRequest ManufactureGETRequestForRoute(string route) { return new Request("GET", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); } protected static IRequest ManufacturePOSTRequestForRoute(string route) { return new Request("POST", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); } protected static IRequest ManufactureDELETERequestForRoute(string route) { return new Request("DELETE", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); } protected static IRequest ManufacturePUTRequestForRoute(string route) { return new Request("PUT", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); } protected static IRequest ManufactureHEADRequestForRoute(string route) { return new Request("HEAD", route, new Dictionary<string, IEnumerable<string>>(), new MemoryStream()); } } }
4
import com.jfinal.kit.LogKit; import com.jfinal.plugin.activerecord.Db; import com.jfinal.plugin.activerecord.Record; import io.jboot.Jboot; import io.jboot.component.hystrix.annotation.EnableHystrixCommand; import io.jboot.db.dao.JbootDaoBase; import io.jboot.db.model.JbootModel; import io.jboot.web.controller.JbootController; import io.jboot.web.controller.annotation.RequestMapping; import javax.inject.Inject; import javax.inject.Singleton; import java.util.List; @RequestMapping("/test") public class ControllerTest extends JbootController { public static void main(String[] args) { Jboot.setBootArg("jboot.hystrix.url", "/hystrix.stream"); Jboot.setBootArg("jboot.cache.type", "redis"); Jboot.setBootArg("jboot.cache.redis.host", "127.0.0.1"); Jboot.run(args); } @Inject @EnableHystrixCommand ServiceTest serviceTest; // @JbootrpcService // ServiceInter serviceInter; public void index() { List<Record> records = Db.find("select * from `user`"); System.out.println("index .... "); LogKit.error("xxxxxxx"); Jboot.getCache().put("test","test","valueeeeeeeeee"); String value = Jboot.getCache().get("test","test"); System.out.println("value:"+value); renderText("hello " + serviceTest.getName()); // render(); } @Singleton public static class ServiceTest extends JbootDaoBase { public String getName() { return "michael"; } @Override public JbootModel findById(Object id) { return null; } @Override public boolean deleteById(Object id) { return false; } } public static interface ServiceInter { public String hello(); } }
4
package fr.opensagres.xdocreport.document.pptx.preprocessor; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.xml.sax.Attributes; import fr.opensagres.xdocreport.document.preprocessor.sax.BufferedElement; import fr.opensagres.xdocreport.document.preprocessor.sax.ISavable; public class APBufferedRegion extends BufferedElement { private List<ARBufferedRegion> arBufferedRegions = new ArrayList<ARBufferedRegion>(); public APBufferedRegion(BufferedElement parent, String uri, String localName, String name, Attributes attributes) { super(parent, uri, localName, name, attributes); } @Override public void addRegion(ISavable region) { if (region instanceof ARBufferedRegion) { arBufferedRegions.add((ARBufferedRegion) region); } else { super.addRegion(region); } } public void process() { Collection<BufferedElement> toRemove = new ArrayList<BufferedElement>(); int size = arBufferedRegions.size(); String s = null; StringBuilder fullContent = new StringBuilder(); boolean fieldFound = false; ARBufferedRegion currentAR = null; ARBufferedRegion lastAR = null; for (int i = 0; i < size; i++) { currentAR = arBufferedRegions.get(i); s = currentAR.getTContent(); if (fieldFound) { fieldFound = !(s == null || s.length() == 0 || Character .isWhitespace(s.charAt(0))); } else { fieldFound = s != null && s.indexOf("$") != -1; } if (fieldFound) { fullContent.append(s); toRemove.add(currentAR); } else { if (fullContent.length() > 0) { lastAR.setTContent(fullContent.toString()); fullContent.setLength(0); toRemove.remove(lastAR); } } lastAR = currentAR; } if (fullContent.length() > 0) { lastAR.setTContent(fullContent.toString()); fullContent.setLength(0); toRemove.remove(lastAR); } super.removeAll(toRemove); } }
4
/** * Copyright (c) 2015-2017, Michael Yang 杨福海 (fuhai999@gmail.com). * <p> * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.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.gnu.org/licenses/lgpl-3.0.txt * <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 io.jboot.wechat; import com.jfinal.weixin.sdk.cache.IAccessTokenCache; import io.jboot.Jboot; public class JbootAccessTokenCache implements IAccessTokenCache { static final String cache_name = "wechat_access_tokens"; @Override public String get(String key) { return Jboot.getJbootCache().get(cache_name, key); } @Override public void set(String key, String value) { Jboot.getJbootCache().put(cache_name, key, value); } @Override public void remove(String key) { Jboot.getJbootCache().remove(cache_name, key); } }
2
package com.github.tobato.fastdfs.domain.conn; import com.github.tobato.fastdfs.TestConstants; import com.github.tobato.fastdfs.domain.fdfs.GroupState; import com.github.tobato.fastdfs.domain.proto.tracker.TrackerListGroupsCommand; import com.github.tobato.fastdfs.exception.FdfsConnectException; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * 验证会轮询地址 * * @author tobato */ public class TrackerConnectionManagerTest { /** * 日志 */ protected static Logger LOGGER = LoggerFactory.getLogger(TrackerConnectionManagerTest.class); private String[] ips = {"192.168.174.141:22122", "192.168.1.115:22122"}; private List<String> trackerIpList = Arrays.asList(ips); @Test public void testConnectionManager() { // 初始化 TrackerConnectionManager manager = new TrackerConnectionManager(createPool()); manager.setTrackerList(trackerIpList); manager.initTracker(); List<GroupState> list = null; // 第一次执行 try { // 连接失败 list = manager.executeFdfsTrackerCmd(new TrackerListGroupsCommand()); fail("No exception thrown."); } catch (Exception e) { assertTrue(e instanceof FdfsConnectException); } // 第二次执行 try { // 连接失败 list = manager.executeFdfsTrackerCmd(new TrackerListGroupsCommand()); fail("No exception thrown."); } catch (Exception e) { assertTrue(e instanceof FdfsConnectException); } LOGGER.debug("执行结果{}", list); } private FdfsConnectionPool createPool() { PooledConnectionFactory factory = new PooledConnectionFactory(); factory.setConnectTimeout(TestConstants.connectTimeout); factory.setSoTimeout(TestConstants.soTimeout); return new FdfsConnectionPool(factory); } }
4
package org.rapidoid.http.customize.defaults; import org.rapidoid.RapidoidThing; import org.rapidoid.annotation.Authors; import org.rapidoid.annotation.Since; import org.rapidoid.http.Req; import org.rapidoid.http.customize.BeanParameterFactory; import org.rapidoid.http.customize.Customization; import java.util.Map; /* * #%L * rapidoid-http-fast * %% * Copyright (C) 2014 - 2017 Nikolche Mihajlovski and contributors * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ @Authors("Nikolche Mihajlovski") @Since("5.1.0") public class DefaultBeanParameterFactory extends RapidoidThing implements BeanParameterFactory { @Override public Object getParamValue(Req req, Class<?> paramType, String paramName, Map<String, Object> properties) throws Exception { return Customization.of(req).jackson().convertValue(properties, paramType); } }
2
package org.seckill.service; import lombok.extern.slf4j.Slf4j; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * 服务启动类 * Created by techa03 on 2017/2/3. */ @Slf4j public class GoodsKillRpcServiceApplication { public static void main(String[] args) { log.info(">>>>> goodsKill-rpc-service 正在启动 <<<<<"); AbstractApplicationContext context= new ClassPathXmlApplicationContext( "classpath*:META-INF/spring/spring-*.xml"); // 程序退出前优雅关闭JVM context.registerShutdownHook(); context.start(); log.info(">>>>> goodsKill-rpc-service 启动完成 <<<<<"); } }
4
/* * Copyright (c) 2012-2015, Luigi R. Viggiano * All rights reserved. * * This software is distributable under the BSD license. * See the terms of the BSD license in the documentation provided with this software. */ package org.aeonbits.owner; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; /** * @author Luigi R. Viggiano */ class ConfigURIFactory { private static final String CLASSPATH_PROTOCOL = "classpath:"; private final transient ClassLoader classLoader; private final VariablesExpander expander; ConfigURIFactory(ClassLoader classLoader, VariablesExpander expander) { this.classLoader = classLoader; this.expander = expander; } URI newURI(String spec) throws URISyntaxException { String expanded = expand(spec); if (expanded.startsWith(CLASSPATH_PROTOCOL)) { String path = expanded.substring(CLASSPATH_PROTOCOL.length()); URL url = classLoader.getResource(path); if (url == null) return null; return url.toURI(); } else { return new URI(expanded); } } private String expand(String path) { return expander.expand(path); } String toClasspathURLSpec(String name) { return CLASSPATH_PROTOCOL + name.replace('.', '/'); } }
4
package cc.blynk.server.notifications.push; import cc.blynk.server.notifications.push.android.AndroidGCMMessage; import cc.blynk.server.notifications.push.enums.Priority; import cc.blynk.server.notifications.push.ios.IOSGCMMessage; import com.fasterxml.jackson.core.JsonProcessingException; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * The Blynk Project. * Created by Dmitriy Dumanskiy. * Created on 26.06.15. */ public class GCMWrapperTest { @Test @Ignore public void testIOS() throws Exception { GCMWrapper gcmWrapper = new GCMWrapper(null, null); gcmWrapper.send(new IOSGCMMessage("to", Priority.normal, "yo!!!", 1), null, null); } @Test @Ignore public void testAndroid() throws Exception { GCMWrapper gcmWrapper = new GCMWrapper(null, null); gcmWrapper.send(new AndroidGCMMessage("", Priority.normal, "yo!!!", 1), null, null); } @Test public void testValidAndroidJson() throws JsonProcessingException { assertEquals("{\"to\":\"to\",\"priority\":\"normal\",\"data\":{\"message\":\"yo!!!\",\"dashId\":1}}", new AndroidGCMMessage("to", Priority.normal, "yo!!!", 1).toJson()); } @Test public void testValidIOSJson() throws JsonProcessingException { assertEquals("{\"to\":\"to\",\"priority\":\"normal\",\"notification\":{\"title\":\"Blynk Notification\",\"body\":\"yo!!!\",\"dashId\":1,\"sound\":\"default\"}}", new IOSGCMMessage("to", Priority.normal, "yo!!!", 1).toJson()); } }
10
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace Engine.Helpers { class EngineSyncContext : SynchronizationContext { private class Event : IDisposable { private SendOrPostCallback callback; private object state; private ManualResetEvent resetEvent; public WaitHandle Handle { get { return resetEvent; } } public Event(SendOrPostCallback callback, object state, bool isSend) { this.callback = callback; this.state = state; resetEvent = new ManualResetEvent(!isSend); } public void Dispatch() { var e = callback; if (e != null) e(state); resetEvent.Set(); } public void Dispose() { resetEvent.Close(); } } private Queue<Event> callbackQueue; private Thread engineTread; public EngineSyncContext() { callbackQueue = new Queue<Event>(); engineTread = new Thread(ThreadFunc); engineTread.IsBackground = true; engineTread.Start(); } public override void Post(SendOrPostCallback d, object state) { lock (callbackQueue) { callbackQueue.Enqueue(new Event(d, state, false)); } } public override void Send(SendOrPostCallback d, object state) { Event item = null; lock (callbackQueue) { item = new Event(d, state, true); callbackQueue.Enqueue(item); } if (item != null) item.Handle.WaitOne(); } public override SynchronizationContext CreateCopy() { return this; } private void ThreadFunc() { while(true) { lock(callbackQueue) { if (callbackQueue.Count <= 0) { Monitor.PulseAll(callbackQueue); continue; } var e = callbackQueue.Dequeue(); e.Dispatch(); } } } } }
2
package org.hotswap.agent.plugin.proxy.hscglib; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.hotswap.agent.javassist.ClassPool; import org.hotswap.agent.javassist.CtClass; import org.hotswap.agent.logging.AgentLogger; import org.hotswap.agent.plugin.proxy.ProxyTransformationUtils; /** * Stores GeneratorStrategy instance along with the parameter used to generate with it * * @author Erki Ehtla * */ public class GeneratorParametersRecorder { // this Map is used in the App ClassLoader public static Map<String, GeneratorParams> generatorParams = new ConcurrentHashMap<>(); private static AgentLogger LOGGER = AgentLogger.getLogger(GeneratorParametersRecorder.class); /** * * @param generatorStrategy * Cglib generator strategy instance that generated the bytecode * @param classGenerator * parameter used to generate the bytecode with generatorStrategy * @param bytes * generated bytecode */ public static void register(Object generatorStrategy, Object classGenerator, byte[] bytes) { try { ClassPool classPool = ProxyTransformationUtils.getClassPool(generatorStrategy.getClass().getClassLoader()); CtClass cc = classPool.makeClass(new ByteArrayInputStream(bytes), false); generatorParams.put(cc.getName(), new GeneratorParams(generatorStrategy, classGenerator)); cc.detach(); } catch (IOException | RuntimeException e) { LOGGER.error("Error saving parameters of a creation of a Cglib proxy", e); } } }
7
using System; using System.Reflection; using System.Threading; using System.Threading.Tasks; namespace Dasync.Accessors { public static class DelayPromiseAccessor { public static bool IsDelayPromise(Task task) { return task.GetType().Name == "DelayPromise"; } private static bool TryGetTimer(Task task, out Timer timer) { timer = null; if (task.GetType().Name == "DelayPromise") { timer = task.GetType() .GetField("Timer", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .GetValue(task) as Timer; } return timer != null; } public static bool TryGetTimerStartAndDelay(Task delayPromise, out DateTime startTime, out TimeSpan delay) { if (TryGetTimer(delayPromise, out var timer)) { timer.GetSettings(out var start, out var initialDelay, out var interval); if (start.HasValue && initialDelay.HasValue) { startTime = start.Value; delay = initialDelay.Value; return true; } } startTime = default(DateTime); delay = default(TimeSpan); return false; } public static bool TryCancelTimer(Task delayPromise) { if (TryGetTimer(delayPromise, out var timer)) { timer.Dispose(); return true; } return false; } } }
2
package net.runelite.cache.fs; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class DataFileTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void test1() throws IOException { File file = folder.newFile(); Store store = new Store(); DataFile df = new DataFile(store, 42, file); int sector = df.write(3, ByteBuffer.wrap("test".getBytes())); ByteBuffer buf = df.read(3, sector, 4); String str = new String(buf.array()); Assert.assertEquals("test", str); file.delete(); } @Test public void test2() throws IOException { byte[] b = new byte[1024]; for (int i = 0; i < 1024; ++i) b[i] = (byte) i; File file = folder.newFile(); Store store = new Store(); DataFile df = new DataFile(store, 42, file); int sector = df.write(0x1FFFF, ByteBuffer.wrap(b)); ByteBuffer buf = df.read(0x1FFFF, sector, b.length); Assert.assertArrayEquals(b, buf.array()); file.delete(); } }
10
using System; using System.Collections.Generic; using Flux.Client; using Flux.Flux.Options; using Platform.Common.Flux.Domain; namespace Flux.Examples { public class FluxClientSimpleExample { public static void Main(string[] args) { Console.WriteLine("Start"); FluxConnectionOptions options = new FluxConnectionOptions("http://127.0.0.1:8086", TimeSpan.FromSeconds(20)); FluxClient client = FluxClientFactory.Connect(options); String fluxQuery = "from(bucket: \"telegraf\")\n" + " |> filter(fn: (r) => (r[\"_measurement\"] == \"cpu\" AND r[\"_field\"] == \"usage_system\"))" + " |> range(start: -1d)" + " |> sample(n: 5, pos: 1)"; List<FluxTable> tables = client.Query(fluxQuery).GetAwaiter().GetResult(); } } }
2
package gumi.builders.url; import java.io.*; import java.nio.charset.Charset; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; /** * Regular expressions for URL parsing. * <p> * There are times when I wish Java had such advanced features as multiline * strings, or even a zero-dependency command to read a file into a string. * <p> * @author Mikael Gueck gumi{@literal @}iki.fi */ public class UrlRegularExpressions { private static final Charset ASCII = Charset.forName("ASCII"); public static final Pattern RFC3986_GENERIC_URL; static { RFC3986_GENERIC_URL = Pattern.compile( readResource("gumi/builders/url/rfc3986_generic_url.txt"), Pattern.CASE_INSENSITIVE | Pattern.COMMENTS); } private static String readResource(final String name) { final StringBuilder ret = new StringBuilder(); InputStream is = null; try { is = UrlRegularExpressions.class.getClassLoader().getResourceAsStream(name); final InputStreamReader reader = new InputStreamReader(is, ASCII); int read = 0; final char[] buf = new char[1024]; do { read = reader.read(buf, 0, buf.length); if (read > 0) { ret.append(buf, 0, read); } } while (read >= 0); } catch (final IOException ex) { throw new RuntimeException(ex); } finally { closeQuietly(is); } return ret.toString(); } private static void closeQuietly(final Closeable closeable) { if (null == closeable) { return; } try { closeable.close(); } catch (IOException ex) { Logger.getLogger(UrlRegularExpressions.class.getName()).log(Level.SEVERE, null, ex); } } }
2
package fr.opensagres.xdocreport.document.tools; import java.io.File; import java.io.FileReader; import java.io.StringWriter; import fr.opensagres.xdocreport.core.io.IOUtils; import fr.opensagres.xdocreport.document.tools.json.JSONPoupluateContextAware; public class Main { public static void main(String[] args) throws Exception { String fileIn = null; String fileOut = null; String templateEngineKind = null; String jsonData = null; String jsonFile = null; IPopulateContextAware contextAware = null; String arg = null; for (int i = 0; i < args.length; i++) { arg = args[i]; if ("-in".equals(arg)) { fileIn = getValue(args, i); } else if ("-out".equals(arg)) { fileOut = getValue(args, i); } else if ("-engine".equals(arg)) { templateEngineKind = getValue(args, i); } else if ("-jsonData".equals(arg)) { jsonData = getValue(args, i); contextAware = new JSONPoupluateContextAware(jsonData); } else if ("-jsonFile".equals(arg)) { jsonFile = getValue(args, i); StringWriter jsonDataWriter = new StringWriter(); IOUtils.copy(new FileReader(new File(jsonFile)), jsonDataWriter); contextAware = new JSONPoupluateContextAware( jsonDataWriter.toString()); } } Tools tools = new Tools(); tools.process(new File(fileIn), new File(fileOut), templateEngineKind, contextAware); } private static String getValue(String[] args, int i) { if (i == (args.length - 1)) { printUsage(); return null; } else { return args[i + 1]; } } private static void printUsage() { System.out.print("Usage: "); System.out.print("java " + Main.class.getName()); System.out.print(" -in <a file in>"); System.out.print(" -out <a file out>"); System.exit(-1); } }
10
using System.Net; using Lms.Core.Modularity; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; namespace Lms.Core { public static class ServiceCollectionExtensions { public static IEngine ConfigureLmsServices(this IServiceCollection services, IConfiguration configuration, IHostEnvironment hostEnvironment) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; services.AddHttpContextAccessor(); CommonHelper.DefaultFileProvider = new LmsFileProvider(hostEnvironment); var engine = EngineContext.Create(); var moduleLoder = new ModuleLoader(); services.TryAddSingleton<IModuleLoader>(moduleLoder); engine.ConfigureServices(services, configuration); return engine; } } }
10
// Copyright © 2018 Martin Stoeckli. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. using System; using SilentNotes.HtmlView; using SilentNotes.Services; using SilentNotes.ViewModels; namespace SilentNotes.Controllers { /// <summary> /// Controller to show a <see cref="SettingsViewModel"/> in an (Html)view. /// </summary> public class SettingsController : ControllerBase { private SettingsViewModel _viewModel; /// <summary> /// Initializes a new instance of the <see cref="SettingsController"/> class. /// </summary> /// <param name="viewService">Razor view service which can generate the HTML view.</param> public SettingsController(IRazorViewService viewService) : base(viewService) { } /// <inheritdoc/> protected override IViewModel GetViewModel() { return _viewModel; } /// <inheritdoc/> public override void ShowInView(IHtmlView htmlView, KeyValueList<string, string> variables, Navigation redirectedFrom) { base.ShowInView(htmlView, variables, redirectedFrom); _viewModel = new SettingsViewModel( Ioc.GetOrCreate<INavigationService>(), Ioc.GetOrCreate<ILanguageService>(), Ioc.GetOrCreate<ISvgIconService>(), Ioc.GetOrCreate<IThemeService>(), Ioc.GetOrCreate<IBaseUrlService>(), Ioc.GetOrCreate<ISettingsService>(), Ioc.GetOrCreate<IStoryBoardService>()); VueBindings = new VueDataBinding(_viewModel, View); _viewModel.VueDataBindingScript = VueBindings.BuildVueScript(); VueBindings.StartListening(); string html = _viewService.GenerateHtml(_viewModel); View.LoadHtml(html); } } }
4
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using OSS.Common.BasicMos.Resp; using OSS.Common.Helpers; using OSS.Core.Context; using OSS.Core.Context.Attributes; using OSS.Core.Infrastructure.Const; using OSS.Core.Services.Basic.Portal.IProxies; namespace OSS.Core.WebApi.App_Codes.AuthProviders { public class UserAuthProvider : IUserAuthProvider { public Task<Resp<UserIdentity>> GetIdentity(HttpContext context, AppIdentity appinfo) { return PortalAuthHelper.GetMyself(context.Request); } } public class PortalAuthHelper { public static Task<Resp<UserIdentity>> GetMyself(HttpRequest req) { var appinfo = CoreAppContext.Identity; if (appinfo.source_mode >= AppSourceMode.Browser) { appinfo.token = GetCookie(req); } return InsContainer<IPortalServiceProxy>.Instance.GetMyself(); } public static void SetCookie(HttpResponse response, string token) { response.Cookies.Append(CoreCookieKeys.UserCookieName, token, new CookieOptions() { HttpOnly = true, //SameSite = SameSiteMode.None, //Secure = true, Expires = DateTimeOffset.Now.AddDays(30) }); } public static string GetCookie(HttpRequest req) { return req.Cookies[CoreCookieKeys.UserCookieName]; } public static void ClearCookie(HttpResponse response) { response.Cookies.Delete(CoreCookieKeys.UserCookieName); } } }
4
/* * 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 httl.spi.loaders; import httl.Resource; import httl.spi.Loader; import httl.util.UrlUtils; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.List; import java.util.Locale; /** * UrlLoader. (SPI, Singleton, ThreadSafe) * * @see httl.spi.engines.DefaultEngine#setLoader(Loader) * * @author Liang Fei (liangfei0201 AT gmail DOT com) */ public class UrlLoader extends AbstractLoader { public List<String> doList(String directory, String suffix) throws IOException { return UrlUtils.listUrl(new URL(directory), suffix); } protected Resource doLoad(String name, Locale locale, String encoding, String path) throws IOException { return new UrlResource(getEngine(), name, locale, encoding, path); } public boolean doExists(String name, Locale locale, String path) throws Exception { InputStream in = new URL(path).openStream(); try { return in != null; } finally { in.close(); } } }
2
/* * 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.sanselan.common; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.zip.DeflaterInputStream; import java.util.zip.InflaterInputStream; import org.apache.sanselan.ImageReadException; public class ZLibInflater extends BinaryFileFunctions { public final byte[] inflate(byte bytes[]) throws IOException // slow, probably. { ByteArrayInputStream in = new ByteArrayInputStream(bytes); InflaterInputStream zIn = new InflaterInputStream(in); return getStreamBytes(zIn); } public final byte[] deflate(byte bytes[]) throws IOException { ByteArrayInputStream in = new ByteArrayInputStream(bytes); DeflaterInputStream zIn = new DeflaterInputStream(in); return getStreamBytes(zIn); } }
2
package ru.yandex.metrika.clickhouse; import ru.yandex.metrika.clickhouse.util.LogProxy; import ru.yandex.metrika.clickhouse.util.Logger; import java.sql.*; import java.util.Properties; /** * * URL Format * * пока что примитивный * * jdbc:clickhouse:host:port * * например, jdbc:clickhouse:localhost:8123 * * Created by jkee on 14.03.15. */ public class CHDriver implements Driver { private static final Logger logger = Logger.of(CHDriver.class); static { CHDriver driver = new CHDriver(); try { DriverManager.registerDriver(driver); } catch (SQLException e) { throw new RuntimeException(e); } logger.info("Driver registered"); } @Override public CHConnection connect(String url, Properties info) throws SQLException { logger.info("Creating connection"); return LogProxy.wrap(CHConnection.class, new CHConnectionImpl(url)); } @Override public boolean acceptsURL(String url) throws SQLException { return url.startsWith("jdbc:clickhouse:"); } @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return new DriverPropertyInfo[0]; } @Override public int getMajorVersion() { return 0; } @Override public int getMinorVersion() { return 0; } @Override public boolean jdbcCompliant() { return false; } public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { throw new SQLFeatureNotSupportedException(); } }
4
package org.jenkinsci.plugins.ghprb; import java.io.IOException; import hudson.Extension; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.Environment; import hudson.model.Run; import hudson.model.TaskListener; import hudson.model.listeners.RunListener; /** * @author janinko */ @Extension public class GhprbBuildListener extends RunListener<AbstractBuild<?, ?>> { @Override public void onStarted(AbstractBuild<?, ?> build, TaskListener listener) { GhprbTrigger trigger = Ghprb.extractTrigger(build); if (trigger != null) { trigger.getBuilds().onStarted(build, listener); } } @Override public void onCompleted(AbstractBuild<?, ?> build, TaskListener listener) { GhprbTrigger trigger = Ghprb.extractTrigger(build); if (trigger != null) { trigger.getBuilds().onCompleted(build, listener); } } @Override public Environment setUpEnvironment(@SuppressWarnings("rawtypes") AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException, Run.RunnerAbortedException { GhprbTrigger trigger = Ghprb.extractTrigger(build); if (trigger != null) { trigger.getBuilds().onEnvironmentSetup(build, launcher, listener); } return new hudson.model.Environment(){}; } }