label
int64 0
10
| text
stringlengths 210
2.04k
|
---|---|
2 | package org.rapidoid.jdbc;
/*
* #%L
* rapidoid-integration-tests
* %%
* 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%
*/
import org.junit.Test;
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.http.IsolatedIntegrationTest;
import org.rapidoid.u.U;
import org.rapidoid.util.Msc;
import java.util.Map;
@Authors("Nikolche Mihajlovski")
@Since("5.3.4")
public class JDBCPoolHikariTest extends IsolatedIntegrationTest {
@Test(timeout = 30000)
public void testHikariPool() {
JdbcClient jdbc = JDBC.api();
jdbc.h2("hikari-test");
jdbc.pool(new HikariConnectionPool(jdbc));
jdbc.execute("create table abc (id int, name varchar)");
jdbc.execute("insert into abc values (?, ?)", 123, "xyz");
final Map<String, ?> expected = U.map("id", 123, "name", "xyz");
Msc.benchmarkMT(100, "select", 100000, () -> {
Map<String, Object> record = U.single(JDBC.query("select id, name from abc").all());
record = Msc.lowercase(record);
eq(record, expected);
});
isTrue(jdbc.pool() instanceof HikariConnectionPool);
}
}
|
2 | package com.github.ompc.greys.core.view;
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
/**
* KV排版控件
* Created by vlinux on 15/5/9.
*/
public class KVView implements View {
private final TableView tableView;
public KVView() {
this.tableView = new TableView(new TableView.ColumnDefine[]{
new TableView.ColumnDefine(TableView.Align.RIGHT),
new TableView.ColumnDefine(TableView.Align.RIGHT),
new TableView.ColumnDefine(TableView.Align.LEFT)
})
.hasBorder(false)
.padding(0);
}
public KVView(TableView.ColumnDefine keyColumnDefine, TableView.ColumnDefine valueColumnDefine) {
this.tableView = new TableView(new TableView.ColumnDefine[]{
keyColumnDefine,
new TableView.ColumnDefine(TableView.Align.RIGHT),
valueColumnDefine
})
.hasBorder(false)
.padding(0);
}
public KVView add(final Object key, final Object value) {
tableView.addRow(key, " : ", value);
return this;
}
@Override
public String draw() {
String content = tableView.draw();
StringBuilder sb = new StringBuilder();
// 清理多余的空格
Scanner scanner = new Scanner(content);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line != null) {
//清理一行后面多余的空格
line = StringUtils.stripEnd(line, " ");
if(line.isEmpty()){
line = " ";
}
}
sb.append(line).append('\n');
}
scanner.close();
return sb.toString();
}
}
|
4 | package com.nepxion.discovery.plugin.example.gateway.impl;
/**
* <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.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.nepxion.discovery.plugin.framework.adapter.PluginAdapter;
import com.nepxion.discovery.plugin.strategy.adapter.DiscoveryEnabledStrategy;
import com.nepxion.discovery.plugin.strategy.gateway.context.GatewayStrategyContextHolder;
import com.netflix.loadbalancer.Server;
// 实现了组合策略,版本路由策略+区域路由策略+IP和端口路由策略+自定义策略
public class MyDiscoveryEnabledStrategy implements DiscoveryEnabledStrategy {
private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryEnabledStrategy.class);
@Autowired
private GatewayStrategyContextHolder gatewayStrategyContextHolder;
@Autowired
private PluginAdapter pluginAdapter;
@Override
public boolean apply(Server server, Map<String, String> metadata) {
// 对Rest调用传来的Header参数(例如Token)做策略
return applyFromHeader(server, metadata);
}
// 根据Rest调用传来的Header参数(例如Token),选取执行调用请求的服务实例
private boolean applyFromHeader(Server server, Map<String, String> metadata) {
String token = gatewayStrategyContextHolder.getHeader("token");
String serviceId = pluginAdapter.getServerServiceId(server);
LOG.info("Gateway端负载均衡用户定制触发:token={}, serviceId={}, metadata={}", token, serviceId, metadata);
String filterToken = "abc";
if (StringUtils.isNotEmpty(token) && token.contains(filterToken)) {
LOG.info("过滤条件:当Token含有'{}'的时候,不能被Ribbon负载均衡到", filterToken);
return false;
}
return true;
}
} |
10 | // Copyright (c) Shane Woolcock. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Rush.Configuration;
namespace osu.Game.Rulesets.Rush.UI
{
public class RushSettingsSubsection : RulesetSettingsSubsection
{
private readonly Ruleset ruleset;
protected override string Header => ruleset.Description;
public RushSettingsSubsection(Ruleset ruleset)
: base(ruleset)
{
this.ruleset = ruleset;
}
[BackgroundDependencyLoader]
private void load()
{
var config = (RushRulesetConfigManager)Config;
Children = new Drawable[]
{
new SettingsCheckbox
{
LabelText = "Automatic Fever activation",
Current = config.GetBindable<bool>(RushRulesetSettings.AutomaticFever)
},
};
}
}
}
|
1 | using DeBroglie.Constraints;
using DeBroglie.Models;
using DeBroglie.Topo;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DeBroglie.Test.Constraints
{
[TestFixture]
public class SeparationConstraintTest
{
[Test]
public void TestSeparationConstraint()
{
var model = new AdjacentModel(DirectionSet.Cartesian2d);
var tile1 = new Tile(1);
var tile2 = new Tile(2);
var tiles = new[] { tile1, tile2 };
model.AddAdjacency(tiles, tiles, Direction.XPlus);
model.AddAdjacency(tiles, tiles, Direction.YPlus);
model.SetUniformFrequency();
var separationConstraint = new SeparationConstraint
{
Tiles = new[] { tile1 }.ToHashSet(),
MinDistance = 2,
};
var countConstraint = new CountConstraint
{
Tiles = new[] { tile1 }.ToHashSet(),
Count = 2,
Comparison = CountComparison.Exactly,
};
var topology = new GridTopology(3, 1, false);
var options = new TilePropagatorOptions
{
Constraints = new ITileConstraint[] { separationConstraint, countConstraint },
BackTrackDepth = -1,
};
var propagator = new TilePropagator(model, topology, options);
propagator.Run();
Assert.AreEqual(Resolution.Decided, propagator.Status);
var r = propagator.ToArray();
// Only possible solution given the constraints
Assert.AreEqual(tile1, r.Get(0));
Assert.AreEqual(tile2, r.Get(1));
Assert.AreEqual(tile1, r.Get(2));
}
}
}
|
2 | package org.kohsuke.randname;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* Dictionary of adjectives and nouns.
*
* @author Kohsuke Kawaguchi
*/
public class Dictionary {
private List<String> nouns = new ArrayList<String>();
private List<String> adjectives = new ArrayList<String>();
private final int prime;
public Dictionary() {
try {
load("a.txt", adjectives);
load("n.txt", nouns);
} catch (IOException e) {
throw new Error(e);
}
int combo = size();
int primeCombo = 2;
while (primeCombo<=combo) {
int nextPrime = primeCombo+1;
primeCombo *= nextPrime;
}
prime = primeCombo+1;
}
/**
* Total size of the combined words.
*/
public int size() {
return nouns.size()*adjectives.size();
}
/**
* Sufficiently big prime that's bigger than {@link #size()}
*/
public int getPrime() {
return prime;
}
public String word(int i) {
int a = i%adjectives.size();
int n = i/adjectives.size();
return adjectives.get(a)+"_"+nouns.get(n);
}
private void load(String name, List<String> col) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(name),"US-ASCII"));
String line;
while ((line=r.readLine())!=null)
col.add(line);
r.close();
}
static final Dictionary INSTANCE = new Dictionary();
}
|
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.examples;
import com.zuoxiaolong.niubi.job.cluster.node.StandbyNode;
import com.zuoxiaolong.niubi.job.scheduler.node.Node;
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("localhost:2181,localhost:3181,localhost:4181", "http://localhost:8080/job");
node.join();
new BufferedReader(new InputStreamReader(System.in)).readLine();
}
}
|
4 | package us.codecraft.webmagic.selector;
import org.junit.Test;
import us.codecraft.webmagic.Page;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author code4crafter@gmai.com
* @since 0.5.0
*/
public class JsonTest {
private String text = "callback({\"name\":\"json\"})";
@Test
public void testRemovePadding() throws Exception {
String name = new Json(text).removePadding("callback").jsonPath("$.name").get();
assertThat(name).isEqualTo("json");
Page page = null;
page.getJson().jsonPath("$.name").get();
page.getJson().removePadding("callback").jsonPath("$.name").get();
}
}
|
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.jsecurity.web.filter.authz;
import org.jsecurity.subject.Subject;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Set;
/**
* Filter that allows access if the current user has the roles specified by the mapped value, or denies access
* if the user does not have all of the roles specified.
*
* @author Les Hazlewood
* @author Jeremy Haile
* @since 0.9
*/
public class RolesAuthorizationFilter extends AuthorizationFilter {
@SuppressWarnings({"unchecked"})
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
Subject subject = getSubject(request, response);
Set<String> roles = (Set<String>) mappedValue;
boolean hasRoles = true;
if (roles != null && !roles.isEmpty()) {
if (roles.size() == 1) {
if (!subject.hasRole(roles.iterator().next())) {
hasRoles = false;
}
} else {
if (!subject.hasAllRoles(roles)) {
hasRoles = false;
}
}
}
return hasRoles;
}
}
|
2 | /**
* Copyright 1999-2014 dangdang.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dangdang.config.service.easyzk.demo.normal;
import com.dangdang.config.service.easyzk.ConfigFactory;
import com.dangdang.config.service.easyzk.ConfigNode;
import com.dangdang.config.service.observer.IObserver;
import com.google.common.base.Preconditions;
/**
* @author <a href="mailto:wangyuxuan@dangdang.com">Yuxuan Wang</a>
*
*/
public class WithoutSpring {
public static void main(String[] args) {
ConfigFactory configFactory = new ConfigFactory("zoo.host1:8181", "/projectx/modulex");
ConfigNode propertyGroup1 = configFactory.getConfigNode("property-group1");
System.out.println(propertyGroup1);
// Listen changes
propertyGroup1.register(new IObserver() {
@Override
public void notifiy(String data, String value) {
// Some initialization
}
});
String stringProperty = propertyGroup1.getProperty("string_property_key");
Preconditions.checkState("Welcome here.".equals(stringProperty));
String intProperty = propertyGroup1.getProperty("int_property_key");
Preconditions.checkState(1123 == Integer.parseInt(intProperty));
Object lock = new Object();
synchronized (lock) {
try {
while (true)
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
4 | package org.basex.query.xpath.internal;
import static org.basex.query.xpath.XPText.*;
import org.basex.data.Serializer;
import org.basex.index.IndexToken;
import org.basex.query.xpath.XPContext;
import org.basex.query.xpath.values.NodeSet;
import org.basex.util.Token;
/**
* This index class retrieves attribute values from the index.
*
* @author Workgroup DBIS, University of Konstanz 2005-08, ISC License
* @author Tim Petrowsky
* @author Christian Gruen
*/
public final class IndexAccess extends InternalExpr {
/** Index type. */
private final IndexToken index;
/**
* Constructor.
* @param ind index reference
*/
public IndexAccess(final IndexToken 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.openElement(this, Token.token(TYPE),
Token.token(index.type.toString()));
ser.item(index.get());
ser.closeElement(this);
}
@Override
public String color() {
return "CC99FF";
}
@Override
public String toString() {
return Token.string(name()) + "(" + index.type + ", \"" +
Token.string(index.get()) + "\")";
}
}
|
10 | using System;
using System.Diagnostics;
using System.Threading;
using BosunReporter;
namespace Scratch
{
class Program
{
static void Main(string[] args)
{
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
Debug.AutoFlush = true;
var options = new BosunReporterOptions()
{
MetricsNamePrefix = "bret.",
BosunUrl = new Uri("http://192.168.59.104:8070/"),
ThrowOnPostFail = true,
ReportingInterval = 5
};
var reporter = new BosunReporter.BosunReporter(options);
var counter = reporter.GetMetric<TestCounter>("my_counter");
counter.Increment();
counter.Increment();
var gauge = reporter.GetMetric<TestAggregateGauge>("my_gauge");
if (gauge != reporter.GetMetric<TestAggregateGauge>("my_gauge"))
throw new Exception("WAT?");
//reporter.GetMetric<TestAggregateGauge>("my_gauge_95"); // <- should throw an exception
var rand = new Random();
while (true)
{
gauge.Record(rand.NextDouble());
Thread.Sleep(5);
}
}
}
[GaugeAggregator(AggregateMode.Average)]
[GaugeAggregator(AggregateMode.Max)]
[GaugeAggregator(AggregateMode.Min)]
[GaugeAggregator(AggregateMode.Median)]
[GaugeAggregator(AggregateMode.Percentile, 0.95)]
[GaugeAggregator(AggregateMode.Percentile, 0.25)]
public class TestAggregateGauge : BosunAggregateGauge
{
[BosunTag("host")]
public readonly string Host;
public TestAggregateGauge()
{
Host = "bret-host";
}
}
public class TestCounter : BosunCounter
{
[BosunTag("host")]
public readonly string Host;
public TestCounter()
{
Host = "bret-host";
}
}
}
|
4 | using System;
using System.Linq;
using Kiota.Builder.Extensions;
namespace Kiota.Builder.Writers.CSharp {
public class CodeIndexerWriter : BaseElementWriter<CodeIndexer, CSharpConventionService>
{
public CodeIndexerWriter(CSharpConventionService conventionService) : base(conventionService) {}
public override void WriteCodeElement(CodeIndexer codeElement, LanguageWriter writer)
{
var parentClass = codeElement.Parent as CodeClass;
var urlTemplateParametersProp = parentClass.GetPropertyOfKind(CodePropertyKind.UrlTemplateParameters);
var returnType = conventions.GetTypeString(codeElement.ReturnType, codeElement);
conventions.WriteShortDescription(codeElement.Description, writer);
writer.WriteLine($"public {returnType} this[{conventions.GetTypeString(codeElement.IndexType, codeElement)} position] {{ get {{");
writer.IncreaseIndent();
conventions.AddParametersAssignment(writer, urlTemplateParametersProp.Type, urlTemplateParametersProp.Name.ToFirstCharacterUpperCase(), new (CodeTypeBase, string, string)[] {
(codeElement.IndexType, codeElement.ParameterName, "position")
});
conventions.AddRequestBuilderBody(parentClass, returnType, writer, conventions.TempDictionaryVarName, "return ");
writer.DecreaseIndent();
writer.WriteLine("} }");
}
}
}
|
3 | package se.vidstige.jadb.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
// >set ANDROID_ADB_SERVER_PORT=15037
public abstract class SocketServer implements Runnable {
private final int port;
private ServerSocket socket;
private Thread thread;
private boolean isStarted = false;
private final Object lockObject = new Object();
protected SocketServer(int port) {
this.port = port;
}
public void start() throws InterruptedException {
thread = new Thread(this, "Fake Adb Server");
thread.setDaemon(true);
thread.start();
synchronized (lockObject) {
if (!isStarted) {
lockObject.wait();
}
}
}
public int getPort() {
return port;
}
@Override
public void run() {
try {
socket = new ServerSocket(port);
socket.setReuseAddress(true);
synchronized (lockObject) {
lockObject.notify();
isStarted = true;
}
while (true) {
Socket c = socket.accept();
Thread clientThread = new Thread(createResponder(c), "AdbClientWorker");
clientThread.setDaemon(true);
clientThread.start();
}
} catch (IOException e) {
}
}
protected abstract Runnable createResponder(Socket socket);
public void stop() throws IOException, InterruptedException {
socket.close();
thread.join();
}
}
|
10 | // Copyright (c) Dominick Baier & Brock Allen. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Tests.Util
{
class DiscoveryEndpointHandler : HttpMessageHandler
{
public string Endpoint { get; set; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
if (request.RequestUri.AbsoluteUri.ToString() == "https://authority.com/.well-known/openid-configuration")
{
Endpoint = request.RequestUri.AbsoluteUri;
var data = new Dictionary<string, object>
{
{ "issuer", "https://authority.com" },
{ "introspection_endpoint", "https://authority.com/introspection_endpoint" }
};
var json = SimpleJson.SimpleJson.SerializeObject(data);
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent(json, Encoding.UTF8, "application/json");
return Task.FromResult(response);
}
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound));
}
}
} |
10 | using System;
using System.IO;
using System.Reflection;
namespace RazorEngineCore
{
public class RazorEngineCompiledTemplate
{
private readonly MemoryStream assemblyByteCode;
private readonly Type templateType;
internal RazorEngineCompiledTemplate(MemoryStream assemblyByteCode)
{
this.assemblyByteCode = assemblyByteCode;
Assembly assembly = Assembly.Load(assemblyByteCode.ToArray());
this.templateType = assembly.GetType("TemplateNamespace.Template");
}
public static RazorEngineCompiledTemplate LoadFromFile(string fileName)
{
return new RazorEngineCompiledTemplate(new MemoryStream(File.ReadAllBytes(fileName)));
}
public static RazorEngineCompiledTemplate LoadFromStream(Stream stream)
{
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
memoryStream.Position = 0;
return new RazorEngineCompiledTemplate(memoryStream);
}
public void SaveToStream(Stream stream)
{
this.assemblyByteCode.CopyTo(stream);
}
public void SaveToFile(string fileName)
{
File.WriteAllBytes(fileName, this.assemblyByteCode.ToArray());
}
public string Run(object model = null)
{
if (model != null && model.IsAnonymous())
{
model = new AnonymousTypeWrapper(model);
}
RazorEngineTemplateBase instance = (RazorEngineTemplateBase)Activator.CreateInstance(this.templateType);
instance.Model = model;
instance.ExecuteAsync().Wait();
return instance.Result();
}
}
} |
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));
}
}
} |
10 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Couchbase.Authentication.SASL;
using Couchbase.Configuration.Client;
using Couchbase.Configuration.Server.Serialization;
using Couchbase.Core;
using Couchbase.IO;
using Couchbase.IO.Strategies.Async;
using Couchbase.IO.Strategies.Awaitable;
namespace Couchbase.Tests.Helpers
{
public static class ObjectFactory
{
internal static IOStrategy CreateIOStrategy(string server)
{
var connectionPool = new DefaultConnectionPool(new PoolConfiguration(), Server.GetEndPoint(server));
var ioStrategy = new SocketAsyncStrategy(connectionPool);
return ioStrategy;
}
internal static IOStrategy CreateIOStrategy(Node node)
{
var server = node.Hostname.Replace("8091", node.Ports.Direct.ToString());
var connectionPool = new DefaultConnectionPool(new PoolConfiguration(), Server.GetEndPoint(server));
var ioStrategy = new SocketAsyncStrategy(connectionPool);
return ioStrategy;
}
}
}
#region [ License information ]
/* ************************************************************
*
* @author Couchbase <info@couchbase.com>
* @copyright 2014 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ************************************************************/
#endregion
|
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(new WebsocketCustomTransport());
}
public void Stop(TimeSpan timeout)
{
connection.Stop(timeout);
}
}
}
|
4 | /*
* Copyright (c) 2016 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.neural_network;
import java.util.List;
import numpy.core.NDArray;
import numpy.core.NDArrayUtil;
import org.dmg.pmml.MiningFunctionType;
import org.dmg.pmml.NeuralNetwork;
import org.dmg.pmml.Output;
import org.jpmml.sklearn.Schema;
import sklearn.Classifier;
import sklearn.EstimatorUtil;
public class MLPClassifier extends Classifier {
public MLPClassifier(String module, String name){
super(module, name);
}
@Override
public int getNumberOfFeatures(){
List<?> coefs = getCoefs();
NDArray input = (NDArray)coefs.get(0);
int[] shape = NDArrayUtil.getShape(input);
return shape[0];
}
@Override
public NeuralNetwork encodeModel(Schema schema){
String activation = getActivation();
List<?> coefs = getCoefs();
List<?> intercepts = getIntercepts();
Output output = EstimatorUtil.encodeClassifierOutput(schema);
NeuralNetwork neuralNetwork = NeuralNetworkUtil.encodeNeuralNetwork(MiningFunctionType.CLASSIFICATION, activation, coefs, intercepts, schema)
.setOutput(output);
return neuralNetwork;
}
public String getActivation(){
return (String)get("activation");
}
public List<?> getCoefs(){
return (List<?>)get("coefs_");
}
public List<?> getIntercepts(){
return (List<?>)get("intercepts_");
}
} |
10 | // --------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// --------------------------------------------------------------------------------------------
using System;
using System.IO;
using McMaster.Extensions.CommandLineUtils;
using Microsoft.Oryx.BuildScriptGeneratorCli;
using Xunit;
namespace BuildScriptGeneratorCli.Tests
{
public class ScriptCommandTest
{
[Fact]
public void ScriptCommand_OnExecute_ShowsHelp_AndExits_WhenSourceFolderIsEmpty()
{
// Arrange
var scriptCommand = new ScriptCommand
{
SourceCodeFolder = string.Empty
};
var testConsole = new TestConsole();
// Act
var exitCode = scriptCommand.OnExecute(new CommandLineApplication(testConsole), testConsole);
// Assert
Assert.NotEqual(0, exitCode);
Assert.Contains("Usage:", testConsole.Output);
}
[Fact]
public void OnExecute_ShowsHelp_AndExits_WhenSourceDirectoryDoesNotExist()
{
// Arrange
var scriptCommand = new ScriptCommand
{
SourceCodeFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())
};
var testConsole = new TestConsole();
// Act
var exitCode = scriptCommand.OnExecute(new CommandLineApplication(testConsole), testConsole);
// Assert
Assert.NotEqual(0, exitCode);
var output = testConsole.Output;
Assert.DoesNotContain("Usage:", output);
Assert.Contains("Could not find the source code folder", output);
}
[Fact(Skip = "Todo")]
public void Execute_DoesNotWriteAnythingElseToConsole_ApartFromScript()
{
}
}
}
|
4 | package org.panda_lang.panda.core.syntax.block;
import org.panda_lang.panda.core.Particle;
import org.panda_lang.panda.core.parser.Atom;
import org.panda_lang.panda.core.parser.essential.BlockCenter;
import org.panda_lang.panda.core.parser.essential.ParameterParser;
import org.panda_lang.panda.core.parser.essential.util.BlockInitializer;
import org.panda_lang.panda.core.parser.essential.util.BlockLayout;
import org.panda_lang.panda.core.syntax.Block;
import org.panda_lang.panda.core.syntax.Essence;
import org.panda_lang.panda.lang.PBoolean;
public class WhileBlock extends Block {
static {
BlockCenter.registerBlock(new BlockLayout(WhileBlock.class, "while").initializer(new BlockInitializer() {
@Override
public Block initialize(Atom atom) {
Block current = new WhileBlock();
current.setParameters(new ParameterParser().parse(atom, atom.getBlockInfo().getParameters()));
return current;
}
}));
}
public WhileBlock() {
super.setName("while::" + System.nanoTime());
}
@Override
public Essence run(Particle particle) {
while (parameters[0].getValue(PBoolean.class).isTrue()) {
Essence o = super.run(particle);
if (o != null) {
return o;
}
}
return null;
}
}
|
2 | package net.runelite.cache.fs;
import java.io.File;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class IndexFileTest
{
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void test1() throws IOException
{
File file = folder.newFile();
Store store = new Store();
IndexFile index = new IndexFile(store, 5, file);
IndexEntry entry = new IndexEntry(index, 7, 8, 9);
index.write(entry);
IndexEntry entry2 = index.read(7);
Assert.assertEquals(entry, entry2);
}
}
|
10 | using TerminalGuiDesigner.UI;
namespace TerminalGuiDesigner;
public partial class Program
{
public static void Main(string[] args)
{
var editor = new Editor();
editor.Run();
}
}
|
3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace i18n.Domain.Helpers
{
/// <summary>
/// Helper class for implementing a property with 'typically' lock-free thread-safe accessors.
/// </summary>
public class LockFreeProperty<T>
{
readonly object m_sync = new object();
private T m_prop;
public T Get(Func<T> factory)
{
if (m_prop != null) { // Read attempt 1 of lock-free read.
return m_prop; }
lock (m_sync) {
if (m_prop != null) { // Read attempt 2 of lock-free read.
return m_prop; }
m_prop = factory();
return m_prop;
}
}
public void Set(T value)
{
m_prop = value;
}
}
}
|
10 | using System;
using System.IO;
using Yoakke.X86.Instructions;
using Yoakke.X86.Operands;
using Yoakke.X86.Writers;
namespace Yoakke.X86.Sample
{
class Program
{
static void Main(string[] args)
{
var sw = new StringWriter();
var writer = new IntelAssemblyWriter(sw);
writer.Write(new Add(
Registers.Eax,
new Indirect(DataWidth.Dword, new Address(Registers.Ecx, new ScaledIndex(Registers.Edx, 4), 23))));
Console.WriteLine(sw);
}
}
}
|
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.logging.log4j.io;
import java.io.PrintStream;
import java.util.List;
import org.apache.logging.log4j.junit.InitialLoggerContext;
import org.apache.logging.log4j.test.appender.ListAppender;
import org.junit.Rule;
import org.junit.Test;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.*;
public class IoBuilderTest {
@Rule
public InitialLoggerContext context = new InitialLoggerContext("log4j2-streams-calling-info.xml");
@Test
public void testNoArgBuilderCallerClassInfo() throws Exception {
final PrintStream ps = IoBuilder.forLogger().buildPrintStream();
ps.println("discarded");
final ListAppender app = context.getListAppender("IoBuilderTest");
final List<String> messages = app.getMessages();
assertThat(messages, not(empty()));
assertThat(messages, hasSize(1));
final String message = messages.get(0);
assertThat(message, startsWith(getClass().getName() + ".testNoArgBuilderCallerClassInfo"));
app.clear();
}
}
|
4 | /**
*
* APDPlat - Application Product Development Platform
* Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.apdplat.word.util;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author 杨尚川
*/
public class GenericTrieTest {
private final GenericTrie<Integer> trie = new GenericTrie<>();
@Before
public void setUp() {
trie.put("杨尚川", 100);
trie.put("杨尚喜", 99);
trie.put("杨尚丽", 98);
trie.put("中华人民共和国", 1);
}
@After
public void tearDown() {
trie.clear();
}
@Test
public void testClear() {
Assert.assertEquals(100, trie.get("杨尚川"), 0);
Assert.assertEquals(1, trie.get("中华人民共和国"), 0);
trie.clear();
Assert.assertEquals(null, trie.get("杨尚川"));
Assert.assertEquals(null, trie.get("中华人民共和国"));
}
@Test
public void testGet() {
Assert.assertEquals(100, trie.get("杨尚川"), 0);
Assert.assertEquals(99, trie.get("杨尚喜"), 0);
Assert.assertEquals(98, trie.get("杨尚丽"), 0);
Assert.assertEquals(1, trie.get("中华人民共和国"), 0);
Assert.assertEquals(null, trie.get("杨"));
Assert.assertEquals(null, trie.get("杨尚"));
}
} |
10 | using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Tests.Infrastructure
{
class NetworkHandler : HttpMessageHandler
{
public Uri Address { get; set; }
public HttpContent Content { get; set; }
public IDictionary<string, object> Properties { get; set; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Address = request.RequestUri;
Content = request.Content;
Properties = request.Properties;
return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.NotFound));
}
}
} |
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);
}
}
|
10 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using NetMQ;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Context context = Context.Create();
PairSocket pairSocket1 = context.CreatePairSocket();
PairSocket pairSocket2 = context.CreatePairSocket();
//RequestSocket pairSocket1 = context.CreateRequestSocket();
//ResponseSocket pairSocket2 = context.CreateResponseSocket();
pairSocket1.Bind("inproc://d");
pairSocket2.Connect("inproc://d");
pairSocket1.Send("1");
bool ok = pairSocket2.Poll(TimeSpan.FromSeconds(2));
//pairSocket1.Send("1");
bool hasMore;
string m = pairSocket2.ReceiveString(out hasMore);
//var j = pairSocket2.ReceiveString(true, out hasMore);
//pairSocket1.Send("1");
Console.WriteLine(m);
}
}
}
|
10 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Moq;
namespace Cosmonaut.Tests
{
public class MockHelpers
{
public static Mock<IDocumentClient> GetFakeDocumentClient(string databaseName = "databaseName")
{
var mockDocumentClient = new Mock<IDocumentClient>();
var mockDatabase = new Mock<Database>();
var mockCollection = new Mock<DocumentCollection>();
var mockOffer = new Mock<Offer>();
mockDatabase.Setup(x => x.Id).Returns(databaseName);
mockCollection.Setup(x => x.Id).Returns("dummies");
mockDocumentClient.Setup(x => x.AuthKey).Returns(new SecureString());
mockDocumentClient.Setup(x => x.ServiceEndpoint).Returns(new Uri("http://test.com"));
mockDocumentClient.Setup(x => x.ReadDatabaseAsync(It.IsAny<string>(), null))
.ReturnsAsync(new ResourceResponse<Database>(mockDatabase.Object));
mockDocumentClient.Setup(x => x.ReadDocumentCollectionAsync(It.IsAny<string>(), null))
.ReturnsAsync(new ResourceResponse<DocumentCollection>(mockCollection.Object));
mockDocumentClient.Setup(x => x.CreateDatabaseQuery(null))
.Returns(new EnumerableQuery<Database>(new List<Database>() { mockDatabase.Object }));
mockDocumentClient.Setup(x => x.CreateDocumentCollectionQuery(It.IsAny<string>(), null))
.Returns(new EnumerableQuery<DocumentCollection>(new List<DocumentCollection>() { new DocumentCollection() { Id = "dummies" } }));
mockDocumentClient.Setup(x => x.CreateOfferQuery(null)).Returns(
new EnumerableQuery<OfferV2>(new List<OfferV2>()
{
new OfferV2(mockOffer.Object, 400)
}));
return mockDocumentClient;
}
}
} |
4 | package org.sfm.map;
import org.junit.Test;
import org.sfm.jdbc.JdbcColumnKey;
import org.sfm.map.impl.FieldMapperColumnDefinition;
import org.sfm.reflect.Getter;
import java.sql.ResultSet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class FieldMapperColumnDefinitionTest {
@Test
public void testCompose() throws Exception {
Getter<ResultSet, Integer> getter = new Getter<ResultSet, Integer>() {
@Override
public Integer get(ResultSet target) throws Exception {
return 3;
}
};
FieldMapperColumnDefinition<JdbcColumnKey, ResultSet> compose =
FieldMapperColumnDefinition.compose(
FieldMapperColumnDefinition.<JdbcColumnKey, ResultSet>renameDefinition("blop"),
FieldMapperColumnDefinition.<JdbcColumnKey, ResultSet>customGetter(getter));
assertEquals("blop", compose.rename(new JdbcColumnKey("bar", -1)).getName());
assertEquals(new Integer(3), compose.getCustomGetter().get(null));
assertTrue(compose.hasCustomSource());
assertEquals(Integer.class, compose.getCustomSourceReturnType());
}
}
|
4 | namespace MefContrib.Hosting.Interception.Handlers
{
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
public class ConcreteTypeExportHandler : IExportHandler
{
private readonly AggregateCatalog catalog;
public ConcreteTypeExportHandler()
{
this.catalog = new AggregateCatalog();
}
public void Initialize(ComposablePartCatalog interceptedCatalog)
{
}
public IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition, IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> exports)
{
if (!exports.Any())
exports = this.catalog.GetExports(definition);
if (exports.Any())
return exports;
var returnedExports = new List<Tuple<ComposablePartDefinition, ExportDefinition>>();
var importDefinitionType = TypeHelper.GetImportDefinitionType(definition);
if (!importDefinitionType.IsAbstract && !importDefinitionType.IsInterface)
{
var typeCatalog = new TypeCatalog(importDefinitionType);
this.catalog.Catalogs.Add(typeCatalog);
var currentExports = this.catalog.GetExports(definition);
returnedExports.AddRange(currentExports);
}
return returnedExports;
}
}
}
|
4 | package com.tairanchina.csp.dew.idempotent.strategy;
import com.tairanchina.csp.dew.Dew;
public class ItemProcessor implements IdempotentProcessor {
private static final String CACHE_KEY = "dew:idempotent:item:";
@Override
public StatusEnum process(String optType, String optId, StatusEnum initStatus, long expireMs) {
if (Dew.cluster.cache.setnx(CACHE_KEY + optType + ":" + optId, initStatus.toString(), expireMs / 1000)) {
// 设置成功,表示之前不存在
return StatusEnum.NOT_EXIST;
} else {
// 设置不成功,表示之前存在,返回存在的值
String status = Dew.cluster.cache.get(CACHE_KEY + optType + ":" + optId);
if (status == null && status.isEmpty()) {
// 设置成功,表示之前不存在
return StatusEnum.NOT_EXIST;
} else {
return StatusEnum.valueOf(status);
}
}
}
@Override
public boolean confirm(String optType, String optId) {
long ttl = Dew.cluster.cache.ttl(CACHE_KEY + optType + ":" + optId);
if (ttl > 0) {
Dew.cluster.cache.setex(CACHE_KEY + optType + ":" + optId, StatusEnum.CONFIRMED.toString(), ttl);
}
return true;
}
@Override
public boolean cancel(String optType, String optId) {
Dew.cluster.cache.del(CACHE_KEY + optType + ":" + optId);
return true;
}
}
|
4 | using System.Globalization;
using System.Xml.Linq;
using DefaultDocumentation.Markdown.Extensions;
using DefaultDocumentation.Api;
namespace DefaultDocumentation.Markdown.Elements
{
public sealed class NoteElement : IElement
{
public string Name => "note";
public void Write(IWriter writer, XElement element)
{
if (writer.GetDisplayAsSingleLine())
{
return;
}
string type = element.GetTypeAttribute()?.ToLower(CultureInfo.InvariantCulture);
string notePrefix = type switch
{
"note" or "tip" or "caution" or "warning" or "important" => char.ToUpper(type[0], CultureInfo.InvariantCulture) + 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.AppendAsMarkdown(element);
}
}
}
|
4 | /**
* Copyright (c) 2012-2019 Nikita Koksharov
*
* 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.corundumstudio.socketio.parser;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import com.corundumstudio.socketio.protocol.Packet;
import com.corundumstudio.socketio.protocol.PacketType;
public class DecoderMessagePacketTest extends DecoderBaseTest {
@Test
public void testDecodeId() throws IOException {
Packet packet = decoder.decodePacket("3:1::asdfasdf", null);
Assert.assertEquals(PacketType.MESSAGE, packet.getType());
// Assert.assertEquals(1, (long)packet.getId());
// Assert.assertTrue(packet.getArgs().isEmpty());
// Assert.assertTrue(packet.getAck().equals(Boolean.TRUE));
}
@Test
public void testDecode() throws IOException {
Packet packet = decoder.decodePacket("3:::woot", null);
Assert.assertEquals(PacketType.MESSAGE, packet.getType());
Assert.assertEquals("woot", packet.getData());
}
@Test
public void testDecodeWithIdAndEndpoint() throws IOException {
Packet packet = decoder.decodePacket("3:5:/tobi", null);
Assert.assertEquals(PacketType.MESSAGE, packet.getType());
// Assert.assertEquals(5, (long)packet.getId());
// Assert.assertEquals(true, packet.getAck());
Assert.assertEquals("/tobi", packet.getNsp());
}
}
|
4 | package cc.blynk.server.application.handlers.main.logic.dashboard.device;
import cc.blynk.server.core.model.DashBoard;
import cc.blynk.server.core.model.auth.User;
import cc.blynk.server.core.model.device.Device;
import cc.blynk.server.core.protocol.exceptions.IllegalCommandException;
import cc.blynk.server.core.protocol.model.messages.StringMessage;
import cc.blynk.utils.JsonParser;
import cc.blynk.utils.ParseUtil;
import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import static cc.blynk.utils.BlynkByteBufUtil.ok;
import static cc.blynk.utils.StringUtils.split2;
/**
* The Blynk Project.
* Created by Dmitriy Dumanskiy.
* Created on 01.02.16.
*/
public class UpdateDeviceLogic {
private static final Logger log = LogManager.getLogger(UpdateDeviceLogic.class);
public void messageReceived(ChannelHandlerContext ctx, User user, StringMessage message) {
String[] split = split2(message.body);
if (split.length < 2) {
throw new IllegalCommandException("Wrong income message format.");
}
int dashId = ParseUtil.parseInt(split[0]) ;
String deviceString = split[1];
if (deviceString == null || deviceString.equals("")) {
throw new IllegalCommandException("Income device message is empty.");
}
DashBoard dash = user.profile.getDashByIdOrThrow(dashId);
Device newDevice = JsonParser.parseDevice(deviceString);
log.debug("Updating new device {}.", deviceString);
Device existingDevice = dash.getDeviceById(newDevice.id);
existingDevice.update(newDevice);
dash.updatedAt = System.currentTimeMillis();
user.lastModifiedTs = dash.updatedAt;
ctx.writeAndFlush(ok(message.id), ctx.voidPromise());
}
}
|
2 | package org.rrd4j.core;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import junit.framework.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class RrdNioBackendTest {
@Rule
public TemporaryFolder testFolder = new TemporaryFolder();
@Test
public void testBackendFactoryWithExecutor() throws IOException {
RrdNioBackendFactory factory = (RrdNioBackendFactory) RrdBackendFactory.getFactory("NIO");
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
factory.setSyncThreadPool(new RrdSyncThreadPool());
File rrdfile = testFolder.newFile("testfile");
RrdBackend be = factory.open(rrdfile.getCanonicalPath(), false);
be.setLength(10);
be.writeDouble(0, 0);
be.close();
executor.shutdown();
DataInputStream is = new DataInputStream(new FileInputStream(rrdfile));
Double d = is.readDouble();
Assert.assertEquals("write to NIO failed", 0, d, 1e-10);
}
@Test
public void testBackendFactory() throws IOException {
RrdNioBackendFactory factory = (RrdNioBackendFactory) RrdBackendFactory.getFactory("NIO");
File rrdfile = testFolder.newFile("testfile");
RrdBackend be = factory.open(rrdfile.getCanonicalPath(), false);
be.setLength(10);
be.writeDouble(0, 0);
be.close();
DataInputStream is = new DataInputStream(new FileInputStream(rrdfile));
Double d = is.readDouble();
Assert.assertEquals("write to NIO failed", 0, d, 1e-10);
}
}
|
2 | package com.brianway.webporter.collector.zhihu;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
* Created by brian on 16/12/19.
*/
public class SegmentReader {
private static final Logger logger = LoggerFactory.getLogger(SegmentReader.class);
public static String readFollowees(File inItem) {
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader(inItem)
);
String s;
in.readLine();//pass first line
s = in.readLine();
if (!StringUtils.isEmpty(s)) {
s = s.substring(s.indexOf("{"));
}
in.close();
return s;
} catch (IOException e) {
logger.error("IOException when readFollowees user data from file : {}", e);
return null;
}
}
public static String readMember(File inItem) {
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader(inItem)
);
String s;
in.readLine();//pass first line
s = in.readLine();
in.close();
return s;
} catch (IOException e) {
logger.error("IOException when readFollowees user data from file : {}", e);
return null;
}
}
}
|
2 | import ocr.OCR;
import ocr.impl.OCRFactory;
import pattern.Pattern;
import pattern.impl.PatternFactory;
import utils.Utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by 618 on 2018/1/8.
*
* @author lingfengsan
*/
public class Main {
/**
* ADB_PATH为自己的adb驱动目录,可以放在resource目录下,也可以自己指定
* IMAGE_PATH为本机图片存放目录,必须是已存在目录
*/
// private static final String ADB_PATH = "D:\\software\\Android\\android-sdk\\platform-tools\\adb";
private static final String ADB_PATH = new File("").getAbsolutePath()+"\\target\\classes\\adb\\adb";
private static final String IMAGE_PATH = "D:\\Photo";
private static final OCRFactory OCR_FACTORY = new OCRFactory();
private static final PatternFactory PATTERN_FACTORY = new PatternFactory();
private static final Utils UTILS = new Utils(ADB_PATH, IMAGE_PATH);
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请选择您要使用的文字识别方式\n1.TessOCR\n2.百度OCR");
System.out.println("默认使用TessOCR,选择后回车");
OCR ocr = OCR_FACTORY.getOcr(Integer.valueOf(bf.readLine()));
System.out.println("请选择您要进入的游戏\n1.百万英雄\n2.冲顶大会");
System.out.println("默认为百万英雄,选择后回车");
Pattern pattern = PATTERN_FACTORY.getPattern(Integer.valueOf(bf.readLine()), ocr, UTILS);
while (true) {
String str = bf.readLine();
if ("exit".equals(str)) {
System.out.println("ヾ( ̄▽ ̄)Bye~Bye~");
break;
} else {
if (str.length() == 0) {
System.out.print("开始答题");
pattern.run();
}
}
}
}
}
|
1 | using DeBroglie.Constraints;
using DeBroglie.Models;
using DeBroglie.Topo;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DeBroglie.Test.Constraints
{
[TestFixture]
public class SeparationConstraintTest
{
[Test]
public void TestSeparationConstraint()
{
var model = new AdjacentModel(DirectionSet.Cartesian2d);
var tile1 = new Tile(1);
var tile2 = new Tile(2);
var tiles = new[] { tile1, tile2 };
model.AddAdjacency(tiles, tiles, Direction.XPlus);
model.AddAdjacency(tiles, tiles, Direction.YPlus);
model.SetUniformFrequency();
var separationConstraint = new SeparationConstraint
{
Tiles = new[] { tile1 }.ToHashSet(),
MinDistance = 3,
};
var countConstraint = new CountConstraint
{
Tiles = new[] { tile1 }.ToHashSet(),
Count = 2,
Comparison = CountComparison.Exactly,
};
var topology = new GridTopology(4, 1, false);
var options = new TilePropagatorOptions
{
Constraints = new ITileConstraint[] { separationConstraint, countConstraint },
BackTrackDepth = -1,
};
var propagator = new TilePropagator(model, topology, options);
propagator.Run();
Assert.AreEqual(Resolution.Decided, propagator.Status);
var r = propagator.ToArray();
// Only possible solution given the constraints
Assert.AreEqual(tile1, r.Get(0));
Assert.AreEqual(tile2, r.Get(1));
Assert.AreEqual(tile2, r.Get(2));
Assert.AreEqual(tile1, r.Get(3));
}
}
}
|
10 | using System;
using System.Security.Cryptography;
using System.Text;
namespace SQLite.CodeFirst.Utility
{
internal static class HashCreator
{
public static string CreateHash(string data)
{
byte[] dataBytes = Encoding.ASCII.GetBytes(data);
SHA512 sha512 = new SHA512Managed();
byte[] hashBytes = sha512.ComputeHash(dataBytes);
string hash = Convert.ToBase64String(hashBytes);
return hash;
}
}
}
|
10 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
namespace FluentEmail
{
public class Email
{
public MailMessage Message { get; set; }
public Exception Error { get; set; }
public bool HasError
{
get
{
return Error != null;
}
}
public static Email New { get { return new Email(); } }
private Email()
{
Message = new MailMessage() { IsBodyHtml = true };
}
public Email To(string emailAddress, string name = "")
{
Message.To.Add(new MailAddress(emailAddress, name));
return this;
}
public Email From(string emailAddress, string name = "")
{
Message.From = new MailAddress(emailAddress, name);
return this;
}
public Email Subject(string subject)
{
Message.Subject = subject;
return this;
}
public Email Body(string body)
{
Message.Body = body;
return this;
}
public Email Send()
{
try
{
var client = new SmtpClient();
client.Send(Message);
}
catch (Exception ex)
{
Error = ex;
}
return this;
}
public Email SendAsync(SendCompletedEventHandler callback, object token = null)
{
var client = new SmtpClient();
client.SendCompleted += callback;
client.SendAsync(Message, token);
return this;
}
}
}
|
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.FileOutputStream;
import junit.framework.TestCase;
public final class ArOutputStreamTestCase extends TestCase {
public void testWrite() throws Exception {
final File out1 = File.createTempFile("jdeb", ".ar");
final ArOutputStream os = new ArOutputStream(new FileOutputStream(out1));
os.putNextEntry(new ArEntry("data", 4));
os.write("data".getBytes());
os.close();
assertTrue(out1.delete());
}
}
|
10 | using System;
using System.Drawing;
using System.Linq;
using System.Threading;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server.Features;
namespace Webview.WebHost
{
public static class WebHostExtensions
{
public static void RunWebview(this IWebHost host, WebviewBuilder builder)
{
CancellationTokenSource cts = new CancellationTokenSource();
host.StartAsync(cts.Token);
var features = host.ServerFeatures.Get<IServerAddressesFeature>();
string address = features.Addresses.FirstOrDefault();
IContent content = Content.FromUri(new Uri(address));
builder.WithContent(content).Build().Run();
cts.Cancel();
}
public static void RunWebview(this IWebHost host, string Title = "", Size size = default(Size))
{
RunWebview(host, new WebviewBuilder().WithTitle(Title).WithSize(size));
}
}
public static class WebHostBuilderExtensions
{
public static IWebHostBuilder ConfigureForWebview(this IWebHostBuilder builder)
{
return builder.ConfigureLogging((ILoggingBuilder logBuilder) => { logBuilder.ClearProviders(); })
.UseUrls("http://127.0.0.1:0");
}
}
}
|
2 | package org.zalando.riptide;
/*
*
* Riptide
*
* Copyright (C) 2015 - 2016 Zalando SE
*
* 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.
*
*/
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.http.client.AsyncClientHttpRequestFactory;
import java.io.IOException;
import java.net.URISyntaxException;
import static java.util.Collections.emptyList;
import static org.springframework.http.HttpStatus.Series.SUCCESSFUL;
import static org.zalando.riptide.Bindings.on;
import static org.zalando.riptide.Navigators.series;
import static org.zalando.riptide.Routes.pass;
public final class HandlesIOExceptionTest {
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void shouldHandleExceptionDuringRequestCreation() throws URISyntaxException, IOException {
exception.expect(IOException.class);
exception.expectMessage("Could not create request");
final AsyncClientHttpRequestFactory factory = (uri, httpMethod) -> {
throw new IOException("Could not create request");
};
Rest.create(factory, emptyList())
.get("http://localhost/")
.dispatch(series(),
on(SUCCESSFUL).call(pass()));
}
}
|
4 | package com.fasterxml.jackson.databind.deser;
import java.util.concurrent.atomic.*;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestSimpleAtomicTypes
extends com.fasterxml.jackson.databind.BaseMapTest
{
public void testAtomicBoolean() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
AtomicBoolean b = mapper.readValue("true", AtomicBoolean.class);
assertTrue(b.get());
}
public void testAtomicInt() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
AtomicInteger value = mapper.readValue("13", AtomicInteger.class);
assertEquals(13, value.get());
}
public void testAtomicLong() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
AtomicLong value = mapper.readValue("12345678901", AtomicLong.class);
assertEquals(12345678901L, value.get());
}
public void testAtomicReference() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
AtomicReference<long[]> value = mapper.readValue("[1,2]",
new com.fasterxml.jackson.core.type.TypeReference<AtomicReference<long[]>>() { });
Object ob = value.get();
assertNotNull(ob);
assertEquals(long[].class, ob.getClass());
long[] longs = (long[]) ob;
assertNotNull(longs);
assertEquals(2, longs.length);
assertEquals(1, longs[0]);
assertEquals(2, longs[1]);
}
}
|
10 | using System;
using System.IO;
using System.Reflection;
namespace RazorEngineCore
{
public class RazorEngineCompiledTemplate<T> where T : RazorEngineTemplateBase
{
private readonly MemoryStream assemblyByteCode;
private readonly Type templateType;
internal RazorEngineCompiledTemplate(MemoryStream assemblyByteCode)
{
this.assemblyByteCode = assemblyByteCode;
Assembly assembly = Assembly.Load(assemblyByteCode.ToArray());
this.templateType = assembly.GetType("TemplateNamespace.Template");
}
public static RazorEngineCompiledTemplate<T> LoadFromFile(string fileName)
{
return new RazorEngineCompiledTemplate<T>(new MemoryStream(File.ReadAllBytes(fileName)));
}
public static RazorEngineCompiledTemplate<T> LoadFromStream(Stream stream)
{
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
memoryStream.Position = 0;
return new RazorEngineCompiledTemplate<T>(memoryStream);
}
public void SaveToStream(Stream stream)
{
this.assemblyByteCode.CopyTo(stream);
}
public void SaveToFile(string fileName)
{
File.WriteAllBytes(fileName, this.assemblyByteCode.ToArray());
}
public string Run(Action<T> initializer)
{
T instance = (T) Activator.CreateInstance(this.templateType);
initializer(instance);
instance.ExecuteAsync().Wait();
return instance.Result();
}
}
} |
2 | package com.duoqu.commons.fmj.runner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by tonydeng on 15/4/20.
*/
public class DefaultProcessCallbackHandler implements ProcessCallbackHandler{
private static final Logger log = LoggerFactory.getLogger(DefaultProcessCallbackHandler.class);
private String result;
public String handler(InputStream errorStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream,BaseCommandOption.UTF8));
StringBuffer sb = new StringBuffer();
String line;
try {
while ((line = reader.readLine()) != null){
sb.append(line).append("\n");
// if(log.isDebugEnabled())
// log.debug(line);
}
}catch (IOException e){
log.error("read from process error : '{}'",e);
throw e;
}finally {
try {
errorStream.close();
}catch (IOException e){
log.error("close errorStream error: '{}'",e);
}
}
setResult(sb.toString());
return getResult();
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
|
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 | /*
* 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.compress.compressors;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.compress.AbstractTestCase;
import org.apache.commons.compress.utils.IOUtils;
public final class BZip2TestCase extends AbstractTestCase {
public void testBzipCreation() throws Exception {
final File input = getFile("test.txt");
final File output = new File(dir, "test.txt.bz2");
final OutputStream out = new FileOutputStream(output);
final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("bzip2", out);
IOUtils.copy(new FileInputStream(input), cos);
cos.close();
}
public void testBzip2Unarchive() throws Exception {
final File input = getFile("bla.txt.bz2");
final File output = new File(dir, "bla.txt");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
}
}
|
10 | using Microsoft.Extensions.DependencyInjection;
using Rhisis.Game.Abstractions.Entities;
using Rhisis.Game.Abstractions.Features;
using Rhisis.Game.Abstractions.Systems;
using Rhisis.Game.Common;
using Rhisis.Network;
using Rhisis.Network.Snapshots;
using System;
namespace Rhisis.Game.Abstractions.Components
{
public class Health : IHealth
{
private readonly IMover _mover;
private readonly Lazy<IHealthFormulas> _healthFormulas;
public bool IsDead => Hp < 0;
public int Hp { get; set; }
public int Mp { get; set; }
public int Fp { get; set; }
public int MaxHp => _healthFormulas.Value.GetMaxHp(_mover);
public int MaxMp => _healthFormulas.Value.GetMaxMp(_mover);
public int MaxFp => _healthFormulas.Value.GetMaxFp(_mover);
/// <summary>
/// Creates a new <see cref="Health"/> instance.
/// </summary>
/// <param name="player">Current player.</param>
public Health(IMover mover)
{
_mover = mover;
_healthFormulas = new Lazy<IHealthFormulas>(() => mover.Systems.GetService<IHealthFormulas>());
}
public void RegenerateAll()
{
Hp = MaxHp;
Mp = MaxMp;
Fp = MaxFp;
using var healthSnapshot = new FFSnapshot();
healthSnapshot.Merge(new UpdateParamPointSnapshot(_mover, DefineAttributes.HP, Hp));
healthSnapshot.Merge(new UpdateParamPointSnapshot(_mover, DefineAttributes.MP, Mp));
healthSnapshot.Merge(new UpdateParamPointSnapshot(_mover, DefineAttributes.FP, Fp));
_mover.SendToVisible(healthSnapshot);
if (_mover is IPlayer)
{
_mover.Send(healthSnapshot);
}
}
}
}
|
2 | package de.l3s.boilerpipe.sax;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.zip.GZIPInputStream;
/**
* A very simple HTTP/HTML fetcher, really just for demo purposes.
*
* @author Christian Kohlschütter
*/
public class HTMLFetcher {
private HTMLFetcher() {
}
/**
* Fetches the document at the given URL, using {@link URLConnection}.
* @param url
* @return
* @throws IOException
*/
public static HTMLDocument fetch(final URL url) throws IOException {
final URLConnection conn = url.openConnection();
final String charset = conn.getContentEncoding();
Charset cs = Charset.forName("Cp1252");
if (charset != null) {
try {
cs = Charset.forName(charset);
} catch (UnsupportedCharsetException e) {
// keep default
}
}
InputStream in = conn.getInputStream();
final String encoding = conn.getContentEncoding();
if(encoding != null) {
if("gzip".equalsIgnoreCase(encoding)) {
in = new GZIPInputStream(in);
} else {
System.err.println("WARN: unsupported Content-Encoding: "+encoding);
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
int r;
while ((r = in.read(buf)) != -1) {
bos.write(buf, 0, r);
}
in.close();
final byte[] data = bos.toByteArray();
return new HTMLDocument(data, cs);
}
}
|
2 | package com.poiji.internal;
import com.poiji.internal.PoijiOptions.PoijiOptionsBuilder;
import com.poiji.internal.marshaller.Deserializer;
import com.poiji.util.Files;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
/**
* The main entry point of mapping excel data to Java classes
* <br>
* Created by hakan on 16/01/2017.
*/
public final class Poiji {
private Poiji() {
}
public static <T> List<T> fromExcel(File file, Class<T> clazz) throws FileNotFoundException {
final Deserializer unmarshaller = deserializer(file, PoijiOptionsBuilder.settings().build());
return deserialize(clazz, unmarshaller);
}
public static <T> List<T> fromExcel(File file, Class<T> clazz, PoijiOptions options) throws FileNotFoundException {
final Deserializer unmarshaller = deserializer(file, options);
return deserialize(clazz, unmarshaller);
}
@SuppressWarnings("unchecked")
private static Deserializer deserializer(File file, PoijiOptions options) throws FileNotFoundException {
final PoijiStream poiParser = new PoijiStream(fileInputStream(file));
final PoiWorkbook workbook = PoiWorkbook.workbook(Files.getExtension(file.getName()), poiParser);
return Deserializer.instance(workbook, options);
}
private static <T> List<T> deserialize(final Class<T> type, final Deserializer unmarshaller) {
return unmarshaller.deserialize(type);
}
private static FileInputStream fileInputStream(File file) throws FileNotFoundException {
return new FileInputStream(file);
}
}
|
2 | package com.tinkerpop.gremlin.elastic.elastic;
import com.tinkerpop.gremlin.elastic.ElasticService;
import com.tinkerpop.gremlin.elastic.structure.ElasticGraph;
import com.tinkerpop.gremlin.structure.Edge;
import com.tinkerpop.gremlin.structure.Graph;
import com.tinkerpop.gremlin.structure.Vertex;
import org.apache.commons.configuration.BaseConfiguration;
import org.apache.commons.lang3.time.StopWatch;
import org.junit.Test;
import java.io.IOException;
import java.util.Iterator;
public class PerformanceTests {
StopWatch sw = new StopWatch();
@Test
public void profile() throws IOException {
BaseConfiguration config = new BaseConfiguration();
config.addProperty(Graph.GRAPH, ElasticGraph.class.getName());
config.addProperty("elasticsearch.cluster.name", "test");
String indexName = "graph";
config.addProperty("elasticsearch.index.name", indexName.toLowerCase());
config.addProperty("elasticsearch.refresh", true);
config.addProperty("elasticsearch.client", ElasticService.ClientType.NODE.toString());
startWatch();
ElasticGraph graph = new ElasticGraph(config);
stopWatch("graph initalization");
startWatch();
int count = 1000;
for(int i = 0; i < count; i++)
graph.addVertex();
stopWatch("add vertices");
startWatch();
Iterator<Vertex> vertexIterator = graph.iterators().vertexIterator();
stopWatch("vertex iterator");
startWatch();
vertexIterator.forEachRemaining(v -> v.addEdge("bla", v));
stopWatch("add edges");
startWatch();
Iterator<Edge> edgeIterator = graph.iterators().edgeIterator();
stopWatch("edge iterator");
}
private void stopWatch(String s) {
sw.stop();
System.out.println(s + ": " + sw.getTime()/1000f);
}
private void startWatch() {
sw.reset();
sw.start();
}
}
|
2 | package com.github.davidmoten.rtree.fbs;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import com.github.davidmoten.rtree.GreekEarthquakes;
import com.github.davidmoten.rtree.RTree;
import com.github.davidmoten.rtree.geometry.Geometry;
import com.github.davidmoten.rtree.geometry.Point;
import rx.functions.Func1;
public class FlatBuffersSerializerTest {
private static final byte[] EMPTY = new byte[] {};
@Test
public void testSerializeRoundTrip() throws IOException {
RTree<Object, Point> tree = RTree.star().maxChildren(10).create();
tree = tree.add(GreekEarthquakes.entries()).last().toBlocking().single();
long t = System.currentTimeMillis();
File output = new File("target/file");
FileOutputStream os = new FileOutputStream(output);
FlatBuffersSerializer serializer = new FlatBuffersSerializer();
serializer.serialize(tree, new Func1<Object, byte[]>() {
@Override
public byte[] call(Object o) {
return EMPTY;
}
}, os);
os.close();
System.out.println("written in " + (System.currentTimeMillis() - t) + "ms, " + "file size="
+ output.length() / 1000000.0 + "MB");
System.out.println("bytes per entry=" + output.length() / tree.size());
InputStream is = new FileInputStream(output);
if (false) {
RTree<Object, Geometry> tr = serializer.deserialize(is, new Func1<byte[], Object>() {
@Override
public Object call(byte[] bytes) {
return "a";
}
});
}
}
}
|
10 | using System;
using System.IO;
using Eto.Drawing;
using MonoMac.AppKit;
using MonoMac.Foundation;
namespace Eto.Platform.Mac.Drawing
{
public class IconHandler : WidgetHandler<NSImage, Icon>, IIcon
{
public IconHandler()
{
}
public IconHandler(NSImage image)
{
Control = image;
}
#region IIcon Members
public void Create (Stream stream)
{
var data = NSData.FromStream(stream);
// I love linda lots and lots and lots!!!
Control = new NSImage (data);
}
public void Create (string fileName)
{
Control = new NSImage (fileName);
}
#endregion
public Size Size {
get {
return Generator.ConvertF(Control.Size);
}
}
}
}
|
10 | using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Sir.Search;
using Sir.VectorSpace;
using System;
using System.IO;
namespace Sir.HttpServer
{
public static class ServiceConfiguration
{
public static IServiceProvider Configure(IServiceCollection services)
{
var assemblyPath = Directory.GetCurrentDirectory();
var config = new KeyValueConfiguration(Path.Combine(assemblyPath, "sir.ini"));
services.Add(new ServiceDescriptor(typeof(IConfigurationProvider), config));
var loggerFactory = services.BuildServiceProvider().GetService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger("Sir");
var model = new BagOfCharsModel();
var sessionFactory = new Database(logger);
var directory = config.Get("data_dir");
var qp = new QueryParser<string>(directory, sessionFactory, model, logger);
var httpParser = new HttpQueryParser(qp);
services.AddSingleton(typeof(IModel<string>), model);
services.AddSingleton(typeof(IDatabase), sessionFactory);
services.AddSingleton(typeof(Database), sessionFactory);
services.AddSingleton(typeof(QueryParser<string>), qp);
services.AddSingleton(typeof(HttpQueryParser), httpParser);
services.AddSingleton(typeof(IHttpWriter), new HttpWriter(sessionFactory, config));
services.AddSingleton(typeof(IHttpReader), new HttpReader(
sessionFactory,
httpParser,
config,
loggerFactory.CreateLogger<HttpReader>()));
return services.BuildServiceProvider();
}
}
}
|
4 | package cn.sinjinsong.chat.server;
import cn.sinjinsong.chat.server.handler.MessageHandler;
import cn.sinjinsong.chat.server.util.SpringContextUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by SinjinSong on 2017/5/23.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@Configuration
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class ChatServerTest {
@Test
public void test() {
MessageHandler messageHandler = SpringContextUtil.getBean("MessageHandler","login");
messageHandler.handle(null,null,null,null);
}
} |
2 | package org.slf4j.converter;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import org.slf4j.converter.line.LineConverter;
public class InplaceFileConverter {
final static int BUFFER_LEN = 8 * 1024;
final LineConverter lineConverter;
final String lineTerminator;
InplaceFileConverter(LineConverter lineConverter) {
this.lineConverter = lineConverter;
lineTerminator = System.getProperty("line.separator");
}
byte[] readFile(File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int n = 0;
byte[] buffer = new byte[BUFFER_LEN];
while ((n = fis.read(buffer)) != -1) {
// System.out.println("ba="+new String(buffer, "UTF-8"));
baos.write(buffer, 0, n);
}
fis.close();
return baos.toByteArray();
}
void convert(File file, byte[] input) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(input);
Reader reader = new InputStreamReader(bais);
BufferedReader breader = new BufferedReader(reader);
FileWriter fileWriter = new FileWriter(file);
while (true) {
String line = breader.readLine();
if (line != null) {
String[] replacement = lineConverter.getReplacement(line);
writeReplacement(fileWriter, replacement);
} else {
fileWriter.close();
break;
}
}
}
void writeReplacement(Writer writer, String[] replacement) throws IOException {
for (int i = 0; i < replacement.length; i++) {
writer.write(replacement[i]);
writer.write(lineTerminator);
}
}
}
|
2 | /**
* Created by shenhongxi on 2017/6/21.
*/
package org.hongxi.whatsmars.dubbo.demo.consumer;
import com.alibaba.dubbo.rpc.service.EchoService;
import org.hongxi.whatsmars.dubbo.demo.api.DemoService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DemoConsumer {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"META-INF/spring/dubbo-demo-consumer.xml"});
context.start();
// dubbo protocol
DemoService demoService = (DemoService) context.getBean("demoService"); // 获取远程服务代理
String hello = demoService.sayHello("dubbo"); // 执行远程方法
System.out.println(hello); // 显示调用结果
// hessian protocol 直连
DemoService demoService2 = (DemoService) context.getBean("demoService2");
String hello2 = demoService2.sayHello("hessian直连");
System.out.println(hello2);
// hessian protocol
DemoService demoService3 = (DemoService) context.getBean("demoService3");
String hello3 = demoService3.sayHello("hessian");
System.out.println(hello3);
// service group
DemoService demoService4 = (DemoService) context.getBean("demoService4");
String hello4 = demoService4.sayHello("group:new");
System.out.println(hello4);
// 回声测试可用性
EchoService echoService = (EchoService) demoService;
Object status = echoService.$echo("OK");
System.out.println("回声测试:" + status.equals("OK"));
}
} |
10 | // --------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// --------------------------------------------------------------------------------------------
using McMaster.Extensions.CommandLineUtils;
using Microsoft.Oryx.BuildScriptGeneratorCli;
using Xunit;
namespace BuildScriptGeneratorCli.Tests
{
public class ProgramTest
{
[Fact]
public void OnExecute_ShowsHelp_AndExits_WithSuccessExitCode()
{
// Arrange
var program = new Program();
var testConsole = new TestConsole();
// Act
var exitCode = program.OnExecute(new CommandLineApplication(testConsole), testConsole);
// Assert
Assert.Equal(0, exitCode);
Assert.Contains("Usage:", testConsole.Output);
}
}
}
|
7 | using System;
using DocoptNet;
namespace NavalFate
{
internal class Program
{
private const string usage = @"Naval Fate.
Usage:
naval_fate.exe ship new <name>...
naval_fate.exe ship <name> move <x> <y> [--speed=<kn>]
naval_fate.exe ship shoot <x> <y>
naval_fate.exe mine (set|remove) <x> <y> [--moored | --drifting]
naval_fate.exe (-h | --help)
naval_fate.exe --version
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.
";
private static void Main(string[] args)
{
var arguments = new Docopt().Apply(usage, args, version: "Naval Fate 2.0");
foreach (var argument in arguments)
{
Console.WriteLine("{0} = {1}", argument.Key, argument.Value);
}
}
}
} |
10 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KafkaNet;
using KafkaNet.Model;
using KafkaNet.Protocol;
using Moq;
using NUnit.Framework;
using Ninject.MockingKernel.Moq;
namespace kafka_tests.Unit
{
[TestFixture]
public class ProducerTests
{
private MoqMockingKernel _kernel;
private BrokerRouterMock _brokerRouterMock;
[SetUp]
public void Setup()
{
_kernel = new MoqMockingKernel();
_brokerRouterMock = new BrokerRouterMock(_kernel);
}
[Test]
public void ProducerShouldGroupMessagesByBroker()
{
var router = _brokerRouterMock.CreateBrokerRouter();
var producer = new Producer(router);
var messages = new List<Message>
{
new Message{Value = "1"}, new Message{Value = "2"}
};
var response = producer.SendMessageAsync("UnitTest", messages).Result;
Assert.That(response.Count, Is.EqualTo(2));
_brokerRouterMock.BrokerConn0.Verify(x => x.SendAsync(It.IsAny<IKafkaRequest<ProduceResponse>>()), Times.Once());
_brokerRouterMock.BrokerConn1.Verify(x => x.SendAsync(It.IsAny<IKafkaRequest<ProduceResponse>>()), Times.Once());
}
}
}
|
2 | package com.github.davidmoten.rtree.fbs;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import com.github.davidmoten.rtree.GreekEarthquakes;
import com.github.davidmoten.rtree.RTree;
import com.github.davidmoten.rtree.geometry.Geometry;
import com.github.davidmoten.rtree.geometry.Point;
import rx.functions.Func1;
public class FlatBuffersSerializerTest {
@Test
public void testSerializeRoundTrip() throws IOException {
RTree<Object, Point> tree = RTree.star().maxChildren(4).create();
tree = tree.add(GreekEarthquakes.entries()).last().toBlocking().single();
long t = System.currentTimeMillis();
File output = new File("target/file");
FileOutputStream os = new FileOutputStream(output);
FlatBuffersSerializer serializer = new FlatBuffersSerializer();
serializer.serialize(tree, new Func1<Object, byte[]>() {
@Override
public byte[] call(Object o) {
return "boo".getBytes();
}
}, os);
os.close();
System.out.println("written in " + (System.currentTimeMillis() - t) + "ms, " + "file size="
+ output.length());
InputStream is = new FileInputStream(output);
RTree<Object, Geometry> tr = serializer.deserialize(is);
}
}
|
10 | using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Xml.Linq;
using PointOfSale.Common.Config;
using PointOfSale.Common.Utils;
using PointOfSale.Services.Products.Models;
namespace PointOfSale.Services.Products
{
public class ProductService : IProductService
{
private readonly string _endpoint;
private readonly INemesis _nemesis;
public ProductService(IServiceEndpoints serviceEndpoints, INemesis nemesis)
{
if (serviceEndpoints == null)
throw new ArgumentNullException("serviceEndpoints");
if (nemesis == null)
throw new ArgumentNullException("nemesis");
_endpoint = serviceEndpoints.ProductEndpoint;
_nemesis = nemesis;
}
public Collection<int> GetProductIds()
{
_nemesis.Invoke();
var webClient = new WebClient();
string response = webClient.DownloadString(_endpoint);
var productIds = XDocument.Parse(response).Root.Elements("PRODUCT").Select(p => (int)p).ToList();
return new Collection<int>(productIds);
}
public Product GetProduct(int productId)
{
_nemesis.Invoke();
var webClient = new WebClient();
string response = webClient.DownloadString(string.Format("{0}/{1}", _endpoint, productId));
var xml = XDocument.Parse(response).Root;
return new Product
{
ProductId = (int)xml.Element("ID"),
Name = (string)xml.Element("NAME"),
Price = (decimal)xml.Element("PRICE")
};
}
}
}
|
10 | using System;
using System.Collections.Generic;
using System.Diagnostics;
using Elastic.Agent.Core.DiagnosticListeners;
using Elastic.Agent.Core.DiagnosticSource;
namespace Elastic.Agent.EntityFrameworkCore
{
//TODO: probably rename, make it somehow central to start every listener with 1 line - should live in Agent.Core
public class EfCoreListener
{
public void Start()
{
System.Diagnostics.DiagnosticListener
.AllListeners
.Subscribe(new DiagnosticInitializer(new List<IDiagnosticListener>{ new EfCoreDiagnosticListener(), new HttpDiagnosticListener() }));
}
}
}
|
4 | /*
* Copyright 2010-2014, Sikuli.org, SikuliX.com
* Released under the MIT License.
*
* modified RaiMan
*/
package org.sikuli.script;
import org.sikuli.basics.Debug;
import java.awt.Rectangle;
/**
* CANDIDATE FOR DEPRECATION
* INTERNAL USE
* An extension of DesktopScreen, that uses all active monitors as one big screen
*
* TO BE EVALUATED: is this really needed?
*/
public class ScreenUnion extends Screen {
private Rectangle _bounds;
public ScreenUnion() {
super(true);
Rectangle r = getBounds();
x = r.x;
y = r.y;
w = r.width;
h = r.height;
}
public int getIdFromPoint(int x, int y) {
Rectangle sr = getBounds();
int _x = x + getBounds().x;
int _y = y + getBounds().y;
for (int i = 0; i < getNumberScreens(); i++) {
if (Screen.getScreen(i).contains(new Location(_x, _y))) {
Debug.log(3, "ScreenUnion: getIdFromPoint: " +
"(%d, %d) as (%d, %d) in (%d, %d, %d, %d) on %d",
x, y, _x, _y, sr.x, sr.y, sr.width, sr.height, i);
return i;
}
}
Debug.log(3, "ScreenUnion: getIdFromPoint: " +
"(%d, %d) as (%d, %d) in (%d, %d, %d, %d) on ???",
x, y, _x, _y, sr.x, sr.y, sr.width, sr.height);
return 0;
}
@Override
public Rectangle getBounds() {
if (_bounds == null) {
_bounds = new Rectangle();
for (int i = 0; i < Screen.getNumberScreens(); i++) {
_bounds = _bounds.union(Screen.getBounds(i));
}
}
return _bounds;
}
@Override
public ScreenImage capture(Rectangle rect) {
Debug.log(3, "ScreenUnion: capture: " + rect);
return Region.create(rect).getScreen().capture(rect);
}
@Override
public boolean useFullscreen() {
return false;
}
}
|
2 | package com.github.tobato.soket.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class SoketServer {
private int port = 22122;
private ServerSocket serverSocket;
public void service() {
int i = 0;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e1) {
e1.printStackTrace();
}
while (true) {
Socket socket = null;
try {
i++;
socket = serverSocket.accept(); // 主线程获取客户端连接
System.out.println("第" + i + "个客户端成功连接!");
Thread workThread = new Thread(new Handler(socket)); // 创建线程
workThread.start(); // 启动线程
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] agrs) {
SoketServer server = new SoketServer();
System.out.println("------服务启动--------");
server.service();
}
}
|
2 | import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by 618 on 2018/1/8.
*
* @author lingfengsan
*/
public class Phone {
/**
* 此处应更改为自己的adb目录
*/
private static final String ADB_PATH = "D:\\software\\Android\\android-sdk\\platform-tools\\adb";
private static final String HERO_PATH = "D:\\Photo";
File getImage() {
//获取当前时间作为名字
Date current = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String curDate = df.format(current);
File curPhoto = new File(HERO_PATH, curDate + ".png");
//截屏存到手机本地
try {
while(!curPhoto.exists()) {
Runtime.getRuntime().exec(ADB_PATH
+ " shell /system/bin/screencap -p /sdcard/screenshot.png");
Thread.sleep(700);
//将截图放在电脑本地
Runtime.getRuntime().exec(ADB_PATH
+ " pull /sdcard/screenshot.png " + curPhoto.getAbsolutePath());
Thread.sleep(200);
}
//返回当前图片名字
return curPhoto;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("获取图片失败");
return null;
}
public static void main(String[] args) {
new Phone().getImage();
}
}
|
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);
}
}
|
2 | package com.wf.captcha;
import org.junit.Test;
import java.io.File;
import java.io.FileOutputStream;
/**
* 测试类
* Created by 王帆 on 2018-07-27 上午 10:08.
*/
public class CaptchaTest {
@Test
public void test() throws Exception {
SpecCaptcha specCaptcha = new SpecCaptcha();
System.out.println(specCaptcha.text());
specCaptcha.out(new FileOutputStream(new File("D:/a/aa.png")));
}
@Test
public void testGIf() throws Exception {
GifCaptcha specCaptcha = new GifCaptcha(130, 48, 5);
System.out.println(specCaptcha.text());
specCaptcha.out(new FileOutputStream(new File("D:/a/aa.gif")));
}
}
|
7 | using System.IO;
using System.Linq;
using NUnit.Framework;
using Resin;
namespace Tests
{
[TestFixture]
public class FieldReaderTests
{
[Test]
public void Can_read_field_file()
{
const string fileName = "c:\\temp\\resin_tests\\Can_read_field_file\\0.fld";
if (File.Exists(fileName)) File.Delete(fileName);
using (var fw = new FieldFile(fileName))
{
fw.Write(0, "hello", 0);
fw.Write(5, "world", 1);
}
var reader = FieldReader.Load(fileName);
var helloPositionsForDocId0 = reader.GetDocPosition("hello")[0];
var worldPositionsForDocId5 = reader.GetDocPosition("world")[5];
Assert.AreEqual(0, helloPositionsForDocId0.First());
Assert.AreEqual(1, worldPositionsForDocId5.First());
}
}
}
|
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();
}
}
|
8 | // Copyright 2016 Jon Skeet. All rights reserved. Use of this source code is governed by the Apache License 2.0, as found in the LICENSE.txt file.
using System;
namespace CSharp7
{
class RefReturn
{
static void Main(string[] args)
{
var rng = new Random();
int a = 0, b = 0;
for (int i = 0; i < 20; i++)
{
GetRandomVariable(rng, ref a, ref b)++;
Console.WriteLine($"a={a}, b={b}");
}
}
static ref int GetRandomVariable(Random rng, ref int x, ref int y)
{
if (rng.NextDouble() >= 0.5)
{
return ref x;
}
else
{
return ref y;
}
}
}
}
|
2 | package fr.univartois.sonargo;
import static fr.univartois.sonargo.GoLintRulesDefinition.REPO_KEY;
import static fr.univartois.sonargo.GoLintRulesDefinition.REPO_NAME;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.Map.Entry;
import org.sonar.api.internal.apachecommons.lang.StringUtils;
import org.sonar.api.profiles.ProfileDefinition;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.rules.Rule;
import org.sonar.api.utils.ValidationMessages;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.graph.StringEdgeFactory;
/**
* The class define all rules that will detect by the sensor, it's not the same of {@link GoLintRulesDefinition}
* @author thibault
*
*/
public final class GoQualityProfile extends ProfileDefinition {
private static final Logger LOGGER=Loggers.get(GoQualityProfile.class);
private static final String PROFILE_PATH="/profile.properties";
/**
* {@inheritDoc}
*/
@Override
public RulesProfile createProfile(ValidationMessages validation) {
LOGGER.info("Golint Quality profile");
RulesProfile profile = RulesProfile.create("Golint Rules", GoLanguage.KEY);
profile.setDefaultProfile(Boolean.TRUE);
Properties prop=new Properties();
try {
prop.load(new FileInputStream(new File(PROFILE_PATH)));
for (Entry<Object, Object> e : prop.entrySet()) {
if(Boolean.TRUE.equals(Boolean.parseBoolean((String) e.getValue()))){
profile.activateRule(Rule.create(REPO_KEY,(String) e.getKey(),REPO_NAME), null);
}
}
}catch (IOException e) {
LOGGER.error((new StringBuilder()).append("Unable to load ").append(PROFILE_PATH).toString(), e);
}
LOGGER.info((new StringBuilder()).append("Profil generate: ").append(profile.getActiveRules()).toString());
return profile;
}
} |
10 | using Microsoft.Extensions.DependencyInjection;
using System.IO;
namespace Sir.Store
{
public class Start : IPluginStart
{
public void OnApplicationStartup(IServiceCollection services, ServiceProvider serviceProvider)
{
var tokenizer = new LatinTokenizer();
var config = serviceProvider.GetService<IConfigurationService>();
services.AddSingleton(typeof(LocalStorageSessionFactory),
new LocalStorageSessionFactory(
Path.Combine(Directory.GetCurrentDirectory(), "App_Data"),
tokenizer,
config));
services.AddSingleton(typeof(ITokenizer), tokenizer);
services.AddSingleton(typeof(HttpQueryParser), new HttpQueryParser(new BooleanKeyValueQueryParser()));
}
}
}
|
10 | namespace FakeItEasy
{
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using IoC;
internal class ImportsModule
: Module
{
[ImportMany(typeof(IArgumentValueFormatter))]
private IEnumerable<IArgumentValueFormatter> importedArgumentValueFormatters;
[ImportMany(typeof(IDummyDefinition))]
private IEnumerable<IDummyDefinition> importedDummyDefinitions;
[ImportMany(typeof(IFakeConfigurator))]
private IEnumerable<IFakeConfigurator> importedFakeConfigurators;
public ImportsModule()
{
this.SatisfyImports();
}
private void SatisfyImports()
{
var catalog = new DirectoryCatalog(Path.GetDirectoryName(typeof (ImportsModule).Assembly.Location));
var container = new CompositionContainer(catalog);
container.SatisfyImportsOnce(this);
}
public override void RegisterDependencies(DictionaryContainer container)
{
container.RegisterSingleton(c => this.importedArgumentValueFormatters);
container.RegisterSingleton(c => this.importedDummyDefinitions);
container.RegisterSingleton(c => this.importedFakeConfigurators);
}
}
} |
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();
}
}
|
10 | // -----------------------------------------------------------------------------------------
// <copyright file="HttpContentFactory.cs" company="Microsoft">
// Copyright 2013 Microsoft Corporation
//
// 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.
// </copyright>
// -----------------------------------------------------------------------------------------
namespace Microsoft.Azure.Storage.Shared.Protocol
{
using Microsoft.Azure.Storage.Core;
using Microsoft.Azure.Storage.Core.Executor;
using System;
using System.IO;
using System.Net.Http;
internal static class HttpContentFactory
{
public static HttpContent BuildContentFromStream<T>(Stream stream, long offset, long? length, Checksum checksum, RESTCommand<T> cmd, OperationContext operationContext)
{
stream.Seek(offset, SeekOrigin.Begin);
HttpContent retContent = new StreamContent(new NonCloseableStream(stream));
retContent.Headers.ContentLength = length;
if (checksum?.MD5 != null)
{
retContent.Headers.ContentMD5 = Convert.FromBase64String(checksum.MD5);
}
if (checksum?.CRC64 != null)
{
retContent.Headers.Add(Constants.HeaderConstants.ContentCrc64Header, checksum.CRC64);
}
return retContent;
}
}
}
|
4 | package net.dzikoysk.funnyguilds.command.admin;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import net.dzikoysk.funnyguilds.basic.Guild;
import net.dzikoysk.funnyguilds.basic.util.GuildUtils;
import net.dzikoysk.funnyguilds.command.util.Executor;
import net.dzikoysk.funnyguilds.data.Messages;
import net.dzikoysk.funnyguilds.data.configs.MessagesConfig;
public class AxcDelete implements Executor {
@Override
public void execute(CommandSender sender, String[] args) {
MessagesConfig messages = Messages.getInstance();
if (args.length < 1) {
sender.sendMessage(messages.generalNoTagGiven);
return;
}
if (!GuildUtils.tagExists(args[0])) {
sender.sendMessage(messages.generalNoGuildFound);
return;
}
Guild guild = GuildUtils.byTag(args[0]);
GuildUtils.deleteGuild(guild);
sender.sendMessage(messages.deleteSuccessful.replace("{GUILD}", guild.getName()).replace("{TAG}", guild.getTag()));
Player owner = guild.getOwner().getPlayer();
if (owner != null) {
owner.sendMessage(messages.adminGuildBroken.replace("{ADMIN}", sender.getName()));
}
Bukkit.getServer().broadcastMessage(messages.broadcastDelete.replace("{PLAYER}", sender.getName()).replace("{GUILD}", guild.getName()).replace("{TAG}", guild.getTag()));
}
}
|
4 | using System.Threading.Tasks;
using Disqord.Gateway.Api;
using Disqord.Gateway.Api.Models;
namespace Disqord.Gateway.Default.Dispatcher
{
public class GuildMemberUpdateHandler : Handler<GuildMemberUpdateJsonModel, MemberUpdatedEventArgs>
{
public override ValueTask<MemberUpdatedEventArgs> HandleDispatchAsync(IGatewayApiClient shard, GuildMemberUpdateJsonModel model)
{
CachedMember oldMember = null;
IMember newMember = null;
if (CacheProvider.TryGetMembers(model.GuildId, out var memberCache))
{
if (memberCache.TryGetValue(model.User.Value.Id, out var member))
{
newMember = member;
var oldUser = member.SharedUser.Clone() as CachedSharedUser;
oldMember = member.Clone() as CachedMember;
oldMember.SharedUser = oldUser;
newMember.Update(model);
}
else if (CacheProvider.TryGetUsers(out var userCache))
{
newMember = Dispatcher.GetOrAddMember(userCache, memberCache, model.GuildId, model);
}
}
newMember ??= new TransientMember(Client, model.GuildId, model);
var e = new MemberUpdatedEventArgs(oldMember, newMember);
return new(e);
}
}
}
|
4 | package com.itextpdf.core.pdf.navigation;
import com.itextpdf.basics.PdfException;
import com.itextpdf.core.pdf.*;
import java.util.HashMap;
public class PdfNamedDestination extends PdfDestination<PdfName> {
public PdfNamedDestination(String name) {
this(new PdfName(name));
}
public PdfNamedDestination(PdfName pdfObject) {
super(pdfObject);
}
public PdfNamedDestination(PdfName pdfObject, PdfDocument pdfDocument) throws PdfException {
super(pdfObject, pdfDocument);
}
@Override
public PdfObject getDestinationPage(final HashMap<Object, PdfObject> names) throws PdfException {
PdfArray array = (PdfArray) names.get(getPdfObject());
return array.get(0, false);
}
@Override
public PdfDestination replaceNamedDestination(final HashMap<Object, PdfObject> names){
PdfArray array = (PdfArray) names.get(getPdfObject());
if (array != null){
return PdfDestination.makeDestination(array);
}
return null;
}
}
|
4 | package net.benas.cb4j.tutorials;
import net.benas.cb4j.core.api.FieldValidator;
import net.benas.cb4j.core.impl.DefaultRecordValidatorImpl;
import net.benas.cb4j.core.model.Record;
import java.util.List;
import java.util.Map;
/**
* A custom validator to implement validation rule that involve multiple fields at the same time
* @author benas (md.benhassine@gmail.com)
*/
public class MyCustomRecordValidator extends DefaultRecordValidatorImpl {
public MyCustomRecordValidator(Map<Integer, List<FieldValidator>> fieldValidators) {
super(fieldValidators);
}
@Override
public String validateRecord(Record record) {
String error = super.validateRecord(record);
if (error.length() == 0){//no errors after applying declared validators on each field => all fields are valid
//add custom validation : field 2 content must starts with field 1 content
final String content1 = record.getFieldContentByIndex(1);
final String content2 = record.getFieldContentByIndex(2);
if (!content2.startsWith(content1))
return "field 2 content [" + content2 + "] must start with field 1 content [" + content1 + "]";
}
return "";
}
}
|
10 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetMQ.Actors;
using NUnit.Framework;
namespace NetMQ.Tests.InProcActors.Echo
{
[TestFixture]
public class EchoActorTests
{
[TestCase("I like NetMQ")]
[TestCase("NetMQ Is quite awesome")]
[TestCase("Agreed sockets on steroids with isotopes")]
public void EchoActorSendReceiveTests(string actorMessage)
{
EchoShimHandler echoShimHandler = new EchoShimHandler();
Actor actor = new Actor(NetMQContext.Create(), null,echoShimHandler, new object[] { "Hello World" });
actor.SendMore("ECHO");
actor.Send(actorMessage);
var result = actor.ReceiveString();
string expectedEchoHandlerResult = string.Format("ECHO BACK : {0}", actorMessage);
Assert.AreEqual(expectedEchoHandlerResult, result);
actor.Dispose();
}
[TestCase("BadCommand1")]
public void BadCommandTests(string command)
{
string actorMessage = "whatever";
EchoShimHandler echoShimHandler = new EchoShimHandler();
Action<Exception> pipeExceptionHandler = (ex) =>
{
Assert.AreEqual("Unexpected command",ex.Message);
};
Actor actor = new Actor(NetMQContext.Create(), pipeExceptionHandler, echoShimHandler, new object[] { "Hello World" });
actor.SendMore(command);
actor.Send(actorMessage);
var result = actor.ReceiveString();
string expectedEchoHandlerResult = string.Format("ECHO BACK : {0}", actorMessage);
Assert.AreEqual(expectedEchoHandlerResult, result);
actor.Dispose();
}
}
}
|
4 | package com.belerweb.social.weixin.api;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.belerweb.social.TestConfig;
import com.belerweb.social.bean.Result;
public class UserTest extends TestConfig {
@Test
public void testSnsapiUserInfo() {
String accessToken = System.getProperty("weixin.atoken");
String openId = System.getProperty("weixin.openid");
Result<com.belerweb.social.weixin.bean.User> result =
weixin.getUser().snsapiUserInfo(accessToken, openId);
Assert.assertTrue(result.success());
System.out.println(result.getResult().getJsonObject());
}
@Test
public void testUserInfo() {
String accessToken = System.getProperty("weixin.atoken");
String openId = System.getProperty("weixin.openid");
Result<com.belerweb.social.weixin.bean.User> result =
weixin.getUser().userInfo(accessToken, openId);
Assert.assertTrue(result.success());
System.out.println(result.getResult().getJsonObject());
}
@Test
public void testGetFollowUsers() {
Result<List<com.belerweb.social.weixin.bean.User>> result = weixin.getUser().getFollowUsers();
Assert.assertTrue(result.success());
for (com.belerweb.social.weixin.bean.User user : result.getResult()) {
System.out.println(user.getJsonObject());
}
}
}
|
10 | using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace Neo4jClient.Test.GraphClientTests.Cypher
{
[TestFixture]
public class ResultsTests
{
readonly Uri fakeEndpoint = new Uri("http://test.example.com/foo");
[Test]
public void ReturnColumnAlias()
{
// http://docs.neo4j.org/chunked/1.6/query-return.html#return-column-alias
// START a=node(1)
// RETURN a.Age AS SomethingTotallyDifferent
var client = new GraphClient(fakeEndpoint);
var results = client
.Cypher
.Start("a", (NodeReference)1)
.Return(a => new ReturnPropertyQueryResult
{
SomethingTotallyDifferent = a.As<FooNode>().Age
})
.Results;
Assert.IsInstanceOf<IEnumerable<ReturnPropertyQueryResult>>(results);
}
public class FooNode
{
public int Age { get; set; }
}
public class ReturnPropertyQueryResult
{
public int SomethingTotallyDifferent { get; set; }
}
}
}
|
2 | /*
* Copyright (c) 2016-2019 Zerocracy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to read
* the Software only. Permissions is hereby NOT GRANTED to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.zerocracy.tk;
import com.jcabi.matchers.XhtmlMatchers;
import com.zerocracy.Farm;
import com.zerocracy.FkFarm;
import com.zerocracy.farm.footprint.FtFarm;
import com.zerocracy.farm.props.PropsFarm;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
/**
* Test case for {@link TkIndex}.
* @since 1.0
* @checkstyle JavadocMethodCheck (500 lines)
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
*/
public final class TkIndexTest {
@Test
public void rendersIndexPage() throws Exception {
final Farm farm = new FtFarm(new PropsFarm(new FkFarm()));
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(new View(farm, "/").xml()),
XhtmlMatchers.hasXPaths("/page/alive")
);
}
}
|
10 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetMQ.Actors;
using NetMQ.Tests.InProcActors.AccountJSON;
using Newtonsoft.Json;
using NUnit.Framework;
namespace NetMQ.Tests.InProcActors.Echo
{
[TestFixture]
public class AccountActorTests
{
[Test]
public void AccountActorJSONSendReceiveTests()
{
AccountShimHandler accountShimHandler = new AccountShimHandler();
AccountAction accountAction = new AccountAction(TransactionType.Credit, 10);
Account account = new Account(1, "Test Account", "11223", 0);
Actor accountActor = new Actor(NetMQContext.Create(), null,accountShimHandler,
new object[] { JsonConvert.SerializeObject(accountAction) });
accountActor.SendMore("AMEND ACCOUNT");
accountActor.Send(JsonConvert.SerializeObject(account));
Account updatedAccount =
JsonConvert.DeserializeObject<Account>(accountActor.ReceiveString());
decimal expectedAccountBalance = 10.0m;
Assert.AreEqual(expectedAccountBalance, updatedAccount.Balance);
accountActor.Dispose();
}
}
}
|
10 | using Microsoft.Extensions.DependencyInjection;
namespace Sir.Store
{
/// <summary>
/// Initialize app.
/// </summary>
public class Start : IPluginStart
{
public void OnApplicationStartup(IServiceCollection services, ServiceProvider serviceProvider)
{
var tokenizer = new LatinTokenizer();
var config = serviceProvider.GetService<IConfigurationProvider>();
services.AddSingleton(typeof(SessionFactory),
new SessionFactory(
config.Get("data_dir"),
tokenizer,
config));
services.AddSingleton(typeof(ITokenizer), tokenizer);
services.AddSingleton(typeof(HttpQueryParser), new HttpQueryParser(new TermQueryParser(), tokenizer));
services.AddSingleton(typeof(HttpBowQueryParser), new HttpBowQueryParser(tokenizer));
}
}
}
|
2 | package com.github.jknack.handlebars.context;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import static org.apache.commons.io.FileUtils.copyURLToFile;
public class MultipleClassLoadersMethodValueResolverTest {
private final static String CLASS_NAME = "TestClass";
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private MethodValueResolver resolver = new MethodValueResolver();
@Before
public void compileTestClass() throws IOException, URISyntaxException {
String sourceFileName = CLASS_NAME + ".java";
File sourceFile = temp.newFile(sourceFileName);
URL sourceFileResourceUrl = getClass().getResource(sourceFileName).toURI().toURL();
copyURLToFile(sourceFileResourceUrl, sourceFile);
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, "-d", temp.getRoot().getAbsolutePath(), sourceFile.getAbsolutePath());
}
@Test
public void canResolveMethodsFromTheSameClassLoadedByDistinctClassLoaders() throws Exception {
Assert.assertEquals(resolver.resolve(loadTestClassWithDistinctClassLoader().newInstance(), "getField"), "value");
Assert.assertEquals(resolver.resolve(loadTestClassWithDistinctClassLoader().newInstance(), "getField"), "value");
}
private Class<?> loadTestClassWithDistinctClassLoader() throws Exception {
URL[] classpath = {temp.getRoot().toURI().toURL()};
URLClassLoader loader = new URLClassLoader(classpath);
return loader.loadClass(CLASS_NAME);
}
}
|
2 | package net.lingala.zip4j.util;
import net.lingala.zip4j.exception.ZipException;
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 java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import static net.lingala.zip4j.util.FileUtils.setFileAttributes;
import static net.lingala.zip4j.util.FileUtils.setFileLastModifiedTime;
import static net.lingala.zip4j.util.FileUtils.setFileLastModifiedTimeWithoutNio;
public class UnzipUtil {
public static ZipInputStream createZipInputStream(ZipModel zipModel, FileHeader fileHeader, char[] password)
throws ZipException {
try {
SplitInputStream splitInputStream = new SplitInputStream(zipModel.getZipFile(), zipModel.isSplitArchive(),
zipModel.getEndOfCentralDirectoryRecord().getNumberOfThisDisk());
splitInputStream.prepareExtractionForFileHeader(fileHeader);
ZipInputStream zipInputStream = new ZipInputStream(splitInputStream, password);
if (zipInputStream.getNextEntry(fileHeader) == null) {
throw new ZipException("Could not locate local file header for corresponding file header");
}
return zipInputStream;
} catch (IOException e) {
throw new ZipException(e);
}
}
public static void applyFileAttributes(FileHeader fileHeader, File file) {
try {
Path path = file.toPath();
setFileAttributes(path, fileHeader.getExternalFileAttributes());
setFileLastModifiedTime(path, fileHeader.getLastModifiedTime());
} catch (NoSuchMethodError e) {
setFileLastModifiedTimeWithoutNio(file, fileHeader.getLastModifiedTime());
}
}
}
|
10 | using Microsoft.Extensions.DependencyInjection;
namespace Sir.Store
{
/// <summary>
/// Initialize app.
/// </summary>
public class Start : IPluginStart
{
public void OnApplicationStartup(
IServiceCollection services, ServiceProvider serviceProvider, IConfigurationProvider config)
{
var model = new BocModel();
var httpParser = new HttpQueryParser(new QueryParser());
var httpBowParser = new HttpBowQueryParser(httpParser);
var sessionFactory = new SessionFactory(config, model);
services.AddSingleton(typeof(IStringModel), model);
services.AddSingleton(typeof(SessionFactory), sessionFactory);
services.AddSingleton(typeof(HttpQueryParser), httpParser);
services.AddSingleton(typeof(HttpBowQueryParser), new HttpBowQueryParser(httpParser));
services.AddSingleton(typeof(IQueryFormatter), new QueryFormatter());
services.AddSingleton(typeof(IWriter), new StoreWriter(sessionFactory));
services.AddSingleton(typeof(IReader), new StoreReader(sessionFactory, httpParser, httpBowParser));
}
}
} |
2 | package com.wf.captcha;
import org.junit.Test;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
/**
* 测试类
* Created by 王帆 on 2018-07-27 上午 10:08.
*/
public class CaptchaTest {
@Test
public void test() throws Exception {
for (int i = 0; i < 100; i++) {
SpecCaptcha specCaptcha = new SpecCaptcha();
specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
System.out.println(specCaptcha.text());
specCaptcha.out(new FileOutputStream(new File("D:/a/aa" + i + ".png")));
}
}
@Test
public void testGIf() throws Exception {
GifCaptcha gifCaptcha = new GifCaptcha(130, 48, 5);
System.out.println(gifCaptcha.text());
//gifCaptcha.out(new FileOutputStream(new File("D:/a/aa.gif")));
}
}
|
2 | package org.jsoup;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
/**
* Internal static utilities for handling data.
*
*/
class DataUtil {
/**
* Loads a file to a String.
* @param in
* @param charsetName
* @return
* @throws IOException
*/
static String load(File in, String charsetName) throws IOException {
char[] buffer = new char[0x20000]; // ~ 130K
StringBuilder data = new StringBuilder(0x20000);
InputStream inStream = new FileInputStream(in);
Reader inReader = new InputStreamReader(inStream, charsetName);
int read;
do {
read = inReader.read(buffer, 0, buffer.length);
if (read > 0) {
data.append(buffer, 0, read);
}
} while (read >= 0);
return data.toString();
}
}
|
10 | using System.Data;
using System.Threading;
using Dapper;
using Microsoft.EntityFrameworkCore;
namespace DotNetCore.CAP.SqlServer.Test
{
public abstract class DatabaseTestHost : TestHost
{
private static bool _sqlObjectInstalled;
protected override void PostBuildServices()
{
base.PostBuildServices();
InitializeDatabase();
}
public override void Dispose()
{
DeleteAllData();
base.Dispose();
}
private void InitializeDatabase()
{
if (!_sqlObjectInstalled)
{
using (CreateScope())
{
var storage = GetService<SqlServerStorage>();
var token = new CancellationTokenSource().Token;
storage.InitializeAsync(token).Wait();
_sqlObjectInstalled = true;
}
}
}
private void DeleteAllData()
{
using (CreateScope())
{
var context = GetService<TestDbContext>();
var commands = new[]
{
"DISABLE TRIGGER ALL ON ?",
"ALTER TABLE ? NOCHECK CONSTRAINT ALL",
"DELETE FROM ?",
"ALTER TABLE ? CHECK CONSTRAINT ALL",
"ENABLE TRIGGER ALL ON ?"
};
foreach (var command in commands)
{
context.Database.GetDbConnection().Execute(
"sp_MSforeachtable",
new { command1 = command },
commandType: CommandType.StoredProcedure);
}
}
}
}
} |
7 | using Business.Constants;
using Castle.DynamicProxy;
using Core.Extensions;
using Core.Utilities.Interceptors;
using Core.Utilities.IoC;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Security;
using Core.CrossCuttingConcerns.Caching;
namespace Business.BusinessAspects
{
/// <summary>
///This Aspect control the user's roles in HttpContext by inject the IHttpContextAccessor.
///It is checked by writing as [SecuredOperation] on the handler.
///If a valid authorization cannot be found in aspect, it throws an exception.
/// </summary>
public class SecuredOperation : MethodInterception
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ICacheManager _cacheManager;
public SecuredOperation()
{
_httpContextAccessor = ServiceTool.ServiceProvider.GetService<IHttpContextAccessor>();
_cacheManager = ServiceTool.ServiceProvider.GetService<ICacheManager>();
}
protected override void OnBefore(IInvocation invocation)
{
var roleClaims = _httpContextAccessor.HttpContext.User.ClaimRoles();
var operationName = invocation.TargetType.ReflectedType.Name;
if (roleClaims.Contains(operationName))
return;
throw new SecurityException(Messages.AuthorizationsDenied);
}
}
}
|
4 | package org.verdictdb.core.execution.ola;
import static org.junit.Assert.*;
import org.junit.Test;
import org.verdictdb.core.execution.AggExecutionNode;
import org.verdictdb.core.execution.QueryExecutionNode;
import org.verdictdb.core.query.BaseTable;
import org.verdictdb.core.query.ColumnOp;
import org.verdictdb.core.query.SelectQuery;
import org.verdictdb.core.rewriter.ScrambleMeta;
import org.verdictdb.core.scramble.Scrambler;
import org.verdictdb.exception.VerdictDBValueException;
public class AggExecutionNodeBlockTest {
ScrambleMeta generateTestScrambleMeta() {
int aggblockCount = 2;
ScrambleMeta meta = new ScrambleMeta();
meta.insertScrambleMetaEntry("myschema", "mytable",
Scrambler.getAggregationBlockColumn(),
Scrambler.getSubsampleColumn(),
Scrambler.getTierColumn(),
aggblockCount);
return meta;
}
@Test
public void testConvertFlatToProgressiveAgg() throws VerdictDBValueException {
SelectQuery aggQuery = SelectQuery.create(
ColumnOp.count(),
new BaseTable("myschema", "mytable", "t"));
AggExecutionNode aggnode = AggExecutionNode.create(aggQuery, "myschema");
AggExecutionNodeBlock block = new AggExecutionNodeBlock(aggnode);
ScrambleMeta scrambleMeta = generateTestScrambleMeta();
QueryExecutionNode converted = block.convertToProgressiveAgg(scrambleMeta);
converted.print();
}
}
|
2 | /*
* Copyright (c) 2016-2019 Zerocracy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to read
* the Software only. Permissions is hereby NOT GRANTED to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.zerocracy;
import com.zerocracy.farm.props.PropsFarm;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
/**
* Test case for {@link Policy}.
* @since 1.0
* @checkstyle JavadocMethodCheck (500 lines)
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
*/
public final class PolicyTest {
@Test
public void findsBasicNumbers() throws Exception {
MatcherAssert.assertThat(
new Policy(new PropsFarm(new FkFarm())).get("1.min-rep", "???"),
Matchers.startsWith("??")
);
}
}
|