hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e048ae7ea20112fa8675ea722660f2471f3e0ea
789
java
Java
src/Akcija.java
wolwemaan/draw
83bb12faf38a989be172bf5a428393c5c8589219
[ "MIT" ]
null
null
null
src/Akcija.java
wolwemaan/draw
83bb12faf38a989be172bf5a428393c5c8589219
[ "MIT" ]
null
null
null
src/Akcija.java
wolwemaan/draw
83bb12faf38a989be172bf5a428393c5c8589219
[ "MIT" ]
null
null
null
17.931818
52
0.584284
1,913
import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class Akcija { static int maxGroup = 3; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = Integer.valueOf(sc.nextLine()).intValue(); System.out.println("n=" + n); int ctr = -1; Integer[] arr = new Integer[n]; while (++ctr < n) { arr[ctr] = Integer.valueOf(sc.nextLine()); //System.out.println(arr[ctr]); } sc.close(); Arrays.sort(arr, Collections.reverseOrder()); int tot = 0; int group[] = new int[maxGroup]; int j = -1; for (int i = 0; i < n; i++) { if (++j < maxGroup) group[j] = arr[i]; else { // int calc = calcGroup(group); j = -1; } } System.out.println("PASS" + "FAIL"); } }
3e048b12ed32fa2b15987841985a3fe3c71b2da4
275
java
Java
src/main/java/com/eduardoreis/pontointeligente/api/services/EmpresaService.java
eduardore1s/ponto-inteligente-api
42af1a0be9244e1bfc102a1aadd476187dda5f8c
[ "MIT" ]
null
null
null
src/main/java/com/eduardoreis/pontointeligente/api/services/EmpresaService.java
eduardore1s/ponto-inteligente-api
42af1a0be9244e1bfc102a1aadd476187dda5f8c
[ "MIT" ]
null
null
null
src/main/java/com/eduardoreis/pontointeligente/api/services/EmpresaService.java
eduardore1s/ponto-inteligente-api
42af1a0be9244e1bfc102a1aadd476187dda5f8c
[ "MIT" ]
null
null
null
21.153846
61
0.803636
1,914
package com.eduardoreis.pontointeligente.api.services; import com.eduardoreis.pontointeligente.api.entities.Empresa; import java.util.Optional; public interface EmpresaService { Optional<Empresa> buscarPorCnpj(String cnpj); Empresa persistir(Empresa empresa); }
3e048c2ef737f87618baacf63e1f26cbba93d37a
2,438
java
Java
dropwizard-json-logging/src/test/java/io/dropwizard/logging/json/layout/JsonFormatterTest.java
contextshuffling/dropwizard
a3a2896bee16d93c9ae23df9b64f2e468703f9b5
[ "Apache-2.0" ]
null
null
null
dropwizard-json-logging/src/test/java/io/dropwizard/logging/json/layout/JsonFormatterTest.java
contextshuffling/dropwizard
a3a2896bee16d93c9ae23df9b64f2e468703f9b5
[ "Apache-2.0" ]
null
null
null
dropwizard-json-logging/src/test/java/io/dropwizard/logging/json/layout/JsonFormatterTest.java
contextshuffling/dropwizard
a3a2896bee16d93c9ae23df9b64f2e468703f9b5
[ "Apache-2.0" ]
null
null
null
39.322581
130
0.657096
1,915
package io.dropwizard.logging.json.layout; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.dropwizard.jackson.Jackson; import io.dropwizard.util.Maps; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Arrays; import java.util.Map; import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; import static org.assertj.core.api.Assertions.assertThat; public class JsonFormatterTest { private final Map<String, Object> map = Maps.of( "name", "Jim", "hobbies", Arrays.asList("Reading", "Biking", "Snorkeling")); private final ObjectMapper objectMapper = Jackson.newObjectMapper(); @Test public void testNoPrettyPrintNoLineSeparator() throws IOException { JsonFormatter formatter = new JsonFormatter(objectMapper, false, false); final JsonNode actual = objectMapper.readTree(formatter.toJson(map)); final JsonNode expected = objectMapper.readTree("{\"name\":\"Jim\",\"hobbies\":[\"Reading\",\"Biking\",\"Snorkeling\"]}"); assertThat(actual).isEqualTo(expected); } @Test public void testNoPrettyPrintWithLineSeparator() throws IOException { JsonFormatter formatter = new JsonFormatter(objectMapper, false, true); final String content = formatter.toJson(map); assertThat(content).endsWith(System.lineSeparator()); final JsonNode actual = objectMapper.readTree(content); final JsonNode expected = objectMapper.readTree("{\"name\":\"Jim\",\"hobbies\":[\"Reading\",\"Biking\",\"Snorkeling\"]}"); assertThat(actual).isEqualTo(expected); } @Test public void testPrettyPrintWithLineSeparator() { JsonFormatter formatter = new JsonFormatter(objectMapper, true, true); assertThatJson(formatter.toJson(map)).isEqualTo(String.format("{%n" + " \"hobbies\" : [ \"Reading\", \"Biking\", \"Snorkeling\" ],%n" + " \"name\" : \"Jim\"%n" + "}%n")); } @Test public void testPrettyPrintNoLineSeparator() { JsonFormatter formatter = new JsonFormatter(objectMapper, true, false); assertThatJson(formatter.toJson(map)).isEqualTo(String.format("{%n" + " \"hobbies\" : [ \"Reading\", \"Biking\", \"Snorkeling\" ],%n" + " \"name\" : \"Jim\"%n" + "}")); } }
3e048c2f8cbc7a2cc4889b5b57af98db4e549d0f
662
java
Java
src/main/java/org/stellar/sdk/responses/effects/TrustlineDeauthorizedEffectResponse.java
ardevd/java-stellar-sdk
36c862de9e310fa5f22f909dad8da5ed11e04b9b
[ "Apache-2.0" ]
null
null
null
src/main/java/org/stellar/sdk/responses/effects/TrustlineDeauthorizedEffectResponse.java
ardevd/java-stellar-sdk
36c862de9e310fa5f22f909dad8da5ed11e04b9b
[ "Apache-2.0" ]
null
null
null
src/main/java/org/stellar/sdk/responses/effects/TrustlineDeauthorizedEffectResponse.java
ardevd/java-stellar-sdk
36c862de9e310fa5f22f909dad8da5ed11e04b9b
[ "Apache-2.0" ]
null
null
null
41.375
133
0.791541
1,916
package org.stellar.sdk.responses.effects; /** * @deprecated As of release 0.24.0, replaced by {@link TrustlineFlagsUpdatedEffectResponse} * * Represents trustline_deauthorized effect response. * @see <a href="https://www.stellar.org/developers/horizon/reference/resources/effect.html" target="_blank">Effect documentation</a> * @see org.stellar.sdk.requests.EffectsRequestBuilder * @see org.stellar.sdk.Server#effects() */ public class TrustlineDeauthorizedEffectResponse extends TrustlineAuthorizationResponse { TrustlineDeauthorizedEffectResponse(String trustor, String assetType, String assetCode) { super(trustor, assetType, assetCode); } }
3e048cb7423f3685ac75ac50fe180a802f554e5a
4,773
java
Java
app/src/main/java/br/com/mobiclub/quantoprima/ui/adapter/notification/NotifyLocationListAdapter.java
LuisMesquita/android-quantoprima
a6e6227696952999c08831b562ba1efc13da4143
[ "Apache-2.0" ]
null
null
null
app/src/main/java/br/com/mobiclub/quantoprima/ui/adapter/notification/NotifyLocationListAdapter.java
LuisMesquita/android-quantoprima
a6e6227696952999c08831b562ba1efc13da4143
[ "Apache-2.0" ]
null
null
null
app/src/main/java/br/com/mobiclub/quantoprima/ui/adapter/notification/NotifyLocationListAdapter.java
LuisMesquita/android-quantoprima
a6e6227696952999c08831b562ba1efc13da4143
[ "Apache-2.0" ]
null
null
null
37.582677
97
0.651791
1,917
package br.com.mobiclub.quantoprima.ui.adapter.notification; import android.content.res.Resources; import android.os.Build; import android.view.LayoutInflater; import android.widget.CompoundButton; import android.widget.ImageView; import com.github.kevinsawicki.wishlist.SingleTypeAdapter; import java.util.List; import br.com.mobiclub.quantoprima.R; import br.com.mobiclub.quantoprima.core.service.api.entity.Establishment; import br.com.mobiclub.quantoprima.core.service.api.entity.EstablishmentLocation; import br.com.mobiclub.quantoprima.core.service.api.entity.Image; import br.com.mobiclub.quantoprima.ui.view.ImageLoader; import br.com.mobiclub.quantoprima.util.Ln; /** * */ public class NotifyLocationListAdapter extends SingleTypeAdapter<EstablishmentLocation> { private final NotifyLocationListAdapterListener listener; private Resources resources; private EstablishmentLocation lastLocation; public NotifyLocationListAdapter(NotifyLocationListAdapterListener listener, LayoutInflater layoutInflater, Resources resources, List<EstablishmentLocation> items) { super(layoutInflater, R.layout.list_item_notify_location); this.resources = resources; this.listener = listener; setItems(items); } @Override public long getItemId(final int position) { final int id = getItem(position).getId(); return id != 0 ? id : super.getItemId(position); } @Override protected int[] getChildViewIds() { return new int[] { R.id.image_logo, R.id.label_location_name, R.id.label_location_reference, R.id.btn_switch }; } private void loadImage(Image image, ImageView imageItem) { ImageLoader.getInstance().loadImage(imageItem, image, ImageLoader.Placeholder.NOTIFY_LOCATION); } @Override protected void update(final int position, final EstablishmentLocation location) { Establishment establishment = location.getEstablishment(); if(establishment == null) { Ln.e("establishment == null"); return; } loadImage(new Image(establishment.getLogoUrl()), imageView(0)); if(establishment.isGroup()) { showItem(true); //TODO: mostrar item com estilo apropriado showLocation(establishment, location, position); } else if(!establishment.getLocations().isEmpty()) { showLocation(establishment, location, position); } else { //estabelecimento sem locations showItem(true); setText(1, String.format("%s", establishment.getName())); setText(2, String.format("%s", resources.getString(R.string.unknown))); } } private void showLocation(Establishment establishment, EstablishmentLocation location, int position) { showItem(false); String name = establishment.getName(); if(name != null) setText(1, String.format("%s", name)); String reference = location.getReference(); if(reference != null) setText(2, String.format("%s", reference)); if(location.getBlocked() != null) { int currentapiVersion = android.os.Build.VERSION.SDK_INT; CompoundButton btnSwitchLocation; if (currentapiVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { btnSwitchLocation = getView(3, CompoundButton.class); } else { btnSwitchLocation = getView(4, CompoundButton.class); //((ToggleButton)btnSwitchLocation).setButtonDrawable(R.drawable.bg_btn_switch); } btnSwitchLocation.setOnCheckedChangeListener(null); if (location.getBlocked()) { btnSwitchLocation.setChecked(false); } else { btnSwitchLocation.setChecked(true); } setListener(btnSwitchLocation, position); } } private void setListener(final CompoundButton btnSwitchToggle, int position) { btnSwitchToggle.setTag(position); btnSwitchToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int position = (int) btnSwitchToggle.getTag(); EstablishmentLocation location = getItem(position); NotifyLocationListAdapter.this.lastLocation = location; listener.onSwitched(location, isChecked); } }); } private void showItem(boolean locations) { } }
3e048d6152be91c383de6684ca886e4542656fb2
462
java
Java
modules/core/src/main/java/io/smsc/config/Oracle10gDialectExtended.java
bulktrade/smsc
33dfffc2f840ba3aa98343f9ac6f6b2fc7a7e4b6
[ "Apache-2.0" ]
58
2016-01-16T04:09:49.000Z
2022-03-16T05:27:24.000Z
modules/core/src/main/java/io/smsc/config/Oracle10gDialectExtended.java
bulktrade/smsc
33dfffc2f840ba3aa98343f9ac6f6b2fc7a7e4b6
[ "Apache-2.0" ]
61
2016-11-01T10:42:06.000Z
2021-08-19T07:49:49.000Z
modules/core/src/main/java/io/smsc/config/Oracle10gDialectExtended.java
bulktrade/smsc
33dfffc2f840ba3aa98343f9ac6f6b2fc7a7e4b6
[ "Apache-2.0" ]
29
2016-02-19T21:52:20.000Z
2022-02-01T18:06:40.000Z
22
65
0.720779
1,918
package io.smsc.config; import org.hibernate.dialect.Oracle10gDialect; import java.sql.Types; /** * This class is extending base {@link Oracle10gDialect} class to * register a double data type as float column type. * * @author Nazar Lipkovskyy * @since 0.0.1-SNAPSHOT */ public class Oracle10gDialectExtended extends Oracle10gDialect { public Oracle10gDialectExtended() { super(); registerColumnType(Types.DOUBLE, "float"); } }
3e048d687c37d5406f45d910c39567efe9375f6d
606
java
Java
src/main/java/brv/notifier/packt/restclients/ProductsRestClient.java
Flashky/notifier-packt
7de9d64a57e6521b20f134962f606e2b6ad18077
[ "Apache-2.0" ]
1
2019-06-04T21:12:14.000Z
2019-06-04T21:12:14.000Z
src/main/java/brv/notifier/packt/restclients/ProductsRestClient.java
Flashky/notifier-packt
7de9d64a57e6521b20f134962f606e2b6ad18077
[ "Apache-2.0" ]
84
2018-12-09T18:41:08.000Z
2020-02-09T17:14:28.000Z
src/main/java/brv/notifier/packt/restclients/ProductsRestClient.java
Flashky/notifier-packt
7de9d64a57e6521b20f134962f606e2b6ad18077
[ "Apache-2.0" ]
1
2018-12-24T11:58:38.000Z
2018-12-24T11:58:38.000Z
33.666667
73
0.775578
1,919
package brv.notifier.packt.restclients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import brv.notifier.packt.restclients.model.JsonSummary; @FeignClient(name = "${api.products.name}", url = "${api.products.url}") public interface ProductsRestClient { @GetMapping("/{productId}/summary") JsonSummary getProductSummary(@PathVariable Long productId); @GetMapping("/{productId}/cover/smaller") byte[] getProductImage(@PathVariable Long productId); }
3e048e885e6b3cc00b566faea06d2849c1a34441
2,308
java
Java
qe/serde/src/java/org/apache/hadoop/hive/serde2/dynamic_type/DynamicSerDeStructBase.java
tonycody/tencent-tdw
92357724319bbc24f3f0d5563d68d299d237a17f
[ "Apache-1.1" ]
3
2019-11-08T12:47:19.000Z
2021-06-10T19:46:01.000Z
qe/serde/src/java/org/apache/hadoop/hive/serde2/dynamic_type/DynamicSerDeStructBase.java
tonycody/tencent-tdw
92357724319bbc24f3f0d5563d68d299d237a17f
[ "Apache-1.1" ]
null
null
null
qe/serde/src/java/org/apache/hadoop/hive/serde2/dynamic_type/DynamicSerDeStructBase.java
tonycody/tencent-tdw
92357724319bbc24f3f0d5563d68d299d237a17f
[ "Apache-1.1" ]
8
2020-03-12T13:42:59.000Z
2021-05-27T06:34:33.000Z
26.837209
75
0.724003
1,920
/** * 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.hadoop.hive.serde2.dynamic_type; import org.apache.thrift.TException; import org.apache.thrift.protocol.*; import java.io.*; import java.util.List; import org.apache.hadoop.hive.serde2.*; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; abstract public class DynamicSerDeStructBase extends DynamicSerDeTypeBase implements Serializable { DynamicSerDeFieldList fieldList; public DynamicSerDeStructBase(int i) { super(i); } public DynamicSerDeStructBase(thrift_grammar p, int i) { super(p, i); } abstract public DynamicSerDeFieldList getFieldList(); public void initialize() { fieldList = getFieldList(); fieldList.initialize(); } public boolean isPrimitive() { return false; } public Class getRealType() { return List.class; } public Object deserialize(Object reuse, TProtocol iprot) throws SerDeException, TException, IllegalAccessException { if (thrift_mode) { iprot.readStructBegin(); } Object o = fieldList.deserialize(reuse, iprot); if (thrift_mode) { iprot.readStructEnd(); } return o; } public void serialize(Object o, ObjectInspector oi, TProtocol oprot) throws TException, SerDeException, NoSuchFieldException, IllegalAccessException { if (thrift_mode) { oprot.writeStructBegin(new TStruct(this.name)); } fieldList.serialize(o, oi, oprot); if (thrift_mode) { oprot.writeStructEnd(); } } }
3e048f324b0b8ce652fb306b24d1813a75e5b3f7
1,026
java
Java
_src/Chapter06/MyFirstBukkitPlugin 0.2/MyFirstBukkitPlugin.java
paullewallencom/minecraft-978-1-7858-8302-6
6f9527974127769a53b9318385c10507db0f7545
[ "Apache-2.0" ]
null
null
null
_src/Chapter06/MyFirstBukkitPlugin 0.2/MyFirstBukkitPlugin.java
paullewallencom/minecraft-978-1-7858-8302-6
6f9527974127769a53b9318385c10507db0f7545
[ "Apache-2.0" ]
null
null
null
_src/Chapter06/MyFirstBukkitPlugin 0.2/MyFirstBukkitPlugin.java
paullewallencom/minecraft-978-1-7858-8302-6
6f9527974127769a53b9318385c10507db0f7545
[ "Apache-2.0" ]
null
null
null
29.314286
76
0.580897
1,921
package com.codisimus.myfirstbukkitplugin; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; /** * Broadcasts a hello message to the server */ public class MyFirstBukkitPlugin extends JavaPlugin { @Override public void onEnable() { if (Bukkit.getOnlinePlayers().size() >= 1) { for (Player player : Bukkit.getOnlinePlayers()) { //Only say 'Hello' to each player that has permission if (player.hasPermission("myfirstbukkitplugin.greeting")) { player.sendMessage("Hello " + player.getName()); } } } else { //Say 'Hello' to the Minecraft World broadcastToServer("Hello World!"); } } /** * Sends a message to everyone on the server * * @param msg the message to send */ private void broadcastToServer(String msg) { Bukkit.broadcastMessage(msg); } }
3e0490d07b70dd83037d68c5d97374c85659dde4
1,565
java
Java
src/main/java/com/example/demo/annotation/ReadTransactional.java
SimonHarmonicMinor/spring-boot-readonly-transactions
5e4d0d317688810a437bad438468500f442cb3ba
[ "MIT" ]
1
2022-01-05T17:34:31.000Z
2022-01-05T17:34:31.000Z
src/main/java/com/example/demo/annotation/ReadTransactional.java
SimonHarmonicMinor/spring-boot-readonly-transactions
5e4d0d317688810a437bad438468500f442cb3ba
[ "MIT" ]
null
null
null
src/main/java/com/example/demo/annotation/ReadTransactional.java
SimonHarmonicMinor/spring-boot-readonly-transactions
5e4d0d317688810a437bad438468500f442cb3ba
[ "MIT" ]
null
null
null
38.170732
79
0.800639
1,922
package com.example.demo.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Transactional(readOnly = true, noRollbackFor = Exception.class) @Documented public @interface ReadTransactional { @AliasFor(annotation = Transactional.class, attribute = "value") String value() default ""; @AliasFor(annotation = Transactional.class, attribute = "transactionManager") String transactionManager() default ""; @AliasFor(annotation = Transactional.class, attribute = "label") String[] label() default {}; @AliasFor(annotation = Transactional.class, attribute = "propagation") Propagation propagation() default Propagation.REQUIRED; @AliasFor(annotation = Transactional.class, attribute = "isolation") Isolation isolation() default Isolation.DEFAULT; @AliasFor(annotation = Transactional.class, attribute = "timeout") int timeout() default TransactionDefinition.TIMEOUT_DEFAULT; @AliasFor(annotation = Transactional.class, attribute = "timeoutString") String timeoutString() default ""; }
3e04911d890cd53a49b1e6753d2b13cd58b6e354
360
java
Java
src/test/examples/multidex005/CheckCastReference.java
ganadist/r8
850b5a4725954b677103a3a575239d0f330c0b0f
[ "Apache-2.0", "BSD-3-Clause" ]
8
2019-02-16T19:27:05.000Z
2020-10-30T20:10:42.000Z
src/test/examples/multidex005/CheckCastReference.java
ganadist/r8
850b5a4725954b677103a3a575239d0f330c0b0f
[ "Apache-2.0", "BSD-3-Clause" ]
3
2020-01-27T22:30:05.000Z
2020-07-31T20:58:15.000Z
src/test/examples/multidex005/CheckCastReference.java
ganadist/r8
850b5a4725954b677103a3a575239d0f330c0b0f
[ "Apache-2.0", "BSD-3-Clause" ]
5
2019-03-03T04:49:03.000Z
2021-11-23T15:47:38.000Z
27.692308
77
0.75
1,923
// Copyright (c) 2019, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package multidex005; public class CheckCastReference { public Object directReference(Object obj) { return (DirectlyReferenced) obj; } }
3e04923c928875d894c32857d118b28885fe496c
15,527
java
Java
litho-it/src/test/java/com/facebook/litho/ComponentTreeTest.java
abhirocks1211/litho
c9c36d588ae9af8f5356969c7a908e1584216d61
[ "BSD-3-Clause" ]
4
2020-04-21T10:24:00.000Z
2020-04-21T11:22:30.000Z
litho-it/src/test/java/com/facebook/litho/ComponentTreeTest.java
abhirocks1211/litho
c9c36d588ae9af8f5356969c7a908e1584216d61
[ "BSD-3-Clause" ]
null
null
null
litho-it/src/test/java/com/facebook/litho/ComponentTreeTest.java
abhirocks1211/litho
c9c36d588ae9af8f5356969c7a908e1584216d61
[ "BSD-3-Clause" ]
1
2021-11-10T10:01:33.000Z
2021-11-10T10:01:33.000Z
32.619748
98
0.719521
1,924
/* * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.litho; import static com.facebook.litho.ComponentTree.create; import static com.facebook.litho.SizeSpec.AT_MOST; import static com.facebook.litho.SizeSpec.EXACTLY; import static com.facebook.litho.SizeSpec.makeSizeSpec; import static junit.framework.Assert.assertEquals; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.fail; import static org.powermock.reflect.Whitebox.getInternalState; import android.os.Looper; import com.facebook.litho.testing.TestDrawableComponent; import com.facebook.litho.testing.TestLayoutComponent; import com.facebook.litho.testing.testrunner.ComponentsTestRunner; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.reflect.Whitebox; import org.robolectric.RuntimeEnvironment; import org.robolectric.Shadows; import org.robolectric.shadows.ShadowLooper; @RunWith(ComponentsTestRunner.class) public class ComponentTreeTest { private int mWidthSpec; private int mWidthSpec2; private int mHeightSpec; private int mHeightSpec2; private Component mComponent; private ShadowLooper mLayoutThreadShadowLooper; private ComponentContext mContext; @Before public void setup() throws Exception { mContext = new ComponentContext(RuntimeEnvironment.application); mComponent = TestDrawableComponent.create(mContext) .build(); mLayoutThreadShadowLooper = Shadows.shadowOf( (Looper) Whitebox.invokeMethod( ComponentTree.class, "getDefaultLayoutThreadLooper")); mWidthSpec = makeSizeSpec(39, EXACTLY); mWidthSpec2 = makeSizeSpec(40, EXACTLY); mHeightSpec = makeSizeSpec(41, EXACTLY); mHeightSpec2 = makeSizeSpec(42, EXACTLY); } private void creationCommonChecks(ComponentTree componentTree) { // Not view or attached yet Assert.assertNull(getLithoView(componentTree)); Assert.assertFalse(isAttached(componentTree)); // No measure spec from view yet. Assert.assertFalse( (Boolean) Whitebox.getInternalState(componentTree, "mHasViewMeasureSpec")); // The component input should be the one we passed in Assert.assertSame( mComponent, Whitebox.getInternalState(componentTree, "mRoot")); } private void postSizeSpecChecks( ComponentTree componentTree, String layoutStateVariableName) { postSizeSpecChecks( componentTree, layoutStateVariableName, mWidthSpec, mHeightSpec); } private void postSizeSpecChecks( ComponentTree componentTree, String layoutStateVariableName, int widthSpec, int heightSpec) { // Spec specified in create assertThat(componentTreeHasSizeSpec(componentTree)).isTrue(); assertThat((int) getInternalState(componentTree, "mWidthSpec")) .isEqualTo(widthSpec); assertThat((int) getInternalState(componentTree, "mHeightSpec")) .isEqualTo(heightSpec); LayoutState mainThreadLayoutState = getInternalState( componentTree, "mMainThreadLayoutState"); LayoutState backgroundLayoutState = getInternalState( componentTree, "mBackgroundLayoutState"); LayoutState layoutState = null; LayoutState nullLayoutState = null; if ("mMainThreadLayoutState".equals(layoutStateVariableName)) { layoutState = mainThreadLayoutState; nullLayoutState = backgroundLayoutState; } else if ("mBackgroundLayoutState".equals(layoutStateVariableName)) { layoutState = backgroundLayoutState; nullLayoutState = mainThreadLayoutState; } else { fail("Incorrect variable name: " + layoutStateVariableName); } Assert.assertNull(nullLayoutState); assertThat(layoutState.isCompatibleComponentAndSpec( mComponent.getId(), widthSpec, heightSpec)).isTrue(); } @Test public void testCreate() { ComponentTree componentTree = ComponentTree.create(mContext, mComponent) .incrementalMount(false) .layoutDiffing(false) .build(); creationCommonChecks(componentTree); // Both the main thread and the background layout state shouldn't be calculated yet. Assert.assertNull(Whitebox.getInternalState(componentTree, "mMainThreadLayoutState")); Assert.assertNull(Whitebox.getInternalState(componentTree, "mBackgroundLayoutState")); Assert.assertFalse(componentTreeHasSizeSpec(componentTree)); } @Test public void testSetSizeSpec() { ComponentTree componentTree = ComponentTree.create(mContext, mComponent) .incrementalMount(false) .layoutDiffing(false) .build(); componentTree.setSizeSpec(mWidthSpec, mHeightSpec); // Since this happens post creation, it's not in general safe to update the main thread layout // state synchronously, so the result should be in the background layout state postSizeSpecChecks(componentTree, "mBackgroundLayoutState"); } @Test public void testSetSizeSpecAsync() { ComponentTree componentTree = create(mContext, mComponent) .incrementalMount(false) .layoutDiffing(false) .build(); componentTree.setSizeSpecAsync(mWidthSpec, mHeightSpec); // Only fields changed but no layout is done yet. assertThat(componentTreeHasSizeSpec(componentTree)).isTrue(); assertThat((int) getInternalState(componentTree, "mWidthSpec")) .isEqualTo(mWidthSpec); assertThat((int) getInternalState(componentTree, "mHeightSpec")) .isEqualTo(mHeightSpec); Assert.assertNull(getInternalState(componentTree, "mMainThreadLayoutState")); Assert.assertNull(getInternalState(componentTree, "mBackgroundLayoutState")); // Now the background thread run the queued task. mLayoutThreadShadowLooper.runOneTask(); // Since this happens post creation, it's not in general safe to update the main thread layout // state synchronously, so the result should be in the background layout state postSizeSpecChecks(componentTree, "mBackgroundLayoutState"); } @Test public void testSetSizeSpecAsyncThenSyncBeforeRunningTask() { ComponentTree componentTree = ComponentTree.create(mContext, mComponent) .incrementalMount(false) .layoutDiffing(false) .build(); componentTree.setSizeSpecAsync(mWidthSpec, mHeightSpec); componentTree.setSizeSpec(mWidthSpec2, mHeightSpec2); mLayoutThreadShadowLooper.runToEndOfTasks(); // Since this happens post creation, it's not in general safe to update the main thread layout // state synchronously, so the result should be in the background layout state postSizeSpecChecks( componentTree, "mBackgroundLayoutState", mWidthSpec2, mHeightSpec2); } @Test public void testSetSizeSpecAsyncThenSyncAfterRunningTask() { ComponentTree componentTree = ComponentTree.create(mContext, mComponent) .incrementalMount(false) .layoutDiffing(false) .build(); componentTree.setSizeSpecAsync(mWidthSpec, mHeightSpec); mLayoutThreadShadowLooper.runToEndOfTasks(); componentTree.setSizeSpec(mWidthSpec2, mHeightSpec2); // Since this happens post creation, it's not in general safe to update the main thread layout // state synchronously, so the result should be in the background layout state postSizeSpecChecks( componentTree, "mBackgroundLayoutState", mWidthSpec2, mHeightSpec2); } @Test public void testSetSizeSpecWithOutput() { ComponentTree componentTree = ComponentTree.create(mContext, mComponent) .incrementalMount(false) .layoutDiffing(false) .build(); Size size = new Size(); componentTree.setSizeSpec(mWidthSpec, mHeightSpec, size); assertEquals(SizeSpec.getSize(mWidthSpec), size.width, 0.0); assertEquals(SizeSpec.getSize(mHeightSpec), size.height, 0.0); // Since this happens post creation, it's not in general safe to update the main thread layout // state synchronously, so the result should be in the background layout state postSizeSpecChecks(componentTree, "mBackgroundLayoutState"); } @Test public void testSetCompatibleSizeSpec() { ComponentTree componentTree = create(mContext, mComponent) .incrementalMount(false) .layoutDiffing(false) .build(); Size size = new Size(); componentTree.setSizeSpec( makeSizeSpec(100, AT_MOST), makeSizeSpec(100, AT_MOST), size); assertEquals(100, size.width, 0.0); assertEquals(100, size.height, 0.0); LayoutState firstLayoutState = componentTree.getBackgroundLayoutState(); assertThat(firstLayoutState).isNotNull(); componentTree.setSizeSpec( makeSizeSpec(100, EXACTLY), makeSizeSpec(100, EXACTLY), size); assertEquals(100, size.width, 0.0); assertEquals(100, size.height, 0.0); assertThat(componentTree.getBackgroundLayoutState()).isEqualTo(firstLayoutState); } @Test public void testSetCompatibleSizeSpecWithDifferentRoot() { ComponentTree componentTree = create(mContext, mComponent) .incrementalMount(false) .layoutDiffing(false) .build(); Size size = new Size(); componentTree.setSizeSpec( makeSizeSpec(100, AT_MOST), makeSizeSpec(100, AT_MOST), size); assertEquals(100, size.width, 0.0); assertEquals(100, size.height, 0.0); LayoutState firstLayoutState = componentTree.getBackgroundLayoutState(); assertThat(firstLayoutState).isNotNull(); componentTree.setRootAndSizeSpec( TestDrawableComponent.create(mContext).build(), makeSizeSpec(100, EXACTLY), makeSizeSpec(100, EXACTLY), size); assertNotEquals(firstLayoutState, componentTree.getBackgroundLayoutState()); } @Test public void testSetInput() { Component component = TestLayoutComponent.create(mContext) .build(); ComponentTree componentTree = ComponentTree.create(mContext, component) .incrementalMount(false) .layoutDiffing(false) .build(); componentTree.setRoot(mComponent); creationCommonChecks(componentTree); Assert.assertNull(Whitebox.getInternalState(componentTree, "mMainThreadLayoutState")); Assert.assertNull(Whitebox.getInternalState(componentTree, "mBackgroundLayoutState")); componentTree.setSizeSpec(mWidthSpec, mHeightSpec); // Since this happens post creation, it's not in general safe to update the main thread layout // state synchronously, so the result should be in the background layout state postSizeSpecChecks(componentTree, "mBackgroundLayoutState"); } @Test public void testSetComponentFromView() { Component component1 = TestDrawableComponent.create(mContext) .build(); ComponentTree componentTree1 = ComponentTree.create( mContext, component1) .incrementalMount(false) .layoutDiffing(false) .build(); Component component2 = TestDrawableComponent.create(mContext) .build(); ComponentTree componentTree2 = ComponentTree.create( mContext, component2) .incrementalMount(false) .layoutDiffing(false) .build(); Assert.assertNull(getLithoView(componentTree1)); Assert.assertNull(getLithoView(componentTree2)); LithoView lithoView = new LithoView(mContext); lithoView.setComponentTree(componentTree1); Assert.assertNotNull(getLithoView(componentTree1)); Assert.assertNull(getLithoView(componentTree2)); lithoView.setComponentTree(componentTree2); Assert.assertNull(getLithoView(componentTree1)); Assert.assertNotNull(getLithoView(componentTree2)); } @Test public void testComponentTreeReleaseClearsView() { Component component = TestDrawableComponent.create(mContext) .build(); ComponentTree componentTree = create( mContext, component) .incrementalMount(false) .layoutDiffing(false) .build(); LithoView lithoView = new LithoView(mContext); lithoView.setComponentTree(componentTree); assertThat(componentTree).isEqualTo(lithoView.getComponentTree()); componentTree.release(); assertThat(lithoView.getComponentTree()).isNull(); } @Test public void testsetTreeToTwoViewsBothAttached() { Component component = TestDrawableComponent.create(mContext) .build(); ComponentTree componentTree = ComponentTree.create( mContext, component) .incrementalMount(false) .layoutDiffing(false) .build(); // Attach first view. LithoView lithoView1 = new LithoView(mContext); lithoView1.setComponentTree(componentTree); lithoView1.onAttachedToWindow(); // Attach second view. LithoView lithoView2 = new LithoView(mContext); lithoView2.onAttachedToWindow(); // Set the component that is already mounted on the first view, on the second attached view. // This should be ok. lithoView2.setComponentTree(componentTree); } @Test public void testSettingNewViewToTree() { Component component = TestDrawableComponent.create(mContext) .build(); ComponentTree componentTree = create( mContext, component) .incrementalMount(false) .layoutDiffing(false) .build(); // Attach first view. LithoView lithoView1 = new LithoView(mContext); lithoView1.setComponentTree(componentTree); assertThat(getLithoView(componentTree)).isEqualTo(lithoView1); assertThat(getComponentTree(lithoView1)).isEqualTo(componentTree); // Attach second view. LithoView lithoView2 = new LithoView(mContext); Assert.assertNull(getComponentTree(lithoView2)); lithoView2.setComponentTree(componentTree); assertThat(getLithoView(componentTree)).isEqualTo(lithoView2); assertThat(getComponentTree(lithoView2)).isEqualTo(componentTree); Assert.assertNull(getComponentTree(lithoView1)); } private static LithoView getLithoView(ComponentTree componentTree) { return Whitebox.getInternalState(componentTree, "mLithoView"); } private static boolean isAttached(ComponentTree componentTree) { return Whitebox.getInternalState(componentTree, "mIsAttached"); } private static ComponentTree getComponentTree(LithoView lithoView) { return Whitebox.getInternalState(lithoView, "mComponentTree"); } private static boolean componentTreeHasSizeSpec(ComponentTree componentTree) { try { boolean hasCssSpec; // Need to hold the lock on componentTree here otherwise the invocation of hasCssSpec // will fail. synchronized (componentTree) { hasCssSpec = Whitebox.invokeMethod(componentTree, ComponentTree.class, "hasSizeSpec"); } return hasCssSpec; } catch (Exception e) { throw new IllegalArgumentException("Failed to invoke hasSizeSpec on ComponentTree for: "+e); } } }
3e0492f67c20711bf439549d865f9dbf3e33edf4
5,573
java
Java
viewpagerlayoutmanager/src/main/java/com/leochuan/CarouselLayoutManager.java
angcyo/ViewPagerLayoutManager
ad2ed43af134062db89f082c77c3b04d61241ef3
[ "Apache-2.0" ]
5
2020-03-17T13:14:49.000Z
2021-04-08T15:13:38.000Z
viewpagerlayoutmanager/src/main/java/com/leochuan/CarouselLayoutManager.java
angcyo/ViewPagerLayoutManager
ad2ed43af134062db89f082c77c3b04d61241ef3
[ "Apache-2.0" ]
null
null
null
viewpagerlayoutmanager/src/main/java/com/leochuan/CarouselLayoutManager.java
angcyo/ViewPagerLayoutManager
ad2ed43af134062db89f082c77c3b04d61241ef3
[ "Apache-2.0" ]
null
null
null
30.453552
106
0.637897
1,925
package com.leochuan; import android.content.Context; import android.util.AttributeSet; import android.view.View; /** * An implementation of {@link ViewPagerLayoutManager} * which layouts items like carousel */ @SuppressWarnings({"WeakerAccess", "unused"}) public class CarouselLayoutManager extends ViewPagerLayoutManager { private int itemSpace; private float minScale; private float moveSpeed; public CarouselLayoutManager(Context context, int itemSpace) { this(new Builder(context, itemSpace)); } public CarouselLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { this(context, 0); } public CarouselLayoutManager(Context context, int itemSpace, int orientation) { this(new Builder(context, itemSpace).setOrientation(orientation)); } public CarouselLayoutManager(Context context, int itemSpace, int orientation, boolean reverseLayout) { this(new Builder(context, itemSpace).setOrientation(orientation).setReverseLayout(reverseLayout)); } public CarouselLayoutManager(Builder builder) { this(builder.context, builder.itemSpace, builder.minScale, builder.orientation, builder.maxVisibleItemCount, builder.moveSpeed, builder.distanceToBottom, builder.reverseLayout); } private CarouselLayoutManager(Context context, int itemSpace, float minScale, int orientation, int maxVisibleItemCount, float moveSpeed, int distanceToBottom, boolean reverseLayout) { super(context, orientation, reverseLayout); setEnableBringCenterToFront(true); setDistanceToBottom(distanceToBottom); setMaxVisibleItemCount(maxVisibleItemCount); this.itemSpace = itemSpace; this.minScale = minScale; this.moveSpeed = moveSpeed; } public int getItemSpace() { return itemSpace; } public float getMinScale() { return minScale; } public float getMoveSpeed() { return moveSpeed; } public void setItemSpace(int itemSpace) { assertNotInLayoutOrScroll(null); if (this.itemSpace == itemSpace) { return; } this.itemSpace = itemSpace; removeAllViews(); } public void setMinScale(float minScale) { assertNotInLayoutOrScroll(null); if (minScale > 1f) { minScale = 1f; } if (this.minScale == minScale) { return; } this.minScale = minScale; requestLayout(); } public void setMoveSpeed(float moveSpeed) { assertNotInLayoutOrScroll(null); if (this.moveSpeed == moveSpeed) { return; } this.moveSpeed = moveSpeed; } @Override protected float getInterval() { return (mDecoratedMeasurement - itemSpace); } @Override protected void setItemViewProperty(View itemView, float targetOffset) { float scale = calculateScale(targetOffset + mSpaceMain); itemView.setScaleX(scale); itemView.setScaleY(scale); } @Override protected float getDistanceRatio() { if (moveSpeed == 0) { return Float.MAX_VALUE; } return 1 / moveSpeed; } @Override protected float getViewElevation(View itemView, float targetOffset) { return itemView.getScaleX() * 5; } private float calculateScale(float x) { float deltaX = Math.abs(x - (mOrientationHelper.getTotalSpace() - mDecoratedMeasurement) / 2f); return (minScale - 1) * deltaX / (mOrientationHelper.getTotalSpace() / 2f) + 1f; } public static class Builder { private static final float DEFAULT_SPEED = 1f; private static final float MIN_SCALE = 0.5f; private Context context; private int itemSpace; private int orientation; private float minScale; private float moveSpeed; private int maxVisibleItemCount; private boolean reverseLayout; private int distanceToBottom; public Builder(Context context, int itemSpace) { this.itemSpace = itemSpace; this.context = context; orientation = HORIZONTAL; minScale = MIN_SCALE; this.moveSpeed = DEFAULT_SPEED; reverseLayout = false; maxVisibleItemCount = ViewPagerLayoutManager.DETERMINE_BY_MAX_AND_MIN; distanceToBottom = ViewPagerLayoutManager.INVALID_SIZE; } public Builder setOrientation(int orientation) { this.orientation = orientation; return this; } public Builder setMinScale(float minScale) { this.minScale = minScale; return this; } public Builder setReverseLayout(boolean reverseLayout) { this.reverseLayout = reverseLayout; return this; } public Builder setMoveSpeed(float moveSpeed) { this.moveSpeed = moveSpeed; return this; } public Builder setMaxVisibleItemCount(int maxVisibleItemCount) { this.maxVisibleItemCount = maxVisibleItemCount; return this; } public Builder setDistanceToBottom(int distanceToBottom) { this.distanceToBottom = distanceToBottom; return this; } public CarouselLayoutManager build() { return new CarouselLayoutManager(this); } } }
3e0492f833bb49140b49ea2097b8c757a04bfcbc
47,315
java
Java
src/core/org/luaj/vm2/LuaString.java
desb42/luaj_xowa
3ca7c55d2c8f923577c72b1d0e2968ccf6f6d623
[ "MIT" ]
1
2015-06-22T08:15:18.000Z
2015-06-22T08:15:18.000Z
src/core/org/luaj/vm2/LuaString.java
desb42/luaj_xowa
3ca7c55d2c8f923577c72b1d0e2968ccf6f6d623
[ "MIT" ]
null
null
null
src/core/org/luaj/vm2/LuaString.java
desb42/luaj_xowa
3ca7c55d2c8f923577c72b1d0e2968ccf6f6d623
[ "MIT" ]
2
2017-11-14T22:19:28.000Z
2020-05-18T07:33:42.000Z
37.226593
203
0.628152
1,926
/******************************************************************************* * Copyright (c) 2009-2011 Luaj.org. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ package org.luaj.vm2; import java.io.ByteArrayInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import org.luaj.vm2.lib.MathLib; import org.luaj.vm2.lib.StringLib; import gplx.objects.strings.String_; import gplx.objects.strings.char_sources.Char_source; /** * Subclass of {@link LuaValue} for representing lua strings. * <p> * Because lua string values are more nearly sequences of bytes than * sequences of characters or unicode code points, the {@link LuaString} * implementation holds the string value in an internal byte array. * <p> * {@link LuaString} values are not considered mutable once constructed, * so multiple {@link LuaString} values can chare a single byte array. * <p> * Currently {@link LuaString}s are pooled via a centrally managed weak table. * To ensure that as many string values as possible take advantage of this, * Constructors are not exposed directly. As with number, booleans, and nil, * instance construction should be via {@link LuaValue#valueOf(byte[])} or similar API. * <p> * Because of this pooling, users of LuaString <em>must not directly alter the * bytes in a LuaString</em>, or undefined behavior will result. * <p> * When Java Strings are used to initialize {@link LuaString} data, the UTF8 encoding is assumed. * The functions * {@link #lengthAsUtf8(char[])}, * {@link #encodeToUtf8(char[], int, byte[], int)}, and * {@link #decodeAsUtf8(byte[], int, int)} * are used to convert back and forth between UTF8 byte arrays and character arrays. * * @see LuaValue * @see LuaValue#valueOf(String) * @see LuaValue#valueOf(byte[]) */ public class LuaString extends LuaValue implements Char_source { private String src = null; public String Src() { if (src == null) src = decodeAsUtf8(m_bytes, m_offset, m_length); return src; } public int Get_data(int pos) {return m_bytes[m_offset + pos] & 0x0FF;} public int Len_in_data() {return m_length;} public String Substring(int bgn, int end) { String rv = decodeAsUtf8(m_bytes, bgn + m_offset, end - bgn); return rv; } public byte[] SubstringAsBry(int bgn, int end) { // NOTE: MUST use substring.m_bytes, not Substring().getBytes(); FOOTNOTE:SUBSTRING_MULTI_BYTE_CHARS ISSUE#:735; DATE:2020-05-03 return substring(bgn, end).m_bytes; } public int Index_of(Char_source find, int bgn) { int find_len = find.Len_in_data(); int src_bgn = m_offset + bgn; int src_end = m_offset + m_length; for (int i = src_bgn; i < src_end; i++) { boolean found = true; for (int j = 0; j < find_len; j++) { int src_idx = i + j; if (src_idx >= src_end) { found = false; break; } if ((m_bytes[src_idx] & 0xFF) != find.Get_data(j)) { found = false; break; } } if (found == true) return i - m_offset; } return -1; } public boolean Eq(int lhs_bgn, Char_source rhs, int rhs_bgn, int rhs_end) { if (this.Len_in_data() < lhs_bgn + rhs_end || rhs.Len_in_data() < rhs_bgn + rhs_end) return false; while ( --rhs_end>=0 ) if ((this.Get_data(lhs_bgn++) != rhs.Get_data(rhs_bgn++))) return false; return true; } /** The singleton instance for string metatables that forwards to the string functions. * Typically, this is set to the string metatable as a side effect of loading the string * library, and is read-write to provide flexible behavior by default. When used in a * server environment where there may be roge scripts, this should be replaced with a * read-only table since it is shared across all lua code in this Java VM. */ public static LuaValue s_metatable; /** The bytes for the string. These <em><b>must not be mutated directly</b></em> because * the backing may be shared by multiple LuaStrings, and the hash code is * computed only at construction time. * It is exposed only for performance and legacy reasons. */ public final byte[] m_bytes; /** The offset into the byte array, 0 means start at the first byte */ public final int m_offset; /** The number of bytes that comprise this string */ public final int m_length; /** The hashcode for this string. Computed at construct time. */ private final int m_hashcode; /** Size of cache of recent short strings. This is the maximum number of LuaStrings that * will be retained in the cache of recent short strings. Exposed to package for testing. */ static final int RECENT_STRINGS_CACHE_SIZE = 128; /** Maximum length of a string to be considered for recent short strings caching. * This effectively limits the total memory that can be spent on the recent strings cache, * because no LuaString whose backing exceeds this length will be put into the cache. * Exposed to package for testing. */ static final int RECENT_STRINGS_MAX_LENGTH = 32; /** Simple cache of recently created strings that are short. * This is simply a list of strings, indexed by their hash codes modulo the cache size * that have been recently constructed. If a string is being constructed frequently * from different contexts, it will generally show up as a cache hit and resolve * to the same value. */ private static final class RecentShortStrings { private static final LuaString recent_short_strings[] = new LuaString[RECENT_STRINGS_CACHE_SIZE]; } /** * Get a {@link LuaString} instance whose bytes match * the supplied Java String using the UTF8 encoding. * @param string Java String containing characters to encode as UTF8 * @return {@link LuaString} with UTF8 bytes corresponding to the supplied String */ public static LuaString valueOf(String string) { char[] c = string.toCharArray(); byte[] b = new byte[lengthAsUtf8(c)]; encodeToUtf8(c, c.length, b, 0); return valueUsing(b, 0, b.length); } // XOWA: carried over from 2014 version of LuaJ public static LuaString valueOfCopy(byte[] bytes, int off, int len) { byte[] rv = new byte[len]; for (int i = 0; i < len; i++) rv[i] = bytes[i + off]; return valueOf(rv, 0, len); } /** Construct a {@link LuaString} for a portion of a byte array. * <p> * The array is first be used as the backing for this object, so clients must not change contents. * If the supplied value for 'len' is more than half the length of the container, the * supplied byte array will be used as the backing, otherwise the bytes will be copied to a * new byte array, and cache lookup may be performed. * <p> * @param bytes byte buffer * @param off offset into the byte buffer * @param len length of the byte buffer * @return {@link LuaString} wrapping the byte buffer */ public static LuaString valueOf(byte[] bytes, int off, int len) { if (len > RECENT_STRINGS_MAX_LENGTH) return valueFromCopy(bytes, off, len); final int hash = hashCode(bytes, off, len); final int bucket = hash & (RECENT_STRINGS_CACHE_SIZE - 1); final LuaString t = RecentShortStrings.recent_short_strings[bucket]; if (t != null && t.m_hashcode == hash && t.byteseq(bytes, off, len)) return t; final LuaString s = valueFromCopy(bytes, off, len); RecentShortStrings.recent_short_strings[bucket] = s; return s; } /** Construct a new LuaString using a copy of the bytes array supplied */ private static LuaString valueFromCopy(byte[] bytes, int off, int len) { final byte[] copy = new byte[len]; System.arraycopy(bytes, off, copy, 0, len); return new LuaString(copy, 0, len); } /** Construct a {@link LuaString} around, possibly using the the supplied * byte array as the backing store. * <p> * The caller must ensure that the array is not mutated after the call. * However, if the string is short enough the short-string cache is checked * for a match which may be used instead of the supplied byte array. * <p> * @param bytes byte buffer * @return {@link LuaString} wrapping the byte buffer, or an equivalent string. */ static public LuaString valueUsing(byte[] bytes, int off, int len) { if (bytes.length > RECENT_STRINGS_MAX_LENGTH) return new LuaString(bytes, off, len); final int hash = hashCode(bytes, off, len); final int bucket = hash & (RECENT_STRINGS_CACHE_SIZE - 1); final LuaString t = RecentShortStrings.recent_short_strings[bucket]; if (t != null && t.m_hashcode == hash && t.byteseq(bytes, off, len)) return t; final LuaString s = new LuaString(bytes, off, len); RecentShortStrings.recent_short_strings[bucket] = s; return s; } /** Construct a {@link LuaString} using the supplied characters as byte values. * <p> * Only the low-order 8-bits of each character are used, the remainder is ignored. * <p> * This is most useful for constructing byte sequences that do not conform to UTF8. * @param bytes array of char, whose values are truncated at 8-bits each and put into a byte array. * @return {@link LuaString} wrapping a copy of the byte buffer */ public static LuaString valueOf(char[] bytes) { return valueOf(bytes, 0, bytes.length); } /** Construct a {@link LuaString} using the supplied characters as byte values. * <p> * Only the low-order 8-bits of each character are used, the remainder is ignored. * <p> * This is most useful for constructing byte sequences that do not conform to UTF8. * @param bytes array of char, whose values are truncated at 8-bits each and put into a byte array. * @return {@link LuaString} wrapping a copy of the byte buffer */ public static LuaString valueOf(char[] bytes, int off, int len) { // byte[] b = new byte[len]; // for ( int i=0; i<len; i++ ) // b[i] = (byte) bytes[i + off]; // return valueUsing(b, 0, len); // XOWA: calc length of bry by looping char[] and summing length of each char int bry_len = 0; for (int i = 0; i < len; i++) { int b_len = LuaString.Utf16_Len_by_char((int)(bytes[i + off])); if (b_len == 4) ++i; // char is 4 bytes, so has 2-len (surrogate pair); skip next char; bry_len += b_len; } byte[] bry = new byte[bry_len]; // set bytes in byte[] by looping char[] int bry_idx = 0; int i = 0; while (i < len) { char c = bytes[i + off]; int b_len = Utf16_Encode_char(c, bytes, i + off, bry, bry_idx); // XOWA: changed to "i + off" to get current position; DATE:2016-01-21; DATE:2017-03-23 bry_idx += b_len; i += b_len == 4 ? 2 : 1; // 4 bytes; surrogate pair; skip next char; } return valueOf(bry, 0, bry_len); } /** Construct a {@link LuaString} for all the bytes in a byte array. * <p> * The LuaString returned will either be a new LuaString containing a copy * of the bytes array, or be an existing LuaString used already having the same value. * <p> * @param bytes byte buffer * @return {@link LuaString} wrapping the byte buffer */ public static LuaString valueOf(byte[] bytes) { return valueOf(bytes, 0, bytes.length); } /** Construct a {@link LuaString} for all the bytes in a byte array, possibly using * the supplied array as the backing store. * <p> * The LuaString returned will either be a new LuaString containing the byte array, * or be an existing LuaString used already having the same value. * <p> * The caller must not mutate the contents of the byte array after this call, as * it may be used elsewhere due to recent short string caching. * @param bytes byte buffer * @return {@link LuaString} wrapping the byte buffer */ public static LuaString valueUsing(byte[] bytes) { return valueUsing(bytes, 0, bytes.length); } /** Construct a {@link LuaString} around a byte array without copying the contents. * <p> * The array is used directly after this is called, so clients must not change contents. * <p> * @param bytes byte buffer * @param offset offset into the byte buffer * @param length length of the byte buffer * @return {@link LuaString} wrapping the byte buffer */ private LuaString(byte[] bytes, int offset, int length) { this.m_bytes = bytes; this.m_offset = offset; this.m_length = length; this.m_hashcode = hashCode(bytes, offset, length); } public boolean isstring() { return true; } public LuaValue getmetatable() { return s_metatable; } public int type() { return LuaValue.TSTRING; } public String typename() { return "string"; } public String tojstring() { return decodeAsUtf8(m_bytes, m_offset, m_length); } // unary operators public LuaValue neg() { double d = scannumber(); return Double.isNaN(d)? super.neg(): valueOf(-d); } // basic binary arithmetic public LuaValue add( LuaValue rhs ) { double d = scannumber(); return Double.isNaN(d)? arithmt(ADD,rhs): rhs.add(d); } public LuaValue add( double rhs ) { return valueOf( checkarith() + rhs ); } public LuaValue add( int rhs ) { return valueOf( checkarith() + rhs ); } public LuaValue sub( LuaValue rhs ) { double d = scannumber(); return Double.isNaN(d)? arithmt(SUB,rhs): rhs.subFrom(d); } public LuaValue sub( double rhs ) { return valueOf( checkarith() - rhs ); } public LuaValue sub( int rhs ) { return valueOf( checkarith() - rhs ); } public LuaValue subFrom( double lhs ) { return valueOf( lhs - checkarith() ); } public LuaValue mul( LuaValue rhs ) { double d = scannumber(); return Double.isNaN(d)? arithmt(MUL,rhs): rhs.mul(d); } public LuaValue mul( double rhs ) { return valueOf( checkarith() * rhs ); } public LuaValue mul( int rhs ) { return valueOf( checkarith() * rhs ); } public LuaValue pow( LuaValue rhs ) { double d = scannumber(); return Double.isNaN(d)? arithmt(POW,rhs): rhs.powWith(d); } public LuaValue pow( double rhs ) { return MathLib.dpow(checkarith(),rhs); } public LuaValue pow( int rhs ) { return MathLib.dpow(checkarith(),rhs); } public LuaValue powWith( double lhs ) { return MathLib.dpow(lhs, checkarith()); } public LuaValue powWith( int lhs ) { return MathLib.dpow(lhs, checkarith()); } public LuaValue div( LuaValue rhs ) { double d = scannumber(); return Double.isNaN(d)? arithmt(DIV,rhs): rhs.divInto(d); } public LuaValue div( double rhs ) { return LuaDouble.ddiv(checkarith(),rhs); } public LuaValue div( int rhs ) { return LuaDouble.ddiv(checkarith(),rhs); } public LuaValue divInto( double lhs ) { return LuaDouble.ddiv(lhs, checkarith()); } public LuaValue mod( LuaValue rhs ) { double d = scannumber(); return Double.isNaN(d)? arithmt(MOD,rhs): rhs.modFrom(d); } public LuaValue mod( double rhs ) { return LuaDouble.dmod(checkarith(), rhs); } public LuaValue mod( int rhs ) { return LuaDouble.dmod(checkarith(), rhs); } public LuaValue modFrom( double lhs ) { return LuaDouble.dmod(lhs, checkarith()); } // relational operators, these only work with other strings public LuaValue lt( LuaValue rhs ) { return rhs.isstring() ? (rhs.strcmp(this)>0? LuaValue.TRUE: FALSE) : super.lt(rhs); } public boolean lt_b( LuaValue rhs ) { return rhs.isstring() ? rhs.strcmp(this)>0 : super.lt_b(rhs); } public boolean lt_b( int rhs ) { typerror("attempt to compare string with number"); return false; } public boolean lt_b( double rhs ) { typerror("attempt to compare string with number"); return false; } public LuaValue lteq( LuaValue rhs ) { return rhs.isstring() ? (rhs.strcmp(this)>=0? LuaValue.TRUE: FALSE) : super.lteq(rhs); } public boolean lteq_b( LuaValue rhs ) { return rhs.isstring() ? rhs.strcmp(this)>=0 : super.lteq_b(rhs); } public boolean lteq_b( int rhs ) { typerror("attempt to compare string with number"); return false; } public boolean lteq_b( double rhs ) { typerror("attempt to compare string with number"); return false; } public LuaValue gt( LuaValue rhs ) { return rhs.isstring() ? (rhs.strcmp(this)<0? LuaValue.TRUE: FALSE) : super.gt(rhs); } public boolean gt_b( LuaValue rhs ) { return rhs.isstring() ? rhs.strcmp(this)<0 : super.gt_b(rhs); } public boolean gt_b( int rhs ) { typerror("attempt to compare string with number"); return false; } public boolean gt_b( double rhs ) { typerror("attempt to compare string with number"); return false; } public LuaValue gteq( LuaValue rhs ) { return rhs.isstring() ? (rhs.strcmp(this)<=0? LuaValue.TRUE: FALSE) : super.gteq(rhs); } public boolean gteq_b( LuaValue rhs ) { return rhs.isstring() ? rhs.strcmp(this)<=0 : super.gteq_b(rhs); } public boolean gteq_b( int rhs ) { typerror("attempt to compare string with number"); return false; } public boolean gteq_b( double rhs ) { typerror("attempt to compare string with number"); return false; } // concatenation public LuaValue concat(LuaValue rhs) { return rhs.concatTo(this); } public Buffer concat(Buffer rhs) { return rhs.concatTo(this); } public LuaValue concatTo(LuaNumber lhs) { return concatTo(lhs.strvalue()); } public LuaValue concatTo(LuaString lhs) { byte[] b = new byte[lhs.m_length+this.m_length]; System.arraycopy(lhs.m_bytes, lhs.m_offset, b, 0, lhs.m_length); System.arraycopy(this.m_bytes, this.m_offset, b, lhs.m_length, this.m_length); return valueUsing(b, 0, b.length); } // string comparison public int strcmp(LuaValue lhs) { return -lhs.strcmp(this); } private static final Utf16_char lhs_tmp = new Utf16_char(), rhs_tmp = new Utf16_char(); public int strcmp(LuaString rhs) { // for ( int i=0, j=0; i<m_length && j<rhs.m_length; ++i, ++j ) { // if ( m_bytes[m_offset+i] != rhs.m_bytes[rhs.m_offset+j] ) { // return ((int)m_bytes[m_offset+i]) - ((int) rhs.m_bytes[rhs.m_offset+j]); // } // } // XOWA: handle utf16 bytes int lhs_idx = 0, rhs_idx = 0; while (lhs_idx < m_length && rhs_idx < rhs.m_length) { synchronized (lhs_tmp) { Utf16_Decode_to_int( m_bytes, m_offset + lhs_idx, lhs_tmp); Utf16_Decode_to_int(rhs.m_bytes, rhs.m_offset + rhs_idx, rhs_tmp); int comp = lhs_tmp.Codepoint - rhs_tmp.Codepoint; if (comp != 0) return comp; lhs_idx += lhs_tmp.Len; rhs_idx += rhs_tmp.Len; } } return m_length - rhs.m_length; } /** Check for number in arithmetic, or throw aritherror */ private double checkarith() { double d = scannumber(); if ( Double.isNaN(d) ) aritherror(); return d; } public int checkint() { return (int) (long) checkdouble(); } public LuaInteger checkinteger() { return valueOf(checkint()); } public long checklong() { return (long) checkdouble(); } public double checkdouble() { double d = scannumber(); if ( Double.isNaN(d) ) argerror("number"); return d; } public LuaNumber checknumber() { return valueOf(checkdouble()); } public LuaNumber checknumber(String msg) { double d = scannumber(); if ( Double.isNaN(d) ) error(msg); return valueOf(d); } public boolean isnumber() { double d = scannumber(); return ! Double.isNaN(d); } public boolean isint() { double d = scannumber(); if ( Double.isNaN(d) ) return false; int i = (int) d; return i == d; } public boolean islong() { double d = scannumber(); if ( Double.isNaN(d) ) return false; long l = (long) d; return l == d; } public byte tobyte() { return (byte) toint(); } public char tochar() { return (char) toint(); } public double todouble() { double d=scannumber(); return Double.isNaN(d)? 0: d; } public float tofloat() { return (float) todouble(); } public int toint() { return (int) tolong(); } public long tolong() { return (long) todouble(); } public short toshort() { return (short) toint(); } public double optdouble(double defval) { return checkdouble(); } public int optint(int defval) { return checkint(); } public LuaInteger optinteger(LuaInteger defval) { return checkinteger(); } public long optlong(long defval) { return checklong(); } public LuaNumber optnumber(LuaNumber defval) { return checknumber(); } public LuaString optstring(LuaString defval) { return this; } public LuaValue tostring() { return this; } public String optjstring(String defval) { return tojstring(); } public LuaString strvalue() { return this; } /** Take a substring using Java zero-based indexes for begin and end or range. * @param beginIndex The zero-based index of the first character to include. * @param endIndex The zero-based index of position after the last character. * @return LuaString which is a substring whose first character is at offset * beginIndex and extending for (endIndex - beginIndex ) characters. */ public LuaString substring( int beginIndex, int endIndex ) { final int off = m_offset + beginIndex; final int len = endIndex - beginIndex; return len >= m_length / 2? valueUsing(m_bytes, off, len): valueOf(m_bytes, off, len); } public int hashCode() { return m_hashcode; } /** Compute the hash code of a sequence of bytes within a byte array using * lua's rules for string hashes. For long strings, not all bytes are hashed. * @param bytes byte array containing the bytes. * @param offset offset into the hash for the first byte. * @param length number of bytes starting with offset that are part of the string. * @return hash for the string defined by bytes, offset, and length. */ public static int hashCode(byte[] bytes, int offset, int length) { int h = length; /* seed */ int step = (length>>5)+1; /* if string is too long, don't hash all its chars */ for (int l1=length; l1>=step; l1-=step) /* compute hash */ h = h ^ ((h<<5)+(h>>2)+(((int) bytes[offset+l1-1] ) & 0x0FF )); return h; } // object comparison, used in key comparison public boolean equals( Object o ) { if ( o instanceof LuaString ) { return raweq( (LuaString) o ); } return false; } // equality w/ metatable processing public LuaValue eq( LuaValue val ) { return val.raweq(this)? TRUE: FALSE; } public boolean eq_b( LuaValue val ) { return val.raweq(this); } // equality w/o metatable processing public boolean raweq( LuaValue val ) { return val.raweq(this); } public boolean raweq( LuaString s ) { if ( this == s ) return true; if ( s.m_length != m_length ) return false; if ( s.m_bytes == m_bytes && s.m_offset == m_offset ) return true; if ( s.hashCode() != hashCode() ) return false; for ( int i=0; i<m_length; i++ ) if ( s.m_bytes[s.m_offset+i] != m_bytes[m_offset+i] ) return false; return true; } public static boolean equals( LuaString a, int i, LuaString b, int j, int n ) { return equals( a.m_bytes, a.m_offset + i, b.m_bytes, b.m_offset + j, n ); } /** Return true if the bytes in the supplied range match this LuaStrings bytes. */ private boolean byteseq(byte[] bytes, int off, int len) { return (m_length == len && equals(m_bytes, m_offset, bytes, off, len)); } public static boolean equals( byte[] a, int i, byte[] b, int j, int n ) { if ( a.length < i + n || b.length < j + n ) return false; while ( --n>=0 ) if ( a[i++]!=b[j++] ) return false; return true; } public void write(DataOutputStream writer, int i, int len) throws IOException { writer.write(m_bytes,m_offset+i,len); } public LuaValue len() { return LuaInteger.valueOf(m_length); } public int length() { return m_length; } public int rawlen() { return m_length; } public int luaByte(int index) { return m_bytes[m_offset + index] & 0x0FF; } public int charAt( int index ) { if ( index < 0 || index >= m_length ) throw new IndexOutOfBoundsException(); return luaByte( index ); } public String checkjstring() { return tojstring(); } public LuaString checkstring() { return this; } /** Convert value to an input stream. * * @return {@link InputStream} whose data matches the bytes in this {@link LuaString} */ public InputStream toInputStream() { return new ByteArrayInputStream(m_bytes, m_offset, m_length); } /** * Copy the bytes of the string into the given byte array. * @param strOffset offset from which to copy * @param bytes destination byte array * @param arrayOffset offset in destination * @param len number of bytes to copy */ public void copyInto( int strOffset, byte[] bytes, int arrayOffset, int len ) { System.arraycopy( m_bytes, m_offset+strOffset, bytes, arrayOffset, len ); } /** Java version of strpbrk - find index of any byte that in an accept string. * @param accept {@link LuaString} containing characters to look for. * @return index of first match in the {@code accept} string, or -1 if not found. */ public int indexOfAny( LuaString accept ) { final int ilimit = m_offset + m_length; final int jlimit = accept.m_offset + accept.m_length; for ( int i = m_offset; i < ilimit; ++i ) { for ( int j = accept.m_offset; j < jlimit; ++j ) { if ( m_bytes[i] == accept.m_bytes[j] ) { return i - m_offset; } } } return -1; } /** * Find the index of a byte starting at a point in this string * @param b the byte to look for * @param start the first index in the string * @return index of first match found, or -1 if not found. */ public int indexOf( byte b, int start ) { for ( int i=start; i < m_length; ++i ) { if ( m_bytes[m_offset+i] == b ) return i; } return -1; } /** * Find the index of a string starting at a point in this string * @param s the string to search for * @param start the first index in the string * @return index of first match found, or -1 if not found. */ public int indexOf( LuaString s, int start ) { final int slen = s.length(); final int limit = m_length - slen; for ( int i=start; i <= limit; ++i ) { if ( equals( m_bytes, m_offset+i, s.m_bytes, s.m_offset, slen ) ) return i; } return -1; } /** * Find the last index of a string in this string * @param s the string to search for * @return index of last match found, or -1 if not found. */ public int lastIndexOf( LuaString s ) { final int slen = s.length(); final int limit = m_length - slen; for ( int i=limit; i >= 0; --i ) { if ( equals( m_bytes, m_offset+i, s.m_bytes, s.m_offset, slen ) ) return i; } return -1; } /** * Convert to Java String interpreting as utf8 characters. * * @param bytes byte array in UTF8 encoding to convert * @param offset starting index in byte array * @param length number of bytes to convert * @return Java String corresponding to the value of bytes interpreted using UTF8 * @see #lengthAsUtf8(char[]) * @see #encodeToUtf8(char[], int, byte[], int) * @see #isValidUtf8() */ public static String decodeAsUtf8(byte[] bytes, int offset, int length) { // int i,j,n,b; // for ( i=offset,j=offset+length,n=0; i<j; ++n ) { // switch ( 0xE0 & bytes[i++] ) { // case 0xE0: ++i; // case 0xC0: ++i; // } // } // char[] chars=new char[n]; // for ( i=offset,j=offset+length,n=0; i<j; ) { // chars[n++] = (char) ( // ((b=bytes[i++])>=0||i>=j)? b: // (b<-32||i+1>=j)? (((b&0x3f) << 6) | (bytes[i++]&0x3f)): // (((b&0xf) << 12) | ((bytes[i++]&0x3f)<<6) | (bytes[i++]&0x3f))); // } // return new String(chars); // XOWA: handle 3+ byte chars return new String(bytes, offset, length, java.nio.charset.Charset.forName("UTF-8")); } /** * Count the number of bytes required to encode the string as UTF-8. * @param chars Array of unicode characters to be encoded as UTF-8 * @return count of bytes needed to encode using UTF-8 * @see #encodeToUtf8(char[], int, byte[], int) * @see #decodeAsUtf8(byte[], int, int) * @see #isValidUtf8() */ public static int lengthAsUtf8(char[] chars) { // int i,b; // char c; // for ( i=b=chars.length; --i>=0; ) // if ( (c=chars[i]) >=0x80 ) // b += (c>=0x800)? 2: 1; // return b; // XOWA: UTF-8 int len = chars.length; int rv = 0; for (int i = 0; i < len; i++) { int c = chars[i]; // XOWA.PERF: inlined function per VisualVM; DATE:2014-08-08 if ( (c > -1) && (c < 128)) rv += 1; // 1 << 7 else if ( (c < 2048)) rv += 2; // 1 << 11 else if ( (c > 55295) // 0xD800 && (c < 56320)) { rv += 4; // 0xDFFF ++i; } else if ( (c < 65536)) rv += 3; // 1 << 16 } return rv; } /** * Encode the given Java string as UTF-8 bytes, writing the result to bytes * starting at offset. * <p> * The string should be measured first with lengthAsUtf8 * to make sure the given byte array is large enough. * @param chars Array of unicode characters to be encoded as UTF-8 * @param nchars Number of characters in the array to convert. * @param bytes byte array to hold the result * @param off offset into the byte array to start writing * @return number of bytes converted. * @see #lengthAsUtf8(char[]) * @see #decodeAsUtf8(byte[], int, int) * @see #isValidUtf8() */ public static int encodeToUtf8(char[] chars, int nchars, byte[] bytes, int off) { //char c; //int j = off; //for ( int i=0; i<nchars; i++ ) { // if ( (c = chars[i]) < 0x80 ) { // bytes[j++] = (byte) c; // } else if ( c < 0x800 ) { // bytes[j++] = (byte) (0xC0 | ((c>>6) & 0x1f)); // bytes[j++] = (byte) (0x80 | ( c & 0x3f)); // } else { // bytes[j++] = (byte) (0xE0 | ((c>>12) & 0x0f)); // bytes[j++] = (byte) (0x80 | ((c>>6) & 0x3f)); // bytes[j++] = (byte) (0x80 | ( c & 0x3f)); // } //} //return j - off; // XOWA: handle 4+ byte chars; already using Encode_by_int, so might as well be consistent int bry_idx = off; int i = 0; while (i < nchars) { char c = chars[i]; // XOWA.PERF: inlined function per VisualVM; DATE:2014-08-08 if (c > -1 && c < 128) { bytes[bry_idx++] = (byte)c; ++i; } else if (c < 2048) { bytes[bry_idx++] = (byte)(0xC0 | (c >> 6)); bytes[bry_idx++] = (byte)(0x80 | (c & 0x3F)); ++i; } else if((c > 55295) // 0xD800 && (c < 56320)) { // 0xDFFF if (i >= nchars) throw new RuntimeException("incomplete surrogate pair at end of string; char=" + c); int nxt_char = chars[i + 1]; int v = Utf16_Surrogate_merge(c, nxt_char); bytes[bry_idx++] = (byte)(0xF0 | (v >> 18)); bytes[bry_idx++] = (byte)(0x80 | (v >> 12) & 0x3F); bytes[bry_idx++] = (byte)(0x80 | (v >> 6) & 0x3F); bytes[bry_idx++] = (byte)(0x80 | (v & 0x3F)); i += 2; } else { bytes[bry_idx++] = (byte)(0xE0 | (c >> 12)); bytes[bry_idx++] = (byte)(0x80 | (c >> 6) & 0x3F); bytes[bry_idx++] = (byte)(0x80 | (c & 0x3F)); ++i; } } return nchars; // NOTE: code returned # of bytes which is wrong; Globals.UTF8Stream.read caches rv as j which is used as index to char[] not byte[]; will throw out of bounds exception if bytes returned } /** Check that a byte sequence is valid UTF-8 * @return true if it is valid UTF-8, otherwise false * @see #lengthAsUtf8(char[]) * @see #encodeToUtf8(char[], int, byte[], int) * @see #decodeAsUtf8(byte[], int, int) */ public boolean isValidUtf8() { for (int i=m_offset,j=m_offset+m_length; i<j;) { int c = m_bytes[i++]; if ( c >= 0 ) continue; if ( ((c & 0xE0) == 0xC0) && i<j && (m_bytes[i++] & 0xC0) == 0x80) continue; if ( ((c & 0xF0) == 0xE0) && i+1<j && (m_bytes[i++] & 0xC0) == 0x80 && (m_bytes[i++] & 0xC0) == 0x80) continue; return false; } return true; } // --------------------- number conversion ----------------------- /** * convert to a number using baee 10 or base 16 if it starts with '0x', * or NIL if it can't be converted * @return IntValue, DoubleValue, or NIL depending on the content of the string. * @see LuaValue#tonumber() */ public LuaValue tonumber() { double d = scannumber(); return Double.isNaN(d)? NIL: valueOf(d); } /** * convert to a number using a supplied base, or NIL if it can't be converted * @param base the base to use, such as 10 * @return IntValue, DoubleValue, or NIL depending on the content of the string. * @see LuaValue#tonumber() */ public LuaValue tonumber( int base ) { double d = scannumber( base ); return Double.isNaN(d)? NIL: valueOf(d); } /** * Convert to a number in base 10, or base 16 if the string starts with '0x', * or return Double.NaN if it cannot be converted to a number. * @return double value if conversion is valid, or Double.NaN if not */ public double scannumber() { int i=m_offset,j=m_offset+m_length; // XOWA:trim ws int idx = i; while (idx < j) { switch (m_bytes[idx]) { case 9: case 10: case 13: case 32: ++idx; i = idx; break; default: idx = j; break; } } idx = j - 1; while (idx >= i) { switch (m_bytes[idx]) { case 9: case 10: case 13: case 32: j = idx; --idx; break; default: idx = i -1; break; } } // while ( i<j && m_bytes[i]==' ' ) ++i; // while ( i<j && m_bytes[j-1]==' ' ) --j; if ( i>=j ) return Double.NaN; // if ( m_bytes[i]=='0' && i+1<j && (m_bytes[i+1]=='x'||m_bytes[i+1]=='X')) // return scanlong(16, i+2, j); if ( i + 1 < j && m_bytes[i] == '0' ) { byte next_byte = m_bytes[i+1]; if (next_byte == 'x' || next_byte == 'X') { return i + 2 < j // XOWA: bounds check; DATE:2014-08-26 ? scanlong(16, i+2, j) : Double.NaN ; } } double l = scanlong(10, i, j); return Double.isNaN(l)? scandouble(i,j): l; } /** * Convert to a number in a base, or return Double.NaN if not a number. * @param base the base to use between 2 and 36 * @return double value if conversion is valid, or Double.NaN if not */ public double scannumber(int base) { if ( base < 2 || base > 36 ) return Double.NaN; int i=m_offset,j=m_offset+m_length; while ( i<j && m_bytes[i]==' ' ) ++i; while ( i<j && m_bytes[j-1]==' ' ) --j; if ( i>=j ) return Double.NaN; return scanlong( base, i, j ); } /** * Scan and convert a long value, or return Double.NaN if not found. * @param base the base to use, such as 10 * @param start the index to start searching from * @param end the first index beyond the search range * @return double value if conversion is valid, * or Double.NaN if not */ private double scanlong( int base, int start, int end ) { long x = 0; boolean neg = (m_bytes[start] == '-'); // XOWA:if "-" only, return "nil", not "0"; EX:tonumber('-'); DATE:2017-12-05 int bgn = neg?start+1:start; if (neg && bgn == end) { return Double.NaN; } for ( int i=bgn; i<end; i++ ) { // for ( int i=(neg?start+1:start); i<end; i++ ) { int digit = m_bytes[i] - (base<=10||(m_bytes[i]>='0'&&m_bytes[i]<='9')? '0': m_bytes[i]>='A'&&m_bytes[i]<='Z'? ('A'-10): ('a'-10)); if ( digit < 0 || digit >= base ) return Double.NaN; x = x * base + digit; if ( x < 0 ) return Double.NaN; // overflow } return neg? -x: x; } /** * Scan and convert a double value, or return Double.NaN if not a double. * @param start the index to start searching from * @param end the first index beyond the search range * @return double value if conversion is valid, * or Double.NaN if not */ private double scandouble(int start, int end) { if ( end>start+64 ) end=start+64; for ( int i=start; i<end; i++ ) { switch ( m_bytes[i] ) { case '-': case '+': case '.': case 'e': case 'E': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': break; default: return Double.NaN; } } char [] c = new char[end-start]; for ( int i=start; i<end; i++ ) c[i-start] = (char) m_bytes[i]; try { return Double.parseDouble(new String(c)); } catch ( Exception e ) { return Double.NaN; } } /** * Print the bytes of the LuaString to a PrintStream as if it were * an ASCII string, quoting and escaping control characters. * @param ps PrintStream to print to. */ public void printToStream(PrintStream ps) { for (int i = 0, n = m_length; i < n; i++) { int c = m_bytes[m_offset+i]; ps.print((char) c); } } public static int Utf16_Len_by_char(int c) { if ((c > -1) && (c < 128)) return 1; // 1 << 7 else if (c < 2048) return 2; // 1 << 11 else if((c > 55295) // 0xD800 && (c < 56320)) return 4; // 0xDFFF else if (c < 65536) return 3; // 1 << 16 else throw new RuntimeException("UTF-16 int must be between 0 and 2097152; char=" + c); } public static int Utf16_Len_by_int(int c) { if ((c > -1) && (c < 128)) return 1; // 1 << 7 else if (c < 2048) return 2; // 1 << 11 else if (c < 65536) return 3; // 1 << 16 else if (c < 2097152) return 4; else throw new RuntimeException("UTF-16 int must be between 0 and 2097152; char=" + c); } public static int Utf8_Len_of_char_by_1st_byte(byte b) {// SEE:w:UTF-8 int i = b & 0xff; // PATCH.JAVA:need to convert to unsigned byte switch (i) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: case 59: case 60: case 61: case 62: case 63: case 64: case 65: case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79: case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87: case 88: case 89: case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: case 98: case 99: case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: case 108: case 109: case 110: case 111: case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: case 124: case 125: case 126: case 127: case 128: case 129: case 130: case 131: case 132: case 133: case 134: case 135: case 136: case 137: case 138: case 139: case 140: case 141: case 142: case 143: case 144: case 145: case 146: case 147: case 148: case 149: case 150: case 151: case 152: case 153: case 154: case 155: case 156: case 157: case 158: case 159: case 160: case 161: case 162: case 163: case 164: case 165: case 166: case 167: case 168: case 169: case 170: case 171: case 172: case 173: case 174: case 175: case 176: case 177: case 178: case 179: case 180: case 181: case 182: case 183: case 184: case 185: case 186: case 187: case 188: case 189: case 190: case 191: return 1; case 192: case 193: case 194: case 195: case 196: case 197: case 198: case 199: case 200: case 201: case 202: case 203: case 204: case 205: case 206: case 207: case 208: case 209: case 210: case 211: case 212: case 213: case 214: case 215: case 216: case 217: case 218: case 219: case 220: case 221: case 222: case 223: return 2; case 224: case 225: case 226: case 227: case 228: case 229: case 230: case 231: case 232: case 233: case 234: case 235: case 236: case 237: case 238: case 239: return 3; case 240: case 241: case 242: case 243: case 244: case 245: case 246: case 247: return 4; default: throw new RuntimeException("invalid initial utf8 byte; byte=" + b); } } static class Utf16_char { public int Codepoint; public int Len; } public static void Utf16_Decode_to_int(byte[] ary, int pos, Utf16_char c) { byte b0 = ary[pos]; if ((b0 & 0x80) == 0) { c.Len = 1; c.Codepoint = b0; } else if ((b0 & 0xE0) == 0xC0) { c.Len = 2; c.Codepoint = ( b0 & 0x1f) << 6 | ( ary[pos + 1] & 0x3f) ; } else if ((b0 & 0xF0) == 0xE0) { c.Len = 3; c.Codepoint = ( b0 & 0x0f) << 12 | ((ary[pos + 1] & 0x3f) << 6) | ( ary[pos + 2] & 0x3f) ; } else if ((b0 & 0xF8) == 0xF0) { c.Len = 4; c.Codepoint = ( b0 & 0x07) << 18 | ((ary[pos + 1] & 0x3f) << 12) | ((ary[pos + 2] & 0x3f) << 6) | ( ary[pos + 3] & 0x3f) ; } else throw new RuntimeException("invalid utf8 byte: byte=" + b0); } public static int Utf16_Decode_to_int(byte[] ary, int pos) { byte b0 = ary[pos]; if ((b0 & 0x80) == 0) { return b0; } else if ((b0 & 0xE0) == 0xC0) { return ( b0 & 0x1f) << 6 | ( ary[pos + 1] & 0x3f) ; } else if ((b0 & 0xF0) == 0xE0) { return ( b0 & 0x0f) << 12 | ((ary[pos + 1] & 0x3f) << 6) | ( ary[pos + 2] & 0x3f) ; } else if ((b0 & 0xF8) == 0xF0) { return ( b0 & 0x07) << 18 | ((ary[pos + 1] & 0x3f) << 12) | ((ary[pos + 2] & 0x3f) << 6) | ( ary[pos + 3] & 0x3f) ; } else throw new RuntimeException("invalid utf8 byte: byte=" + b0); } public static int Utf16_Encode_int(int c, byte[] src, int pos) { if ((c > -1) && (c < 128)) { src[ pos] = (byte)c; return 1; } else if (c < 2048) { src[ pos] = (byte)(0xC0 | (c >> 6)); src[++pos] = (byte)(0x80 | (c & 0x3F)); return 2; } else if (c < 65536) { src[pos] = (byte)(0xE0 | (c >> 12)); src[++pos] = (byte)(0x80 | (c >> 6) & 0x3F); src[++pos] = (byte)(0x80 | (c & 0x3F)); return 3; } else if (c < 2097152) { src[pos] = (byte)(0xF0 | (c >> 18)); src[++pos] = (byte)(0x80 | (c >> 12) & 0x3F); src[++pos] = (byte)(0x80 | (c >> 6) & 0x3F); src[++pos] = (byte)(0x80 | (c & 0x3F)); return 4; } else throw new RuntimeException("UTF-16 int must be between 0 and 2097152; char=" + c); } public static int Utf16_Encode_char(int c, char[] c_ary, int c_pos, byte[] b_ary, int b_pos) { if ((c > -1) && (c < 128)) { b_ary[ b_pos] = (byte)c; return 1; } else if (c < 2048) { b_ary[ b_pos] = (byte)(0xC0 | (c >> 6)); b_ary[++b_pos] = (byte)(0x80 | (c & 0x3F)); return 2; } else if((c > 55295) // 0xD800 && (c < 56320)) { // 0xDFFF if (c_pos >= c_ary.length) throw new RuntimeException("incomplete surrogate pair at end of string; char=" + c); int nxt_char = c_ary[c_pos + 1]; int v = Utf16_Surrogate_merge(c, nxt_char); b_ary[b_pos] = (byte)(0xF0 | (v >> 18)); b_ary[++b_pos] = (byte)(0x80 | (v >> 12) & 0x3F); b_ary[++b_pos] = (byte)(0x80 | (v >> 6) & 0x3F); b_ary[++b_pos] = (byte)(0x80 | (v & 0x3F)); return 4; } else { b_ary[b_pos] = (byte)(0xE0 | (c >> 12)); b_ary[++b_pos] = (byte)(0x80 | (c >> 6) & 0x3F); b_ary[++b_pos] = (byte)(0x80 | (c & 0x3F)); return 3; } } public static int Utf16_Encode_char(int c, int nxt_char, byte[] b_ary, int b_pos) { if ((c > -1) && (c < 128)) { b_ary[ b_pos] = (byte)c; return 1; } else if (c < 2048) { b_ary[ b_pos] = (byte)(0xC0 | (c >> 6)); b_ary[++b_pos] = (byte)(0x80 | (c & 0x3F)); return 2; } else if((c > 55295) // 0xD800 && (c < 56320)) { // 0xDFFF int v = Utf16_Surrogate_merge(c, nxt_char); b_ary[b_pos] = (byte)(0xF0 | (v >> 18)); b_ary[++b_pos] = (byte)(0x80 | (v >> 12) & 0x3F); b_ary[++b_pos] = (byte)(0x80 | (v >> 6) & 0x3F); b_ary[++b_pos] = (byte)(0x80 | (v & 0x3F)); return 4; } else { b_ary[b_pos] = (byte)(0xE0 | (c >> 12)); b_ary[++b_pos] = (byte)(0x80 | (c >> 6) & 0x3F); b_ary[++b_pos] = (byte)(0x80 | (c & 0x3F)); return 3; } } public static int Utf16_Encode_char_ascii_skip(int c, char[] c_ary, int c_pos, byte[] b_ary, int b_pos) { if (c < 2048) { b_ary[ b_pos] = (byte)(0xC0 | (c >> 6)); b_ary[++b_pos] = (byte)(0x80 | (c & 0x3F)); return 2; } else if((c > 55295) // 0xD800 && (c < 56320)) { // 0xDFFF if (c_pos >= c_ary.length) throw new RuntimeException("incomplete surrogate pair at end of string; char=" + c); int nxt_char = c_ary[c_pos + 1]; int v = Utf16_Surrogate_merge(c, nxt_char); b_ary[b_pos] = (byte)(0xF0 | (v >> 18)); b_ary[++b_pos] = (byte)(0x80 | (v >> 12) & 0x3F); b_ary[++b_pos] = (byte)(0x80 | (v >> 6) & 0x3F); b_ary[++b_pos] = (byte)(0x80 | (v & 0x3F)); return 4; } else { b_ary[b_pos] = (byte)(0xE0 | (c >> 12)); b_ary[++b_pos] = (byte)(0x80 | (c >> 6) & 0x3F); b_ary[++b_pos] = (byte)(0x80 | (c & 0x3F)); return 3; } } private static int Utf16_Surrogate_merge(int hi, int lo) { // REF: http://perldoc.perl.org/Encode/Unicode.html return 0x10000 + (hi - 0xD800) * 0x400 + (lo - 0xDC00); } public static void Utf16_Surrogate_split(int v, int[] tmp_ary) { tmp_ary[0] = ((v - 0x10000) / 0x400 + 0xD800); tmp_ary[1] = ((v - 0x10000) % 0x400 + 0xDC00); } } /* == SUBSTRING_MULTI_BYTE_CHARS == `SubstringAsBry()` MUST use substring.m_bytes, not Substring().getBytes(); This is necessary for multi-byte chars and single-character matches like `.`. For example: `string.gsub("¢", ".", tbl);` Since lua matches at the byte-level, Lua will incrementally add each byte of the multi-byte char one-by-one to the ByteBuffer. For example, "¢" gets added to the ByteBuffer as "-62" in the one pass, and then "-94" in another pass When `new LuaString()` is called, it is still properly passed a byte[] of `{-62}` and a byte[] of `{-94}` These will later be concatenated to "reconsistute" the "{-62, -94}" of "¢" if `substring.m_bytes` is called. However, if Substring().getBytes() is called, Java will try to create a String from `{-62}`. Since this is an invalid UTF-8 byte sequence, Java will instead "fix" it by creating a string with bytes {-17, -65, -126} See also ISSUE#:504 and `"æ".Substring(0, 1)` */
3e04952c2ba12fcc27deb61d599d2e4f9dd8dbc2
9,771
java
Java
Processing/angryartists/libraries/fisica/src/fisica/FRevoluteJoint.java
7Ds7/AngryArtists
27d92a8c2e4b8351de06276edfada9dcb3ee3ea3
[ "MIT" ]
1
2022-03-12T22:47:22.000Z
2022-03-12T22:47:22.000Z
Processing/angryartists/libraries/fisica/src/fisica/FRevoluteJoint.java
7Ds7/AngryArtists
27d92a8c2e4b8351de06276edfada9dcb3ee3ea3
[ "MIT" ]
null
null
null
Processing/angryartists/libraries/fisica/src/fisica/FRevoluteJoint.java
7Ds7/AngryArtists
27d92a8c2e4b8351de06276edfada9dcb3ee3ea3
[ "MIT" ]
null
null
null
33.57732
355
0.689489
1,927
/* Part of the Fisica library - http://www.ricardmarxer.com/fisica Copyright (c) 2009 - 2010 Ricard Marxer Fisica is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package fisica; import processing.core.*; import java.util.ArrayList; import org.jbox2d.common.*; import org.jbox2d.collision.*; import org.jbox2d.collision.shapes.*; import org.jbox2d.dynamics.*; import org.jbox2d.dynamics.joints.*; /** * Represents a revolute joint that restricts the movement of one body with respect to another to rotation around a given anchor. The rotation can be further limited given a lower and un upper angles. Additionally the user can enable a motor in order to apply a constant rotation force (torque) to the joint in order to reach the desired rotation speed. * */ public class FRevoluteJoint extends FJoint { protected FBody m_body1; protected FBody m_body2; protected Vec2 m_anchor; /** * The local anchor point relative to body1's origin. */ protected Vec2 m_localAnchor1 = new Vec2(0.0f, 0.0f); /** * The local anchor point relative to body2's origin. */ protected Vec2 m_localAnchor2 = new Vec2(0.0f, 0.0f); /** * The body2 angle minus body1 angle in the reference state (radians). */ protected float m_referenceAngle = 0.0f; /** * A flag to enable joint limits. */ protected boolean m_enableLimit = false; /** * The lower angle for the joint limit (radians). */ protected float m_lowerAngle = 0.0f; /** * The upper angle for the joint limit (radians). */ protected float m_upperAngle = 0.0f; /** * A flag to enable the joint motor. */ protected boolean m_enableMotor = false; /** * The desired motor speed. Usually in radians per second. */ protected float m_motorSpeed = 0.0f; /** * The maximum motor torque used to achieve the desired motor speed. * Usually in N-m. */ protected float m_maxMotorTorque = 0.0f; protected void updateLocalAnchors() { m_localAnchor1 = m_body1.getLocalWorldPoint(Fisica.screenToWorld(getAnchorX(), getAnchorY())); //Fisica.screenToWorld(getAnchorX() - m_body1.getX(), getAnchorY() - m_body1.getY()); m_localAnchor2 = m_body2.getLocalWorldPoint(Fisica.screenToWorld(getAnchorX(), getAnchorY())); //Fisica.screenToWorld(getAnchorX() - m_body2.getX(), getAnchorY() - m_body2.getY()); } protected JointDef getJointDef(FWorld world) { RevoluteJointDef md = new RevoluteJointDef(); md.body1 = m_body1.m_body; md.body2 = m_body2.m_body; md.localAnchor1 = m_localAnchor1.clone(); md.localAnchor2 = m_localAnchor2.clone(); md.referenceAngle = m_referenceAngle; md.lowerAngle = m_lowerAngle; md.upperAngle = m_upperAngle; md.enableMotor = m_enableMotor; md.enableLimit = m_enableLimit; md.motorSpeed = m_motorSpeed; md.maxMotorTorque = m_maxMotorTorque; if (m_body1.m_body != null) { m_body1.m_body.wakeUp(); } if (m_body2.m_body != null) { m_body2.m_body.wakeUp(); } return md; } /** * Construct a revolute joint between two bodies given an anchor position. * * @param body1 first body of the joint * @param body2 second body of the joint * @param x horizontal coordinate of the anchor given in global coordinates, relative to the canvas' center * @param y vertical coordinate of the anchor given in global coordinates, relative to the canvas' center */ public FRevoluteJoint(FBody body1, FBody body2, float x, float y) { super(); m_body1 = body1; m_body2 = body2; m_anchor = Fisica.screenToWorld(x, y); updateLocalAnchors(); m_referenceAngle = m_body2.getRotation() - m_body1.getRotation(); } /** * Construct a revolute joint between two bodies. * * @param body1 first body of the joint * @param body2 second body of the joint */ public FRevoluteJoint(FBody body1, FBody body2) { this(body1, body2, (body1.getX() + body2.getX())/2, (body1.getY() + body2.getY())/2); } /** * Set the lowest angle allowed. This property only has effect if the {@code enableLimit} has been set to {@code true} using {@link #setEnableLimit(boolean)}. * * @param a lowest angle allowed in radians */ public void setLowerAngle(float a) { if (m_joint != null) { ((RevoluteJoint)m_joint).m_lowerAngle = a; } m_lowerAngle = a; } /** * Set the highest angle allowed. This property only has effect if the {@code enableLimit} has been set to {@code true} using {@link #setEnableLimit(boolean)}. * * @param a highest angle allowed in radians */ public void setUpperAngle(float a) { if (m_joint != null) { ((RevoluteJoint)m_joint).m_upperAngle = a; } m_upperAngle = a; } /** * Set limits to the allowed rotation of one body respect to the other. If set to {@code true} the limits imposed using {@link #setLowerAngle(float) setLowerAngle} and {@link #setUpperAngle(float) setLowerAngle} are enforced. * * @param value if {@code true} the bodies will be able to rotate around the anchor only between certain limits */ public void setEnableLimit(boolean value) { if (m_joint != null) { ((RevoluteJoint)m_joint).m_enableLimit = value; } m_enableLimit = value; } /** * Set the desired rotation speed of the joint. This property only has effect if the {@code enableMotor} has been set to {@code true} using {@link #setEnableMotor(boolean)}. The speed is given in radians per second. * * @param a the desired speed in radians per second */ public void setMotorSpeed(float a) { if (m_joint != null) { ((RevoluteJoint)m_joint).m_motorSpeed = a; } m_motorSpeed = a; } /** * Set the maximum torque that the joint's motor can apply in order to acheive the desired speed. This property only has effect if the {@code enableMotor} has been set to {@code true} using {@link #setEnableMotor(boolean)}. * * @param a the maximum torque of the joint's motor */ public void setMaxMotorTorque(float a) { if (m_joint != null) { ((RevoluteJoint)m_joint).m_maxMotorTorque = a; } m_maxMotorTorque = a; } /** * Set the state of the motor in order to generate a rotation force (torque) on the joint. If set to {@code true} the desired motor speed, set using {@link #setMotorSpeed(float) setMotorSpeed}, will try to be matched using a motor with a maximum rotation force (torque) set using {@link #setMaxMotorTorque(float) setMaxMotorTorque}. * * @param value if {@code true} the joint will receive the rotation force (torque) of a motor */ public void setEnableMotor(boolean value) { if (m_joint != null) { ((RevoluteJoint)m_joint).m_enableMotor = value; } m_enableMotor = value; } /** * Sets the position of the anchor of the joint around which the bodies rotate. This position is given global coordinates, relative to the center of the canvas. * * @param x the horizontal coordinate of the anchor in global coordinates, relative to the center of the canvas * @param y the vertical coordinate of the anchor in global coordinates, relative to the center of the canvas */ public void setAnchor(float x, float y) { if (m_joint != null) { ((RevoluteJoint)m_joint).getAnchor2().set(Fisica.screenToWorld(x), Fisica.screenToWorld(y)); } m_anchor = Fisica.screenToWorld(x, y); updateLocalAnchors(); } /** * Get the horizontal coordinate of the anchor of the joint around which the bodies can rotate. This position is given global coordinates, relative to the center of the canvas. * * @return the horizontal coordinate of the anchor in global coordinates, relative to the center of the canvas */ public float getAnchorX() { if (m_joint != null) { return Fisica.worldToScreen(m_joint.getAnchor2()).x; } return Fisica.worldToScreen(m_anchor.x); } /** * Get the vertical coordinate of the anchor of the joint around which the bodies can rotate. This position is given global coordinates, relative to the center of the canvas. * * @return the vertical coordinate of the anchor in global coordinates, relative to the center of the canvas */ public float getAnchorY() { if (m_joint != null) { return Fisica.worldToScreen(m_joint.getAnchor2()).y; } return Fisica.worldToScreen(m_anchor.y); } public void setReferenceAngle(float ang) { m_referenceAngle = ang; } public void draw(PGraphics applet){ preDraw(applet); applet.line(getAnchorX(), getAnchorY(), getBody1().getX(), getBody1().getY()); applet.line(getAnchorX(), getAnchorY(), getBody2().getX(), getBody2().getY()); applet.ellipse(getAnchorX(), getAnchorY(), 10, 10); postDraw(applet); } public void drawDebug(PGraphics applet){ preDrawDebug(applet); applet.line(getAnchorX(), getAnchorY(), getBody1().getX(), getBody1().getY()); applet.line(getAnchorX(), getAnchorY(), getBody2().getX(), getBody2().getY()); applet.ellipse(getAnchorX(), getAnchorY(), 10, 10); postDrawDebug(applet); } }
3e049643535057bacd2938c9ccd82d0434c414b4
2,468
java
Java
app/src/main/java/adapter/HighScoreAdapter.java
DenhiHuynh/Four-in-a-row
f2d4a1c2276eb25b2745804df83cfad9f13eea5c
[ "Apache-2.0" ]
null
null
null
app/src/main/java/adapter/HighScoreAdapter.java
DenhiHuynh/Four-in-a-row
f2d4a1c2276eb25b2745804df83cfad9f13eea5c
[ "Apache-2.0" ]
null
null
null
app/src/main/java/adapter/HighScoreAdapter.java
DenhiHuynh/Four-in-a-row
f2d4a1c2276eb25b2745804df83cfad9f13eea5c
[ "Apache-2.0" ]
null
null
null
29.73494
84
0.655592
1,928
package adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.denhihuynh.connectfour.R; import java.util.List; import model.HighScore; /** * Adapter to populate the highscore listview. */ public class HighScoreAdapter extends BaseAdapter { private LayoutInflater mInflater; private List<HighScore> highScores; public HighScoreAdapter(Context context, List<HighScore> highScores){ mInflater = LayoutInflater.from(context); this.highScores = highScores; } @Override public int getCount() { return highScores.size(); } @Override public Object getItem(int position) { return highScores.get(position); } @Override public long getItemId(int position) { return position; } /** * Creating the rowlayout for each entry in highscores. * @param position which position in the highscores list to populate. * @param convertView which view to inflate as row layout. * @param parent the view to insert row layout into. * @return */ @Override public View getView(int position, View convertView, ViewGroup parent) { View view; ViewHolder holder; if(convertView == null) { view = mInflater.inflate(R.layout.row_layout_highscores, parent, false); holder = new ViewHolder(); holder.playerName = (TextView) view.findViewById(R.id.playerName); holder.wins = (TextView) view.findViewById(R.id.wins); holder.draws = (TextView) view.findViewById(R.id.draws); holder.losses = (TextView) view.findViewById(R.id.losses); view.setTag(holder); } else { view = convertView; holder = (ViewHolder)view.getTag(); } HighScore highScore = highScores.get(position); holder.playerName.setText(highScore.getPlayerName()); holder.wins.setText("W: " + Integer.toString(highScore.getWins())); holder.draws.setText("D: " + Integer.toString(highScore.getDraws())); holder.losses.setText("L: " + Integer.toString(highScore.getLosses())); return view; } /** * Class to use view holder pattern. */ private class ViewHolder { public TextView playerName, wins, draws, losses; } }
3e0497e78ee1edb55e8328504c946279056195c3
650
java
Java
src/Escena1.java
mjaque/Kay
a6c819af93f498984cb45a445cdabf34d5478fe3
[ "Unlicense" ]
1
2019-03-29T16:57:15.000Z
2019-03-29T16:57:15.000Z
src/Escena1.java
mjaque/Kay
a6c819af93f498984cb45a445cdabf34d5478fe3
[ "Unlicense" ]
8
2019-03-29T17:05:52.000Z
2019-04-14T10:06:06.000Z
src/Escena1.java
mjaque/Kay
a6c819af93f498984cb45a445cdabf34d5478fe3
[ "Unlicense" ]
null
null
null
26
115
0.735385
1,929
import javafx.scene.Group; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; public class Escena1 extends Scene { // Atributos de la Escena static final Group RAIZ = new Group(); static final Image IMAGEN = new Image(Escena1.class.getClassLoader().getResourceAsStream("recursos/imagen1.png")); public Escena1() { super (RAIZ); ImageView iv = new ImageView(IMAGEN); RAIZ.getChildren().add(iv); Jugador player = new Jugador(); player.setX(100); player.setY(100); player.setFitWidth(60); player.setFitHeight(60); RAIZ.getChildren().add(player); } }
3e0497f51dbd1a5054956a0c6edf276c692a2410
6,013
java
Java
app/src/main/java/com/tianlb/driverpos/common/ChatHelper.java
lebincn/DriverPos
4e8dd991f198b2f505b868ec6471f1cce48a46bd
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/tianlb/driverpos/common/ChatHelper.java
lebincn/DriverPos
4e8dd991f198b2f505b868ec6471f1cce48a46bd
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/tianlb/driverpos/common/ChatHelper.java
lebincn/DriverPos
4e8dd991f198b2f505b868ec6471f1cce48a46bd
[ "Apache-2.0" ]
null
null
null
33.405556
112
0.613837
1,930
package com.tianlb.driverpos.common; import android.util.Log; import com.easemob.EMCallBack; import com.easemob.EMError; import com.easemob.chat.CmdMessageBody; import com.easemob.chat.EMChatManager; import com.easemob.chat.EMContactManager; import com.easemob.chat.EMConversation; import com.easemob.chat.EMMessage; import com.easemob.chat.LocationMessageBody; import com.easemob.chat.TextMessageBody; import com.easemob.exceptions.EaseMobException; import java.util.List; /** * 发送消息助手 */ public class ChatHelper { private static final String TAG = "ChatHelper"; /** * 注册用户并登录 * * @param username */ public static boolean register(String username) { boolean blnRet = false; // try { // EMClient.getInstance().createAccount(username, Constant.DEF_PASSWORD); // blnRet = true; // } catch (HyphenateException e) { // e.printStackTrace(); // } try { EMChatManager.getInstance().createAccountOnServer(username, Constant.DEF_PASSWORD); blnRet = true; } catch (EaseMobException e) { if (e.getErrorCode() == EMError.USER_ALREADY_EXISTS) { blnRet = true; } e.printStackTrace(); } return blnRet; } /** * 添加管理员为好友(只有管理员不是自己好友时才添加) */ public static void addAdminContact() { // try { // if (isAdminfriends()) { // EMClient.getInstance().contactManager().addContact(Constant.ADMIN_NAME, "我是司机,我要向你定时报告位置信息。"); // } // } catch (HyphenateException e) { // e.printStackTrace(); // } Log.i(TAG, "addAdminContact"); try { if (!isAdminfriends()) { EMContactManager.getInstance().addContact(Constant.ADMIN_NAME, "我是司机,我要向你定时报告位置信息。"); } } catch (EaseMobException e) { e.printStackTrace(); } } /** * 检查管理员是否为自己的好友 * * @return true:管理员为自己的好友,false:管理员不是自己的好友 */ public static boolean isAdminfriends() { boolean blnRet = false; try { //List<String> usernames = EMClient.getInstance().contactManager().getAllContactsFromServer(); List<String> usernames = EMContactManager.getInstance().getContactUserNames(); if (usernames != null) { Log.i(TAG, usernames.toString()); for (String userName : usernames) { if (Constant.ADMIN_NAME.equalsIgnoreCase(userName)) { blnRet = true; break; } } } } catch (EaseMobException e) { e.printStackTrace(); } return blnRet; } /** * 发送自己的当前位置给管理员 */ public static void sendLocationPosInfo(double longitude, double latitude, String locationAddress) { EMConversation conversation = EMChatManager.getInstance().getConversation(Constant.ADMIN_NAME); // System.out.println("****** In sendLocationPosInfo ***********"); // System.out.println("longitude = " + longitude); // System.out.println("latitude = " + latitude); // System.out.println("locationAddress = " + locationAddress); // 正常处理,发送位置信息 // TODO: 在上报内容中加入司机信息 EMMessage message = EMMessage.createSendMessage(EMMessage.Type.LOCATION); LocationMessageBody locBody = new LocationMessageBody(locationAddress, latitude, longitude); message.addBody(locBody); message.setReceipt(Constant.ADMIN_NAME); conversation.addMessage(message); EMChatManager.getInstance().sendMessage(message, new EMCallBack() { @Override public void onSuccess() { Log.i(TAG, "sendLocationPosInfo onSuccess"); } @Override public void onError(int i, String s) { Log.i(TAG, "sendLocationPosInfo onError:" + s); } @Override public void onProgress(int i, String s) { Log.i(TAG, "sendLocationPosInfo onProgress:" + s); } }); } /** * 发送取得指定用户的位置信息 * * @param toUsername 目标用户名 */ public static void sendGetLocationPositionCmd(String toUsername) { // EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD); // EMCmdMessageBody cmdBody = new EMCmdMessageBody(Constant.GET_LOCATION_POSITION_CMD); // cmdMsg.setReceipt(toUsername); // cmdMsg.addBody(cmdBody); // EMClient.getInstance().chatManager().sendMessage(cmdMsg); EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD); CmdMessageBody cmdBody = new CmdMessageBody(Constant.GET_LOCATION_POSITION_CMD); cmdMsg.setReceipt(toUsername); cmdMsg.addBody(cmdBody); EMChatManager.getInstance().sendMessage(cmdMsg, null); } /** * 发送设置上报位置信息的时间间隔命令 * * @param toUsername 目标用户名 * @param interval 时间间隔(分钟) */ public static void sendSetUpPosIntervalCmd(String toUsername, long interval) { // EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD); // HashMap<String, String> paramsMap = new HashMap<String, String>(); // paramsMap.put("interval", String.valueOf(interval)); // EMCmdMessageBody cmdBody = new EMCmdMessageBody(Constant.SET_UP_POS_INTERVAL_CMD, paramsMap); // cmdMsg.setReceipt(toUsername); // cmdMsg.addBody(cmdBody); // EMClient.getInstance().chatManager().sendMessage(cmdMsg); EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD); CmdMessageBody cmdBody = new CmdMessageBody(Constant.SET_UP_POS_INTERVAL_CMD); cmdMsg.setReceipt(toUsername); cmdMsg.addBody(cmdBody); cmdMsg.setAttribute("interval", String.valueOf(interval)); EMChatManager.getInstance().sendMessage(cmdMsg, null); } }
3e049858179e1ad3de8dead4396da797cfba7a16
292
java
Java
A03.DesignPattern/B01.TheZenOfDesignPatterns/src/main/java/com/book/study/zen/chapter22/demob/Client.java
huaxueyihao/NoteOfStudy
061e62c97f4fa04fa417fd08ecf1dab361c20b87
[ "Apache-2.0" ]
null
null
null
A03.DesignPattern/B01.TheZenOfDesignPatterns/src/main/java/com/book/study/zen/chapter22/demob/Client.java
huaxueyihao/NoteOfStudy
061e62c97f4fa04fa417fd08ecf1dab361c20b87
[ "Apache-2.0" ]
2
2020-05-12T02:05:50.000Z
2022-01-12T23:04:55.000Z
A03.DesignPattern/B01.TheZenOfDesignPatterns/src/main/java/com/book/study/zen/chapter22/demob/Client.java
huaxueyihao/NoteOfStudy
061e62c97f4fa04fa417fd08ecf1dab361c20b87
[ "Apache-2.0" ]
null
null
null
16.222222
44
0.585616
1,931
package com.book.study.zen.chapter22.demob; public class Client { public static void main(String[] args) { // 定义出韩非子 HanFeiZi hanFeiZi = new HanFeiZi(); // 然后我们看看韩非子在干什么 hanFeiZi.haveBreakfast(); // 韩非子娱乐了 hanFeiZi.haveFun(); } }
3e04996c8d107809b85929c0f9b25aed6d2f1698
5,188
java
Java
src/main/java/org/microbean/servicebroker/api/command/ProvisionServiceInstanceCommand.java
ljnelson/microbean-service-broker-api
2c8c645bfd7c77dd5579e80037fb5acb325c2bce
[ "Apache-2.0" ]
2
2017-11-16T19:20:12.000Z
2017-11-25T13:50:16.000Z
src/main/java/org/microbean/servicebroker/api/command/ProvisionServiceInstanceCommand.java
microbean/microbean-service-broker-api
2c8c645bfd7c77dd5579e80037fb5acb325c2bce
[ "Apache-2.0" ]
2
2017-11-16T19:20:08.000Z
2017-12-19T00:43:59.000Z
src/main/java/org/microbean/servicebroker/api/command/ProvisionServiceInstanceCommand.java
microbean/microbean-service-broker-api
2c8c645bfd7c77dd5579e80037fb5acb325c2bce
[ "Apache-2.0" ]
null
null
null
43.596639
109
0.588281
1,932
/* -*- mode: Java; c-basic-offset: 2; indent-tabs-mode: nil; coding: utf-8-unix -*- * * Copyright © 2017 MicroBean. * * 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.microbean.servicebroker.api.command; import java.net.URI; import java.util.Map; import java.util.Objects; // import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; public class ProvisionServiceInstanceCommand extends AbstractServiceInstanceMutatingCommand { private final String organizationGuid; private final String spaceGuid; public ProvisionServiceInstanceCommand(final String instanceId, @NotNull /* @NotEmpty */ final String serviceId, @NotNull /* @NotEmpty */ final String planId, final Map<? extends String, ?> parameters, @NotNull /* @NotEmpty */ final String organizationGuid, @NotNull /* @NotEmpty */ final String spaceGuid) { this(instanceId, serviceId, planId, null, false, organizationGuid, spaceGuid, parameters); } public ProvisionServiceInstanceCommand(final String instanceId, @NotNull /* @NotEmpty */ final String serviceId, @NotNull /* @NotEmpty */ final String planId, final Map<? extends String, ?> parameters, final boolean acceptsIncomplete, @NotNull /* @NotEmpty */ final String organizationGuid, @NotNull /* @NotEmpty */ final String spaceGuid) { this(instanceId, serviceId, planId, null, acceptsIncomplete, organizationGuid, spaceGuid, parameters); } public ProvisionServiceInstanceCommand(final String instanceId, @NotNull /* @NotEmpty */ final String serviceId, @NotNull /* @NotEmpty */ final String planId, final Map<? extends String, ?> context, @NotNull /* @NotEmpty */ final String organizationGuid, @NotNull /* @NotEmpty */ final String spaceGuid, final Map<? extends String, ?> parameters) { this(instanceId, serviceId, planId, context, false, organizationGuid, spaceGuid, parameters); } public ProvisionServiceInstanceCommand(final String instanceId, @NotNull /* @NotEmpty */ final String serviceId, @NotNull /* @NotEmpty */ final String planId, final Map<? extends String, ?> context, final boolean acceptsIncomplete, @NotNull /* @NotEmpty */ final String organizationGuid, @NotNull /* @NotEmpty */ final String spaceGuid, final Map<? extends String, ?> parameters) { super(instanceId, serviceId, planId, parameters, acceptsIncomplete); if (!Boolean.getBoolean("org.microbean.servicebroker.api.lenient")) { Objects.requireNonNull(serviceId, () -> "serviceId must not be null"); Objects.requireNonNull(planId, () -> "planId must not be null"); Objects.requireNonNull(organizationGuid, () -> "organizationGuid must not be null"); Objects.requireNonNull(spaceGuid, () -> "spaceGuid must not be null"); } this.organizationGuid = organizationGuid; this.spaceGuid = spaceGuid; } public final String getOrganizationGuid() { return this.organizationGuid; } public final String getSpaceGuid() { return this.spaceGuid; } public static class Response extends org.microbean.servicebroker.api.command.AbstractProvisioningResponse { private final URI dashboardUri; public Response() { super(null); this.dashboardUri = null; } public Response(final URI dashboardUri) { super(null); this.dashboardUri = dashboardUri; } public Response(@NotNull /* @NotEmpty */ final String operation) { this(null, operation); } public Response(final URI dashboardUri, @NotNull /* @NotEmpty */ final String operation) { super(operation); this.dashboardUri = dashboardUri; } public final URI getDashboardUri() { return this.dashboardUri; } } }
3e0499e9f7a4959e5a95b8d6263ab37261933665
5,513
java
Java
com.ld.net.spider/src/main/java/io/spider/meta/SpiderOtherMetaConstant.java
2014shijina2014/io.spider
8c201458f3d86d447019ccb237cfff824778fd96
[ "Apache-2.0" ]
8
2018-11-01T03:37:20.000Z
2021-12-29T10:37:57.000Z
com.ld.net.spider/src/main/java/io/spider/meta/SpiderOtherMetaConstant.java
2014shijina2014/io.spider
8c201458f3d86d447019ccb237cfff824778fd96
[ "Apache-2.0" ]
null
null
null
com.ld.net.spider/src/main/java/io/spider/meta/SpiderOtherMetaConstant.java
2014shijina2014/io.spider
8c201458f3d86d447019ccb237cfff824778fd96
[ "Apache-2.0" ]
6
2018-10-02T19:03:22.000Z
2021-05-08T10:05:00.000Z
34.879747
96
0.772092
1,933
/** * Licensed under the Apache License, Version 2.0 */ package io.spider.meta; import java.net.InetAddress; import java.net.UnknownHostException; /** * * spider 通信中间件 * @author [email protected] * {@link} http://www.cnblogs.com/zhjh256 */ public final class SpiderOtherMetaConstant { public static final String NODE_NAME_LOCALSERVICE = "spider.localService"; /** * 配置文件中插件名称 */ public static final String PLUGIN_ID_LOCALSERVICE = "spider.localService"; public static final String PLUGIN_ID_CHANNEL = "spider.channel"; public static final String PLUGIN_ID_FILTER = "spider.filter"; public static final String PLUGIN_ID_CUSTOM = "spider.customPlugin"; public static final String SPIDER_RT_ROLE_NP = "np"; public static final String SPIDER_RT_ROLE_SC = "sc"; public static final String SPIDER_RT_ROLE_NB = "nb"; public static final String SPIDER_RT_ROLE_CLIENT = "client"; public static final String LOG_OUTPUT_FILE = "file"; public static final String LOG_OUTPUT_MONGODB = "mongodb"; public static final int DEFAULT_TIMEOUT_MS = 300000; public static final int HEARTBEAT_INTERVAL_MS = 60000; public static final int METRICS_REPORT_INTERVAL_MS = 300000; public static final int SLOW_LONG_TIME_MS = 300; public static final int RELIABLE_MAX_QUEUE_COUNT = 300; public static final String CONFIG_SEPARATOR = ";,"; public static final String SOCKET_ENDPOINT_AND_ERROR_CAUSE_SEP = ";"; public static final String CLUSTERNAME_AND_ADDRESS_SEP = ";"; public static final String ADDRESS_AND_PORT_SEP = ":"; public static final String BIZ_ERROR_NO_AND_INFO_SEP = "&~"; public static final String SPIDER_INTERNAL_MSG_HEARTBEAT = "drpcpqq"; public static final String SPIDER_INTERNAL_MSG_HANDSHAKE1_MSG = "spider"; public static final String SPIDER_INTERNAL_MSG_HANDSHAKE_ACK = "ack"; public static final String SPIDER_INTERNAL_MSG_HANDSHAKE2_AUTH = "auth"; public static final int DISPATCHER_RET_CODE_RETURN = 0; public static final int DISPATCHER_RET_CODE_CLOSE_CONNECTION = -1; public static final int DISPATCHER_RET_CODE_RETURN_AND_CLOSE = -2; public static final int DISPATCHER_RET_CODE_2SERVER_AUTH_PASS = 2; public static final int DISPATCHER_RET_CODE_NOP = 1; /** * 这个返回码正常情况下不会发生,除非主程序发生未捕获的运行时异常 */ public static final int DISPATCHER_RET_CODE_FATAL = 3; /** * 插件处理器容器返回值, 正常往后执行 */ public static final int DISPATCHER_RET_CODE_GO_ON = 4; /** * 插件处理器容器返回值, 正常往后,但并行处理 */ public static final int DISPATCHER_RET_CODE_PARALLEL = 5; public static final int DISPATCHER_RET_CODE_PRE_CHECK_FOR_OLD_OK = 10; /** * 插件处理器内部返回值, 发给下一个插件处理, 作为DISPATCHER_RET_CODE的子集 */ public static final int PLUGIN_RET_CODE_NEXT_PLUGIN = 6; /** * 插件处理器内部返回值, 发给指定插件处理, 作为DISPATCHER_RET_CODE的子集 */ public static final int PLUGIN_RET_CODE_SPECIFIED_PLUGIN = 7; /** * 报文类型1:请求;2:响应;3:广播; */ public static final char MSG_TYPE_RESP = '2'; public static final char MSG_TYPE_REQ = '1'; public static final char MSG_TYPE_BROADCAST = '3'; /** * 请求类别 1:业务请求; 0:spider内部管理请求 */ public static final char REQ_TYPE_BIZ = '1'; public static final char REQ_TYPE_SPIDER = '0'; public static final String DEFAULT_SYSTEM_ID = "qq"; public static final String DEFAULT_APP_VERSION = "qq.qq.qq"; public static final String DEFAULT_COMPANY_ID = "qqqqqq"; public static final char DEFAULT_SPIDER_PACKET_HEAD_PAD_CHAR = ' '; public static final String NOTHING = ""; public static final String SERVICE_DEFINE_TYPE_LD = "ld"; public static final String BEAN_NAME_LOCAL_REDIS_TEMPLATE = "localRedisTemplate"; public static final String BEAN_NAME_REMOTE_REDIS_TEMPLATE = "remoteRedisTemplate"; /** * 可信请求处理状态,INIT:未处理;FIN:完成; */ public static final String REQ_PROCESS_STATUS_INIT = "INIT"; public static final String REQ_PROCESS_STATUS_FINISH = "FIN"; /** * spider内核运行状态 */ public static final int SPIDER_KERNEL_STATUS_FORCE_RECOVER = -1; public static final int SPIDER_KERNEL_STATUS_SHUTDOWNING = 0; public static final int SPIDER_KERNEL_STATUS_STARTING = 1; public static final int SPIDER_KERNEL_STATUS_STARTED = 2; /** * 可信模式spider启动级别 */ public static final int SPIDER_RECOVER_LEVEL_NORMAL = 0; public static final int SPIDER_RECOVER_LEVEL_FROM_REMOTE = 1; /** * 线程名称 */ public static final String THREAD_NAME_RELIABLE_DISPATCHER_THREAD = "spider-reliable-dispatch"; public static final String THREAD_NAME_HEARTBEAT_THREAD = "spider-heartbeat"; public static final String THREAD_NAME_MONITOR_REPORT = "spider-metrics-uploader"; public static final String THREAD_NAME_SPIDER_BUSI_GROUP = "spider-busi-group"; public static final String THREAD_NAME_SPIDER_WORKER_GROUP = "spider-io-group"; public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; public static final String DATE_FORMAT = "yyyy-MM-dd"; public static final String DATETIMEMS_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; public static final String DATETIME_FORMAT_NUM = "yyyyMMddHHmmss"; public static final String DATE_FORMAT_NUM = "yyyyMMdd"; public static final String DATETIMEMS_FORMAT_NUM = "yyyyMMddHHmmssSSS"; public static final String TCP_DUMP_MODE_PUSH = "push"; public static final String TCP_DUMP_MODE_PULL = "pull"; public static final String SPIDER_AUTO_PROXY_SERVICE_PREFIX = "AutoProxy."; public static String HOSTNAME = null; static { InetAddress addr; try { addr = InetAddress.getLocalHost(); HOSTNAME = addr.getHostName(); } catch (UnknownHostException e) { e.printStackTrace(); } } }
3e049a72e46979209bf37d50c35f62d568b26b5b
8,468
java
Java
src/main/java/com/appslandia/plum/base/RequestAccessor.java
haducloc/appslandia-plum
2b9bee7abacda4bd486421181f564cd807f36f4d
[ "MIT" ]
423
2016-09-08T21:36:38.000Z
2021-03-01T19:15:17.000Z
src/main/java/com/appslandia/plum/base/RequestAccessor.java
haducloc/appslandia-plum
2b9bee7abacda4bd486421181f564cd807f36f4d
[ "MIT" ]
null
null
null
src/main/java/com/appslandia/plum/base/RequestAccessor.java
haducloc/appslandia-plum
2b9bee7abacda4bd486421181f564cd807f36f4d
[ "MIT" ]
1
2017-01-06T15:35:51.000Z
2017-01-06T15:35:51.000Z
32.209125
149
0.759178
1,934
// The MIT License (MIT) // Copyright © 2015 AppsLandia. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.appslandia.plum.base; import java.time.ZoneId; import java.util.Arrays; import java.util.Map; import java.util.stream.Stream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import com.appslandia.common.formatters.FormatterException; import com.appslandia.common.utils.AssertUtils; import com.appslandia.common.utils.ObjectUtils; import com.appslandia.common.utils.StringUtils; import com.appslandia.plum.utils.ServletUtils; /** * * @author <a href="mailto:[email protected]">Loc Ha</a> * */ public class RequestAccessor extends HttpServletRequestWrapper { public static final String PARAM_ACTION_TYPE = "actionType"; public RequestAccessor(HttpServletRequest request) { super(request); } public Stream<String> getParamValues(String name) { String[] values = getParameterValues(name); return Arrays.stream((values != null) ? values : StringUtils.EMPTY_ARRAY); } public <T> T findParam(String name, Class<T> targetType) throws IllegalArgumentException, FormatterException { String[] values = getParameterValues(name); if (values == null) { return null; } String value = Arrays.stream(values).filter(v -> !StringUtils.isNullOrEmpty(v)).findFirst().orElse(null); return ObjectUtils.cast(getRequestContext().getFormatterProvider().getFormatter(targetType).parse(value, getRequestContext().getFormatProvider())); } public <T> T getParamValue(String name, Class<T> targetType) throws IllegalArgumentException, FormatterException { String value = getParameter(name); if (value == null) { return null; } return ObjectUtils.cast(getRequestContext().getFormatterProvider().getFormatter(targetType).parse(value, getRequestContext().getFormatProvider())); } public boolean isGetOrHead() { return getRequestContext().isGetOrHead(); } public boolean isAjaxRequest() { return ServletUtils.isAjaxRequest(this); } public String getParamOrNull(String name) { return StringUtils.trimToNull(getParameter(name)); } public ZoneId getClientZone(ZoneId orZone) { ZoneId zone = ServletUtils.getClientZone(this); if (zone != null) return zone; return (orZone != null) ? orZone : ZoneId.systemDefault(); } public String getPref(String name) { PrefCookie prefs = ServletUtils.getPrefCookie(this); return (prefs != null) ? prefs.get(name) : null; } public String getPref(String name, String defaultValue) { PrefCookie prefs = ServletUtils.getPrefCookie(this); return (prefs != null) ? prefs.getString(name, defaultValue) : null; } public int getIntPref(String name, int defaultValue) { PrefCookie prefs = ServletUtils.getPrefCookie(this); return (prefs != null) ? prefs.getInt(name, defaultValue) : defaultValue; } public long getLongPref(String name, long defaultValue) { PrefCookie prefs = ServletUtils.getPrefCookie(this); return (prefs != null) ? prefs.getLong(name, defaultValue) : defaultValue; } public double getLongPref(String name, double defaultValue) { PrefCookie prefs = ServletUtils.getPrefCookie(this); return (prefs != null) ? prefs.getDouble(name, defaultValue) : defaultValue; } public boolean getBoolPref(String name, boolean defaultValue) { PrefCookie prefs = ServletUtils.getPrefCookie(this); return (prefs != null) ? prefs.getBool(name, defaultValue) : defaultValue; } public String getActionType() { return getParameter(PARAM_ACTION_TYPE); } public boolean isSaveAction() { return "save".equalsIgnoreCase(getActionType()); } public boolean isSaveContAction() { return "saveCont".equalsIgnoreCase(getActionType()); } public boolean isRemoveAction() { return "remove".equalsIgnoreCase(getActionType()); } public void store(String key, Object value) { setAttribute(key, value); } public void storeModel(Object model) { store(ServletUtils.REQUEST_ATTRIBUTE_MODEL, model); } public void storePagerModel(PagerModel pagerModel) { store(PagerModel.REQUEST_ATTRIBUTE_ID, pagerModel); } public void storeSortBag(SortBag sortBag) { store(SortBag.REQUEST_ATTRIBUTE_ID, sortBag); } public boolean isModuleAuthenticated() { return (getUserPrincipal() != null) && getUserPrincipal().getModule().equalsIgnoreCase(getRequestContext().getModule()); } @Override public UserPrincipal getUserPrincipal() { return ServletUtils.getUserPrincipal((HttpServletRequest) super.getRequest()); } public UserPrincipal getRequiredPrincipal() { return AssertUtils.assertStateNotNull(getUserPrincipal(), "getUserPrincipal() must be not null."); } public int getUserId() { return getRequiredPrincipal().getUserId(); } public boolean isUserInRoles(String... roles) { AssertUtils.assertHasElements(roles); return Arrays.stream(roles).anyMatch(role -> isUserInRole(role)); } public RequestContext getRequestContext() { return ServletUtils.getRequestContext(this); } public ModelState getModelState() { return ServletUtils.getModelState(this); } public TempData getTempData() { return ServletUtils.getTempData(this); } public Messages getMessages() { return ServletUtils.getMessages(this); } public Resources getResources() { return getRequestContext().getResources(); } public String res(String key) { return getResources().get(key); } public String res(String key, Object... params) { return getResources().get(key, params); } public String res(String key, Map<String, Object> params) { return getResources().get(key, params); } public void assertTrue(boolean expr) throws BadRequestException { if (!expr) { throw new BadRequestException(res(Resources.ERROR_BAD_REQUEST)).setTitleKey(Resources.ERROR_BAD_REQUEST); } } public <T> T assertNotNull(T value) throws BadRequestException { if (value == null) { throw new BadRequestException(res(Resources.ERROR_BAD_REQUEST)).setTitleKey(Resources.ERROR_BAD_REQUEST); } return value; } public void assertPositive(int value) throws BadRequestException { if (value <= 0) { throw new BadRequestException(res(Resources.ERROR_BAD_REQUEST)).setTitleKey(Resources.ERROR_BAD_REQUEST); } } public void assertValidFields(String... fieldNames) throws BadRequestException { if (!getModelState().areValid(fieldNames)) { throw new BadRequestException(res(Resources.ERROR_BAD_REQUEST)).setTitleKey(Resources.ERROR_BAD_REQUEST); } } public void assertValidModel() throws BadRequestException { if (!getModelState().isValid()) { throw new BadRequestException(res(Resources.ERROR_BAD_REQUEST)).setTitleKey(Resources.ERROR_BAD_REQUEST); } } public void assertInRoles(String[] roles) throws ForbiddenException { AssertUtils.assertHasElements(roles); if (!isUserInRoles(roles)) { throw new ForbiddenException(res(Resources.ERROR_FORBIDDEN)).setTitleKey(Resources.ERROR_FORBIDDEN); } } public void assertForbidden(boolean expr) throws ForbiddenException { if (!expr) { throw new ForbiddenException(res(Resources.ERROR_FORBIDDEN)).setTitleKey(Resources.ERROR_FORBIDDEN); } } public void assertNotFound(boolean expr) throws ForbiddenException { if (!expr) { throw new NotFoundException(res(Resources.ERROR_NOT_FOUND)).setTitleKey(Resources.ERROR_NOT_FOUND); } } @Override public String toString() { return "[" + getClass().getSimpleName() + "] " + getRequest(); } }
3e049bbc112c82659b1414f78690538571281447
20,231
java
Java
app/src/main/java/com/imaginers/onirban/home/usershop/ManageStore.java
onirban27/eshop
38351ce60840b907e1971dc0f0bfd951a396ec34
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/imaginers/onirban/home/usershop/ManageStore.java
onirban27/eshop
38351ce60840b907e1971dc0f0bfd951a396ec34
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/imaginers/onirban/home/usershop/ManageStore.java
onirban27/eshop
38351ce60840b907e1971dc0f0bfd951a396ec34
[ "Apache-2.0" ]
null
null
null
38.461977
119
0.614206
1,935
package com.imaginers.onirban.home.usershop; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.imaginers.onirban.home.MainActivity; import com.imaginers.onirban.home.R; import com.imaginers.onirban.home.Storage.MyUploadService; import com.imaginers.onirban.home.product.helper.ProductServices; import com.imaginers.onirban.home.product.model.Product; import com.imaginers.onirban.home.product.model.Products; import com.imaginers.onirban.home.rest.RetrofitInstance; import java.util.ArrayList; import okhttp3.OkHttpClient; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class ManageStore extends AppCompatActivity implements AdminProductsAdapter.MyDialogItemClickListener { public static final String EXTRA_POSITION = "position"; private Context mContext; private RecyclerView recyclerView; private AdminProductsAdapter adapter; Double lat; Double lon; String storeId,storeName,storeImage; ImageView signBoard1,signBoard2; //upload private static final String TAG = "Storage#MainActivity"; private static final int RC_TAKE_PICTURE = 101; private static final String KEY_FILE_URI = "key_file_uri"; private static final String KEY_DOWNLOAD_URL = "key_download_url"; private BroadcastReceiver mBroadcastReceiver; private ProgressDialog mProgressDialog; public Uri mDownloadUrl = null; public Uri mFileUri = null; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manage_store); mContext = this; Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); Intent intent = getIntent(); storeName = intent.getStringExtra(MainActivity.EXTRA_STORENAME); storeId = intent.getStringExtra(MainActivity.EXTRA_STOREID); storeImage = intent.getStringExtra(MainActivity.EXTRA_STOREIMAGE); lat = intent.getDoubleExtra(MainActivity.EXTRA_LAT,0.0); lon = intent.getDoubleExtra(MainActivity.EXTRA_LON,0.0); signBoard1 = findViewById(R.id.productAddImageView); signBoard2 = findViewById(R.id.productNaImageView); initCollapsingToolbar(); recyclerView = findViewById(R.id.product_recycler_view); final FloatingActionButton fab_add = findViewById(R.id.fab_add); fab_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showProductDialog(savedInstanceState); } }); prepareProducts(); // Restore instance state if (savedInstanceState != null) { mFileUri = savedInstanceState.getParcelable(KEY_FILE_URI); mDownloadUrl = savedInstanceState.getParcelable(KEY_DOWNLOAD_URL); } onNewIntent(getIntent()); // Local broadcast receiver mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "onReceive:" + intent); hideProgressDialog(); switch (intent.getAction()) { case MyUploadService.UPLOAD_COMPLETED: case MyUploadService.UPLOAD_ERROR: onUploadResultIntent(intent); break; } } }; } public void prepareProducts() { /*Create handle for the RetrofitInstance interface*/ ProductServices service = RetrofitInstance.getRetrofitInstance(). create(ProductServices.class); /*Call the method with parameter in the interface to get the employee data*/ Call<Products> call = service.getProductData(storeId); /*Log the URL called*/ Log.wtf("URL Called", call.request().url() + ""); call.enqueue(new Callback<Products>() { @Override public void onResponse(Call<Products> call, Response<Products> response) { if (response.body() != null) { generateProductList(getApplicationContext(),response.body().getProducts()); Log.wtf("productResponse", response.body().getMessage() + ""); }else { Toast.makeText(ManageStore.this, "No Products found! "+response.body(), Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<Products> call, Throwable t) { Toast.makeText(ManageStore.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show(); } }); } /** * Initializing collapsing toolbar * Will show and hide the toolbar title on scroll */ private void initCollapsingToolbar() { final CollapsingToolbarLayout collapsingToolbar = findViewById(R.id.collapsing_toolbar); // Set title of Detail page collapsingToolbar.setTitle(storeName); AppBarLayout appBarLayout = findViewById(R.id.appbar); appBarLayout.setExpanded(true); ImageView placePicture = findViewById(R.id.storeCoverImage); Glide.with(this).load(storeImage).into(placePicture); // hiding & showing the title when toolbar expanded & collapsed appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() { boolean isShow = false; int scrollRange = -1; @Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { int position = getIntent().getIntExtra(EXTRA_POSITION, 0); if (scrollRange == -1) { scrollRange = appBarLayout.getTotalScrollRange(); } if (scrollRange + verticalOffset == 0) { collapsingToolbar.setTitle(storeName); isShow = true; } else if (isShow) { collapsingToolbar.setTitle(storeName); isShow = true; } } }); } private void showProductDialog(Bundle savedInstanceState) { final Dialog dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before dialog.setContentView(R.layout.dialog_add_product); dialog.setCancelable(true); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.WRAP_CONTENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; final ImageView imageView = dialog.findViewById(R.id.productImage); final TextView url = dialog.findViewById(R.id.pictureDownloadUri); final EditText name = dialog.findViewById(R.id.et_product_name); final EditText price = dialog.findViewById(R.id.et_product_price); final EditText quantity = dialog.findViewById(R.id.et_product_quantity); final EditText description = dialog.findViewById(R.id.et_product_description); // Restore instance state if (savedInstanceState != null) { mFileUri = savedInstanceState.getParcelable(KEY_FILE_URI); mDownloadUrl = savedInstanceState.getParcelable(KEY_DOWNLOAD_URL); } onNewIntent(getIntent()); (dialog.findViewById(R.id.image_upload_button)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { launchCamera(); } }); // Download URL and Download button if (mDownloadUrl != null) { String myUrl = mDownloadUrl.toString(); Glide.with(getBaseContext()) .load(myUrl) .into(imageView); imageView.setVisibility(View.VISIBLE); } (dialog.findViewById(R.id.bt_cancel)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); ( dialog.findViewById(R.id.bt_submit)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Product product = new Product( name.getText().toString(), quantity.getText().toString(), price.getText().toString(), description.getText().toString(), mDownloadUrl.toString(), "dress", lon.toString(), lat.toString(), storeId); OkHttpClient client = new OkHttpClient(); Retrofit.Builder builder = new Retrofit.Builder() .baseUrl("http://huthat.net/") .addConverterFactory(GsonConverterFactory.create()) .client(client); Retrofit retrofit = builder.build(); ProductServices service = retrofit.create(ProductServices.class); Call<Product> call = service.insertData(product); call.enqueue(new Callback<Product>() { @Override public void onResponse(Call<Product> call, Response<Product> response) { Log.d("received", "onResponse: " + response.body().getStatus()); prepareProducts(); Toast.makeText(ManageStore.this, response.body().getStatus() , Toast.LENGTH_LONG).show(); } @Override public void onFailure(Call<Product> call, Throwable t) { Log.i("Hello", "" + t); Toast.makeText(ManageStore.this, "Throwable" + t, Toast.LENGTH_LONG).show(); } }); dialog.dismiss(); } }); dialog.show(); dialog.getWindow().setAttributes(lp); } private void generateProductList(Context mContext, ArrayList<Product> proDataList) { recyclerView = findViewById(R.id.product_recycler_view); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(ManageStore.this); recyclerView.setLayoutManager(layoutManager); if(proDataList != null) { if(proDataList.size() > 0) { adapter = new AdminProductsAdapter(mContext, proDataList, this); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(adapter); signBoard1.setVisibility(View.GONE); signBoard2.setVisibility(View.GONE); } }else { Toast.makeText(mContext, "Product is null", Toast.LENGTH_SHORT).show(); signBoard1.setVisibility(View.VISIBLE); signBoard2.setVisibility(View.VISIBLE); } } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); // Check if this Activity was launched by clicking on an upload notification if (intent.hasExtra(MyUploadService.EXTRA_DOWNLOAD_URL)) { onUploadResultIntent(intent); } } @Override public void onStart() { super.onStart(); // Register receiver for uploads and downloads LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this); manager.registerReceiver(mBroadcastReceiver, MyUploadService.getIntentFilter()); } @Override public void onStop() { super.onStop(); // Unregister download receiver LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver); } @Override public void onSaveInstanceState(Bundle out) { super.onSaveInstanceState(out); out.putParcelable(KEY_FILE_URI, mFileUri); out.putParcelable(KEY_DOWNLOAD_URL, mDownloadUrl); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data); if (requestCode == RC_TAKE_PICTURE) { if (resultCode == RESULT_OK) { mFileUri = data.getData(); if (mFileUri != null) { uploadFromUri(mFileUri); } else { Log.w(TAG, "File URI is null"); } } else { Toast.makeText(this, "Taking picture failed.", Toast.LENGTH_SHORT).show(); } } } private void uploadFromUri(Uri fileUri) { Log.d(TAG, "uploadFromUri:src:" + fileUri.toString()); // Save the File URI mFileUri = fileUri; // Clear the last download, if any mDownloadUrl = null; // Start MyUploadService to upload the file, so that the file is uploaded // even if this Activity is killed or put in the background startService(new Intent(this, MyUploadService.class) .putExtra(MyUploadService.EXTRA_FILE_URI, fileUri) .setAction(MyUploadService.ACTION_UPLOAD)); // Show loading spinner showProgressDialog(getString(R.string.progress_uploading)); } private void launchCamera() { Log.d(TAG, "launchCamera"); // Pick an image from storage Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.setType("image/*"); startActivityForResult(intent, RC_TAKE_PICTURE); } private void onUploadResultIntent(Intent intent) { // Got a new intent from MyUploadService with a success or failure mDownloadUrl = intent.getParcelableExtra(MyUploadService.EXTRA_DOWNLOAD_URL); mFileUri = intent.getParcelableExtra(MyUploadService.EXTRA_FILE_URI); } private void showProgressDialog(String caption) { if (mProgressDialog == null) { mProgressDialog = new ProgressDialog(this); mProgressDialog.setIndeterminate(true); } mProgressDialog.setMessage(caption); mProgressDialog.show(); } private void hideProgressDialog() { if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } } //Dialog listeners public void onEditClickListener(final Product pProduct){ Toast.makeText(this, "clicked", Toast.LENGTH_SHORT).show(); final Dialog dialog = new Dialog(mContext); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before dialog.setContentView(R.layout.dialog_edit_product); dialog.setCancelable(true); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.WRAP_CONTENT; lp.height = WindowManager.LayoutParams.WRAP_CONTENT; final EditText name = dialog.findViewById(R.id.et_product_namee); final EditText price = dialog.findViewById(R.id.et_product_pricee); final EditText quantity = dialog.findViewById(R.id.et_product_quantityy); final EditText description = dialog.findViewById(R.id.et_product_descriptionn); name.setText(pProduct.getProductName() ); price.setText(pProduct.getPrice() ); quantity.setText(pProduct.getQuantity() ); description.setText(pProduct.getDescription() ); (dialog.findViewById(R.id.bt_cancel)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); ( dialog.findViewById(R.id.bt_submit)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Product product = new Product( pProduct.getProductId(), name.getText().toString(), quantity.getText().toString(), price.getText().toString(), description.getText().toString(), pProduct.getImage(), "dress", pProduct.getLon(), pProduct.getLat(), pProduct.getStoreId()); System.out.println(product.getProductId()+" "+pProduct.getProductId()); OkHttpClient client = new OkHttpClient(); Retrofit.Builder builder = new Retrofit.Builder() .baseUrl("http://huthat.net/api/") .addConverterFactory(GsonConverterFactory.create()) .client(client); Retrofit retrofit = builder.build(); ProductServices productServices = retrofit.create(ProductServices.class); Call<Product> call = productServices.upData(product); call.enqueue(new Callback<Product>() { @Override public void onResponse(Call<Product> call, Response<Product> response) { prepareProducts(); adapter.notifyDataSetChanged(); Toast.makeText(mContext, response.body().getStatus() , Toast.LENGTH_LONG).show(); } @Override public void onFailure(Call<Product> call, Throwable t) { Log.i("Hello", "" + t); Toast.makeText(mContext, "Throwable" + t, Toast.LENGTH_LONG).show(); } }); dialog.dismiss(); } }); dialog.show(); dialog.getWindow().setAttributes(lp); } public void onDeleteClickListener(final Product pProduct) { /*Create handle for the RetrofitInstance interface*/ ProductServices productServices = RetrofitInstance.getRetrofitInstance(). create(ProductServices.class); /*Call the method with parameter in the interface to get the employee data*/ Call<Product> call = productServices.delData(pProduct.getProductId()); call.enqueue(new Callback<Product>() { @Override public void onResponse(Call<Product> call, Response<Product> response) { if(response.isSuccessful()){ Toast.makeText(mContext, "response"+response.body().getStatus(), Toast.LENGTH_SHORT).show(); prepareProducts(); adapter.notifyDataSetChanged(); } } @Override public void onFailure(Call<Product> call, Throwable t) { Log.e("ERROR: ", t.getMessage()); Toast.makeText(mContext, "delete failed "+pProduct.getStatus(), Toast.LENGTH_SHORT).show(); } }); } }
3e049c09d6234b60bd21514c9a953833fe172ae7
1,940
java
Java
ivif-jee6-angularjs-impl/src/test/resources/ivif-expected-generated-sources/java/com/iorga/ivif/test/ws/LeftJoinComputerGridBaseWS.java
iorga-group/ivif
62794188934f029a4ea725f19c0ccb7265589c6b
[ "Apache-2.0" ]
1
2016-10-07T08:17:22.000Z
2016-10-07T08:17:22.000Z
ivif-jee6-angularjs-impl/src/test/resources/ivif-expected-generated-sources/java/com/iorga/ivif/test/ws/LeftJoinComputerGridBaseWS.java
iorga-group/ivif
62794188934f029a4ea725f19c0ccb7265589c6b
[ "Apache-2.0" ]
null
null
null
ivif-jee6-angularjs-impl/src/test/resources/ivif-expected-generated-sources/java/com/iorga/ivif/test/ws/LeftJoinComputerGridBaseWS.java
iorga-group/ivif
62794188934f029a4ea725f19c0ccb7265589c6b
[ "Apache-2.0" ]
null
null
null
35.272727
131
0.768557
1,936
package com.iorga.ivif.test.ws; import com.iorga.ivif.ja.Generated; import com.iorga.ivif.ja.GridSearchParam; import com.iorga.ivif.test.service.ComputerBaseService; import com.mysema.query.SearchResults; import java.lang.Integer; import java.lang.String; import javax.ejb.Stateless; import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.codehaus.jackson.annotate.JsonIgnoreProperties; @Path("/leftJoinComputerGrid") @Generated @Stateless public class LeftJoinComputerGridBaseWS { @Inject @Generated private ComputerBaseService computerBaseService; public static class LeftJoinComputerGridFilterResult { public Integer id; public String name; } public static class LeftJoinComputerGridSearchResult extends LeftJoinComputerGridFilterResult { public String __defaultProfile_description; public String __user_name; public LeftJoinComputerGridSearchResult() {} public LeftJoinComputerGridSearchResult(Integer id, String name, String __defaultProfile_description, String __user_name) { this.id = id; this.name = name; this.__defaultProfile_description = __defaultProfile_description; this.__user_name = __user_name; } } @JsonIgnoreProperties(ignoreUnknown = true) public static class LeftJoinComputerGridSearchFilter extends LeftJoinComputerGridFilterResult { } public static class LeftJoinComputerGridSearchParam extends GridSearchParam<LeftJoinComputerGridSearchFilter> {} @POST @Path("/search") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public SearchResults<LeftJoinComputerGridSearchResult> search(LeftJoinComputerGridSearchParam searchParam) { return computerBaseService.search(searchParam); } }
3e049d1ed092740b4c7c96d8ae2cbfd7211bc398
263
java
Java
src/main/java/org/age/zk/services/worker/event/ExitEvent.java
franc90/age-zk-starter
bef2ecb41b8ba96ba1e416e3dcde5720a3cbaf81
[ "MIT" ]
null
null
null
src/main/java/org/age/zk/services/worker/event/ExitEvent.java
franc90/age-zk-starter
bef2ecb41b8ba96ba1e416e3dcde5720a3cbaf81
[ "MIT" ]
null
null
null
src/main/java/org/age/zk/services/worker/event/ExitEvent.java
franc90/age-zk-starter
bef2ecb41b8ba96ba1e416e3dcde5720a3cbaf81
[ "MIT" ]
null
null
null
18.785714
52
0.711027
1,937
package org.age.zk.services.worker.event; import java.io.Serializable; public class ExitEvent implements Serializable { private static final long serialVersionUID = 1L; @Override public String toString() { return super.toString(); } }
3e049d33e44a2db5080fcb1bc54dbb1b72b4a78a
1,106
java
Java
JDBC/TPJDBCCDI11/src/fr/imie/DTO/UsagerDTO.java
imie-source/CDI-N-11-SHARE
d13a7f86d511af1d83d93e7f4243ad9844ce891d
[ "MIT" ]
3
2015-11-03T13:32:51.000Z
2017-09-19T17:25:51.000Z
JDBC/TPJDBCCDI11/src/fr/imie/DTO/UsagerDTO.java
imie-source/CDI-N-11-SHARE
d13a7f86d511af1d83d93e7f4243ad9844ce891d
[ "MIT" ]
null
null
null
JDBC/TPJDBCCDI11/src/fr/imie/DTO/UsagerDTO.java
imie-source/CDI-N-11-SHARE
d13a7f86d511af1d83d93e7f4243ad9844ce891d
[ "MIT" ]
null
null
null
16.757576
50
0.69349
1,938
/** * */ package fr.imie.DTO; import java.util.Date; /** * @author imie * */ public class UsagerDTO { private Integer id; private String nom; private String prenom; private Date dateNaiss; private Integer nbConnexion; private String email; private SiteDTO siteDTO; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getPrenom() { return prenom; } public void setPrenom(String prenom) { this.prenom = prenom; } public Date getDateNaiss() { return dateNaiss; } public void setDateNaiss(Date dateNaiss) { this.dateNaiss = dateNaiss; } public Integer getNbConnexion() { return nbConnexion; } public void setNbConnexion(Integer nbConnexion) { this.nbConnexion = nbConnexion; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public SiteDTO getSiteDTO() { return siteDTO; } public void setSiteDTO(SiteDTO siteDTO) { this.siteDTO = siteDTO; } }
3e049e0adf6212cb4976b530c757047479b21e2f
1,462
java
Java
aliyun-java-sdk-rdc/src/main/java/com/aliyuncs/rdc/transform/v20180816/AddProjectMembersResponseUnmarshaller.java
limfriend/aliyun-openapi-java-sdk
12d004883c6ad54456dbf6eb47c06a6d27b77977
[ "Apache-2.0" ]
3
2020-04-26T09:15:45.000Z
2020-05-09T03:10:26.000Z
aliyun-java-sdk-rdc/src/main/java/com/aliyuncs/rdc/transform/v20180816/AddProjectMembersResponseUnmarshaller.java
JingZiLa/aliyun-openapi-java-sdk
82f71ce8c45b1312dd7331abff29401d7c6f8ab2
[ "Apache-2.0" ]
null
null
null
aliyun-java-sdk-rdc/src/main/java/com/aliyuncs/rdc/transform/v20180816/AddProjectMembersResponseUnmarshaller.java
JingZiLa/aliyun-openapi-java-sdk
82f71ce8c45b1312dd7331abff29401d7c6f8ab2
[ "Apache-2.0" ]
null
null
null
44.30303
133
0.795486
1,939
/* * 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.aliyuncs.rdc.transform.v20180816; import com.aliyuncs.rdc.model.v20180816.AddProjectMembersResponse; import com.aliyuncs.transform.UnmarshallerContext; public class AddProjectMembersResponseUnmarshaller { public static AddProjectMembersResponse unmarshall(AddProjectMembersResponse addProjectMembersResponse, UnmarshallerContext _ctx) { addProjectMembersResponse.setRequestId(_ctx.stringValue("AddProjectMembersResponse.RequestId")); addProjectMembersResponse.setCode(_ctx.integerValue("AddProjectMembersResponse.Code")); addProjectMembersResponse.setData(_ctx.booleanValue("AddProjectMembersResponse.Data")); addProjectMembersResponse.setSuccess(_ctx.booleanValue("AddProjectMembersResponse.Success")); addProjectMembersResponse.setMessage(_ctx.stringValue("AddProjectMembersResponse.Message")); return addProjectMembersResponse; } }
3e049f2df22eb273549d6a411a51fc6c0b236243
1,714
java
Java
src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringNewlineDifference_create_Test.java
weissreto/assertj-core
d20f3d381960a5ad504e7be9c44e16464cd64b51
[ "Apache-2.0" ]
1
2020-11-24T09:39:24.000Z
2020-11-24T09:39:24.000Z
src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringNewlineDifference_create_Test.java
weissreto/assertj-core
d20f3d381960a5ad504e7be9c44e16464cd64b51
[ "Apache-2.0" ]
43
2020-11-02T07:26:38.000Z
2022-03-30T21:04:32.000Z
src/test/java/org/assertj/core/error/ShouldBeEqualIgnoringNewlineDifference_create_Test.java
weissreto/assertj-core
d20f3d381960a5ad504e7be9c44e16464cd64b51
[ "Apache-2.0" ]
1
2020-10-09T13:05:59.000Z
2020-10-09T13:05:59.000Z
42.85
118
0.677363
1,940
/* * 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 2012-2020 the original author or authors. */ package org.assertj.core.error; import static java.lang.String.format; import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.ShouldBeEqualIgnoringNewLineDifferences.shouldBeEqualIgnoringNewLineDifferences; import static org.assertj.core.presentation.StandardRepresentation.STANDARD_REPRESENTATION; import org.assertj.core.internal.TestDescription; import org.junit.jupiter.api.Test; class ShouldBeEqualIgnoringNewlineDifference_create_Test { @Test void should_create_error_message() { // GIVEN ErrorMessageFactory factory = shouldBeEqualIgnoringNewLineDifferences("foo", "bar"); // WHEN String message = factory.create(new TestDescription("Test"), STANDARD_REPRESENTATION); // THEN then(message).isEqualTo(format("[Test] %n" + "Expecting:%n" + " <\"foo\">%n" + "to be equal to:%n" + " <\"bar\">%n" + "ignoring newline differences ('\\r\\n' == '\\n')")); } }
3e049f68742676517c214793a12b1f29ad014758
15,703
java
Java
geode-core/src/main/java/org/apache/geode/internal/tcp/MsgOutputStream.java
nikochiko/geode
19f55add07d6a652911dc5a5e2116fcf7bf7b2f7
[ "Apache-2.0" ]
1,475
2016-12-06T06:10:53.000Z
2022-03-30T09:55:23.000Z
geode-core/src/main/java/org/apache/geode/internal/tcp/MsgOutputStream.java
nikochiko/geode
19f55add07d6a652911dc5a5e2116fcf7bf7b2f7
[ "Apache-2.0" ]
2,809
2016-12-06T19:24:26.000Z
2022-03-31T22:02:20.000Z
geode-core/src/main/java/org/apache/geode/internal/tcp/MsgOutputStream.java
Krishnan-Raghavan/geode
708588659751c1213c467f5b200b2c36952af563
[ "Apache-2.0", "BSD-3-Clause" ]
531
2016-12-06T05:48:47.000Z
2022-03-31T23:06:37.000Z
37.929952
100
0.650704
1,941
/* * 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.geode.internal.tcp; import java.io.IOException; import java.io.OutputStream; import java.io.UTFDataFormatException; import java.nio.ByteBuffer; import org.apache.geode.DataSerializer; import org.apache.geode.internal.ObjToByteArraySerializer; import org.apache.geode.internal.net.BufferPool; import org.apache.geode.internal.serialization.StaticSerialization; /** * MsgOutputStream should no longer be used except in Connection to do the handshake. Otherwise * MsgStreamer should always be used. * * @since GemFire 3.0 * */ public class MsgOutputStream extends OutputStream implements ObjToByteArraySerializer { private final ByteBuffer buffer; /** * The caller of this constructor is responsible for managing the allocated instance. */ public MsgOutputStream(int allocSize) { if (BufferPool.useDirectBuffers) { this.buffer = ByteBuffer.allocateDirect(allocSize); } else { this.buffer = ByteBuffer.allocate(allocSize); } this.buffer.position(Connection.MSG_HEADER_BYTES); } /** write the low-order 8 bits of the given int */ @Override public void write(int b) { buffer.put((byte) (b & 0xff)); } /** override OutputStream's write() */ @Override public void write(byte[] source, int offset, int len) { this.buffer.put(source, offset, len); } private int size() { return this.buffer.position() - Connection.MSG_HEADER_BYTES; } /** * write the header after the message has been written to the stream */ public void setMessageHeader(int msgType, int processorType, short msgId) { buffer.putInt(Connection.MSG_HEADER_SIZE_OFFSET, Connection.calcHdrSize(size())); buffer.put(Connection.MSG_HEADER_TYPE_OFFSET, (byte) (msgType & 0xff)); buffer.putShort(Connection.MSG_HEADER_ID_OFFSET, msgId); } public void reset() { this.buffer.clear(); this.buffer.position(Connection.MSG_HEADER_BYTES); } /** * gets the content ByteBuffer, ready for reading. The stream should not be written to past this * point until it has been reset. */ public ByteBuffer getContentBuffer() { buffer.flip(); return buffer; } // DataOutput methods /** * Writes a <code>boolean</code> value to this output stream. If the argument <code>v</code> is * <code>true</code>, the value <code>(byte)1</code> is written; if <code>v</code> is * <code>false</code>, the value <code>(byte)0</code> is written. The byte written by this method * may be read by the <code>readBoolean</code> method of interface <code>DataInput</code>, which * will then return a <code>boolean</code> equal to <code>v</code>. * * @param v the boolean to be written. * @exception IOException if an I/O error occurs. */ @Override public void writeBoolean(boolean v) throws IOException { write(v ? 1 : 0); } /** * Writes to the output stream the eight low- order bits of the argument <code>v</code>. The 24 * high-order bits of <code>v</code> are ignored. (This means that <code>writeByte</code> does * exactly the same thing as <code>write</code> for an integer argument.) The byte written by this * method may be read by the <code>readByte</code> method of interface <code>DataInput</code>, * which will then return a <code>byte</code> equal to <code>(byte)v</code>. * * @param v the byte value to be written. * @exception IOException if an I/O error occurs. */ @Override public void writeByte(int v) throws IOException { write(v); } /** * Writes two bytes to the output stream to represent the value of the argument. The byte values * to be written, in the order shown, are: * <p> * * <pre> * <code> * (byte)(0xff &amp; (v &gt;&gt; 8)) * (byte)(0xff &amp; v) * </code> * </pre> * <p> * The bytes written by this method may be read by the <code>readShort</code> method of interface * <code>DataInput</code> , which will then return a <code>short</code> equal to * <code>(short)v</code>. * * @param v the <code>short</code> value to be written. * @exception IOException if an I/O error occurs. */ @Override public void writeShort(int v) throws IOException { buffer.putShort((short) (v & 0xffff)); } /** * Writes a <code>char</code> value, wich is comprised of two bytes, to the output stream. The * byte values to be written, in the order shown, are: * <p> * * <pre> * <code> * (byte)(0xff &amp; (v &gt;&gt; 8)) * (byte)(0xff &amp; v) * </code> * </pre> * <p> * The bytes written by this method may be read by the <code>readChar</code> method of interface * <code>DataInput</code> , which will then return a <code>char</code> equal to * <code>(char)v</code>. * * @param v the <code>char</code> value to be written. * @exception IOException if an I/O error occurs. */ @Override public void writeChar(int v) throws IOException { buffer.putChar((char) v); } /** * Writes an <code>int</code> value, which is comprised of four bytes, to the output stream. The * byte values to be written, in the order shown, are: * <p> * * <pre> * <code> * (byte)(0xff &amp; (v &gt;&gt; 24)) * (byte)(0xff &amp; (v &gt;&gt; 16)) * (byte)(0xff &amp; (v &gt;&gt; &#32; &#32;8)) * (byte)(0xff &amp; v) * </code> * </pre> * <p> * The bytes written by this method may be read by the <code>readInt</code> method of interface * <code>DataInput</code> , which will then return an <code>int</code> equal to <code>v</code>. * * @param v the <code>int</code> value to be written. * @exception IOException if an I/O error occurs. */ @Override public void writeInt(int v) throws IOException { buffer.putInt(v); } /** * Writes a <code>long</code> value, which is comprised of eight bytes, to the output stream. The * byte values to be written, in the order shown, are: * <p> * * <pre> * <code> * (byte)(0xff &amp; (v &gt;&gt; 56)) * (byte)(0xff &amp; (v &gt;&gt; 48)) * (byte)(0xff &amp; (v &gt;&gt; 40)) * (byte)(0xff &amp; (v &gt;&gt; 32)) * (byte)(0xff &amp; (v &gt;&gt; 24)) * (byte)(0xff &amp; (v &gt;&gt; 16)) * (byte)(0xff &amp; (v &gt;&gt; 8)) * (byte)(0xff &amp; v) * </code> * </pre> * <p> * The bytes written by this method may be read by the <code>readLong</code> method of interface * <code>DataInput</code> , which will then return a <code>long</code> equal to <code>v</code>. * * @param v the <code>long</code> value to be written. * @exception IOException if an I/O error occurs. */ @Override public void writeLong(long v) throws IOException { buffer.putLong(v); } /** * Writes a <code>float</code> value, which is comprised of four bytes, to the output stream. It * does this as if it first converts this <code>float</code> value to an <code>int</code> in * exactly the manner of the <code>Float.floatToIntBits</code> method and then writes the * <code>int</code> value in exactly the manner of the <code>writeInt</code> method. The bytes * written by this method may be read by the <code>readFloat</code> method of interface * <code>DataInput</code>, which will then return a <code>float</code> equal to <code>v</code>. * * @param v the <code>float</code> value to be written. * @exception IOException if an I/O error occurs. */ @Override public void writeFloat(float v) throws IOException { buffer.putFloat(v); } /** * Writes a <code>double</code> value, which is comprised of eight bytes, to the output stream. It * does this as if it first converts this <code>double</code> value to a <code>long</code> in * exactly the manner of the <code>Double.doubleToLongBits</code> method and then writes the * <code>long</code> value in exactly the manner of the <code>writeLong</code> method. The bytes * written by this method may be read by the <code>readDouble</code> method of interface * <code>DataInput</code>, which will then return a <code>double</code> equal to <code>v</code>. * * @param v the <code>double</code> value to be written. * @exception IOException if an I/O error occurs. */ @Override public void writeDouble(double v) throws IOException { buffer.putDouble(v); } /** * Writes a string to the output stream. For every character in the string <code>s</code>, taken * in order, one byte is written to the output stream. If <code>s</code> is <code>null</code>, a * <code>NullPointerException</code> is thrown. * <p> * If <code>s.length</code> is zero, then no bytes are written. Otherwise, the character * <code>s[0]</code> is written first, then <code>s[1]</code>, and so on; the last character * written is <code>s[s.length-1]</code>. For each character, one byte is written, the low-order * byte, in exactly the manner of the <code>writeByte</code> method . The high-order eight bits of * each character in the string are ignored. * * @param str the string of bytes to be written. * @exception IOException if an I/O error occurs. */ @Override public void writeBytes(String str) throws IOException { int strlen = str.length(); if (strlen > 0) { // I know this is a deprecated method but it is PERFECT for this impl. if (this.buffer.hasArray()) { // I know this is a deprecated method but it is PERFECT for this impl. int pos = this.buffer.position(); str.getBytes(0, strlen, this.buffer.array(), this.buffer.arrayOffset() + pos); this.buffer.position(pos + strlen); } else { byte[] bytes = new byte[strlen]; str.getBytes(0, strlen, bytes, 0); this.buffer.put(bytes); } // for (int i = 0 ; i < len ; i++) { // this.buffer.put((byte)s.charAt(i)); // } } } /** * Writes every character in the string <code>s</code>, to the output stream, in order, two bytes * per character. If <code>s</code> is <code>null</code>, a <code>NullPointerException</code> is * thrown. If <code>s.length</code> is zero, then no characters are written. Otherwise, the * character <code>s[0]</code> is written first, then <code>s[1]</code>, and so on; the last * character written is <code>s[s.length-1]</code>. For each character, two bytes are actually * written, high-order byte first, in exactly the manner of the <code>writeChar</code> method. * * @param s the string value to be written. * @exception IOException if an I/O error occurs. */ @Override public void writeChars(String s) throws IOException { int len = s.length(); if (len > 0) { for (int i = 0; i < len; i++) { this.buffer.putChar(s.charAt(i)); } } } /** * Writes two bytes of length information to the output stream, followed by the Java modified UTF * representation of every character in the string <code>s</code>. If <code>s</code> is * <code>null</code>, a <code>NullPointerException</code> is thrown. Each character in the string * <code>s</code> is converted to a group of one, two, or three bytes, depending on the value of * the character. * <p> * If a character <code>c</code> is in the range <code>&#92;u0001</code> through * <code>&#92;u007f</code>, it is represented by one byte: * <p> * * <pre> * (byte) c * </pre> * <p> * If a character <code>c</code> is <code>&#92;u0000</code> or is in the range * <code>&#92;u0080</code> through <code>&#92;u07ff</code>, then it is represented by two bytes, * to be written in the order shown: * <p> * * <pre> * <code> * (byte)(0xc0 | (0x1f &amp; (c &gt;&gt; 6))) * (byte)(0x80 | (0x3f &amp; c)) * </code> * </pre> * <p> * If a character <code>c</code> is in the range <code>&#92;u0800</code> through * <code>uffff</code>, then it is represented by three bytes, to be written in the order shown: * <p> * * <pre> * <code> * (byte)(0xe0 | (0x0f &amp; (c &gt;&gt; 12))) * (byte)(0x80 | (0x3f &amp; (c &gt;&gt; 6))) * (byte)(0x80 | (0x3f &amp; c)) * </code> * </pre> * <p> * First, the total number of bytes needed to represent all the characters of <code>s</code> is * calculated. If this number is larger than <code>65535</code>, then a * <code>UTFDataFormatException</code> is thrown. Otherwise, this length is written to the output * stream in exactly the manner of the <code>writeShort</code> method; after this, the one-, two-, * or three-byte representation of each character in the string <code>s</code> is written. * <p> * The bytes written by this method may be read by the <code>readUTF</code> method of interface * <code>DataInput</code> , which will then return a <code>String</code> equal to <code>s</code>. * * @param str the string value to be written. * @exception IOException if an I/O error occurs. */ @Override public void writeUTF(String str) throws IOException { writeFullUTF(str); } private void writeFullUTF(String str) throws IOException { int strlen = str.length(); if (strlen > 65535) { throw new UTFDataFormatException( "String too long for java serialization"); } // make room for worst case space 3 bytes for each char and 2 for len int utfSizeIdx = this.buffer.position(); // skip bytes reserved for length this.buffer.position(utfSizeIdx + 2); for (int i = 0; i < strlen; i++) { int c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { this.buffer.put((byte) c); } else if (c > 0x07FF) { this.buffer.put((byte) (0xE0 | ((c >> 12) & 0x0F))); this.buffer.put((byte) (0x80 | ((c >> 6) & 0x3F))); this.buffer.put((byte) (0x80 | ((c >> 0) & 0x3F))); } else { this.buffer.put((byte) (0xC0 | ((c >> 6) & 0x1F))); this.buffer.put((byte) (0x80 | ((c >> 0) & 0x3F))); } } int utflen = this.buffer.position() - (utfSizeIdx + 2); if (utflen > 65535) { // act as if we wrote nothing to this buffer this.buffer.position(utfSizeIdx); throw new UTFDataFormatException( "String too long for java serialization"); } this.buffer.putShort(utfSizeIdx, (short) utflen); } /** * Writes the given object to this stream as a byte array. The byte array is produced by * serializing v. The serialization is done by calling DataSerializer.writeObject. */ @Override public void writeAsSerializedByteArray(Object v) throws IOException { ByteBuffer sizeBuf = this.buffer; int sizePos = sizeBuf.position(); sizeBuf.position(sizePos + 5); final int preArraySize = size(); DataSerializer.writeObject(v, this); int arraySize = size() - preArraySize; sizeBuf.put(sizePos, StaticSerialization.INT_ARRAY_LEN); sizeBuf.putInt(sizePos + 1, arraySize); } }
3e04a0686d111c12dfc4bf71e955cf5a36b9db0d
6,444
java
Java
client/src/org/jchlabs/gharonda/client/presenter/results/ResultWithoutMapPresenter.java
jchaganti/gharonda
c60c3546bbcb95c864e1ff5a2ffa0dcc18cb4bac
[ "MIT" ]
2
2015-08-16T12:13:06.000Z
2019-07-22T12:08:33.000Z
client/src/org/jchlabs/gharonda/client/presenter/results/ResultWithoutMapPresenter.java
jchaganti/gharonda
c60c3546bbcb95c864e1ff5a2ffa0dcc18cb4bac
[ "MIT" ]
1
2015-08-16T12:13:45.000Z
2015-08-16T12:13:45.000Z
client/src/org/jchlabs/gharonda/client/presenter/results/ResultWithoutMapPresenter.java
jchaganti/gharonda
c60c3546bbcb95c864e1ff5a2ffa0dcc18cb4bac
[ "MIT" ]
null
null
null
35.406593
114
0.779795
1,942
package org.jchlabs.gharonda.client.presenter.results; import java.util.List; import org.jchlabs.gharonda.client.NameTokens; import org.jchlabs.gharonda.client.events.ResultsWithMapSelectedEvent; import org.jchlabs.gharonda.client.events.ResultsWithoutMapSelectedEvent; import org.jchlabs.gharonda.client.events.ResultsWithoutMapSelectedEventHandler; import org.jchlabs.gharonda.client.presenter.AbstractAppPresenter; import org.jchlabs.gharonda.client.presenter.app.AppPresenter; import org.jchlabs.gharonda.client.util.PropertyOptions; import org.jchlabs.gharonda.client.util.SearchFeaturedListing; import org.jchlabs.gharonda.client.util.SearchProfile; import org.jchlabs.gharonda.client.view.results.ResultWithoutMapUiHandlers; import org.jchlabs.gharonda.domain.model.PropertiesDTO; import org.jchlabs.gharonda.domain.model.SearchCriteriaIFace; import org.jchlabs.gharonda.shared.rpc.FeaturedListingProfileIF; import org.jchlabs.gharonda.shared.rpc.GetFeaturedProperties; import org.jchlabs.gharonda.shared.rpc.GetSearchProperties; import org.jchlabs.gharonda.shared.rpc.GetSearchPropertiesResult; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.inject.Inject; import com.gwtplatform.dispatch.client.DispatchAsync; import com.gwtplatform.mvp.client.EventBus; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.annotations.ProxyEvent; import com.gwtplatform.mvp.client.annotations.TitleFunction; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.PlaceRequest; import com.gwtplatform.mvp.client.proxy.RevealContentEvent; public class ResultWithoutMapPresenter extends AbstractAppPresenter<ResultWithoutMapPresenter.MyView, ResultWithoutMapPresenter.MyProxy> implements ResultsWithoutMapSelectedEventHandler, ResultWithoutMapUiHandlers { /** * {@link ResultWithoutMapPresenter}'s proxy. */ @ProxyCodeSplit @NameToken(NameTokens.resultsWOMapPage) public interface MyProxy extends AbstractAppPresenter.MyProxy<ResultWithoutMapPresenter> { } /** * {@link ResultWithoutMapPresenter}'s view. */ public interface MyView extends AbstractAppPresenter.MyView, HasUiHandlers<ResultWithoutMapUiHandlers> { SearchProfile getDefaultSearchProfile(); void loadResults(List<PropertiesDTO> searchProperties, int realCount, SearchProfile listSearchProfile); void initUI(int mode); } private static final String MODE = "mode"; private final DispatchAsync dispatcher; private SearchProfile listSearchProfile; private SearchProfile mapSearchProfile; private int mode; private final PlaceManager placeManager; @Inject public ResultWithoutMapPresenter(final EventBus eventBus, final PlaceManager placeManager, final MyView view, final MyProxy proxy, final DispatchAsync dispatcher) { super(dispatcher, eventBus, view, proxy); this.dispatcher = dispatcher; this.placeManager = placeManager; getView().setUiHandlers(this); } @Override public void handleSearch(SearchProfile listSearchProfile) { this.listSearchProfile = listSearchProfile; displayResults(); } @Override public void handleViewMap() { ResultsWithMapSelectedEvent.fire(this, listSearchProfile, mapSearchProfile); placeManager.revealRelativePlace(new PlaceRequest(NameTokens.resultsWMapPage).with("mode", new Integer(mode).toString())); } @ProxyEvent @Override public void onResultsWithoutMapSelected(ResultsWithoutMapSelectedEvent event) { // this.featuredProperties = event.getFeaturedProperties(); this.listSearchProfile = event.getListSearchProfile(); this.mapSearchProfile = event.getMapSearchProfile(); } @Override public void prepareFromRequest(PlaceRequest request) { super.prepareFromRequest(request); String modeStr = request.getParameter(MODE, "-1"); mode = Integer.parseInt(modeStr); } @Override public String getBreadCrumbHeading() { String heading = ""; if (mode == 1) { heading = PropertyOptions.searchResultsSale; } else if (mode == 2) { heading = PropertyOptions.searchResultsRent; } return heading; } @TitleFunction public static String getTitle(PlaceRequest request) { String heading = ""; String modeStr = request.getParameter(MODE, "-1"); int _mode = Integer.parseInt(modeStr); if (_mode == 1) { heading = PropertyOptions.searchResultsSale; } else if (_mode == 2) { heading = PropertyOptions.searchResultsRent; } return heading; } @Override protected void onReset() { super.onReset(); displayResults(); } @Override protected void revealInParent() { RevealContentEvent.fire(this, AppPresenter.TYPE_SetMainContent, this); } private void displayResults() { if (listSearchProfile == null) { listSearchProfile = getView().getDefaultSearchProfile(); listSearchProfile.setResultsSizeLimit(20); } List<SearchCriteriaIFace> slCriteria = listSearchProfile.getSelListCriteria(); PropertyOptions.adjustForPModeSearchCriteria(slCriteria, mode); GetSearchProperties action = new GetSearchProperties(listSearchProfile.getFetchProfile(), slCriteria, listSearchProfile.getSearchTextCriteria(), true, listSearchProfile.getResultsSizeLimit()); dispatcher.execute(action, new AsyncCallback<GetSearchPropertiesResult>() { @Override public void onFailure(Throwable caught) { } @Override public void onSuccess(GetSearchPropertiesResult result) { getView().initUI(mode); getView().loadResults(result.getSearchProperties(), result.getRealCount(), listSearchProfile); showFeaturedProperties(getFeaturedPropertiesAction(listSearchProfile)); } }); } private GetFeaturedProperties getFeaturedPropertiesAction(SearchProfile listProfile) { FeaturedListingProfileIF flp = new SearchFeaturedListing(listProfile.getSelListCriteria(), listProfile.getSearchTextCriteria(), PropertyOptions.DEFAULT_FEATURED_SEARCH_PROFILE); GetFeaturedProperties action = new GetFeaturedProperties(flp.getANDSearchCriteria(), flp.getORSearchCriteria(), flp.getFeaturedListingType(), flp.getFetchProfile()); ; return action; } @Override protected int getFeaturedListingsSize() { return 10; } }
3e04a26622671d60e43062d9264b989e2c616829
245
java
Java
beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MethodHideFieldBean.java
vipcxj/beanknife
e2fff38fac99a818c429029366e2068e64fa8fda
[ "Apache-2.0" ]
186
2020-12-25T03:31:35.000Z
2022-02-04T16:11:10.000Z
beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/MethodHideFieldBean.java
zgood9527/beanknife
2ecd7f85897c7b1b84da8055d815f88ecdff78bc
[ "Apache-2.0" ]
2
2021-04-15T14:25:07.000Z
2021-04-15T15:17:35.000Z
beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/MethodHideFieldBean.java
zgood9527/beanknife
2ecd7f85897c7b1b84da8055d815f88ecdff78bc
[ "Apache-2.0" ]
9
2021-01-09T07:33:03.000Z
2021-10-10T18:16:21.000Z
17.5
63
0.730612
1,943
package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; @ViewMeta public class MethodHideFieldBean { public String test; private String getTest() { return test; } }
3e04a44c134a8c9a6350f33a4d727b81cfe5006a
2,900
java
Java
src/main/java/fr/insee/sabianedata/ws/model/queen/SurveyUnitDto.java
InseeFrLab/Sabiane-Data
dd174487f40867a9c6eb2b5cde809bcc5c8b31c6
[ "MIT" ]
null
null
null
src/main/java/fr/insee/sabianedata/ws/model/queen/SurveyUnitDto.java
InseeFrLab/Sabiane-Data
dd174487f40867a9c6eb2b5cde809bcc5c8b31c6
[ "MIT" ]
null
null
null
src/main/java/fr/insee/sabianedata/ws/model/queen/SurveyUnitDto.java
InseeFrLab/Sabiane-Data
dd174487f40867a9c6eb2b5cde809bcc5c8b31c6
[ "MIT" ]
5
2021-07-05T15:21:46.000Z
2021-09-09T13:49:03.000Z
35.802469
119
0.708966
1,944
package fr.insee.sabianedata.ws.model.queen; import java.io.File; import com.fasterxml.jackson.databind.JsonNode; import fr.insee.sabianedata.ws.utils.JsonFileToJsonNode; public class SurveyUnitDto extends SurveyUnit { public static final String FOLDER = "surveyUnits"; private JsonNode data; private JsonNode comment; private JsonNode personalization; public SurveyUnitDto(SurveyUnit surveyUnit, String folder) { super(surveyUnit.getId(), surveyUnit.getQuestionnaireId(), surveyUnit.getStateData()); String finalFolder = folder + File.separator + FOLDER; File dtodataFile = new File(finalFolder + File.separator + surveyUnit.getDataFile()); File commentFile = new File(finalFolder + File.separator + surveyUnit.getCommentFile()); File personalizationFile = new File(finalFolder + File.separator + surveyUnit.getPersonalizationFile()); this.data = JsonFileToJsonNode.getJsonNodeFromFile(dtodataFile); this.comment = JsonFileToJsonNode.getJsonNodeFromFile(commentFile); this.personalization = JsonFileToJsonNode.getJsonNodeFromFile(personalizationFile); } public SurveyUnitDto(SurveyUnit surveyUnit) { super(surveyUnit.getId(), surveyUnit.getQuestionnaireId(), surveyUnit.getStateData(), surveyUnit.getDataFile(), surveyUnit.getCommentFile(), surveyUnit.getPersonalizationFile()); } public SurveyUnitDto(SurveyUnitDto suDto, SurveyUnit su) { super(su); this.data = suDto.getData(); this.comment = suDto.getComment(); this.personalization = suDto.getPersonalization(); } public void extractJsonFromFiles(String folder) { String finalFolder = folder + File.separator + FOLDER; File dtodataFile = new File(finalFolder + File.separator + getDataFile()); File commentFile = new File(finalFolder + File.separator + getCommentFile()); File personalizationFile = new File(finalFolder + File.separator + getPersonalizationFile()); setData(JsonFileToJsonNode.getJsonNodeFromFile(dtodataFile)); setComment(JsonFileToJsonNode.getJsonNodeFromFile(commentFile)); setPersonalization(JsonFileToJsonNode.getJsonNodeFromFile(personalizationFile)); // to prevent jsonification to API calls setDataFile(null); setCommentFile(null); setPersonalizationFile(null); } public JsonNode getData() { return data; } public void setData(JsonNode data) { this.data = data; } public JsonNode getComment() { return comment; } public void setComment(JsonNode comment) { this.comment = comment; } public JsonNode getPersonalization() { return personalization; } public void setPersonalization(JsonNode personalization) { this.personalization = personalization; } }
3e04a548623b673a9f339dbfb003c8221a820b13
2,143
java
Java
src/main/java/moe/gensoukyo/mcgproject/common/feature/rsgauges/blocks/BlockKnockPulseSwitch.java
Chloe-koopa/MCGProject
cfbe67c291b605e5dc72f56408b3dc51b917d3de
[ "MIT" ]
5
2020-03-10T03:09:12.000Z
2020-07-18T06:29:34.000Z
src/main/java/moe/gensoukyo/mcgproject/common/feature/rsgauges/blocks/BlockKnockPulseSwitch.java
Chloe-koopa/MCGProject
cfbe67c291b605e5dc72f56408b3dc51b917d3de
[ "MIT" ]
2
2020-04-27T04:01:43.000Z
2020-05-27T08:42:01.000Z
src/main/java/moe/gensoukyo/mcgproject/common/feature/rsgauges/blocks/BlockKnockPulseSwitch.java
Chloe-koopa/MCGProject
cfbe67c291b605e5dc72f56408b3dc51b917d3de
[ "MIT" ]
5
2020-03-10T03:09:37.000Z
2020-06-29T08:11:36.000Z
48.704545
280
0.773682
1,945
/* * @file BlockBistableKnockSwitch.java * @author Stefan Wilhelm (wile) * @copyright (C) 2018 Stefan Wilhelm * @license MIT (see https://opensource.org/licenses/MIT) * * Seismic mass based adjacent block "knock" detection activate. */ package moe.gensoukyo.mcgproject.common.feature.rsgauges.blocks; import moe.gensoukyo.mcgproject.common.feature.rsgauges.detail.ModResources; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import javax.annotation.Nullable; public class BlockKnockPulseSwitch extends BlockSwitch implements IRsNeighbourInteractionSensitive { public BlockKnockPulseSwitch(String registryName, AxisAlignedBB unrotatedBBUnpowered, @Nullable AxisAlignedBB unrotatedBBPowered, long config, @Nullable ModResources.BlockSoundEvent powerOnSound, @Nullable ModResources.BlockSoundEvent powerOffSound, @Nullable Material material) { super(registryName, unrotatedBBUnpowered, unrotatedBBPowered, config|SWITCH_CONFIG_PULSE, powerOnSound, powerOffSound, material); } public BlockKnockPulseSwitch(String registryName, AxisAlignedBB unrotatedBBUnpowered, AxisAlignedBB unrotatedBBPowered, long config, @Nullable ModResources.BlockSoundEvent powerOnSound, @Nullable ModResources.BlockSoundEvent powerOffSound) { super(registryName, unrotatedBBUnpowered, unrotatedBBPowered, config, powerOnSound, powerOffSound, null); } // ------------------------------------------------------------------------------------------------------------------- @Override public boolean onNeighborBlockPlayerInteraction(World world, BlockPos pos, IBlockState state, BlockPos fromPos, EntityLivingBase entity, EnumHand hand, boolean isLeftClick) { EnumFacing facing = state.getValue(BlockSwitch.FACING); if(!pos.offset(facing).equals(fromPos)) return false; onSwitchActivated(world, pos, state, null, facing); return false; } }
3e04a5d308b1c89fb9021e594b8ffef9d504a9eb
139
java
Java
Desgin_FactoryKit/src/com/lucidastar/factorykit/Spear.java
Lucidastar/DesginPatterns
d54c69d70e10e953e2a0af2800baddccd9ec565f
[ "Apache-2.0" ]
null
null
null
Desgin_FactoryKit/src/com/lucidastar/factorykit/Spear.java
Lucidastar/DesginPatterns
d54c69d70e10e953e2a0af2800baddccd9ec565f
[ "Apache-2.0" ]
null
null
null
Desgin_FactoryKit/src/com/lucidastar/factorykit/Spear.java
Lucidastar/DesginPatterns
d54c69d70e10e953e2a0af2800baddccd9ec565f
[ "Apache-2.0" ]
null
null
null
12.636364
38
0.726619
1,946
package com.lucidastar.factorykit; public class Spear implements Weapon { @Override public String toString() { return "Spear"; } }
3e04a6348e7b71d0f65aa2f1fd78aed76998abdd
359
java
Java
src/main/java/com/moolng/canal/es/entity/suggest/Shards.java
BluceLee2014/binlog2es
884c57755631d44d890420ede1adebb664a1f011
[ "Apache-2.0" ]
null
null
null
src/main/java/com/moolng/canal/es/entity/suggest/Shards.java
BluceLee2014/binlog2es
884c57755631d44d890420ede1adebb664a1f011
[ "Apache-2.0" ]
null
null
null
src/main/java/com/moolng/canal/es/entity/suggest/Shards.java
BluceLee2014/binlog2es
884c57755631d44d890420ede1adebb664a1f011
[ "Apache-2.0" ]
null
null
null
19.944444
71
0.674095
1,947
package com.moolng.canal.es.entity.suggest; import java.io.Serializable; /** * @author 李权 * @description * @date 2020/6/4 16:00 */ public class Shards implements Serializable { private static final long serialVersionUID = 4652893711745238576L; private int total; private int successful; private int failed0; }
3e04a663157ad653f41785fb395a7a7e3c05ec51
5,384
java
Java
openbanking-api-client/src/test/java/com/laegler/openbanking/api/OrganisationCertificatesApiTest.java
thlaegler/openbanking
924a29ac8c0638622fba7a5674c21c803d6dc5a9
[ "MIT" ]
null
null
null
openbanking-api-client/src/test/java/com/laegler/openbanking/api/OrganisationCertificatesApiTest.java
thlaegler/openbanking
924a29ac8c0638622fba7a5674c21c803d6dc5a9
[ "MIT" ]
6
2019-10-20T18:56:35.000Z
2021-12-09T21:41:46.000Z
openbanking-api-server/src/test/java/com/laegler/openbanking/api/OrganisationCertificatesApiTest.java
thlaegler/openbanking
924a29ac8c0638622fba7a5674c21c803d6dc5a9
[ "MIT" ]
null
null
null
32.311377
206
0.705708
1,948
/** * Open Banking API * Latest Swagger specification for OpenBanking * * OpenAPI spec version: v2.3 * Contact: [email protected] * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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.laegler.openbanking.api; import com.laegler.openbanking.model.CertificateOrKeyGetSchema; import org.junit.Test; import org.junit.Before; import static org.junit.Assert.*; import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.client.JAXRSClientFactory; import org.apache.cxf.jaxrs.client.ClientConfiguration; import org.apache.cxf.jaxrs.client.WebClient; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Open Banking API * * <p>Latest Swagger specification for OpenBanking * * API tests for OrganisationCertificatesApi */ public class OrganisationCertificatesApiTest { private OrganisationCertificatesApi api; @Before public void setup() { JacksonJsonProvider provider = new JacksonJsonProvider(); List providers = new ArrayList(); providers.add(provider); api = JAXRSClientFactory.create("https://localhost:8080/api/v1", OrganisationCertificatesApi.class, providers); org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); ClientConfiguration config = WebClient.getConfig(client); } /** * Get the certificates for the given organisation * * @throws ApiException * if the Api call fails */ @Test public void organisationOrganisationTypeOrganisationIdCertificateGetTest() { String organisationType = null; String organisationId = null; //api.organisationOrganisationTypeOrganisationIdCertificateGet(organisationType, organisationId); // TODO: test validations } /** * Revoke or remove a certificate with the given CertificateOrKeyId * * @throws ApiException * if the Api call fails */ @Test public void organisationOrganisationTypeOrganisationIdCertificateKidCertificateOrKeyIdDeleteTest() { String organisationType = null; String organisationId = null; String certificateOrKeyId = null; //api.organisationOrganisationTypeOrganisationIdCertificateKidCertificateOrKeyIdDelete(organisationType, organisationId, certificateOrKeyId); // TODO: test validations } /** * Retrieve a certificate with the given CertificateOrKeyId * * @throws ApiException * if the Api call fails */ @Test public void organisationOrganisationTypeOrganisationIdCertificateKidCertificateOrKeyIdGetTest() { String organisationType = null; String organisationId = null; String certificateOrKeyId = null; //api.organisationOrganisationTypeOrganisationIdCertificateKidCertificateOrKeyIdGet(organisationType, organisationId, certificateOrKeyId); // TODO: test validations } /** * Get the certificates of the given OrganisationCertificateType for the given oranisation * * @throws ApiException * if the Api call fails */ @Test public void organisationOrganisationTypeOrganisationIdCertificateOrganisationCertificateTypeGetTest() { String organisationType = null; String organisationId = null; String organisationCertificateType = null; String softwareStatementId = null; //api.organisationOrganisationTypeOrganisationIdCertificateOrganisationCertificateTypeGet(organisationType, organisationId, organisationCertificateType, softwareStatementId); // TODO: test validations } /** * Store or create a new certificate of the given OrganisationCertificateType for the given organisation * * @throws ApiException * if the Api call fails */ @Test public void organisationOrganisationTypeOrganisationIdCertificateOrganisationCertificateTypePostTest() { String organisationType = null; String organisationId = null; String organisationCertificateType = null; String softwareStatementId = null; CertificateOrKeyGetSchema certificateOrCSROrJWS = null; //api.organisationOrganisationTypeOrganisationIdCertificateOrganisationCertificateTypePost(organisationType, organisationId, organisationCertificateType, softwareStatementId, certificateOrCSROrJWS); // TODO: test validations } }
3e04a6dfac0f019e662ab688a6c906144a4089a3
4,669
java
Java
client/src/com/vaadin/client/widget/grid/selection/SpaceSelectHandler.java
allanim/vaadin
b7f9b2316bff98bc7d37c959fa6913294d9608e4
[ "Apache-2.0" ]
2
2016-12-06T09:05:58.000Z
2016-12-07T08:57:55.000Z
client/src/com/vaadin/client/widget/grid/selection/SpaceSelectHandler.java
allanim/vaadin
b7f9b2316bff98bc7d37c959fa6913294d9608e4
[ "Apache-2.0" ]
null
null
null
client/src/com/vaadin/client/widget/grid/selection/SpaceSelectHandler.java
allanim/vaadin
b7f9b2316bff98bc7d37c959fa6913294d9608e4
[ "Apache-2.0" ]
null
null
null
34.080292
80
0.610623
1,949
/* * Copyright 2000-2014 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.client.widget.grid.selection; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.shared.HandlerRegistration; import com.vaadin.client.widget.grid.DataAvailableEvent; import com.vaadin.client.widget.grid.DataAvailableHandler; import com.vaadin.client.widget.grid.events.BodyKeyDownHandler; import com.vaadin.client.widget.grid.events.BodyKeyUpHandler; import com.vaadin.client.widget.grid.events.GridKeyDownEvent; import com.vaadin.client.widget.grid.events.GridKeyUpEvent; import com.vaadin.client.widgets.Grid; import com.vaadin.shared.ui.grid.ScrollDestination; /** * Generic class to perform selections when pressing space key. * * @author Vaadin Ltd * @param <T> * row data type * @since 7.4 */ public class SpaceSelectHandler<T> { /** * Handler for space key down events in Grid Body */ private class SpaceKeyDownHandler implements BodyKeyDownHandler { private HandlerRegistration scrollHandler = null; @Override public void onKeyDown(GridKeyDownEvent event) { if (event.getNativeKeyCode() != KeyCodes.KEY_SPACE || spaceDown) { return; } // Prevent space page scrolling event.getNativeEvent().preventDefault(); spaceDown = true; final int rowIndex = event.getFocusedCell().getRowIndex(); if (scrollHandler != null) { scrollHandler.removeHandler(); scrollHandler = null; } scrollHandler = grid .addDataAvailableHandler(new DataAvailableHandler() { @Override public void onDataAvailable( DataAvailableEvent dataAvailableEvent) { if (dataAvailableEvent.getAvailableRows().contains( rowIndex)) { setSelected(grid, rowIndex); scrollHandler.removeHandler(); scrollHandler = null; } } }); grid.scrollToRow(rowIndex, ScrollDestination.ANY); } protected void setSelected(Grid<T> grid, int rowIndex) { T row = grid.getDataSource().getRow(rowIndex); if (!grid.isSelected(row)) { grid.select(row); } else if (deselectAllowed) { grid.deselect(row); } } } private boolean spaceDown = false; private Grid<T> grid; private HandlerRegistration spaceUpHandler; private HandlerRegistration spaceDownHandler; private boolean deselectAllowed = true; /** * Constructor for SpaceSelectHandler. This constructor will add all * necessary handlers for selecting rows with space. * * @param grid * grid to attach to */ public SpaceSelectHandler(Grid<T> grid) { this.grid = grid; spaceDownHandler = grid .addBodyKeyDownHandler(new SpaceKeyDownHandler()); spaceUpHandler = grid.addBodyKeyUpHandler(new BodyKeyUpHandler() { @Override public void onKeyUp(GridKeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_SPACE) { spaceDown = false; } } }); } /** * Clean up function for removing all now obsolete handlers. */ public void removeHandler() { spaceDownHandler.removeHandler(); spaceUpHandler.removeHandler(); } /** * Sets whether pressing space for the currently selected row should * deselect the row. * * @param deselectAllowed * <code>true</code> to allow deselecting the selected row; * otherwise <code>false</code> */ public void setDeselectAllowed(boolean deselectAllowed) { this.deselectAllowed = deselectAllowed; } }
3e04a7908ce8d8939b9e1c07c66ba0b7f993e480
1,354
java
Java
basex-core/src/main/java/org/basex/io/serial/SerializerMode.java
jbrazda/basex
ca6ea437bbee1b239fabbc4c280da978f8494e4e
[ "BSD-3-Clause" ]
441
2015-01-05T09:33:58.000Z
2022-03-24T12:57:45.000Z
basex-core/src/main/java/org/basex/io/serial/SerializerMode.java
jbrazda/basex
ca6ea437bbee1b239fabbc4c280da978f8494e4e
[ "BSD-3-Clause" ]
977
2015-01-06T11:18:14.000Z
2022-03-31T11:13:15.000Z
basex-core/src/main/java/org/basex/io/serial/SerializerMode.java
jbrazda/basex
ca6ea437bbee1b239fabbc4c280da978f8494e4e
[ "BSD-3-Clause" ]
276
2015-01-21T07:03:59.000Z
2022-03-11T21:35:17.000Z
22.196721
67
0.660266
1,950
package org.basex.io.serial; import org.basex.util.options.Options.*; /** * Pre-defined serialization parameters. * * @author BaseX Team 2005-21, BSD License * @author Christian Gruen */ public enum SerializerMode { /** Default serialization. */ DEFAULT { @Override void init(final SerializerOptions options) { } }, /** Default serialization, but no indentation. */ NOINDENT { @Override void init(final SerializerOptions options) { options.set(SerializerOptions.INDENT, YesNo.NO); } }, /** Debugging (adaptive method). */ DEBUG { @Override void init(final SerializerOptions options) { options.set(SerializerOptions.METHOD, SerialMethod.ADAPTIVE); } }, /** API result retrieval. Also used by XQJ. */ API { @Override void init(final SerializerOptions options) { options.set(SerializerOptions.BINARY, YesNo.NO); } }; /** Options (lazy instantiation). */ private SerializerOptions options; /** * Initializes serialization parameters. * @param sopts options */ abstract void init(SerializerOptions sopts); /** * Returns serialization parameters. * @return parameters */ public final SerializerOptions get() { if(options == null) { options = new SerializerOptions(); init(options); } return options; } }
3e04a79279fc94435f327afe3c32d79b6ec19989
5,528
java
Java
core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterClass.java
w3aponx/orientdb
3b2ddd31284bb443e78b6eb47aba331c27b680bc
[ "Apache-2.0" ]
1
2019-01-26T04:19:17.000Z
2019-01-26T04:19:17.000Z
core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterClass.java
henryzhao81/orientdb
ff875b3ed402bb79515fb13b5c0f2a1bcaf31382
[ "Apache-2.0" ]
null
null
null
core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterClass.java
henryzhao81/orientdb
ff875b3ed402bb79515fb13b5c0f2a1bcaf31382
[ "Apache-2.0" ]
null
null
null
40.647059
140
0.714001
1,951
/* * Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.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.orientechnologies.orient.core.sql; import java.util.Arrays; import java.util.Locale; import java.util.Map; import com.orientechnologies.orient.core.command.OCommandDistributedReplicateRequest; import com.orientechnologies.orient.core.command.OCommandRequest; import com.orientechnologies.orient.core.command.OCommandRequestText; import com.orientechnologies.orient.core.db.record.ODatabaseRecord; import com.orientechnologies.orient.core.exception.OCommandExecutionException; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OClass.ATTRIBUTES; import com.orientechnologies.orient.core.metadata.schema.OClassImpl; import com.orientechnologies.orient.core.metadata.security.ODatabaseSecurityResources; import com.orientechnologies.orient.core.metadata.security.ORole; /** * SQL ALTER PROPERTY command: Changes an attribute of an existent property in the target class. * * @author Luca Garulli * */ @SuppressWarnings("unchecked") public class OCommandExecutorSQLAlterClass extends OCommandExecutorSQLAbstract implements OCommandDistributedReplicateRequest{ public static final String KEYWORD_ALTER = "ALTER"; public static final String KEYWORD_CLASS = "CLASS"; private String className; private ATTRIBUTES attribute; private String value; public OCommandExecutorSQLAlterClass parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); init((OCommandRequestText) iRequest); StringBuilder word = new StringBuilder(); int oldPos = 0; int pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true); if (pos == -1 || !word.toString().equals(KEYWORD_ALTER)) throw new OCommandSQLParsingException("Keyword " + KEYWORD_ALTER + " not found", parserText, oldPos); oldPos = pos; pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true); if (pos == -1 || !word.toString().equals(KEYWORD_CLASS)) throw new OCommandSQLParsingException("Keyword " + KEYWORD_CLASS + " not found", parserText, oldPos); oldPos = pos; pos = nextWord(parserText, parserTextUpperCase, oldPos, word, false); if (pos == -1) throw new OCommandSQLParsingException("Expected <class>", parserText, oldPos); className = word.toString(); oldPos = pos; pos = nextWord(parserText, parserTextUpperCase, oldPos, word, true); if (pos == -1) throw new OCommandSQLParsingException("Missed the class's attribute to change", parserText, oldPos); final String attributeAsString = word.toString(); try { attribute = OClass.ATTRIBUTES.valueOf(attributeAsString.toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException e) { throw new OCommandSQLParsingException("Unknown class's attribute '" + attributeAsString + "'. Supported attributes are: " + Arrays.toString(OClass.ATTRIBUTES.values()), parserText, oldPos); } value = parserText.substring(pos + 1).trim(); if (value.length() == 0) throw new OCommandSQLParsingException("Missed the property's value to change for attribute '" + attribute + "'", parserText, oldPos); if (value.equalsIgnoreCase("null")) value = null; return this; } /** * Execute the ALTER CLASS. */ public Object execute(final Map<Object, Object> iArgs) { if (attribute == null) throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet"); final OClassImpl cls = (OClassImpl) getDatabase().getMetadata().getSchema().getClass(className); if (cls == null) throw new OCommandExecutionException("Source class '" + className + "' not found"); cls.setInternalAndSave(attribute, value); renameCluster(); return null; } private void renameCluster() { final ODatabaseRecord database = getDatabase(); if (attribute.equals(OClass.ATTRIBUTES.NAME) && checkClusterRenameOk(database.getStorage().getClusterIdByName(value))) { database.command(new OCommandSQL("alter cluster " + className + " name " + value)).execute(); } } private boolean checkClusterRenameOk(int clusterId) { final ODatabaseRecord database = getDatabase(); for (OClass clazz : database.getMetadata().getSchema().getClasses()) { if (clazz.getName().equals(value)) continue; else if (clazz.getDefaultClusterId() == clusterId || Arrays.asList(clazz.getClusterIds()).contains(clusterId)) return false; } return true; } public String getSyntax() { return "ALTER CLASS <class> <attribute-name> <attribute-value>"; } }
3e04a7940debbc9344cd96b7d66a56ccb396f040
334
java
Java
ChefJ/src/email/SMTPAuthenticator.java
dev-jihyun/chefj
b882457a6e63680b477dd8395d01e7af6ba8f1cb
[ "MIT" ]
null
null
null
ChefJ/src/email/SMTPAuthenticator.java
dev-jihyun/chefj
b882457a6e63680b477dd8395d01e7af6ba8f1cb
[ "MIT" ]
null
null
null
ChefJ/src/email/SMTPAuthenticator.java
dev-jihyun/chefj
b882457a6e63680b477dd8395d01e7af6ba8f1cb
[ "MIT" ]
1
2021-03-04T12:48:16.000Z
2021-03-04T12:48:16.000Z
22.533333
84
0.727811
1,952
package email; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class SMTPAuthenticator extends Authenticator{ @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("[email protected]","나의 소중한 비번..,,"); } }
3e04a7cb27dc24139da5f8e113223c79344ef963
715
java
Java
Javac2007/流程/comp/02MemberEnter/enumBase.java
codefollower/Open-Source-Research
b9f2aed9d0f060b80be45f713c3d48fe91f247b2
[ "Apache-2.0" ]
184
2015-01-04T03:38:20.000Z
2022-03-30T05:47:21.000Z
Javac2007/流程/comp/02MemberEnter/enumBase.java
codefollower/Open-Source-Research
b9f2aed9d0f060b80be45f713c3d48fe91f247b2
[ "Apache-2.0" ]
1
2016-01-17T09:18:17.000Z
2016-01-17T09:18:17.000Z
Javac2007/流程/comp/02MemberEnter/enumBase.java
codefollower/Open-Source-Research
b9f2aed9d0f060b80be45f713c3d48fe91f247b2
[ "Apache-2.0" ]
101
2015-01-16T23:46:31.000Z
2022-03-30T05:47:06.000Z
44.6875
78
0.616783
1,953
/** Generate a base clause for an enum type. * @param pos The position for trees and diagnostics, if any * @param c The class symbol of the enum */ private JCExpression enumBase(int pos, ClassSymbol c) { DEBUG.P(this,"enumBase(2)"); JCExpression result = make.at(pos). TypeApply(make.QualIdent(syms.enumSym), List.<JCExpression>of(make.Type(c.type))); DEBUG.P("result="+result); //result=.java.lang.Enum<.test.memberEnter.EnumTest> //为什么最前面是"."号呢?因为在enterPackage时,java包、test包的owner //都是rootPackage,调用make.QualIdent时递归到rootPackage时才结束 DEBUG.P(0,this,"enumBase(2)"); return result; }
3e04a8cfbed9d3474a3da95c05c3acaf095f1e99
1,709
java
Java
sdk/network/mgmt/src/main/java/com/azure/management/network/AzureFirewallNetworkRuleProtocol.java
Azure-Fluent/azure-sdk-for-java
c123e88d3e78b3d1b81a977aae0646220457f2c1
[ "MIT" ]
1
2020-10-05T18:51:27.000Z
2020-10-05T18:51:27.000Z
sdk/network/mgmt/src/main/java/com/azure/management/network/AzureFirewallNetworkRuleProtocol.java
Azure-Fluent/azure-sdk-for-java
c123e88d3e78b3d1b81a977aae0646220457f2c1
[ "MIT" ]
24
2020-05-27T05:21:27.000Z
2021-06-25T15:37:42.000Z
sdk/network/mgmt/src/main/java/com/azure/management/network/AzureFirewallNetworkRuleProtocol.java
Azure-Fluent/azure-sdk-for-java
c123e88d3e78b3d1b81a977aae0646220457f2c1
[ "MIT" ]
null
null
null
41.682927
116
0.771211
1,954
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.management.network; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for AzureFirewallNetworkRuleProtocol. */ public final class AzureFirewallNetworkRuleProtocol extends ExpandableStringEnum<AzureFirewallNetworkRuleProtocol> { /** Static value TCP for AzureFirewallNetworkRuleProtocol. */ public static final AzureFirewallNetworkRuleProtocol TCP = fromString("TCP"); /** Static value UDP for AzureFirewallNetworkRuleProtocol. */ public static final AzureFirewallNetworkRuleProtocol UDP = fromString("UDP"); /** Static value Any for AzureFirewallNetworkRuleProtocol. */ public static final AzureFirewallNetworkRuleProtocol ANY = fromString("Any"); /** Static value ICMP for AzureFirewallNetworkRuleProtocol. */ public static final AzureFirewallNetworkRuleProtocol ICMP = fromString("ICMP"); /** * Creates or finds a AzureFirewallNetworkRuleProtocol from its string representation. * * @param name a name to look for. * @return the corresponding AzureFirewallNetworkRuleProtocol. */ @JsonCreator public static AzureFirewallNetworkRuleProtocol fromString(String name) { return fromString(name, AzureFirewallNetworkRuleProtocol.class); } /** @return known AzureFirewallNetworkRuleProtocol values. */ public static Collection<AzureFirewallNetworkRuleProtocol> values() { return values(AzureFirewallNetworkRuleProtocol.class); } }
3e04a92b3d0ea71f49d3a0665e4f135fb0caa115
932
java
Java
mini project/Source Code/Module1/WSM.java
waleskeen/Java
34a4d9cf5f4a5801afb1d5bf7abbb98c591790dc
[ "MIT" ]
1
2020-08-19T09:06:45.000Z
2020-08-19T09:06:45.000Z
mini project/Source Code/Module1/WSM.java
waleskeen/Java
34a4d9cf5f4a5801afb1d5bf7abbb98c591790dc
[ "MIT" ]
null
null
null
mini project/Source Code/Module1/WSM.java
waleskeen/Java
34a4d9cf5f4a5801afb1d5bf7abbb98c591790dc
[ "MIT" ]
null
null
null
34.518519
148
0.585837
1,955
package projectcharter; //Contribute by Ang Fan Yee import java.util.*; import java.text.DecimalFormat; public class WSM { DecimalFormat round2 = new DecimalFormat("0.00"); public double res = 0; public double total = 0; //function:to calculate the total of WSM //input:the list of WSM //output:total value of WSM public void wsm(List<WSMList> WL) { for (int a = 0; a < WL.size(); a++) { WL.get(a).res = WL.get(a).calrequirement(WL.get(a).getwei(), WL.get(a).getm()); } total = (WL.get(0).res+WL.get(1).res+WL.get(2).res+WL.get(3).res+WL.get(4).res)/100; /* for (int a = 0; a < WL.size(); a++) { System.out.println("Criteria: " + WL.get(a).getcri() + "\n Weight of criteria: " + WL.get(a).getwei() + "\n Mark: " + WL.get(a).getm()); } System.out.println("Total value of weighted scoring model: " + round2.format(total)+"%");*/ } }
3e04a96a7f37c2dd31590a6a2d2b1dfbd272ca28
2,585
java
Java
radixdlt-core/radixdlt/src/main/java/com/radixdlt/api/module/ConstructEndpointModule.java
stuartbain/radixdlt
88873f525d0a6b070472a48a0ad332a50a20370a
[ "Apache-2.0" ]
null
null
null
radixdlt-core/radixdlt/src/main/java/com/radixdlt/api/module/ConstructEndpointModule.java
stuartbain/radixdlt
88873f525d0a6b070472a48a0ad332a50a20370a
[ "Apache-2.0" ]
null
null
null
radixdlt-core/radixdlt/src/main/java/com/radixdlt/api/module/ConstructEndpointModule.java
stuartbain/radixdlt
88873f525d0a6b070472a48a0ad332a50a20370a
[ "Apache-2.0" ]
null
null
null
34.466667
103
0.818569
1,956
/* * (C) Copyright 2021 Radix DLT Ltd * * Radix DLT Ltd licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the * License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package com.radixdlt.api.module; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Scopes; import com.google.inject.multibindings.ProvidesIntoMap; import com.google.inject.multibindings.StringMapKey; import com.radixdlt.api.Controller; import com.radixdlt.api.JsonRpcHandler; import com.radixdlt.api.controller.JsonRpcController; import com.radixdlt.api.handler.ConstructionHandler; import com.radixdlt.api.qualifier.ArchiveServer; import com.radixdlt.api.qualifier.ConstructionEndpoint; import com.radixdlt.api.server.JsonRpcServer; import java.util.Map; public class ConstructEndpointModule extends AbstractModule { @Override protected void configure() { bind(ConstructionHandler.class).in(Scopes.SINGLETON); } @ArchiveServer @ProvidesIntoMap @StringMapKey("/construction") public Controller constructController(@ConstructionEndpoint JsonRpcServer jsonRpcServer) { return new JsonRpcController(jsonRpcServer); } @ConstructionEndpoint @Provides public JsonRpcServer rpcServer(@ConstructionEndpoint Map<String, JsonRpcHandler> additionalHandlers) { return new JsonRpcServer(additionalHandlers); } @ConstructionEndpoint @ProvidesIntoMap @StringMapKey("construction.build_transaction") public JsonRpcHandler constructionBuildTransaction(ConstructionHandler constructionHandler) { return constructionHandler::handleConstructionBuildTransaction; } @ConstructionEndpoint @ProvidesIntoMap @StringMapKey("construction.finalize_transaction") public JsonRpcHandler constructionFinalizeTransaction(ConstructionHandler constructionHandler) { return constructionHandler::handleConstructionFinalizeTransaction; } @ConstructionEndpoint @ProvidesIntoMap @StringMapKey("construction.submit_transaction") public JsonRpcHandler constructionSubmitTransaction(ConstructionHandler constructionHandler) { return constructionHandler::handleConstructionSubmitTransaction; } }
3e04aa8be1acb72172b5f19538c6cc61b683a1ef
936
java
Java
src/org/omg/PortableInterceptor/ORBInitInfoPackage/DuplicateName.java
zhouhanglalala/JDKSourceCode1.8
3cc08230bf3cac476fc685799832028529979ad4
[ "MIT" ]
1,305
2018-03-11T15:04:26.000Z
2022-03-30T16:02:34.000Z
src/org/omg/PortableInterceptor/ORBInitInfoPackage/DuplicateName.java
zhouhanglalala/JDKSourceCode1.8
3cc08230bf3cac476fc685799832028529979ad4
[ "MIT" ]
7
2019-03-20T09:43:08.000Z
2021-08-20T03:19:24.000Z
src/org/omg/PortableInterceptor/ORBInitInfoPackage/DuplicateName.java
zhouhanglalala/JDKSourceCode1.8
3cc08230bf3cac476fc685799832028529979ad4
[ "MIT" ]
575
2018-03-11T15:15:41.000Z
2022-03-30T16:03:48.000Z
24.631579
137
0.705128
1,957
package org.omg.PortableInterceptor.ORBInitInfoPackage; /** * org/omg/PortableInterceptor/ORBInitInfoPackage/DuplicateName.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from c:/re/workspace/8-2-build-windows-amd64-cygwin/jdk8u201/12322/corba/src/share/classes/org/omg/PortableInterceptor/Interceptors.idl * Saturday, December 15, 2018 6:38:38 PM PST */ public final class DuplicateName extends org.omg.CORBA.UserException { /** * The name for which there was already an interceptor registered. */ public String name = null; public DuplicateName () { super(DuplicateNameHelper.id()); } // ctor public DuplicateName (String _name) { super(DuplicateNameHelper.id()); name = _name; } // ctor public DuplicateName (String $reason, String _name) { super(DuplicateNameHelper.id() + " " + $reason); name = _name; } // ctor } // class DuplicateName
3e04ab6bca339092834a5f16c96b749184235ff2
552
java
Java
XXE-detection/findsecbugs-samples-java/src/test/java/testcode/script/ognl/ValueStackSample.java
Berger-and-Molland/xxe-autofix-tool
dda05c0436fc1bc1dfa4242f32c5dde18307665d
[ "MIT" ]
null
null
null
XXE-detection/findsecbugs-samples-java/src/test/java/testcode/script/ognl/ValueStackSample.java
Berger-and-Molland/xxe-autofix-tool
dda05c0436fc1bc1dfa4242f32c5dde18307665d
[ "MIT" ]
null
null
null
XXE-detection/findsecbugs-samples-java/src/test/java/testcode/script/ognl/ValueStackSample.java
Berger-and-Molland/xxe-autofix-tool
dda05c0436fc1bc1dfa4242f32c5dde18307665d
[ "MIT" ]
null
null
null
29.052632
66
0.682971
1,958
package testcode.script.ognl; import com.opensymphony.xwork2.util.ValueStack; public class ValueStackSample { public void testExpression(String expression, ValueStack vs) { vs.findString(expression); vs.findString(expression,false); vs.findValue(expression); vs.findValue(expression, false); vs.findValue(expression,null); vs.findValue(expression,null, false); vs.setValue(expression, null); vs.setValue(expression, null, false); vs.setParameter(expression, null); } }
3e04ab89e61c56597c80259ffd01a0c8abd40d1c
527
java
Java
2007/wiki/desktop-wiki/src/ee/pri/rl/wiki/desktop/test/WikiTreeBuilderTest.java
rla/old-code
06aa69c3adef8434992410687d466dc42779e57b
[ "Ruby", "MIT" ]
2
2015-11-08T10:01:47.000Z
2020-03-10T00:00:58.000Z
2007/wiki/desktop-wiki/src/ee/pri/rl/wiki/desktop/test/WikiTreeBuilderTest.java
rla/old-code
06aa69c3adef8434992410687d466dc42779e57b
[ "Ruby", "MIT" ]
null
null
null
2007/wiki/desktop-wiki/src/ee/pri/rl/wiki/desktop/test/WikiTreeBuilderTest.java
rla/old-code
06aa69c3adef8434992410687d466dc42779e57b
[ "Ruby", "MIT" ]
null
null
null
23.954545
67
0.760911
1,959
package ee.pri.rl.wiki.desktop.test; import java.io.IOException; import ee.pri.rl.wiki.desktop.ui.tree.WikiTreeBuilder; import ee.pri.rl.wiki.desktop.ui.tree.WikiTreeNode; import junit.framework.TestCase; /** * Test cases for wiki tree builder. */ public class WikiTreeBuilderTest extends TestCase { public void testBuildTree() throws IOException { WikiTreeNode root = WikiTreeBuilder.buildTree("/home/raivo/web"); assertNotNull(root); assertNotNull(root.getNodes()); assertTrue(root.getChildCount() > 0); } }
3e04acb6865a8add73ad84b90b82c95f466b42e4
146
java
Java
src/main/java/com/verygood/security/coding/api/Encryption.java
kochniev/3DES-Encryption
af13a9b23094abd61fdc00b8e5113a46138c51d2
[ "Apache-2.0" ]
null
null
null
src/main/java/com/verygood/security/coding/api/Encryption.java
kochniev/3DES-Encryption
af13a9b23094abd61fdc00b8e5113a46138c51d2
[ "Apache-2.0" ]
null
null
null
src/main/java/com/verygood/security/coding/api/Encryption.java
kochniev/3DES-Encryption
af13a9b23094abd61fdc00b8e5113a46138c51d2
[ "Apache-2.0" ]
null
null
null
20.857143
41
0.787671
1,960
package com.verygood.security.coding.api; public interface Encryption { String encrypt(String text); String decrypt(String encryptedData); }
3e04ad0a68e2258693ebe3d50c57d9efa6474a34
7,406
java
Java
Backend/src/test/java/preferenceData/PreferenceRulesGenerator.java
KITE-Cloud/AGADE-TRAFFIC
25b1f368ab5b5784985f5d9d9febd819e873ec39
[ "MIT" ]
2
2021-05-13T09:59:22.000Z
2021-06-22T10:24:49.000Z
Backend/src/test/java/preferenceData/PreferenceRulesGenerator.java
KITE-Cloud/AGADE-TRAFFIC
25b1f368ab5b5784985f5d9d9febd819e873ec39
[ "MIT" ]
null
null
null
Backend/src/test/java/preferenceData/PreferenceRulesGenerator.java
KITE-Cloud/AGADE-TRAFFIC
25b1f368ab5b5784985f5d9d9febd819e873ec39
[ "MIT" ]
null
null
null
38.978947
211
0.564542
1,961
package preferenceData; import org.junit.Test; import utility.ExcelReader; import java.util.ArrayList; import java.util.List; public class PreferenceRulesGenerator { @Test public void generateTravelPreferenceRules() { String preferenceName = "Occupation"; int sheetNumber = 6; ExcelReader excelReader = new ExcelReader(); excelReader.readExcelFile("C:\\Users\\Johannes\\IdeaProjects\\AGADE-Traffic\\AGADE\\src\\main\\resources\\preferenceData\\GESIS_2000.xls", sheetNumber); List<ArrayList<String>> excelData = excelReader.getExcelData(); //remove first and last row excelData.remove(excelData.size() - 1); excelData.remove(0); ArrayList<String> headerRow = excelData.get(0); int numberOfCensusCategories = (excelData.size() - 1) / 5; int indexColumnPercentStart = 0; int indexRowStart = 1; int numberOfPreferences = 0; for (int i = 0; i < headerRow.size(); i++) { String col = headerRow.get(i); if (col.equals("Flexibility")) { indexColumnPercentStart = i; } } numberOfPreferences = headerRow.size() - indexColumnPercentStart; for (int i = indexRowStart; i < excelData.size(); i = i + 5) { String categoryName = excelData.get(i).get(0); String ruleHead = "Person(?p) ^ has" + preferenceName.replace("_", "") + "(?p, ?" + preferenceName.toLowerCase() + ") ^ swrlb:equal(?" + preferenceName.toLowerCase() + ", \"" + categoryName + "\") "; String ruleBody = " -> Person(?p)"; for (int j = indexColumnPercentStart; j < headerRow.size(); j++) { String prefName = headerRow.get(j); //add Preference Konzept: ^ hasPreference(?p, ?pr1) ruleHead = ruleHead + " ^" + prefName + "(?pr" + (j - indexColumnPercentStart) + ")"; ruleBody = ruleBody + " ^" + prefName + "(?pr" + (j - indexColumnPercentStart) + ")"; //add hasPreferenceProp: ^ Flexibility(?pr1) ruleBody = ruleBody + " ^hasPreference(?p, ?pr" + (j - indexColumnPercentStart) + ")"; for (int s = 0; s < 5; s++) { //add hasScoreCatProp: ^hasScoreCat1(?pr1, \"20\"^^xsd:integer) String percentValue = excelData.get(i + (s)).get(j); ruleBody = ruleBody + " ^hasScoreCat" + (s + 1) + "(?pr" + (j - indexColumnPercentStart) + ", \"" + percentValue + "\"^^xsd:double)"; } } System.out.println("Pref_" + preferenceName + "_" + categoryName); System.out.println(ruleHead + ruleBody); System.out.println(""); } //"Person(?p) ^ hasAge(?p, ?age) ^ swrlb:equal(?age, \"18-24\") ^ Flexibility(?pr1) -> Person(?p) ^ Flexibility(?pr1) ^ hasPreference(?p, ?pr1) ^ hasScoreCat1(?pr1, \"20\"^^xsd:integer)\n" System.out.println("done"); } @Test public void generateHouseHoldRules() { String preferenceName = "Marital_Status"; int sheetNumber = 8; ExcelReader excelReader = new ExcelReader(); excelReader.readExcelFile("C:\\Users\\Johannes\\IdeaProjects\\AGADE-Traffic\\AGADE\\src\\main\\resources\\preferenceData\\GESIS_2000.xls", sheetNumber); List<ArrayList<String>> excelData = excelReader.getExcelData(); //remove first and last row excelData.remove(excelData.size() - 1); excelData.remove(0); ArrayList<String> headerRow = excelData.get(0); int indexColumnPercentStart = 4; int indexRowStart = 1; for (int i = indexRowStart; i < excelData.size(); i = i + 5) { String categoryName = excelData.get(i).get(0); String ruleHead = "Person(?p) ^ has" + preferenceName.replace("_", "") + "(?p, ?" + preferenceName.toLowerCase() + ") ^ swrlb:equal(?" + preferenceName.toLowerCase() + ", \"" + categoryName + "\") "; String ruleBody = " -> Person(?p)"; String prefName = headerRow.get(indexColumnPercentStart); for (int s = 0; s < 5; s++) { //add hasScoreCatProp: ^hasProbabilityHouseholdSize1(?pr1, \"20\"^^xsd:integer) String percentValue = excelData.get(i + (s)).get(indexColumnPercentStart); ruleBody = ruleBody + " ^hasProbabilityHouseholdSize" + (s + 1) + "(?p" + ", \"" + percentValue + "\"^^xsd:double)"; } System.out.println("Household_" + preferenceName + "_" + categoryName); System.out.println(ruleHead + ruleBody); System.out.println(""); } System.out.println("done"); } @Test public void generateFoodPreferenceRules(){ String preferenceName = "Gender"; int sheetNumber = 3; ExcelReader excelReader = new ExcelReader(); excelReader.readExcelFile("C:\\Users\\-DELL-\\Desktop\\PAAMS\\AGADE-Traffic\\AGADE\\src\\main\\resources\\preferenceData\\Food Data (Processed + Rules).xls", sheetNumber); List<ArrayList<String>> excelData = excelReader.getExcelData(); //remove first and last row excelData.remove(excelData.size() - 1); excelData.remove(0); ArrayList<String> headerRow = excelData.get(0); int numberOfCensusCategories = (excelData.size() - 1) / 5; int indexColumnPercentStart = 0; int indexRowStart = 1; int numberOfPreferences = 0; for (int i = 0; i < headerRow.size(); i++) { String col = headerRow.get(i); if (col.equals("Healthy")) { indexColumnPercentStart = i; } } numberOfPreferences = headerRow.size() - indexColumnPercentStart; for (int i = indexRowStart; i < excelData.size(); i = i + 5) { String categoryName = excelData.get(i).get(0); String ruleHead = "Person(?p) ^ has" + preferenceName.replace("_", "") + "(?p, ?" + preferenceName.toLowerCase() + ") ^ swrlb:equal(?" + preferenceName.toLowerCase() + ", \"" + categoryName + "\") "; String ruleBody = " -> Person(?p)"; for (int j = indexColumnPercentStart; j < headerRow.size(); j++) { String prefName = headerRow.get(j); //add Preference Konzept: ^ hasFoodPreference(?p, ?pr1) ruleHead = ruleHead + " ^" + prefName + "(?pr" + (j - indexColumnPercentStart) + ")"; ruleBody = ruleBody + " ^" + prefName + "(?pr" + (j - indexColumnPercentStart) + ")"; //add hasPreferenceProp: ^ Flexibility(?pr1) ruleBody = ruleBody + " ^hasFoodPreference(?p, ?pr" + (j - indexColumnPercentStart) + ")"; for (int s = 0; s < 5; s++) { //add hasScoreCatProp: ^hasScoreCat1(?pr1, \"20\"^^xsd:integer) String percentValue = excelData.get(i + (s)).get(j); ruleBody = ruleBody + " ^hasScoreCat" + (s + 1) + "(?pr" + (j - indexColumnPercentStart) + ", \"" + percentValue + "\"^^xsd:double)"; } } System.out.println("Pref_Food_" + preferenceName + "_" + categoryName); System.out.println(ruleHead + ruleBody); System.out.println(""); } System.out.println("done"); } }
3e04ad317a8dd297b664776dfdf84707d52dd6b8
2,165
java
Java
src/viaversion/viaversion/util/ConcurrentList.java
josesilveiraa/novoline
9146c4add3aa518d9aa40560158e50be1b076cf0
[ "Unlicense" ]
5
2022-02-04T12:57:17.000Z
2022-03-26T16:12:16.000Z
src/viaversion/viaversion/util/ConcurrentList.java
josesilveiraa/novoline
9146c4add3aa518d9aa40560158e50be1b076cf0
[ "Unlicense" ]
2
2022-02-25T20:10:14.000Z
2022-03-03T14:25:03.000Z
src/viaversion/viaversion/util/ConcurrentList.java
josesilveiraa/novoline
9146c4add3aa518d9aa40560158e50be1b076cf0
[ "Unlicense" ]
1
2021-11-28T09:59:55.000Z
2021-11-28T09:59:55.000Z
20.817308
57
0.627714
1,962
package viaversion.viaversion.util; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import net.Z1; import net.ZU; /** @deprecated */ @Deprecated public class ConcurrentList extends ArrayList { private final Object lock = new Object(); public boolean add(Object param1) { // $FF: Couldn't be decompiled } public void add(int param1, Object param2) { // $FF: Couldn't be decompiled } public boolean addAll(Collection param1) { // $FF: Couldn't be decompiled } public boolean addAll(int param1, Collection param2) { // $FF: Couldn't be decompiled } public void clear() { // $FF: Couldn't be decompiled } public Object clone() { // $FF: Couldn't be decompiled } public boolean contains(Object param1) { // $FF: Couldn't be decompiled } public void ensureCapacity(int param1) { // $FF: Couldn't be decompiled } public Object get(int param1) { // $FF: Couldn't be decompiled } public int indexOf(Object param1) { // $FF: Couldn't be decompiled } public int lastIndexOf(Object param1) { // $FF: Couldn't be decompiled } public Object remove(int param1) { // $FF: Couldn't be decompiled } public boolean remove(Object param1) { // $FF: Couldn't be decompiled } public boolean removeAll(Collection param1) { // $FF: Couldn't be decompiled } public boolean retainAll(Collection param1) { // $FF: Couldn't be decompiled } public Object set(int param1, Object param2) { // $FF: Couldn't be decompiled } public List subList(int param1, int param2) { // $FF: Couldn't be decompiled } public Object[] toArray() { // $FF: Couldn't be decompiled } public Object[] toArray(Object[] param1) { // $FF: Couldn't be decompiled } public void trimToSize() { // $FF: Couldn't be decompiled } public ListIterator listIterator() { return new Z1(this, 0); } public Iterator iterator() { return new ZU(this); } }
3e04ad9e2d0db8b78ba86e123fc548fe70cb6f5c
7,019
java
Java
src/test/java/com/rarysoft/u4/game/GameTest.java
Rarysoft/u4
1bf1459d0695214242703b28f7a480f1b70843dc
[ "MIT" ]
null
null
null
src/test/java/com/rarysoft/u4/game/GameTest.java
Rarysoft/u4
1bf1459d0695214242703b28f7a480f1b70843dc
[ "MIT" ]
null
null
null
src/test/java/com/rarysoft/u4/game/GameTest.java
Rarysoft/u4
1bf1459d0695214242703b28f7a480f1b70843dc
[ "MIT" ]
null
null
null
37.736559
117
0.689842
1,963
/* * MIT License * * Copyright (c) 2020 Rarysoft Enterprises * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.rarysoft.u4.game; import com.rarysoft.u4.game.physics.ViewFinder; import com.rarysoft.u4.i18n.Messages; import com.rarysoft.u4.game.npc.Dialog; import com.rarysoft.u4.game.npc.Dialogs; import com.rarysoft.u4.game.npc.NonPlayerCharacter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class GameTest { @Mock private Messages messages; @Mock private Dialogs dialogs; @Mock private InformationListener informationListener; @Mock private GameState gameState; @Mock private Dialog dialog; @Mock private ViewFinder viewFinder; @InjectMocks private Game game; @Captor private ArgumentCaptor<String> messageCaptor; @Before public void initializeGame() { game.addInformationListener(informationListener); RenderedTile empty = new RenderedTile().withBaseTile(Tile.BRICK_FLOOR); RenderedTile[] emptyRow = new RenderedTile[] { empty, empty, empty, empty, empty, empty, empty, empty, empty, empty, empty, empty, empty, empty, empty, empty, empty, empty, empty, empty, empty }; RenderedTile[][] emptyMap = new RenderedTile[][] { emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow, emptyRow }; when(gameState.mapView(viewFinder, 10)).thenReturn(emptyMap); when(gameState.dialog()).thenReturn(dialog); when(messages.speechCitizenPrompt()).thenReturn("Prompt:"); game.start(gameState); } @Test public void onUserInputWhenNotInConversationDoesNothing() { when(gameState.inConversation()).thenReturn(false); game.onUserInput('\n'); verify(informationListener, never()).responseRequested(any()); } @Test public void onUserInputWhenInConversationNotAwaitingResponseAndDescriptionRequestedRespondsWithDescription() { when(gameState.inConversation()).thenReturn(true); when(gameState.inConversationRespondingYesOrNo()).thenReturn(false); when(gameState.input()).thenReturn("look"); when(dialog.getLookResponse()).thenReturn("You see a character."); game.onUserInput('\n'); verifyResponse("You see a character."); } @Test public void onUserInputWhenInConversationNotAwaitingResponseAndNameRequestedRespondsWithName() { when(gameState.inConversation()).thenReturn(true); when(gameState.inConversationRespondingYesOrNo()).thenReturn(false); when(gameState.input()).thenReturn("name"); when(dialog.getNameResponse()).thenReturn("Pronoun says: I am Character Name."); game.onUserInput('\n'); verifyResponse("Pronoun says: I am Character Name."); } @Test public void onUserInputWhenInConversationNotAwaitingResponseAndJobRequestedRespondsWithJob() { when(gameState.inConversation()).thenReturn(true); when(gameState.inConversationRespondingYesOrNo()).thenReturn(false); when(gameState.input()).thenReturn("job"); when(dialog.getJobResponse()).thenReturn("Pronoun says: I have a job."); game.onUserInput('\n'); verifyResponse("Pronoun says: I have a job."); } @Test public void onUserInputWhenInConversationNotAwaitingResponseAndHealthRequestedRespondsWithHealth() { when(gameState.inConversation()).thenReturn(true); when(gameState.inConversationRespondingYesOrNo()).thenReturn(false); when(gameState.input()).thenReturn("health"); when(dialog.getHealthResponse()).thenReturn("Pronoun says: I have health."); game.onUserInput('\n'); verifyResponse("Pronoun says: I have health."); } @Test public void onUserInputWhenInConversationNotAwaitingResponseAndKeyword1RequestedRespondsWithKeyword1Response() { when(gameState.inConversation()).thenReturn(true); when(gameState.inConversationRespondingYesOrNo()).thenReturn(false); when(gameState.input()).thenReturn("key1"); when(dialog.getNpc()).thenReturn(NonPlayerCharacter.CITIZEN); when(dialog.getKeyword(0)).thenReturn("KEY1"); when(dialog.getKeywordResponse(0)).thenReturn("Pronoun says: Blah 1."); game.onUserInput('\n'); verifyResponse("Pronoun says: Blah 1."); } @Test public void onUserInputWhenInConversationNotAwaitingResponseAndKeyword2RequestedRespondsWithKeyword2Response() { when(gameState.inConversation()).thenReturn(true); when(gameState.inConversationRespondingYesOrNo()).thenReturn(false); when(gameState.input()).thenReturn("key2"); when(dialog.getNpc()).thenReturn(NonPlayerCharacter.CITIZEN); when(dialog.getKeyword(1)).thenReturn("KEY2"); when(dialog.getKeywordResponse(1)).thenReturn("Pronoun says: Blah 2."); game.onUserInput('\n'); verifyResponse("Pronoun says: Blah 2."); } private void verifyResponse(String message) { verify(informationListener).responseRequested(messageCaptor.capture()); String result = messageCaptor.getValue(); assertThat(result).isNotNull().isEqualTo(message + "\nPrompt:"); } }
3e04ae4569d66c1138eb2862914624db5ac69876
802
java
Java
src/test/java/org/apache/ibatis/submitted/mapper_extend/GrandpaMapper.java
houfanGitHub/mybatis-3
159b9f7d16714728fb62570bf66f8b539f685387
[ "ECL-2.0", "Apache-2.0" ]
18,538
2015-01-01T09:46:22.000Z
2022-03-31T18:21:50.000Z
src/test/java/org/apache/ibatis/submitted/mapper_extend/GrandpaMapper.java
houfanGitHub/mybatis-3
159b9f7d16714728fb62570bf66f8b539f685387
[ "ECL-2.0", "Apache-2.0" ]
1,686
2015-01-01T14:21:54.000Z
2022-03-31T20:12:51.000Z
src/test/java/org/apache/ibatis/submitted/mapper_extend/GrandpaMapper.java
houfanGitHub/mybatis-3
159b9f7d16714728fb62570bf66f8b539f685387
[ "ECL-2.0", "Apache-2.0" ]
13,353
2015-01-01T08:57:45.000Z
2022-03-31T07:22:42.000Z
32.08
78
0.721945
1,964
/* * Copyright 2009-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.submitted.mapper_extend; public interface GrandpaMapper { User getUserByName(String name); User noMappedStatement(); }
3e04ae4fcc857ca497955d45dde7bf028b4ea1ca
203
java
Java
chapter_004/src/main/java/ru/job4j/calculator/Operation.java
bulainikolai/job4j
a4b4020f83383b978654196d28aa14d164d19b74
[ "Apache-2.0" ]
null
null
null
chapter_004/src/main/java/ru/job4j/calculator/Operation.java
bulainikolai/job4j
a4b4020f83383b978654196d28aa14d164d19b74
[ "Apache-2.0" ]
1
2020-10-13T08:23:47.000Z
2020-10-13T08:23:47.000Z
chapter_004/src/main/java/ru/job4j/calculator/Operation.java
bulainikolai/job4j
a4b4020f83383b978654196d28aa14d164d19b74
[ "Apache-2.0" ]
null
null
null
16.076923
50
0.674641
1,965
package ru.job4j.calculator; /** * Operation * * @author Nikolai Bulai ([email protected]) * @version 1 * @since 22.11.2018 */ public interface Operation { double calc(int left, int right); }
3e04aecb45951ec902432592fd62446e3fe7dbb1
356
java
Java
picshare-model/src/main/java/org/neonsis/picshare/service/ProfileSignUpService.java
Neonsis/picshare
eacfb445977d4c41dc54cb6d744f42a3bad9ce29
[ "MIT" ]
null
null
null
picshare-model/src/main/java/org/neonsis/picshare/service/ProfileSignUpService.java
Neonsis/picshare
eacfb445977d4c41dc54cb6d744f42a3bad9ce29
[ "MIT" ]
null
null
null
picshare-model/src/main/java/org/neonsis/picshare/service/ProfileSignUpService.java
Neonsis/picshare
eacfb445977d4c41dc54cb6d744f42a3bad9ce29
[ "MIT" ]
null
null
null
22.25
63
0.794944
1,966
package org.neonsis.picshare.service; import org.neonsis.picshare.exception.ObjectNotFoundException; import org.neonsis.picshare.model.domain.Profile; public interface ProfileSignUpService { void createSignUpProfile(Profile profile); Profile getCurrentProfile() throws ObjectNotFoundException; void completeSignUp(); void cancel(); }
3e04af0da7de9da7aadc269b299899dc0ba1a714
1,309
java
Java
Chapter08/exercise06/MultiplyTwoMatrices.java
oguzhan2142/IntroductionToJavaProgrammingSolutions-Y.DanielLiang
e2462fb1b94a2efd86fab029c630e3421731d5de
[ "MIT" ]
null
null
null
Chapter08/exercise06/MultiplyTwoMatrices.java
oguzhan2142/IntroductionToJavaProgrammingSolutions-Y.DanielLiang
e2462fb1b94a2efd86fab029c630e3421731d5de
[ "MIT" ]
null
null
null
Chapter08/exercise06/MultiplyTwoMatrices.java
oguzhan2142/IntroductionToJavaProgrammingSolutions-Y.DanielLiang
e2462fb1b94a2efd86fab029c630e3421731d5de
[ "MIT" ]
null
null
null
22.568966
85
0.588235
1,967
package Chapter08.exercise06; import java.util.Scanner; public class MultiplyTwoMatrices { public static void main(String[] args) { Scanner scan = new Scanner(System.in); double[][] matrix1 = new double[3][3]; double[][] matrix2 = new double[3][3]; System.out.println("Enter matrix1:"); for (int i = 0; i < matrix1.length; i++) { for (int j = 0; j < matrix1[i].length; j++) { matrix1[i][j] = scan.nextDouble(); } } System.out.println("Enter matrix2:"); for (int i = 0; i < matrix2.length; i++) { for (int j = 0; j < matrix2[i].length; j++) { matrix2[i][j] = scan.nextDouble(); } } scan.close(); double[][] multiplyOfTwoMatrix = multiplyMatrix(matrix1, matrix2); for (int i = 0; i < multiplyOfTwoMatrix.length; i++) { for (int j = 0; j < multiplyOfTwoMatrix[i].length; j++) { System.out.printf(multiplyOfTwoMatrix[i][j] + " "); } System.out.println(); } } public static double[][] multiplyMatrix(double[][] a, double[][] b) { double[][] multiplyMatrix = new double[a.length][a[0].length]; for (int i = 0; i < multiplyMatrix.length; i++) { for (int j = 0; j < multiplyMatrix[i].length; j++) { multiplyMatrix[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j]; } } return multiplyMatrix; } }
3e04af28d6b63554471a83a7cb520c947ad185a9
10,865
java
Java
app/src/main/java/com/a7552_2c_2018/melliapp/activity/QuestionsActivity.java
7552-2C-2018/MelliApp
c9b261466f5a22bd81f1c02e791669b33b744ef7
[ "Apache-1.1" ]
null
null
null
app/src/main/java/com/a7552_2c_2018/melliapp/activity/QuestionsActivity.java
7552-2C-2018/MelliApp
c9b261466f5a22bd81f1c02e791669b33b744ef7
[ "Apache-1.1" ]
null
null
null
app/src/main/java/com/a7552_2c_2018/melliapp/activity/QuestionsActivity.java
7552-2C-2018/MelliApp
c9b261466f5a22bd81f1c02e791669b33b744ef7
[ "Apache-1.1" ]
null
null
null
37.081911
141
0.596318
1,968
package com.a7552_2c_2018.melliapp.activity; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import com.a7552_2c_2018.melliapp.R; import com.a7552_2c_2018.melliapp.adapters.QuestionsAdapter; import com.a7552_2c_2018.melliapp.model.Question; import com.a7552_2c_2018.melliapp.singletons.SingletonConnect; import com.a7552_2c_2018.melliapp.singletons.SingletonUser; import com.a7552_2c_2018.melliapp.utils.PopUpManager; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.StringRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import butterknife.BindView; import butterknife.ButterKnife; public class QuestionsActivity extends AppCompatActivity { private static final String TAG = "QuestionsActivity"; private static final int RESULT_ANSWER_ACTIVITY = 1; private String Id; private String user; @BindView(R.id.aqRecycler) RecyclerView recyclerView; @BindView(R.id.aqTvEmpty) TextView tvEmpty; @BindView(R.id.aqRlAsk) RelativeLayout rlAsk; @BindView(R.id.aqEtQuestion) EditText etQuestion; @BindView(R.id.aqBtSendQuestion) Button btnAsk; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_questions); ButterKnife.bind(this); Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); Objects.requireNonNull(getSupportActionBar()).setTitle(R.string.st_questions); Id = getIntent().getStringExtra("ID"); user = getIntent().getStringExtra("user"); tvEmpty.setVisibility(View.GONE); recyclerView.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 1); recyclerView.setLayoutManager(layoutManager); if (user.equals("seller")){ rlAsk.setVisibility(View.GONE); } etQuestion.setOnTouchListener((v, event) -> { v.setFocusable(true); v.setFocusableInTouchMode(true); return false; }); btnAsk.setOnClickListener(v -> { String qst = etQuestion.getText().toString(); if (qst.isEmpty()){ PopUpManager.showToastError(getApplicationContext(), getString(R.string.ia_ask_error)); } else { sendQuestion(qst); } }); final GestureDetector mGestureDetector = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return true; } }); recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() { @Override public void onRequestDisallowInterceptTouchEvent(boolean b) { } @Override public boolean onInterceptTouchEvent(@NonNull RecyclerView recyclerView, @NonNull MotionEvent motionEvent) { try { View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY()); if (child != null && mGestureDetector.onTouchEvent(motionEvent)) { int position = recyclerView.getChildAdapterPosition(child); QuestionsAdapter aux = (QuestionsAdapter) recyclerView.getAdapter(); if (!Objects.requireNonNull(aux).getQstItem(position).getHasResponse()){ Intent responseIntent = new Intent(getApplicationContext(), QuestionsResponseActivity.class); String qstId = Objects.requireNonNull(aux).getQstItem(position).getId(); responseIntent.putExtra("ID", qstId); startActivityForResult(responseIntent, RESULT_ANSWER_ACTIVITY); } return true; } }catch (Exception e){ e.printStackTrace(); } return false; } @Override public void onTouchEvent(@NonNull RecyclerView recyclerView, @NonNull MotionEvent motionEvent) { } }); getQuestions(); //mocking(); } private void sendQuestion(final String qst) { String REQUEST_TAG = "sendQuestion"; String url = getString(R.string.remote_questions); StringRequest stringRequest = new StringRequest(Request.Method.POST, url, response -> { Log.d(TAG, "Success"); etQuestion.setText(""); getQuestions(); PopUpManager.showToastError(getApplicationContext(), getString(R.string.ia_ask_ok)); }, error -> { Log.d(TAG, "volley error create " + error.getMessage()); //OR Log.d(TAG, "volley msg " +error.getLocalizedMessage()); //OR Log.d(TAG, "volley msg3 " +error.getLocalizedMessage()); //Or if nothing works than splitting is the only option Log.d(TAG, "volley msg4 " + new String(error.networkResponse.data)); PopUpManager.showToastError(getApplicationContext(), getString(R.string.general_error)); }) { @Override public String getBodyContentType() { return "application/x-www-form-urlencoded; charset=UTF-8"; } @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("postId", Id); params.put("question", qst); return params; } @Override public Map<String, String> getHeaders() { Map<String, String> params = new HashMap<>(); params.put("facebookId", SingletonUser.getInstance().getUser().getFacebookID()); params.put("token", SingletonUser.getInstance().getToken()); return params; } }; stringRequest.setRetryPolicy(new DefaultRetryPolicy( DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); Log.d(TAG, "request a enviar post questions: " + stringRequest); SingletonConnect.getInstance(getApplicationContext()).addToRequestQueue(stringRequest,REQUEST_TAG); } private void getQuestions() { String REQUEST_TAG = "getQuestions"; String url = getString(R.string.remote_questions); url = url + "postId=" + Id; JsonArrayRequest jsonArrayRequest = new JsonArrayRequest( Request.Method.GET, url, null, this::getQuestionsResponse, error -> { Log.d(TAG, "volley error check" + error.getMessage()); //OR Log.d(TAG, "volley msg " +error.getLocalizedMessage()); //OR Log.d(TAG, "volley msg3 " +error.getLocalizedMessage()); //Or if nothing works than splitting is the only option PopUpManager.showToastError(getApplicationContext(), getString(R.string.general_error)); }) { @Override public String getBodyContentType() { return "application/x-www-form-urlencoded; charset=UTF-8"; } @Override public Map<String, String> getHeaders() { Map<String, String> params = new HashMap<>(); params.put("facebookId", SingletonUser.getInstance().getUser().getFacebookID()); params.put("token", SingletonUser.getInstance().getToken()); return params; } }; SingletonConnect.getInstance(getApplicationContext()).addToRequestQueue(jsonArrayRequest,REQUEST_TAG); } private void getQuestionsResponse(JSONArray response) { Log.d(TAG, response.toString()); try { List<Question> input = new ArrayList<>(); Question item; if (response.length() == 0){ tvEmpty.setVisibility(View.VISIBLE); } for (int i = 0; i < response.length(); i++) { JSONObject jItem = response.getJSONObject(i); item = new Question(); item.setId(jItem.getString("ID")); item.setQuestion(jItem.getString("pregunta")); item.setUserId(jItem.getString("userId")); JSONObject jAux = jItem.getJSONObject("_id"); item.setPostId(jAux.getString("postId")); item.setDate(jAux.getLong("publication_date")); if (user.equals("seller")) { item.setCanAnswer(true); } if (jItem.has("answer")){ item.setHasResponse(true); item.setResponse(jItem.getString("answer")); item.setRespDate(jItem.getLong("answer_date")); } input.add(item); } RecyclerView.Adapter mAdapter = new QuestionsAdapter(input); recyclerView.setAdapter(mAdapter); } catch (JSONException e) { e.printStackTrace(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case RESULT_ANSWER_ACTIVITY: if (resultCode == RESULT_OK) { getQuestions(); } break; default: super.onActivityResult(requestCode,resultCode, data); } } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } }
3e04afc810d3755e719f1eba231f23f293a34011
467
java
Java
src/main/java/com/rbkmoney/analytics/listener/handler/BatchHandler.java
rbkmoney/analytics
b0f137708a1a05c3a30708f33763e1e7ebadad96
[ "Apache-2.0" ]
null
null
null
src/main/java/com/rbkmoney/analytics/listener/handler/BatchHandler.java
rbkmoney/analytics
b0f137708a1a05c3a30708f33763e1e7ebadad96
[ "Apache-2.0" ]
null
null
null
src/main/java/com/rbkmoney/analytics/listener/handler/BatchHandler.java
rbkmoney/analytics
b0f137708a1a05c3a30708f33763e1e7ebadad96
[ "Apache-2.0" ]
1
2021-12-07T09:03:32.000Z
2021-12-07T09:03:32.000Z
23.35
79
0.719486
1,969
package com.rbkmoney.analytics.listener.handler; import com.rbkmoney.analytics.listener.Processor; import com.rbkmoney.analytics.listener.mapper.Mapper; import java.util.List; import java.util.Map; public interface BatchHandler<C, P> { default boolean accept(C change) { return getMappers().stream().anyMatch(mapper -> mapper.accept(change)); } Processor handle(List<Map.Entry<P, C>> changes); <T> List<Mapper<C, P, T>> getMappers(); }
3e04b059f884ea6aec3a74b642cf483396678a79
8,191
java
Java
actividades/prog/files/java/mil-ejemplos/src/aplicaciones/terminal/shell/ShellAPIjava.java
TheXerax/libro-de-actividades
92091ed9f3f571edb8b392797a2c5369b6e485d2
[ "CC0-1.0" ]
null
null
null
actividades/prog/files/java/mil-ejemplos/src/aplicaciones/terminal/shell/ShellAPIjava.java
TheXerax/libro-de-actividades
92091ed9f3f571edb8b392797a2c5369b6e485d2
[ "CC0-1.0" ]
null
null
null
actividades/prog/files/java/mil-ejemplos/src/aplicaciones/terminal/shell/ShellAPIjava.java
TheXerax/libro-de-actividades
92091ed9f3f571edb8b392797a2c5369b6e485d2
[ "CC0-1.0" ]
null
null
null
31.75969
110
0.477178
1,970
/* * Autor: David Vargas <[email protected]> * Versión: 0.2.0 */ package terminal.shell; import java.io.File; import java.util.HashMap; import java.util.Date; /** * Esta clase implementa la misma funcionalidad que una consola<br> * o interfaz de modo comando.<br> * @author david */ public class ShellAPIjava implements InterfazShell { public static final String RUTA_INICIAL = "/home/david/tmp"; private boolean fin; private String salida; private String rutaActual; private HashMap<String, String> parametros; /** * Constructor de la clase ShellAPIjava */ public ShellAPIjava() { this.inicializar(); } public ShellAPIjava(String ruta_inicial) { this.inicializar(); rutaActual = ruta_inicial; } public boolean isFin() { return this.fin; } public void setEntrada(String entrada) { this.mapearEntrada(entrada); if (parametros.get("comando").equals("exit")) { fin = true; salida = "Saliendo de la consola virtual...\n"; } else if (parametros.get("comando").equals("help")) { salida = this.ejecutaRhelp(); } else if (parametros.get("comando").equals("cd")) { salida = this.ejecutaRcd(); } else if (parametros.get("comando").equals("dir")) { this.mapearEntrada(entrada + " -c"); salida = this.ejecutaRls(); } else if (parametros.get("comando").equals("ls")) { salida = this.ejecutaRls(); } else if (parametros.get("comando").equals("mkdir")) { salida = this.ejecutaRmkdir(); } else if (parametros.get("comando").equals("pwd")) { salida = this.ejecutaRpwd(); } else if (parametros.get("comando").equals("rmdir")) { salida = this.ejecutaRrmdir(); } else if (parametros.get("comando").equals("vdir")) { this.mapearEntrada(entrada + " -l -c"); salida = this.ejecutaRls(); } else { salida = "No se entiende la orden: " + entrada; } salida = salida + "\n" + this.getPrompt(); } public String getSalida() { if (fin) { salida = ""; } return salida; } public String getPrompt() { return "consola[" + rutaActual + "]$ "; } //Métodos privados private void inicializar() { fin = false; rutaActual = RUTA_INICIAL; salida = "Consola Virtual 0.1.3\n" + "Fecha: 2008-01-15\n" + "Autor: David Vargas\n"; salida = salida + "Sistema Operativo: " + System.getProperty("os.name") + "\n"; salida = salida + this.getPrompt(); parametros = new HashMap<String, String>(); } private void mapearEntrada(String entrada) { String p[] = entrada.trim().split(" "); parametros.clear(); parametros.put("comando", p[0]); for (int i = 1; i < p.length; i++) { parametros.put("parametro_" + i, p[i]); } } private String ejecutaRhelp() { String s = ""; s = s + "Ayuda de la ConsolaVirtual:\n"; s = s + " * help\t, muestra esta ayuda.\n"; s = s + " * exit\t, salir de la consola.\n"; s = s + "\n"; s = s + " * cd\t, cambia el directorio actual.\n"; s = s + " * ls\t, muestra el contenido del directorio.\n"; s = s + " * mkdir\t, crear un nuevo directorio.\n"; s = s + " * mv\t, renombrar archivo.\n"; s = s + " * pwd\t, muestra el directorio actual.\n"; return s; } private String ejecutaRcd() { File dir; salida = ""; try { if (parametros.size() == 1) { //Respuesta al comando 'cd' rutaActual = RUTA_INICIAL; } else { dir = new File(rutaActual + "/" + parametros.get("parametro_1")); dir = dir.getCanonicalFile(); if (dir.exists() && dir.isDirectory()) { rutaActual = dir.getCanonicalPath(); } else { salida = "Directorio " + parametros.get("parametro_1") + " incorrecto."; } } } catch (java.io.IOException e) { salida = e.toString(); } return salida; } private String ejecutaRls() { String s = ""; int total = 0; try { File dir = new File(rutaActual); File[] ficheros = dir.listFiles(); for (int i = 0; i < dir.listFiles().length; i++) { if (!parametros.containsValue("-a") && ficheros[i].isHidden()) { continue; } if (parametros.containsValue("-d") && !ficheros[i].isDirectory()) { continue; } if (parametros.containsValue("-l")) { s = s + this.getAtributosArchivo(ficheros[i]) + this.getNombreArchivo(ficheros[i]) + "\n"; } else { s = s + this.getNombreArchivo(ficheros[i]) + "\t"; } total++; } s = s + "\nTotal de archivos " + total + "\n"; } catch (Exception e) { System.err.println(e); } return s; } private String ejecutaRmkdir() { String s = ""; String ruta; try { if (parametros.size() != 2) { s = "Número de argumentos incorrecto."; } else { ruta = this.getRutaAbsoluta(parametros.get("parametro_1")); File f = new File(ruta); if (f.exists()) { s = "Existe el archivo " + ruta; } else { if (f.mkdir()) { s = "Directorio creado."; } else { s = "No se ha podido crear el directorio.\n"; s += "Revise los permisos."; } } } } catch (Exception e) { s = "[mkdir] " + e; } return s; } private String ejecutaRpwd() { return this.rutaActual; } private String ejecutaRrmdir() { String s = ""; String ruta; try { if (parametros.size() != 2) { s = "Número de argumentos incorrecto."; } else { ruta = this.getRutaAbsoluta(parametros.get("parametro_1")); File f = new File(ruta); if (!f.exists()||!f.isDirectory()) { s = "No existe el fichero " + ruta+" o no es un directorio."; } else { if (f.delete()) { s = "Directorio eliminado."; } else { s = "No se ha podido borar el directorio.\n"; s += "Revise los permisos o su contenido."; } } } } catch (Exception e) { s = "[mkdir] " + e; } return s; } private String getNombreArchivo(File fichero) { String s = fichero.getName(); if (parametros.containsValue("-c")) { s += (fichero.isDirectory() ? "/" : ""); s += (fichero.isFile() && fichero.canExecute() ? "*" : ""); } return s; } private String getAtributosArchivo(File fichero) { String s = ""; Date f = new Date(fichero.lastModified()); s += f.toString(); s += "\t" + fichero.length() + "\t"; s += (fichero.isDirectory() ? "d" : "-"); s += (fichero.isHidden() ? "h" : "-"); s += " "; s += (fichero.canRead() ? "r" : "-"); s += (fichero.canWrite() ? "w" : "-"); s += (fichero.canExecute() ? "x" : "-"); s += " \t"; return s; } private String getRutaAbsoluta(String fichero) { if (!fichero.startsWith("/") && !fichero.startsWith("c:\\")) { //Tenemos una ruta relativa fichero = this.rutaActual + "/" + fichero; } return fichero; } }
3e04b12feb0be9cc93e51392498c6f087905d306
1,798
java
Java
src/main/java/com/amazonaws/services/simpledb/model/transform/CreateDomainRequestMarshaller.java
pbailis/aws-java-sdk-dynamodb-timestamp
33d9beb9e8b8bf6965312c2c61c621ce96d054c8
[ "Apache-2.0" ]
2
2015-04-09T03:30:56.000Z
2020-07-06T20:23:21.000Z
src/main/java/com/amazonaws/services/simpledb/model/transform/CreateDomainRequestMarshaller.java
pbailis/aws-java-sdk-dynamodb-timestamp
33d9beb9e8b8bf6965312c2c61c621ce96d054c8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/amazonaws/services/simpledb/model/transform/CreateDomainRequestMarshaller.java
pbailis/aws-java-sdk-dynamodb-timestamp
33d9beb9e8b8bf6965312c2c61c621ce96d054c8
[ "Apache-2.0" ]
4
2015-02-03T19:36:40.000Z
2020-07-06T20:30:56.000Z
35.254902
126
0.746385
1,971
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpledb.model.transform; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.services.simpledb.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * Create Domain Request Marshaller */ public class CreateDomainRequestMarshaller implements Marshaller<Request<CreateDomainRequest>, CreateDomainRequest> { public Request<CreateDomainRequest> marshall(CreateDomainRequest createDomainRequest) { if (createDomainRequest == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } Request<CreateDomainRequest> request = new DefaultRequest<CreateDomainRequest>(createDomainRequest, "AmazonSimpleDB"); request.addParameter("Action", "CreateDomain"); request.addParameter("Version", "2009-04-15"); if (createDomainRequest.getDomainName() != null) { request.addParameter("DomainName", StringUtils.fromString(createDomainRequest.getDomainName())); } return request; } }
3e04b13c443bf798d6ad604ee8861f3b9b54c736
4,188
java
Java
IHMCRoboticsToolkit/src/us/ihmc/robotics/math/filters/BacklashProcessingYoVariable.java
wxmerkt/ihmc-open-robotics-software
2c47c9a9bd999e7811038e99c3888683f9973a2a
[ "Apache-2.0" ]
null
null
null
IHMCRoboticsToolkit/src/us/ihmc/robotics/math/filters/BacklashProcessingYoVariable.java
wxmerkt/ihmc-open-robotics-software
2c47c9a9bd999e7811038e99c3888683f9973a2a
[ "Apache-2.0" ]
null
null
null
IHMCRoboticsToolkit/src/us/ihmc/robotics/math/filters/BacklashProcessingYoVariable.java
wxmerkt/ihmc-open-robotics-software
2c47c9a9bd999e7811038e99c3888683f9973a2a
[ "Apache-2.0" ]
null
null
null
26.846154
153
0.654011
1,972
package us.ihmc.robotics.math.filters; import us.ihmc.robotics.MathTools; import us.ihmc.robotics.dataStructures.registry.YoVariableRegistry; import us.ihmc.robotics.dataStructures.variable.BooleanYoVariable; import us.ihmc.robotics.dataStructures.variable.DoubleYoVariable; import us.ihmc.robotics.dataStructures.variable.EnumYoVariable; /** * This does essentially the same as RevisedBacklashCompensatingVelocityYoVariable, except it takes a velocity signal as input. * */ public class BacklashProcessingYoVariable extends DoubleYoVariable implements ProcessingYoVariable { private final DoubleYoVariable velocity; private final BooleanYoVariable hasBeenCalled; private final EnumYoVariable<BacklashState> backlashState; private final DoubleYoVariable slopTime; private final DoubleYoVariable timeSinceSloppy; private final double dt; public BacklashProcessingYoVariable(String name, String description, double dt, DoubleYoVariable slopTime, YoVariableRegistry registry) { this(name, description, null, dt, slopTime, registry); } public BacklashProcessingYoVariable(String name, String description, DoubleYoVariable velocityVariable, double dt, DoubleYoVariable slopTime, YoVariableRegistry registry) { super(name, description, registry); this.hasBeenCalled = new BooleanYoVariable(name + "HasBeenCalled", registry); backlashState = new EnumYoVariable<BacklashState>(name + "BacklashState", registry, BacklashState.class, true); backlashState.set(null); timeSinceSloppy = new DoubleYoVariable(name + "TimeSinceSloppy", registry); velocity = velocityVariable; this.slopTime = slopTime; this.dt = dt; reset(); } public void reset() { hasBeenCalled.set(false); backlashState.set(null); } public void update() { if (velocity == null) { throw new NullPointerException( "BacklashProcessingYoVariable must be constructed with a non null " + "velocity variable to call update(), otherwise use update(double)"); } update(velocity.getDoubleValue()); } public void update(double currentVelocity) { if (backlashState.getEnumValue() == null) { backlashState.set(BacklashState.FORWARD_OK); } if (!hasBeenCalled.getBooleanValue()) { hasBeenCalled.set(true); set(currentVelocity); } timeSinceSloppy.add(dt); switch (backlashState.getEnumValue()) { case BACKWARD_OK: { if (currentVelocity > 0.0) { timeSinceSloppy.set(0.0); backlashState.set(BacklashState.FORWARD_SLOP); } break; } case FORWARD_OK: { if (currentVelocity < 0.0) { timeSinceSloppy.set(0.0); backlashState.set(BacklashState.BACKWARD_SLOP); } break; } case BACKWARD_SLOP: { if (currentVelocity > 0.0) { timeSinceSloppy.set(0.0); backlashState.set(BacklashState.FORWARD_SLOP); } else if (timeSinceSloppy.getDoubleValue() > slopTime.getDoubleValue()) { backlashState.set(BacklashState.BACKWARD_OK); } break; } case FORWARD_SLOP: { if (currentVelocity < 0.0) { timeSinceSloppy.set(0.0); backlashState.set(BacklashState.BACKWARD_SLOP); } else if (timeSinceSloppy.getDoubleValue() > slopTime.getDoubleValue()) { backlashState.set(BacklashState.FORWARD_OK); } break; } } double percent = timeSinceSloppy.getDoubleValue() / slopTime.getDoubleValue(); percent = MathTools.clipToMinMax(percent, 0.0, 1.0); if (Double.isNaN(percent) || slopTime.getDoubleValue() < dt) percent = 1.0; this.set(percent * currentVelocity); } public void setSlopTime(double slopTime) { this.slopTime.set(slopTime); } private enum BacklashState { BACKWARD_OK, FORWARD_OK, BACKWARD_SLOP, FORWARD_SLOP; } }
3e04b23506764640293c2e8bc9db90c224a6078e
88
java
Java
main/java/org/mozilla/javascript/resources/__resources_location__.java
Longor1996/talecraft
b5269dbc25a4d47667f9dec7fd2cbd912e33821a
[ "Unlicense", "MIT" ]
7
2015-08-11T12:39:25.000Z
2021-06-03T23:09:53.000Z
main/java/org/mozilla/javascript/resources/__resources_location__.java
Longor1996/talecraft
b5269dbc25a4d47667f9dec7fd2cbd912e33821a
[ "Unlicense", "MIT" ]
3
2015-06-04T18:40:34.000Z
2015-08-01T16:09:34.000Z
main/java/org/mozilla/javascript/resources/__resources_location__.java
Longor1996/talecraft
b5269dbc25a4d47667f9dec7fd2cbd912e33821a
[ "Unlicense", "MIT" ]
12
2015-03-12T19:57:47.000Z
2022-03-21T21:55:27.000Z
14.666667
41
0.829545
1,973
package org.mozilla.javascript.resources; public interface __resources_location__ { }
3e04b27a1aa9a13f4c470725cdd8500bd084e863
1,029
java
Java
xcc/java/tools/commandline/LocationClassApplicator.java
JianpingZeng/xcc
c756fa9a860ab4b713f29ab70f8478421105b7a0
[ "BSD-3-Clause" ]
28
2017-01-20T15:25:54.000Z
2020-03-17T00:28:31.000Z
xcc/java/tools/commandline/LocationClassApplicator.java
JianpingZeng/xcc
c756fa9a860ab4b713f29ab70f8478421105b7a0
[ "BSD-3-Clause" ]
1
2017-01-20T15:26:27.000Z
2018-08-20T00:55:37.000Z
xcc/java/tools/commandline/LocationClassApplicator.java
JianpingZeng/xcc
c756fa9a860ab4b713f29ab70f8478421105b7a0
[ "BSD-3-Clause" ]
2
2019-07-15T19:07:04.000Z
2019-09-07T14:21:04.000Z
28.583333
70
0.731778
1,974
/* * Extremely Compiler Collection * Copyright (c) 2015-2020, Jianping Zeng. * * 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 tools.commandline; /** * @author Jianping Zeng * @version 0.4 */ public class LocationClassApplicator<T> implements Modifier { private LocationClass<T> locationClass; public LocationClassApplicator(LocationClass<T> locClass) { locationClass = locClass; } @Override public void apply(Option<?> opt) { ((LocationOpt<T>) opt).setLocation(locationClass); } }
3e04b306ca0cd2acdc5041d3da4402d007ba4be3
1,486
java
Java
imagepipeline/src/main/java/com/facebook/imagepipeline/producers/ThreadHandoffProducerQueue.java
MaTriXy/fresco
e05b18eafe36c6809b889bfc9ccb66598eabda7b
[ "BSD-3-Clause" ]
10
2017-11-27T03:18:15.000Z
2021-08-10T07:21:44.000Z
imagepipeline/src/main/java/com/facebook/imagepipeline/producers/ThreadHandoffProducerQueue.java
MaTriXy/fresco
e05b18eafe36c6809b889bfc9ccb66598eabda7b
[ "BSD-3-Clause" ]
null
null
null
imagepipeline/src/main/java/com/facebook/imagepipeline/producers/ThreadHandoffProducerQueue.java
MaTriXy/fresco
e05b18eafe36c6809b889bfc9ccb66598eabda7b
[ "BSD-3-Clause" ]
10
2018-04-20T08:43:59.000Z
2022-03-16T02:52:53.000Z
25.186441
78
0.724764
1,975
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.imagepipeline.producers; import com.facebook.common.internal.Preconditions; import java.util.ArrayDeque; import java.util.Deque; import java.util.concurrent.Executor; public class ThreadHandoffProducerQueue { private boolean mQueueing = false; private final Deque<Runnable> mRunnableList; private final Executor mExecutor; public ThreadHandoffProducerQueue(Executor executor) { mExecutor = Preconditions.checkNotNull(executor); mRunnableList = new ArrayDeque<>(); } public synchronized void addToQueueOrExecute(Runnable runnable) { if (mQueueing) { mRunnableList.add(runnable); } else { mExecutor.execute(runnable); } } public synchronized void startQueueing() { mQueueing = true; } public synchronized void stopQueuing() { mQueueing = false; execInQueue(); } private void execInQueue() { while (!mRunnableList.isEmpty()) { mExecutor.execute(mRunnableList.pop()); } mRunnableList.clear(); } public synchronized void remove(Runnable runnable) { mRunnableList.remove(runnable); } public synchronized boolean isQueueing() { return mQueueing; } }
3e04b312ad728eeb3ed561f90e8c3e8568dd27a6
15,455
java
Java
src/main/java/no/nav/pto/veilarbportefolje/domene/Bruker.java
navikt/veilarbportefolje
f0cfdd79bc428327ce96543ae1fc041687f6bfa3
[ "MIT" ]
4
2020-01-09T16:02:54.000Z
2022-03-23T11:46:21.000Z
src/main/java/no/nav/pto/veilarbportefolje/domene/Bruker.java
navikt/veilarbportefolje
f0cfdd79bc428327ce96543ae1fc041687f6bfa3
[ "MIT" ]
46
2018-11-28T06:35:09.000Z
2022-03-21T10:45:08.000Z
src/main/java/no/nav/pto/veilarbportefolje/domene/Bruker.java
navikt/veilarbportefolje
f0cfdd79bc428327ce96543ae1fc041687f6bfa3
[ "MIT" ]
2
2020-04-06T09:24:31.000Z
2022-02-18T08:34:49.000Z
55.394265
224
0.716726
1,976
package no.nav.pto.veilarbportefolje.domene; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import lombok.extern.slf4j.Slf4j; import no.nav.pto.veilarbportefolje.arbeidsliste.Arbeidsliste; import no.nav.pto.veilarbportefolje.elastic.domene.Endring; import no.nav.pto.veilarbportefolje.elastic.domene.OppfolgingsBruker; import no.nav.pto.veilarbportefolje.postgres.PostgresUtils; import no.nav.pto.veilarbportefolje.util.OppfolgingUtils; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.*; import static no.nav.pto.veilarbportefolje.database.PostgresTable.BRUKER_VIEW.*; import static no.nav.pto.veilarbportefolje.domene.AktivitetFiltervalg.JA; import static no.nav.pto.veilarbportefolje.util.DateUtils.*; import static no.nav.pto.veilarbportefolje.util.OppfolgingUtils.vurderingsBehov; import static org.apache.commons.lang3.StringUtils.isNotEmpty; @Slf4j @Data @Accessors(chain = true) @AllArgsConstructor @NoArgsConstructor public class Bruker { String fnr; String fornavn; String etternavn; String veilederId; List<String> sikkerhetstiltak; String diskresjonskode; boolean egenAnsatt; boolean nyForVeileder; boolean nyForEnhet; boolean trengerVurdering; VurderingsBehov vurderingsBehov; boolean erDoed; String manuellBrukerStatus; int fodselsdagIMnd; LocalDateTime fodselsdato; String kjonn; YtelseMapping ytelse; LocalDateTime utlopsdato; ManedFasettMapping utlopsdatoFasett; Integer dagputlopUke; DagpengerUkeFasettMapping dagputlopUkeFasett; Integer permutlopUke; DagpengerUkeFasettMapping permutlopUkeFasett; Integer aapmaxtidUke; AAPMaxtidUkeFasettMapping aapmaxtidUkeFasett; AAPUnntakUkerIgjenFasettMapping aapUnntakUkerIgjenFasett; Integer aapUnntakUkerIgjen; Arbeidsliste arbeidsliste; LocalDateTime venterPaSvarFraNAV; LocalDateTime venterPaSvarFraBruker; LocalDateTime nyesteUtlopteAktivitet; LocalDateTime aktivitetStart; LocalDateTime nesteAktivitetStart; LocalDateTime forrigeAktivitetStart; LocalDateTime oppfolgingStartdato; LocalDateTime nesteUtlopsdatoAktivitet; List<String> brukertiltak; Map<String, Timestamp> aktiviteter = new HashMap<>(); LocalDateTime moteStartTid; LocalDateTime moteSluttTid; boolean erSykmeldtMedArbeidsgiver; String vedtakStatus; String ansvarligVeilederForVedtak; LocalDateTime vedtakStatusEndret; boolean trengerRevurdering; String sisteEndringKategori; LocalDateTime sisteEndringTidspunkt; String sisteEndringAktivitetId; public static Bruker of(OppfolgingsBruker bruker, boolean erVedtakstottePilotPa) { String formidlingsgruppekode = bruker.getFormidlingsgruppekode(); String kvalifiseringsgruppekode = bruker.getKvalifiseringsgruppekode(); String sikkerhetstiltak = bruker.getSikkerhetstiltak(); String profileringResultat = bruker.getProfilering_resultat(); String diskresjonskode = bruker.getDiskresjonskode(); LocalDateTime oppfolgingStartDato = toLocalDateTimeOrNull(bruker.getOppfolging_startdato()); boolean trengerVurdering = bruker.isTrenger_vurdering(); return new Bruker() .setFnr(bruker.getFnr()) .setNyForEnhet(bruker.isNy_for_enhet()) .setNyForVeileder(bruker.isNy_for_veileder()) .setTrengerVurdering(trengerVurdering) .setErSykmeldtMedArbeidsgiver(OppfolgingUtils.erSykmeldtMedArbeidsgiver(formidlingsgruppekode, kvalifiseringsgruppekode)) // Etiketten sykemeldt ska vises oavsett om brukeren har ett påbegynnt vedtak eller ej .setVurderingsBehov(trengerVurdering ? vurderingsBehov(formidlingsgruppekode, kvalifiseringsgruppekode, profileringResultat, erVedtakstottePilotPa) : null) .setFornavn(bruker.getFornavn()) .setEtternavn(bruker.getEtternavn()) .setVeilederId(bruker.getVeileder_id()) .setDiskresjonskode(("7".equals(diskresjonskode) || "6".equals(diskresjonskode)) ? diskresjonskode : null) .setEgenAnsatt(bruker.isEgen_ansatt()) .setErDoed(bruker.isEr_doed()) .setSikkerhetstiltak(sikkerhetstiltak == null ? new ArrayList<>() : Collections.singletonList(sikkerhetstiltak)) //TODO: Hvorfor er dette en liste? .setFodselsdagIMnd(bruker.getFodselsdag_i_mnd()) .setFodselsdato(toLocalDateTimeOrNull(bruker.getFodselsdato())) .setKjonn(bruker.getKjonn()) .setYtelse(YtelseMapping.of(bruker.getYtelse())) .setUtlopsdato(toLocalDateTimeOrNull(bruker.getUtlopsdato())) .setUtlopsdatoFasett(ManedFasettMapping.of(bruker.getUtlopsdatofasett())) .setDagputlopUke(bruker.getDagputlopuke()) .setDagputlopUkeFasett(DagpengerUkeFasettMapping.of(bruker.getDagputlopukefasett())) .setPermutlopUke(bruker.getPermutlopuke()) .setPermutlopUkeFasett(DagpengerUkeFasettMapping.of(bruker.getPermutlopukefasett())) .setAapmaxtidUke(bruker.getAapmaxtiduke()) .setAapmaxtidUkeFasett(AAPMaxtidUkeFasettMapping.of(bruker.getAapmaxtidukefasett())) .setAapUnntakUkerIgjen(bruker.getAapunntakukerigjen()) .setAapUnntakUkerIgjenFasett(AAPUnntakUkerIgjenFasettMapping.of(bruker.getAapunntakukerigjenfasett())) .setArbeidsliste(Arbeidsliste.of(bruker)) .setVenterPaSvarFraNAV(toLocalDateTimeOrNull(bruker.getVenterpasvarfranav())) .setVenterPaSvarFraBruker(toLocalDateTimeOrNull(bruker.getVenterpasvarfrabruker())) .setNyesteUtlopteAktivitet(toLocalDateTimeOrNull(bruker.getNyesteutlopteaktivitet())) .setAktivitetStart(toLocalDateTimeOrNull(bruker.getAktivitet_start())) .setNesteAktivitetStart(toLocalDateTimeOrNull(bruker.getNeste_aktivitet_start())) .setForrigeAktivitetStart(toLocalDateTimeOrNull(bruker.getForrige_aktivitet_start())) .setBrukertiltak(new ArrayList<>(bruker.getTiltak())) .setManuellBrukerStatus(bruker.getManuell_bruker()) .setMoteStartTid(toLocalDateTimeOrNull(bruker.getAktivitet_mote_startdato())) .setMoteSluttTid(toLocalDateTimeOrNull(bruker.getAktivitet_mote_utlopsdato())) .setVedtakStatus(bruker.getVedtak_status()) .setVedtakStatusEndret(toLocalDateTimeOrNull(bruker.getVedtak_status_endret())) .setAnsvarligVeilederForVedtak(bruker.getAnsvarlig_veileder_for_vedtak()) .setOppfolgingStartdato(oppfolgingStartDato) .setTrengerRevurdering(trengerRevurdering(bruker, erVedtakstottePilotPa)) .addAktivitetUtlopsdato("tiltak", dateToTimestamp(bruker.getAktivitet_tiltak_utlopsdato())) .addAktivitetUtlopsdato("behandling", dateToTimestamp(bruker.getAktivitet_behandling_utlopsdato())) .addAktivitetUtlopsdato("sokeavtale", dateToTimestamp(bruker.getAktivitet_sokeavtale_utlopsdato())) .addAktivitetUtlopsdato("stilling", dateToTimestamp(bruker.getAktivitet_stilling_utlopsdato())) .addAktivitetUtlopsdato("ijobb", dateToTimestamp(bruker.getAktivitet_ijobb_utlopsdato())) .addAktivitetUtlopsdato("egen", dateToTimestamp(bruker.getAktivitet_egen_utlopsdato())) .addAktivitetUtlopsdato("gruppeaktivitet", dateToTimestamp(bruker.getAktivitet_gruppeaktivitet_utlopsdato())) .addAktivitetUtlopsdato("mote", dateToTimestamp(bruker.getAktivitet_mote_utlopsdato())) .addAktivitetUtlopsdato("utdanningaktivitet", dateToTimestamp(bruker.getAktivitet_utdanningaktivitet_utlopsdato())); } public void kalkulerNesteUtlopsdatoAvValgtAktivitetFornklet(List<String> aktiviteterForenklet) { if (aktiviteterForenklet == null) { return; } aktiviteterForenklet.forEach(navnPaaAktivitet -> setNesteUtlopsdatoAktivitetHvisNyest(aktiviteter.get(navnPaaAktivitet.toLowerCase()))); } public void kalkulerNesteUtlopsdatoAvValgtAktivitetAvansert(Map<String, AktivitetFiltervalg> aktiviteterAvansert) { if (aktiviteterAvansert == null) { return; } aktiviteterAvansert.forEach((navnPaaAktivitet, valg) -> { if (JA.equals(valg)) { setNesteUtlopsdatoAktivitetHvisNyest(aktiviteter.get(navnPaaAktivitet.toLowerCase())); } }); } public boolean erKonfidensiell() { return (isNotEmpty(this.diskresjonskode)) || (this.egenAnsatt); } public void kalkulerSisteEndring(Map<String, Endring> siste_endringer, List<String> kategorier) { if (siste_endringer == null) { return; } kategorier.forEach(kategori -> { if (erNyesteKategori(siste_endringer, kategori)) { Endring endring = siste_endringer.get(kategori); sisteEndringKategori = kategori; sisteEndringTidspunkt = toLocalDateTimeOrNull(endring.getTidspunkt()); sisteEndringAktivitetId = endring.getAktivtetId(); } }); } private boolean erNyesteKategori(Map<String, Endring> siste_endringer, String kategori) { if (siste_endringer.get(kategori) == null) { return false; } LocalDateTime tidspunkt = toLocalDateTimeOrNull(siste_endringer.get(kategori).getTidspunkt()); return sisteEndringTidspunkt == null || (tidspunkt != null && tidspunkt.isAfter(sisteEndringTidspunkt)); } private Bruker addAktivitetUtlopsdato(String type, Timestamp utlopsdato) { if (Objects.isNull(utlopsdato) || isFarInTheFutureDate(utlopsdato)) { return this; } aktiviteter.put(type, utlopsdato); return this; } private static boolean trengerRevurdering(OppfolgingsBruker oppfolgingsBruker, boolean erVedtakstottePilotPa) { if (erVedtakstottePilotPa) { return oppfolgingsBruker.isTrenger_revurdering(); } return false; } private void setNesteUtlopsdatoAktivitetHvisNyest(Timestamp aktivitetUlopsdato) { if (aktivitetUlopsdato == null) { return; } if (nesteUtlopsdatoAktivitet == null) { nesteUtlopsdatoAktivitet = aktivitetUlopsdato.toLocalDateTime(); } else if (nesteUtlopsdatoAktivitet.isAfter(aktivitetUlopsdato.toLocalDateTime())) { nesteUtlopsdatoAktivitet = aktivitetUlopsdato.toLocalDateTime(); } } public Bruker fraEssensiellInfo(Map<String, Object> row) { String diskresjonskode = (String) row.get(DISKRESJONSKODE); String formidlingsgruppekode = (String) row.get(FORMIDLINGSGRUPPEKODE); return setNyForVeileder((boolean) row.get(NY_FOR_VEILEDER)) .setVeilederId((String) row.get(VEILEDERID)) .setDiskresjonskode((String) row.get(DISKRESJONSKODE)) .setFnr((String) row.get(FODSELSNR)) .setFornavn((String) row.get(FORNAVN)) .setEtternavn((String) row.get(ETTERNAVN)) .setDiskresjonskode(("7".equals(diskresjonskode) || "6".equals(diskresjonskode)) ? diskresjonskode : null) .setOppfolgingStartdato(toLocalDateTimeOrNull((Timestamp) row.get(STARTDATO))) .setArbeidsliste(new Arbeidsliste(null, null, null, null, null, null)); } public Bruker fraBrukerView(Map<String, Object> row, boolean erVedtakstottePilotPa) { String diskresjonskode = (String) row.get(DISKRESJONSKODE); String kvalifiseringsgruppekode = (String) row.get(KVALIFISERINGSGRUPPEKODE); String formidlingsgruppekode = (String) row.get(FORMIDLINGSGRUPPEKODE); String vedtakstatus = (String) row.get(VEDTAKSTATUS); String sikkerhetstiltak = (String) row.get(SIKKERHETSTILTAK_TYPE_KODE); String profileringResultat = (String) row.get(PROFILERING_RESULTAT); boolean trengerVurdering = OppfolgingUtils.trengerVurdering(formidlingsgruppekode, kvalifiseringsgruppekode); boolean trengerRevurdering = OppfolgingUtils.trengerRevurderingVedtakstotte(formidlingsgruppekode, kvalifiseringsgruppekode, vedtakstatus); boolean erSykmeldtMedArbeidsgiver = OppfolgingUtils.erSykmeldtMedArbeidsgiver(formidlingsgruppekode, kvalifiseringsgruppekode); return setFnr((String) row.get(FODSELSNR)) .setNyForVeileder(PostgresUtils.safeBool((boolean) row.get(NY_FOR_VEILEDER))) .setTrengerVurdering(trengerVurdering) .setErSykmeldtMedArbeidsgiver(erSykmeldtMedArbeidsgiver) // Etiketten sykemeldt ska vises oavsett om brukeren har ett påbegynnt vedtak eller ej; .setFornavn((String) row.get(FORNAVN)) .setEtternavn((String) row.get(ETTERNAVN)) .setVeilederId((String) row.get(VEILEDERID)) .setDiskresjonskode(("7".equals(diskresjonskode) || "6".equals(diskresjonskode)) ? diskresjonskode : null) .setEgenAnsatt(PostgresUtils.safeBool((boolean) row.get(SPERRET_ANSATT))) .setErDoed(PostgresUtils.safeBool((boolean) row.get(ER_DOED))) .setSikkerhetstiltak(sikkerhetstiltak == null ? new ArrayList<>() : Collections.singletonList(sikkerhetstiltak)) .setFodselsdato(toLocalDateTimeOrNull((java.sql.Date) row.get(FODSELS_DATO))) .setKjonn((String) row.get(KJONN)) .setVenterPaSvarFraNAV(toLocalDateTimeOrNull((Timestamp) row.get(VENTER_PA_NAV))) .setVenterPaSvarFraBruker(toLocalDateTimeOrNull((Timestamp) row.get(VENTER_PA_BRUKER))) .setVedtakStatus(vedtakstatus) .setVedtakStatusEndret(toLocalDateTimeOrNull((Timestamp) row.get(VEDTAKSTATUS_ENDRET_TIDSPUNKT))) .setOppfolgingStartdato(toLocalDateTimeOrNull((Timestamp) row.get(STARTDATO))) .setAnsvarligVeilederForVedtak((String) row.get(VEDTAKSTATUS_ANSVARLIG_VEILDERNAVN)) .setOppfolgingStartdato(toLocalDateTimeOrNull((Timestamp) row.get(STARTDATO))) .setTrengerRevurdering(trengerRevurdering) .setArbeidsliste(Arbeidsliste.of(row)) .setVurderingsBehov(trengerVurdering ? vurderingsBehov(formidlingsgruppekode, kvalifiseringsgruppekode, profileringResultat, erVedtakstottePilotPa) : null); //TODO: utledd manuell } // TODO: sjekk om disse feltene er i bruk, de kan være nødvendige for statuser eller filtere /* public static final String MANUELL = "MANUELL"; public static final String ISERV_FRA_DATO = "ISERV_FRA_DATO"; public static final String FORMIDLINGSGRUPPEKODE = "FORMIDLINGSGRUPPEKODE"; public static final String KVALIFISERINGSGRUPPEKODE = "KVALIFISERINGSGRUPPEKODE"; public static final String RETTIGHETSGRUPPEKODE = "RETTIGHETSGRUPPEKODE"; public static final String HOVEDMAALKODE = "HOVEDMAALKODE"; public static final String SIKKERHETSTILTAK_TYPE_KODE = "SIKKERHETSTILTAK_TYPE_KODE"; public static final String HAR_OPPFOLGINGSSAK = "HAR_OPPFOLGINGSSAK"; */ }
3e04b3293058d129f7bbaa13d17518646b0f5674
1,430
java
Java
hazelcast/src/main/java/com/hazelcast/queue/PeekOperation.java
seeburger-ag/hazelcast
4d9259fdd709ab30448d15d339e6230e7f02acdf
[ "Apache-2.0" ]
1
2015-06-30T09:57:29.000Z
2015-06-30T09:57:29.000Z
hazelcast/src/main/java/com/hazelcast/queue/PeekOperation.java
SunGard-Labs/hazelcast
291345b5cd4d019c80d2eb8938b1c23f69bdd344
[ "Apache-2.0" ]
8
2022-01-07T17:05:44.000Z
2022-03-31T17:40:13.000Z
hazelcast/src/main/java/com/hazelcast/queue/PeekOperation.java
SunGard-Labs/hazelcast
291345b5cd4d019c80d2eb8938b1c23f69bdd344
[ "Apache-2.0" ]
1
2022-03-08T12:46:55.000Z
2022-03-08T12:46:55.000Z
27.5
95
0.7
1,977
/* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.queue; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; /** * User: ali * Date: 11/23/12 * Time: 3:56 AM */ public final class PeekOperation extends QueueOperation implements IdentifiedDataSerializable { public PeekOperation() { } public PeekOperation(final String name) { super(name); } public void run() { QueueItem item = getOrCreateContainer().peek(); response = item != null ? item.getData() : null; } public void afterRun() throws Exception { getQueueService().getLocalQueueStatsImpl(name).incrementOtherOperations(); } public int getFactoryId() { return QueueDataSerializerHook.F_ID; } public int getId() { return QueueDataSerializerHook.PEEK; } }
3e04b3d2911f82e9ea5deb967644071745c490c5
1,263
java
Java
backend/src/test/java/com/redhat/cloud/notifications/utils/LineBreakRemoverTest.java
dgaikwad/notifications-backend
b911cae311afbacf89e74a5e845c70472ced95e6
[ "Apache-2.0" ]
6
2019-07-13T18:11:52.000Z
2022-03-15T15:09:10.000Z
backend/src/test/java/com/redhat/cloud/notifications/utils/LineBreakRemoverTest.java
dgaikwad/notifications-backend
b911cae311afbacf89e74a5e845c70472ced95e6
[ "Apache-2.0" ]
633
2019-01-24T13:18:53.000Z
2022-03-31T19:18:06.000Z
backend/src/test/java/com/redhat/cloud/notifications/utils/LineBreakRemoverTest.java
dgaikwad/notifications-backend
b911cae311afbacf89e74a5e845c70472ced95e6
[ "Apache-2.0" ]
36
2019-02-14T13:11:25.000Z
2022-03-24T13:02:33.000Z
29.372093
74
0.666667
1,978
package com.redhat.cloud.notifications.utils; import org.junit.jupiter.api.Test; import static com.redhat.cloud.notifications.utils.LineBreakCleaner.clean; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; public class LineBreakRemoverTest { @Test void testCr() { String initialValue = "Hello,\r world\r"; assertTrue(initialValue.contains("\r")); String cleanedValue = clean(initialValue); assertFalse(cleanedValue.contains("\r")); } @Test void testLf() { String initialValue = "Hello,\n world\n"; assertTrue(initialValue.contains("\n")); String cleanedValue = clean(initialValue); assertFalse(cleanedValue.contains("\n")); } @Test void testCrLf() { String initialValue = "Hello,\r\n world\r\n"; assertTrue(initialValue.contains("\r")); assertTrue(initialValue.contains("\n")); String cleanedValue = clean(initialValue); assertFalse(cleanedValue.contains("\r")); assertFalse(cleanedValue.contains("\n")); } @Test void testNull() { assertNull(clean(null)); } }
3e04b5177927b6ee1f2f198cc7315546cd895eb7
105
java
Java
hub/config/src/main/java/uk/gov/ida/hub/config/domain/EntityIdentifiable.java
uk-gov-mirror/alphagov.verify-hub
0511d9cdc41a668f3aaca414d7088b69dd2e4eb2
[ "MIT" ]
10
2017-12-08T17:13:09.000Z
2020-11-20T11:05:12.000Z
hub/config/src/main/java/uk/gov/ida/hub/config/domain/EntityIdentifiable.java
uk-gov-mirror/alphagov.verify-hub
0511d9cdc41a668f3aaca414d7088b69dd2e4eb2
[ "MIT" ]
212
2017-12-11T09:53:52.000Z
2022-03-31T00:27:54.000Z
hub/config/src/main/java/uk/gov/ida/hub/config/domain/EntityIdentifiable.java
uk-gov-mirror/alphagov.verify-hub
0511d9cdc41a668f3aaca414d7088b69dd2e4eb2
[ "MIT" ]
6
2017-12-08T17:13:22.000Z
2021-04-10T18:07:44.000Z
17.5
37
0.761905
1,979
package uk.gov.ida.hub.config.domain; public interface EntityIdentifiable { String getEntityId(); }
3e04b65c589af30247fc707ccfffc5365482100a
1,418
java
Java
src/main/java/net/pl3x/minimap/queue/ReadQueue.java
CyberFlameGO/MiniMap
1ef8edc9ab77466571b46f873d23906aac66f291
[ "MIT" ]
2
2022-03-01T12:02:32.000Z
2022-03-01T13:52:38.000Z
src/main/java/net/pl3x/minimap/queue/ReadQueue.java
CyberFlameGO/MiniMap
1ef8edc9ab77466571b46f873d23906aac66f291
[ "MIT" ]
null
null
null
src/main/java/net/pl3x/minimap/queue/ReadQueue.java
CyberFlameGO/MiniMap
1ef8edc9ab77466571b46f873d23906aac66f291
[ "MIT" ]
1
2022-03-23T09:09:24.000Z
2022-03-23T09:09:24.000Z
27.803922
104
0.617772
1,980
package net.pl3x.minimap.queue; import net.pl3x.minimap.tile.Image; import net.pl3x.minimap.tile.Tile; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import java.awt.image.BufferedImage; import java.io.IOException; import java.nio.file.Files; public class ReadQueue implements QueueAction { private final Tile tile; public ReadQueue(Tile tile) { this.tile = tile; } @Override public void run() { read(this.tile.getBaseImage()); read(this.tile.getBiomesImage()); read(this.tile.getHeightmapImage()); read(this.tile.getFluidsImage()); read(this.tile.getLightmapImage()); this.tile.upload(); this.tile.setReady(true); } private void read(Image image) { if (!Files.exists(image.path())) { return; } ImageReader reader = null; try (ImageInputStream in = ImageIO.createImageInputStream(Files.newInputStream(image.path()))) { reader = ImageIO.getImageReadersByFormatName("png").next(); reader.setInput(in, true, false); BufferedImage buffer = reader.read(0); image.setPixels(buffer); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { reader.dispose(); } } } }
3e04b8e9f5896a83fbd56c206eab7491804d39af
580
java
Java
src/com/iterlife/xdp/tmpmethod/ConcreteClass1.java
LuJie0403/iterlife-apollo
fcd848f53653164e019736461f1b638a3e61b644
[ "MIT" ]
null
null
null
src/com/iterlife/xdp/tmpmethod/ConcreteClass1.java
LuJie0403/iterlife-apollo
fcd848f53653164e019736461f1b638a3e61b644
[ "MIT" ]
null
null
null
src/com/iterlife/xdp/tmpmethod/ConcreteClass1.java
LuJie0403/iterlife-apollo
fcd848f53653164e019736461f1b638a3e61b644
[ "MIT" ]
null
null
null
19.333333
57
0.724138
1,981
package com.iterlife.xdp.tmpmethod; /** * @Description:com.iterlife.xdp.tmpmethod.ConcreteClass1 * * @author:Lu Jie * @date:2015-7-25 上午10:12:55 * @version:1.0.0 * @copyright:https://github.com/LuJie0403 */ public class ConcreteClass1 extends AbstractClass { @Override protected void doSomething1() { System.out.println("ConcreteClass1.doSomething1()"); } @Override protected void doSomething2() { System.out.println("ConcreteClass1.doSomething2()"); } @Override protected void doSomething3() { System.out.println("ConcreteClass1.doSomething3()"); } }
3e04b91902f16cd0b7204c82d1e610fe1fc863fc
2,455
java
Java
backend/vertical-healthcare_ch/forum_datenaustausch_ch.invoice_base/src/main/java/de/metas/vertical/healthcare_ch/forum_datenaustausch_ch/base/Types.java
dram/metasfresh
a1b881a5b7df8b108d4c4ac03082b72c323873eb
[ "RSA-MD" ]
1,144
2016-02-14T10:29:35.000Z
2022-03-30T09:50:41.000Z
backend/vertical-healthcare_ch/forum_datenaustausch_ch.invoice_base/src/main/java/de/metas/vertical/healthcare_ch/forum_datenaustausch_ch/base/Types.java
dram/metasfresh
a1b881a5b7df8b108d4c4ac03082b72c323873eb
[ "RSA-MD" ]
8,283
2016-04-28T17:41:34.000Z
2022-03-30T13:30:12.000Z
backend/vertical-healthcare_ch/forum_datenaustausch_ch.invoice_base/src/main/java/de/metas/vertical/healthcare_ch/forum_datenaustausch_ch/base/Types.java
dram/metasfresh
a1b881a5b7df8b108d4c4ac03082b72c323873eb
[ "RSA-MD" ]
441
2016-04-29T08:06:07.000Z
2022-03-28T06:09:56.000Z
22.318182
81
0.709165
1,982
package de.metas.vertical.healthcare_ch.forum_datenaustausch_ch.base; import lombok.Getter; import lombok.NonNull; import java.util.Map; import com.google.common.collect.ImmutableMap; import de.metas.util.Check; /* * #%L * vertical-healthcare_ch.invoice_gateway.forum_datenaustausch_ch.invoice_commons * %% * Copyright (C) 2018 metas GmbH * %% * 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 2 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/gpl-2.0.html>. * #L% */ public class Types { public enum RequestType { INVOICE("invoice"), REMINDER("reminder"); @Getter private final String value; private RequestType(String value) { this.value = value; } } public enum Language { DE("de", "de_CH"), IT("it", "it_CH"), FR("fr", "fr_CH"); public static Language ofXmlValue(@NonNull final String xmlValue) { return Check.assumeNotNull( LANGUAGES.get(xmlValue), "There needs to be a language for the given xmlValue={}", xmlValue); } @Getter private final String xmlValue; @Getter private final String metasfreshValue; private static final Map<String, Language> LANGUAGES = ImmutableMap.of( DE.getXmlValue(), DE, IT.getXmlValue(), IT, FR.getXmlValue(), FR); private Language(String xmlValue, String metasfreshValue) { this.xmlValue = xmlValue; this.metasfreshValue = metasfreshValue; } } public enum Mode { PRODUCTION("production"), TEST("test"); private static final Map<String, Mode> MODES = ImmutableMap.of( PRODUCTION.getXmlValue(), PRODUCTION, TEST.getXmlValue(), TEST); public static Mode ofXmlValue(@NonNull final String xmlValue) { return Check.assumeNotNull( MODES.get(xmlValue), "There needs to be a mode for the given xmlValue={}", xmlValue); } @Getter private final String xmlValue; private Mode(String xmlValue) { this.xmlValue = xmlValue; } } }
3e04b931d8027a8e97ee977fb40b6d3094362a60
28,876
java
Java
src/net/sf/markov4jmeter/testplangenerator/TestPlanGenerator.java
tangerstein/wessbas.testPlanGenerator
bde4d1696c2d7f204d7606bdba2145232aa7de0e
[ "Apache-2.0" ]
null
null
null
src/net/sf/markov4jmeter/testplangenerator/TestPlanGenerator.java
tangerstein/wessbas.testPlanGenerator
bde4d1696c2d7f204d7606bdba2145232aa7de0e
[ "Apache-2.0" ]
1
2016-03-14T11:10:41.000Z
2016-03-14T11:10:41.000Z
src/net/sf/markov4jmeter/testplangenerator/TestPlanGenerator.java
tangerstein/wessbas.testPlanGenerator
bde4d1696c2d7f204d7606bdba2145232aa7de0e
[ "Apache-2.0" ]
3
2016-02-22T17:26:42.000Z
2017-09-21T10:49:53.000Z
35.398284
90
0.617483
1,983
/*************************************************************************** * Copyright (c) 2016 the WESSBAS project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ***************************************************************************/ package net.sf.markov4jmeter.testplangenerator; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Locale; import m4jdsl.WorkloadModel; import m4jdsl.impl.M4jdslPackageImpl; import net.sf.markov4jmeter.testplangenerator.transformation.AbstractTestPlanTransformer; import net.sf.markov4jmeter.testplangenerator.transformation.SimpleTestPlanTransformer; import net.sf.markov4jmeter.testplangenerator.transformation.TransformationException; import net.sf.markov4jmeter.testplangenerator.transformation.filters.AbstractFilter; import net.sf.markov4jmeter.testplangenerator.transformation.filters.HeaderDefaultsFilter; import net.sf.markov4jmeter.testplangenerator.util.CSVHandler; import net.sf.markov4jmeter.testplangenerator.util.Configuration; import org.apache.commons.cli.ParseException; import org.apache.jmeter.save.SaveService; import org.apache.jorphan.collections.ListedHashTree; import wessbas.commons.util.XmiEcoreHandler; /** * Generator class for building Test Plans which result from M4J-DSL models. * * <p>The generator must be initialized before it can be used properly; * hence, the {@link #init(String)} method must be called once for initializing * the default configuration of Test Plan elements. The name of the * configuration properties file must be passed to the initialization method * therefore. The {@link #isInitialized()} method might be used for requesting * the initialization status of the generator. * * <p>An M4J-DSL model for which a Test Plan shall be generated, might be passed * to the regarding <code>generate()</code> method; the model might be even * loaded from an XMI file alternatively, requiring the related filename to be * passed to the regarding <code>generate()</code> method. * * @author Eike Schulz ([email protected]) * @version 1.0 * @since 1.7 */ public class TestPlanGenerator { /* IMPLEMENTATION NOTE: * -------------------- * The following elements of the Test Plan Factory have not been used for * creating Markov4JMeter Test Plans, but they are already supported by the * framework: * * WhileController whileController = testPlanElementFactory.createWhileController(); * IfController ifController = testPlanElementFactory.createIfController(); * CounterConfig counterConfig = testPlanElementFactory.createCounterConfig(); * * The following elements are just required as nested parts for other types * of Test Plan elements, but they can be even created independently: * * Arguments arguments = testPlanElementFactory.createArguments(); * LoopController loopController = testPlanElementFactory.createLoopController(); */ /** Default properties file for the Test Plan Generator, to be used in case * no user-defined properties file can be read from command line. */ private final static String GENERATOR_DEFAULT_PROPERTIES = "configuration/generator.default.properties"; /** Property key for the JMeter home directory. */ private final static String PKEY_JMETER__HOME = "jmeter_home"; /** Property key for the JMeter default properties. */ private final static String PKEY_JMETER__PROPERTIES = "jmeter_properties"; /** Property key for the language tag which indicates the locality. */ private final static String PKEY_JMETER__LANGUAGE_TAG = "jmeter_languageTag"; /** Property key for the flag which indicates whether the generation process * shall be aborted, if undefined arguments are detected. */ private final static String PKEY_USE_FORCED_ARGUMENTS = "useForcedArguments"; // info-, warn- and error-messages (names should be self-explaining); private final static String ERROR_CONFIGURATION_UNDEFINED = "Configuration file is null."; private final static String ERROR_CONFIGURATION_NOT_FOUND = "Could not find configuration file \"%s\"."; private final static String ERROR_CONFIGURATION_READING_FAILED = "Could not read configuration file \"%s\"."; private final static String ERROR_TEST_PLAN_PROPERTIES_UNDEFINED = "Test Plan properties file is null."; private final static String ERROR_TEST_PLAN_PROPERTIES_NOT_FOUND = "Could not find Test Plan properties file \"%s\"."; private final static String ERROR_TEST_PLAN_PROPERTIES_READING_FAILED = "Could not read Test Plan properties file \"%s\"."; private final static String ERROR_INITIALIZATION_FAILED = "Initialization of Test Plan Generator failed."; private final static String ERROR_INPUT_FILE_COULD_NOT_BE_READ = "Input file \"%s\" could not be read: %s"; private final static String ERROR_OUTPUT_FILE_COULD_NOT_BE_WRITTEN = "Output file \"%s\" could not be written: %s"; private final static String ERROR_OUTPUT_FILE_ACCESS_FAILED = "Could not access file \"%s\" for writing output data: %s"; private final static String ERROR_TREE_SAVING_FAILED = "Could not save Test Plan tree \"%s\" via SaveService: %s"; private final static String INFO_INITIALIZATION_SUCCESSFUL = "Test Plan Generator has been successfully initialized."; private final static String INFO_TEST_PLAN_GENERATION_STARTED = "Generating Test Plan ..."; private final static String ERROR_TEST_PLAN_GENERATION_FAILED = "Test Plan generation failed."; private final static String INFO_MODEL_VALIDATION_SUCCESSFUL = "Validation of M4J-DSL model successful."; private final static String ERROR_MODEL_VALIDATION_FAILED = "Validation of M4J-DSL model failed."; private final static String WARNING_OUTPUT_FILE_CLOSING_FAILED = "Could not close file-output stream for file \"%s\": %s"; private final static String ERROR_TEST_PLAN_RUN_FAILED = "Could not run Test Plan \"%s\": %s"; /* ********************* global (non-final) fields ******************** */ /** Factory to be used for creating Test Plan elements. */ private TestPlanElementFactory testPlanElementFactory; /* ************************** public methods ************************** */ /** * Returns the Test Plan Factory associated with the Test Plan Generator. * * @return * a valid Test Plan Factory, if the Test Plan Generator has been * initialized successfully; otherwise <code>null</code> will be * returned. */ public TestPlanElementFactory getTestPlanElementFactory () { return this.testPlanElementFactory; } /** * Returns the information whether the Test Plan Generator is initialized, * meaning that the {@link #init(String)} method has been called * successfully. * * @return * <code>true</code> if and only if the Test Plan Generator is * initialized. */ public boolean isInitialized () { return this.testPlanElementFactory != null; } /** * Initializes the Test Plan Generator by loading the specified * configuration file and setting its properties accordingly. * * @param configurationFile * properties file which provides required or optional properties. * @param testPlanProperties * file with Test Plan default properties. */ public void init ( final String configurationFile, final String testPlanProperties) { // read the configuration and give an error message, if reading fails; // in that case, null will be returned; final Configuration configuration = this.readConfiguration(configurationFile); if (configuration != null) { // could configuration be read? final boolean useForcedArguments = configuration.getBoolean( TestPlanGenerator.PKEY_USE_FORCED_ARGUMENTS); final String jMeterHome = configuration.getString( TestPlanGenerator.PKEY_JMETER__HOME); final String jMeterProperties = configuration.getString( TestPlanGenerator.PKEY_JMETER__PROPERTIES); final String jMeterLanguageTag = configuration.getString( TestPlanGenerator.PKEY_JMETER__LANGUAGE_TAG); final Locale jMeterLocale = Locale.forLanguageTag(jMeterLanguageTag); final boolean success = JMeterEngineGateway.getInstance().initJMeter( jMeterHome, jMeterProperties, jMeterLocale); if (success) { // create a factory which builds Test Plan elements according // to the specified properties. this.testPlanElementFactory = this.createTestPlanFactory( testPlanProperties, useForcedArguments); if (this.testPlanElementFactory != null) { this.logInfo( TestPlanGenerator.INFO_INITIALIZATION_SUCCESSFUL); return; } } } this.logError(TestPlanGenerator.ERROR_INITIALIZATION_FAILED); } /** * Generates a Test Plan for the given workload model and writes the result * into the specified file. * * @param workloadModel * workload model which provides the values for the Test Plan to be * generated. * @param testPlanTransformer * builder to be used for building a Test Plan of certain structure. * @param filters * (optional) modification filters to be finally applied on the newly * generated Test Plan. * @param outputFilename * name of the file where the Test Plan shall be stored in. * * @return * the generated Test Plan, or <code>null</code> if any error occurs. * * @throws TransformationException * if any critical error in the transformation process occurs. */ public ListedHashTree generate ( final WorkloadModel workloadModel, final AbstractTestPlanTransformer testPlanTransformer, final AbstractFilter[] filters, final String outputFilename) throws TransformationException { ListedHashTree testPlanTree = null; // to be returned; final boolean validationSuccessful; this.logInfo(TestPlanGenerator.INFO_TEST_PLAN_GENERATION_STARTED); //validationSuccessful = validator.validateAndPrintResult(workloadModel); validationSuccessful = true; this.logInfo(TestPlanGenerator.INFO_MODEL_VALIDATION_SUCCESSFUL); if (!validationSuccessful) { this.logError(TestPlanGenerator.ERROR_MODEL_VALIDATION_FAILED); this.logError(TestPlanGenerator.ERROR_TEST_PLAN_GENERATION_FAILED); } else { // validation successful -> generate Test Plan output file; testPlanTree = testPlanTransformer.transform( workloadModel, this.testPlanElementFactory, filters); final boolean success = this.writeOutput(testPlanTree, outputFilename); if (!success) { this.logError( TestPlanGenerator.ERROR_TEST_PLAN_GENERATION_FAILED); } } return testPlanTree; } /** * Generates a Test Plan for the (Ecore) workload model which is stored in * the given XMI-file; the result will be written into the specified output * file. * * @param inputFile * XMI file containing the (Ecore) workload model which provides the * values for the Test Plan to be generated. * @param outputFile * name of the file where the Test Plan shall be stored in. * @param testPlanTransformer * builder to be used for building a Test Plan of certain structure. * @param filters * (optional) modification filters to be finally applied on the newly * generated Test Plan. * * @return * the generated Test Plan, or <code>null</code> if any error occurs. * * @throws IOException * in case any file reading or writing operation failed. * @throws TransformationException * if any critical error in the transformation process occurs. */ public ListedHashTree generate ( final String inputFile, final String outputFile, final AbstractTestPlanTransformer testPlanTransformer, final AbstractFilter[] filters) throws IOException, TransformationException { // initialize the model package; M4jdslPackageImpl.init(); // might throw an IOException; final WorkloadModel workloadModel = (WorkloadModel) XmiEcoreHandler.getInstance().xmiToEcore(inputFile, "xmi"); return this.generate( workloadModel, testPlanTransformer, filters, outputFile); } /* ************************* protected methods ************************ */ /** * Writes a given Test Plan into the specified output file. * * @param testPlanTree Test Plan to be written into the output file. * @param outputFilename name of the output file. */ protected boolean writeOutput ( final ListedHashTree testPlanTree, final String outputFilename) { boolean success = true; FileOutputStream fileOutputStream = null; try { // might throw a FileNotFoundException or SecurityException; fileOutputStream = new FileOutputStream(outputFilename); // might throw an IOException; SaveService.saveTree(testPlanTree, fileOutputStream); } catch (final FileNotFoundException ex) { final String message = String.format( TestPlanGenerator.ERROR_OUTPUT_FILE_COULD_NOT_BE_WRITTEN, outputFilename, ex.getMessage()); this.logError(message); success = false; } catch (final SecurityException ex) { final String message = String.format( TestPlanGenerator.ERROR_OUTPUT_FILE_ACCESS_FAILED, outputFilename, ex.getMessage()); this.logError(message); success = false; } catch (final IOException ex) { final String message = String.format( TestPlanGenerator.ERROR_TREE_SAVING_FAILED, outputFilename, ex.getMessage()); this.logError(message); success = false; } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (final IOException ex) { final String message = String.format( TestPlanGenerator.WARNING_OUTPUT_FILE_CLOSING_FAILED, outputFilename, ex.getMessage()); this.logWarning(message); // success remains true, since output file content has been // written, just the file could not be closed; } } } return success; } /* ************************** private methods ************************* */ /** * Reads all configuration properties from the specified file and gives an * error message, if reading fails. * * @param propertiesFile properties file to be read. * * @return * a valid configuration, if the specified properties file could be * read successfully; otherwise <code>null</code> will be returned. */ private Configuration readConfiguration (final String propertiesFile) { Configuration configuration = new Configuration(); try { // might throw FileNotFound-, IO-, or NullPointerException; configuration.load(propertiesFile); } catch (final FileNotFoundException ex) { final String message = String.format( TestPlanGenerator.ERROR_CONFIGURATION_NOT_FOUND, propertiesFile); this.logError(message); configuration = null; // indicates an error; } catch (final IOException ex) { final String message = String.format( TestPlanGenerator.ERROR_CONFIGURATION_READING_FAILED, propertiesFile); this.logError(message); configuration = null; // indicates an error; } catch (final NullPointerException ex) { this.logError(TestPlanGenerator.ERROR_CONFIGURATION_UNDEFINED); configuration = null; // indicates an error; } return configuration; } /** * Creates a Factory which builds Test Plan according to the default * properties defined in the specified file. * * @param propertiesFile * properties file with default properties for Test Plan elements. * @param useForcedValues * <code>true</code> if and only if the generation process shall be * aborted, if undefined arguments are detected. * * @return * a valid Test Plan Factory if the properties file could be read * successfully; otherwise <code>null</code> will be returned. */ private TestPlanElementFactory createTestPlanFactory ( final String propertiesFile, final boolean useForcedValues) { // to be returned; TestPlanElementFactory testPlanElementFactory = null; final Configuration testPlanProperties = new Configuration(); try { // might throw FileNotFound-, IO-, or NullPointerException; testPlanProperties.load(propertiesFile); // store factory globally for regular and simplified access; testPlanElementFactory = new TestPlanElementFactory( testPlanProperties, useForcedValues); } catch (final FileNotFoundException ex) { final String message = String.format( TestPlanGenerator.ERROR_TEST_PLAN_PROPERTIES_NOT_FOUND, propertiesFile); this.logError(message); } catch (final IOException ex) { final String message = String.format( TestPlanGenerator.ERROR_TEST_PLAN_PROPERTIES_READING_FAILED, propertiesFile); this.logError(message); } catch (final NullPointerException ex) { this.logError( TestPlanGenerator.ERROR_TEST_PLAN_PROPERTIES_UNDEFINED); } return testPlanElementFactory; } /** * Logs an information to standard output. * * @param message information to be logged. */ private void logInfo (final String message) { // TODO: remove print-command, solve the issue below; System.out.println(message); // this command would print in red color, indicating an error: // // TestPlanGenerator.LOG.info(message); // // --> adjust "commons-logging.properties" accordingly; // --> even better: use JMeter logging unit; } /** * Logs a warning message to standard output. * * @param message warning message to be logged. */ private void logWarning (final String message) { // TODO: remove print-command, solve the issue below; System.err.println(message); // this command would print in non-uniform format: // // TestPlanGenerator.LOG.warning(message); // // --> adjust "commons-logging.properties" accordingly; // --> even better: use JMeter logging unit; } /** * Logs an error message to standard output. * * @param message error message to be logged. */ private void logError (final String message) { // TODO: remove print-command, solve the issue below; System.err.println(message); // this command would print in non-uniform format: // // TestPlanGenerator.LOG.error(message); // // --> adjust "commons-logging.properties" accordingly; // --> even better: use JMeter logging unit; } /** * Generates a Test Plan for the (Ecore) workload model which is stored in * the given XMI-file; the result will be written into the specified output * file. * * @param inputFile * XMI file containing the (Ecore) workload model which provides the * values for the Test Plan to be generated. * @param outputFile * name of the file where the Test Plan shall be stored in. * @param generatorPropertiesFile * properties file which provides the core settings for the Test Plan * Generator. * @param testPlanPropertiesFile * properties file which provides the default settings for the Test * Plans to be generated. * @param filterFlags * (optional) modification filters to be finally applied on the newly * generated Test Plan. * @param lineBreakType * OS-specific line-break type; this must be one of the * <code>LINEBREAK_TYPE</code> constants defined in class * {@link CSVHandler}. * * @return * the generated Test Plan, or <code>null</code> if any error occurs. * * @throws TransformationException * if any critical error in the transformation process occurs. */ private ListedHashTree generate ( final String inputFile, final String outputFile, final String outputPath, final int lineBreakType, final String testPlanPropertiesFile, final String generatorPropertiesFile, final String filterFlags) throws TransformationException { ListedHashTree testPlan = null; // to be returned; // TODO: collect these filters according to the command line flags; final AbstractFilter[] filters = new AbstractFilter[]{ // new ConstantWorkloadIntensityFilter(), /* this is just for testing, think times will be taken from the * workload model and managed by the Markov Controller; * new GaussianThinkTimeDistributionFilter( "Think Time", "", true, 300.0d, 100.0d), */ new HeaderDefaultsFilter() }; this.init( generatorPropertiesFile, testPlanPropertiesFile); if (this.isInitialized()) { final CSVHandler csvHandler = new CSVHandler(lineBreakType); // TODO: destination path must exist; create path, if necessary; // TODO: use output path also for test plan? final String behaviorModelsOutputPath = outputPath == null ? "./" : outputPath; // path "" denotes "/"; final AbstractTestPlanTransformer testPlanTransformer = new SimpleTestPlanTransformer( csvHandler, behaviorModelsOutputPath); try { testPlan = this.generate( inputFile, outputFile, testPlanTransformer, filters); } catch (final IOException ex) { final String message = String.format( TestPlanGenerator.ERROR_INPUT_FILE_COULD_NOT_BE_READ, inputFile, ex.getMessage()); this.logError(message); } } return testPlan; } /* ************************ static main content *********************** */ /** * Main method which parses the command line parameters and generates a * Test Plan afterwards. * * @param argv arguments vector. */ public static void main (final String[] argv) { try { System.out.println("****************************"); System.out.println("Start ApacheJMeter Testplan generation"); System.out.println("****************************"); // initialize arguments handler for requesting the command line // values afterwards via get() methods; might throw a // NullPointer-, IllegalArgument- or ParseException; CommandLineArgumentsHandler.init(argv); TestPlanGenerator.readArgumentsAndGenerate(); System.out.println("****************************"); System.out.println("END ApacheJMeter Testplan generation"); System.out.println("****************************"); } catch (final NullPointerException | IllegalArgumentException | ParseException | TransformationException ex) { System.err.println(ex.getMessage()); CommandLineArgumentsHandler.printUsage(); } } /** * Starts the generation process with the arguments which have been passed * to command line. * * @throws TransformationException * if any critical error in the transformation process occurs. */ private static void readArgumentsAndGenerate () throws TransformationException { final TestPlanGenerator testPlanGenerator = new TestPlanGenerator(); final String inputFile = CommandLineArgumentsHandler.getInputFile(); final String outputFile = CommandLineArgumentsHandler.getOutputFile(); final String outputPath = CommandLineArgumentsHandler.getPath(); final int lineBreakType = CommandLineArgumentsHandler.getLineBreakType(); final String testPlanPropertiesFile = CommandLineArgumentsHandler.getTestPlanPropertiesFile(); final String filters = CommandLineArgumentsHandler.getFilters(); final boolean runTest = CommandLineArgumentsHandler.getRunTest(); String generatorPropertiesFile = CommandLineArgumentsHandler.getGeneratorPropertiesFile(); if (generatorPropertiesFile == null) { generatorPropertiesFile = TestPlanGenerator.GENERATOR_DEFAULT_PROPERTIES; } // ignore returned Test Plan, since the output file will provide it // for being tested in the (possibly) following test run; testPlanGenerator.generate( inputFile, outputFile, outputPath, lineBreakType, testPlanPropertiesFile, generatorPropertiesFile, filters); if (runTest) { // TODO: libraries need to be added for running tests correctly; // otherwise the tests fail at runtime (e.g., class HC3CookieHandler // is declared to be still unknown); try { JMeterEngineGateway.getInstance().startJMeterEngine(outputFile); } catch (final Exception ex) { final String message = String.format( TestPlanGenerator.ERROR_TEST_PLAN_RUN_FAILED, outputFile, ex.getMessage()); System.err.println(message); ex.printStackTrace(); } } } }
3e04b9a2889348be5c2c65b35e427ce5229fac64
1,041
java
Java
server/sdp/src/main/java/cn/mysdp/biz/dto/request/SdpWorkspaceGetTableListRequest.java
BrookYuGit/sdp
d8307ef7a2310e89d9301f132396d4cb472aec7a
[ "MIT" ]
2
2021-11-07T11:57:05.000Z
2021-11-25T22:49:37.000Z
server/sdp/src/main/java/cn/mysdp/biz/dto/request/SdpWorkspaceGetTableListRequest.java
BrookYuGit/sdp
d8307ef7a2310e89d9301f132396d4cb472aec7a
[ "MIT" ]
null
null
null
server/sdp/src/main/java/cn/mysdp/biz/dto/request/SdpWorkspaceGetTableListRequest.java
BrookYuGit/sdp
d8307ef7a2310e89d9301f132396d4cb472aec7a
[ "MIT" ]
null
null
null
20.82
68
0.730067
1,984
package cn.mysdp.biz.dto.request; import com.alibaba.fastjson.annotation.JSONField; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.Map; import lombok.Getter; import lombok.Setter; /** * @ClassName: SdpWorkspaceGetTableListRequest * @Description: SQLRequest * @Author: SDP * @Date: 2021-10-30 * @Version: 1.0 * Table: sdp_workspace * Comment: * workspace */ @Getter @Setter public class SdpWorkspaceGetTableListRequest extends BaseRequest { private static final long serialVersionUID = 21474270763906109L; public SdpWorkspaceGetTableListRequest() { } @JsonProperty("workspace_name") @JSONField(name = "workspace_name") private String workspaceName; @JsonProperty("name") @JSONField(name = "name") private String name; @JsonProperty("id_list") @JSONField(name = "id_list") private List<Integer> idList; @Override public void checkRequest() throws Exception { } }
3e04ba155ded60992be160ebba0c4b239169af1c
1,248
java
Java
src/main/java/io/github/zomky/client/ClusterManagementClient.java
pmackowski/rsocket-playground
aef307a15e06fd6c0453abc056040306693a4e08
[ "Apache-2.0" ]
2
2019-09-30T13:37:57.000Z
2019-10-24T11:12:13.000Z
src/main/java/io/github/zomky/client/ClusterManagementClient.java
pmackowski/rsocket-playground
aef307a15e06fd6c0453abc056040306693a4e08
[ "Apache-2.0" ]
9
2019-08-26T08:18:54.000Z
2019-09-09T09:18:16.000Z
src/main/java/io/github/zomky/client/ClusterManagementClient.java
pmackowski/rsocket-raft
aef307a15e06fd6c0453abc056040306693a4e08
[ "Apache-2.0" ]
1
2021-11-09T10:38:52.000Z
2021-11-09T10:38:52.000Z
34.666667
96
0.735577
1,985
package io.github.zomky.client; import io.github.zomky.gossip.protobuf.InitJoinRequest; import io.github.zomky.gossip.protobuf.InitJoinResponse; import io.github.zomky.gossip.protobuf.InitLeaveRequest; import io.github.zomky.gossip.protobuf.InitLeaveResponse; import io.github.zomky.gossip.transport.GossipTcpTransport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; import java.net.InetAddress; public class ClusterManagementClient { private static final Logger LOGGER = LoggerFactory.getLogger(ClusterManagementClient.class); public Mono<InitJoinResponse> initJoin(Integer agentPort, InetAddress host, int port) { InitJoinRequest initJoinRequest = InitJoinRequest.newBuilder() .setRequesterPort(agentPort) .setHost(host.getHostAddress()) .setPort(port) .build(); return GossipTcpTransport.initJoin(initJoinRequest); } public Mono<InitLeaveResponse> initLeave(Integer agentPort) { InitLeaveRequest initLeaveRequest = InitLeaveRequest.newBuilder() .setRequesterPort(agentPort) .build(); return GossipTcpTransport.initLeave(initLeaveRequest); } }
3e04ba9c94315f8b1c66dd44b62250794951379f
4,158
java
Java
src/main/java/com/kivimango/sluggenerator/SlugGenerator.java
kivimango/slug-generator
2e568e15227c5c2fd7ef0cbec4ef3935ed8ff840
[ "MIT" ]
2
2017-07-08T22:01:44.000Z
2018-04-17T11:07:32.000Z
src/main/java/com/kivimango/sluggenerator/SlugGenerator.java
kivimango/slug-generator
2e568e15227c5c2fd7ef0cbec4ef3935ed8ff840
[ "MIT" ]
null
null
null
src/main/java/com/kivimango/sluggenerator/SlugGenerator.java
kivimango/slug-generator
2e568e15227c5c2fd7ef0cbec4ef3935ed8ff840
[ "MIT" ]
null
null
null
37.8
131
0.608706
1,986
package com.kivimango.sluggenerator; import java.util.Random; /** * _________.__ ________ __ * / _____/| | __ __ ____ / _____/ ____ ____ ________________ _/ |_ ___________ * \_____ \ | | | | \/ ___\/ \ ____/ __ \ / \_/ __ \_ __ \__ \\ __\/ _ \_ __ \ * / \| |_| | / /_/ > \_\ \ ___/| | \ ___/| | \// __ \| | ( <_> ) | \/ * /_______ /|____/____/\___ / \______ /\___ >___| /\___ >__| (____ /__| \____/|__| * \/ /_____/ \/ \/ \/ \/ \/ * * This class will generate a random, unique string from letters and numbers in 9gag-style which you can use for * identify a blog post, a video, an article etc. in an URL. * * Usage example : * Call the static method generate() of the class : * * <code>SlugGenerator.generate(SlugGenerator.Options.GENERATE_FROM_NUMBERS_AND_LETTERS, 23);</code> * * @author kivimango * @link https://github.com/kivimango/slug-generator/ * @version 1.1 */ public class SlugGenerator { /** * The generated slug will contain letters from the english alphabet only. */ public enum Options { GENERATE_ONLY_FROM_NUMBERS, GENERATE_ONLY_FROM_LETTERS, GENERATE_FROM_NUMBERS_AND_LETTERS } static final byte LENGTH_MIN_LIMIT = 3; static final byte LENGTH_MAX_LIMIT = 127; private static final char[] numbers = "0123456789".toCharArray(); private static final char[] letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); private static final char[] numbersAndLetters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); /** * Randomizing the slug based on the generation option and length. * The maximum length of the slug limited to 127 character, it should cover all the needs of the user/client * (if the passed length parameter is out of the limits, the class will silently cut the value to the limit). * * The GENERATE_FROM_NUMBERS_AND_LETTERS option does not guarantee that the result will contain both numbers AND letters. * * @param option The generation modifier flag.Possible values is GENERATE_ONLY_FROM_NUMBERS, * GENERATE_ONLY_FROM_LETTERS, and GENERATE_FROM_NUMBERS_AND_LETTERS. * The default is GENERATE_FROM_NUMBERS_AND_LETTERS. * @param length The final character length of the generated slug. * @return The generated slug based on the passed parameters. * @author kivimango * @since 1.0 */ public static String generate(Options option, int length) { length = checkAndSetLength(length); char[] slug; switch (option) { case GENERATE_ONLY_FROM_NUMBERS: slug = generateFromSource(numbers, length); break; case GENERATE_ONLY_FROM_LETTERS: slug = generateFromSource(letters, length); break; case GENERATE_FROM_NUMBERS_AND_LETTERS: slug = generateFromSource(numbersAndLetters, length); break; default: slug = generateFromSource(numbersAndLetters, length); break; } return String.valueOf(slug); } /** * Method to avoid code duplication. * The generation will happen here. * * @author kivimango * @since 1.0 */ private static char[] generateFromSource(char[] source, int length) { char[] result = new char[length]; Random randomizer = new Random(); for (byte i = 0; i < length; i++) { result[i] = source[randomizer.nextInt(source.length)]; } return result; } private static int checkAndSetLength(int lengthToCheck) { if (lengthToCheck < LENGTH_MIN_LIMIT) { lengthToCheck = LENGTH_MIN_LIMIT; } else if (lengthToCheck > LENGTH_MAX_LIMIT) { lengthToCheck = LENGTH_MAX_LIMIT; } return lengthToCheck; } }
3e04bbd634c5025921e06067ea7bb70123b1769c
2,303
java
Java
src/main/java/com/buuz135/industrial/jei/manual/ManualCategory.java
duely/Industrial-Foregoing
ff3afe62fcab65e4dcd8cca52ca31e6595a48cd8
[ "MIT" ]
null
null
null
src/main/java/com/buuz135/industrial/jei/manual/ManualCategory.java
duely/Industrial-Foregoing
ff3afe62fcab65e4dcd8cca52ca31e6595a48cd8
[ "MIT" ]
30
2021-02-22T07:07:59.000Z
2021-04-28T05:53:45.000Z
src/main/java/com/buuz135/industrial/jei/manual/ManualCategory.java
duely/Industrial-Foregoing
ff3afe62fcab65e4dcd8cca52ca31e6595a48cd8
[ "MIT" ]
null
null
null
35.430769
110
0.737733
1,987
/* * This file is part of Industrial Foregoing. * * Copyright 2019, Buuz135 * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.buuz135.industrial.jei.manual; import com.buuz135.industrial.utils.Reference; import mezz.jei.api.IGuiHelper; import mezz.jei.api.gui.IDrawable; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.IRecipeCategory; public class ManualCategory implements IRecipeCategory<ManualWrapper> { private final IDrawable drawable; public ManualCategory(IGuiHelper helper) { this.drawable = helper.createBlankDrawable(160, 125); } @Override public String getUid() { return "if_manual_category"; } @Override public String getTitle() { return "Industrial Foregoing's Manual"; } @Override public String getModName() { return Reference.MOD_ID; } @Override public IDrawable getBackground() { return drawable; } @Override public void setRecipe(IRecipeLayout recipeLayout, ManualWrapper recipeWrapper, IIngredients ingredients) { recipeLayout.getItemStacks().init(0, true, 70, 0); recipeLayout.getItemStacks().set(0, recipeWrapper.getEntry().getDisplay()); } }
3e04bcdb25ca646f623e3e9795a46a5520469024
1,995
java
Java
src/test/java/io/r2dbc/h2/codecs/UuidCodecTest.java
alexo134/r2dbc-h2
864fd3356a47f57aa0612a44f688282407d6b491
[ "Apache-2.0" ]
158
2018-09-29T21:13:31.000Z
2022-03-30T22:31:40.000Z
src/test/java/io/r2dbc/h2/codecs/UuidCodecTest.java
alexo134/r2dbc-h2
864fd3356a47f57aa0612a44f688282407d6b491
[ "Apache-2.0" ]
188
2018-10-02T18:47:46.000Z
2022-03-31T06:56:30.000Z
src/test/java/io/r2dbc/h2/codecs/UuidCodecTest.java
alexo134/r2dbc-h2
864fd3356a47f57aa0612a44f688282407d6b491
[ "Apache-2.0" ]
45
2018-11-12T06:49:59.000Z
2022-03-30T22:31:43.000Z
30.227273
93
0.696742
1,988
/* * Copyright 2018-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.r2dbc.h2.codecs; import org.h2.value.Value; import org.h2.value.ValueNull; import org.h2.value.ValueUuid; import org.junit.jupiter.api.Test; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; final class UuidCodecTest { private static final String SAMPLE_UUID = "79e9eb45-2835-49c8-ad3b-c951b591bc7f"; @Test void decode() { assertThat(new UuidCodec().decode(ValueUuid.get(SAMPLE_UUID), UUID.class)) .isEqualTo(UUID.fromString(SAMPLE_UUID)); } @Test void doCanDecode() { UuidCodec codec = new UuidCodec(); assertThat(codec.doCanDecode(Value.UUID)).isTrue(); assertThat(codec.doCanDecode(Value.UNKNOWN)).isFalse(); assertThat(codec.doCanDecode(Value.INT)).isFalse(); } @Test void doEncode() { assertThat(new UuidCodec().doEncode(UUID.fromString(SAMPLE_UUID))) .isEqualTo(ValueUuid.get(SAMPLE_UUID)); } @Test void doEncodeNoValue() { assertThatIllegalArgumentException().isThrownBy(() -> new UuidCodec().doEncode(null)) .withMessage("value must not be null"); } @Test void encodeNull() { assertThat(new UuidCodec().encodeNull()) .isEqualTo(ValueNull.INSTANCE); } }
3e04bd27ec57c1e75f8d17bcd2d6e1bae45d75a5
816
java
Java
app/src/androidTest/java/com/google/samples/apps/topeka/rule/AnimationAwareAwesome.java
ardock/android-topeka
ed23df1a48f6a9a903ef87dfe133706f92159186
[ "Apache-2.0" ]
1
2020-08-17T07:17:30.000Z
2020-08-17T07:17:30.000Z
app/src/androidTest/java/com/google/samples/apps/topeka/rule/AnimationAwareAwesome.java
ardock/android-topeka
ed23df1a48f6a9a903ef87dfe133706f92159186
[ "Apache-2.0" ]
1
2015-11-22T17:23:37.000Z
2016-08-17T13:33:06.000Z
app/src/androidTest/java/com/google/samples/apps/topeka/rule/AnimationAwareAwesome.java
ardock/android-topeka
ed23df1a48f6a9a903ef87dfe133706f92159186
[ "Apache-2.0" ]
2
2015-12-02T16:02:56.000Z
2020-01-09T18:27:42.000Z
32.64
99
0.745098
1,989
/* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.topeka.rule; /** * An interface for triple-A helper classes used to manage animation scales to avoid timing errors. */ public interface AnimationAwareAwesome { }
3e04be82aef00e23bcd9c21f9b2058221b7bbb8b
6,789
java
Java
src/jToolkit4FixedPipeline/image/texture/TextureUploader.java
Graveward/jToolkit
3a4c2009a70a25646b8c81d5975b1050e4525209
[ "MIT" ]
6
2018-09-12T08:07:01.000Z
2018-12-31T08:13:14.000Z
src/jToolkit4FixedPipeline/image/texture/TextureUploader.java
Graveward/jToolkit
3a4c2009a70a25646b8c81d5975b1050e4525209
[ "MIT" ]
null
null
null
src/jToolkit4FixedPipeline/image/texture/TextureUploader.java
Graveward/jToolkit
3a4c2009a70a25646b8c81d5975b1050e4525209
[ "MIT" ]
null
null
null
35.176166
83
0.644278
1,990
package jToolkit4FixedPipeline.image.texture; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import javax.imageio.ImageIO; import org.lwjgl.BufferUtils; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.util.glu.MipMap.gluBuild2DMipmaps; public class TextureUploader { private static final int BYTES_PER_PIXEL = 4;// 3 for RGB, 4 for RGBA public static int loadTexture(BufferedImage image) { int[] pixels = new int[image.getWidth() * image.getHeight()]; image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth()); ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * BYTES_PER_PIXEL); // 4 for RGBA, 3 for RGB for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { int pixel = pixels[y * image.getWidth() + x]; buffer.put((byte) ((pixel >> 16) & 0xFF)); // Red component buffer.put((byte) ((pixel >> 8) & 0xFF)); // Green component buffer.put((byte) (pixel & 0xFF)); // Blue component buffer.put((byte) ((pixel >> 24) & 0xFF)); // Alpha component. // Only for RGBA } } buffer.flip(); // FOR THE LOVE OF GOD DO NOT FORGET THIS // You now have a ByteBuffer filled with the color data of each pixel. // Now just create a texture ID and bind it. Then you can load it using // whatever OpenGL method you want, for example: int textureID = glGenTextures(); // Generate texture ID glBindTexture(GL_TEXTURE_2D, textureID); // Bind texture ID // Setup wrap mode glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Setup texture scaling filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Send texel data to OpenGL gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, image.getWidth(), image.getHeight(), GL_RGBA, GL_UNSIGNED_BYTE, buffer); glBindTexture(GL_TEXTURE_2D, 0); // Return the texture ID so we can bind it later again return textureID; } public static BufferedImage loadImage(String loc) { try { return ImageIO.read(new File(loc)); } catch (IOException e) { System.err.println("Failed to load Textures"); } return null; } public static int loadMipTexture(BufferedImage image) { int[] pixels = new int[image.getWidth() * image.getHeight()]; image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth()); ByteBuffer buffer2 = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * BYTES_PER_PIXEL); // 4 for RGBA, 3 for RGB for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { int pixel = pixels[y * image.getWidth() + x]; buffer2.put((byte) ((pixel >> 16) & 0xFF)); // Red component buffer2.put((byte) ((pixel >> 8) & 0xFF)); // Green component buffer2.put((byte) (pixel & 0xFF)); // Blue component buffer2.put((byte) ((pixel >> 24) & 0xFF)); // Alpha component. // Only for RGBA } } buffer2.flip(); // FOR THE LOVE OF GOD DO NOT FORGET THIS // You now have a ByteBuffer filled with the color data of each pixel. // Now just create a texture ID and bind it. Then you can load it using // whatever OpenGL method you want, for example: int textureID2 = glGenTextures(); // Generate texture ID glBindTexture(GL_TEXTURE_2D, textureID2); // Bind texture ID glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Setup texture scaling filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Setup wrap mode //glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); // Send texel data to OpenGL gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA8, image.getWidth(), image.getHeight(), GL_RGBA, GL_UNSIGNED_BYTE, buffer2); // Return the texture ID so we can bind it later again return textureID2; } public static int loadLightTexture(BufferedImage image2) { for(int i=0; i<image2.getWidth(); i++){ for(int j=0; j<image2.getHeight(); j++){ int color = image2.getRGB(i,j); int alpha = (color >> 24) & 255; int red = (color >> 16) & 255; int green = (color >> 8) & 255; int blue = (color) & 255; final int lum = (int)(0.2126 * red + 0.7152 * green + 0.0722 * blue); alpha = (alpha << 24); red = (lum << 16); green = (lum << 8); blue = lum; color = alpha + red + green + blue; image2.setRGB(i,j,color); } } BufferedImage image = image2; int[] pixels = new int[image.getWidth() * image.getHeight()]; image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth()); ByteBuffer buffer2 = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * BYTES_PER_PIXEL); // 4 for RGBA, 3 for RGB for (int y = 0; y < image.getHeight(); y++) { for (int x = 0; x < image.getWidth(); x++) { int pixel = pixels[y * image.getWidth() + x]; buffer2.put((byte) ((pixel >> 16) & 0xFF)); // Red component buffer2.put((byte) ((pixel >> 8) & 0xFF)); // Green component buffer2.put((byte) (pixel & 0xFF)); // Blue component buffer2.put((byte) ((pixel >> 24) & 0xFF)); // Alpha component. // Only for RGBA } } buffer2.flip(); // FOR THE LOVE OF GOD DO NOT FORGET THIS // You now have a ByteBuffer filled with the color data of each pixel. // Now just create a texture ID and bind it. Then you can load it using // whatever OpenGL method you want, for example: int textureID2 = glGenTextures(); // Generate texture ID glBindTexture(GL_TEXTURE_2D, textureID2); // Bind texture ID // Setup texture scaling filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Setup wrap mode //glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); // Send texel data to OpenGL gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, image.getWidth(), image.getHeight(), GL_RGBA, GL_UNSIGNED_BYTE, buffer2); // Return the texture ID so we can bind it later again return textureID2; } }
3e04bea32329567e0a27dd567594dd75b75a0495
3,674
java
Java
src/main/java/io/bootique/tools/release/service/preferences/credential/PreferenceCredentialFactory.java
OlegKhodokevich/release
27740614093297450405e64b1a88bc4a7adf6c20
[ "Apache-2.0" ]
1
2021-05-22T14:06:44.000Z
2021-05-22T14:06:44.000Z
src/main/java/io/bootique/tools/release/service/preferences/credential/PreferenceCredentialFactory.java
OlegKhodokevich/release
27740614093297450405e64b1a88bc4a7adf6c20
[ "Apache-2.0" ]
6
2021-04-30T08:33:23.000Z
2022-01-21T09:52:00.000Z
src/main/java/io/bootique/tools/release/service/preferences/credential/PreferenceCredentialFactory.java
OlegKhodokevich/release
27740614093297450405e64b1a88bc4a7adf6c20
[ "Apache-2.0" ]
5
2020-04-07T11:59:30.000Z
2022-01-26T09:08:56.000Z
34.990476
141
0.72074
1,991
package io.bootique.tools.release.service.preferences.credential; import io.bootique.annotation.BQConfig; import io.bootique.annotation.BQConfigProperty; import io.bootique.tools.release.service.desktop.DesktopException; import io.bootique.tools.release.service.git.GitService; import io.bootique.tools.release.service.github.GitHubApiImport; import io.bootique.tools.release.service.logger.LoggerService; import io.bootique.tools.release.service.maven.MavenService; import io.bootique.tools.release.service.preferences.DefaultPreferenceService; import io.bootique.tools.release.service.preferences.PreferenceService; import io.bootique.tools.release.service.release.persistent.ReleasePersistentService; import java.io.File; import java.nio.file.Paths; @BQConfig public class PreferenceCredentialFactory { private String organizationName; private String organizationGroupId; private String gitHubToken; private String basePath; private String groupIdPattern; private String logsPath; private String savePath; @BQConfigProperty("Organization name") public void setOrganizationName(String organizationName) { this.organizationName = organizationName; } @BQConfigProperty("Organization group id") public void setOrganizationGroupId(String organizationGroupId) { this.organizationGroupId = organizationGroupId; } @BQConfigProperty("Github token") public void setGitHubToken(String gitHubToken) { this.gitHubToken = gitHubToken; } @BQConfigProperty("Pattern group id") public void setGroupIdPattern(String groupIdPattern) { this.groupIdPattern = groupIdPattern; } @BQConfigProperty public void setBasePath(String basePath) { this.basePath = basePath; } @BQConfigProperty public void setLogsPath(String logsPath) { this.logsPath = logsPath; } @BQConfigProperty public void setSavePath(String savePath) { this.savePath = savePath; } public PreferenceService createPreferenceService(){ if(gitHubToken == null) { throw new DesktopException("Can't find gitHub token."); } if(basePath == null) { throw new DesktopException("Can't find base path."); } PreferenceService preferences = new DefaultPreferenceService(); if(!preferences.have(GitHubApiImport.ORGANIZATION_PREFERENCE)) { preferences.set(GitHubApiImport.ORGANIZATION_PREFERENCE, organizationName); // bootique } if(!preferences.have(MavenService.ORGANIZATION_GROUP_ID)) { preferences.set(MavenService.ORGANIZATION_GROUP_ID, organizationGroupId); // io.bootique } if(!preferences.have(MavenService.GROUP_ID_PATTERN)) { preferences.set(MavenService.GROUP_ID_PATTERN, groupIdPattern); // io.bootique } if(!preferences.have(GitHubApiImport.AUTH_TOKEN_PREFERENCE)) { preferences.set(GitHubApiImport.AUTH_TOKEN_PREFERENCE, gitHubToken); } if(!preferences.have(GitService.BASE_PATH_PREFERENCE)) { preferences.set(GitService.BASE_PATH_PREFERENCE, Paths.get(basePath)); } if (!preferences.have(ReleasePersistentService.SAVE_PATH)) { preferences.set(ReleasePersistentService.SAVE_PATH, savePath == null ? "release-status" + File.separator + "persist" : savePath); } if(!preferences.have(LoggerService.LOGGER_BASE_PATH)) { preferences.set(LoggerService.LOGGER_BASE_PATH, logsPath == null ? "release-status" + File.separator + "logs" : logsPath); } return preferences; } }
3e04c0b2628486c1772f7895c82d48aa375a166f
579
java
Java
cosmetic-core/src/main/java/com/cyberlink/core/dao/hibernate/AbstractDaoCosmetic.java
datree-demo/bcserver_demo
852a8d4780d3724236e1d5069cccf2dbe7a4dce9
[ "Apache-2.0" ]
1
2019-01-08T15:53:01.000Z
2019-01-08T15:53:01.000Z
cosmetic-core/src/main/java/com/cyberlink/core/dao/hibernate/AbstractDaoCosmetic.java
datree-demo/bcserver_demo
852a8d4780d3724236e1d5069cccf2dbe7a4dce9
[ "Apache-2.0" ]
null
null
null
cosmetic-core/src/main/java/com/cyberlink/core/dao/hibernate/AbstractDaoCosmetic.java
datree-demo/bcserver_demo
852a8d4780d3724236e1d5069cccf2dbe7a4dce9
[ "Apache-2.0" ]
null
null
null
30.473684
90
0.747841
1,992
package com.cyberlink.core.dao.hibernate; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import com.cyberlink.core.dao.GenericDao; import com.cyberlink.core.model.IdEntity; @SuppressWarnings("unchecked") public abstract class AbstractDaoCosmetic<T extends IdEntity<PK>, PK extends Serializable> extends CosmeticSupportDao<T, PK> implements GenericDao<T, PK> { public AbstractDaoCosmetic() { setEntityClass((Class<T>) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]); } }
3e04c1181fd904fd49482684b9f6f2724019e748
1,687
java
Java
servicekeeper-core/src/main/java/io/esastack/servicekeeper/core/executionchain/SyncExecutionChain.java
Mkabaka/esa-servicekeeper
a8f064d7470cf02d559334c87176b95088729254
[ "Apache-2.0" ]
15
2021-05-08T08:55:52.000Z
2022-02-18T08:02:37.000Z
servicekeeper-core/src/main/java/io/esastack/servicekeeper/core/executionchain/SyncExecutionChain.java
Mkabaka/esa-servicekeeper
a8f064d7470cf02d559334c87176b95088729254
[ "Apache-2.0" ]
10
2021-07-28T02:06:55.000Z
2022-03-07T16:04:33.000Z
servicekeeper-core/src/main/java/io/esastack/servicekeeper/core/executionchain/SyncExecutionChain.java
Mkabaka/esa-servicekeeper
a8f064d7470cf02d559334c87176b95088729254
[ "Apache-2.0" ]
7
2021-05-08T10:05:15.000Z
2022-02-22T12:16:59.000Z
34.428571
97
0.701838
1,993
/* * Copyright 2021 OPPO ESA Stack Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.esastack.servicekeeper.core.executionchain; import io.esastack.servicekeeper.core.common.OriginalInvocation; import java.util.function.Supplier; public interface SyncExecutionChain extends ExecutionChain { /** * Just execute the executable when the {@link #tryToExecute(Context)} return true. * * @param ctx Context * @param invocation the supplier to get original invocation * @param executable executable * @param <R> R * @return R * @throws Throwable any throwable */ <R> R execute(Context ctx, Supplier<OriginalInvocation> invocation, Executable<R> executable) throws Throwable; /** * Just execute the runnable when the {@link #tryToExecute(Context)} return true. * * @param ctx Context * @param invocation the supplier to get original invocation * @param runnable runnable * @throws Throwable any throwable */ void execute(Context ctx, Supplier<OriginalInvocation> invocation, Runnable runnable) throws Throwable; }
3e04c141b0fcb90a8f7bfef02317386ab7e1636e
116
java
Java
app/src/main/java/com/shaoyue/weizhegou/interfac/CommCallBack.java
coypanglei/nanjinJianduo
b6ca49d6fa1182bbf61214338ab08aba63786e4a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/shaoyue/weizhegou/interfac/CommCallBack.java
coypanglei/nanjinJianduo
b6ca49d6fa1182bbf61214338ab08aba63786e4a
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/shaoyue/weizhegou/interfac/CommCallBack.java
coypanglei/nanjinJianduo
b6ca49d6fa1182bbf61214338ab08aba63786e4a
[ "Apache-2.0" ]
null
null
null
19.333333
40
0.767241
1,994
package com.shaoyue.weizhegou.interfac; public interface CommCallBack { void complete(int code, String msg); }
3e04c1543117b8f0c2d9b8a57df47d5790038a27
1,439
java
Java
core/java/android/security/keymaster/KeymasterDateArgument.java
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
164
2015-01-05T16:49:11.000Z
2022-03-29T20:40:27.000Z
core/java/android/security/keymaster/KeymasterDateArgument.java
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
127
2015-01-12T12:02:32.000Z
2021-11-28T08:46:25.000Z
core/java/android/security/keymaster/KeymasterDateArgument.java
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
1,141
2015-01-01T22:54:40.000Z
2022-02-09T22:08:26.000Z
28.215686
75
0.671994
1,995
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.security.keymaster; import android.annotation.UnsupportedAppUsage; import android.os.Parcel; import java.util.Date; /** * @hide */ class KeymasterDateArgument extends KeymasterArgument { public final Date date; public KeymasterDateArgument(int tag, Date date) { super(tag); switch (KeymasterDefs.getTagType(tag)) { case KeymasterDefs.KM_DATE: break; // OK. default: throw new IllegalArgumentException("Bad date tag " + tag); } this.date = date; } @UnsupportedAppUsage public KeymasterDateArgument(int tag, Parcel in) { super(tag); date = new Date(in.readLong()); } @Override public void writeValue(Parcel out) { out.writeLong(date.getTime()); } }
3e04c38ad7f4a0a5fcc89f83777fc990210a62bd
8,919
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/skystone/teleop/MeccanumDriveV2.java
Rumblebots/UltimateGoal
2e3c424e0a86d3ced996bfc937a6cc92a6813714
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/skystone/teleop/MeccanumDriveV2.java
Rumblebots/UltimateGoal
2e3c424e0a86d3ced996bfc937a6cc92a6813714
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/skystone/teleop/MeccanumDriveV2.java
Rumblebots/UltimateGoal
2e3c424e0a86d3ced996bfc937a6cc92a6813714
[ "MIT" ]
null
null
null
43.296117
125
0.639309
1,996
package org.firstinspires.ftc.teamcode.skystone.teleop; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.Gamepad; import com.qualcomm.robotcore.hardware.TouchSensor; import com.qualcomm.robotcore.util.Range; import org.firstinspires.ftc.teamcode.skystone.RobotCore.Utils; import org.firstinspires.ftc.teamcode.skystone.hardware.v2.Motors_Aux; import org.firstinspires.ftc.teamcode.skystone.hardware.v2.Motors_Drive; import org.firstinspires.ftc.teamcode.skystone.hardware.v2.Motors_Drive.motorPowerObject; import org.firstinspires.ftc.teamcode.skystone.hardware.v2.Sensors.Sensors; import org.firstinspires.ftc.teamcode.skystone.hardware.v2.Servos; @Disabled @Deprecated public class MeccanumDriveV2 extends LinearOpMode { private Motors_Drive motorsDrive = new Motors_Drive(); private Motors_Aux motorsAux = new Motors_Aux(); private Servos servos = new Servos(); private Sensors sensors = new Sensors(); private Motors_Aux.TeleOp motorsAuxTeleOp = motorsAux.new TeleOp(); private Motors_Aux.TeleOpEncoders motorsAuxTeleOpEncoders = motorsAux.new TeleOpEncoders(); private TouchSensor lifterTouch; private TouchSensor extenderTouch; private Utils utils = new Utils(); private Utils.Toggle gripperToggle = utils.new Toggle(false); private Utils.Toggle foundationToggle = utils.new Toggle(false); private Utils.Toggle capstoneToggle = utils.new Toggle(false); private Utils.Shifter lifterShifter = utils.new Shifter(1, 6); private Modes extenderMode; private Modes lifterMode; private int encoderAdjustment; private int adjustedEncoderPosition; private motorPowerObject yalign(double right, double left) { motorPowerObject motorPowerObject = motorsDrive.new motorPowerObject(); if (right >= 10 && left >= 10) { motorPowerObject.frontRight = 0.4; motorPowerObject.backRight = 0.4; motorPowerObject.frontLeft = 0.4; motorPowerObject.backLeft = 0.4; } else if (right - 1 < left && left < right + 1) { motorPowerObject.frontRight = 0; motorPowerObject.backRight = 0; motorPowerObject.frontLeft = 0; motorPowerObject.backLeft = 0; } else if (right > left) { motorPowerObject.frontRight = 0; motorPowerObject.backRight = 0; motorPowerObject.frontLeft = 0.4; motorPowerObject.backLeft = 0.4; } else if (left > right) { motorPowerObject.frontRight = 0.4; motorPowerObject.backRight = 0.4; motorPowerObject.frontLeft = 0; motorPowerObject.backLeft = 0; } return motorPowerObject; } private motorPowerObject xalign(double distance) { motorPowerObject motorPowerObject = motorsDrive.new motorPowerObject(); if (8 - 0.5 <= distance && distance <= 8 + 0.5) { motorPowerObject.frontRight = 0; motorPowerObject.backRight = 0; motorPowerObject.frontLeft = 0; motorPowerObject.backLeft = 0; } else if (distance < 8 - 2) { // Strafe right motorPowerObject.frontLeft = 0.45; motorPowerObject.backRight = 0.45; motorPowerObject.frontRight = -0.45; motorPowerObject.backLeft = -0.45; } else if (distance > 8 + 2) { // Strafe left motorPowerObject.frontLeft = -0.45; motorPowerObject.backRight = -0.45; motorPowerObject.frontRight = 0.45; motorPowerObject.backLeft = 0.45; } else if (distance < 8 - 1) { // Strafe right motorPowerObject.frontLeft = 0.4; motorPowerObject.backRight = 0.4; motorPowerObject.frontRight = -0.4; motorPowerObject.backLeft = -0.4; } else if (distance > 8 + 1) { // Strafe left motorPowerObject.frontLeft = -0.4; motorPowerObject.backRight = -0.4; motorPowerObject.frontRight = 0.4; motorPowerObject.backLeft = 0.4; } else if (distance < 8 - 0.5) { // Strafe right motorPowerObject.frontLeft = 0.35; motorPowerObject.backRight = 0.35; motorPowerObject.frontRight = -0.35; motorPowerObject.backLeft = -0.35; } else if (distance > 8 + 0.5) { // Strafe left motorPowerObject.frontLeft = -0.35; motorPowerObject.backRight = -0.35; motorPowerObject.frontRight = 0.35; motorPowerObject.backLeft = 0.35; } return motorPowerObject; } private motorPowerObject meccanum(Gamepad gamepad) { motorPowerObject motorPowerObject = motorsDrive.new motorPowerObject(); double motorSpeedDiv = 2; if (gamepad.right_trigger > 0) motorSpeedDiv = (1.01 - gamepad.right_trigger) * 2; motorPowerObject.frontRight = -gamepad.left_stick_y + gamepad.left_stick_x + gamepad.right_stick_x; motorPowerObject.frontLeft = gamepad.left_stick_y + gamepad.left_stick_x + gamepad.right_stick_x; motorPowerObject.backRight = -gamepad.left_stick_y - gamepad.left_stick_x + gamepad.right_stick_x; motorPowerObject.backLeft = gamepad.left_stick_y - gamepad.left_stick_x + gamepad.right_stick_x; motorPowerObject.frontRight /= motorSpeedDiv; motorPowerObject.frontLeft /= motorSpeedDiv; motorPowerObject.backRight /= motorSpeedDiv; motorPowerObject.backLeft /= motorSpeedDiv; return motorPowerObject; } private void writeMotorValues(motorPowerObject motor) { Motors_Drive.FrontRight.setPower(motor.frontRight); Motors_Drive.FrontLeft.setPower(motor.frontLeft); Motors_Drive.BackRight.setPower(motor.backRight); Motors_Drive.BackLeft.setPower(motor.backLeft); } private void setLifterPower(double power) { motorsAuxTeleOp.SetStackerDirection(power); } private boolean setLifterPowerBasedOnEncoders(double current) { double target = /* noelia is cool */ motorsAuxTeleOpEncoders.GetTargetPos(); double distanceFromTarget = target - current; if (Math.abs(distanceFromTarget) < 50) { setLifterPower(0); return true; } else { setLifterPower(Range.clip(distanceFromTarget * 0.001, -1, 1)); return false; } } public void runOpMode() { motorsDrive.init(hardwareMap); motorsAux.init(hardwareMap); servos.init(hardwareMap); sensors.init(hardwareMap); lifterTouch = hardwareMap.touchSensor.get("liftertouch"); extenderTouch = hardwareMap.touchSensor.get("extenderlimit"); waitForStart(); while (opModeIsActive()) { motorPowerObject motorPower; // vv yalign vv if (gamepad1.a) motorPower = yalign(sensors.distanceSensorRight.getDistanceCm(), sensors.distanceSensorLeft.getDistanceCm()); // vv xalign vv else if (gamepad1.b) motorPower = xalign(sensors.alignDistance.getDistanceCm()); // vv meccanum vv else motorPower = meccanum(gamepad1); writeMotorValues(motorPower); if (lifterTouch.isPressed()) encoderAdjustment = 0 - motorsAuxTeleOpEncoders.GetCurrentPos(); adjustedEncoderPosition = motorsAuxTeleOpEncoders.GetCurrentPos() - encoderAdjustment; double lifterPower = Math.abs(gamepad2.right_trigger) - Math.abs(gamepad2.left_trigger); if (gamepad2.right_trigger > 0) lifterMode = Modes.Manual; else if (gamepad2.left_trigger > 0) lifterMode = Modes.Manual; else if (gamepad2.y) lifterMode = Modes.Automatic; else lifterMode = Modes.Inactive; switch (lifterMode) { case Manual: setLifterPower(Range.clip(lifterPower, -1, 1)); break; case Automatic: if (setLifterPowerBasedOnEncoders(motorsAux.stackerVertical1.getCurrentPosition())) { lifterMode = Modes.Manual; } break; case Inactive: setLifterPower(0); break; default: throw new IllegalStateException("Unexpected value: " + lifterMode); } } } private enum Modes { Automatic, Inactive, Manual, } /* * TODO * i cant think straight enough to work on this rn * but when i get home i'm gonna fix all this * i still gotta add most of gamepad 2 controls before itll be 100%0%00% okay */ }
3e04c47ac6e8cacb2278546039900c531fe184b0
5,689
java
Java
2017/9th/app/src/main/java/com/fbla/dulaney/fblayardsale/CommentsAdapter.java
fbla-competitive-events/mobile-application-development
eff4f150498a1650091fb9a3cefd13e2e1a303e1
[ "MIT" ]
null
null
null
2017/9th/app/src/main/java/com/fbla/dulaney/fblayardsale/CommentsAdapter.java
fbla-competitive-events/mobile-application-development
eff4f150498a1650091fb9a3cefd13e2e1a303e1
[ "MIT" ]
null
null
null
2017/9th/app/src/main/java/com/fbla/dulaney/fblayardsale/CommentsAdapter.java
fbla-competitive-events/mobile-application-development
eff4f150498a1650091fb9a3cefd13e2e1a303e1
[ "MIT" ]
null
null
null
38.70068
119
0.595711
1,997
/* CommentsAdapter.java ============================================================================= Josh Talley and Daniel O'Donnell Dulaney High School Mobile Application Development 2016-17 ============================================================================= Purpose: This adapter is used by the Comments activity to manage the list of comments. It makes use of the CommentListController. When you delete a comment, it uses a popup window to ask if you are sure. */ package com.fbla.dulaney.fblayardsale; import android.content.DialogInterface; import android.databinding.DataBindingUtil; import android.os.AsyncTask; import android.support.v7.app.AlertDialog; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.fbla.dulaney.fblayardsale.controller.CommentListController; import com.fbla.dulaney.fblayardsale.databinding.ListCommentsBinding; import com.fbla.dulaney.fblayardsale.model.ItemComment; import com.microsoft.windowsazure.mobileservices.table.MobileServiceTable; public class CommentsAdapter extends RecyclerView.Adapter<CommentsAdapter.ViewHolder> implements View.OnClickListener { private View.OnClickListener mParentListener; private ListCommentsBinding mBinding; private Comments mContext; private FblaAzure mAzure; public CommentsAdapter (Comments context, View.OnClickListener onClickListener, FblaAzure azure) { mContext = context; mParentListener = onClickListener; mAzure = azure; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ListCommentsBinding mBinding = DataBindingUtil.inflate( LayoutInflater.from(parent.getContext()), R.layout.list_comments, parent, false); View view = mBinding.getRoot(); mBinding.delete.setOnClickListener(this); Log.d("CommentsAdapter", "onCreateViewHolder"); return new ViewHolder(view, mBinding); } @Override public void onBindViewHolder(ViewHolder holder, int position) { if (!mAzure.getLoggedOn()) return; ItemComment comment = CommentListController.getComment(position); if (comment != null) { mBinding = holder.getBinding(); Log.d("CommentsAdapter", "onBindViewHolder"); mBinding.comments.setText(comment.getComment()); if (comment.getAccount() == null) mBinding.username.setText("{Unknown}"); else mBinding.username.setText(comment.getAccount().getName()); mBinding.delete.setTag(position); } } @Override public int getItemCount() { return CommentListController.getCommentCount(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.delete: final int position = (int)v.getTag(); AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle("Are You Sure?"); final TextView info = new TextView(mContext); info.setText("By Pressing Confirm, The Comment Will Be Deleted."); info.setPadding(30, 0, 0, 0); builder.setView(info); builder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteComment(position); dialog.dismiss(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); break; default: break; } } private void deleteComment(int position) { if (!mAzure.getLoggedOn()) return; final int pos = position; final ItemComment comment = CommentListController.getComment(position); final MobileServiceTable<ItemComment> mCommentTable = mAzure.getClient().getTable(ItemComment.class); // Delete the comment from the database. AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { mCommentTable.delete(comment); Log.d("Comments:delete", "Deleted comment " + comment.getComment()); mContext.runOnUiThread(new Runnable() { @Override public void run() { CommentListController.removeComment(pos); } }); } catch (Exception e) { Log.d("Comments:delete", e.toString()); } return null; } }; task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR); } public class ViewHolder extends RecyclerView.ViewHolder { private ListCommentsBinding mBinding; public ViewHolder(View itemView, ListCommentsBinding binding) { super(itemView); mBinding = binding; } public ListCommentsBinding getBinding() { return mBinding; } } }
3e04c47f0a51ede53bce9746541a4ac735e79725
695
java
Java
src/main/java/com/omertron/imdbapi/wrapper/WrapperActorData.java
jr2730/SixDegrees
eabcb366740a61bc297dfd1b7c31907abf96de18
[ "Apache-2.0" ]
null
null
null
src/main/java/com/omertron/imdbapi/wrapper/WrapperActorData.java
jr2730/SixDegrees
eabcb366740a61bc297dfd1b7c31907abf96de18
[ "Apache-2.0" ]
null
null
null
src/main/java/com/omertron/imdbapi/wrapper/WrapperActorData.java
jr2730/SixDegrees
eabcb366740a61bc297dfd1b7c31907abf96de18
[ "Apache-2.0" ]
null
null
null
24.821429
67
0.716547
1,998
package com.omertron.imdbapi.wrapper; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonSetter; import com.omertron.imdbapi.model.ImdbPerson; /** * JSON Wrapper class for the response from the API * * Not intended for use outside of the API * * @author stuart.boston */ @JsonIgnoreProperties({"@meta", "exp", "copyright", "@type", "db"}) public class WrapperActorData extends AbstractWrapper<ImdbPerson> { @JsonSetter("data") @Override public void setResult(ImdbPerson result) { this.result = result; } @Override public ImdbPerson getResult() { return getResult(ImdbPerson.class); } }
3e04c4a52fbf4927968e78375ec9456a1fe68617
1,501
java
Java
mod-data-import-converter-storage-server/src/main/java/org/folio/services/forms/configs/FormConfigServiceImpl.java
julianladisch/mod-data-import-converter-storage
d5583f99fdd7f4dac743c2ec900821f7b509be23
[ "Apache-2.0" ]
1
2019-01-31T12:03:46.000Z
2019-01-31T12:03:46.000Z
mod-data-import-converter-storage-server/src/main/java/org/folio/services/forms/configs/FormConfigServiceImpl.java
julianladisch/mod-data-import-converter-storage
d5583f99fdd7f4dac743c2ec900821f7b509be23
[ "Apache-2.0" ]
131
2019-02-04T08:51:31.000Z
2022-03-28T16:36:17.000Z
mod-data-import-converter-storage-server/src/main/java/org/folio/services/forms/configs/FormConfigServiceImpl.java
julianladisch/mod-data-import-converter-storage
d5583f99fdd7f4dac743c2ec900821f7b509be23
[ "Apache-2.0" ]
1
2020-04-20T10:48:08.000Z
2020-04-20T10:48:08.000Z
31.270833
126
0.782811
1,999
package org.folio.services.forms.configs; import io.vertx.core.Future; import org.folio.dao.forms.configs.FormConfigDao; import org.folio.rest.jaxrs.model.FormConfig; import org.folio.rest.jaxrs.model.FormConfigCollection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.ws.rs.NotFoundException; import static java.lang.String.format; @Component public class FormConfigServiceImpl implements FormConfigService { @Autowired private FormConfigDao formConfigDao; @Override public Future<FormConfig> save(FormConfig formConfig, String tenantId) { return formConfigDao.save(formConfig, tenantId); } @Override public Future<FormConfig> getByFormName(String formName, String tenantId) { return formConfigDao.getByFormName(formName, tenantId) .compose(configOptional -> configOptional .map(Future::succeededFuture) .orElse(Future.failedFuture(new NotFoundException(format("FormConfig with formName '%s' was not found", formName))))); } @Override public Future<FormConfigCollection> getAll(String tenantId) { return formConfigDao.getAll(tenantId); } @Override public Future<FormConfig> update(FormConfig formConfig, String tenantId) { return formConfigDao.updateByFormName(formConfig, tenantId); } @Override public Future<Boolean> deleteByFormName(String formName, String tenantId) { return formConfigDao.deleteByFormName(formName, tenantId); } }
3e04c55c76f536e6a80c57f00fe4fc0f54a1d4fe
889
java
Java
formatters/formatter-api/src/com/marvinformatics/formatter/Formatter.java
velo/maven-java-formatter-plugin
88fffd318eef03d96e99211e78eeed4d8d31913e
[ "Apache-2.0" ]
17
2015-01-23T02:32:53.000Z
2017-09-22T21:21:41.000Z
formatters/formatter-api/src/com/marvinformatics/formatter/Formatter.java
velo/maven-java-formatter-plugin
88fffd318eef03d96e99211e78eeed4d8d31913e
[ "Apache-2.0" ]
37
2015-03-23T02:14:38.000Z
2018-09-17T20:38:46.000Z
formatters/formatter-api/src/com/marvinformatics/formatter/Formatter.java
velo/maven-java-formatter-plugin
88fffd318eef03d96e99211e78eeed4d8d31913e
[ "Apache-2.0" ]
15
2015-02-26T14:01:50.000Z
2020-02-06T13:13:59.000Z
28.0625
75
0.727171
2,000
/** * Copyright (C) 2010 Marvin Herman Froeder ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.marvinformatics.formatter; /** * @author marvin.froeder */ public interface Formatter { /** * Format individual file. * * @param originalCode code to be formatted * @return formatted code */ String format(String originalCode); }
3e04c64d800f5328ce48bbc1510a6273e45477de
16,096
java
Java
model-pain-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/CreditTransferTransactionInformation14.java
luongnvUIT/prowide-iso20022
59210a4b67cd38759df2d0dd82ad19acf93ffe75
[ "Apache-2.0" ]
40
2020-10-13T13:44:59.000Z
2022-03-30T13:58:32.000Z
model-pain-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/CreditTransferTransactionInformation14.java
luongnvUIT/prowide-iso20022
59210a4b67cd38759df2d0dd82ad19acf93ffe75
[ "Apache-2.0" ]
25
2020-10-04T23:46:22.000Z
2022-03-30T12:31:03.000Z
model-pain-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/CreditTransferTransactionInformation14.java
luongnvUIT/prowide-iso20022
59210a4b67cd38759df2d0dd82ad19acf93ffe75
[ "Apache-2.0" ]
22
2020-12-22T14:50:22.000Z
2022-03-30T13:19:10.000Z
25.96129
117
0.605741
2,001
package com.prowidesoftware.swift.model.mx.dic; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * Set of elements used to provide information specific to the individual transaction(s) included in the message. * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CreditTransferTransactionInformation14", propOrder = { "pmtId", "pmtTpInf", "amt", "chrgBr", "chqInstr", "ultmtDbtr", "intrmyAgt1", "intrmyAgt2", "intrmyAgt3", "cdtrAgt", "cdtr", "cdtrAcct", "ultmtCdtr", "instrForCdtrAgt", "purp", "rgltryRptg", "tax", "rltdRmtInf", "rmtInf" }) public class CreditTransferTransactionInformation14 { @XmlElement(name = "PmtId", required = true) protected PaymentIdentification1 pmtId; @XmlElement(name = "PmtTpInf") protected PaymentTypeInformation19 pmtTpInf; @XmlElement(name = "Amt", required = true) protected AmountType3Choice amt; @XmlElement(name = "ChrgBr", required = true) @XmlSchemaType(name = "string") protected ChargeBearerType1Code chrgBr; @XmlElement(name = "ChqInstr") protected Cheque6 chqInstr; @XmlElement(name = "UltmtDbtr") protected PartyIdentification43 ultmtDbtr; @XmlElement(name = "IntrmyAgt1") protected BranchAndFinancialInstitutionIdentification5 intrmyAgt1; @XmlElement(name = "IntrmyAgt2") protected BranchAndFinancialInstitutionIdentification5 intrmyAgt2; @XmlElement(name = "IntrmyAgt3") protected BranchAndFinancialInstitutionIdentification5 intrmyAgt3; @XmlElement(name = "CdtrAgt", required = true) protected BranchAndFinancialInstitutionIdentification5 cdtrAgt; @XmlElement(name = "Cdtr", required = true) protected PartyIdentification43 cdtr; @XmlElement(name = "CdtrAcct") protected CashAccount16 cdtrAcct; @XmlElement(name = "UltmtCdtr") protected PartyIdentification43 ultmtCdtr; @XmlElement(name = "InstrForCdtrAgt") protected List<InstructionForCreditorAgent1> instrForCdtrAgt; @XmlElement(name = "Purp") protected Purpose2Choice purp; @XmlElement(name = "RgltryRptg") protected List<RegulatoryReporting3> rgltryRptg; @XmlElement(name = "Tax") protected TaxInformation3 tax; @XmlElement(name = "RltdRmtInf") protected List<RemittanceLocation2> rltdRmtInf; @XmlElement(name = "RmtInf") protected RemittanceInformation6 rmtInf; /** * Gets the value of the pmtId property. * * @return * possible object is * {@link PaymentIdentification1 } * */ public PaymentIdentification1 getPmtId() { return pmtId; } /** * Sets the value of the pmtId property. * * @param value * allowed object is * {@link PaymentIdentification1 } * */ public CreditTransferTransactionInformation14 setPmtId(PaymentIdentification1 value) { this.pmtId = value; return this; } /** * Gets the value of the pmtTpInf property. * * @return * possible object is * {@link PaymentTypeInformation19 } * */ public PaymentTypeInformation19 getPmtTpInf() { return pmtTpInf; } /** * Sets the value of the pmtTpInf property. * * @param value * allowed object is * {@link PaymentTypeInformation19 } * */ public CreditTransferTransactionInformation14 setPmtTpInf(PaymentTypeInformation19 value) { this.pmtTpInf = value; return this; } /** * Gets the value of the amt property. * * @return * possible object is * {@link AmountType3Choice } * */ public AmountType3Choice getAmt() { return amt; } /** * Sets the value of the amt property. * * @param value * allowed object is * {@link AmountType3Choice } * */ public CreditTransferTransactionInformation14 setAmt(AmountType3Choice value) { this.amt = value; return this; } /** * Gets the value of the chrgBr property. * * @return * possible object is * {@link ChargeBearerType1Code } * */ public ChargeBearerType1Code getChrgBr() { return chrgBr; } /** * Sets the value of the chrgBr property. * * @param value * allowed object is * {@link ChargeBearerType1Code } * */ public CreditTransferTransactionInformation14 setChrgBr(ChargeBearerType1Code value) { this.chrgBr = value; return this; } /** * Gets the value of the chqInstr property. * * @return * possible object is * {@link Cheque6 } * */ public Cheque6 getChqInstr() { return chqInstr; } /** * Sets the value of the chqInstr property. * * @param value * allowed object is * {@link Cheque6 } * */ public CreditTransferTransactionInformation14 setChqInstr(Cheque6 value) { this.chqInstr = value; return this; } /** * Gets the value of the ultmtDbtr property. * * @return * possible object is * {@link PartyIdentification43 } * */ public PartyIdentification43 getUltmtDbtr() { return ultmtDbtr; } /** * Sets the value of the ultmtDbtr property. * * @param value * allowed object is * {@link PartyIdentification43 } * */ public CreditTransferTransactionInformation14 setUltmtDbtr(PartyIdentification43 value) { this.ultmtDbtr = value; return this; } /** * Gets the value of the intrmyAgt1 property. * * @return * possible object is * {@link BranchAndFinancialInstitutionIdentification5 } * */ public BranchAndFinancialInstitutionIdentification5 getIntrmyAgt1() { return intrmyAgt1; } /** * Sets the value of the intrmyAgt1 property. * * @param value * allowed object is * {@link BranchAndFinancialInstitutionIdentification5 } * */ public CreditTransferTransactionInformation14 setIntrmyAgt1(BranchAndFinancialInstitutionIdentification5 value) { this.intrmyAgt1 = value; return this; } /** * Gets the value of the intrmyAgt2 property. * * @return * possible object is * {@link BranchAndFinancialInstitutionIdentification5 } * */ public BranchAndFinancialInstitutionIdentification5 getIntrmyAgt2() { return intrmyAgt2; } /** * Sets the value of the intrmyAgt2 property. * * @param value * allowed object is * {@link BranchAndFinancialInstitutionIdentification5 } * */ public CreditTransferTransactionInformation14 setIntrmyAgt2(BranchAndFinancialInstitutionIdentification5 value) { this.intrmyAgt2 = value; return this; } /** * Gets the value of the intrmyAgt3 property. * * @return * possible object is * {@link BranchAndFinancialInstitutionIdentification5 } * */ public BranchAndFinancialInstitutionIdentification5 getIntrmyAgt3() { return intrmyAgt3; } /** * Sets the value of the intrmyAgt3 property. * * @param value * allowed object is * {@link BranchAndFinancialInstitutionIdentification5 } * */ public CreditTransferTransactionInformation14 setIntrmyAgt3(BranchAndFinancialInstitutionIdentification5 value) { this.intrmyAgt3 = value; return this; } /** * Gets the value of the cdtrAgt property. * * @return * possible object is * {@link BranchAndFinancialInstitutionIdentification5 } * */ public BranchAndFinancialInstitutionIdentification5 getCdtrAgt() { return cdtrAgt; } /** * Sets the value of the cdtrAgt property. * * @param value * allowed object is * {@link BranchAndFinancialInstitutionIdentification5 } * */ public CreditTransferTransactionInformation14 setCdtrAgt(BranchAndFinancialInstitutionIdentification5 value) { this.cdtrAgt = value; return this; } /** * Gets the value of the cdtr property. * * @return * possible object is * {@link PartyIdentification43 } * */ public PartyIdentification43 getCdtr() { return cdtr; } /** * Sets the value of the cdtr property. * * @param value * allowed object is * {@link PartyIdentification43 } * */ public CreditTransferTransactionInformation14 setCdtr(PartyIdentification43 value) { this.cdtr = value; return this; } /** * Gets the value of the cdtrAcct property. * * @return * possible object is * {@link CashAccount16 } * */ public CashAccount16 getCdtrAcct() { return cdtrAcct; } /** * Sets the value of the cdtrAcct property. * * @param value * allowed object is * {@link CashAccount16 } * */ public CreditTransferTransactionInformation14 setCdtrAcct(CashAccount16 value) { this.cdtrAcct = value; return this; } /** * Gets the value of the ultmtCdtr property. * * @return * possible object is * {@link PartyIdentification43 } * */ public PartyIdentification43 getUltmtCdtr() { return ultmtCdtr; } /** * Sets the value of the ultmtCdtr property. * * @param value * allowed object is * {@link PartyIdentification43 } * */ public CreditTransferTransactionInformation14 setUltmtCdtr(PartyIdentification43 value) { this.ultmtCdtr = value; return this; } /** * Gets the value of the instrForCdtrAgt property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the instrForCdtrAgt property. * * <p> * For example, to add a new item, do as follows: * <pre> * getInstrForCdtrAgt().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link InstructionForCreditorAgent1 } * * */ public List<InstructionForCreditorAgent1> getInstrForCdtrAgt() { if (instrForCdtrAgt == null) { instrForCdtrAgt = new ArrayList<InstructionForCreditorAgent1>(); } return this.instrForCdtrAgt; } /** * Gets the value of the purp property. * * @return * possible object is * {@link Purpose2Choice } * */ public Purpose2Choice getPurp() { return purp; } /** * Sets the value of the purp property. * * @param value * allowed object is * {@link Purpose2Choice } * */ public CreditTransferTransactionInformation14 setPurp(Purpose2Choice value) { this.purp = value; return this; } /** * Gets the value of the rgltryRptg property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the rgltryRptg property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRgltryRptg().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link RegulatoryReporting3 } * * */ public List<RegulatoryReporting3> getRgltryRptg() { if (rgltryRptg == null) { rgltryRptg = new ArrayList<RegulatoryReporting3>(); } return this.rgltryRptg; } /** * Gets the value of the tax property. * * @return * possible object is * {@link TaxInformation3 } * */ public TaxInformation3 getTax() { return tax; } /** * Sets the value of the tax property. * * @param value * allowed object is * {@link TaxInformation3 } * */ public CreditTransferTransactionInformation14 setTax(TaxInformation3 value) { this.tax = value; return this; } /** * Gets the value of the rltdRmtInf property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the rltdRmtInf property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRltdRmtInf().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link RemittanceLocation2 } * * */ public List<RemittanceLocation2> getRltdRmtInf() { if (rltdRmtInf == null) { rltdRmtInf = new ArrayList<RemittanceLocation2>(); } return this.rltdRmtInf; } /** * Gets the value of the rmtInf property. * * @return * possible object is * {@link RemittanceInformation6 } * */ public RemittanceInformation6 getRmtInf() { return rmtInf; } /** * Sets the value of the rmtInf property. * * @param value * allowed object is * {@link RemittanceInformation6 } * */ public CreditTransferTransactionInformation14 setRmtInf(RemittanceInformation6 value) { this.rmtInf = value; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } /** * Adds a new item to the instrForCdtrAgt list. * @see #getInstrForCdtrAgt() * */ public CreditTransferTransactionInformation14 addInstrForCdtrAgt(InstructionForCreditorAgent1 instrForCdtrAgt) { getInstrForCdtrAgt().add(instrForCdtrAgt); return this; } /** * Adds a new item to the rgltryRptg list. * @see #getRgltryRptg() * */ public CreditTransferTransactionInformation14 addRgltryRptg(RegulatoryReporting3 rgltryRptg) { getRgltryRptg().add(rgltryRptg); return this; } /** * Adds a new item to the rltdRmtInf list. * @see #getRltdRmtInf() * */ public CreditTransferTransactionInformation14 addRltdRmtInf(RemittanceLocation2 rltdRmtInf) { getRltdRmtInf().add(rltdRmtInf); return this; } }
3e04c9eef7130582194d4f8faf4600e815962db9
3,079
java
Java
app/src/main/java/com/cunoraz/mta/MyCardView.java
Cutta/MaterialTransitionAnimation
297c39b1cb825a683d41afb79b755584d39a0756
[ "Apache-2.0" ]
184
2016-11-04T15:24:45.000Z
2022-03-09T13:28:52.000Z
app/src/main/java/com/cunoraz/mta/MyCardView.java
Cutta/MaterialTransitionAnimation
297c39b1cb825a683d41afb79b755584d39a0756
[ "Apache-2.0" ]
2
2016-11-09T06:06:40.000Z
2017-04-14T13:47:52.000Z
app/src/main/java/com/cunoraz/mta/MyCardView.java
Cutta/MaterialTransitionAnimation
297c39b1cb825a683d41afb79b755584d39a0756
[ "Apache-2.0" ]
42
2016-11-09T04:47:49.000Z
2020-09-22T21:33:41.000Z
34.595506
140
0.664177
2,002
package com.cunoraz.mta; import android.animation.ValueAnimator; import android.content.Context; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.RelativeLayout; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; /** * Created by cuneytcarikci on 02/11/2016. * This view is layout of list item. * when list scrolling margin of items adjust here via eventbus */ public class MyCardView extends RelativeLayout { CardView cardView; ValueAnimator increaseAnimation; ValueAnimator decreaseAnimation; public static final int DURATION = 150; public MyCardView(Context context) { super(context); initialize(context); EventBus.getDefault().register(this); } private void initialize(Context context) { View root = inflate(context, R.layout.item_list, this); cardView = (CardView) root.findViewById(R.id.item_root); } @Subscribe public void onMessage(ScrollEvent event) { int margin = event.getMargin(); if (margin == 0) { if (increaseAnimation != null && increaseAnimation.isRunning()) increaseAnimation.cancel(); RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) getLayoutParams(); int marginBottom = layoutParams.bottomMargin; decreaseAnimation = ValueAnimator.ofInt(marginBottom, 0); decreaseAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) getLayoutParams(); layoutParams.bottomMargin = (int) animation.getAnimatedValue(); setLayoutParams(layoutParams); } }); decreaseAnimation.setDuration(DURATION); decreaseAnimation.start(); } else { if (decreaseAnimation != null && decreaseAnimation.isRunning()) decreaseAnimation.cancel(); RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) getLayoutParams(); int marginBottom = layoutParams.bottomMargin; increaseAnimation = ValueAnimator.ofInt(marginBottom, getResources().getDimensionPixelSize(R.dimen.cardview_max_margin_bottom)); increaseAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) getLayoutParams(); layoutParams.bottomMargin = (int) animation.getAnimatedValue(); setLayoutParams(layoutParams); } }); increaseAnimation.setDuration(DURATION); increaseAnimation.start(); } } }
3e04ca944da546cb83553810638103d78af623a4
73
java
Java
src/unluac/test/TestResult.java
trarck/unluac
ca885dbf5a14b7467ce90f1e91b49401c2959138
[ "MIT" ]
6
2015-10-21T07:14:10.000Z
2019-10-24T15:38:20.000Z
unluac-hgcode/src/unluac/test/TestResult.java
duangsuse/AUnluac
61c106fe7de0b1d6636f29564ffb1aea89e1643f
[ "MIT" ]
null
null
null
unluac-hgcode/src/unluac/test/TestResult.java
duangsuse/AUnluac
61c106fe7de0b1d6636f29564ffb1aea89e1643f
[ "MIT" ]
4
2016-07-10T00:55:09.000Z
2021-08-09T07:29:26.000Z
9.125
24
0.712329
2,003
package unluac.test; public enum TestResult { OK, SKIPPED, FAILED }
3e04cb8a6bbababdd21d3eb152b0fa875dae593c
6,724
java
Java
justify/src/main/java/org/leadpony/justify/internal/schema/AbstractJsonSchema.java
talkdesk-tdx/justify
15682458077fb76731808507764a41f7dd41d638
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
null
null
null
justify/src/main/java/org/leadpony/justify/internal/schema/AbstractJsonSchema.java
talkdesk-tdx/justify
15682458077fb76731808507764a41f7dd41d638
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
null
null
null
justify/src/main/java/org/leadpony/justify/internal/schema/AbstractJsonSchema.java
talkdesk-tdx/justify
15682458077fb76731808507764a41f7dd41d638
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
null
null
null
27.333333
112
0.624777
2,004
/* * Copyright 2018-2019 the Justify authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.leadpony.justify.internal.schema; import static org.leadpony.justify.internal.base.Arguments.requireNonNull; import java.net.URI; import java.util.AbstractMap; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.stream.Stream; import javax.json.JsonValue; import org.leadpony.justify.api.ObjectJsonSchema; import org.leadpony.justify.api.JsonSchema; import org.leadpony.justify.api.Keyword; import org.leadpony.justify.internal.base.json.JsonPointerTokenizer; import org.leadpony.justify.internal.keyword.SchemaKeyword; import org.leadpony.justify.internal.keyword.annotation.Default; import org.leadpony.justify.internal.keyword.core.Comment; import org.leadpony.justify.internal.keyword.core.Schema; /** * Skeletal implementation of {@link JsonSchema}. * * @author leadpony */ abstract class AbstractJsonSchema extends AbstractMap<String, Keyword> implements ObjectJsonSchema, Resolvable { private URI id; private final JsonValue json; private final Map<String, SchemaKeyword> keywordMap; protected AbstractJsonSchema(URI id, JsonValue json, Map<String, SchemaKeyword> keywords) { this.id = id; this.json = json; this.keywordMap = Collections.unmodifiableMap(keywords); this.keywordMap.forEach((k, v) -> v.setEnclosingSchema(this)); if (hasAbsoluteId()) { resolveSubschemas(id()); } } /* As a JsonSchema */ @Override public boolean hasId() { return id != null; } @Override public URI id() { return id; } @Override public URI schema() { if (containsKeyword("$schema")) { Schema keyword = getKeyword("$schema"); return keyword.value(); } else { return null; } } @Override public String comment() { if (containsKeyword("$comment")) { Comment keyword = getKeyword("$comment"); return keyword.value(); } else { return null; } } @Override public JsonValue defaultValue() { if (containsKeyword("default")) { Default keyword = getKeyword("default"); return keyword.value(); } else { return null; } } @Override public boolean isBoolean() { return false; } @Override public boolean containsKeyword(String keyword) { requireNonNull(keyword, "keyword"); return keywordMap.containsKey(keyword); } @Override public JsonValue getKeywordValue(String keyword) { return getKeywordValue(keyword, null); } @Override public JsonValue getKeywordValue(String keyword, JsonValue defaultValue) { requireNonNull(keyword, "keyword"); Keyword found = keywordMap.get(keyword); if (found == null) { return defaultValue; } return found.getValueAsJson(); } @Override public Stream<JsonSchema> getSubschemas() { return keywordMap.values().stream() .filter(SchemaKeyword::hasSubschemas) .flatMap(SchemaKeyword::getSubschemas); } @Override public Stream<JsonSchema> getInPlaceSubschemas() { return keywordMap.values().stream() .filter(SchemaKeyword::hasSubschemas) .filter(SchemaKeyword::isInPlace) .flatMap(SchemaKeyword::getSubschemas); } @Override public JsonSchema getSubschemaAt(String jsonPointer) { requireNonNull(jsonPointer, "jsonPointer"); if (jsonPointer.isEmpty()) { return this; } return searchKeywordsForSubschema(jsonPointer); } @Override public final JsonValue toJson() { return json; } @Override public int hashCode() { return System.identityHashCode(this); } @Override public boolean equals(Object obj) { return this == obj; } @Override public String toString() { return toJson().toString(); } /* Resolvable interface */ @Override public void resolve(URI baseUri) { if (hasAbsoluteId()) { return; } else if (hasId()) { this.id = baseUri.resolve(this.id); baseUri = this.id; } resolveSubschemas(baseUri); } public boolean hasAbsoluteId() { return hasId() && id().isAbsolute(); } /* As a Map */ @Override public int size() { return keywordMap.size(); } @Override public boolean containsKey(Object key) { return keywordMap.containsKey(key); } @Override public boolean containsValue(Object value) { return keywordMap.containsValue(value); } @Override public Keyword get(Object key) { return keywordMap.get(key); } @Override @SuppressWarnings("unchecked") public Set<Entry<String, Keyword>> entrySet() { Set<?> entrySet = this.keywordMap.entrySet(); return (Set<Entry<String, Keyword>>) entrySet; } @SuppressWarnings("unchecked") protected <T extends Keyword> T getKeyword(String name) { return (T) keywordMap.get(name); } private JsonSchema searchKeywordsForSubschema(String jsonPointer) { JsonPointerTokenizer tokenizer = new JsonPointerTokenizer(jsonPointer); SchemaKeyword keyword = keywordMap.get(tokenizer.next()); if (keyword != null) { JsonSchema candidate = keyword.getSubschema(tokenizer); if (candidate != null) { if (tokenizer.hasNext()) { return candidate.getSubschemaAt(tokenizer.remaining()); } else { return candidate; } } } return null; } private void resolveSubschemas(URI baseUri) { getSubschemas() .filter(s -> !s.hasAbsoluteId()) .filter(s -> s instanceof Resolvable) .forEach(s -> ((Resolvable) s).resolve(baseUri)); } }
3e04cb9ca2e1e1426580d24ad79c9ba6fb816e47
11,665
java
Java
src/main/java/com/xero/api/OAuthRequestResource.java
trungie/Xero-Java
981ec06610faf4d31f88da577d27e5edbf942b1e
[ "MIT" ]
null
null
null
src/main/java/com/xero/api/OAuthRequestResource.java
trungie/Xero-Java
981ec06610faf4d31f88da577d27e5edbf942b1e
[ "MIT" ]
null
null
null
src/main/java/com/xero/api/OAuthRequestResource.java
trungie/Xero-Java
981ec06610faf4d31f88da577d27e5edbf942b1e
[ "MIT" ]
null
null
null
32.67507
174
0.672953
2,005
/* * Copyright (c) 2015 Xero Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.xero.api; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.api.client.auth.oauth.OAuthSigner; import com.google.api.client.http.GenericUrl; public class OAuthRequestResource { private String token; private String tokenSecret; private GenericUrl url; private byte[] requestBody = null; public String contentType = null; public String ifModifiedSince = null; public String accept = null; private String body = null; private String httpMethod = "GET"; private String resource; private int connectTimeout = 20; private int readTimeout = 20; private Map<? extends String, ?> params = null; private Config config; private SignerFactory signerFactory; private String fileName; final static Logger logger = LogManager.getLogger(OAuthRequestResource.class); private OAuthRequestResource(Config config, SignerFactory signerFactory, String resource, String method, Map<? extends String, ?> params) { this.config = config; this.signerFactory = signerFactory; this.resource = resource; this.httpMethod = method; this.params = params; this.connectTimeout = config.getConnectTimeout() * 1000; this.readTimeout = config.getReadTimeout() * 1000; } public OAuthRequestResource(Config config, SignerFactory signerFactory, String resource, String method, String body, Map<? extends String, ?> params) { this(config, signerFactory, resource, method, params); this.body = body; } public OAuthRequestResource(Config config, SignerFactory signerFactory, String resource, String method, String body, Map<? extends String, ?> params, String accept) { this(config, signerFactory, resource, method, params); this.accept = accept; this.body = body; } public OAuthRequestResource(Config config, SignerFactory signerFactory, String resource, String method, String contentType, byte[] bytes, Map<? extends String, ?> params) { this(config, signerFactory, resource, method, params); this.contentType = contentType; this.requestBody = bytes; } public OAuthRequestResource(Config config, SignerFactory signerFactory, String resource, String method, String contentType, File file, Map<? extends String, ?> params) { this(config, signerFactory, resource, method, params); this.contentType = contentType; } public final ByteArrayInputStream executefile() throws UnsupportedOperationException, IOException { CloseableHttpClient httpclient =null; httpclient = new XeroHttpContext(config,this.accept,this.contentType,this.ifModifiedSince).getHttpClient(); url = new GenericUrl(config.getApiUrl() + this.resource); if (this.params != null) { url.putAll(this.params); } HttpGet httpget = new HttpGet(url.toString()); if (httpMethod == "GET") { this.createParameters().intercept(httpget,url); httpget.addHeader("accept", "application/pdf"); } HttpPost httppost = new HttpPost(url.toString()); if (httpMethod == "POST") { httppost.setEntity(new StringEntity(this.body, "utf-8")); this.createParameters().intercept(httppost,url); } HttpPut httpput = new HttpPut(url.toString()); if (httpMethod == "PUT") { httpput.setEntity(new StringEntity(this.body, "utf-8")); this.createParameters().intercept(httpput,url); } HttpEntity entity; try { CloseableHttpResponse response = null; if (httpMethod == "GET") { response = httpclient.execute(httpget); } if (httpMethod == "POST") { response = httpclient.execute(httppost); } if (httpMethod == "PUT") { response = httpclient.execute(httpput); } try { entity = response.getEntity(); List<Header> httpHeaders = Arrays.asList(response.getAllHeaders()); for (Header header : httpHeaders) { if (header.getName() == "Content-Disposition") { this.fileName = parseFileName(header.getValue()); } //System.out.println("Headers.. name,value:"+header.getName() + "," + header.getValue()); } InputStream is = entity.getContent(); byte[] bytes = IOUtils.toByteArray(is); is.close(); return new ByteArrayInputStream(bytes); } finally { response.close(); } } finally { httpclient.close(); } } private String parseFileName(String param) { String fileName = null; Pattern regex = Pattern.compile("(?<=filename=\").*?(?=\")"); Matcher regexMatcher = regex.matcher(param); if (regexMatcher.find()) { fileName = regexMatcher.group(); } return fileName; } public String getFileName() { return this.fileName; } public final Map<String, String> execute() throws IOException,XeroApiException { CloseableHttpClient httpclient =null; httpclient = new XeroHttpContext(config,this.accept,this.contentType,this.ifModifiedSince).getHttpClient(); url = new GenericUrl(config.getApiUrl() + this.resource); if (this.params != null) { url.putAll(this.params); } RequestConfig.Builder requestConfig = RequestConfig.custom() .setConnectTimeout(connectTimeout) .setConnectionRequestTimeout(readTimeout) .setSocketTimeout(connectTimeout); //Proxy Service Setup - unable to fully test as we don't have a proxy // server to test against. if(!"".equals(config.getProxyHost()) && config.getProxyHost() != null) { int port = (int) (config.getProxyPort() == 80 && config.getProxyHttpsEnabled() ? 443 : config.getProxyPort()); HttpHost proxy = new HttpHost(config.getProxyHost(), port, config.getProxyHttpsEnabled() ? "https" : "http"); requestConfig.setProxy(proxy); } HttpGet httpget = new HttpGet(url.toString()); if (httpMethod == "GET") { this.createParameters().intercept(httpget,url); httpget.setConfig(requestConfig.build()); if(logger.isInfoEnabled()){ logger.info("------------------ GET : URL -------------------"); logger.info(url.toString()); } } HttpPost httppost = new HttpPost(url.toString()); if (httpMethod == "POST") { if(logger.isInfoEnabled()){ logger.info("------------------ POST: BODY -------------------"); logger.info(this.body); } httppost.setEntity(new StringEntity(this.body, "utf-8")); this.createParameters().intercept(httppost,url); httppost.setConfig(requestConfig.build()); } HttpPut httpput = new HttpPut(url.toString()); if (httpMethod == "PUT") { if(logger.isInfoEnabled()){ logger.info("------------------ PUT : BODY -------------------"); logger.info(this.body); } if(this.requestBody != null) { httpput.setEntity(new ByteArrayEntity(this.requestBody)); } else { httpput.setEntity(new StringEntity(this.body, "utf-8")); } this.createParameters().intercept(httpput,url); httpput.setConfig(requestConfig.build()); } HttpDelete httpdelete = new HttpDelete(url.toString()); if (httpMethod == "DELETE") { this.createParameters().intercept(httpdelete,url); httpdelete.setConfig(requestConfig.build()); if(logger.isInfoEnabled()){ logger.info("------------------ DELTE : URL -------------------"); logger.info(url.toString()); } } HttpEntity entity; try { CloseableHttpResponse response = null; if (httpMethod == "GET") { response = httpclient.execute(httpget); } if (httpMethod == "POST") { response = httpclient.execute(httppost); } if (httpMethod == "PUT") { response = httpclient.execute(httpput); } if (httpMethod == "DELETE") { response = httpclient.execute(httpdelete); } try { String content = ""; entity = response.getEntity(); if(entity != null) { content = EntityUtils.toString(entity); } int code = response.getStatusLine().getStatusCode(); if (code == 204) { content = "<Response><Status>DELETED</Status></Response>"; } if (code != 200 && code != 204) { Header rateHeader = response.getFirstHeader("x-rate-limit-problem"); if (rateHeader != null) { content += "&rate=" + rateHeader.getValue().toLowerCase(); } XeroApiException e = new XeroApiException(code,content); throw e; } Map<String, String> responseMap = new HashMap<>(); addToMapIfNotNull(responseMap, "content", content); addToMapIfNotNull(responseMap, "code", code); // TODO: ADD LOGGING of Code & Content if(entity != null) { EntityUtils.consume(entity); } return responseMap; } finally { response.close(); } } finally { httpclient.close(); } } protected void addToMapIfNotNull(Map<String, String> map, String key, Object value) { if (value != null) { map.put(key, value.toString()); } } public void setMethod(String method) { this.httpMethod = method; } public void setToken(String token) { this.token = token; if(config.getAppType().equals("PRIVATE")) { this.token = config.getConsumerKey(); } } public void setTokenSecret(String secret) { this.tokenSecret = secret; } public void setIfModifiedSince(Date modifiedAfter) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); this.ifModifiedSince = formatter.format(modifiedAfter); } public OAuthParameters createParameters() { OAuthSigner signer = signerFactory.createSigner(tokenSecret); OAuthParameters result = new OAuthParameters(); result.consumerKey = config.getConsumerKey(); result.usingAppFirewall = config.isUsingAppFirewall(); result.appFirewallHostname = config.getAppFirewallHostname(); result.appFirewallUrlPrefix = config.getAppFirewallUrlPrefix(); result.token = token; result.signer = signer; return result; } @Deprecated public void setProxy(String host, int port, boolean httpsEnabled) { } }
3e04cbdf8f25b6546e1fb611ccbc6662a4bbbbde
1,145
java
Java
commons/core/src/test/java/org/openehealth/ipf/commons/core/test/ConditionalClassRuleTest.java
DevFlorian/ipf
72a63c22800317cfe036999a65d8cc7116f53f1a
[ "Apache-2.0" ]
121
2015-04-01T05:27:48.000Z
2022-03-19T14:12:48.000Z
commons/core/src/test/java/org/openehealth/ipf/commons/core/test/ConditionalClassRuleTest.java
dumip/ipf
67edd842f2317dd8657238c406f28c3d0b009315
[ "Apache-2.0" ]
304
2015-01-09T12:55:33.000Z
2022-03-30T17:19:01.000Z
commons/core/src/test/java/org/openehealth/ipf/commons/core/test/ConditionalClassRuleTest.java
dumip/ipf
67edd842f2317dd8657238c406f28c3d0b009315
[ "Apache-2.0" ]
70
2015-02-07T16:32:23.000Z
2022-02-16T06:48:50.000Z
28.625
84
0.716157
2,006
/* * Copyright 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 org.openehealth.ipf.commons.core.test; import org.junit.ClassRule; import org.junit.Test; import static org.junit.Assert.fail; /** * */ public class ConditionalClassRuleTest { private static final String currentArchitecture = System.getProperty("os.name"); @ClassRule public static ConditionalRule rule = new ConditionalRule() .ifSystemPropertyIs("os.name", currentArchitecture) .negate(); @Test public void testIgnore() { fail("Should not be executed"); } }
3e04cc75e1743255d7ca92ae09bc87ecbafc70e6
933
java
Java
src/sistema/util/Date.java
filipeluiz/SistemaControleAcademico
c21d59733356d10422c88f93acf9d13792de17e2
[ "MIT" ]
null
null
null
src/sistema/util/Date.java
filipeluiz/SistemaControleAcademico
c21d59733356d10422c88f93acf9d13792de17e2
[ "MIT" ]
null
null
null
src/sistema/util/Date.java
filipeluiz/SistemaControleAcademico
c21d59733356d10422c88f93acf9d13792de17e2
[ "MIT" ]
null
null
null
25.216216
99
0.637728
2,007
package sistema.util; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; /** * * @author filipe */ public class Date { private static final String dataPadrao = "dd/MM/yyyy"; private static final DateTimeFormatter dataFormato = DateTimeFormatter.ofPattern(dataPadrao); //Data converter para String public static String format(LocalDate date) { if (date == null) { return null; } return dataFormato.format(date); } //String converter para Data public static LocalDate parse(String dateString) { try { return dataFormato.parse(dateString, LocalDate::from); } catch (DateTimeParseException e) { return null; } } //Validar Data public static boolean validDate(LocalDate date) { return date == null; } }
3e04cd55ab933fc6bee67ba87d56360c15d792de
1,509
java
Java
hrms/src/main/java/com/konstantinlevin77/hrms/business/concretes/employerFieldCheckers/EmployerDomainChecker.java
konstantinlevin77/hrms
a2233c0e74fa76081bb7c219f6c69daa20044b6b
[ "MIT" ]
7
2021-05-26T12:51:06.000Z
2021-06-09T18:51:36.000Z
hrms/src/main/java/com/konstantinlevin77/hrms/business/concretes/employerFieldCheckers/EmployerDomainChecker.java
konstantinlevin77/hrms
a2233c0e74fa76081bb7c219f6c69daa20044b6b
[ "MIT" ]
null
null
null
hrms/src/main/java/com/konstantinlevin77/hrms/business/concretes/employerFieldCheckers/EmployerDomainChecker.java
konstantinlevin77/hrms
a2233c0e74fa76081bb7c219f6c69daa20044b6b
[ "MIT" ]
null
null
null
26.946429
82
0.761431
2,008
package com.konstantinlevin77.hrms.business.concretes.employerFieldCheckers; import com.konstantinlevin77.hrms.business.abstracts.FieldChecker; import com.konstantinlevin77.hrms.core.results.abstracts.Result; import com.konstantinlevin77.hrms.core.results.concretes.ErrorResult; import com.konstantinlevin77.hrms.core.results.concretes.SuccessResult; import com.konstantinlevin77.hrms.dataAccess.abstracts.EmployerDao; import com.konstantinlevin77.hrms.entities.concretes.Employer; import java.net.*; import java.io.*; public class EmployerDomainChecker implements FieldChecker<Employer, EmployerDao>{ @Override public Result check(Employer data, EmployerDao dao){ try { String webDomain = this.getWebsiteDomain(data.getCompanyWebsite()); String emailDomain = this.getEmailDomain(data.getEmail()); System.out.println(webDomain); System.out.println(emailDomain); if (!webDomain.equals(emailDomain)) { return new ErrorResult("Website ve email'in domaini aynı olmalıdır."); } } catch(MalformedURLException e){ return new ErrorResult("Website çözümlenirken bir sorun ile karşılaşıldı."); } return new SuccessResult(); } private String getWebsiteDomain(String url) throws MalformedURLException{ URL websiteUrl = new URL(url); String websiteDomain = websiteUrl.getHost().replace("www.", ""); return websiteDomain; } private String getEmailDomain(String email) { return email.substring(email.indexOf("@") + 1); } }
3e04cea0bd96ac72dc70032e7eb315dad5b8fadd
3,214
java
Java
jaxws-cxf-client-ssl/src/test/java/com/codenotfound/soap/http/cxf/HelloWorldClientImplTest.java
harishkadamudi/spring-boot-cxf
92c33093bc69c080edfd607b025aedfaf1aff9b5
[ "MIT" ]
5
2016-12-06T23:09:58.000Z
2020-01-30T18:21:54.000Z
jaxws-cxf-client-ssl/src/test/java/com/codenotfound/soap/http/cxf/HelloWorldClientImplTest.java
harishkadamudi/spring-boot-cxf
92c33093bc69c080edfd607b025aedfaf1aff9b5
[ "MIT" ]
2
2016-12-06T23:09:33.000Z
2017-01-13T19:23:17.000Z
jaxws-cxf-client-ssl/src/test/java/com/codenotfound/soap/http/cxf/HelloWorldClientImplTest.java
harishkadamudi/spring-boot-cxf
92c33093bc69c080edfd607b025aedfaf1aff9b5
[ "MIT" ]
26
2016-10-17T12:45:07.000Z
2020-12-09T18:57:45.000Z
40.683544
103
0.755756
2,009
package com.codenotfound.soap.http.cxf; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileInputStream; import java.security.KeyStore; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import org.apache.cxf.configuration.jsse.TLSServerParameters; import org.apache.cxf.jaxws.JaxWsServerFactoryBean; import org.apache.cxf.transport.http_jetty.JettyHTTPServerEngineFactory; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.codenotfound.services.helloworld.Person; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:/META-INF/spring/cxf-client.xml" }) public class HelloWorldClientImplTest { private static String KEY_STORE_PATH_NAME = "./src/test/resources/jks/keystore-server.jks"; private static String KEY_STORE_PASSWORD = "keystore-server-password"; private static String PRIVATE_KEY_PASSWORD = "server-privatekey-password"; private static String ENDPOINT_ADDRESS = "https://localhost:9443/cnf/services/helloworld"; @Autowired private HelloWorldClientImpl helloWorldClientImplBean; @BeforeClass public static void setUpBeforeClass() throws Exception { /* * create a JettyHTTPServerEngineFactory to handle the configuration of * network port numbers for use with "HTTPS" */ JettyHTTPServerEngineFactory jettyHTTPServerEngineFactory = new JettyHTTPServerEngineFactory(); // load the key store containing the server certificate File keyStoreFile = new File(KEY_STORE_PATH_NAME); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(keyStoreFile), KEY_STORE_PASSWORD.toCharArray()); // create a key manager to handle the server private/public key pair KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, PRIVATE_KEY_PASSWORD.toCharArray()); KeyManager[] keyManager = keyManagerFactory.getKeyManagers(); // set the TLSServerParameters on theJettyHTTPServerEngineFactory TLSServerParameters tLSServerParameters = new TLSServerParameters(); tLSServerParameters.setKeyManagers(keyManager); jettyHTTPServerEngineFactory.setTLSServerParametersForPort(9443, tLSServerParameters); JaxWsServerFactoryBean jaxWsServerFactoryBean = new JaxWsServerFactoryBean(); jaxWsServerFactoryBean.setServiceBean(new HelloWorldServerImplMock()); jaxWsServerFactoryBean.setAddress(ENDPOINT_ADDRESS); jaxWsServerFactoryBean.create(); } @Test public void testSayHello() { Person person = new Person(); person.setFirstName("Sherlock"); person.setLastName("Holmes"); assertEquals("Hello Sherlock Holmes!", helloWorldClientImplBean.sayHello(person)); } }
3e04cf3c571bdf8e90131b6af23e4b34daa57593
3,906
java
Java
main/plugins/org.talend.repository.items.importexport.ui/src/main/java/org/talend/repository/items/importexport/ui/managers/ProviderManager.java
coheigea/tcommon-studio-se
681d9a8240b120f5633d751590ac09d31ea8879b
[ "Apache-2.0" ]
75
2015-01-29T03:23:32.000Z
2022-02-26T07:05:40.000Z
main/plugins/org.talend.repository.items.importexport.ui/src/main/java/org/talend/repository/items/importexport/ui/managers/ProviderManager.java
coheigea/tcommon-studio-se
681d9a8240b120f5633d751590ac09d31ea8879b
[ "Apache-2.0" ]
813
2015-01-21T09:36:31.000Z
2022-03-30T01:15:29.000Z
main/plugins/org.talend.repository.items.importexport.ui/src/main/java/org/talend/repository/items/importexport/ui/managers/ProviderManager.java
coheigea/tcommon-studio-se
681d9a8240b120f5633d751590ac09d31ea8879b
[ "Apache-2.0" ]
272
2015-01-08T06:47:46.000Z
2022-02-09T23:22:27.000Z
33.101695
87
0.654378
2,010
// ============================================================================ // // Copyright (C) 2006-2021 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.repository.items.importexport.ui.managers; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.zip.ZipFile; import org.eclipse.core.runtime.IPath; import org.eclipse.ui.internal.wizards.datatransfer.ArchiveFileManipulations; import org.eclipse.ui.internal.wizards.datatransfer.TarFile; import org.eclipse.ui.internal.wizards.datatransfer.TarLeveledStructureProvider; import org.eclipse.ui.internal.wizards.datatransfer.ZipLeveledStructureProvider; import org.eclipse.ui.wizards.datatransfer.IImportStructureProvider; import org.talend.repository.items.importexport.handlers.model.ImportItem; /** */ public class ProviderManager extends AbstractImportResourcesManager { private IImportStructureProvider provider; public ProviderManager(Object provider) { this.provider = (IImportStructureProvider) provider; } public ProviderManager(File file) throws Exception { if (ArchiveFileManipulations.isTarFile(file.getPath())) { provider = new TarLeveledStructureProvider(new TarFile(file)); } else if (ArchiveFileManipulations.isZipFile(file.getPath())) { provider = new TalendZipLeveledStructureProvider(new ZipFile(file)); } } @Override public InputStream getStream(IPath path, ImportItem importItem) { return provider.getContents(path2Object.get(path)); } @Override public boolean collectPath2Object(Object root) { return doCollectItemFiles(root, 0); } private boolean doCollectItemFiles(Object entry, int level) { List children = provider.getChildren(entry); if (children == null) { children = new ArrayList(1); } Iterator childrenEnum = children.iterator(); while (childrenEnum.hasNext()) { Object child = childrenEnum.next(); if (provider.isFolder(child)) { doCollectItemFiles(child, level + 1); addFolder(provider.getFullPath(child)); } else { add(provider.getFullPath(child), child); } } return true; } @Override public void closeResource() { if (provider instanceof ZipLeveledStructureProvider) { ((ZipLeveledStructureProvider) provider).closeArchive(); } if (provider instanceof TarLeveledStructureProvider) { ((TarLeveledStructureProvider) provider).closeArchive(); } if (provider instanceof TalendZipLeveledStructureProvider) { ((TalendZipLeveledStructureProvider) provider).closeArchive(); } } /** * Getter for provider. * * @return the provider */ @Override public IImportStructureProvider getProvider() { return this.provider; } /* * (non-Javadoc) * * @see org.talend.repository.items.importexport.manager.ResourcesManager#getRoot() */ @Override public Object getRoot() { if (provider instanceof ZipLeveledStructureProvider) { return ((ZipLeveledStructureProvider) provider).getRoot(); } if (provider instanceof TarLeveledStructureProvider) { return ((TarLeveledStructureProvider) provider).getRoot(); } return null; } }
3e04cf6578f9a4f503f97da1e8ef2065a89e467b
237
java
Java
src/main/java/com/design/patterns/structural/adapter/SquarePeg.java
surajpjannu/DesignPatterns
aca8ccb61062de3e620dc183504baeec841520a8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/design/patterns/structural/adapter/SquarePeg.java
surajpjannu/DesignPatterns
aca8ccb61062de3e620dc183504baeec841520a8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/design/patterns/structural/adapter/SquarePeg.java
surajpjannu/DesignPatterns
aca8ccb61062de3e620dc183504baeec841520a8
[ "Apache-2.0" ]
null
null
null
16.928571
47
0.805907
2,011
package com.design.patterns.structural.adapter; import lombok.AllArgsConstructor; import lombok.Data; import lombok.Getter; import lombok.Setter; @Getter @Setter @AllArgsConstructor public class SquarePeg { private double width; }
3e04cf6e908c844188487979348a98e427586468
861
java
Java
Acacia360CASA_CBS/services/UserAccountFacade/src/com/user/maintenance/form/UserListForm.java
dekso/casa-project
d29da70fdd3efb13d69d8a2ec6c7db7122fe03c1
[ "Apache-2.0" ]
null
null
null
Acacia360CASA_CBS/services/UserAccountFacade/src/com/user/maintenance/form/UserListForm.java
dekso/casa-project
d29da70fdd3efb13d69d8a2ec6c7db7122fe03c1
[ "Apache-2.0" ]
null
null
null
Acacia360CASA_CBS/services/UserAccountFacade/src/com/user/maintenance/form/UserListForm.java
dekso/casa-project
d29da70fdd3efb13d69d8a2ec6c7db7122fe03c1
[ "Apache-2.0" ]
null
null
null
16.882353
43
0.691057
2,012
package com.user.maintenance.form; public class UserListForm { private int id; private String username; private String name; private String userid; private String branch; private String role; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } }