blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 28 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bc6a0e94e8f95a8107e21d1981ca30b9ea27dee2 | ae0d4f528c889cbaba046197ac1a58fb774d38fe | /optaplanner-persistence/optaplanner-persistence-jackson/src/test/java/org/optaplanner/persistence/jackson/api/score/buildin/simplelong/SimpleLongScoreJacksonJsonSerializerAndDeserializerTest.java | 4494d6304cd1368af77f17d213185d6d8c269bc9 | [
"Apache-2.0"
] | permissive | guotechfin/optaplanner | 9ee4771bd55c7511c8a4f9753a3105f3dd511c9d | f66b33b580af92ec4b55f9ec2ac926a27dab3b1c | refs/heads/master | 2021-01-25T11:39:20.868655 | 2018-02-28T18:08:34 | 2018-02-28T18:08:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,337 | java | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* 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.optaplanner.persistence.jackson.api.score.buildin.simplelong;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.junit.Test;
import org.optaplanner.core.api.score.buildin.simplelong.SimpleLongScore;
import org.optaplanner.persistence.jackson.api.score.AbstractScoreJacksonJsonSerializerAndDeserializerTest;
import org.optaplanner.persistence.jackson.api.score.ScoreJacksonJsonSerializer;
public class SimpleLongScoreJacksonJsonSerializerAndDeserializerTest extends AbstractScoreJacksonJsonSerializerAndDeserializerTest {
@Test
public void serializeAndDeserialize() {
assertSerializeAndDeserialize(null, new TestSimpleLongScoreWrapper(null));
SimpleLongScore score = SimpleLongScore.valueOf(1234L);
assertSerializeAndDeserialize(score, new TestSimpleLongScoreWrapper(score));
score = SimpleLongScore.valueOfUninitialized(-7, 1234L);
assertSerializeAndDeserialize(score, new TestSimpleLongScoreWrapper(score));
}
public static class TestSimpleLongScoreWrapper extends AbstractScoreJacksonJsonSerializerAndDeserializerTest.TestScoreWrapper<SimpleLongScore> {
@JsonSerialize(using = ScoreJacksonJsonSerializer.class)
@JsonDeserialize(using = SimpleLongScoreJacksonJsonDeserializer.class)
private SimpleLongScore score;
@SuppressWarnings("unused")
private TestSimpleLongScoreWrapper() {
}
public TestSimpleLongScoreWrapper(SimpleLongScore score) {
this.score = score;
}
@Override
public SimpleLongScore getScore() {
return score;
}
}
}
| [
"gds.geoffrey.de.smet@gmail.com"
] | gds.geoffrey.de.smet@gmail.com |
fbbcb1a590bfcc9372da67f58a5e30b25e0a75cc | 70daf318d027f371ada3abeaaa31dd47651640d7 | /src/jdo/sta/bean/ABDSType.java | 1bcbc868147aa17c490e649d2a23ae815b142ae4 | [] | no_license | wangqing123654/web | 00613f6db653562e2e8edc14327649dc18b2aae6 | bd447877400291d3f35715ca9c7c7b1e79653531 | refs/heads/master | 2023-04-07T15:23:34.705954 | 2020-11-02T10:10:57 | 2020-11-02T10:10:57 | 309,329,277 | 0 | 0 | null | null | null | null | WINDOWS-1252 | Java | false | false | 2,110 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.06.30 at 10:28:02 ÉÏÎç CST
//
package jdo.sta.bean;
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.XmlType;
/**
* <p>Java class for ABDSType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ABDSType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ABD" type="{}ABDType" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ABDSType", propOrder = {
"abd"
})
public class ABDSType {
@XmlElement(name = "ABD", required = true, nillable = true)
protected List<ABDType> abd;
/**
* Gets the value of the abd 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 abd property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getABD().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ABDType }
*
*
*/
public List<ABDType> getABD() {
if (abd == null) {
abd = new ArrayList<ABDType>();
}
return this.abd;
}
}
| [
"1638364772@qq.com"
] | 1638364772@qq.com |
05c13c7f570d165fa2a25fc34d8c38d88c5400b3 | 56ed12faef5df49ba73e7f83e1e8adaa79448985 | /src/main/java/steps/TravelSteps.java | 08c4d0d0aba15282494b24dfd148c7d6c7ebbf65 | [] | no_license | risen777/thirdtest | 316b79420fcd8cc899101729843734e7e342e066 | 7d989366276302b01676ff50f1549532e5e0f836 | refs/heads/master | 2021-05-08T16:54:19.329589 | 2018-02-05T20:32:57 | 2018-02-05T20:32:57 | 120,176,576 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 362 | java | package steps;
import ru.yandex.qatools.allure.annotations.Step;
import pages.TravelPage;
/**
* Created by Sergey
*/
public class TravelSteps extends BaseSteps {
@Step("выполнено нажатие на кнопку отправить заявку")
public void stepSendAppButton(){
new TravelPage(driver).sendButton.click();
}
}
| [
"21risen@gmail.com"
] | 21risen@gmail.com |
4e1e81fade72c070231eaa37d077e352bd51e6e6 | a80600955f65bae7876d79a04952503d4c404157 | /src/main/java/org/morrah77/amazon_score/service/ScoreService.java | 04aef62c75972215cd4a1aa79d0e01faab8535dc | [] | no_license | morrah77/amazon_score | d52b70e08c8927ee496447ceb7e044a2bd96f95d | b5dc715c43eb2f536a5a1f9b52846c8671446a31 | refs/heads/master | 2023-07-14T07:29:42.276973 | 2021-08-08T20:19:37 | 2021-08-08T20:19:37 | 394,062,895 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,998 | java | package org.morrah77.amazon_score.service;
import org.morrah77.amazon_score.domain.AmazonResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Locale;
@Service
public class ScoreService implements IScoreService {
static final int MAX_REQUESTS_NUMBER = 10;
@Autowired
@Qualifier("AmazonDataService")
IDataService service;
@Override
public int getScore(String keyword) {
int result = 0;
String searchKeyword = keyword.toLowerCase(Locale.ROOT).replaceAll("\\s+", "+");
ResponseEntity<AmazonResponseEntity> data = service.getData(searchKeyword);
if ((data.hasBody()) && (data.getBody().getEntry().size() > 1)) {
if (!searchKeyword.replaceAll("\\+", " ").equals((String) (data.getBody().getEntry().get(0)))) {
return result;
}
List<Object> matches = (List<Object>)(data.getBody().getEntry().get(1));
result = calculateScore((String) (data.getBody().getEntry().get(0)), matches);
}
return result;
}
int calculateScore(String keyword, List<Object> matches) {
int reslut = 0;
double intermediateResult = 0;
double coefficient = getCoefficient(matches);
for (Object o : matches) {
if (((String)o).equals(keyword)) {
return 100;
}
if (((String)o).startsWith(keyword)) {
intermediateResult += coefficient / matches.size();
}
}
reslut = (int)(intermediateResult * 100);
return reslut;
}
double getCoefficient(List<Object> matches) {
if (matches.size() >= MAX_REQUESTS_NUMBER) {
return 0.4;
}
return 0.4 / (1 + MAX_REQUESTS_NUMBER - matches.size());
}
}
| [
"helen.lazar.77@gmail.com"
] | helen.lazar.77@gmail.com |
b0944a337df2c96bcd6b6a284c61cd42fc485660 | 5a5e195e0b420a6e218cb44ef916fab167192260 | /src/main/java/com/example/controller/MainController.java | 1f3d666e8e9c755a17b1f430d1bc18cba7855600 | [] | no_license | KrzysztofS20/employee-administration | 64b59481a6398c557f3132c596bf0161627b7459 | 4d97ba45990422ba72fdf8148d9e307c666692d4 | refs/heads/master | 2023-07-14T15:16:34.705528 | 2021-08-19T18:08:02 | 2021-08-19T18:08:02 | 398,033,465 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 272 | java | package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MainController {
@GetMapping("/index")
public String index() {
return "index";
}
}
| [
"krzystof@kursGIT.pl"
] | krzystof@kursGIT.pl |
81a701fc3de3aff5c956a6df8353bf075198460a | 24f66774802ee019595b10c39a9c1dd17db0f622 | /src/replQuestions/Question111.java | 51198c82895e3bb15208678401349860a69c4d5a | [] | no_license | OmarSeker123/untitled2 | 00586010ae940db851b054096d0243dfbc1614f6 | 9795e3c75753186e4a859d90baeec00aba9812d9 | refs/heads/master | 2021-01-14T04:20:25.169440 | 2020-03-26T00:58:37 | 2020-03-26T00:58:37 | 242,597,185 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 280 | java | package replQuestions;
public class Question111 {
public static void main(String[] args) {
int k=1;
int total=0;
do {
total = total + (k * k);
k++;
}while (k<=50);
System.out.println(total);
}
}
| [
"omarseker@yahoo.com"
] | omarseker@yahoo.com |
e61ba7b7b2bb915c8b1ad66fad915535bad137bf | 95460aa445bb62eca02485b17b3465a9efb609a0 | /hw8/HW8.java | 37190667b92498d1b94b8ad72135dc64a5fad6f3 | [] | no_license | caoxantb/developh_hw23 | 0bfbe0a5720136b103ec34f3c3762b121a34a90e | e095a9a68a7c90478da498488d0fa89681fe266a | refs/heads/main | 2023-06-24T03:42:20.318100 | 2021-07-22T05:32:54 | 2021-07-22T05:32:54 | 388,321,182 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 853 | java | package hw8;
public final class HW8 {
private HW8() {
//
}
public static boolean isMultipleBasePalindrome(int num) {
int biNum = intToBi(num);
return isPalindrome(num) && isPalindrome(biNum);
}
public static boolean isPalindrome(int num) {
int tempNum = num;
int reversedNum = 0;
while (tempNum != 0) {
int lastDigit = tempNum % 10;
reversedNum = reversedNum * 10 + lastDigit;
tempNum /= 10;
}
return reversedNum == num;
}
public static Integer intToBi(int num) {
int count = 0;
int biNum = 0;
while (num != 0) {
int re = num % 2;
if (re == 1) biNum += Math.pow(10, count);
count += 1;
num /= 2;
}
return biNum;
}
}
| [
"caoxantb@gmail.com"
] | caoxantb@gmail.com |
cbd1c6ac23d9c7b0523ad6a015ac4bfa145896e8 | 1e3001d4b2c020f3044b65b50bb6d37e7a9b1232 | /src/main/java/com/umesh/learning/multipleJPA/controller/LoginController.java | 768d6fb25ddedafbbe0204113398f0246af23da4 | [] | no_license | umesh936/multipleJPA | 7b315a23525f324f57807f269c4173253ce154fd | 33cc38c9bff33d168a1a13c09cf8b2d86cbf5a21 | refs/heads/master | 2021-01-10T02:01:46.676123 | 2016-04-12T06:11:01 | 2016-04-12T06:11:01 | 52,787,974 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,072 | java | package com.umesh.learning.multipleJPA.controller;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.umesh.learning.multipleJPA.model.user.User;
import com.umesh.learning.multipleJPA.services.LoginService;
@RestController
@RequestMapping("/user")
public class LoginController {
@Resource
LoginService loginservice;
@Resource
ObjectMapper objectMap;
@RequestMapping(value = { "/" }, method = RequestMethod.POST)
public Object saveUser(User user) {
user = loginservice.saveUser(user);
return user;
}
@RequestMapping(value = { "/login" }, method = RequestMethod.GET)
public Object getLoginPage(@RequestParam("email") String email,
@RequestParam("password") String password) {
User user = loginservice.loginAllowed(email, password);
return user;
}
}
| [
"umesh936@gmail.com"
] | umesh936@gmail.com |
cfc21801b8b5aeb5ad0bce23f7f8a145b2162cab | 2ff64b921f884cb59ad26848b3991ca2e2b8967f | /movieCatalog/src/main/java/in/charan/movieCatalog/model/response/MovieRating.java | 49cfff3c9a69bfd9fd682b9a3fbb699464d025f5 | [] | no_license | charankumarbr/MovieCatalog | 6b2a6a829be6c1c1c6e313a0232e30c7922a096e | 5d29bab23ccc42b0a8355d5d7867acbaf3e97088 | refs/heads/master | 2022-12-21T20:19:50.946192 | 2020-10-04T18:08:08 | 2020-10-04T18:08:08 | 297,319,655 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,276 | java | package in.charan.movieCatalog.model.response;
public class MovieRating {
private String movieId;
private String title;
private String desc;
private String releaseDate;
private int userRating;
public MovieRating() {
}
public MovieRating(String movieId, String title, String desc, String releaseDate, int userRating) {
this.movieId = movieId;
this.title = title;
this.desc = desc;
this.releaseDate = releaseDate;
this.userRating = userRating;
}
public String getMovieId() {
return movieId;
}
public void setMovieId(String movieId) {
this.movieId = movieId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public int getUserRating() {
return userRating;
}
public void setUserRating(int userRating) {
this.userRating = userRating;
}
}
| [
"charankumarbr@gmail.com"
] | charankumarbr@gmail.com |
33173dbd7028e1422f12663c55f8d38ca3b00ec6 | dda81b93a12e0695dc1c85a6a8ca3785f2e36e23 | /spigot/work/decompile-93a89a75/net/minecraft/server/LootItemConditionBlockStateProperty.java | be01f43e71c06972a3bfc9d33b3e20fa43793378 | [] | no_license | skychwang/MindCraft | a4a8a337738b884af6ecc65c133b314418757a7d | 48923ed1c2b9fbc807a61619cc17001312082b83 | refs/heads/master | 2023-07-20T14:36:48.872240 | 2021-09-07T20:00:04 | 2021-09-07T20:00:04 | 336,148,107 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,657 | java | package net.minecraft.server;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.function.Predicate;
public class LootItemConditionBlockStateProperty implements LootItemCondition {
private final Block a;
private final Map<IBlockState<?>, Object> b;
private final Predicate<IBlockData> c;
private LootItemConditionBlockStateProperty(Block block, Map<IBlockState<?>, Object> map) {
this.a = block;
this.b = ImmutableMap.copyOf(map);
this.c = a(block, map);
}
private static Predicate<IBlockData> a(Block block, Map<IBlockState<?>, Object> map) {
int i = map.size();
if (i == 0) {
return (iblockdata) -> {
return iblockdata.getBlock() == block;
};
} else if (i == 1) {
Entry<IBlockState<?>, Object> entry = (Entry) map.entrySet().iterator().next();
IBlockState<?> iblockstate = (IBlockState) entry.getKey();
Object object = entry.getValue();
return (iblockdata) -> {
return iblockdata.getBlock() == block && object.equals(iblockdata.get(iblockstate));
};
} else {
Predicate<IBlockData> predicate = (iblockdata) -> {
return iblockdata.getBlock() == block;
};
IBlockState iblockstate1;
Object object1;
for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();predicate = predicate.and((iblockdata) -> {
return object1.equals(iblockdata.get(iblockstate1));
})) {
Entry<IBlockState<?>, Object> entry1 = (Entry) iterator.next();
iblockstate1 = (IBlockState) entry1.getKey();
object1 = entry1.getValue();
}
return predicate;
}
}
@Override
public Set<LootContextParameter<?>> a() {
return ImmutableSet.of(LootContextParameters.BLOCK_STATE);
}
public boolean test(LootTableInfo loottableinfo) {
IBlockData iblockdata = (IBlockData) loottableinfo.getContextParameter(LootContextParameters.BLOCK_STATE);
return iblockdata != null && this.c.test(iblockdata);
}
public static LootItemConditionBlockStateProperty.a a(Block block) {
return new LootItemConditionBlockStateProperty.a(block);
}
public static class b extends LootItemCondition.b<LootItemConditionBlockStateProperty> {
private static <T extends Comparable<T>> String a(IBlockState<T> iblockstate, Object object) {
return iblockstate.a((Comparable) object);
}
protected b() {
super(new MinecraftKey("block_state_property"), LootItemConditionBlockStateProperty.class);
}
public void a(JsonObject jsonobject, LootItemConditionBlockStateProperty lootitemconditionblockstateproperty, JsonSerializationContext jsonserializationcontext) {
jsonobject.addProperty("block", IRegistry.BLOCK.getKey(lootitemconditionblockstateproperty.a).toString());
JsonObject jsonobject1 = new JsonObject();
lootitemconditionblockstateproperty.b.forEach((iblockstate, object) -> {
jsonobject1.addProperty(iblockstate.a(), a(iblockstate, object));
});
jsonobject.add("properties", jsonobject1);
}
@Override
public LootItemConditionBlockStateProperty b(JsonObject jsonobject, JsonDeserializationContext jsondeserializationcontext) {
MinecraftKey minecraftkey = new MinecraftKey(ChatDeserializer.h(jsonobject, "block"));
Block block = (Block) IRegistry.BLOCK.getOptional(minecraftkey).orElseThrow(() -> {
return new IllegalArgumentException("Can't find block " + minecraftkey);
});
BlockStateList<Block, IBlockData> blockstatelist = block.getStates();
Map<IBlockState<?>, Object> map = Maps.newHashMap();
if (jsonobject.has("properties")) {
JsonObject jsonobject1 = ChatDeserializer.t(jsonobject, "properties");
jsonobject1.entrySet().forEach((entry) -> {
String s = (String) entry.getKey();
IBlockState<?> iblockstate = blockstatelist.a(s);
if (iblockstate == null) {
throw new IllegalArgumentException("Block " + IRegistry.BLOCK.getKey(block) + " does not have property '" + s + "'");
} else {
String s1 = ChatDeserializer.a((JsonElement) entry.getValue(), "value");
Object object = iblockstate.b(s1).orElseThrow(() -> {
return new IllegalArgumentException("Block " + IRegistry.BLOCK.getKey(block) + " property '" + s + "' does not have value '" + s1 + "'");
});
map.put(iblockstate, object);
}
});
}
return new LootItemConditionBlockStateProperty(block, map);
}
}
public static class a implements LootItemCondition.a {
private final Block a;
private final Set<IBlockState<?>> b;
private final Map<IBlockState<?>, Object> c = Maps.newHashMap();
public a(Block block) {
this.a = block;
this.b = Sets.newIdentityHashSet();
this.b.addAll(block.getStates().d());
}
public <T extends Comparable<T>> LootItemConditionBlockStateProperty.a a(IBlockState<T> iblockstate, T t0) {
if (!this.b.contains(iblockstate)) {
throw new IllegalArgumentException("Block " + IRegistry.BLOCK.getKey(this.a) + " does not have property '" + iblockstate + "'");
} else if (!iblockstate.getValues().contains(t0)) {
throw new IllegalArgumentException("Block " + IRegistry.BLOCK.getKey(this.a) + " property '" + iblockstate + "' does not have value '" + t0 + "'");
} else {
this.c.put(iblockstate, t0);
return this;
}
}
@Override
public LootItemCondition build() {
return new LootItemConditionBlockStateProperty(this.a, this.c);
}
}
}
| [
"sky.wang@yahoo.com"
] | sky.wang@yahoo.com |
80db40a1360a84a4588d5ef9f2047c66bee011de | aed7582be39933466b9568838189cc0147c51e0f | /src/main/java/com/company/service/impl/UserServiceImpl.java | f8853129cd097258fe33cdbe7f7d76b6a3e71fda | [] | no_license | xllxing/sso | ef3b42de3dabf4456080f561b71a7a682b6ca933 | 9793757b8161a28c09502ca7bd58be4b06480018 | refs/heads/master | 2022-07-04T12:58:59.035812 | 2019-11-28T11:45:22 | 2019-11-28T11:45:22 | 224,640,743 | 0 | 0 | null | 2022-06-21T02:20:10 | 2019-11-28T11:42:25 | Java | UTF-8 | Java | false | false | 964 | java | package com.company.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.company.bean.User;
import com.company.dao.IUserDao;
import com.company.service.IUserService;
/**
* @author xll
* @category 用户业务实现类
*/
@Service
public class UserServiceImpl implements IUserService {
@Autowired
IUserDao userDao;
@Override
public User login(String username, String userpass) {
return userDao.login(username, userpass);
}
@Override
public List<User> findlist() {
return userDao.findlist();
}
@Override
public boolean updateUser(User user) {
return userDao.updateUser(user)>0;
}
@Override
public boolean deleteUserByName(String username) {
return userDao.deleteUserByName(username)>0;
}
@Override
public boolean addUser(User user) {
return userDao.addUser(user)>0;
}
}
| [
"Administrator@169.254.237.24"
] | Administrator@169.254.237.24 |
2cccb0fa30b7ada4d0f457757b37fcb5f8f481b9 | 8b2bbc086035b71e0e0e1afc2dacdd7926ef0af8 | /src/main/java/de/sybig/uniprotFetcher/Isoforms.java | 94d58af6a31cd2cd0aa68564a750937f3992d47d | [] | no_license | BioinformatikGoettingen/uniprotService | 34842c39870cd4af16df96d3c80982464e43e8c8 | 06d30b0c8033e0a61544d301113c3c12b5f388a1 | refs/heads/master | 2021-01-19T15:21:26.913575 | 2018-09-03T16:12:10 | 2018-09-03T16:12:10 | 100,964,395 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 23,275 | java | package de.sybig.uniprotFetcher;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
*
* @author juergen.doenitz@bioinf.med.uni-goettingen.de
*/
@javax.ws.rs.Path("/")
@Produces(MediaType.APPLICATION_JSON)
public class Isoforms {
private static final Logger logger = LoggerFactory.getLogger(Isoforms.class);
private final UniProtConfiguration configuration;
private static final int SVG_LINE_HEIGHT = 25;
// private Document document;
Isoforms(UniProtConfiguration configuration) {
this.configuration = configuration;
}
@GET
@javax.ws.rs.Path("/isoforms/{uniprotID}")
public List<Isoform> getIsoforms(@PathParam(value = "uniprotID") String uniprotID) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
Document doc = getDocument(uniprotID);
List<Isoform> isoforms = new LinkedList<>();
isoforms.add(getCanonicalSequence(doc));
isoforms.addAll(getModifiedSequences(doc));
logger.trace("Got {} isoforms for {}", isoforms.size(), uniprotID);
return isoforms;
}
@GET
@javax.ws.rs.Path("/isoforms/alignmentPos/{uniprotID}")
public List<AlignedSequence> getAlignmentPos(@PathParam(value = "uniprotID") String uniprotID) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
List<Isoform> isoforms = getIsoforms(uniprotID);
ArrayList<AlignedSequence> sequences = new ArrayList<>();
// Init all sequence objects with the sequence as single feature
for (Isoform isoform : isoforms) {
sequences.add(new AlignedSequence(isoform.getSequence(), isoform));
}
for (Isoform isoform : isoforms) {
if (isoform.getModifications() == null) {
continue;
}
for (Modification m : isoform.getModifications()) {
for (AlignedSequence as : sequences) {
logger.trace("Applying modification '{}' to sequence {}", m, as.getId());
as.applyModification(m, isoform, sequences); // the current modification and the parent isoform
}
// break;
}
}
return sequences;
}
@GET
@javax.ws.rs.Path("/isoforms/svg/{uniprotID}/{sequence}")
@Produces("image/svg+xml")
public String getSVGWithSequence(
@PathParam(value = "uniprotID") String uniprotID,
@PathParam(value = "sequence") String sequence,
@QueryParam("color") String color)
throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
int width = 1000;
List<AlignedSequence> alignment = getAlignmentPos(uniprotID);
StringBuilder svg = new StringBuilder();
svg = addSVGStart(svg, width, alignment.size());
addDBD(svg, sequence, alignment, width, validateColor("#" + color));
svg = addAlignmentsToSVG(svg, alignment, width);
svg = addSVGEnd(svg);
return svg.toString();
}
private String validateColor(String color) {
if (color == null) {
color = "#AAAAAA";
}
Pattern pattern = Pattern.compile("^#[0-9A-Fa-f]{6}$");
Matcher matcher = pattern.matcher(color);
if (!matcher.find()) {
color = "#AAAAAA";
}
return color;
}
@GET
@javax.ws.rs.Path("/isoforms/svg/{uniprotID}")
@Produces("image/svg+xml")
public String getSVG(@PathParam(value = "uniprotID") String uniprotID) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
int width = 1000;
List<AlignedSequence> alignment = getAlignmentPos(uniprotID);
// System.out.println("aa size " + aaSize);
StringBuilder svg = new StringBuilder();
svg = addSVGStart(svg, width, alignment.size());
svg = addAlignmentsToSVG(svg, alignment, width);
svg = addSVGEnd(svg);
return svg.toString();
}
@GET
@javax.ws.rs.Path("/best/{uniprotIDs}")
@Produces(MediaType.TEXT_PLAIN)
public String selectBest(@PathParam(value = "uniprotIDs") String uniprotIDs) throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
List<UniProtQuality> items = new LinkedList<>();
XPathFactory xPathfactory = XPathFactory.newInstance();
for (String id : uniprotIDs.split(",")) {
UniProtQuality prot = new UniProtQuality();
prot.setId(id);
Document doc = getDocument(id);
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/RDF/Description/reviewed");
Node reviewedNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
if (reviewedNode == null || reviewedNode.getTextContent().equals("false")) {
prot.setReviewed(false);
} else {
prot.setReviewed(true);
}
xpath = xPathfactory.newXPath();
expr = xpath.compile("/RDF/Description/obsolete");
Node obsoleteNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
if (obsoleteNode == null || reviewedNode.getTextContent().equals("false")) {
prot.setObsolete(false);
} else {
prot.setObsolete(true);
}
xpath = xPathfactory.newXPath();
expr = xpath.compile("/RDF/Description/existence");
Node evidenceNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
if (evidenceNode != null) {
// System.out.println("node " + evidenceNode);
// System.out.println("atts " + evidenceNode.getAttributes());
// System.out.println("res " + evidenceNode.getAttributes().getNamedItem("rdf:resource"));
prot.setLevel(evidenceNode.getAttributes().getNamedItem("rdf:resource").getNodeValue());
}
items.add(prot);
}
items.sort(new UniprotQualityComparator());
System.out.println("sorted list " + items);
return items.get(0).getId();
}
private StringBuilder addSVGStart(StringBuilder svg, int width, int lines) {
svg.append(String.format("<svg width=\"%d\" height=\"%d\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" onload=\"init(evt)\">\n", width, (lines * SVG_LINE_HEIGHT +30) ));
svg.append("<script type=\"text/ecmascript\">\n"
+ "<![CDATA[\n"
+ " function init(evt)\n"
+ " {\n"
+ " if ( window.svgDocument == null )\n"
+ " {\n"
+ " svgDocument = evt.target.ownerDocument;\n"
+ " }\n"
+ " tooltip = svgDocument.getElementById('tooltip');\n"
+ " }\n"
+ "function ShowTooltip(evt, mouseovertext)\n"
+ "{\n"
+ " tooltip.setAttributeNS(null,\"x\",11);\n"
+ " tooltip.setAttributeNS(null,\"y\",evt.clientY+27);\n"
+ " tooltip.firstChild.data = mouseovertext;\n"
+ " tooltip.setAttributeNS(null,\"visibility\",\"visible\");\n"
+ "}\n"
+ "\n"
+ "function HideTooltip()\n"
+ "{\n"
+ " tooltip.setAttributeNS(null,\"visibility\",\"hidden\");\n"
+ "}"
+ "]]></script>");
return svg;
}
private StringBuilder addAlignmentsToSVG(StringBuilder svg, List<AlignedSequence> alignment, int width) {
int ypos = 10;
double aaSize = ((double) width) / (getMaxSequenceLength(alignment));
for (AlignedSequence sequence : alignment) {
svg.append(String.format("<g>\n"
+ " <rect x = \"5\" y = \"%d\" width = \"%d\" height = \"20\" stroke = \"none\" fill = \"#FFCC62\"/>\n",
ypos, (int) (aaSize * sequence.getSequence().length())
));
for (SequenceFeature feature : sequence.getFeatures()) {
String color = null;
if ("gap".equals(feature.getType())) {
color = "EEEEEE";
} else if ("mismatch".equals(feature.getType())) {
color = "FFAAAA";
} else if ("gapD".equals(feature.getType())) {
color = "EEEEEE";
} else if ("gapI".equals(feature.getType())) {
color = "EEEEEE";
}
if (color == null) {
continue;
}
String tooltip = String.format("%s: %d - %d (%d)", feature.getType(), feature.getStart()-feature.getMovedStart(),
feature.getEnd() - feature.getMovedStart(), feature.getLength());
svg.append(String.format(" <rect x = \"%d\" y = \"%d\" width = \"%d\" height = \"18\" "
+ "stroke = \"none\" fill = \"#%s\" "
+ "onmousemove=\"ShowTooltip(evt, '%s')\"\n"
+ " onmouseout=\"HideTooltip()\" /> \n",
(int) (feature.getStart() * aaSize + 5),
ypos + 1, (int) (aaSize * (feature.getLength())), color,
tooltip));
}
svg.append(String.format(" <text x=\"%d\" y=\"%d\" font-family=\"Verdana\" font-size=\"10\" fill=\"blue\">%s</text>\n</g>\n\n",
width - 60, ypos + 15, sequence.getId()));
ypos += SVG_LINE_HEIGHT;
}
return svg;
}
private StringBuilder addDBD(StringBuilder svg, String sequence, List<AlignedSequence> alignment, int width, String color) {
String canonicalSequence = alignment.get(0).getSequence();
String origSequence = canonicalSequence.replace("-", "");
double aaSize = ((double) width) / (getMaxSequenceLength(alignment));
int start = origSequence.indexOf(sequence);
if (start < 0) {
logger.error("Could not find DBD for {}", alignment.get(0).getId());
return svg;
}
for (int pos = 0; pos < start; pos++) {
if ("-".equals(canonicalSequence.charAt(pos))) {
start++;
}
}
int end = start + sequence.length();
//System.out.println("moved start " + start + " " + end);
for (int pos = start; pos < end; pos++) {
if ("-".equals(canonicalSequence.charAt(pos))) {
end++;
}
}
int height = 25 * alignment.size() + 20;
svg.append(String.format(" <rect x = \"%d\" y = \"%d\" width = \"%d\" height = \"%d\" stroke = \"none\" fill = \"%s\"/>\n",
(int) (aaSize * start), 0, (int) (aaSize * end - start), height, color));
logger.debug(" found at " + start + " --- " + end);
return svg;
}
private StringBuilder addSVGEnd(StringBuilder svg) {
svg.append("<text class=\"tooltip\" id=\"tooltip\"\n"
+ " x=\"0\" y=\"0\" visibility=\"hidden\">Tooltip</text>\n");
svg.append("</svg>");
return svg;
}
private int getMaxSequenceLength(List<AlignedSequence> alignment) {
int maxLength = 0;
for (AlignedSequence sequence : alignment) {
maxLength = sequence.getSequence().length() > maxLength ? sequence.getSequence().length() : maxLength;
}
return maxLength;
}
private Document getDocument(String uniprotID) throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
Path rdfFile = getRDFfile(uniprotID);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(rdfFile.toFile());
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/RDF/Description/replacedBy");
Node replaceNode = (Node) expr.evaluate(document, XPathConstants.NODE);
if (replaceNode != null) {
String newID = replaceNode.getAttributes().getNamedItem("rdf:resource").getNodeValue();
newID = newID.substring(newID.lastIndexOf("/") + 1);
System.out.println(uniprotID + " replaced by " + newID);
return getDocument(newID);
}
return document;
}
private Isoform getCanonicalSequence(Document doc) throws XPathExpressionException, IOException, SAXException, ParserConfigurationException {
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/RDF/Description/type[@resource='http://purl.uniprot.org/core/Simple_Sequence']/parent::Description");
NodeList result = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
Isoform isoform = new Isoform();
if (result.getLength() > 0) {
Node descpriptionNode = result.item(0);
isoform = processSequenceNode(descpriptionNode, doc);
}
return isoform;
}
private List<Isoform> getModifiedSequences(Document doc) throws XPathExpressionException, IOException, SAXException, ParserConfigurationException {
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/RDF/Description/type[@resource='http://purl.uniprot.org/core/Modified_Sequence']/parent::Description");
NodeList modifiedSequences = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
List<Isoform> isoforms = new LinkedList<>();
for (int i = 0; i < modifiedSequences.getLength(); i++) {
Node isoformNode = modifiedSequences.item(i);
isoforms.add(processSequenceNode(isoformNode, doc));
}
return isoforms;
}
private Isoform processSequenceNode(Node descpriptionNode, Document doc) throws XPathExpressionException {
Isoform isoform = new Isoform();
String url = descpriptionNode.getAttributes().getNamedItem("rdf:about").getTextContent();
isoform.setUrl(url);
isoform.setId(url.substring(url.lastIndexOf("/") + 1));
NodeList children = descpriptionNode.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
String name = child.getNodeName();
if ("rdf:value".equals(name)) {
isoform.setSequence(child.getTextContent());
} else if ("basedOn".equals(name)){
isoform.setBasedOn(child.getAttributes().getNamedItem("rdf:resource").getNodeValue().replace("http://purl.uniprot.org/isoforms/", ""));
}
else if ("name".equals(name)) {
isoform.addName(child.getTextContent());
} else if ("modification".equals(name)) {
isoform.addModification(getModificationNode(child.getAttributes().getNamedItem("rdf:resource").getNodeValue(), doc));
}
}
return isoform;
}
private Modification getModificationNode(String uri, Document doc) throws XPathExpressionException {
Modification modification = new Modification();
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/RDF/Description[@about='" + uri + "']");
Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
NodeList children = node.getChildNodes();
modification.setId(uri.substring(uri.lastIndexOf("/") + 1));
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if ("substitution".equals(child.getNodeName())) {
modification.setSubstitution(child.getTextContent());
} else if ("range".equals(child.getNodeName())) {
modification = getRange(modification, child.getAttributes().getNamedItem("rdf:resource").getNodeValue(), doc);
}
}
return modification;
}
private Modification getRange(Modification modification, String uri, Document doc) throws XPathExpressionException {
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/RDF/Description[@about='" + uri + "']");
Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
if (node == null) {
System.out.println("no range found for " + uri);
}
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if ("faldo:begin".equals(child.getNodeName())) {
modification.setBegin(getPos(child.getAttributes().getNamedItem("rdf:resource").getNodeValue(), doc));
}
if ("faldo:end".equals(child.getNodeName())) {
modification.setEnd(getPos(child.getAttributes().getNamedItem("rdf:resource").getNodeValue(), doc));
}
}
return modification;
}
private int getPos(String uri, Document doc) throws XPathExpressionException {
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/RDF/Description[@about='" + uri + "']/position");
Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
if (node == null) {
return 0;
}
return Integer.parseInt(node.getTextContent());
}
private Path getRDFfile(String id) throws MalformedURLException, IOException {
Path localFile = getLocalFile(id);
if (!Files.isReadable(localFile)) {
logger.debug("getting from uniprot {}", id);
FileUtils.copyURLToFile(new URL("http://www.uniprot.org/uniprot/" + id + ".rdf"),
getLocalFile(id).toFile(), 10 * 1000, 10 * 1000); // 10 seconds connectionTimeout and 10 seconds readTimeout
return localFile;
}
FileTime validTime = FileTime.fromMillis(System.currentTimeMillis() - (1000 * 60 * 60 * 24 * new Long(90)));
if (Files.readAttributes(localFile, BasicFileAttributes.class).lastModifiedTime().compareTo(validTime) < 1) {
logger.info("File {} is to old, will be refetched from uniprot.", localFile);
try {
FileUtils.copyURLToFile(new URL("https://www.uniprot.org/uniprot/" + id + ".rdf"),
getLocalFile(id).toFile(), 1500, 10 * 1000); // 1.5 seconds connectionTimeout and 10 seconds readTimeout
} catch (java.net.SocketTimeoutException ex) {
logger.warn("Could not re-fetch {} from Uniprot in max 1.5 secs, using old file.");
}
return localFile;
}
return localFile;
}
private Path getLocalFile(String id) {
Path file = Paths.get(configuration.getDataDir(), id + ".rdf");
return file;
}
class UniProtQuality {
private String id;
private boolean obsolete = false;
private boolean reviewed = false;
private int level = 0;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean isObsolete() {
return obsolete;
}
public void setObsolete(boolean obsolete) {
this.obsolete = obsolete;
}
public boolean isReviewed() {
return reviewed;
}
public void setReviewed(boolean reviewed) {
this.reviewed = reviewed;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public void setLevel(String level) {
if ("http://purl.uniprot.org/core/Evidence_at_Protein_Level_Existence".equals(level)) {
this.level = 1;
} else if ("http://purl.uniprot.org/core/Evidence_at_Transcript_Level_Existence".equals(level)) {
this.level = 2;
} else if ("http://purl.uniprot.org/core/Inferred_from_Homology_Existence".equals(level)) {
this.level = 3;
} else if ("http://purl.uniprot.org/core/Predicted_Existence".equals(level)) {
this.level = 4;
} else {
System.out.println("level not found " + level);
}
}
public String toString() {
return String.format("%s {%b %d}", id, reviewed, level);
}
//1. Experimental evidence at protein level <existence rdf:resource="http://purl.uniprot.org/core/Evidence_at_Protein_Level_Existence"/>
//2. Experimental evidence at transcript level <existence rdf:resource="http://purl.uniprot.org/core/Evidence_at_Transcript_Level_Existence"/>
//3. Protein inferred from homology http://purl.uniprot.org/core/Inferred_from_Homology_Existence
//4. Protein predicted http://purl.uniprot.org/core/Predicted_Existence
//5. Protein uncertain
}
class UniprotQualityComparator implements Comparator<UniProtQuality> {
@Override
public int compare(UniProtQuality o1, UniProtQuality o2) {
if (o1.isObsolete() && !o2.isObsolete()) {
return 1;
}
if (!o1.isObsolete() && o2.isObsolete()) {
return -1;
}
if (o1.isReviewed() && !o2.isReviewed()) {
return -1;
}
if (!o1.isReviewed() && o2.isReviewed()) {
return 1;
}
return (((Integer) o1.getLevel()).compareTo((Integer) o2.getLevel()));
}
}
}
| [
"juergen.doenitz@bioinf.med.uni-goettingen.de"
] | juergen.doenitz@bioinf.med.uni-goettingen.de |
a0ba306d92b888217e60249414feec112d060043 | 696426a0680beea292e2f1f59c4a3115d95cdd73 | /test2/src/main/java/com/bw/test2/view/AView.java | 351636e2e50d12b83f9c2820b8c85f04531324ce | [] | no_license | Zzq1335267141/zzq0507monthtest | 9ebad3c0ea456676c5eeb432b47fcd31e671c0bf | 438f10a004d2802f520311534fcd89d93da5cb0f | refs/heads/master | 2020-05-22T07:05:28.251344 | 2019-05-12T13:22:20 | 2019-05-12T13:22:20 | 186,257,809 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 181 | java | package com.bw.test2.view;
/**
* Created by Android Studio.
* User: 张泽强
* Date: 2019/5/12
* Time: 14:03
*/
public interface AView {
void getResponse(String data);
}
| [
"1497405573@qq.com"
] | 1497405573@qq.com |
6abe529441bc54c7c5b428b8d53d15499e060a57 | 4461445ea6b5eda91b5896df1d6b5ecbf200372c | /src/main/java/com/expertzlab/spring/core/postprocess/InitHelloWorld.java | 994cd647a81b0670dc426fcff0b59704f4f768aa | [] | no_license | expertzlab/spring-core-training | b0f27db10fc499a3fc37ea20d494e445d9523c5d | 0928ce5f5864154f48e8f7ef844988b226a201e5 | refs/heads/master | 2020-12-31T07:42:59.980875 | 2018-03-21T18:08:45 | 2018-03-21T18:08:45 | 86,576,911 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 923 | java | package com.expertzlab.spring.core.postprocess;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
* Created by gireeshbabu on 04/04/17.
*/
public class InitHelloWorld implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean,
String beanName) throws BeansException {
System.out.println("BeforeInitialization : " + beanName);
return bean; // you can return any other object as well
}
public Object postProcessAfterInitialization(Object bean,
String beanName) throws BeansException {
System.out.println("AfterInitialization : " + beanName);
if("helloBean".equals(beanName)) {
return new DanyHello();
} else {
return bean;
}
}
}
| [
"gireesh.babu@nibodha.com"
] | gireesh.babu@nibodha.com |
a52bde3803ed5d9667ff84f13a5893673dab6702 | b067adfab9bf61e9e0db1198c6667276d5ec7c9a | /src/main/java/test_heroku/repository/CategoryRepository.java | dd5c4e1d988f5bc064b4d6e73f3d2dfd33f422d0 | [] | no_license | nguyenha2651988/nguyenha2651988 | 85e48b72c9d1f6f46f39a2ab65dc92132e7a5e96 | c092360e4f496f0bb16cb21ced327f77c7e12e9b | refs/heads/master | 2021-04-04T09:09:17.327810 | 2020-03-19T09:03:07 | 2020-03-19T09:03:07 | 248,443,818 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 271 | java | package test_heroku.repository;
import test_heroku.model.Category;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CategoryRepository extends JpaRepository<Category, Long> {
}
| [
"nguyenha2651988@gmail.com"
] | nguyenha2651988@gmail.com |
dcc68ed7ff9f248e5e6d9538935951c3e4ee4673 | 10186b7d128e5e61f6baf491e0947db76b0dadbc | /org/apache/batik/css/engine/Messages.java | c61e1dc9c39f4df179526ed8838d5a7c196f7e0f | [
"SMLNJ",
"Apache-1.1",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | MewX/contendo-viewer-v1.6.3 | 7aa1021e8290378315a480ede6640fd1ef5fdfd7 | 69fba3cea4f9a43e48f43148774cfa61b388e7de | refs/heads/main | 2022-07-30T04:51:40.637912 | 2021-03-28T05:06:26 | 2021-03-28T05:06:26 | 351,630,911 | 2 | 0 | Apache-2.0 | 2021-10-12T22:24:53 | 2021-03-26T01:53:24 | Java | UTF-8 | Java | false | false | 1,662 | java | /* */ package org.apache.batik.css.engine;
/* */
/* */ import java.util.Locale;
/* */ import java.util.MissingResourceException;
/* */ import org.apache.batik.i18n.LocalizableSupport;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class Messages
/* */ {
/* */ protected static final String RESOURCES = "org.apache.batik.css.engine.resources.Messages";
/* 49 */ protected static LocalizableSupport localizableSupport = new LocalizableSupport("org.apache.batik.css.engine.resources.Messages", Messages.class.getClassLoader());
/* */
/* */
/* */
/* */
/* */
/* */ public static void setLocale(Locale l) {
/* 56 */ localizableSupport.setLocale(l);
/* */ }
/* */
/* */
/* */
/* */
/* */ public static Locale getLocale() {
/* 63 */ return localizableSupport.getLocale();
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static String formatMessage(String key, Object[] args) throws MissingResourceException {
/* 72 */ return localizableSupport.formatMessage(key, args);
/* */ }
/* */ }
/* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/batik/css/engine/Messages.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ | [
"xiayuanzhong+gpg2020@gmail.com"
] | xiayuanzhong+gpg2020@gmail.com |
ffada42a66517df1606f142a4a9c596b685295b3 | 28e356d56e3682cdaa53a14f2ef22a2dbb9799c0 | /2.3.04-Exercise-AddDebugPlatforms/core/src/com/udacity/gamedev/gigagal/entities/Platform.java | 3b8559968fec2e5b5391ce7a134adb8642fac8c6 | [
"MIT"
] | permissive | udacity/ud406 | 31fb5e8ef02f6f78e500ad8998bae38bf4296494 | 191d46352271cc74f4232a3f75db3563c200b1c9 | refs/heads/master | 2023-03-28T21:01:07.283156 | 2021-10-21T13:33:06 | 2021-10-21T13:33:06 | 45,005,805 | 60 | 134 | MIT | 2023-05-08T19:41:40 | 2015-10-27T00:05:43 | Java | UTF-8 | Java | false | false | 679 | java | package com.udacity.gamedev.gigagal.entities;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.udacity.gamedev.gigagal.util.Assets;
public class Platform {
float top;
float bottom;
float left;
float right;
public Platform(float left, float top, float width, float height) {
this.top = top;
this.bottom = top - height;
this.left = left;
this.right = left + width;
}
public void render(SpriteBatch batch) {
float width = right - left;
float height = top - bottom;
Assets.instance.platformAssets.platformNinePatch.draw(batch, left - 1, bottom - 1, width + 2, height + 2);
}
}
| [
"jeremy@udacity.com"
] | jeremy@udacity.com |
b1c98fc0132c776e0c138e1099d08449e18175d6 | 6fa701cdaa0d83caa0d3cbffe39b40e54bf3d386 | /google/apps/drive/activity/v2/google-apps-drive-activity-v2-java/proto-google-apps-drive-activity-v2-java/src/main/java/com/google/apps/drive/activity/v2/QueryDriveActivityResponse.java | f91269e45ca6d90c0939597b833627d5af47af5d | [
"Apache-2.0"
] | permissive | oltoco/googleapis-gen | bf40cfad61b4217aca07068bd4922a86e3bbd2d5 | 00ca50bdde80906d6f62314ef4f7630b8cdb6e15 | refs/heads/master | 2023-07-17T22:11:47.848185 | 2021-08-29T20:39:47 | 2021-08-29T20:39:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | true | 35,913 | java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/apps/drive/activity/v2/query_drive_activity_response.proto
package com.google.apps.drive.activity.v2;
/**
* <pre>
* Response message for querying Drive activity.
* </pre>
*
* Protobuf type {@code google.apps.drive.activity.v2.QueryDriveActivityResponse}
*/
public final class QueryDriveActivityResponse extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.apps.drive.activity.v2.QueryDriveActivityResponse)
QueryDriveActivityResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use QueryDriveActivityResponse.newBuilder() to construct.
private QueryDriveActivityResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private QueryDriveActivityResponse() {
activities_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new QueryDriveActivityResponse();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private QueryDriveActivityResponse(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
activities_ = new java.util.ArrayList<com.google.apps.drive.activity.v2.DriveActivity>();
mutable_bitField0_ |= 0x00000001;
}
activities_.add(
input.readMessage(com.google.apps.drive.activity.v2.DriveActivity.parser(), extensionRegistry));
break;
}
case 18: {
java.lang.String s = input.readStringRequireUtf8();
nextPageToken_ = s;
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
activities_ = java.util.Collections.unmodifiableList(activities_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.apps.drive.activity.v2.QueryDriveActivityResponseProto.internal_static_google_apps_drive_activity_v2_QueryDriveActivityResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.apps.drive.activity.v2.QueryDriveActivityResponseProto.internal_static_google_apps_drive_activity_v2_QueryDriveActivityResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.apps.drive.activity.v2.QueryDriveActivityResponse.class, com.google.apps.drive.activity.v2.QueryDriveActivityResponse.Builder.class);
}
public static final int ACTIVITIES_FIELD_NUMBER = 1;
private java.util.List<com.google.apps.drive.activity.v2.DriveActivity> activities_;
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.apps.drive.activity.v2.DriveActivity> getActivitiesList() {
return activities_;
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.apps.drive.activity.v2.DriveActivityOrBuilder>
getActivitiesOrBuilderList() {
return activities_;
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
@java.lang.Override
public int getActivitiesCount() {
return activities_.size();
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
@java.lang.Override
public com.google.apps.drive.activity.v2.DriveActivity getActivities(int index) {
return activities_.get(index);
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
@java.lang.Override
public com.google.apps.drive.activity.v2.DriveActivityOrBuilder getActivitiesOrBuilder(
int index) {
return activities_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
private volatile java.lang.Object nextPageToken_;
/**
* <pre>
* Token to retrieve the next page of results, or
* empty if there are no more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
* <pre>
* Token to retrieve the next page of results, or
* empty if there are no more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
for (int i = 0; i < activities_.size(); i++) {
output.writeMessage(1, activities_.get(i));
}
if (!getNextPageTokenBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < activities_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, activities_.get(i));
}
if (!getNextPageTokenBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.apps.drive.activity.v2.QueryDriveActivityResponse)) {
return super.equals(obj);
}
com.google.apps.drive.activity.v2.QueryDriveActivityResponse other = (com.google.apps.drive.activity.v2.QueryDriveActivityResponse) obj;
if (!getActivitiesList()
.equals(other.getActivitiesList())) return false;
if (!getNextPageToken()
.equals(other.getNextPageToken())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getActivitiesCount() > 0) {
hash = (37 * hash) + ACTIVITIES_FIELD_NUMBER;
hash = (53 * hash) + getActivitiesList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.apps.drive.activity.v2.QueryDriveActivityResponse parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.apps.drive.activity.v2.QueryDriveActivityResponse parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.apps.drive.activity.v2.QueryDriveActivityResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.apps.drive.activity.v2.QueryDriveActivityResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.apps.drive.activity.v2.QueryDriveActivityResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.apps.drive.activity.v2.QueryDriveActivityResponse parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.apps.drive.activity.v2.QueryDriveActivityResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.apps.drive.activity.v2.QueryDriveActivityResponse parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.apps.drive.activity.v2.QueryDriveActivityResponse parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.apps.drive.activity.v2.QueryDriveActivityResponse parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.apps.drive.activity.v2.QueryDriveActivityResponse parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.apps.drive.activity.v2.QueryDriveActivityResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.apps.drive.activity.v2.QueryDriveActivityResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Response message for querying Drive activity.
* </pre>
*
* Protobuf type {@code google.apps.drive.activity.v2.QueryDriveActivityResponse}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.apps.drive.activity.v2.QueryDriveActivityResponse)
com.google.apps.drive.activity.v2.QueryDriveActivityResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.apps.drive.activity.v2.QueryDriveActivityResponseProto.internal_static_google_apps_drive_activity_v2_QueryDriveActivityResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.apps.drive.activity.v2.QueryDriveActivityResponseProto.internal_static_google_apps_drive_activity_v2_QueryDriveActivityResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.apps.drive.activity.v2.QueryDriveActivityResponse.class, com.google.apps.drive.activity.v2.QueryDriveActivityResponse.Builder.class);
}
// Construct using com.google.apps.drive.activity.v2.QueryDriveActivityResponse.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getActivitiesFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (activitiesBuilder_ == null) {
activities_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
activitiesBuilder_.clear();
}
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.apps.drive.activity.v2.QueryDriveActivityResponseProto.internal_static_google_apps_drive_activity_v2_QueryDriveActivityResponse_descriptor;
}
@java.lang.Override
public com.google.apps.drive.activity.v2.QueryDriveActivityResponse getDefaultInstanceForType() {
return com.google.apps.drive.activity.v2.QueryDriveActivityResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.apps.drive.activity.v2.QueryDriveActivityResponse build() {
com.google.apps.drive.activity.v2.QueryDriveActivityResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.apps.drive.activity.v2.QueryDriveActivityResponse buildPartial() {
com.google.apps.drive.activity.v2.QueryDriveActivityResponse result = new com.google.apps.drive.activity.v2.QueryDriveActivityResponse(this);
int from_bitField0_ = bitField0_;
if (activitiesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
activities_ = java.util.Collections.unmodifiableList(activities_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.activities_ = activities_;
} else {
result.activities_ = activitiesBuilder_.build();
}
result.nextPageToken_ = nextPageToken_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.apps.drive.activity.v2.QueryDriveActivityResponse) {
return mergeFrom((com.google.apps.drive.activity.v2.QueryDriveActivityResponse)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.apps.drive.activity.v2.QueryDriveActivityResponse other) {
if (other == com.google.apps.drive.activity.v2.QueryDriveActivityResponse.getDefaultInstance()) return this;
if (activitiesBuilder_ == null) {
if (!other.activities_.isEmpty()) {
if (activities_.isEmpty()) {
activities_ = other.activities_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureActivitiesIsMutable();
activities_.addAll(other.activities_);
}
onChanged();
}
} else {
if (!other.activities_.isEmpty()) {
if (activitiesBuilder_.isEmpty()) {
activitiesBuilder_.dispose();
activitiesBuilder_ = null;
activities_ = other.activities_;
bitField0_ = (bitField0_ & ~0x00000001);
activitiesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ?
getActivitiesFieldBuilder() : null;
} else {
activitiesBuilder_.addAllMessages(other.activities_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.apps.drive.activity.v2.QueryDriveActivityResponse parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.apps.drive.activity.v2.QueryDriveActivityResponse) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.util.List<com.google.apps.drive.activity.v2.DriveActivity> activities_ =
java.util.Collections.emptyList();
private void ensureActivitiesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
activities_ = new java.util.ArrayList<com.google.apps.drive.activity.v2.DriveActivity>(activities_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.apps.drive.activity.v2.DriveActivity, com.google.apps.drive.activity.v2.DriveActivity.Builder, com.google.apps.drive.activity.v2.DriveActivityOrBuilder> activitiesBuilder_;
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public java.util.List<com.google.apps.drive.activity.v2.DriveActivity> getActivitiesList() {
if (activitiesBuilder_ == null) {
return java.util.Collections.unmodifiableList(activities_);
} else {
return activitiesBuilder_.getMessageList();
}
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public int getActivitiesCount() {
if (activitiesBuilder_ == null) {
return activities_.size();
} else {
return activitiesBuilder_.getCount();
}
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public com.google.apps.drive.activity.v2.DriveActivity getActivities(int index) {
if (activitiesBuilder_ == null) {
return activities_.get(index);
} else {
return activitiesBuilder_.getMessage(index);
}
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public Builder setActivities(
int index, com.google.apps.drive.activity.v2.DriveActivity value) {
if (activitiesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureActivitiesIsMutable();
activities_.set(index, value);
onChanged();
} else {
activitiesBuilder_.setMessage(index, value);
}
return this;
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public Builder setActivities(
int index, com.google.apps.drive.activity.v2.DriveActivity.Builder builderForValue) {
if (activitiesBuilder_ == null) {
ensureActivitiesIsMutable();
activities_.set(index, builderForValue.build());
onChanged();
} else {
activitiesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public Builder addActivities(com.google.apps.drive.activity.v2.DriveActivity value) {
if (activitiesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureActivitiesIsMutable();
activities_.add(value);
onChanged();
} else {
activitiesBuilder_.addMessage(value);
}
return this;
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public Builder addActivities(
int index, com.google.apps.drive.activity.v2.DriveActivity value) {
if (activitiesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureActivitiesIsMutable();
activities_.add(index, value);
onChanged();
} else {
activitiesBuilder_.addMessage(index, value);
}
return this;
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public Builder addActivities(
com.google.apps.drive.activity.v2.DriveActivity.Builder builderForValue) {
if (activitiesBuilder_ == null) {
ensureActivitiesIsMutable();
activities_.add(builderForValue.build());
onChanged();
} else {
activitiesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public Builder addActivities(
int index, com.google.apps.drive.activity.v2.DriveActivity.Builder builderForValue) {
if (activitiesBuilder_ == null) {
ensureActivitiesIsMutable();
activities_.add(index, builderForValue.build());
onChanged();
} else {
activitiesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public Builder addAllActivities(
java.lang.Iterable<? extends com.google.apps.drive.activity.v2.DriveActivity> values) {
if (activitiesBuilder_ == null) {
ensureActivitiesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, activities_);
onChanged();
} else {
activitiesBuilder_.addAllMessages(values);
}
return this;
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public Builder clearActivities() {
if (activitiesBuilder_ == null) {
activities_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
activitiesBuilder_.clear();
}
return this;
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public Builder removeActivities(int index) {
if (activitiesBuilder_ == null) {
ensureActivitiesIsMutable();
activities_.remove(index);
onChanged();
} else {
activitiesBuilder_.remove(index);
}
return this;
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public com.google.apps.drive.activity.v2.DriveActivity.Builder getActivitiesBuilder(
int index) {
return getActivitiesFieldBuilder().getBuilder(index);
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public com.google.apps.drive.activity.v2.DriveActivityOrBuilder getActivitiesOrBuilder(
int index) {
if (activitiesBuilder_ == null) {
return activities_.get(index); } else {
return activitiesBuilder_.getMessageOrBuilder(index);
}
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public java.util.List<? extends com.google.apps.drive.activity.v2.DriveActivityOrBuilder>
getActivitiesOrBuilderList() {
if (activitiesBuilder_ != null) {
return activitiesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(activities_);
}
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public com.google.apps.drive.activity.v2.DriveActivity.Builder addActivitiesBuilder() {
return getActivitiesFieldBuilder().addBuilder(
com.google.apps.drive.activity.v2.DriveActivity.getDefaultInstance());
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public com.google.apps.drive.activity.v2.DriveActivity.Builder addActivitiesBuilder(
int index) {
return getActivitiesFieldBuilder().addBuilder(
index, com.google.apps.drive.activity.v2.DriveActivity.getDefaultInstance());
}
/**
* <pre>
* List of activity requested.
* </pre>
*
* <code>repeated .google.apps.drive.activity.v2.DriveActivity activities = 1;</code>
*/
public java.util.List<com.google.apps.drive.activity.v2.DriveActivity.Builder>
getActivitiesBuilderList() {
return getActivitiesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.apps.drive.activity.v2.DriveActivity, com.google.apps.drive.activity.v2.DriveActivity.Builder, com.google.apps.drive.activity.v2.DriveActivityOrBuilder>
getActivitiesFieldBuilder() {
if (activitiesBuilder_ == null) {
activitiesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.apps.drive.activity.v2.DriveActivity, com.google.apps.drive.activity.v2.DriveActivity.Builder, com.google.apps.drive.activity.v2.DriveActivityOrBuilder>(
activities_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
activities_ = null;
}
return activitiesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
* <pre>
* Token to retrieve the next page of results, or
* empty if there are no more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Token to retrieve the next page of results, or
* empty if there are no more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString
getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Token to retrieve the next page of results, or
* empty if there are no more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
onChanged();
return this;
}
/**
* <pre>
* Token to retrieve the next page of results, or
* empty if there are no more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
onChanged();
return this;
}
/**
* <pre>
* Token to retrieve the next page of results, or
* empty if there are no more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.apps.drive.activity.v2.QueryDriveActivityResponse)
}
// @@protoc_insertion_point(class_scope:google.apps.drive.activity.v2.QueryDriveActivityResponse)
private static final com.google.apps.drive.activity.v2.QueryDriveActivityResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.apps.drive.activity.v2.QueryDriveActivityResponse();
}
public static com.google.apps.drive.activity.v2.QueryDriveActivityResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<QueryDriveActivityResponse>
PARSER = new com.google.protobuf.AbstractParser<QueryDriveActivityResponse>() {
@java.lang.Override
public QueryDriveActivityResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new QueryDriveActivityResponse(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<QueryDriveActivityResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<QueryDriveActivityResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.apps.drive.activity.v2.QueryDriveActivityResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| [
"bazel-bot-development[bot]@users.noreply.github.com"
] | bazel-bot-development[bot]@users.noreply.github.com |
28c774a0b04046ae5419fd02fdc814e75d6b23b8 | 52db46cda46618dbd3028e5f54df0864c8ff65b8 | /src/main/java/com/intellij/uiDesigner/impl/actions/GroupButtonsAction.java | f32a81c581f381eb06cb55c110eabb1833b1f4df | [
"Apache-2.0"
] | permissive | consulo/consulo-ui-designer | 73279cdcce6b7006200a08aba56493ae1bd46ac9 | 1a7872cd107c90d8775d3c0e433b4a14bbae418f | refs/heads/master | 2023-08-31T00:23:34.185990 | 2023-05-07T11:01:58 | 2023-05-07T11:01:58 | 13,801,786 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,145 | java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.intellij.uiDesigner.impl.actions;
import consulo.ui.ex.awt.Messages;
import com.intellij.uiDesigner.impl.radComponents.RadButtonGroup;
import com.intellij.uiDesigner.impl.radComponents.RadComponent;
import com.intellij.uiDesigner.impl.radComponents.RadRootContainer;
import com.intellij.uiDesigner.impl.designSurface.GuiEditor;
import com.intellij.uiDesigner.impl.propertyInspector.properties.IdentifierValidator;
import com.intellij.uiDesigner.impl.UIDesignerBundle;
import consulo.ui.ex.action.AnActionEvent;
import javax.annotation.Nonnull;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author yole
*/
public class GroupButtonsAction extends AbstractGuiEditorAction {
protected void actionPerformed(final GuiEditor editor, final List<RadComponent> selection, final AnActionEvent e) {
groupButtons(editor, selection);
}
public static void groupButtons(final GuiEditor editor, final List<RadComponent> selectedComponents) {
if (!editor.ensureEditable()) return;
String groupName = Messages.showInputDialog(editor.getProject(),
UIDesignerBundle.message("group.buttons.name.prompt"),
UIDesignerBundle.message("group.buttons.title"),
Messages.getQuestionIcon(),
editor.getRootContainer().suggestGroupName(),
new IdentifierValidator(editor.getProject()));
if (groupName == null) return;
RadRootContainer rootContainer = editor.getRootContainer();
RadButtonGroup group = rootContainer.createGroup(groupName);
for(RadComponent component: selectedComponents) {
rootContainer.setGroupForComponent(component, group);
}
editor.refreshAndSave(true);
}
protected void update(@Nonnull GuiEditor editor, final ArrayList<RadComponent> selection, final AnActionEvent e) {
e.getPresentation().setVisible(allButtons(selection));
e.getPresentation().setEnabled(allButtons(selection) && selection.size() >= 2 &&
!UngroupButtonsAction.isSameGroup(editor, selection));
}
public static boolean allButtons(final ArrayList<RadComponent> selection) {
for(RadComponent component: selection) {
if (!(component.getDelegee() instanceof AbstractButton) ||
component.getDelegee() instanceof JButton) {
return false;
}
}
return true;
}
}
| [
"vistall.valeriy@gmail.com"
] | vistall.valeriy@gmail.com |
c994802b34784ce4fdf4ea8d807fc0d5f0f1ad1d | 44e79b691b58614f3a9c9e51fb6266afeb7ee4b0 | /app/src/main/java/lrmaldo/platzigram/api/PostResponseTypeAdapter.java | 458447ebc39acf7c83eab7dcd8b7a290b3d5655f | [] | no_license | lrmaldo/platzigram-curso | 013a18223694f1cbd6ae59c7eeea5c034b6c0cea | 23785dce6bfc1c1bfce710f8dccbf47091210628 | refs/heads/master | 2021-01-13T14:21:16.808804 | 2017-02-13T00:06:08 | 2017-02-13T00:06:08 | 79,049,410 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,726 | java | package lrmaldo.platzigram.api;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import lrmaldo.platzigram.model.Post;
/**
* Created by Leo on 09/02/2017.
*/
public class PostResponseTypeAdapter extends TypeAdapter {
@Override
public void write(JsonWriter out, Object value) throws IOException {
}
@Override
public PostResponse read(JsonReader in) throws IOException {
final PostResponse response = new PostResponse();
ArrayList<Post> postList = new ArrayList<Post>();
in.beginObject();
while (in.hasNext()){
Post post = null;
try {
post = readPost(in);
} catch (Exception e) {
e.printStackTrace();
}
postList.add(post);
}
in.endObject();
response.setPostArrayList(postList);
return response;
}
public Post readPost(JsonReader reader)throws Exception{
Post post = new Post();
reader.nextName();
reader.beginObject();
while(reader.hasNext()){
String next = reader.nextName();
switch (next){
case "author":
post.setAuthor(reader.nextString());
break;
case "imageUrl":
post.setImageUrl(reader.nextString());
break;
case "timestampCreated":
post.setTimestampCreated(reader.nextDouble());
break;
}
}
reader.endObject();
return post;
}
}
| [
"lrmaldo@gmail.com"
] | lrmaldo@gmail.com |
dd0b0e5f3f5ac2b03a785139ef0baea98f6e6634 | e178adc0b8902862d7f6b2a4937f157629a515ed | /app/src/main/java/com/liuzhuni/lzn/core/comment/ui/CommentDialog.java | cf991c1deff677a512db46f100400a83deb09ca6 | [] | no_license | jieooo7/miao | 84c723d174f0dab1b2589f4a4764b5a34c4cf912 | b56342e0b186ab5b1ba90ae84bd3ea3b55f15d06 | refs/heads/master | 2020-12-24T14:44:51.440589 | 2016-12-09T05:32:33 | 2016-12-09T05:32:33 | 39,495,156 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,137 | java | package com.liuzhuni.lzn.core.comment.ui;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.liuzhuni.lzn.R;
/**
* Created by Andrew Lee on 2015/7/25.
* E-mail:jieooo7@163.com
* Date: 2015-07-25
* Time: 16:54
*/
public class CommentDialog {
public TextView mTitle;
public ImageView mCloseBtn;
public EditText mEdit;
public TextView mSubmit;
private Activity mContext;
private InputMethodManager imm;
private Dialog mDialog;
public CommentDialog(Activity context) {
mContext=context;
View view = LayoutInflater.from(context).inflate(R.layout.comment_dialog, null);
mDialog = new Dialog(context, R.style.MyDialog);
mDialog.setContentView(view);
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
Window dialogWindow = mDialog.getWindow();
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
lp.width = (int) dm.widthPixels;
lp.height=WindowManager.LayoutParams.WRAP_CONTENT;
dialogWindow.setAttributes(lp);
mDialog.setCanceledOnTouchOutside(true);
mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
dismiss();
return true;
}
return false;
}
});
mTitle = (TextView) view.findViewById(R.id.title);
mCloseBtn = (ImageView) view.findViewById(R.id.close_btn);
mEdit = (EditText) view.findViewById(R.id.et_dialog);
mSubmit = (TextView) view.findViewById(R.id.comment_dia_sumit);
mCloseBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
// mEdit.setFocusable(true);
// mEdit.setFocusableInTouchMode(true);
// mEdit.requestFocus();
// InputMethodManager imm = (InputMethodManager)
// context.getSystemService(context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(mEdit, InputMethodManager.RESULT_SHOWN); //显示软键盘
// imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS);//显示软键盘
}
public void show() {
mDialog.show();
showKeyboard(mEdit);//在view渲染完成前requestFocus没有效果,需要延迟一定的时间主动调用键盘弹出
// mContext.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
// imm = (InputMethodManager)
// mContext.getSystemService(mContext.INPUT_METHOD_SERVICE);
// imm.showSoftInput(mEdit, InputMethodManager.RESULT_SHOWN);
// imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_NOT_ALWAYS);//显示软键盘
}
public void dismiss() {
if (mDialog.isShowing()) {
mDialog.dismiss();
// imm.hideSoftInputFromWindow(mContext.getCurrentFocus().getWindowToken(), 0);
}
}
private void showKeyboard(final EditText editText) {
final InputMethodManager manager = (InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
editText.postDelayed(new Runnable() {
@Override
public void run() {
editText.requestFocus();
manager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
}, 300);
}
}
| [
"jieooo7@163.com"
] | jieooo7@163.com |
3d6e1da717614aa51fca72dacdd465bb1fb8e84e | 729fba4cf817b85975167f6bc068d96d7cc93556 | /pro07/src/sec02/ex01/MemberVO.java | 6f14904278830dd5f6e36d9e1254eed2df7b6b94 | [] | no_license | boyunjjang1/JSPStudy | 2e030180cdae03e8f03ea55ef5f6bac0a4a25277 | f59841da0ff6b0d008871378aff4248021da37ee | refs/heads/master | 2020-07-10T00:38:20.642505 | 2019-09-03T03:11:25 | 2019-09-03T03:11:25 | 204,121,920 | 1 | 0 | null | null | null | null | UHC | Java | false | false | 847 | java | package sec02.ex01;
import java.sql.Date;
public class MemberVO {
private String id;
private String pwd;
private String name;
private String email;
private Date joinDate;
public MemberVO() {
System.out.println("MemberVO 생성자 호출");
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getJoinDate() {
return joinDate;
}
public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}
}
| [
"boyunqueen@gmail.com"
] | boyunqueen@gmail.com |
c18040df65e56609c09fe5be50580ac2e4a7920a | d0bfc9d12bf822bb2f93e5e1ec38fffe69353253 | /benefits/benefits-moudle/benefits-bean/src/main/java/com/lx/benefits/bean/bo/order/SellerOrderReverseOverviewBO.java | f4036d82adb140d1659f95632547c0bd0974874b | [] | no_license | wuyizhong/SpringFramework.wangmeng.definition | 11f3f2958079baad8e4f39a7b6953a87c29fde5f | dd346624d89150836f4a26f1be21192602376b13 | refs/heads/master | 2020-07-23T23:15:23.948727 | 2019-09-09T02:51:36 | 2019-09-09T02:51:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 240 | java | package com.lx.benefits.bean.bo.order;
import lombok.Data;
@Data
public class SellerOrderReverseOverviewBO {
/**全部订单*/
private int allCount;
/**退款成功订单(逆向状态2,4)*/
private int overCount;
}
| [
"15070083409@163.com"
] | 15070083409@163.com |
9f46e5539ca573a0bf85652c0d2bfe8a69dde5d0 | 3bbbdbc9c03b78ab5eee1d6e0721c786dcafe026 | /src/main/java/edu/isu/cs/cs3308/ClassificationTree.java | b4218b3d74f35036f1eb4b17ced1fbfb0573d522 | [] | no_license | baumetha/campaign03 | 5a6f65d313bcafe072ad6c880a921ca717645da1 | a1455747f2a3974af766be0ead34f39981e60689 | refs/heads/master | 2020-04-24T00:32:34.191722 | 2019-03-06T04:05:00 | 2019-03-06T04:05:00 | 171,569,636 | 0 | 0 | null | 2019-02-20T00:00:13 | 2019-02-20T00:00:12 | null | UTF-8 | Java | false | false | 1,909 | java | package edu.isu.cs.cs3308;
import edu.isu.cs.cs3308.structures.BinaryTree;
import edu.isu.cs.cs3308.structures.Node;
import edu.isu.cs.cs3308.structures.impl.LinkedBinaryTree;
import edu.isu.cs.cs3308.traversals.BreadthFirstTraversal;
import edu.isu.cs.cs3308.traversals.InOrderTraversal;
import edu.isu.cs.cs3308.traversals.PreOrderTraversal;
import edu.isu.cs.cs3308.traversals.TreeTraversal;
import edu.isu.cs.cs3308.traversals.commands.EnumeratedSaveCommand;
import edu.isu.cs.cs3308.traversals.commands.EnumerationCommand;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;
/**
* A very simple classification tree example using a BinaryTree and console
* input.
*
* @author Isaac Griffith
*/
public class ClassificationTree {
private LinkedBinaryTree<Datum> tree;
/**
* Constructs a new Animal tree class which manages an underlying animal
* tree
*/
public ClassificationTree() {
tree = new LinkedBinaryTree<>();
load();
}
/**
* Main method which controls the identification and tree management loop.
*/
public void identify() {
throw new UnsupportedOperationException("Not yet implemented");
}
/**
* Saves a tree to a file.
*/
public void save() {
throw new UnsupportedOperationException("Not yet implemented");
}
/**
* Loads a tree from the given file, if an exception occurs during file
* operations, a hardcoded basic tree will be loaded instead.
*/
public void load() {
throw new UnsupportedOperationException("Not yet implemented");
}
}
| [
"grifisaa@isu.edu"
] | grifisaa@isu.edu |
9dbd20ccb4df4ae03e4d3a440dda39021b8542df | b480209490e05f56d14df9822041d4dcb42df178 | /src/exercise/abstractclasses/ListItem.java | 7ed40a656b4f334eefd449648edaaa024fc749fd | [] | no_license | AadityaA1/LearningExercise | 19f70b9bfd15f4b436a5b44b138814b3bf73ad80 | cc837bb854e1d0fe98739fefdd57f4e4d26bdd4c | refs/heads/main | 2023-03-17T23:59:26.092007 | 2021-03-10T14:56:30 | 2021-03-10T14:56:30 | 325,303,539 | 0 | 0 | null | 2021-01-01T06:11:29 | 2020-12-29T14:10:06 | Java | UTF-8 | Java | false | false | 601 | java | package exercise.abstractclasses;
public abstract class ListItem {
protected ListItem rightLink;
protected ListItem leftLink;
protected Object value;
public ListItem(Object value) {
this.value = value;
}
protected abstract ListItem next();
protected abstract ListItem setNext(ListItem item);
protected abstract ListItem previous();
protected abstract ListItem setPrevious(ListItem item);
protected abstract int compareTo(ListItem item);
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
| [
"aadi.ar1@gmail.com"
] | aadi.ar1@gmail.com |
18b0cf448e5c0a86ac089afe4e42e66c299aa837 | a5b8cb340079260b783d5a3313d9a19e27450788 | /mail/EditServlet.java | dfc12c8ec52c13de0a8176e634e72726a4d2aa54 | [] | no_license | suganyashanker/Contacts | 0e60c094e2cac8b2c56b120f8e22b1255a942976 | f555b3061a6d22ddfa0b6f8bfc604b563f9e03d1 | refs/heads/master | 2021-01-11T12:27:26.687778 | 2017-02-21T06:29:06 | 2017-02-21T06:29:06 | 76,647,588 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,873 | java | package mail;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.repackaged.com.google.gson.Gson;
public class EditServlet extends HttpServlet {
public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
String name = req.getParameter("name");
System.out.println(name);
Filter propertyFilter =
new FilterPredicate("Name", FilterOperator.EQUAL, name);
System.out.println(propertyFilter);
Query q = new Query("contacts").setFilter(propertyFilter);
System.out.println(q);
PreparedQuery pq = ds.prepare(q);
System.out.println(pq);
Map<String, String> contact_info_map = new TreeMap<String, String>();
for (Entity categorylist : pq.asIterable()) {
String contact_name = (String) categorylist.getProperty("Name");
String job = (String) categorylist.getProperty("Job");
String company = (String) categorylist.getProperty("company");
String email = (String) categorylist.getProperty("EMail-ID");
String worknum = (String) categorylist.getProperty("Work_Number");
String mobnum = (String) categorylist.getProperty("Mobile_Number");
String address = (String) categorylist.getProperty("Address");
contact_info_map.put("name",contact_name );
contact_info_map.put("job",job );
contact_info_map.put("company",company );
contact_info_map.put("email",email );
contact_info_map.put("worknum",worknum );
contact_info_map.put("mobnum",mobnum );
contact_info_map.put("address",address );
}
Gson gson = new Gson();
String json = gson.toJson(contact_info_map);
System.out.printf("JSON: %s", json.toString());
resp.setContentType("application/json");
resp.getWriter().println(json);
}
}
| [
"suganya.shanker@adaptavantcloud.com"
] | suganya.shanker@adaptavantcloud.com |
7eeab95a8b9d20b50149a8779a11912f82f179c8 | f321e57973319afc58a10698d7eaac9160bf645e | /Assignment2/Swimmer.java | 8ad51333fdfacb54a33885b5de0829f6b3532a4f | [] | no_license | Diem-Vu/SJSU-CS151-S2021 | 60a8107176b6b6e57ede6e6be2d653de43b2f02d | 0d0cd9ed190ce71c483a4e3241daa527d4260654 | refs/heads/main | 2023-04-25T15:41:08.201004 | 2021-05-16T06:39:31 | 2021-05-16T06:39:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 204 | java |
/**
*
* @author Diem.Vu
* Some of the classes are swimmers, which adds functionality swim().
*/
public interface Swimmer {
/**
* method to define an action
*/
void Swim();
}
| [
"vuthingocdiem95@gmail.com"
] | vuthingocdiem95@gmail.com |
30c34eade6756f438bbe2d53d6a6ead5d650e093 | 3a826d69928064593b069b8c6fec0279c6ab8a85 | /coffeeclient/src/main/java/com/ggomez1973/coffeeclient/CoffeeOrder.java | 7159ff8e7ad44fb323f2e4bfdcbb9535bd2cf56e | [] | no_license | ggomez1973/all-things-reactive | 42c072bfa8e31f34f743ff4e042ef7001c5ac81d | 84966e3129c81557d9f00b9b9590485d71029a4f | refs/heads/master | 2020-04-29T03:52:46.840078 | 2019-04-01T13:37:12 | 2019-04-01T13:37:12 | 175,826,897 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 617 | java | package com.ggomez1973.coffeeclient;
import java.time.Instant;
class CoffeeOrder {
private String coffeeId;
private Instant dateOrdered;
public String getCoffeeId() {
return coffeeId;
}
public Instant getDateOrdered() {
return dateOrdered;
}
public CoffeeOrder() {
}
private CoffeeOrder(String coffeeId, Instant dateOrdered) {
this.coffeeId = coffeeId;
this.dateOrdered = dateOrdered;
}
public static CoffeeOrder createCoffeeOrder(String coffeeId, Instant dateOrdered) {
return new CoffeeOrder(coffeeId, dateOrdered);
}
}
| [
"g.gomez@globallogic.com"
] | g.gomez@globallogic.com |
8dc3827f8ad41f35c2d598fe5418218302f6b496 | a2dc645307ae1a949d2ba2d6f32ccdf2514f6d39 | /src/main/java/com/kmwllc/brigade/stage/DivideValues.java | 8a32a28924e05a3b0ccd10a10c7fa93d512a5b1b | [
"Apache-2.0"
] | permissive | nraphael/brigade | 74a447f0a4e37749a437fc33aaca5fe6dce3c248 | ecb509cd4538f6aed62b751c4435fdae2c3e0208 | refs/heads/master | 2022-08-06T00:49:59.134427 | 2022-07-27T17:25:12 | 2022-07-27T17:25:12 | 234,803,816 | 0 | 0 | Apache-2.0 | 2020-01-18T22:02:50 | 2020-01-18T22:02:49 | null | UTF-8 | Java | false | false | 3,065 | java | package com.kmwllc.brigade.stage;
import org.slf4j.Logger;
import com.kmwllc.brigade.config.StageConfig;
import com.kmwllc.brigade.document.Document;
import com.kmwllc.brigade.logging.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* This stage will divide the values of two fields a put the resulting quotient in the quotentField.
* Use the "MathValues" stage instead that's based on exp4j.
*
* @author kwatters
*
*/
@Deprecated
public class DivideValues extends AbstractStage {
// TODO: remove this .. maybe we should depricate?
public final static Logger log = LoggerFactory.getLogger(DivideValues.class.getCanonicalName());
private String dividendField = null;
private String divisorField = null;
private String quotentField = null;
@Override
public void startStage(StageConfig config) {
if (config != null) {
dividendField = config.getProperty("dividendField");
divisorField = config.getProperty("divisorField");
quotentField = config.getProperty("quotentField");
}
}
@Override
public List<Document> processDocument(Document doc) {
// divide the double values in 2 fields, store the result in the quotent
// field.
if (!(doc.hasField(dividendField) && doc.hasField(divisorField))) {
return null;
}
if (doc.getField(dividendField).size() != doc.getField(divisorField).size()) {
log.warn("Dividend and Divisor fields of unequal length.");
return null;
}
ArrayList<Double> results = new ArrayList<Double>();
int size = doc.getField(dividendField).size();
for (int i = 0; i < size; i++) {
try {
// log.info("Compute {} divided by {}",
// doc.getField(dividendField).get(i),
// doc.getField(divisorField).get(i));
Double divisor = convertToDouble(doc.getField(divisorField).get(i));
Double dividend = convertToDouble(doc.getField(dividendField).get(i));
if (divisor == 0.0) {
continue;
}
Double quotient = dividend / divisor;
results.add(quotient);
} catch (ClassCastException e) {
log.warn("Division Error DocID: ", doc.getId());
e.printStackTrace();
}
}
if (dividendField.equals(quotentField)) {
doc.removeField(quotentField);
}
for (Double v : results) {
doc.addToField(quotentField, v);
}
return null;
}
private Double convertToDouble(Object obj) throws ClassCastException {
Double doubleVal = null;
if (obj instanceof Integer) {
doubleVal = new Double(((Integer) obj).intValue());
} else if (obj instanceof Double) {
doubleVal = (Double) obj;
} else {
throw new ClassCastException("Cannot convert " + obj.getClass().getName() + " to Double.");
}
return doubleVal;
}
@Override
public void stopStage() {
// no op for this stage
}
@Override
public void flush() {
// no-op for this stage
}
}
| [
"kwatters@kmwllc.com"
] | kwatters@kmwllc.com |
36b72060c86cc7162d199dd54644960297207719 | 0a3a773d5d65c07a3e05ff5ac1e56492c4557645 | /yuki-hiroshi-design-patterns/src/main/java/com/pearl/genius/command/Main.java | 8ca0ec5081a37da7c58a477c6e2aadd8f2e28977 | [] | no_license | hgs-study/enjoy-design-pattern | d0db4d20f9da85af3b92a3f5874f20fe2d4eeaaf | fe93dce07bcfc025c42347b17adc0307d668dc01 | refs/heads/master | 2023-01-24T21:55:49.326016 | 2020-12-08T09:39:19 | 2020-12-08T09:39:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,514 | java | package com.pearl.genius.command;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JFrame implements ActionListener, MouseMotionListener, WindowListener {
private MacroCommand history = new MacroCommand();
private DrawCanvas canvas = new DrawCanvas(400, 400, history);
private JButton clearButton = new JButton("clear");
private JButton undoButton = new JButton("undo");
private JButton redButton = new JButton("red");
private JButton greenButton = new JButton("green");
private JButton blueButton = new JButton("blue");
public static void main(String[] args) {
new Main("Hellow");
}
public Main(String title) {
super(title);
this.addWindowListener(this);
canvas.addMouseMotionListener(this);
clearButton.addActionListener(this);
undoButton.addActionListener(this);
redButton.addActionListener(this);
greenButton.addActionListener(this);
blueButton.addActionListener(this);
Box buttonBox = new Box(BoxLayout.X_AXIS);
buttonBox.add(clearButton);
buttonBox.add(undoButton);
buttonBox.add(redButton);
buttonBox.add(greenButton);
buttonBox.add(blueButton);
Box mainBox = new Box(BoxLayout.Y_AXIS);
mainBox.add(buttonBox);
mainBox.add(canvas);
getContentPane().add(mainBox);
pack();
show();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == clearButton) {
history.clear();
canvas.init();
canvas.repaint();
} else if (e.getSource() == undoButton) {
history.undo();
canvas.repaint();
} else if (e.getSource() == redButton) {
Command cmd = new ColorCommand(canvas, Color.RED);
history.append(cmd);
cmd.execute();
} else if (e.getSource() == greenButton) {
Command cmd = new ColorCommand(canvas, Color.GREEN);
history.append(cmd);
cmd.execute();
} else if (e.getSource() == blueButton) {
Command cmd = new ColorCommand(canvas, Color.BLUE);
history.append(cmd);
cmd.execute();
}
}
public void mouseDragged(MouseEvent e) {
Command cmd = new DrawCommand(canvas, e.getPoint());
history.append(cmd);
cmd.execute();
}
public void mouseMoved(MouseEvent e) {
}
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
public void windowOpened(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
}
| [
"genius.choi@kakaocorp.com"
] | genius.choi@kakaocorp.com |
e679772ebe84705732a548b03a8ee3a70504b658 | 7150ea06214ca3f801501ffa8c90a3e81be11c86 | /pengrui/src/practice/threadPractice.java | 136acfeb87fab2ddca94dcc4c43479f2a29b8b63 | [] | no_license | prprprpr/school | 19a1a7ef7e36bb527d7740ff45ad6322d5aad899 | 436d65ffa2d0d64e6f4ddf34590f82d1feede3fd | refs/heads/master | 2020-04-09T07:40:06.382682 | 2018-12-03T09:48:06 | 2018-12-03T09:48:06 | 160,163,606 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 394 | java | package practice;
interface Source{void method();}
public class threadPractice implements Source{
private Source source;
public void decorate(){
System.out.println("decorate");
}
@Override
public void method() {
// TODO Auto-generated method stub
decorate();
source.method();
}
public static void main(String args[]){
threadPractice a=new threadPractice();
a.method();
}
}
| [
"pengruiprpr@163.com"
] | pengruiprpr@163.com |
fc0f3d41378b2b9a112a7d0c8594c2fae12ef722 | 8768673b08d6222b077a9e00ffaf4da8a5617ac9 | /app/src/main/java/com/tgithubc/kumao/observer/IKuMaoObserver.java | cbab601a41dfe12357b01f092b49bf84f9623135 | [
"Apache-2.0"
] | permissive | tgithubc/KuMao | 29e1540009323306c94f00523b59dd1aacb6b628 | 92590c54b5340f7e01c8cfb9ee62a0805c0016a8 | refs/heads/master | 2020-03-07T22:32:14.191344 | 2018-09-20T03:13:37 | 2018-09-20T03:13:37 | 127,756,610 | 5 | 0 | null | null | null | null | UTF-8 | Java | false | false | 637 | java | package com.tgithubc.kumao.observer;
import com.tgithubc.kumao.message.IObserver;
/**
* 聚合观察者
* Created by tc :)
*/
public interface IKuMaoObserver extends IObserver {
interface IFragmentSwipeBackObserver extends IKuMaoObserver {
void onMainViewPagerVisible(boolean isVisible);
}
interface IChangeStatusBarObserver extends IKuMaoObserver {
void onChangeStatusBar(boolean isDark);
}
interface IPlayObserver extends IKuMaoObserver {
void onPlayRealStart();
void onPause();
void onContinuePlay();
void onWaveFormDataCapture(byte[] waveform);
}
}
| [
"tc_6008@163.com"
] | tc_6008@163.com |
4e5cbdc5f82ff35b72cd678e81ec71427aa42c50 | 975d92fa474ad1a5ef43049f6ba9b348571957e7 | /app/src/main/java/com/example/mirmhrakib/mydemoapplication/CozListReportActivity.java | 5acb475b65fc532af72b2bcc4b41b8b7864778b5 | [] | no_license | MehnazNipa/myDemoVumiApp | f85b42528faa3f2a957c7865322958c54b91f8cb | ff4250fe888e082370dc923f4d0968eb3c8bab5c | refs/heads/master | 2021-01-18T22:21:55.312758 | 2016-10-31T18:45:36 | 2016-10-31T18:45:36 | 72,464,560 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,695 | java | package com.example.mirmhrakib.mydemoapplication;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import appadapter.CozListReportItem;
import appdatabase.CozListReportDataSource;
import appmodel.CozListReportModel;
public class CozListReportActivity extends AppCompatActivity {
List<CozListReportModel> cozReportArrayList;
ListView mCozList = null;
CozListReportItem mCozListItem = null;
CozListReportDataSource mCozListReportDataSource;
CozListReportModel mCozListReportModel;
static EditText fromDateET;
static EditText toDateET;
String fromDate = "";
String toDate = "";
Calendar myCalendar = Calendar.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coz_list_report);
fromDateET = (EditText) findViewById(R.id.fromDate);
toDateET = (EditText) findViewById(R.id.toDate);
cozReportArrayList = new ArrayList<CozListReportModel>();
mCozList = (ListView) findViewById(R.id.cozList);
mCozListReportDataSource = new CozListReportDataSource(this);
mCozListReportModel = new CozListReportModel();
String [] caseNo = new String[]{"৪-১৮/২০১৫ রিভিশন, চট্টগ্রাম","৩-১১৬/২০১৫-নামজারী-আপীল-নারায়ণগঞ্জ","৩-১৩৯/২০১৫-নামজারী-আপীল-ঢাকা","৪-৪৬/২০১৬-নামজারী-আপীল-বাগেরহাট","৩-২০/২০১৬-নামজারী-আপীল-নারায়ণগঞ্জ","৩-৭৬/১৫ (নাম) আপীল, নারায়ণগঞ্জ","৩-১১২/২০১৫-নামজারী-আপীল-গাজীপুর","৩-৩৮/২০১৬-রেকর্ড সংশোধন-বিবিধ-ঢাকা","৩-১৪৪/২০১৫-নামজারী-আপীল-নারায়ণগঞ্জ","৪-০৯/২০১৪ আপীল,কক্সাবাজার"};
String [] dateOfFiling = new String[]{"18/02/2015","01/07/2015","26/08/2015","12/04/2016","19/04/2016","09/04/2015","25/06/2015","25/10/2016","31/10/2016","31/10/2016"};
String [] nextSetDate = new String[]{"25/10/2016","25/10/2016","25/10/2016","25/10/2016","25/10/2016","25/10/2016","25/10/2016","25/12/2016","08/01/2017","03/03/2017"};
String [] currentCaseStatus = new String[]{"নথির জন্য","নথির জন্য","নথির জন্য","নথির জন্য","নথির জন্য","শুনানীর জন্য","শুনানীর জন্য","শুনানীর জন্য","শুনানীর জন্য","শুনানীর জন্য"};
String [] caseType = new String[]{"নামজারী","নামজারী","নামজারী","নামজারী","নামজারী","নামজারী","নামজারী","রেকর্ড সংশোধন","নামজারী","নামজারী"};
String [] caseClass = new String[]{"রিভিশন","আপীল","আপীল","আপীল","আপীল","আপীল","আপীল","বিবিধ","আপীল","আপীল"};
String [] courtName = new String[]{"সদস্য-১ মহোদয়","চেয়ারম্যান","চেয়ারম্যান","সদস্য-১ মহোদয়","চেয়ারম্যান","চেয়ারম্যান","চেয়ারম্যান","চেয়ারম্যান","চেয়ারম্যান","সদস্য-১ মহোদয়"};
String [] branchNo = new String[]{"৪","৩","৩","৪","৩","৩","৩","৩","৩","৪"};
String [] division = new String[]{"চট্টগ্রাম","ঢাকা","খুলনা","ঢাকা","ঢাকা","ঢাকা","ঢাকা","ঢাকা","ঢাকা","চট্টগ্রাম"};
if (mCozListReportDataSource.isEmpty() == true) {
for (int i = 0; i < caseNo.length; i++) {
String caseNoString = caseNo[i];
String dateOfFilingString = dateOfFiling[i];
String nextSetDateString = nextSetDate[i];
String currentCaseStatusString = currentCaseStatus[i];
String caseTypeString = caseType[i];
String caseClassString = caseClass[i];
String courtNameString = courtName[i];
String branchNoString = branchNo[i];
String divisionString = division[i];
mCozListReportModel = new CozListReportModel(caseNoString, dateOfFilingString, nextSetDateString, currentCaseStatusString, caseTypeString, caseClassString, courtNameString, branchNoString, divisionString);
if (mCozListReportDataSource.insert(mCozListReportModel)) {
Toast.makeText(getApplicationContext(), "Data Saved Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Data Not Saved.", Toast.LENGTH_SHORT).show();
}
}
}
cozReportArrayList = mCozListReportDataSource.getCurrentDateCozList();
//cozReportArrayList = mCozListReportDataSource.getCozList();
mCozListItem = new CozListReportItem(cozReportArrayList,this);
mCozList.setAdapter(mCozListItem);
fromDateET.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment1();
newFragment.show(getFragmentManager(), "datePicker");
}
});
toDateET.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment2();
newFragment.show(getFragmentManager(), "datePicker");
}
});
}
public void searchCozlist(View v){
cozReportArrayList.clear();
cozReportArrayList = new ArrayList<CozListReportModel>();
Toast.makeText(this, "clicked", Toast.LENGTH_LONG).show();
fromDate = fromDateET.getText().toString();
toDate = toDateET.getText().toString();
cozReportArrayList = mCozListReportDataSource.getDateRangeCozList(fromDate,toDate);
//cozReportArrayList = mCozListReportDataSource.getCozList();
mCozListItem = new CozListReportItem(cozReportArrayList,this);
mCozList.setAdapter(mCozListItem);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_coz_list_report, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class DatePickerFragment1 extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
String newDay ="";
String newMonth ="";
String newDate ="";
if(day<10){
newDay = '0'+String.valueOf(day);
}else {
newDay = String.valueOf(day);
}
if(month<9){
newMonth = '0'+ String.valueOf(month + 1);
}else {
newMonth = String.valueOf(month + 1);
}
newDate = newDay+ " / " + newMonth+ " / " + String.valueOf(year);
fromDateET.setText(newDate);
}
}
public static class DatePickerFragment2 extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
String newDay ="";
String newMonth ="";
String newDate ="";
if(day<10){
newDay = '0'+String.valueOf(day);
}else {
newDay = String.valueOf(day);
}
if(month<9){
newMonth = '0'+ String.valueOf(month + 1);
}else {
newMonth = String.valueOf(month + 1);
}
newDate = newDay+ " / " + newMonth+ " / " + String.valueOf(year);
toDateET.setText(newDate);
}
}
}
| [
"mehnaz_nipa@yahoo.com"
] | mehnaz_nipa@yahoo.com |
b432541e04666bef7d3147048005aa55ba5a7fc4 | ba7cab056c31fded038d49ccee0c1c9c54a6f3d4 | /dist/gameserver/data/scripts/quests/_033_MakeAPairOfDressShoes.java | 167e55f9ceecb4953a692f7e147556e74f05aea5 | [] | no_license | MaicoSautner/l2script-teste | 48052f6408be26038e692f48b38f1582a3eded06 | 196979a27575fd3ff48c28d416f2d820ba02059e | refs/heads/master | 2022-07-26T09:08:00.639245 | 2020-05-22T02:12:02 | 2020-05-22T02:16:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,731 | java | package quests;
import l2s.gameserver.model.instances.NpcInstance;
import l2s.gameserver.model.quest.Quest;
import l2s.gameserver.model.quest.QuestState;
public class _033_MakeAPairOfDressShoes extends Quest
{
int LEATHER = 36516;
int GEM_FOR_ACC = 36556;
int DRESS_SHOES_BOX = 7113;
public _033_MakeAPairOfDressShoes()
{
super(PARTY_NONE, REPEATABLE);
addStartNpc(30838);
addTalkId(30838);
addTalkId(30838);
addTalkId(30164);
addTalkId(31520);
addLevelCheck("30838-00.htm", 60);
}
@Override
public String onEvent(String event, QuestState st, NpcInstance npc)
{
String htmltext = event;
if(event.equals("30838-1.htm"))
{
st.setCond(1);
}
else if(event.equals("31520-1.htm"))
st.setCond(2);
else if(event.equals("30838-3.htm"))
st.setCond(3);
else if(event.equals("30838-5.htm"))
{
if(st.getQuestItemsCount(LEATHER) >= 360 && st.getQuestItemsCount(GEM_FOR_ACC) >= 90 && st.getQuestItemsCount(ADENA_ID) >= 500000)
{
st.takeItems(LEATHER, 360);
st.takeItems(GEM_FOR_ACC, 90);
st.takeItems(ADENA_ID, 500000);
st.setCond(4);
}
else
htmltext = "You don't have enough materials";
}
else if(event.equals("30164-1.htm"))
{
if(st.getQuestItemsCount(ADENA_ID) >= 300000)
{
st.takeItems(ADENA_ID, 300000);
st.setCond(5);
}
else
htmltext = "30164-havent.htm";
}
else if(event.equals("30838-7.htm"))
{
st.giveItems(DRESS_SHOES_BOX, 1);
st.finishQuest();
}
return htmltext;
}
@Override
public String onTalk(NpcInstance npc, QuestState st)
{
String htmltext = NO_QUEST_DIALOG;
int npcId = npc.getNpcId();
int cond = st.getCond();
if(npcId == 30838)
{
QuestState fwear = st.getPlayer().getQuestState(37);
if(cond == 0 && st.getQuestItemsCount(DRESS_SHOES_BOX) == 0 && fwear != null && fwear.isStarted())
htmltext = "30838-0.htm";
else if(cond == 1)
htmltext = "30838-1.htm";
else if(cond == 2)
htmltext = "30838-2.htm";
else if(cond == 3 && st.getQuestItemsCount(LEATHER) >= 360 && st.getQuestItemsCount(GEM_FOR_ACC) >= 90 && st.getQuestItemsCount(ADENA_ID) >= 500000)
htmltext = "30838-4.htm";
else if(cond == 3 && (st.getQuestItemsCount(LEATHER) < 360 || st.getQuestItemsCount(GEM_FOR_ACC) < 90 || st.getQuestItemsCount(ADENA_ID) < 500000))
htmltext = "30838-4r.htm";
else if(cond == 4)
htmltext = "30838-5r.htm";
else if(cond == 5)
htmltext = "30838-6.htm";
}
else if(npcId == 31520)
{
if(cond == 1)
htmltext = "31520-0.htm";
else if(cond == 2)
htmltext = "31520-1r.htm";
}
else if(npcId == 30164)
if(cond == 4)
htmltext = "30164-0.htm";
else if(cond == 5)
htmltext = "30164-2.htm";
return htmltext;
}
} | [
"As69839314"
] | As69839314 |
435a8c7662feb8a9755fd9fcf1826cb257095bfc | 6a9c89983114480bffca3fc55601080060fc58f6 | /MyService/app/src/main/java/com/ramusthastudio/myservice/DicodingIntentService.java | 939e106f949bdeb761693428a5a3fdcd6664149b | [
"Apache-2.0"
] | permissive | gibranalfarabi/DicodingAcademy | c3d66a957b76d06f8804e81aba82149d920d61ed | 0f7b805da83b6d9ecdc340e52c97335a6dc522bb | refs/heads/master | 2023-08-19T22:30:36.108894 | 2019-04-16T02:59:14 | 2019-04-16T02:59:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 982 | java | package com.ramusthastudio.myservice;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
* <p>
*/
public class DicodingIntentService extends IntentService {
public static String EXTRA_DURATION = "extra_duration";
public static final String TAG = "DicodingIntentService";
public DicodingIntentService() {
super("DicodingIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "onHandleIntent()");
if (intent != null) {
int duration = intent.getIntExtra(EXTRA_DURATION, 0);
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy()");
}
}
| [
"ramusthanest@gmail.com"
] | ramusthanest@gmail.com |
d9c1ca2b9b79e11d124377ed41a8f4164eb15bfc | 4023d418f113ddcbbc2a64c9a0aab42e8acbee57 | /o2o/src/main/java/com/song/o2o/dto/echarts/LineStepSeries.java | ce445ebce1bfe9b83c9b507f37509033d8aeed11 | [] | no_license | songshiyun/o2o-system | 9b3a69c807f3f83ce26f67235f8fe2015821b8c3 | b96fefe9aece83302c2c9908f25c2ff517af2fe5 | refs/heads/master | 2020-03-28T03:50:02.691414 | 2018-09-06T12:58:03 | 2018-09-06T12:58:03 | 143,446,112 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 568 | java | package com.song.o2o.dto.echarts;
import java.util.List;
public class LineStepSeries {
private String name;
private String type="line";
private String step;
private List<Integer> data;
public List<Integer> getData() {
return data;
}
public void setName(String name) {
this.name = name;
}
public void setStep(String step) {
this.step = step;
}
public void setData(List<Integer> data) {
this.data = data;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public String getStep() {
return step;
}
}
| [
"songshiyun99@gmail.com"
] | songshiyun99@gmail.com |
eaec568ed45d07e2397b00c89255aef956396087 | 6cfab0fcbfdf8b36d6ea01003867163b17579f4a | /collector/JH-Collector/src/main/java/com/jh/collector/mapping/CalibrationInfoMapper.java | e201f565b79255104a953323e3c1a4a5f08dcdef | [] | no_license | Fairy008/JiaHeDC | ac5ed60ae3db608d8656957ce0b0364c2253e51b | bf31ffe8f452f33d2554dd587770467cecd994ee | refs/heads/master | 2020-12-27T13:42:30.153810 | 2020-02-02T10:28:31 | 2020-02-02T10:28:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 976 | java | package com.jh.collector.mapping;
import com.jh.collector.entity.CalibrationInfo;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Mapper
@Component
public interface CalibrationInfoMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table is_calibration_info
*
* @mbggenerated
*/
int insert(CalibrationInfo record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table is_calibration_info
*
* @mbggenerated
*/
int insertSelective(CalibrationInfo record);
void updateInfoById(CalibrationInfo calibrationInfo);
/**
* 根据条件返回多个地块信息
* @param calibrationInfo
* xzg 2019/7/31 14:27
* @return
*/
List<CalibrationInfo> selectCalibrationInfoList(CalibrationInfo calibrationInfo);
} | [
"fanglei613@hotmail.com"
] | fanglei613@hotmail.com |
ebadebc0413be0e65b8d9b73370366bd2251d7b7 | e09d2a6d070ea3e00e3b2a79b71dd1846ff515c7 | /core/src/com/mygdx/game/Main.java | b726505ac5998fdb77c865af3d61218029a9673c | [] | no_license | GeorgebigG/Racer | b8a7f0930d1e34913ed9ef9f3343caa3f06e5fec | 055ce96664c82bfdf3fa37d0c351c54585834676 | refs/heads/master | 2021-01-19T01:23:46.904198 | 2016-06-09T15:49:01 | 2016-06-09T15:49:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 477 | java | package com.mygdx.game;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.mygdx.game.Screens.PlayScreen;
public class Main extends Game {
public SpriteBatch batch;
public static final int WIDTH = 595;
public static final int HEIGHT = 797;
public static String name;
@Override
public void create () {
batch = new SpriteBatch();
setScreen(new PlayScreen(this));
}
@Override
public void render () {
super.render();
}
}
| [
"giorgi.nebieridze.gn@gmail.com"
] | giorgi.nebieridze.gn@gmail.com |
569078c0006bb6a590f8d8682a6837ca25f03dc7 | db8755f38898dac6df92e82ebdd6145cea00f675 | /app/src/main/java/com/example/cliff/customlisttest/utils/StaticUtils.java | ed8e5e91b149e28d1027b6584aa605bc80949e73 | [] | no_license | Xliff/CustomListTest | 0a528b667eea6d00891beee0616cefe89718ed85 | 6ab6692a424d9a59285b5bbba8667efe6457be69 | refs/heads/master | 2021-01-10T20:07:44.311428 | 2015-10-04T06:00:49 | 2015-10-04T06:00:49 | 40,452,233 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,478 | java | package com.example.cliff.customlisttest.utils;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Cliff on 8/11/2015.
*/
public class StaticUtils {
private static final int LINE_THICKNESS = 2;
// Should be moved to a utilities JAR when appropriate.
// TODO: -- cw: Pick a use case and drop the other.
// region Use case 1
public static Bitmap loadBitmapFromView(View v) {
return loadBitmapFromView(v, null);
}
public static Bitmap loadBitmapFromView(View v, Integer line_weight) {
Bitmap b = Bitmap.createBitmap(v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
Rect rect = new Rect(0, 0, b.getWidth(), b.getHeight());
Paint p = new Paint();
p.setStyle(Paint.Style.STROKE);
if (line_weight != null) {
p.setStrokeWidth(line_weight);
}
p.setColor(Color.BLACK);
v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
v.draw(c);
c.drawBitmap(b, 0, 0, null);
c.drawRect(rect, p);
return b;
}
// endregion
public static Pair<Integer,Integer> measureView(View v) {
ViewGroup.LayoutParams lp = v.getLayoutParams();
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(lp.width, View.MeasureSpec.EXACTLY);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(lp.height, View.MeasureSpec.EXACTLY);
v.measure(widthMeasureSpec, heightMeasureSpec);
int h = v.getMeasuredHeight();
int w = v.getMeasuredWidth();
ViewGroup p;
ViewGroup.MarginLayoutParams mlp;
// cw: I hate using literals, but that's what I'm left with.
if (h == 0x00ffffff) {
p = (ViewGroup)v.getParent();
mlp = (ViewGroup.MarginLayoutParams)p.getLayoutParams();
h = p.getHeight()
- mlp.topMargin
- mlp.bottomMargin
- p.getPaddingTop()
- p.getPaddingBottom();
}
if (w == 0x00ffffff) {
p = (ViewGroup)v.getParent();
mlp = (ViewGroup.MarginLayoutParams)p.getLayoutParams();
w = p.getWidth()
- mlp.leftMargin
- mlp.rightMargin
- p.getPaddingLeft()
- p.getPaddingRight();
}
return new Pair<>(w, h);
}
// region Use case 2
public static Bitmap getBitmapWithBorder(View v) {
int w = v.getWidth();
int h = v.getHeight();
// cw: Hail mary special case to obtain width and height
if (w==0 && h==0) {
Pair wh = measureView(v);
w = (Integer)wh.first;
h = (Integer)wh.second;
}
return getBitmapWithBorder(v, w, h, LINE_THICKNESS);
}
public static Bitmap getBitmapWithBorder(View v, int width, int height) {
return getBitmapWithBorder(v, width, height, LINE_THICKNESS);
}
/** Draws a black border over the screenshot of the view passed in. */
public static Bitmap getBitmapWithBorder(View v, Integer width, Integer height, int thickness) {
if (width == null || height == null || width == 0 || height == 0) {
throw new IllegalArgumentException(
"Width and Height must be non-null AND non-zero in call to getBitmapWithBorder()"
);
}
Bitmap bitmap = getBitmapFromView(v, width, height);
Canvas can = new Canvas(bitmap);
Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(thickness);
paint.setColor(Color.BLACK);
can.drawBitmap(bitmap, 0, 0, null);
can.drawRect(rect, paint);
return bitmap;
}
/** Returns a bitmap showing a screenshot of the view passed in. */
public static Bitmap getBitmapFromView(View v, int width, int height) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas (bitmap);
v.draw(canvas);
return bitmap;
}
// endregion
}
| [
"clifton.wood@gmail.com"
] | clifton.wood@gmail.com |
639658cd9f170a94db1783c12ba792efa40771e7 | 0b6b87e5f4d4b1aa9f485c58fc926cc6e7b80b11 | /src/test/java/com/nashtech/toaitran/service/OrderServiceTest.java | 869b333631bd02be6be7a77c80d2e929aca837e5 | [] | no_license | trantoai1/nashtech-task1 | 8328a8d5abcf4fffbd7118e43f63548bbe80f9f3 | 52943492276164d26e241fd506ac080027e5a122 | refs/heads/main | 2023-07-09T04:56:20.052905 | 2021-08-15T09:00:23 | 2021-08-15T09:00:23 | 381,220,785 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,912 | java | package com.nashtech.toaitran.service;
import com.nashtech.toaitran.exception.NotFoundException;
import com.nashtech.toaitran.model.dto.OrderDTO;
import com.nashtech.toaitran.model.entity.Order;
import com.nashtech.toaitran.repository.IOrderRepository;
import com.nashtech.toaitran.service.impl.OrderServiceImpl;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.modelmapper.ModelMapper;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
@SpringBootTest
public class OrderServiceTest {
public static final long ID = 1;
public static final String ENTITYNAME = "CateTest";
public static final String HAS_ID_NOT_FOUND = "Order has id=" + ID + " not found!";
public static final String DTONAME = "DTONAME";
@Mock
IOrderRepository repository;
@Mock
ModelMapper modelMapper;
@InjectMocks
OrderServiceImpl service;
@NotNull
private Order newEntity() {
Order entity = new Order();
entity.setOrderid(ID);
entity.setAddress(ENTITYNAME);
return entity;
}
@NotNull
private OrderDTO newDTO() {
OrderDTO dto = new OrderDTO();
dto.setOrderId(ID);
dto.setAddress(DTONAME);
return dto;
}
@Test
public void findAll() {
assertNotNull(service);
List<Order> list = new ArrayList<>();
Order entity = new Order();
Order entity2 = new Order();
list.add(entity);
list.add(entity2);
when(repository.findAll()).thenReturn(list);
Collection<OrderDTO> result = service.findAll();
assertEquals(2, result.size());
}
@Test
public void findById() {
Order entity = newEntity();
//OrderDTO dto = newDTO();
Optional<Order> optional = Optional.of(entity);
assertNotNull(optional);
when(repository.findById(ID)).thenReturn(optional);
when(modelMapper.map(optional.get(), OrderDTO.class)).thenReturn(newDTO());
OrderDTO dto2 = service.findById(ID);
assertEquals(dto2.getAddress(), DTONAME);
}
@Test
public void findById_Null() {
when(repository.findById(ID)).thenThrow(new NotFoundException(Order.class, ID));
NotFoundException exception = assertThrows(NotFoundException.class, () -> service.findById(ID));
assertEquals(HAS_ID_NOT_FOUND, exception.getMessage());
}
@Test
public void update() {
Order entity = newEntity();
OrderDTO dto = newDTO();
Optional<Order> optional = Optional.of(entity);
assertNotNull(optional);
when(repository.findById(ID)).thenReturn(optional);
when(modelMapper.map(optional.get(), OrderDTO.class)).thenReturn(newDTO());
when(repository.save(optional.get())).thenReturn(entity);
OrderDTO dto2 = service.update(ID, dto);
assertEquals(dto2.getAddress(), DTONAME);
}
@Test
public void save() {
Order entity = newEntity();
OrderDTO dto = newDTO();
when(modelMapper.map(dto, Order.class)).thenReturn(entity);
when(repository.save(entity)).thenReturn(entity);
when(modelMapper.map(entity, OrderDTO.class)).thenReturn(newDTO());
OrderDTO dto2 = service.save(dto);
assertEquals(dto2.getAddress(), DTONAME);
}
@Test
public void delete() {
Order entity = newEntity();
//OrderDTO dto = newDTO();
Optional<Order> optional = Optional.of(entity);
assertNotNull(optional);
when(repository.findById(ID)).thenReturn(optional);
when(modelMapper.map(optional.get(), OrderDTO.class)).thenReturn(newDTO());
OrderDTO dto2 = service.delete(ID);
assertEquals(dto2.getAddress(), DTONAME);
}
@Test
public void updateEntity() {
Order entity = newEntity();
OrderDTO dto = newDTO();
service.updateEntity(entity, dto);
assertEquals(entity.getAddress(), dto.getAddress());
}
@Test
public void createFromE() {
Order entity = newEntity();
OrderDTO dto = newDTO();
when(modelMapper.map(entity, OrderDTO.class)).thenReturn(newDTO());
OrderDTO test = service.createFromE(entity);
assertNotNull(test);
assertEquals(test.getAddress(), dto.getAddress());
}
@Test
public void createFromD() {
Order entity = newEntity();
OrderDTO dto = newDTO();
when(modelMapper.map(dto, Order.class)).thenReturn(newEntity());
Order test = service.createFromD(dto);
assertNotNull(test);
assertEquals(test.getAddress(), entity.getAddress());
}
}
| [
"trantoai.9x@gmail.com"
] | trantoai.9x@gmail.com |
b51b1c3755551b01bb1aa357ff4f1bcfc2385f70 | dbfef24b8e48968baa87dcd2d8d94af6c9821d98 | /lynx-api/src/com/dikshatech/portal/dao/LoanEligibilityCriteriaDao.java | b27625187f29c3ad7e9f1b4a2452a226021fb1cd | [] | no_license | sudheer999/vijay-gradle | 7ab62da1b41120b48ab5c8f06f3e3be5c4a5530e | c03d167319ec915c3eb25e394761682144e1e3b3 | refs/heads/master | 2021-04-26T23:02:03.684417 | 2018-03-02T11:03:07 | 2018-03-02T11:03:07 | 123,918,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,965 | java | /*
* This source file was generated by FireStorm/DAO.
*
* If you purchase a full license for FireStorm/DAO you can customize this header file.
*
* For more information please visit http://www.codefutures.com/products/firestorm
*/
package com.dikshatech.portal.dao;
import com.dikshatech.portal.dto.*;
import com.dikshatech.portal.exceptions.*;
public interface LoanEligibilityCriteriaDao
{
/**
* Inserts a new row in the LOAN_ELIGIBILITY_CRITERIA table.
*/
public LoanEligibilityCriteriaPk insert(LoanEligibilityCriteria dto) throws LoanEligibilityCriteriaDaoException;
/**
* Updates a single row in the LOAN_ELIGIBILITY_CRITERIA table.
*/
public void update(LoanEligibilityCriteriaPk pk, LoanEligibilityCriteria dto) throws LoanEligibilityCriteriaDaoException;
/**
* Deletes a single row in the LOAN_ELIGIBILITY_CRITERIA table.
*/
public void delete(LoanEligibilityCriteriaPk pk) throws LoanEligibilityCriteriaDaoException;
/**
* Returns the rows from the LOAN_ELIGIBILITY_CRITERIA table that matches the specified primary-key value.
*/
public LoanEligibilityCriteria findByPrimaryKey(LoanEligibilityCriteriaPk pk) throws LoanEligibilityCriteriaDaoException;
/**
* Returns all rows from the LOAN_ELIGIBILITY_CRITERIA table that match the criteria 'ID = :id'.
*/
public LoanEligibilityCriteria findByPrimaryKey(int id) throws LoanEligibilityCriteriaDaoException;
/**
* Returns all rows from the LOAN_ELIGIBILITY_CRITERIA table that match the criteria ''.
*/
public LoanEligibilityCriteria[] findAll() throws LoanEligibilityCriteriaDaoException;
/**
* Returns all rows from the LOAN_ELIGIBILITY_CRITERIA table that match the criteria 'TYPE_ID = :typeId'.
*/
public LoanEligibilityCriteria[] findByLoanType(int typeId) throws LoanEligibilityCriteriaDaoException;
/**
* Returns all rows from the LOAN_ELIGIBILITY_CRITERIA table that match the criteria 'ID = :id'.
*/
public LoanEligibilityCriteria[] findWhereIdEquals(int id) throws LoanEligibilityCriteriaDaoException;
/**
* Returns all rows from the LOAN_ELIGIBILITY_CRITERIA table that match the criteria 'LABEL = :label'.
*/
public LoanEligibilityCriteria[] findWhereLabelEquals(String label) throws LoanEligibilityCriteriaDaoException;
/**
* Returns all rows from the LOAN_ELIGIBILITY_CRITERIA table that match the criteria 'ELIGIBILITY_AMOUNT = :eligibilityAmount'.
*/
public LoanEligibilityCriteria[] findWhereEligibilityAmountEquals(String eligibilityAmount) throws LoanEligibilityCriteriaDaoException;
/**
* Returns all rows from the LOAN_ELIGIBILITY_CRITERIA table that match the criteria 'EMI_ELIGIBILITY = :emiEligibility'.
*/
public LoanEligibilityCriteria[] findWhereEmiEligibilityEquals(int emiEligibility) throws LoanEligibilityCriteriaDaoException;
/**
* Returns all rows from the LOAN_ELIGIBILITY_CRITERIA table that match the criteria 'MAX_AMOUNT_LIMIT = :maxAmountLimit'.
*/
public LoanEligibilityCriteria[] findWhereMaxAmountLimitEquals(double maxAmountLimit) throws LoanEligibilityCriteriaDaoException;
/**
* Returns all rows from the LOAN_ELIGIBILITY_CRITERIA table that match the criteria 'TYPE_ID = :typeId'.
*/
public LoanEligibilityCriteria[] findWhereTypeIdEquals(int typeId) throws LoanEligibilityCriteriaDaoException;
/**
* Sets the value of maxRows
*/
public void setMaxRows(int maxRows);
/**
* Gets the value of maxRows
*/
public int getMaxRows();
/**
* Returns all rows from the LOAN_ELIGIBILITY_CRITERIA table that match the specified arbitrary SQL statement
*/
public LoanEligibilityCriteria[] findByDynamicSelect(String sql, Object[] sqlParams) throws LoanEligibilityCriteriaDaoException;
/**
* Returns all rows from the LOAN_ELIGIBILITY_CRITERIA table that match the specified arbitrary SQL statement
*/
public LoanEligibilityCriteria[] findByDynamicWhere(String sql, Object[] sqlParams) throws LoanEligibilityCriteriaDaoException;
}
| [
"sudheer.tsm9@gmail.com"
] | sudheer.tsm9@gmail.com |
6b1e653a341d273b393c8886e504df42f214ff90 | 516b6594e527b9aa08bc82707b27f2f4784fd8d5 | /common-datamodel/src/main/java/ait/ffma/factory/.svn/text-base/ComponentNameConstants.java.svn-base | c810ef54b6d122ec1ec7446c24659a104aac61da | [
"Apache-2.0"
] | permissive | ait-ngcms/ffma | 1efb3c7bfd3822e1f4ff08eea99f967a251b28da | 76c0ff5585b10d02a19f07e85558dd1303bef599 | refs/heads/master | 2021-01-01T06:26:16.669922 | 2015-10-14T12:44:36 | 2015-10-14T12:44:36 | 31,206,908 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 235 | package ait.ffma.factory;
public interface ComponentNameConstants {
public static final String COMPONENT_PRESERVATION_RISKMANAGEMENT = "preservation-riskmanagement";
public static final String COMPONENT_COMMON = "common";
}
| [
"roman.graf@ait.ac.at"
] | roman.graf@ait.ac.at | |
056d4d451b0f4114aad2b6f22b5ab91f1043a251 | bd100ab6cf7f2fa79d9a883e6da721c9da24af67 | /ACompiler/src/ast/Statement.java | e2cc90b67ad146f718992cd1632a11c9bc74f807 | [] | no_license | alonsovb/compiler-codegenerator | 300080863f815ab05dff3b512f9e2d8c81fbf3e3 | b272c20e0213d54fbe0b5a32361ac6ca18b57866 | refs/heads/master | 2020-12-24T13:44:11.409619 | 2012-06-23T03:24:06 | 2012-06-23T03:24:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 115 | java | package ast;
public abstract class Statement extends AST
{
public abstract Object visit(Visitor v,Object arg);
}
| [
"lavb91@gmail.com"
] | lavb91@gmail.com |
47ee814b345f0ef58ed922d828f2769a7eb31a52 | 38e8d4b91d36eb25e1f4229c06523b474f906ddb | /app/src/main/java/bakeapp/rako/layoutteste/BaseActivity.java | 99b3f42f4cf01cb6052d16c311f794f003da77ed | [] | no_license | RafaelKozar/ScrollWithConstraint | abf9ef27265c2c9d086581c995966cbde2e74b1f | 770ad19a2bef6a6b5e1d9b805dbb677a33a874f8 | refs/heads/master | 2020-03-25T19:07:42.902300 | 2018-08-13T13:54:52 | 2018-08-13T13:54:52 | 144,066,161 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,197 | java | /*
package bakeapp.rako.layoutteste;
import android.app.Activity;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
*/
/**
* Created by rako on 08/08/2018.
*//*
public class BaseActivity extends Activity {
private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int heightDiff = rootLayout.getRootView().getHeight() - rootLayout.getHeight();
int contentViewTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(BaseActivity.this);
if(heightDiff <= contentViewTop){
onHideKeyboard();
Intent intent = new Intent("KeyboardWillHide");
broadcastManager.sendBroadcast(intent);
} else {
int keyboardHeight = heightDiff - contentViewTop;
onShowKeyboard(keyboardHeight);
Intent intent = new Intent("KeyboardWillShow");
intent.putExtra("KeyboardHeight", keyboardHeight);
broadcastManager.sendBroadcast(intent);
}
}
};
private boolean keyboardListenersAttached = false;
private ViewGroup rootLayout;
protected void onShowKeyboard(int keyboardHeight) {}
protected void onHideKeyboard() {}
protected void attachKeyboardListeners() {
if (keyboardListenersAttached) {
return;
}
rootLayout = (ViewGroup) findViewById(R.id.rootLayout);
rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(keyboardLayoutListener);
keyboardListenersAttached = true;
}
@Override
protected void onDestroy() {
super.onDestroy();
if (keyboardListenersAttached) {
rootLayout.getViewTreeObserver().removeGlobalOnLayoutListener(keyboardLayoutListener);
}
}
}
*/
| [
"rafael.kozar@gft.com"
] | rafael.kozar@gft.com |
6c6bce428462bafc7932fcb11caa88edd0779070 | 63d3700f93e742c3c76f8e079ef3d7121b74735c | /build/app/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/dev/flutter/e2e/R.java | d5a258866cdd4283f65298094303fa51d7f57c63 | [
"MIT"
] | permissive | ViralS-Truongnh/shainManager | 6b70d67b75d75d21f959a02c232f95cd834cc077 | 8c8d18eabaf7be0e6916cbf1e845f6bdc1e530a3 | refs/heads/master | 2020-12-03T07:12:04.785583 | 2019-12-27T15:15:48 | 2019-12-27T15:15:48 | 231,238,134 | 0 | 1 | null | 2020-01-01T16:24:26 | 2020-01-01T16:24:26 | null | UTF-8 | Java | false | false | 255 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package dev.flutter.e2e;
public final class R {
private R() {}
}
| [
"huynh@scenes.co.jp"
] | huynh@scenes.co.jp |
d4c437b663e6e254d59603ffaa9d02141d7dd20a | 46453350d77e272d776dd4a63be11aa25c9cd944 | /paascloud-provider/paascloud-provider-omc/src/main/java/com/paascloud/provider/config/ResourceServerConfig.java | 1cf7be6892661206d114dae5ed89438adc06f911 | [
"Apache-2.0"
] | permissive | poorhua/paascloud-wechat-auth-master | 34991df6b4de2ee803c82681d9f8871159f24577 | 67877629bb98140e75ad804cedc14a56233f9fa3 | refs/heads/master | 2020-04-12T17:58:37.170355 | 2018-09-17T04:29:24 | 2018-09-17T04:29:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,816 | java | /*
* Copyright (c) 2018. paascloud.net All Rights Reserved.
* 项目名称:paascloud快速搭建企业级分布式微服务平台
* 类名称:ResourceServerConfig.java
* 创建人:刘兆明
* 联系方式:paascloud.net@gmail.com
* 开源地址: https://github.com/paascloud
* 博客地址: http://blog.paascloud.net
* 项目官网: http://paascloud.net
*/
package com.paascloud.provider.config;
import com.paascloud.config.properties.PaascloudProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* The class Resource server config.
*
* @author paascloud.net @gmail.com
*/
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Resource
private PaascloudProperties paascloudProperties;
@Override
public void configure(HttpSecurity http) throws Exception {
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
List<String> urls = paascloudProperties.getSecurity().getOauth2().getIgnore().getUrls();
if(urls != null && urls.size() > 0 ){
urls.forEach(url ->registry.antMatchers(url).permitAll());
}
registry.anyRequest().authenticated()
.and()
.csrf().disable();
http.headers().frameOptions().disable();
}
}
| [
"1215761798@qq.com"
] | 1215761798@qq.com |
09cb09b66d9f7feb2069221271d6627aec0eeba5 | 6eb1bb7665fa6110f0ce9b7d00129ba99210bd6a | /src/nim/NimGame.java | 462814064c5d018a274ec185ae6b57feebe67542 | [] | no_license | phung025/NimGame | 11b2577dd27b9ac403ae9188fe4e8599f534343c | 1acc4877d9546b7b5058791236ddcd615626a05b | refs/heads/master | 2021-01-11T21:37:45.245387 | 2018-03-13T04:56:23 | 2018-03-13T04:56:23 | 78,822,287 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,276 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nim;
import framework_AI_game.Game;
import framework_AI_game.Move;
import framework_AI_game.Player;
import framework_AI_game.State;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
*
* @author user
*/
public class NimGame extends Game {
public NimGame(String introduction,
State initial_game_state,
Player first_player,
State p1_winning_state,
Player second_player,
State p2_winning_state) {
super(introduction, initial_game_state, first_player, p1_winning_state, second_player, p2_winning_state);
}
/**
* Check if the game is finish
*
* @return true if the game's current state is final state
*/
@Override
public boolean isGameEnd() {
return ((NimState) getCurrentGameState()).getAllCoins() == 0;
}
@Override
public void newRandomGame() {
// Initial game piles
List<Integer> initialPiles = new ArrayList<>();
for (int i = 0; i < PILE_SIZE; ++i) {
// Add a random amount of coins from 6 to 12 to the pile
initialPiles.add(ThreadLocalRandom.current().nextInt(6, 12));
}
// Available move list
List<Move> moves = new ArrayList<>();
for (int pile_index = 0; pile_index < initialPiles.size(); ++pile_index) {
for (int coin_capacity = 1; coin_capacity <= initialPiles.get(pile_index); ++coin_capacity) {
moves.add(new NimMove("Take " + coin_capacity + " coins from pile " + (pile_index + 1),
pile_index + ":" + coin_capacity));
}
}
// Create a new random game state with first player playing first
NimState newGameState = new NimState(initialPiles, getFirstPlayer().getPlayerType(), getSecondPlayer().getPlayerType());
// All game players
getFirstPlayer().setAvailableMoves(moves);
getSecondPlayer().setAvailableMoves(moves);
setCurrentPlayer(getFirstPlayer());
// Set new game state
setCurrentGameState(newGameState);
setInitialGameState(newGameState);
}
@Override
public void resetGame() {
setCurrentPlayer(getFirstPlayer());
setCurrentGameState(getInitialGameState());
}
@Override
public String toString() {
StringBuilder s = new StringBuilder("");
s.append("\n---------- World of Nim ----------");
s.append("\nPlayer 1: ".concat(getFirstPlayer().getPlayerName()));
s.append("\nPlayer 2: ".concat(getSecondPlayer().getPlayerName()));
s.append("\n----------Current Score ----------");
s.append("\n".concat(getFirstPlayer().getPlayerName()).concat(": ").concat(String.valueOf(getFirstPlayerScore())).concat(" point(s)"));
s.append("\n".concat(getSecondPlayer().getPlayerName()).concat(": ").concat(String.valueOf(getSecondPlayerScore())).concat(" point(s)"));
return s.toString();
}
// Size of the game piles.
public static int PILE_SIZE = 3;
}
| [
"phung025@d.umn.edu"
] | phung025@d.umn.edu |
e3781f8339b43d544b00d9770770dcbbb29c32e7 | 1baeed75248c36a535749e74c7efbd7f5dc581e2 | /pinyougouparent/pinyougou-content-service/src/main/java/com/pinyougou/content/service/impl/ContentCategoryServiceImpl.java | 5ae47a6d206764175380f0b49c2a3d45cbada466 | [] | no_license | GaoForGot/pyg | a13fa3e0479b47af543cfe54c49f1a4af0ad5c6b | 35b00b7154d7ae39b4521c414b53bc86d79a7cfe | refs/heads/master | 2022-12-22T00:32:57.328344 | 2020-11-09T19:23:33 | 2020-11-09T19:23:33 | 209,957,805 | 0 | 0 | null | 2022-12-16T07:18:30 | 2019-09-21T09:27:46 | JavaScript | UTF-8 | Java | false | false | 2,829 | java | package com.pinyougou.content.service.impl;
import java.util.List;
import com.pinyougou.content.service.ContentCategoryService;
import entities.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pinyougou.mapper.TbContentCategoryMapper;
import com.pinyougou.pojo.TbContentCategory;
import com.pinyougou.pojo.TbContentCategoryExample;
import com.pinyougou.pojo.TbContentCategoryExample.Criteria;
import org.springframework.transaction.annotation.Transactional;
/**
* 服务实现层
*
* @author Administrator
*/
@Service
@Transactional
public class ContentCategoryServiceImpl implements ContentCategoryService {
@Autowired
private TbContentCategoryMapper contentCategoryMapper;
/**
* 查询全部
*/
@Override
public List<TbContentCategory> findAll() {
return contentCategoryMapper.selectByExample(null);
}
/**
* 按分页查询
*/
@Override
public PageResult findPage(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
Page<TbContentCategory> page = (Page<TbContentCategory>) contentCategoryMapper.selectByExample(null);
return new PageResult(page.getTotal(), page.getResult());
}
/**
* 增加
*/
@Override
public void add(TbContentCategory contentCategory) {
contentCategoryMapper.insert(contentCategory);
}
/**
* 修改
*/
@Override
public void update(TbContentCategory contentCategory) {
contentCategoryMapper.updateByPrimaryKey(contentCategory);
}
/**
* 根据ID获取实体
*
* @param id
* @return
*/
@Override
public TbContentCategory findOne(Long id) {
return contentCategoryMapper.selectByPrimaryKey(id);
}
/**
* 批量删除
*/
@Override
public void delete(Long[] ids) {
for (Long id : ids) {
contentCategoryMapper.deleteByPrimaryKey(id);
}
}
@Override
public PageResult findPage(TbContentCategory contentCategory, int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
TbContentCategoryExample example = new TbContentCategoryExample();
Criteria criteria = example.createCriteria();
if (contentCategory != null) {
if (contentCategory.getName() != null && contentCategory.getName().length() > 0) {
criteria.andNameLike("%" + contentCategory.getName() + "%");
}
}
Page<TbContentCategory> page = (Page<TbContentCategory>) contentCategoryMapper.selectByExample(example);
return new PageResult(page.getTotal(), page.getResult());
}
}
| [
"xiaozegavin@outlook.com"
] | xiaozegavin@outlook.com |
19aaa4e62800ce10652137b08d29e679cf22760a | 4bae14b2c62863bbaf98aad5a584cdf81e460ee7 | /src/com/cybertek/AbstarctClass.java | d81fa1b5cb60887045f3402cbeb2259a0acd94bd | [] | no_license | xerinay/FirstSelinum | 68ca6cc8a96b6f1d0ff4a541a98b024b0bdcd383 | c4c3123e9db3b77246343744cb16bb983cbb1e89 | refs/heads/master | 2020-04-17T20:42:59.038281 | 2019-01-22T03:06:31 | 2019-01-22T03:06:31 | 166,917,863 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 81 | java | package com.cybertek;
public class AbstarctClass {
int age ;
public S
}
| [
"xerinay85@gmail.com"
] | xerinay85@gmail.com |
58f723ef2e6620116cb651145017cf444d469f6c | 44e082b233a2e44212422514fa9225cf1b6358d2 | /GPROG_oldPruefungen/src/_glProg_2018_VZ_HT/Dalmatiner.java | 092f7d2ec1cdb37a75b6d70fb2a3120f17c79e5d | [] | no_license | fhbgraceb/VerbundA-SS20 | b3af20000e1a4b6efe768156ad415dbf67e16be0 | 7e672445bb785386af2ff65d3526f89c67882a71 | refs/heads/master | 2022-12-28T05:56:20.158197 | 2020-10-10T23:20:18 | 2020-10-10T23:20:18 | 238,525,365 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 615 | java | package _glProg_2018_VZ_HT;
public class Dalmatiner {
public static void main(String[] args) {
int anzahlDalamtiner = 101;
for (int mickey = 1; mickey < anzahlDalamtiner; mickey++) {
for (int donald = 1; donald < anzahlDalamtiner; donald++) {
for (int goofy = 1; goofy < anzahlDalamtiner; goofy++) {
int summe = mickey + donald + goofy;
if ((summe < anzahlDalamtiner)
&& (summe > 17)
&& (mickey > (donald + goofy) * 2)
&& (donald == goofy + 3)) {
System.out.println("Mickey: " + mickey + " Donald: " + donald + " Goofy: " + goofy);
}
}
}
}
}
}
| [
"fhb190776@fh-vie.ac.at"
] | fhb190776@fh-vie.ac.at |
59ed04b921ee0099ddf639e7eb0f82582d64a5b2 | 6d3fccfe86c0fe4d92632f1d6992990ddc31a05c | /hsweb-easy-orm-rdb/src/main/java/org/hswebframework/ezorm/rdb/mapping/defaults/DefaultReactiveQuery.java | 7a864a62a59b4a330b0dd6b66c5bca817c4402c0 | [] | no_license | MethodLevelAnalyzer/hsweb-easy-orm | 7f81cc218f0a7c14c09861a1bd8946e13e42be1f | 31659eaac403423bffbd021868e4786e21cd8050 | refs/heads/master | 2023-05-14T21:33:30.015536 | 2021-06-08T08:45:56 | 2021-06-08T08:45:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,842 | java | package org.hswebframework.ezorm.rdb.mapping.defaults;
import org.hswebframework.ezorm.rdb.events.ContextKeyValue;
import org.hswebframework.ezorm.rdb.executor.wrapper.ResultWrapper;
import org.hswebframework.ezorm.rdb.mapping.EntityColumnMapping;
import org.hswebframework.ezorm.rdb.mapping.ReactiveQuery;
import org.hswebframework.ezorm.rdb.mapping.events.EventSupportWrapper;
import org.hswebframework.ezorm.rdb.mapping.events.MappingEventTypes;
import org.hswebframework.ezorm.rdb.metadata.TableOrViewMetadata;
import org.hswebframework.ezorm.rdb.operator.DMLOperator;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static org.hswebframework.ezorm.rdb.events.ContextKeys.source;
import static org.hswebframework.ezorm.rdb.events.ContextKeys.tableMetadata;
import static org.hswebframework.ezorm.rdb.executor.wrapper.ResultWrappers.*;
import static org.hswebframework.ezorm.rdb.mapping.events.EventSupportWrapper.*;
import static org.hswebframework.ezorm.rdb.mapping.events.MappingContextKeys.*;
import static org.hswebframework.ezorm.rdb.mapping.events.MappingContextKeys.type;
import static org.hswebframework.ezorm.rdb.operator.dml.query.Selects.count1;
public class DefaultReactiveQuery<T> extends DefaultQuery<T, ReactiveQuery<T>> implements ReactiveQuery<T> {
public DefaultReactiveQuery(TableOrViewMetadata tableMetadata,
EntityColumnMapping mapping,
DMLOperator operator,
ResultWrapper<T, ?> wrapper,
ContextKeyValue<?>... keyValues) {
super(tableMetadata, mapping, operator, wrapper,keyValues);
}
@Override
public Flux<T> fetch() {
return operator
.query(tableMetadata)
.select(getSelectColumn())
.where(param.getTerms())
.orderBy(getSortOrder())
.when(param.isPaging(), query -> query.paging(param.getPageIndex(), param.getPageSize()))
.accept(queryOperator ->
tableMetadata.fireEvent(MappingEventTypes.select_before, eventContext ->
eventContext.set(
source(DefaultReactiveQuery.this),
query(queryOperator),
tableMetadata(tableMetadata),
dml(operator),
executorType("reactive"),
type("fetch")
)))
.fetch(eventWrapper(tableMetadata, wrapper, executorType("reactive"), type("fetch")))
.reactive();
}
@Override
public Mono<T> fetchOne() {
return operator
.query(tableMetadata)
.select(getSelectColumn())
.where(param.getTerms())
.orderBy(getSortOrder())
.paging(0, 1)
.accept(queryOperator ->
tableMetadata.fireEvent(MappingEventTypes.select_before, eventContext ->
eventContext.set(
source(DefaultReactiveQuery.this),
query(queryOperator),
dml(operator),
tableMetadata(tableMetadata),
executorType("reactive"),
type("fetchOne")
)))
.fetch(eventWrapper(tableMetadata, wrapper, executorType("reactive"), type("fetchOne")))
.reactive()
.as(Mono::from);
}
@Override
public Mono<Integer> count() {
return operator
.query(tableMetadata)
.select(count1().as("total"))
.where(param.getTerms())
.accept(queryOperator ->
tableMetadata.fireEvent(MappingEventTypes.select_before, eventContext ->
eventContext.set(
source(DefaultReactiveQuery.this),
query(queryOperator),
dml(operator),
tableMetadata(tableMetadata),
executorType("reactive"),
type("count")
)))
.fetch(column("total", Number.class::cast))
.reactive()
.map(Number::intValue)
.reduce(Math::addExact)
.switchIfEmpty(Mono.just(0));
}
}
| [
"admin@hsweb.me"
] | admin@hsweb.me |
c8d93a386444e8a19af5f0d7384c250ac69fbe22 | 32f38cd53372ba374c6dab6cc27af78f0a1b0190 | /app/src/main/java/com/ta/audid/db/SqliteHelper.java | 0238c0ad5649c62606fbf0b8e450c30e84c21330 | [] | no_license | shuixi2013/AmapCode | 9ea7aefb42e0413f348f238f0721c93245f4eac6 | 1a3a8d4dddfcc5439df8df570000cca12b15186a | refs/heads/master | 2023-06-06T23:08:57.391040 | 2019-08-29T04:36:02 | 2019-08-29T04:36:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,815 | java | package com.ta.audid.db;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.alipay.mobile.common.transport.monitor.RPCDataItems;
import com.ta.audid.utils.UtdidLogger;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
public class SqliteHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private DelayCloseDbTask mCloseDbTask = new DelayCloseDbTask();
/* access modifiers changed from: private */
public AtomicInteger mWritableCounter = new AtomicInteger();
/* access modifiers changed from: private */
public SQLiteDatabase mWritableDatabase;
private Future<?> mcloseFuture;
class DelayCloseDbTask implements Runnable {
DelayCloseDbTask() {
}
public void run() {
synchronized (SqliteHelper.this) {
if (SqliteHelper.this.mWritableCounter.get() == 0 && SqliteHelper.this.mWritableDatabase != null) {
SqliteHelper.this.mWritableDatabase.close();
SqliteHelper.this.mWritableDatabase = null;
}
}
}
}
public void onCreate(SQLiteDatabase sQLiteDatabase) {
}
public void onUpgrade(SQLiteDatabase sQLiteDatabase, int i, int i2) {
}
public SqliteHelper(Context context, String str) {
super(context, str, null, 2);
}
/* JADX WARNING: type inference failed for: r0v0, types: [java.lang.String[], android.database.Cursor] */
/* JADX WARNING: Multi-variable type inference failed. Error: jadx.core.utils.exceptions.JadxRuntimeException: No candidate types for var: r0v0, types: [java.lang.String[], android.database.Cursor]
assigns: [?[int, float, boolean, short, byte, char, OBJECT, ARRAY]]
uses: [android.database.Cursor, java.lang.String[]]
mth insns count: 10
at jadx.core.dex.visitors.typeinference.TypeSearch.fillTypeCandidates(TypeSearch.java:237)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at jadx.core.dex.visitors.typeinference.TypeSearch.run(TypeSearch.java:53)
at jadx.core.dex.visitors.typeinference.TypeInferenceVisitor.runMultiVariableSearch(TypeInferenceVisitor.java:104)
at jadx.core.dex.visitors.typeinference.TypeInferenceVisitor.visit(TypeInferenceVisitor.java:97)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:27)
at jadx.core.dex.visitors.DepthTraversal.lambda$visit$1(DepthTraversal.java:14)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:14)
at jadx.core.ProcessClass.process(ProcessClass.java:30)
at jadx.core.ProcessClass.lambda$processDependencies$0(ProcessClass.java:49)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:49)
at jadx.core.ProcessClass.process(ProcessClass.java:35)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:311)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler.lambda$appendSourcesSave$0(JadxDecompiler.java:217)
*/
/* Code decompiled incorrectly, please refer to instructions dump. */
public void onOpen(android.database.sqlite.SQLiteDatabase r3) {
/*
r2 = this;
r0 = 0
java.lang.String r1 = "PRAGMA journal_mode=DELETE"
android.database.Cursor r1 = r3.rawQuery(r1, r0) // Catch:{ Throwable -> 0x0010, all -> 0x000b }
r2.closeCursor(r1)
goto L_0x0013
L_0x000b:
r3 = move-exception
r2.closeCursor(r0)
throw r3
L_0x0010:
r2.closeCursor(r0)
L_0x0013:
super.onOpen(r3)
return
*/
throw new UnsupportedOperationException("Method not decompiled: com.ta.audid.db.SqliteHelper.onOpen(android.database.sqlite.SQLiteDatabase):void");
}
public synchronized SQLiteDatabase getWritableDatabase() {
try {
if (this.mWritableDatabase == null) {
this.mWritableDatabase = super.getWritableDatabase();
}
this.mWritableCounter.incrementAndGet();
} catch (Throwable th) {
UtdidLogger.w(RPCDataItems.SWITCH_TAG_LOG, "e", th);
}
return this.mWritableDatabase;
}
/* JADX WARNING: Code restructure failed: missing block: B:12:0x0027, code lost:
return;
*/
/* Code decompiled incorrectly, please refer to instructions dump. */
public synchronized void closeWritableDatabase(android.database.sqlite.SQLiteDatabase r5) {
/*
r4 = this;
monitor-enter(r4)
if (r5 != 0) goto L_0x0005
monitor-exit(r4)
return
L_0x0005:
java.util.concurrent.atomic.AtomicInteger r5 = r4.mWritableCounter // Catch:{ Throwable -> 0x002b, all -> 0x0028 }
int r5 = r5.decrementAndGet() // Catch:{ Throwable -> 0x002b, all -> 0x0028 }
if (r5 != 0) goto L_0x0026
java.util.concurrent.Future<?> r5 = r4.mcloseFuture // Catch:{ Throwable -> 0x002b, all -> 0x0028 }
if (r5 == 0) goto L_0x0017
java.util.concurrent.Future<?> r5 = r4.mcloseFuture // Catch:{ Throwable -> 0x002b, all -> 0x0028 }
r0 = 0
r5.cancel(r0) // Catch:{ Throwable -> 0x002b, all -> 0x0028 }
L_0x0017:
com.ta.audid.utils.TaskExecutor r5 = com.ta.audid.utils.TaskExecutor.getInstance() // Catch:{ Throwable -> 0x002b, all -> 0x0028 }
r0 = 0
com.ta.audid.db.SqliteHelper$DelayCloseDbTask r1 = r4.mCloseDbTask // Catch:{ Throwable -> 0x002b, all -> 0x0028 }
r2 = 30000(0x7530, double:1.4822E-319)
java.util.concurrent.ScheduledFuture r5 = r5.schedule(r0, r1, r2) // Catch:{ Throwable -> 0x002b, all -> 0x0028 }
r4.mcloseFuture = r5 // Catch:{ Throwable -> 0x002b, all -> 0x0028 }
L_0x0026:
monitor-exit(r4)
return
L_0x0028:
r5 = move-exception
monitor-exit(r4)
throw r5
L_0x002b:
monitor-exit(r4)
return
*/
throw new UnsupportedOperationException("Method not decompiled: com.ta.audid.db.SqliteHelper.closeWritableDatabase(android.database.sqlite.SQLiteDatabase):void");
}
public void closeCursor(Cursor cursor) {
if (cursor != null) {
try {
cursor.close();
} catch (Throwable unused) {
}
}
}
}
| [
"hubert.yang@nf-3.com"
] | hubert.yang@nf-3.com |
2f4dc80b981048f230592c2db08983c8a1a624ec | 367d92dd52871e4089bb794e8384b9c9a5a81f25 | /leetcode/RangeAdditionII/RangeAddition.java | 0dd733f55c7389f3533f1d3b7a2271a6da97d0c6 | [] | no_license | SpicyZinc/underestimate | 54cfd10e3202e4bce5b8cb5d8b03481d295c308c | dbe9caffb41f153d5e23a583a1abe2c66e4bdf4b | refs/heads/master | 2023-03-09T01:31:43.867486 | 2023-02-28T10:05:14 | 2023-02-28T10:05:14 | 20,214,984 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,310 | java | /*
Given an m * n matrix M initialized with all 0's and several update operations.
Operations are represented by a 2D array, and each operation is represented by an array with two positive integers a and b,
which means M[i][j] should be added by one for all 0 <= i < a and 0 <= j < b.
You need to count and return the number of maximum integers in the matrix after performing all the operations.
Example 1:
Input:
m = 3, n = 3
operations = [[2,2],[3,3]]
Output: 4
Explanation:
Initially, M =
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
After performing [2,2], M =
[[1, 1, 0],
[1, 1, 0],
[0, 0, 0]]
After performing [3,3], M =
[[2, 2, 1],
[2, 2, 1],
[1, 1, 1]]
So the maximum integer in M is 2, and there are four of it in M. So return 4.
Note:
The range of m and n is [1,40000].
The range of a is [1,m], and the range of b is [1,n].
The range of operations size won't exceed 10,000.
idea:
easy
the number of the max
length * width
find the min common part of length
find the min common part of width
note, maxRow and maxCol is NOT index based
*/
public class RangeAddition {
public int maxCount(int m, int n, int[][] ops) {
int maxRow = m;
int maxCol = n;
for (int[] op : ops) {
maxRow = Math.min(op[0], maxRow);
maxCol = Math.min(op[1], maxCol);
}
return maxRow * maxCol;
}
} | [
"angxin880@gmail.com"
] | angxin880@gmail.com |
0d0d5abf0f6ef08b18f11676c806cf4390199989 | ed5159d056e98d6715357d0d14a9b3f20b764f89 | /test/irvine/oeis/a044/A044128Test.java | 22b13e02bd3fe0f99f35632b7d24d8cd5d4c563b | [] | no_license | flywind2/joeis | c5753169cf562939b04dd246f8a2958e97f74558 | e5efd6971a0062ac99f4fae21a7c78c9f9e74fea | refs/heads/master | 2020-09-13T18:34:35.080552 | 2019-11-19T05:40:55 | 2019-11-19T05:40:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 195 | java | package irvine.oeis.a044;
import irvine.oeis.AbstractSequenceTest;
/**
* Tests the corresponding class.
* @author Sean A. Irvine
*/
public class A044128Test extends AbstractSequenceTest {
}
| [
"sairvin@gmail.com"
] | sairvin@gmail.com |
ca84ee6697769f5f0f8d658a6c622bba16ce740a | 0bb95ff114dab9e471006a5596293f20e2821e18 | /ClothesManager/app/src/main/java/database/DatabaseOperations.java | 06fd7a9415b7c5310025b6988284d7675ab24990 | [] | no_license | AngelaRg/ClothesManager | 0df245837a362f273ab705b1403f97223c542480 | b817f9bf0162c3f0cd213b2f3681d9b11f06d7e3 | refs/heads/master | 2021-01-01T04:14:12.965513 | 2017-10-01T10:46:01 | 2017-10-01T10:46:01 | 97,145,493 | 0 | 0 | null | 2017-10-01T10:46:02 | 2017-07-13T16:46:00 | Java | UTF-8 | Java | false | false | 15,010 | java | package database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import models.Basket;
import models.Garment;
import utils.BitmapConverter;
import utils.DateFormatter;
import utils.StringValues;
/**
* This class performs the CRUD operations for the in app database
*
* Created by Cesar on 7/24/2017.
*/
public class DatabaseOperations {
private SQLiteDatabase db;
private DataBaseHelper dataBaseHelper;
/**
* Constructor method
* @param context
*/
public DatabaseOperations(Context context) {
// initialize the database
dataBaseHelper = DataBaseHelper.getInstance(context);
}
/**
* Method to get all the Garments in the database
* @return list of all garments
*/
public List<Garment> getAllGarments() {
db = dataBaseHelper.getWritableDatabase();
// query string
String query = "SELECT * FROM " + StringValues.TABLE_GARMENT;
// execute query
Cursor cursor = db.rawQuery(query,null);
// initialize object list
List<Garment> garments = new ArrayList<Garment>();
try {
if (cursor.moveToFirst()) {
// iterate through all the lines of the result
while (!cursor.isAfterLast()) {
garments.add(createGarmentFromResultQuery(cursor));
// move to next query result
cursor.moveToNext();
}
}
} catch (Exception e) {
Log.d("getAllGarments", "Error while getting all garments");
e.printStackTrace();
}
db.close();
return garments;
}
/**
* Method to create a new Garment in the DB
* @param garment
*/
public void addGarment(Garment garment) {
db = dataBaseHelper.getWritableDatabase();
// add all the values in a ContentValues
ContentValues values = new ContentValues();
values.put(StringValues.COLUMN_IDGARMENT, garment.getIdGarment());
values.put(StringValues.COLUMN_GARMENTNAME, garment.getGarmentName());
values.put(StringValues.COLUMN_GARMENTTYPE, garment.getGarmentType());
values.put(StringValues.COLUMN_USAGE, garment.getUsagePercentage());
values.put(StringValues.COLUMN_LASTUSAGE, DateFormatter.createStringFromDate(garment.getLastUsage()));
values.put(StringValues.COLUMN_GARMENTPCITURE, BitmapConverter.getBytes(garment.getGarmentPicture()));
values.put(StringValues.COLUMN_ISINBASKET, (garment.isInBasket()? 1:0));
values.put(StringValues.COLUMN_IDBASKET, garment.getIdBasket());
// insert the values into a new row in DB
db.insert(StringValues.TABLE_GARMENT, null, values);
db.close();
}
/**
* Method to get a Garment object by its id
* @param garmentId
* @return
*/
public Garment getGarmentById(int garmentId) {
db = dataBaseHelper.getWritableDatabase();
// query string
String query = "SELECT * FROM " + StringValues.TABLE_GARMENT
+ " WHERE " + StringValues.COLUMN_IDGARMENT
+ " = \"" + garmentId + "\"";
// execute query
Cursor cursor = db.rawQuery(query,null);
Garment garment = new Garment();
// try to read the Garment result
try {
if (cursor.moveToFirst()) {
garment = createGarmentFromResultQuery(cursor);
}
} catch (Exception e) {
Log.d("getGarmentById", "Error while getting garment by id");
e.printStackTrace();
}
db.close();
return garment;
}
/**
* Method to get the type of a Garment based on its Id
* @param garmentId
* @return
*/
public String getGarmentTypeByGarmentId(int garmentId) {
db = dataBaseHelper.getWritableDatabase();
// query string
String query = "SELECT * FROM " + StringValues.TABLE_GARMENT
+ " WHERE " + StringValues.COLUMN_IDGARMENT
+ " = \"" + garmentId + "\"";
// execute query
Cursor cursor = db.rawQuery(query,null);
Garment garment = new Garment();
// try to read the Garment result
try {
if (cursor.moveToFirst()) {
garment = createGarmentFromResultQuery(cursor);
}
} catch (Exception e) {
Log.d("getGarmentById", "Error while getting garment by id");
e.printStackTrace();
}
db.close();
return garment.getGarmentType();
}
/**
* Method to update the garmentType of a garment based on its id
* @param idGarment
* @param garmentType
*/
public void setGarmentType(int idGarment, String garmentType) {
db = dataBaseHelper.getWritableDatabase();
// set garmentType value in a ContentValues
ContentValues values = new ContentValues();
values.put(StringValues.COLUMN_GARMENTTYPE, garmentType);
// execute the update in DB
db.update(StringValues.TABLE_GARMENT, values, StringValues.COLUMN_IDGARMENT + "=" + idGarment, null);
db.close();
}
/**
* Method to get a Basket object correspondent to a Garment
* @param idGarment
* @return
*/
public Basket getBasketByGarmentId(int idGarment) {
db = dataBaseHelper.getWritableDatabase();
// get the garment object to access the basketId value
Garment currentGarment = getGarmentById(idGarment);
// get the basket via query
String query = "SELECT * FROM " + StringValues.TABLE_BASKET
+ " WHERE " + StringValues.COLUMN_IDBASKET
+ " = \"" + currentGarment.getIdBasket() + "\"";
// execute query
Cursor cursor = db.rawQuery(query,null);
Basket basket = null;
if (cursor.moveToFirst()) {
// get values and create object
int idBasket = cursor.getInt(cursor.getColumnIndex(StringValues.COLUMN_IDBASKET));
String basketName = cursor.getString(cursor.getColumnIndex(StringValues.COLUMN_BASKETNAME));
String basketDescription = cursor.getString(cursor.getColumnIndex(StringValues.COLUMN_BASKETDESCRIPTION));
basket = new Basket(idBasket, basketName, basketDescription);
}
db.close();
return basket;
}
/**
* Method to set the idBasket to a garment object
* @param idGarment
* @param idBasket
*/
public void setBasket(int idGarment,int idBasket) {
db = dataBaseHelper.getWritableDatabase();
// set idBasket value in a ContentValues
ContentValues values = new ContentValues();
values.put(StringValues.COLUMN_IDBASKET, idBasket);
// execute the update in DB
db.update(StringValues.TABLE_GARMENT, values, StringValues.COLUMN_IDGARMENT + "=" + idGarment, null);
db.close();
}
/**
* Method to get the usage percentage of a garment by its id
* @param idGarment
* @return
*/
public int getUsagePercentage(int idGarment){
Garment currentGarment = getGarmentById(idGarment);
return currentGarment.getUsagePercentage();
}
/**
* Method to update the usagePercentage of a garment by its id
* @param idGarment
* @param newUsagePercentage
*/
public void setUsagePercentage(int idGarment, int newUsagePercentage) {
db = dataBaseHelper.getWritableDatabase();
// set garmentType value in a ContentValues
ContentValues values = new ContentValues();
values.put(StringValues.COLUMN_USAGE, newUsagePercentage);
// execute the update in DB
db.update(StringValues.TABLE_GARMENT, values, StringValues.COLUMN_IDGARMENT + "=" + idGarment, null);
db.close();
}
/**
* Method to delete a garment based on its id
* @param idGarment
*/
public void deleteGarment(int idGarment) {
db = dataBaseHelper.getWritableDatabase();
db.delete(StringValues.TABLE_GARMENT, StringValues.COLUMN_IDGARMENT + "=" + idGarment, null);
db.close();
}
/**
* Method to set the usagePercentage of a garment to 0 (clean)
* @param idGarment
*/
public void cleanGarmentByGarmentId(int idGarment) {
db = dataBaseHelper.getWritableDatabase();
// set usagePercentage value in a ContentValues
ContentValues values = new ContentValues();
values.put(StringValues.COLUMN_USAGE, 0);
// execute the update in DB
db.update(StringValues.TABLE_GARMENT, values, StringValues.COLUMN_IDGARMENT + "=" + idGarment, null);
db.close();
}
/**
* Method to get all the garments that are not 100% used based on its garment type
* @param garmentType
* @return
*/
public List<Garment> getAvailableGarmentsByGarmentType(String garmentType) {
db = dataBaseHelper.getWritableDatabase();
// query string
String query = "SELECT * FROM " + StringValues.TABLE_GARMENT
+ " WHERE " + StringValues.COLUMN_GARMENTTYPE
+ " = \"" + garmentType + "\"";
// execute query
Cursor cursor = db.rawQuery(query,null);
// initialize object list
List<Garment> garments = new ArrayList<Garment>();
try {
if (cursor.moveToFirst()) {
// iterate through all the lines of the result
while (!cursor.isAfterLast()) {
Garment currentGarment = createGarmentFromResultQuery(cursor);
// add to the list the garments that are not 100% used
if(currentGarment.getUsagePercentage() < 100) {
garments.add(currentGarment);
}
// move to next query result
cursor.moveToNext();
}
}
} catch (Exception e) {
Log.d("getAvailableGarments", "Error while getting av. garments");
e.printStackTrace();
}
db.close();
return garments;
}
/**
* Method to get the dirty garments (100% usage) from a basket
* @param idBasket
* @return
*/
public List<Garment> getDirtyGarmentsByBasketId(int idBasket) {
db = dataBaseHelper.getWritableDatabase();
// query string
String query = "SELECT * FROM " + StringValues.TABLE_GARMENT
+ " WHERE " + StringValues.COLUMN_IDBASKET
+ " = \"" + idBasket + "\"";
// execute query
Cursor cursor = db.rawQuery(query,null);
// initialize object list
List<Garment> garments = new ArrayList<Garment>();
try {
if (cursor.moveToFirst()) {
// iterate through all the lines of the result
while (!cursor.isAfterLast()) {
Garment currentGarment = createGarmentFromResultQuery(cursor);
// add to the list only the garments that are 100% used
if(currentGarment.getUsagePercentage() == 100) {
garments.add(currentGarment);
}
// move to next query result
cursor.moveToNext();
}
}
} catch (Exception e) {
Log.d("getDirtyGarments", "Error while getting d. garments");
e.printStackTrace();
}
db.close();
return garments;
}
/**
* Method to clean (set usage to 0) all garments by basket id
* @param idBasket
*/
public void cleanAllGarmentsByBasketId(int idBasket) {
db = dataBaseHelper.getWritableDatabase();
// query string
String query = "SELECT * FROM " + StringValues.TABLE_GARMENT
+ " WHERE " + StringValues.COLUMN_IDBASKET
+ " = \"" + idBasket + "\"";
// execute query
Cursor cursor = db.rawQuery(query,null);
// initialize object list
List<Garment> garments = new ArrayList<Garment>();
try {
if (cursor.moveToFirst()) {
// iterate through all the lines of the result
while (!cursor.isAfterLast()) {
Garment currentGarment = createGarmentFromResultQuery(cursor);
cleanGarmentByGarmentId(currentGarment.getIdGarment());
// move to next query result
cursor.moveToNext();
}
}
} catch (Exception e) {
Log.d("getDirtyGarments", "Error while getting d. garments");
e.printStackTrace();
}
db.close();
}
/**
* Method to create a new basket
* @param basket
*/
public void addBasket(Basket basket) {
db = dataBaseHelper.getWritableDatabase();
// add all the values in a ContentValues
ContentValues values = new ContentValues();
values.put(StringValues.COLUMN_IDBASKET, basket.getIdBasket());
values.put(StringValues.COLUMN_BASKETNAME, basket.getBasketName());
values.put(StringValues.COLUMN_BASKETDESCRIPTION, basket.getBasketDescription());
// insert the values into a new row in DB
db.insert(StringValues.TABLE_BASKET, null, values);
db.close();
}
/**
* Method to create a Garment object from a Cursor of a query result
* @param cursor
* @return
*/
private Garment createGarmentFromResultQuery(Cursor cursor) {
// get all the attributes from the current line of the query result
int idGarment = cursor.getInt(cursor.getColumnIndex(StringValues.COLUMN_IDGARMENT));
String garmentName = cursor.getString(cursor.getColumnIndex(StringValues.COLUMN_GARMENTNAME));
String garmentType = cursor.getString(cursor.getColumnIndex(StringValues.COLUMN_GARMENTTYPE));
int usagePercentage = cursor.getInt(cursor.getColumnIndex(StringValues.COLUMN_USAGE));
Date lastUsage = DateFormatter.createDateFromString(
cursor.getString(cursor.getColumnIndex(StringValues.COLUMN_LASTUSAGE)));
byte[] garmentPicture = cursor.getBlob(cursor.getColumnIndex(StringValues.COLUMN_GARMENTPCITURE));
boolean isInBasket = cursor.getInt(cursor.getColumnIndex(StringValues.COLUMN_ISINBASKET)) > 0;
int idBasket = cursor.getInt(cursor.getColumnIndex(StringValues.COLUMN_IDBASKET));
// create a new Garment object
Garment currentGarment = new Garment(idGarment,garmentName,
garmentType,usagePercentage,lastUsage,
BitmapConverter.getImage(garmentPicture), isInBasket, idBasket);
return currentGarment;
}
}
| [
"cesars90_@hotmail.com"
] | cesars90_@hotmail.com |
866f0c84d5e6c717d46ec5501db490b739d279cc | d5f09c7b0e954cd20dd613af600afd91b039c48a | /sources/net/lingala/zip4j/headers/VersionNeededToExtract.java | 1aa9d17998bf66e25c2b2349fad200509b59375b | [] | no_license | t0HiiBwn/CoolapkRelease | af5e00c701bf82c4e90b1033f5c5f9dc8526f4b3 | a6a2b03e32cde0e5163016e0078391271a8d33ab | refs/heads/main | 2022-07-29T23:28:35.867734 | 2021-03-26T11:41:18 | 2021-03-26T11:41:18 | 345,290,891 | 5 | 2 | null | null | null | null | UTF-8 | Java | false | false | 327 | java | package net.lingala.zip4j.headers;
public enum VersionNeededToExtract {
DEFAULT(10),
DEFLATE_COMPRESSED(20),
ZIP_64_FORMAT(45),
AES_ENCRYPTED(51);
private int code;
private VersionNeededToExtract(int i) {
this.code = i;
}
public int getCode() {
return this.code;
}
}
| [
"test@gmail.com"
] | test@gmail.com |
dc64add0e367138cd32949196ee7cb29941e99c0 | 7480717e8866db20d8738742630b1733410d6d2b | /ApacheDatasets/PIG-0.9.0/pig-0.8.1/test/org/apache/pig/test/TestExampleGenerator.java | 2dee27b5674c5b7c829affb124ab11092bd7993a | [
"Apache-2.0"
] | permissive | abcdefghiklk/SeekChanges | 600ecffeceedbc2caf1672fc7bb553e37b00131a | 82103108425f22e2b535f43e424c23dbdea3b6f2 | refs/heads/master | 2020-04-06T07:02:43.703757 | 2016-08-17T10:43:59 | 2016-08-17T10:43:59 | 57,231,049 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 6,169 | java | /*
* 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.pig.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Random;
import junit.framework.TestCase;
import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.DataBag;
import org.apache.pig.impl.PigContext;
import org.apache.pig.impl.io.FileLocalizer;
import org.apache.pig.impl.logicalLayer.LogicalOperator;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class TestExampleGenerator extends TestCase {
static MiniCluster cluster = MiniCluster.buildCluster();
PigContext pigContext = new PigContext(ExecType.MAPREDUCE, cluster
.getProperties());
Random rand = new Random();
int MAX = 100;
String A, B;
{
try {
pigContext.connect();
} catch (ExecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Before
public void setUp() throws Exception {
File fileA, fileB;
fileA = File.createTempFile("dataA", ".dat");
fileB = File.createTempFile("dataB", ".dat");
writeData(fileA);
writeData(fileB);
A = "'" + FileLocalizer.hadoopify(fileA.toString(), pigContext) + "'";
B = "'" + FileLocalizer.hadoopify(fileB.toString(), pigContext) + "'";
System.out.println("A : " + A + "\n" + "B : " + B);
System.out.println("Test data created.");
fileA.deleteOnExit();
fileB.deleteOnExit();
}
@AfterClass
public static void oneTimeTearDown() throws Exception {
cluster.shutDown();
}
private void writeData(File dataFile) throws Exception {
// File dataFile = File.createTempFile(name, ".dat");
FileOutputStream dat = new FileOutputStream(dataFile);
Random rand = new Random();
for (int i = 0; i < MAX; i++)
dat.write((rand.nextInt(10) + "\t" + rand.nextInt(10) + "\n")
.getBytes());
dat.close();
}
@Test
public void testFilter() throws Exception {
PigServer pigserver = new PigServer(pigContext);
String query = "A = load " + A
+ " using PigStorage() as (x : int, y : int);\n";
pigserver.registerQuery(query);
query = "B = filter A by x > 10;";
pigserver.registerQuery(query);
Map<LogicalOperator, DataBag> derivedData = pigserver.getExamples("B");
assertTrue(derivedData != null);
}
@Test
public void testForeach() throws ExecException, IOException {
PigServer pigServer = new PigServer(pigContext);
pigServer.registerQuery("A = load " + A
+ " using PigStorage() as (x : int, y : int);");
pigServer.registerQuery("B = foreach A generate x + y as sum;");
Map<LogicalOperator, DataBag> derivedData = pigServer.getExamples("B");
assertTrue(derivedData != null);
}
@Test
public void testJoin() throws IOException, ExecException {
PigServer pigServer = new PigServer(pigContext);
pigServer.registerQuery("A1 = load " + A + " as (x, y);");
pigServer.registerQuery("B1 = load " + B + " as (x, y);");
pigServer.registerQuery("E = join A1 by x, B1 by x;");
Map<LogicalOperator, DataBag> derivedData = pigServer.getExamples("E");
assertTrue(derivedData != null);
}
@Test
public void testCogroupMultipleCols() throws Exception {
PigServer pigServer = new PigServer(pigContext);
pigServer.registerQuery("A = load " + A + " as (x, y);");
pigServer.registerQuery("B = load " + B + " as (x, y);");
pigServer.registerQuery("C = cogroup A by (x, y), B by (x, y);");
Map<LogicalOperator, DataBag> derivedData = pigServer.getExamples("C");
assertTrue(derivedData != null);
}
@Test
public void testCogroup() throws Exception {
PigServer pigServer = new PigServer(pigContext);
pigServer.registerQuery("A = load " + A + " as (x, y);");
pigServer.registerQuery("B = load " + B + " as (x, y);");
pigServer.registerQuery("C = cogroup A by x, B by x;");
Map<LogicalOperator, DataBag> derivedData = pigServer.getExamples("C");
assertTrue(derivedData != null);
}
@Test
public void testGroup() throws Exception {
PigServer pigServer = new PigServer(pigContext);
pigServer.registerQuery("A = load " + A.toString() + " as (x, y);");
pigServer.registerQuery("B = group A by x;");
Map<LogicalOperator, DataBag> derivedData = pigServer.getExamples("B");
assertTrue(derivedData != null);
}
@Test
public void testUnion() throws Exception {
PigServer pigServer = new PigServer(pigContext);
pigServer.registerQuery("A = load " + A.toString() + " as (x, y);");
pigServer.registerQuery("B = load " + B.toString() + " as (x, y);");
pigServer.registerQuery("C = union A, B;");
Map<LogicalOperator, DataBag> derivedData = pigServer.getExamples("C");
assertTrue(derivedData != null);
}
}
| [
"Qiuchi.Li@open.ac.uk"
] | Qiuchi.Li@open.ac.uk |
6768e9c407410bef1be41d39e413228b840bb96b | a464211147d0fd47d2be533a5f0ced0da88f75f9 | /EvoSuiteTests/evosuite_3/evosuite-tests/org/mozilla/javascript/NativeJavaClass_ESTest.java | 34ae5ce9b5d3875d7e8a97af1fb4527e96f6b1fb | [
"MIT"
] | permissive | LASER-UMASS/Swami | 63016a6eccf89e4e74ca0ab775e2ef2817b83330 | 5bdba2b06ccfad9d469f8122c2d39c45ef5b125f | refs/heads/master | 2022-05-19T12:22:10.166574 | 2022-05-12T13:59:18 | 2022-05-12T13:59:18 | 170,765,693 | 11 | 5 | NOASSERTION | 2022-05-12T13:59:19 | 2019-02-14T22:16:01 | HTML | UTF-8 | Java | false | false | 6,263 | java | /*
* This file was automatically generated by EvoSuite
* Wed Aug 01 22:00:47 GMT 2018
*/
package org.mozilla.javascript;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
import org.mozilla.javascript.BaseFunction;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Delegator;
import org.mozilla.javascript.ImporterTopLevel;
import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.NativeJavaClass;
import org.mozilla.javascript.NativeJavaObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.TopLevel;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class NativeJavaClass_ESTest extends NativeJavaClass_ESTest_scaffolding {
@Test(timeout = 4000)
public void test0() throws Throwable {
Context context0 = Context.enter();
ImporterTopLevel importerTopLevel0 = new ImporterTopLevel(context0, true);
TopLevel.Builtins topLevel_Builtins0 = TopLevel.Builtins.Object;
BaseFunction baseFunction0 = importerTopLevel0.getBuiltinCtor(topLevel_Builtins0);
Class<Delegator> class0 = Delegator.class;
NativeJavaClass nativeJavaClass0 = new NativeJavaClass(baseFunction0, class0, true);
boolean boolean0 = nativeJavaClass0.has("error reporter", (Scriptable) baseFunction0);
assertFalse(boolean0);
}
@Test(timeout = 4000)
public void test1() throws Throwable {
NativeJavaClass nativeJavaClass0 = new NativeJavaClass();
// Undeclared exception!
try {
nativeJavaClass0.getIds();
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.mozilla.javascript.NativeJavaClass", e);
}
}
@Test(timeout = 4000)
public void test2() throws Throwable {
NativeJavaClass nativeJavaClass0 = new NativeJavaClass();
Class<Delegator> class0 = Delegator.class;
Object object0 = nativeJavaClass0.getDefaultValue(class0);
assertSame(object0, nativeJavaClass0);
}
@Test(timeout = 4000)
public void test3() throws Throwable {
NativeJavaClass nativeJavaClass0 = new NativeJavaClass();
double double0 = Context.toNumber(nativeJavaClass0);
assertEquals(Double.NaN, double0, 0.01);
}
@Test(timeout = 4000)
public void test4() throws Throwable {
NativeJavaClass nativeJavaClass0 = new NativeJavaClass();
// Undeclared exception!
try {
nativeJavaClass0.getDefaultValue((Class<?>) null);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.mozilla.javascript.NativeJavaClass", e);
}
}
@Test(timeout = 4000)
public void test5() throws Throwable {
Context context0 = Context.enter();
ImporterTopLevel importerTopLevel0 = new ImporterTopLevel(context0, true);
TopLevel.Builtins topLevel_Builtins0 = TopLevel.Builtins.Object;
BaseFunction baseFunction0 = importerTopLevel0.getBuiltinCtor(topLevel_Builtins0);
Class<Delegator> class0 = Delegator.class;
NativeJavaClass nativeJavaClass0 = new NativeJavaClass(baseFunction0, class0, true);
NativeArray nativeArray0 = null;
try {
nativeArray0 = new NativeArray(context0.emptyArgs);
// fail("Expecting exception: NullPointerException");
// Unstable assertion
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.mozilla.javascript.NativeArray", e);
}
}
@Test(timeout = 4000)
public void test6() throws Throwable {
ContextFactory contextFactory0 = ContextFactory.getGlobal();
Context context0 = contextFactory0.enterContext();
ImporterTopLevel importerTopLevel0 = new ImporterTopLevel(context0);
TopLevel.NativeErrors topLevel_NativeErrors0 = TopLevel.NativeErrors.ReferenceError;
BaseFunction baseFunction0 = importerTopLevel0.getNativeErrorCtor(topLevel_NativeErrors0);
Class<String> class0 = String.class;
NativeJavaClass nativeJavaClass0 = new NativeJavaClass(baseFunction0, class0);
// Undeclared exception!
try {
nativeJavaClass0.get("error reporter", (Scriptable) baseFunction0);
fail("Expecting exception: RuntimeException");
} catch(RuntimeException e) {
//
// Java class \"java.lang.String\" has no public instance field or method named \"error reporter\".
//
verifyException("org.mozilla.javascript.DefaultErrorReporter", e);
}
}
@Test(timeout = 4000)
public void test7() throws Throwable {
ContextFactory contextFactory0 = ContextFactory.getGlobal();
Context context0 = contextFactory0.enterContext();
ImporterTopLevel importerTopLevel0 = new ImporterTopLevel(context0);
TopLevel.NativeErrors topLevel_NativeErrors0 = TopLevel.NativeErrors.ReferenceError;
BaseFunction baseFunction0 = importerTopLevel0.getNativeErrorCtor(topLevel_NativeErrors0);
Class<String> class0 = String.class;
NativeJavaClass nativeJavaClass0 = new NativeJavaClass(baseFunction0, class0);
Object[] objectArray0 = new Object[1];
objectArray0[0] = (Object) nativeJavaClass0;
NativeJavaObject nativeJavaObject0 = (NativeJavaObject)nativeJavaClass0.call(context0, nativeJavaClass0, nativeJavaClass0, objectArray0);
assertEquals("JavaObject", nativeJavaObject0.getClassName());
}
@Test(timeout = 4000)
public void test8() throws Throwable {
NativeJavaClass nativeJavaClass0 = new NativeJavaClass();
String string0 = nativeJavaClass0.getClassName();
assertEquals("JavaClass", string0);
}
}
| [
"mmotwani@cs.umass.edu"
] | mmotwani@cs.umass.edu |
7262b17ba404321c3af570092e2b81ba84dbe6ff | b50101521ecfb368496a6d11c1774d0773fd62df | /src/server/status/db/SortedList.java | 270c67c604d8d1dda83262b4340006b66075113d | [] | no_license | johvik/server_status | 508e7089e80c332db0567da85f396c8a4dfc2b49 | 06ac6e5c525f413442f08652ae5ad51728220727 | refs/heads/master | 2021-01-22T12:02:37.153164 | 2014-05-09T17:41:50 | 2014-05-09T17:41:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,586 | java | package server.status.db;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
public class SortedList<E extends Comparable<E>> implements Collection<E>,
Iterable<E> {
private ArrayList<E> list = new ArrayList<E>();
@Override
public boolean add(E e) {
int index = Collections.binarySearch(list, e);
if (index < 0) {
list.add((-index) - 1, e);
return true;
}
return false;
}
@Override
public boolean addAll(Collection<? extends E> c) {
int oldSize = list.size();
for (E e : c) {
add(e);
}
return oldSize != list.size();
}
@Override
public void clear() {
list.clear();
}
@Override
public boolean contains(Object o) {
@SuppressWarnings("unchecked")
int index = Collections.binarySearch(list, (E) o);
return index >= 0;
}
@Override
public boolean containsAll(Collection<?> c) {
for (Object o : c) {
if (!contains(o)) {
return false;
}
}
return true;
}
/**
* Finds object in the list.
*
* @param e
* Object to find.
* @return Instance of e in list or null.
*/
public E find(E e) {
int index = Collections.binarySearch(list, e);
if (index >= 0) {
return list.get(index);
}
return null;
}
public E get(int index) {
return list.get(index);
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
/**
* Gets the index of element e.
*
* @param e
* Element to find
* @return Index of element or -1 if not found.
*/
public int indexOf(E e) {
int index = Collections.binarySearch(list, e);
if (index >= 0) {
return index;
}
return -1;
}
@Override
public Iterator<E> iterator() {
return list.iterator();
}
@Override
public boolean remove(Object o) {
@SuppressWarnings("unchecked")
int index = Collections.binarySearch(list, (E) o);
if (index >= 0) {
list.remove(index);
return true;
}
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
int oldSize = list.size();
for (Object o : c) {
remove(o);
}
return oldSize != list.size();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public int size() {
return list.size();
}
@Override
public Object[] toArray() {
return list.toArray();
}
@Override
public <T> T[] toArray(T[] array) {
return list.toArray(array);
}
public boolean update(E e) {
int index = Collections.binarySearch(list, e);
if (index >= 0) {
list.set(index, e);
return true;
}
return false;
}
}
| [
"john.viklund@gmail.com"
] | john.viklund@gmail.com |
cd64f22b5801c2ba6631fbd295ec979a68de81bb | 6378cd7f9e5ca4e8e3eacad55fe9053d4ed65511 | /src/interfaces/IOBBank.java | 2b34997605e79674bc42d178e73fc22e1ef7be11 | [] | no_license | Vinay9190/SectionFInheritance | 1e148adae6f2c007eb084368e50d2cbb20638804 | 383209e5b8a4ee71fb02c93fb215b4275226186f | refs/heads/master | 2022-12-09T22:01:55.125521 | 2020-09-07T17:47:00 | 2020-09-07T17:47:00 | 290,124,347 | 1 | 0 | null | 2020-08-25T05:43:11 | 2020-08-25T05:43:10 | null | UTF-8 | Java | false | false | 514 | java | package interfaces;
public interface IOBBank {
// for inheriting class
// the extends keyword
// for inherinting interfaces we use:
// the implements keyword
class IOBBank implements Bank {
@Override
public void createAccount() {
System.out.println(" ASK FOR NAME,AGE, EMAIL");
}
}
class SBIBank implements Bank, ATM {
@Override
public void createAccount() {
System.out.println("ASK ONLY FOR NAME" );
}
}
}
| [
"vinay.yadav_cs19@gla.ac.in"
] | vinay.yadav_cs19@gla.ac.in |
b52fb334dd356c33b7e7e9fb2990053748eb72c1 | 6754d18ec15386da4c646a26178ef29c5db7697d | /Java/CurrencyConverter/src/com/company/Currency.java | e6c97181ef3a7d3a871e79c8dd7aa3f25e418611 | [] | no_license | Roobun/SomeProjects | bd8e621a01c151ecac2044e261b3256f30c91fc9 | adc8efb7836f3907bc204f1ea188a96f324dcf5a | refs/heads/master | 2020-03-29T06:18:04.950580 | 2018-09-22T13:26:42 | 2018-09-22T13:26:42 | 149,618,656 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 590 | java | package com.company;
public class Currency {
String CharCode;
int Nominal;
String Name;
double Value;
public Currency(String OuterCharCode, int OuterNominal,
String OuterName, double OuterValue) {
this.CharCode = OuterCharCode;
this.Nominal = OuterNominal;
this.Name = OuterName;
this.Value = OuterValue;
}
public int getNominal() {
return this.Nominal;
}
public String getName() {
return this.Name;
}
public double getValue() {
return this.Value;
}
}
| [
"nskrim13@mail.ru"
] | nskrim13@mail.ru |
3dc2bc3991ab127df2e69c686f46e278731299ea | cf9ec4a44ea26d5b3fc21c335a2c71c08abcb49a | /src/algorithms/com/guan/hunan/GraphClient.java | a1b648fe251986988869e2486fbf266e20cdebf9 | [] | no_license | zhongwen7710/algorithm | 22b8ba860ae84f5b9bca6c7e6611a4de982150e6 | 5735237dc48dffa6c02fc982756e1c39978690dd | refs/heads/master | 2021-01-18T17:15:16.523909 | 2020-12-13T07:35:39 | 2020-12-13T07:35:39 | 23,423,697 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,968 | java | package algorithms.com.guan.hunan;
import algorithms.com.guan.stdlib.In;
import algorithms.com.guan.stdlib.StdOut;
/*************************************************************************
* Compilation: javac GraphClient.java
* Execution: java GraphClient graph.txt
* Dependencies: Graph.java
*
* Typical graph-processing code.
*
* % java GraphClient tinyG.txt
* 13 13
* 0: 6 2 1 5
* 1: 0
* 2: 0
* 3: 5 4
* 4: 5 6 3
* 5: 3 4 0
* 6: 0 4
* 7: 8
* 8: 7
* 9: 11 10 12
* 10: 9
* 11: 9 12
* 12: 11 9
*
* vertex of maximum degree = 4
* average degree = 2
* number of self loops = 0
*
*************************************************************************/
public class GraphClient {
// degree of v
public static int degree(Graph G, int v) {
int degree = 0;
for (int w : G.adj(v)) degree++;
return degree;
}
// maximum degree
public static int maxDegree(Graph G) {
int max = 0;
for (int v = 0; v < G.V(); v++)
if (degree(G, v) > max)
max = degree(G, v);
return max;
}
// average degree
public static int avgDegree(Graph G) {
// each edge incident on two vertices
return 2 * G.E() / G.V();
}
// number of self-loops
public static int numberOfSelfLoops(Graph G) {
int count = 0;
for (int v = 0; v < G.V(); v++)
for (int w : G.adj(v))
if (v == w) count++;
return count/2; // self loop appears in adjacency list twice
}
public static void main(String[] args) {
In in = new In(args[0]);
Graph G = new Graph(in);
StdOut.println(G);
StdOut.println("vertex of maximum degree = " + maxDegree(G));
StdOut.println("average degree = " + avgDegree(G));
StdOut.println("number of self loops = " + numberOfSelfLoops(G));
}
} | [
"zhongwen7710@126.com"
] | zhongwen7710@126.com |
de61115778ad9d4b9b717c3a6307981442de2aa2 | 7195a8f1125c55d42c5b6fb0a820ca055583031a | /modules/andes-core/common/src/main/java/org/wso2/andes/messaging/util/Lexicon.java | cc94d819d30c365e5e6a30c7f16ae41194197e0f | [
"Apache-2.0"
] | permissive | wso2/andes | 355d3a3b94ee376ae1bef01871216925199f9065 | 85434f648e56ce5f88cd5abcc6db738edce90af9 | refs/heads/master | 2023-08-16T09:55:41.020956 | 2023-06-07T08:40:22 | 2023-06-07T08:40:22 | 20,559,270 | 38 | 124 | Apache-2.0 | 2023-06-07T07:07:35 | 2014-06-06T10:04:24 | Java | UTF-8 | Java | false | false | 2,619 | java | /*
*
* 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.wso2.andes.messaging.util;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Lexicon
*
*/
public class Lexicon
{
private List<Token.Type> types;
private Token.Type eof;
public Lexicon()
{
this.types = new ArrayList<Token.Type>();
this.eof = null;
}
public Token.Type define(String name, String pattern)
{
Token.Type t = new Token.Type(name, pattern);
types.add(t);
return t;
}
public Token.Type eof(String name)
{
Token.Type t = new Token.Type(name, null);
eof = t;
return t;
}
public Lexer compile()
{
StringBuilder joined = new StringBuilder();
for (Token.Type t : types)
{
if (joined.length() > 0)
{
joined.append('|');
}
joined.append('(').append(t.getPattern()).append(')');
}
Pattern rexp = Pattern.compile(joined.toString());
return new Lexer(new ArrayList<Token.Type>(types), eof, rexp);
}
public static final void main(String[] args)
{
StringBuilder input = new StringBuilder();
for (String a : args)
{
if (input.length() > 0)
{
input.append(" ");
}
input.append(a);
}
Lexicon lxi = new Lexicon();
lxi.define("FOR", "for");
lxi.define("IF", "if");
lxi.define("LPAREN", "\\(");
lxi.define("RPAREN", "\\)");
lxi.define("ID", "[\\S]+");
lxi.define("WSPACE", "[\\s]+");
lxi.eof("EOF");
Lexer lx = lxi.compile();
for (Token t : lx.lex(input.toString()))
{
System.out.println(t);
}
}
}
| [
"shammi@Shammis-MacBook-Pro.local"
] | shammi@Shammis-MacBook-Pro.local |
d389a930036dbab2c7d9f4aabc97cb266b8c3a67 | 29b6a856a81a47ebab7bfdba7fe8a7b845123c9e | /dingtalk/java/src/main/java/com/aliyun/dingtalkdatacenter_1_0/models/GetAdministrativeLicensingRequest.java | 8930eb425ec897350f55586f6ec4dda1279f86f2 | [
"Apache-2.0"
] | permissive | aliyun/dingtalk-sdk | f2362b6963c4dbacd82a83eeebc223c21f143beb | 586874df48466d968adf0441b3086a2841892935 | refs/heads/master | 2023-08-31T08:21:14.042410 | 2023-08-30T08:18:22 | 2023-08-30T08:18:22 | 290,671,707 | 22 | 9 | null | 2021-08-12T09:55:44 | 2020-08-27T04:05:39 | PHP | UTF-8 | Java | false | false | 1,268 | java | // This file is auto-generated, don't edit it. Thanks.
package com.aliyun.dingtalkdatacenter_1_0.models;
import com.aliyun.tea.*;
public class GetAdministrativeLicensingRequest extends TeaModel {
@NameInMap("pageNumber")
public Integer pageNumber;
@NameInMap("pageSize")
public Integer pageSize;
@NameInMap("searchKey")
public String searchKey;
public static GetAdministrativeLicensingRequest build(java.util.Map<String, ?> map) throws Exception {
GetAdministrativeLicensingRequest self = new GetAdministrativeLicensingRequest();
return TeaModel.build(map, self);
}
public GetAdministrativeLicensingRequest setPageNumber(Integer pageNumber) {
this.pageNumber = pageNumber;
return this;
}
public Integer getPageNumber() {
return this.pageNumber;
}
public GetAdministrativeLicensingRequest setPageSize(Integer pageSize) {
this.pageSize = pageSize;
return this;
}
public Integer getPageSize() {
return this.pageSize;
}
public GetAdministrativeLicensingRequest setSearchKey(String searchKey) {
this.searchKey = searchKey;
return this;
}
public String getSearchKey() {
return this.searchKey;
}
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
a626492a96e1581afafa3380518e2722dec95c5b | 709a28bd394652b6211cda052caef70338b457da | /BubbleLayout/app/src/main/java/com/tc/bubblelayout/testrecylerview/GroupItemDecoration.java | 54e8fa91e5719e75445f57f38454f07db1fe52c6 | [] | no_license | ouyangpeng/BubbleLayout | aabd6418cbf61874d12d186a40b5ce0241a397c0 | 9df9014745f980fa9b7ce17a350dc6e20d073580 | refs/heads/master | 2022-03-28T03:13:36.415493 | 2019-12-26T08:07:53 | 2019-12-26T08:07:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,772 | java | package com.tc.bubblelayout.testrecylerview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.tc.bubblelayout.DensityUtil;
import java.util.List;
/**
* author: tc
* date: 2019/9/14 & 16:29
* version 1.0
* description 列表根据不同数据类型,拆分为多个群组进行布局显示的布局间隔绘制类
* item没有触发反馈
*
* @see IGroupSort
* modify by
*/
public class GroupItemDecoration extends AbstractGroupItemDecoration {
private int mCornerRadius;
public GroupItemDecoration(Context context, List list, int cornerRadius) {
super(context, list);
this.mCornerRadius = cornerRadius;
}
private void drawGroupCorner(Canvas canvas, View child, IGroupSort item, float[] corners) {
Path srcPath = new Path();
RectF rectF = new RectF(child.getLeft(), child.getTop(), child.getRight(), child.getBottom());
if (item != null) {
mPaint.setColor(mContext.getResources().getColor(item.getGroupBackgroundColorId()));
}
//默认无圆角
srcPath.addRoundRect(rectF, corners, Path.Direction.CCW);
canvas.drawPath(srcPath, mPaint);
}
@Override
public void onDrawWhenFirstGroupItem(Canvas canvas, View child, RecyclerView parent, RecyclerView.State state,
int adapterPosition, IGroupSort item) {
float[] corners = {mCornerRadius, mCornerRadius, mCornerRadius, mCornerRadius, 0, 0, 0, 0};
drawGroupCorner(canvas, child, item, corners);
}
@Override
public void onDrawWhenMiddleGroupItem(Canvas canvas, View child, RecyclerView parent, RecyclerView.State state,
int adapterPosition, IGroupSort item) {
float[] corners = {0, 0, 0, 0, 0, 0, 0, 0};
drawGroupCorner(canvas, child, item, corners);
}
@Override
public void onDrawWhenLastGroupItem(Canvas canvas, View child, RecyclerView parent, RecyclerView.State state, int
adapterPosition, IGroupSort item) {
float[] corners = {0, 0, 0, 0, mCornerRadius, mCornerRadius, mCornerRadius, mCornerRadius};
drawGroupCorner(canvas, child, item, corners);
}
@Override
public void onDrawWhenSingleGroupItem(Canvas canvas, View child, RecyclerView parent, RecyclerView.State state,
int adapterPosition, IGroupSort item) {
float[] corners = {mCornerRadius, mCornerRadius, mCornerRadius, mCornerRadius, mCornerRadius, mCornerRadius,
mCornerRadius, mCornerRadius};
drawGroupCorner(canvas, child, item, corners);
}
@Override
public void onDrawOverWhenFirstGroupItem(Canvas canvas, View child, RecyclerView parent, RecyclerView.State
state, int adapterPosition, IGroupSort item) {
}
@Override
public void onDrawOverWhenMiddleGroupItem(Canvas canvas, View child, RecyclerView parent, RecyclerView.State
state, int adapterPosition, IGroupSort item) {
}
@Override
public void onDrawOverWhenLastGroupItem(Canvas canvas, View child, RecyclerView parent, RecyclerView.State state,
int adapterPosition, IGroupSort item) {
}
@Override
public void onDrawOverWhenSingleGroupItem(Canvas canvas, View child, RecyclerView parent, RecyclerView.State
state, int adapterPosition, IGroupSort item) {
}
@Override
public void getItemOffsetsWhenFirstGroupItem(Rect outRect, View child, RecyclerView parent, RecyclerView.State
state, int adapterPosition, IGroupSort item) {
if (adapterPosition != 0) {
//第一个群组不加顶部间距
outRect.set(0, DensityUtil.dip2px(mContext, item.getGroupDividerSize()), 0, 0);
}
}
@Override
public void getItemOffsetsWhenMiddleGroupItem(Rect outRect, View child, RecyclerView parent, RecyclerView.State
state, int adapterPosition, IGroupSort item) {
outRect.set(0, 0, 0, 0);
}
@Override
public void getItemOffsetsWhenLastGroupItem(Rect outRect, View child, RecyclerView parent, RecyclerView.State
state, int adapterPosition, IGroupSort item) {
outRect.set(0, 0, 0, 0);
}
@Override
public void getItemOffsetsWhenSingleGroupItem(Rect outRect, View child, RecyclerView parent, RecyclerView.State
state, int adapterPosition, IGroupSort item) {
outRect.set(0, DensityUtil.dip2px(mContext, item.getGroupDividerSize()), 0, 0);
}
}
| [
"tangchao@oaserver.dw.gdbbk.com"
] | tangchao@oaserver.dw.gdbbk.com |
e64abe6af52fdb214131cd2f025a2b5983286001 | cb6c75eed28972d6c07d205fd6ebfeb04cb94f61 | /eclipse-workspace/APPTECH_JAVA2/src/lab8/Type4Demo.java | 3cebcf2088137554d7dac6d29002e213613cd356 | [] | no_license | chehuy97/JavaAptech | 9cf980bcf109a6503fed7a684b14ce92bea44736 | f3bbd231d2ab532b94a3beec07bc5270c15787f7 | refs/heads/master | 2020-03-29T06:24:28.485350 | 2018-09-20T14:41:38 | 2018-09-20T14:41:38 | 149,623,003 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,501 | java | package lab8;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Type4Demo {
public static void main(String[] args) {
Connection cn = null; // tao ket noi voi database
Statement st = null; // chay cau lenh sql
ResultSet rs = null; // chua ket qua tra ve
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");// lay ra dia chi Driver
cn = DriverManager.getConnection("jdbc:sqlserver://DESKTOP-VR6CH56\\SQLEXPRESS:1433;databaseName=QLSV", "sa","huy9101997");
//String sql = "select *from SinhVien";
String sql = "insert into SinhVien values ('MS07','Nguyen Van I',10);";
st = cn.createStatement();
// rs = st.executeQuery(sql);
// while (rs.next()) {
// System.out.printf(" %-5s %-15s %-5s \n", rs.getString(1), rs.getString(2), rs.getString(3));
// }
int n = st.executeUpdate(sql);
if(n>0) {
System.out.println("insert thanh cong");
}else {
System.out.println("insert khong thanh cong");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (st != null)
st.close();
if (cn != null)
cn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
| [
"chehuy97@gmail.com"
] | chehuy97@gmail.com |
bde612cb228a8269320c0ccdde2750a28e2f5b9f | c90fa18e878094746ca6ee0582accb33e85e870d | /demos/AndroidDataStorage/sharedpreferencestest/src/main/java/com/example/sharedpreferencestest/MainActivity.java | f2d4e7c419019816f96349bd26650386199c0738 | [] | no_license | TDCQZD/AndroidDev | f4beb684169be1c00ac121fea3867068baa16852 | 7a217c23547e44273e4f42b784026c257a145517 | refs/heads/master | 2020-04-27T23:39:17.044479 | 2019-03-10T06:09:33 | 2019-03-10T06:09:33 | 174,784,609 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,018 | java | package com.example.sharedpreferencestest;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btDataSave;
private Button btDataRead;
private TextView tvShow;
private SharedPreferences sp;
private SharedPreferences.Editor spe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = getPreferences(MODE_PRIVATE);
spe = sp.edit();
findViews();
}
private void findViews() {
btDataSave = (Button) findViewById(R.id.bt_Data_save);
btDataRead = (Button) findViewById(R.id.bt_Data_read);
tvShow = (TextView) findViewById(R.id.tv_show);
btDataSave.setOnClickListener(this);
btDataRead.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == btDataSave) {
saveData();
} else if (v == btDataRead) {
readData();
}
}
private void readData() {
String name = sp.getString("name", "");
String sex = sp.getString("sex", "");
int hight = sp.getInt("身高", 0);
Boolean b = sp.getBoolean("婚姻状况", false);
tvShow.setText("name:" + name + "\n" + "sex:" + sex + "\n" + "身高:" + hight + "\n" + "婚姻状况:" + b);
// Log.i("TAG", "MainActivity readData()--->" + name);
}
private void saveData() {
spe.putString("name", "张三");
spe.putString("sex", "张三");
spe.putInt("身高", 170);
spe.putBoolean("婚姻状况", false);
spe.commit();
Toast.makeText(MainActivity.this, "数据写入成功", Toast.LENGTH_SHORT).show();
}
}
| [
"ZDTDCQ@163.com"
] | ZDTDCQ@163.com |
3d1bbaee0a2ce84e495a1451798f795d90f67518 | cb074fc882112da644164c26c7ac8dab49dc22d1 | /src/logic/Trains/Restriction.java | 1fe382ccd471b19a3b89948e4c7b21fbc3ce8ce2 | [] | no_license | potockan/Trains | 6aeae277ef12fe072cfcf142074a5681834013f4 | c93e3eea9e9dea08f38bbf376b09c3e7abf7ffb0 | refs/heads/master | 2021-01-12T08:22:31.478717 | 2016-12-22T10:55:19 | 2016-12-22T10:55:19 | 76,557,759 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 458 | java | package logic.Trains;
/**
* Created by npotocka on 15.12.16.
*/
public class Restriction<V> {
private V min;
private V max;
public Restriction(V min, V max){
this.min = min;
this.max = max;
}
public V getMax() {
return max;
}
public V getMin() {
return min;
}
public void setMax(V max) {
this.max = max;
}
public void setMin(V min) {
this.min = min;
}
}
| [
"potockan@gmail.com"
] | potockan@gmail.com |
8a1bffe3a8e7e32aa85a4349ad4480e72f75e55c | 05f15ac1d30be14f1562edeade6117292c28530f | /eskyzdt-server/src/main/java/cn/eskyzdt/WebApplication.java | 684ae7ccf591201b0e8129e1101ab3889fbaf250 | [] | no_license | eskyzdt/eskyzdt | 57798bdc1961f7799b330228677868e527a9c87a | 4a28e1aceb77260df4504e57609af76ba8c8d0af | refs/heads/V1.0 | 2023-08-16T22:34:44.423083 | 2023-08-15T06:53:46 | 2023-08-15T06:53:46 | 206,766,628 | 1 | 0 | null | 2022-10-14T06:12:21 | 2019-09-06T10:03:01 | JavaScript | UTF-8 | Java | false | false | 443 | java | package cn.eskyzdt;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = {"cn.eskyzdt.modules.*.dao"}) //这里扫描的是dao的接口层
public class WebApplication {
public static void main(String[] args) {
SpringApplication.run(WebApplication.class);
}
}
| [
"eskyzdt@sina.com"
] | eskyzdt@sina.com |
f048f0de5e175bc85f279c1ce640812f1e9901ed | 8a4f548ff452adf851805fb2cf21b1dcc8ec0ee8 | /android/app/src/main/java/com/eproject/MainApplication.java | a95cf0eb6000b3d65a037cb665e504dc363f5fe8 | [] | no_license | samuelbrehm/eProject | 0d24315fedcb2d950ee75ae1466e320f4d115c98 | 3affdec8aa41c3c4537f395e011a8ef873e2f859 | refs/heads/master | 2020-03-27T05:25:20.050312 | 2018-08-24T21:24:30 | 2018-08-24T21:24:30 | 146,017,578 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,044 | java | package com.eproject;
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage()
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
| [
"samuelbrehm@gmail.com"
] | samuelbrehm@gmail.com |
137395c0c3a1201f54b1200c558362a49e4e0896 | cf2979c4b54a6f8cbd5a429b21f93d71e9d2a378 | /DroidUtils/src/main/java/rhcloud/com/droidutils/tabutil/tabutil/impl/OnAddTabDefaultImpl.java | 541a5f2a7114e4f6756643a3125e555cbe29bb45 | [] | no_license | Klauswk/DroidUtils | 645dc984c9b97d6f3625768ae1679ebb776f5d17 | f72446f598c61195c5b7290646f6c2810f372e96 | refs/heads/master | 2021-01-20T15:57:56.686891 | 2016-08-12T20:13:30 | 2016-08-12T20:13:30 | 65,158,039 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,246 | java | package rhcloud.com.droidutils.tabutil.tabutil.impl;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import rhcloud.com.droidutils.tabutil.tabutil.Tab;
import rhcloud.com.droidutils.tabutil.tabutil.TabBody;
import rhcloud.com.droidutils.tabutil.tabutil.TabFragment;
import rhcloud.com.droidutils.tabutil.tabutil.interfaces.OnAddTab;
import rhcloud.com.droidutils.tabutil.tabutil.interfaces.TabHeaderUpdater;
/**
* @author <a href="https://github.com/Klauswk">Klaus Klein</a>
* @version 1.0
* @since 1.0
*/
public class OnAddTabDefaultImpl implements OnAddTab {
private TabBody tabBody;
private TabHeaderUpdater updateTabHeader;
public OnAddTabDefaultImpl(TabBody tabBody, TabHeaderUpdater updateTabHeader) {
this.tabBody = tabBody;
this.updateTabHeader = updateTabHeader;
}
@Override
public Tab addTab(@NonNull TabFragment tabFragment){
return addTab(tabFragment,-1);
}
@Override
public Tab addTab(@NonNull TabFragment tabFragment , int position){
tabBody.addTab(tabFragment,position);
updateTabHeader.updateTabHeader();
return null;
}
@Override
public Tab addTab(@NonNull Fragment fragment){
return addTab(new TabFragment(fragment), -1);
}
@Override
public Tab addTab(@NonNull Fragment fragment, @Nullable String title){
return addTab(fragment,title,null);
}
@Override
public Tab addTab(@NonNull Fragment fragment, @Nullable String title , @Nullable Drawable drawable){
return addTab(new TabFragment(fragment,title,drawable), -1);
}
@Override
public Tab addTab(@NonNull Fragment fragment, int position){
return addTab(new TabFragment(fragment), position);
}
@Override
public Tab addTab(@NonNull Fragment fragment, @Nullable String title, int position){
return addTab(fragment,title,null,position);
}
@Override
public Tab addTab(@NonNull Fragment fragment, @Nullable String title , @Nullable Drawable drawable, int position){
return addTab(new TabFragment(fragment,title,drawable), position);
}
}
| [
"klauswk1@hotmail.com"
] | klauswk1@hotmail.com |
974845abe6bb8e516bce2c656c2e8c8a94b65383 | 66bde34f2af40afc55d3c7231cdf9a1da44a95e2 | /progressDialog/app/src/main/java/com/ultron/sahilpratap/progressdialog/MainActivity.java | bb6d01799a35f809738e13d08e43b8681a4e937e | [] | no_license | sahilpratap/resources_ASD | b81e373055eef2159cb1ba48979afa6bb7e7576c | d89c49128d7caeaa100f048b91cdf73456a480c7 | refs/heads/master | 2020-03-23T19:23:15.909466 | 2018-07-23T07:04:32 | 2018-07-23T07:04:32 | 141,100,107 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,269 | java | package com.ultron.sahilpratap.progressdialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button btn;
ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Sanju Movie");
pd.setMessage("Downloading....");
pd.setCancelable(false);
// pd.setCanceledOnTouchOutside(false);
pd.setButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
pd.show();
}
});
}
}
| [
"sahilpratap7200@gmail.com"
] | sahilpratap7200@gmail.com |
3c87c235cc1281079a5d7ac15f367acc67029104 | 7954758bc55ff16441c7892d5cab973c73de0db7 | /android/app/src/main/java/br/com/lifemove/utils/StringUtils.java | e9afe735ae90fe215adc9683cbc074e1d97fbe79 | [] | no_license | phsa/lifemove | f6cbbd32cad0de3c23c4cd76d5c2dcd0b24f22e4 | 952cdec968a1f2a7dad23e19e62d3e93102fad84 | refs/heads/master | 2020-07-07T04:23:20.498337 | 2019-12-03T18:20:28 | 2019-12-03T18:20:28 | 203,248,353 | 1 | 0 | null | 2019-12-03T18:20:30 | 2019-08-19T20:50:23 | Java | UTF-8 | Java | false | false | 632 | java | package br.com.lifemove.utils;
public class StringUtils {
public static final String EMPTY = "";
public static final String DEBUG_TAG = "DebuggingLifeMove";
public static final String SPORTS_EVENT_KEY = "event";
public static final String INVALID_USERNAME_PATTERN = "[^a-zA-Z_.0-9\\-]";
public static boolean checkEmail(String email) {
if (email != null) return email.matches("^[a-z0-9.]+@[a-z0-9]+\\.[a-z]+(\\.[a-z]+)?$");
else return false;
}
public static String valueOf(int resID) {
return LifeMoveApplicationUtils.getLifeMoveAppContext().getString(resID);
}
}
| [
"paulinho.h.s.a.spn@gmail.com"
] | paulinho.h.s.a.spn@gmail.com |
6856d532283898b71c1f21b4576ff882421a760a | b1ef5a31d6b9fb7ec22d0c680dd990c693c80df7 | /src/main/java/bsuir/ppvis/view/style/Titles.java | 88eeea0dd0ee60c9c7144dd430f81ab487694be8 | [] | no_license | DanilaSavkov/inventory-book-lab2 | dc5162be847e1ff09d23b74f97b759e2e0825ce2 | 307e3853e53b6e17b3e81aab8b7f943335feafca | refs/heads/main | 2023-04-21T23:34:40.921018 | 2021-05-25T22:32:42 | 2021-05-25T22:32:42 | 361,668,818 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,218 | java | package bsuir.ppvis.view.style;
public interface Titles {
String FILE_MENU_TITLE = "Файл";
String EDIT_MENU_TITLE = "Изменить";
String OPEN_FILE_TITLE = "Открыть";
String SAVE_FILE_TITLE = "Сохранить";
String ADD_TITLE = "Добавить";
String REMOVE_TITLE = "Удалить";
String SEARCH_TITLE = "Поиск";
String PRODUCT_NAME_TITLE = "Название продукта";
String FABRICATOR_NAME_TITLE = "Название производителя";
String FABRICATOR_NUMBER_TITLE = "УНП производителя";
String COUNT_ON_STORAGE_TITLE = "Количество на складе";
String STORAGE_ADDRESS_TITLE = "Адрес склада";
String ALL_RECORDS_TITLE = "Все записи";
String ADD_RECORD_TITLE = "Добавить запись";
String SEARCH_RECORDS_TITLE = "Найти записи";
String REMOVE_RECORDS_TITLE = "Удалить записи";
String SHOW_TITLE = "Показать";
String RECORDS_TOTAL_TITLE = "Всего записей";
String OK_TITLE = "Ок";
String CANCEL_TITLE = "Отмена";
String EMPTY_TABLE_TITLE = "Нет записей";
}
| [
"danik2002ig@gmail.com"
] | danik2002ig@gmail.com |
914f779078eaec947c9a942d76e148c14fc3b54e | 80cf2ebe9786c5ce8ca1b969e791e8800b2c4cba | /src/main/java/com/brs/oa/staff/entity/Staff.java | 99c2cdceb4f55ce99f168bb1a57b54a4f82fcc3c | [
"Apache-2.0"
] | permissive | tinyjjlin/glod | 2d2ef8c075914af93a71f726e0b1990ba4517ee8 | 7de4c33ac92c1cd0479809c197cb849ff7eab0a5 | refs/heads/master | 2020-04-09T17:56:20.755661 | 2019-03-11T22:48:28 | 2019-03-11T22:48:28 | 160,496,722 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,321 | java | package com.brs.oa.staff.entity;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author tiny lin
* @since 2018-12-04
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class Staff implements Serializable {
private static final long serialVersionUID = 1L;
@TableId
private Integer id;
private Integer empNo;
private String name;
private Integer deptNo;
private String email;
private LocalDate birthday;
private LocalDate hireDate;
private String nation;
private String politicsStatus;
private String highestDegree;
private String maritalStatus;
private String mobile;
private String currentAddress;
private String address;
/**
* 中华人民共和国身份证号
*/
private String nationIdcard;
private String position;
private Integer gender;
/**
* 员工头像
*/
private String picture;
/**
* 表创建时间
*/
private LocalDateTime gmtCreate;
/**
* 表修改时间
*/
private LocalDateTime gmtModified;
}
| [
"tinyjjlin@163.com"
] | tinyjjlin@163.com |
340e918d3a7424362831a9c5605c1ceeff23b6b0 | 3bcd26696ae26414d648f6d01285fb0b67d7cfcd | /BankABC/src/main/java/com/MainAppForRun.java | 324bac60705c4db3c8f3cfc1727c932d66d304b1 | [] | no_license | nooruli/demo | 30b8ed766298858fceed33b7e117835e5c051599 | e4a491909d8134d59dc1546a5d1e0cfa61243421 | refs/heads/master | 2020-04-22T08:54:13.341046 | 2019-02-12T05:10:08 | 2019-02-12T05:10:08 | 170,254,479 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 305 | java | package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MainAppForRun {
public static void main(String[] args) {
SpringApplication.run(MainAppForRun.class, args);
}
}
| [
"noorul.i@hcl.com"
] | noorul.i@hcl.com |
5e9932337afc32f2e1b79fb92b4879168a740834 | 579db55bd3610a4be6bd1b06905c4c0bad735e3d | /services/src/main/java/pl/funnyqrz/mappers/dto/ReportDto.java | 3b879c18f0a104cb61d51a35dd83a6ab61033311 | [] | no_license | macg20/funnyQuartz | 3e3150c428a60080bcd53eb62bc614571815defc | 3eee12761d559c1aa6ce8879575791f270055210 | refs/heads/master | 2021-07-04T16:54:32.881840 | 2018-03-23T19:54:42 | 2018-03-23T19:54:42 | 96,250,838 | 0 | 0 | null | 2018-03-30T17:53:50 | 2017-07-04T20:24:30 | Java | UTF-8 | Java | false | false | 401 | java | package pl.funnyqrz.mappers.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import java.math.BigInteger;
import java.time.LocalDate;
@Data
public class ReportDto {
private BigInteger id;
private String fileName;
@JsonSerialize(using =LocalDateSerializer.class)
private LocalDate date;
}
| [
"kossss1@o2.pl"
] | kossss1@o2.pl |
af2db553725c32d130c2df5fd478dbcb481be0a0 | 6b4b34c9ad78ed81eb019da8f5eb09e861ec630f | /Java OOP/classRoster/classRoster/src/main/java/com/dm/service/ClassRosterDuplicateIdException.java | bb8037e1f83a320100b265c9ffafc8d8ef0a318c | [] | no_license | janssenda/thenewcarag | 497440b3314491f9b87890505e48d4dd48396421 | beea1e1c777fd3bc332cc5e2ba7476926c706b85 | refs/heads/master | 2021-01-19T14:18:39.649854 | 2018-07-02T22:15:38 | 2018-07-02T22:15:38 | 100,893,528 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 531 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.dm.service;
/**
*
* @author danimaetrix
*/
public class ClassRosterDuplicateIdException extends Exception {
public ClassRosterDuplicateIdException(String message) {
super(message);
}
public ClassRosterDuplicateIdException(String message,
Throwable cause) {
super(message, cause);
}
}
| [
"janssenda@gmail.com"
] | janssenda@gmail.com |
da5211cf697d5935d226cae842f687d63a034316 | 034dd8550e48d4b7dfd26fae7bbbfe25a23706d0 | /subprojects/lensFlare/src/water/WaterRenderer.java | 560feeaa3c0ef9c221cc30ed2ab98ada1c2a03b4 | [] | no_license | dtrajko/lwjgl_game | 3182a970fc542dc1fb1e606f7c72349d8934e354 | 91e7e01930f411af3ddc545ce742c6eebf2f5d95 | refs/heads/master | 2021-05-12T03:02:43.863050 | 2020-05-01T23:36:35 | 2020-05-01T23:36:35 | 117,606,702 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,974 | java | package water;
import java.util.List;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector3f;
import openglObjects.Vao;
import textures.Texture;
import utils.ICamera;
import utils.MyFile;
import utils.OpenGlUtils;
public class WaterRenderer {
private static final MyFile DUDV_MAP = new MyFile("res", "waterDUDV.png");
private static final MyFile NORMAL_MAP = new MyFile("res", "normal.png");
// private static final float WAVE_SPEED = 0.03f;
private Vao quad;
private WaterShader shader;
private WaterFrameBuffers fbos;
private float moveFactor = 0;
private Texture dudvTexture;
private Texture normalMap;
public WaterRenderer(WaterFrameBuffers fbos) {
this.shader = new WaterShader();
this.fbos = fbos;
this.quad = QuadGenerator.generateQuad();
this.normalMap = Texture.newTexture(NORMAL_MAP).create();
this.dudvTexture = Texture.newTexture(DUDV_MAP).anisotropic().create();
}
public void render(List<WaterTile> water, ICamera camera, Vector3f lightDir) {
prepareRender(camera, lightDir);
for (WaterTile tile : water) {
Matrix4f modelMatrix = createModelMatrix(tile.getX(), tile.getHeight(), tile.getZ(), WaterTile.TILE_SIZE);
shader.modelMatrix.loadMatrix(modelMatrix);
GL11.glDrawElements(GL11.GL_TRIANGLES, quad.getIndexCount(), GL11.GL_UNSIGNED_INT, 0);
}
finish();
}
public void cleanUp() {
quad.delete();
dudvTexture.delete();
normalMap.delete();
fbos.cleanUp();
shader.cleanUp();
}
private void prepareRender(ICamera camera, Vector3f lightDir) {
shader.start();
shader.projectionMatrix.loadMatrix(camera.getProjectionMatrix());
shader.viewMatrix.loadMatrix(camera.getViewMatrix());
shader.cameraPosition.loadVec3(camera.getPosition());
moveFactor += 0.0005f;
moveFactor %= 1;
shader.moveFactor.loadFloat(moveFactor);
shader.lightDirection.loadVec3(lightDir);
quad.bind(0);
bindTextures();
doRenderSettings();
}
private void bindTextures() {
GL13.glActiveTexture(GL13.GL_TEXTURE0);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, fbos.getReflectionTexture());
GL13.glActiveTexture(GL13.GL_TEXTURE1);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, fbos.getRefractionTexture());
dudvTexture.bindToUnit(2);
normalMap.bindToUnit(3);
GL13.glActiveTexture(GL13.GL_TEXTURE4);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, fbos.getRefractionDepthTexture());
}
private void doRenderSettings() {
OpenGlUtils.enableDepthTesting(true);
OpenGlUtils.antialias(false);
OpenGlUtils.cullBackFaces(true);
OpenGlUtils.enableAlphaBlending();
}
private void finish() {
quad.unbind(0);
shader.stop();
}
private Matrix4f createModelMatrix(float x, float y, float z, float scale) {
Matrix4f modelMatrix = new Matrix4f();
Matrix4f.translate(new Vector3f(x, y, z), modelMatrix, modelMatrix);
Matrix4f.scale(new Vector3f(scale, scale, scale), modelMatrix, modelMatrix);
return modelMatrix;
}
}
| [
"dtrajko@gmail.com"
] | dtrajko@gmail.com |
bc26cd631f7e7e8909b0b060dbdef2f4a48997e2 | 357acd418a438aab82c3cdac8db073dd1b084d60 | /interior-device-gateway/src/main/java/com/konka/iot/interior/device/gateway/config/WebMvcConfig.java | bfb4a77147b742372c2f2e85d9115a00014be6cb | [] | no_license | xiexinyuan/kilink-v2 | bc6048004dc892f6235c65f2d33136897908c44d | 1013dde8097f78c962e9742284692d140657ccf4 | refs/heads/master | 2022-11-24T03:40:21.192321 | 2020-03-10T02:19:08 | 2020-03-10T02:19:08 | 216,464,120 | 0 | 2 | null | 2022-11-16T12:25:44 | 2019-10-21T02:47:52 | Java | UTF-8 | Java | false | false | 1,235 | java | package com.konka.iot.interior.device.gateway.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author xiexinyuan
* @version 1.0
* @createTime 2019-09-29 14:28
* @Description 配置拦截器
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
// @Autowired
// TuyaInterceptor tuyaInterceptor;
//
// // 配置拦截器
// @Override
// public void addInterceptors(InterceptorRegistry registry) {
// registry.addInterceptor(tuyaInterceptor)
// .addPathPatterns("/**")
// // 忽略swagger的请求
// .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
// }
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
| [
"1255083980@qq.com"
] | 1255083980@qq.com |
365ced70a60d6aa736d046111ef7082a1c1d1bd1 | 94b02ebcd4708a54350b47c00f772a7115e282b8 | /src/main/groovy/com/agilemaster/form/constants/FormCoreStaticMethod.java | 2fb21e60ff198555c5c61530944f1d259b72e9eb | [] | no_license | agilizer/junjie-cassandra | 222ffe8dd12fdd7bf9888d1110d0171b577daf1b | f083306833cf8e7a7ef51946ebae406386fe002d | refs/heads/master | 2021-01-19T21:45:06.116366 | 2016-06-22T09:14:46 | 2016-06-22T09:14:46 | 39,555,960 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 200 | java | package com.agilemaster.form.constants;
import java.util.UUID;
public class FormCoreStaticMethod {
public static String genUUID(){
return UUID.randomUUID().toString().replaceAll("-", "");
}
}
| [
"asdtiangxia@163.com"
] | asdtiangxia@163.com |
14429ebec3620fb5f7de32832f42aec9750213eb | c9a21954bb5f4de1893051405b5b95fcb1e8a973 | /app/src/main/java/com/tensor/dapavlov1/tensorfirststep/presentation/common/visual/SwitchGradient.java | e46f02307feb9c1b885eb13307871b0b1d4818fa | [] | no_license | CapitainMarkul/WeatherInfo | 37bbd106e69805cae26525431d7f5fb7ef393fd4 | b82527bd984d0ed9ec70a32d6430bb8158dbab03 | refs/heads/master | 2021-07-11T03:36:10.245119 | 2017-08-16T08:18:30 | 2017-08-16T08:18:30 | 100,246,270 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,363 | java | package com.tensor.dapavlov1.tensorfirststep.presentation.common.visual;
import android.graphics.drawable.Drawable;
import com.tensor.dapavlov1.tensorfirststep.App;
import com.tensor.dapavlov1.tensorfirststep.R;
/**
* Created by da.pavlov1 on 08.08.2017.
*/
public class SwitchGradient {
private static SwitchGradient instance;
private SwitchGradient() {
}
public static SwitchGradient getInstance() {
if (instance == null) {
instance = new SwitchGradient();
}
return instance;
}
public Drawable getBackgroung(String iconCode) {
if (iconCode.contains("c01d")) {
return App.getContext().getResources().getDrawable(R.drawable.background_gradient_cloud_sun, null);
} else if (iconCode.contains("c01n")) {
return App.getContext().getResources().getDrawable(R.drawable.background_gradient_night, null);
} else if (iconCode.contains("c02")
|| iconCode.contains("a")) {
return App.getContext().getResources().getDrawable(R.drawable.background_gradient_cloud_sun, null);
} else if (iconCode.contains("c04")) {
return App.getContext().getResources().getDrawable(R.drawable.background_gradient_cloud, null);
} else {
return App.getContext().getResources().getDrawable(R.drawable.background_gradient_rain, null);
}
// switch (iconCode.substring(0,1)){
// case
// case "t": return App.getContext().getResources().getDrawable(R.drawable.background_gradient_rain, null);
// case "d": return App.getContext().getResources().getDrawable(R.drawable.background_gradient_rain, null);
// case "s": return App.getContext().getResources().getDrawable(R.drawable.background_gradient_rain, null);
// }
}
// public ShapeDrawable createRandomGradient(int widthElement, int heightElement) {
// ShapeDrawable mDrawable = new ShapeDrawable(new RectShape());
// mDrawable.getPaint().setShader(new LinearGradient(0, 0, 0, 350,
// Color.rgb(genInt(), genInt(), genInt()), Color.parseColor("#80FFFFFF"),
// Shader.TileMode.REPEAT));
//
// return mDrawable;
// }
//
// private int genInt() {
// Random random = new Random();
// return random.nextInt(255);
// }
}
| [
"da.pavlov1@tensor.ru"
] | da.pavlov1@tensor.ru |
6e686cbd44c09769b897d58f0dd2e8c54c623507 | 5aaebaafeb75c7616689bcf71b8dd5ab2c89fa3b | /src/ANXGallery/sources/com/miui/gallery/cloudcontrol/ProfileCache.java | 1626206502c45f3c3b6edc02686bcb1abebc9f1b | [] | no_license | gitgeek4dx/ANXGallery9 | 9bf2b4da409ab16492e64340bde4836d716ea7ec | af2e3c031d1857fa25636ada923652b66a37ff9e | refs/heads/master | 2022-01-15T05:23:24.065872 | 2019-07-25T17:34:35 | 2019-07-25T17:34:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 17,432 | java | package com.miui.gallery.cloudcontrol;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.util.Pair;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.miui.gallery.R;
import com.miui.gallery.cloudcontrol.FeatureProfile.Deserializer;
import com.miui.gallery.cloudcontrol.FeatureProfile.Status;
import com.miui.gallery.cloudcontrol.observers.FeatureStatusObserver;
import com.miui.gallery.cloudcontrol.observers.FeatureStrategyObserver;
import com.miui.gallery.cloudcontrol.strategies.BaseStrategy;
import com.miui.gallery.provider.GalleryContract.CloudControl;
import com.miui.gallery.util.GallerySamplingStatHelper;
import com.miui.gallery.util.Log;
import com.miui.gallery.util.SafeDBUtil;
import com.miui.gallery.util.SafeDBUtil.QueryHandler;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.subjects.PublishSubject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
class ProfileCache {
private HashMap<String, FeatureProfile> mCloudCache = new HashMap<>();
private HashMap<String, Object> mCloudStrategyCache = new HashMap<>();
private volatile boolean mIsLoadFinished;
private HashMap<String, FeatureProfile> mLocalCache = new HashMap<>();
private HashMap<String, Object> mLocalStrategyCache = new HashMap<>();
private volatile boolean mPendingNotify;
private final PublishSubject<Pair<String, Status>> mStatusSubject = PublishSubject.create();
private final PublishSubject<String> mStrategySubject = PublishSubject.create();
private final Object mSyncLock = new Object();
ProfileCache() {
}
public static /* synthetic */ Object lambda$loadFromDB$3(ProfileCache profileCache, long j, Cursor cursor) {
if (cursor == null || cursor.isClosed()) {
Log.e("CloudControl.ProfileCache", "Fill cache failed with a null cursor.");
} else {
synchronized (profileCache.mSyncLock) {
while (cursor.moveToNext()) {
FeatureDBItem fromCursor = FeatureDBItem.fromCursor(cursor);
profileCache.mCloudCache.put(fromCursor.getName(), fromCursor);
}
}
Log.d("CloudControl.ProfileCache", "Load %d items from database, cost %d ms.", Integer.valueOf(cursor.getCount()), Long.valueOf(System.currentTimeMillis() - j));
}
return null;
}
static /* synthetic */ boolean lambda$registerStatusObserver$0(String str, Pair pair) throws Exception {
return !TextUtils.isEmpty((CharSequence) pair.first) && ((String) pair.first).equals(str);
}
public static /* synthetic */ Pair lambda$registerStrategyObserver$2(ProfileCache profileCache, Class cls, Merger merger, String str) throws Exception {
return new Pair(str, profileCache.queryStrategy(str, cls, merger));
}
private void loadFromDB(Context context) {
Context context2 = context;
SafeDBUtil.safeQuery(context2, CloudControl.URI, FeatureDBItem.PROJECTION, (String) null, (String[]) null, (String) null, (QueryHandler<T>) new QueryHandler(System.currentTimeMillis()) {
private final /* synthetic */ long f$1;
{
this.f$1 = r2;
}
public final Object handle(Cursor cursor) {
return ProfileCache.lambda$loadFromDB$3(ProfileCache.this, this.f$1, cursor);
}
});
}
private void loadFromLocalFile(Reader reader) {
try {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(FeatureProfile.class, new Deserializer());
ArrayList arrayList = (ArrayList) gsonBuilder.create().fromJson(reader, new TypeToken<ArrayList<FeatureProfile>>() {
}.getType());
synchronized (this.mSyncLock) {
Iterator it = arrayList.iterator();
while (it.hasNext()) {
FeatureProfile featureProfile = (FeatureProfile) it.next();
this.mLocalCache.put(featureProfile.getName(), featureProfile);
}
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e2) {
try {
Log.e("CloudControl.ProfileCache", "Failed to load from local file, errorClause: %s, errorMessage: %s.", e2.getCause(), e2.getMessage());
e2.printStackTrace();
Map generatorCommonParams = GallerySamplingStatHelper.generatorCommonParams();
generatorCommonParams.put("errorMsg", e2.getMessage());
GallerySamplingStatHelper.recordErrorEvent("cloud_control", "parse_local_file_failed", generatorCommonParams);
} finally {
try {
reader.close();
} catch (IOException e3) {
e3.printStackTrace();
}
}
}
}
private void notifyStatusChanged(String str, String str2) {
this.mStatusSubject.onNext(new Pair(str, Status.fromValue(str2)));
}
private void notifyStrategyChanged(String str) {
this.mStrategySubject.onNext(str);
}
/* access modifiers changed from: 0000 */
public void clearCloudCache() {
synchronized (this.mSyncLock) {
for (Entry key : this.mCloudCache.entrySet()) {
String str = (String) key.getKey();
notifyStatusChanged(str, this.mLocalCache.get(str) != null ? ((FeatureProfile) this.mLocalCache.get(str)).getStatus() : Status.UNAVAILABLE.getValue());
}
this.mCloudCache.clear();
this.mCloudStrategyCache.clear();
}
}
/* access modifiers changed from: 0000 */
public void insertToCloudCache(FeatureProfile featureProfile) {
String name = featureProfile.getName();
String status = featureProfile.getStatus();
String strategy = featureProfile.getStrategy();
FeatureProfile featureProfile2 = (FeatureProfile) this.mCloudCache.get(name);
synchronized (this.mSyncLock) {
if (Status.REMOVE.getValue().equals(status)) {
if (featureProfile2 != null) {
this.mCloudCache.remove(name);
this.mCloudStrategyCache.remove(name);
}
notifyStatusChanged(name, status);
} else if (featureProfile2 != null) {
if (featureProfile2.getStatus() != null && featureProfile2.getStatus().equals(Status.ENABLE.getValue())) {
status = Status.ENABLE.getValue();
}
if (!TextUtils.equals(featureProfile2.getStrategy(), strategy)) {
featureProfile2.setStrategy(strategy);
this.mCloudStrategyCache.remove(name);
notifyStrategyChanged(name);
}
if (!TextUtils.equals(featureProfile2.getStatus(), status)) {
featureProfile2.setStatus(status);
notifyStatusChanged(name, status);
}
} else {
FeatureProfile featureProfile3 = new FeatureProfile();
featureProfile3.setStrategy(strategy);
featureProfile3.setStatus(status);
featureProfile3.setName(name);
this.mCloudCache.put(name, featureProfile3);
notifyStatusChanged(name, status);
notifyStrategyChanged(name);
}
}
}
/* access modifiers changed from: 0000 */
public void load(Context context) {
loadFromDB(context);
loadFromLocalFile(new InputStreamReader(context.getResources().openRawResource(R.raw.cloud_control)));
this.mIsLoadFinished = true;
}
/* access modifiers changed from: 0000 */
public void notifyAfterLoadFinished() {
synchronized (this.mSyncLock) {
if (this.mPendingNotify) {
Log.d("CloudControl.ProfileCache", "Notify all feature status after cache load finished:");
for (Entry entry : this.mCloudCache.entrySet()) {
if (!TextUtils.isEmpty((CharSequence) entry.getKey()) && entry.getValue() != null) {
Log.d("CloudControl.ProfileCache", "Feature name: %s, feature status: %s", entry.getKey(), String.valueOf(((FeatureProfile) entry.getValue()).getStatus()));
notifyStatusChanged((String) entry.getKey(), ((FeatureProfile) entry.getValue()).getStatus());
notifyStrategyChanged((String) entry.getKey());
}
}
this.mPendingNotify = false;
}
}
}
/* access modifiers changed from: 0000 */
public Status queryStatus(String str) {
if (TextUtils.isEmpty(str)) {
return Status.UNAVAILABLE;
}
synchronized (this.mSyncLock) {
if (this.mIsLoadFinished) {
String str2 = null;
if (this.mCloudCache.get(str) != null) {
str2 = ((FeatureProfile) this.mCloudCache.get(str)).getStatus();
} else if (this.mLocalCache.get(str) != null) {
str2 = ((FeatureProfile) this.mLocalCache.get(str)).getStatus();
}
if (TextUtils.isEmpty(str2)) {
Status status = Status.UNAVAILABLE;
return status;
}
try {
Status fromValue = Status.fromValue(str2);
return fromValue;
} catch (Exception unused) {
return Status.UNAVAILABLE;
}
} else {
this.mPendingNotify = true;
Status status2 = Status.UNAVAILABLE;
return status2;
}
}
}
/* access modifiers changed from: 0000 */
/* JADX WARNING: Removed duplicated region for block: B:35:0x007d */
/* JADX WARNING: Removed duplicated region for block: B:49:0x00b1 A[ADDED_TO_REGION] */
/* JADX WARNING: Removed duplicated region for block: B:55:0x00bf */
public <T extends BaseStrategy> T queryStrategy(String str, Class<T> cls, Merger<T> merger) {
BaseStrategy baseStrategy;
Object obj;
BaseStrategy baseStrategy2 = null;
if (TextUtils.isEmpty(str)) {
return null;
}
synchronized (this.mSyncLock) {
if (this.mIsLoadFinished) {
Object obj2 = this.mCloudStrategyCache.get(str);
if (obj2 != null && cls.isAssignableFrom(obj2.getClass())) {
baseStrategy = (BaseStrategy) obj2;
} else if (this.mCloudCache.get(str) != null) {
String strategy = ((FeatureProfile) this.mCloudCache.get(str)).getStrategy();
try {
baseStrategy = (BaseStrategy) new Gson().fromJson(strategy, cls);
if (baseStrategy != null) {
try {
baseStrategy.doAdditionalProcessing();
this.mCloudStrategyCache.put(str, baseStrategy);
} catch (Exception e) {
e = e;
}
}
} catch (Exception e2) {
e = e2;
baseStrategy = null;
Log.e("CloudControl.ProfileCache", "Failed to deserialize strategy: %s", (Object) strategy);
e.printStackTrace();
obj = this.mLocalStrategyCache.get(str);
if (obj == null) {
}
if (this.mLocalCache.get(str) != null) {
}
if (merger == null) {
}
if (baseStrategy != null) {
}
return baseStrategy2;
}
} else {
baseStrategy = null;
}
obj = this.mLocalStrategyCache.get(str);
if (obj == null && cls.isAssignableFrom(obj.getClass())) {
baseStrategy2 = (BaseStrategy) obj;
} else if (this.mLocalCache.get(str) != null) {
String strategy2 = ((FeatureProfile) this.mLocalCache.get(str)).getStrategy();
try {
BaseStrategy baseStrategy3 = (BaseStrategy) new Gson().fromJson(strategy2, cls);
if (baseStrategy3 != null) {
try {
baseStrategy3.doAdditionalProcessing();
this.mLocalStrategyCache.put(str, baseStrategy3);
} catch (Exception e3) {
e = e3;
baseStrategy2 = baseStrategy3;
}
}
baseStrategy2 = baseStrategy3;
} catch (Exception e4) {
e = e4;
Log.e("CloudControl.ProfileCache", "Failed to deserialize strategy: %s", (Object) strategy2);
e.printStackTrace();
if (merger == null) {
}
if (baseStrategy != null) {
}
return baseStrategy2;
}
}
if (merger == null && baseStrategy != null && baseStrategy2 != null) {
T t = (BaseStrategy) merger.merge(baseStrategy2, baseStrategy);
return t;
} else if (baseStrategy != null) {
baseStrategy2 = baseStrategy;
}
} else {
this.mPendingNotify = true;
return null;
}
}
}
/* access modifiers changed from: 0000 */
public Status registerStatusObserver(String str, FeatureStatusObserver featureStatusObserver) {
if (!TextUtils.isEmpty(str)) {
if (featureStatusObserver != null) {
this.mStatusSubject.filter(new Predicate(str) {
private final /* synthetic */ String f$0;
{
this.f$0 = r1;
}
public final boolean test(Object obj) {
return ProfileCache.lambda$registerStatusObserver$0(this.f$0, (Pair) obj);
}
}).observeOn(AndroidSchedulers.mainThread()).subscribe((Observer<? super T>) featureStatusObserver);
}
return queryStatus(str);
}
throw new IllegalArgumentException("feature should not be empty or null.");
}
/* access modifiers changed from: 0000 */
public <T extends BaseStrategy> T registerStrategyObserver(String str, Class<T> cls, Merger<T> merger, FeatureStrategyObserver<T> featureStrategyObserver) {
if (!TextUtils.isEmpty(str)) {
if (featureStrategyObserver != null) {
this.mStrategySubject.filter(new Predicate(str) {
private final /* synthetic */ String f$0;
{
this.f$0 = r1;
}
public final boolean test(Object obj) {
return ((String) obj).equals(this.f$0);
}
}).map(new Function(cls, merger) {
private final /* synthetic */ Class f$1;
private final /* synthetic */ Merger f$2;
{
this.f$1 = r2;
this.f$2 = r3;
}
public final Object apply(Object obj) {
return ProfileCache.lambda$registerStrategyObserver$2(ProfileCache.this, this.f$1, this.f$2, (String) obj);
}
}).observeOn(AndroidSchedulers.mainThread()).subscribe((Observer<? super T>) featureStrategyObserver);
}
return queryStrategy(str, cls, merger);
}
throw new IllegalArgumentException("feature should not be empty or null.");
}
/* access modifiers changed from: 0000 */
public void unregisterStatusObserver(FeatureStatusObserver featureStatusObserver) {
if (!featureStatusObserver.isDisposed()) {
featureStatusObserver.dispose();
}
}
/* access modifiers changed from: 0000 */
public void unregisterStrategyObserver(FeatureStrategyObserver featureStrategyObserver) {
if (!featureStrategyObserver.isDisposed()) {
featureStrategyObserver.dispose();
}
}
}
| [
"sv.xeon@gmail.com"
] | sv.xeon@gmail.com |
4ff04c000b955680c96ba513d33ab8ef85de0628 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/14/14_4e41553096ed8825e7d1ce4b0a0a6bdb6699cddc/SVTableModel/14_4e41553096ed8825e7d1ce4b0a0a6bdb6699cddc_SVTableModel_s.java | 9a125a744cb9dc31e328bbaccc2fe4fece2a39dd | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 4,012 | java |
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache POI" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* "Apache POI", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.poi.hssf.contrib.view;
import java.util.Iterator;
import javax.swing.table.*;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFCell;
/**
* Sucky Viewer Table Model - The model for the Sucky Viewer just overrides things.
* @author Andrew C. Oliver
*/
public class SVTableModel extends AbstractTableModel {
private HSSFSheet st = null;
int maxcol = 0;
public SVTableModel(HSSFSheet st, int maxcol) {
this.st = st;
this.maxcol=maxcol;
}
public SVTableModel(HSSFSheet st) {
this.st = st;
Iterator i = st.rowIterator();
while (i.hasNext()) {
HSSFRow row = (HSSFRow)i.next();
if (maxcol < (row.getLastCellNum()+1)) {
this.maxcol = row.getLastCellNum();
}
}
}
public int getColumnCount() {
return this.maxcol+1;
}
public Object getValueAt(int row, int col) {
HSSFRow r = st.getRow(row);
HSSFCell c = null;
if (r != null) {
c = r.getCell((short)col);
}
return c;
}
public int getRowCount() {
return st.getLastRowNum() + 1;
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
d85b05ebdbb32381b66516b09db6a4c9fae1e0ad | 000c7ff03a7da1788bc596ce519751de515e846e | /greendaostudy/src/main/java/com/assassin/greendaostudy/app/GreenDaoApp.java | 9a1a405241a6aa4554f68ce8b21fc6a68934ee44 | [] | no_license | shaycormac/ShayPatrickCormacStudy | bd4faacd9d74781b3130f66590e6775cdf1fc099 | 4f4c685c45b079bc968a01c3bba4d60ffde4c856 | refs/heads/master | 2021-01-20T12:23:05.319732 | 2017-07-15T04:46:25 | 2017-07-15T04:46:25 | 90,359,265 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 701 | java | package com.assassin.greendaostudy.app;
import android.app.Application;
import com.assassin.greendaostudy.greendaohelper.DBManager;
import com.facebook.stetho.Stetho;
/**
* @Author: Shay-Patrick-Cormac
* @Email: fang47881@126.com
* @Ltd: GoldMantis
* @Date: 2017/5/2 13:42
* @Version:
* @Description:
*/
public class GreenDaoApp extends Application
{
public static GreenDaoApp instance;
@Override
public void onCreate()
{
super.onCreate();
instance = this;
// GreenDaoHelper.intDatabase();
//初始化数据库
DBManager.INSTANCE.initDataBase();
//facebook调试数据库
Stetho.initializeWithDefaults(this);
}
}
| [
"574583006@qq.com"
] | 574583006@qq.com |
a6505a06f509e8c7c40d440a9d3a3c6e4a394acc | ebf47fd5dd0f42000b7d3e494c3df679cabf7dad | /backend/src/main/java/de/pharos/myPosts/dao/PostDao.java | 90717fa74721fd0030aa1d44e2916c86ecd93422 | [
"MIT"
] | permissive | OmarGSharaf/MyPosts | 28ba77986d46cd9e2eac110e2bb028b6de2bdc75 | 6e8773591b33b7fa11105a4e3a50c2d3b7745f3c | refs/heads/master | 2023-01-10T03:47:41.160272 | 2019-08-26T11:12:42 | 2019-08-26T11:12:42 | 203,486,690 | 0 | 0 | null | 2022-12-11T02:51:24 | 2019-08-21T02:02:49 | Java | UTF-8 | Java | false | false | 561 | java | package de.pharos.myPosts.dao;
import de.pharos.myPosts.model.Post;
import de.pharos.myPosts.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PostDao extends JpaRepository<Post, Integer> {
Page<Post> findAllByUser(User user, Pageable pageable);
Page<Post> findByContentIgnoreCaseContainingAndStatus(String content, String status, Pageable pageable);
} | [
"omargamal@Omars-MacBook-Pro.local"
] | omargamal@Omars-MacBook-Pro.local |
53487124473f00413091a959a05b7a270f1e4181 | 4299f856f23977ddbec27d2af67c962e8b36b5ed | /Aufgabe/src/SongTree1.java | fe46e31949859f599be4b6d2a915a34d39f76a49 | [] | no_license | Florian-S-A-W/Eprog2_SS2018 | 9ecfb24333a318d0b4225f928e5cc66e0fbcabfe | 91e0c6d161bc2af2bda461daf8393cbeb4665118 | refs/heads/master | 2020-03-13T16:35:48.898226 | 2018-06-17T20:36:55 | 2018-06-17T20:36:55 | 131,201,853 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 713 | java |
public class SongTree1 {
SongTreeNodable root;
public SongTree1() {
this.root = new SongTree1Null();
}
/**
* Adds a song to the binary tree
*
* @param song a new song that shall be added to the tree
* @throws IllegalArgumentException song == null
*
* Postcondition: The song is in the tree if it is not null
*/
public void add(Song song) throws IllegalArgumentException {
if(song == null) {
throw new IllegalArgumentException();
}
this.root = this.root.add(song);
}
public void print() {
this.root.print();
}
public String toString() {
return this.root.toString();
}
} | [
"florian_winkler@kw-studios.com"
] | florian_winkler@kw-studios.com |
5a87fa25140c89b68c0bf47d513b38e2092c9834 | a339529563aacef12e1f587354bccfc68d1cd462 | /src/main/java/org/segrada/service/repository/NodeRepository.java | 8660938896946cf858b4f708ae39915f60a8dc62 | [
"Apache-2.0"
] | permissive | ronypik/segrada | e9ff9af4468d69eb325dff0867acf6c6a9353d25 | 2fa6f77b4d8c7dcf28f50a9597f855a3902d517c | refs/heads/master | 2020-04-21T23:58:15.682013 | 2018-04-20T12:50:10 | 2018-04-20T12:50:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,543 | java | package org.segrada.service.repository;
import org.segrada.model.prototype.INode;
import org.segrada.service.repository.prototype.CRUDRepository;
import org.segrada.service.repository.prototype.PaginatingRepositoryOrService;
import org.segrada.service.repository.prototype.SearchTermRepository;
import javax.annotation.Nullable;
import java.util.List;
/**
* Copyright 2015 Maximilian Kalus [segrada@auxnet.de]
*
* 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.
*
* Node Repository
*/
public interface NodeRepository extends CRUDRepository<INode>, SearchTermRepository<INode>, PaginatingRepositoryOrService<INode> {
/**
* find by search terms, but also contain by tags (used in reference search)
* @param term to search for
* @param maximum to show
* @param returnWithoutTerm show list even without search
* @param tagIds list of tag ids to contain search in
* @return list of entities
*/
List<INode> findBySearchTermAndTags(@Nullable String term, int maximum, boolean returnWithoutTerm, @Nullable String[] tagIds);
}
| [
"info@auxnet.de"
] | info@auxnet.de |
eb57e606b0f878112828d4d4c99ef822bd4b2d90 | 5af6d6bd4936f639f9d383ae142fe93708505b66 | /core/infinit.e.api.server/WEB-INF/src/com/ikanow/infinit/e/api/knowledge/federated/SimpleFederatedQueryEngine.java | 9a06de0727776ba9589d443e39643d1bf4a6438e | [] | no_license | amadu80/Infinit.e | d4ef2c6e53d83f8cb811c5a14b7e0cb8da95f4cf | a33540980ff8d3065c33e0ebf85b7582dfc365b2 | refs/heads/master | 2020-07-11T11:46:10.602644 | 2015-03-03T00:23:04 | 2015-03-03T00:23:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 70,494 | java | /*******************************************************************************
* Copyright 2012, The Infinit.e Open Source Project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package com.ikanow.infinit.e.api.knowledge.federated;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import net.minidev.json.JSONArray;
import org.bson.types.ObjectId;
import com.google.common.collect.Iterators;
import com.google.common.collect.PeekingIterator;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.ikanow.infinit.e.api.knowledge.QueryHandler.ISimpleFederatedQueryEngine;
import com.ikanow.infinit.e.api.knowledge.processing.ScoringUtils;
import com.ikanow.infinit.e.data_model.api.ResponsePojo;
import com.ikanow.infinit.e.data_model.api.knowledge.AdvancedQueryPojo;
import com.ikanow.infinit.e.data_model.interfaces.query.IQueryExtension;
import com.ikanow.infinit.e.data_model.store.DbManager;
import com.ikanow.infinit.e.data_model.store.MongoDbManager;
import com.ikanow.infinit.e.data_model.store.MongoDbUtil;
import com.ikanow.infinit.e.data_model.store.config.source.SimpleFederatedCache;
import com.ikanow.infinit.e.data_model.store.config.source.SourceFederatedQueryConfigPojo;
import com.ikanow.infinit.e.data_model.store.config.source.SourcePojo;
import com.ikanow.infinit.e.data_model.store.document.AssociationPojo;
import com.ikanow.infinit.e.data_model.store.document.DocumentPojo;
import com.ikanow.infinit.e.data_model.store.document.EntityPojo;
import com.ikanow.infinit.e.data_model.utils.IkanowSecurityManager;
import com.ikanow.infinit.e.harvest.HarvestController;
import com.ikanow.infinit.e.harvest.HarvestControllerPipeline;
import com.ikanow.infinit.e.harvest.extraction.text.externalscript.TextExtractorExternalScript;
import com.jayway.jsonpath.JsonPath;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.Response;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
public class SimpleFederatedQueryEngine implements IQueryExtension, ISimpleFederatedQueryEngine {
//DEBUG
static private boolean _DEBUG = false;
//static private boolean _DEBUG = true;
static Logger _logger = Logger.getLogger(SimpleFederatedQueryEngine.class);
private ScoringUtils _scoreStats = null;
public void registerScoringEngine(ScoringUtils scoreStats) {
_scoreStats = scoreStats;
}
private boolean _cacheMode = true;
private boolean _testMode = false;
public void setTestMode(boolean testMode) {
_testMode = testMode;
_cacheMode = !_testMode; // (don't cache in some places if in test mode)
}
public static class FederatedRequest {
// Endpoint version
public SourceFederatedQueryConfigPojo.FederatedQueryEndpointUrl subRequest;
public Future<Response> responseFuture;
public AsyncHttpClient asyncClient;
public String mergeKey;
// Script import version
public FederatedHarvest importThread;
public AdvancedQueryPojo fullQuery;
public Throwable errorMessage;
public BasicDBObject scriptResult = null;
public List<DocumentPojo> complexSourceProcResults = null;
// Joint
public SourceFederatedQueryConfigPojo endpointInfo;
public BasicDBObject cachedResult = null;
public BasicDBObject cachedDoc = null;
public BasicDBObject cachedDoc_expired = null;
public String requestParameter;
public String[] communityIdStrs;
public String queryIndex;
}
public void addEndpoint(SourceFederatedQueryConfigPojo newEndpoint) {
if (null == _endpoints) {
_endpoints = new LinkedList<SourceFederatedQueryConfigPojo>();
}
_endpoints.add(newEndpoint);
}
LinkedList<FederatedRequest> _asyncRequestsPerQuery = null;
LinkedList<SourceFederatedQueryConfigPojo> _endpoints = null;
IkanowSecurityManager _scriptingSecurityManager = new IkanowSecurityManager();
private ScriptEngine _pyEngine = null;
@Override
public void preQueryActivities(ObjectId queryId, AdvancedQueryPojo query, String[] communityIdStrs) {
_scoreStats = null;
_asyncRequestsPerQuery = null;
// 1] Check whether this makes sense to query, get the (sole) entity if so
String entityType = null;
String entityValue = null;
String entityIndex = null;
String textToTest = null;
if ((null != query.qt) && (query.qt.size() > 0) && (query.qt.size() < 4)) {
String logic = query.logic;
if (null != logic) {
logic = logic.toLowerCase();
}
if ((null != logic) && (logic.contains("or") || logic.contains("not"))) {
//DEBUG
if (_DEBUG) _logger.debug("DEB: preQA1: Logic too complex: " + query.logic);
if (_testMode) {
throw new RuntimeException("Bad testQueryJson: Logic too complex: " + query.logic);
}
return; // logic too complex
}//TESTED (1.3)
for (AdvancedQueryPojo.QueryTermPojo qt: query.qt) {
if ((null != qt.entity) || ((null != qt.entityType) && (null != qt.entityValue))) {
if (null == entityType) { // we now have == 1 entity
if (null != qt.entityValue) {
entityValue = qt.entityValue;
entityType = qt.entityType;
entityIndex = entityValue.toLowerCase() + "/" + entityType.toLowerCase();
}//TESTED (1.5)
else {
entityIndex = qt.entity.toLowerCase();
int index = qt.entity.lastIndexOf('/');
if (index > 0) {
entityValue = qt.entity.substring(0, index);
entityType = qt.entity.substring(index + 1).toLowerCase();
}
}//TESTED (1.6)
}
else { // >1 entity, not supported
//DEBUG
if (_DEBUG) _logger.debug("DEB: preQA2a: >1 entity: " + qt.entity + " / " + entityType + " / " + query.toApi());
if (_testMode) {
throw new RuntimeException("Bad testQueryJson: >1 entity: " + qt.entity + " / " + entityType + " / " + query.toApi());
}
return;
}//TESTED (1.4)
}//TESTED
else if ((null != qt.etext) && (qt.etext.equals("*"))) {
//this is fine provided it's only ANDed together (eg above logic case)
}
else if (null != qt.etext) { // Only work if it matches one of the regexes
if (null == entityType) {
textToTest = qt.etext;
entityType = "etext";
}
else { // >1 entity, not supported
//DEBUG
if (_DEBUG) _logger.debug("DEB: preQA2b: >1 entity: " + qt.entity + " / " + entityType + " / " + query.toApi());
if (_testMode) {
throw new RuntimeException("Bad testQueryJson: >1 entity: " + qt.entity + " / " + entityType + " / " + query.toApi());
}
return;
}//TESTED (1.4)
}
else if (null == qt.time) { // temporal
//DEBUG
if (_DEBUG) _logger.debug("DEB: preQA3: non-entity/date " + query.toApi());
if (_testMode) {
throw new RuntimeException("Bad testQueryJson: non-entity/date " + query.toApi());
}
return;
}//TESTED (1.1)
}//(end loop over query terms)
}//TESTED (1.*)
if (null == entityType) { // Query too complex
//DEBUG
if (_DEBUG) _logger.debug("DEB: preQA4: query missing entity " + query.toApi());
if (_testMode) {
throw new RuntimeException("Bad testQueryJson: query missing entity " + query.toApi());
}
return;
}//TESTED (1.2)
entityType = entityType.toLowerCase();
// 2] If so, query across all the end
for (SourceFederatedQueryConfigPojo endpoint: _endpoints) {
// Endpoint validation:
if (null == endpoint.entityTypes) {
if (_testMode) {
throw new RuntimeException("No entity types specified");
}
else {
continue;
}
}
if (null != textToTest) { // This is text, see if you can convert to an entity
entityValue = null; //(reset for different endpoints - used in the check to decide whether to continue)
for (String entityTypeRegex: endpoint.entityTypes) {
if (entityTypeRegex.startsWith("/")) {
int regexIndex = entityTypeRegex.lastIndexOf('/'); // (guaranteed to be >= 0)
try {
Pattern regex = Pattern.compile(entityTypeRegex.substring(1, regexIndex));
if (regex.matcher(textToTest).matches()) {
entityType = entityTypeRegex.substring(1+regexIndex);
if (entityType.length() > 0) {
entityValue = textToTest;
entityIndex = entityValue.toLowerCase() + "/" + entityType.toLowerCase();
}
}
}
catch (Exception e) { // if not in test mode, carry on
if (_testMode) {
throw new RuntimeException(e);
}
}
}
}//(end loop over entity regexes)
}//TESTED
if (null == entityValue) { // None of the regexes matched
if (_testMode) {
throw new RuntimeException("Text specified, does not match any of the regexes: " + Arrays.toString(endpoint.entityTypes.toArray()) + " ... text = " + textToTest);
}
continue;
}
//DEBUG
if (_DEBUG) _logger.debug("DEB: preQA5: ENDPOINT: " + Arrays.toString(endpoint.entityTypes.toArray()) + " / " + entityType);
if ((null != endpoint.importScript) && !endpoint.importScript.isEmpty()) {
if (null == endpoint.scriptlang) {
endpoint.scriptlang = "python"; // python ==default
}
if (endpoint.scriptlang.equalsIgnoreCase("python")) {
_pyEngine = new ScriptEngineManager().getEngineByName("python");
if (null == _pyEngine) {
_logger.error("Python not installed - copy jython 2.5+ into /opt/infinite-home/lib/unbundled");
if (_testMode) {
throw new RuntimeException("Python not installed - copy jython 2.5+ into /opt/infinite-home/lib/unbundled");
}
}//TESTED (by hand, importScript != null and scriptlang: "python", jython not on classpath)
}
else if (endpoint.scriptlang.equalsIgnoreCase("external")) {
//nothing to do here, just carry on, will handle the external bit later on
}
else {
_logger.error("Python/External is currently the only supported scriptlang");
if (_testMode) {
throw new RuntimeException("Python is currently the only supported scriptlang");
}
}//TESTED (by hand, importScript != null and scriptlang: "none")
}//TESTED
if ((null != endpoint.bypassSimpleQueryParsing) && endpoint.bypassSimpleQueryParsing) {
throw new RuntimeException("Currently only simple query parsing is supported");
}
if ((null != endpoint.entityTypes) && endpoint.entityTypes.contains(entityType)) {
// If not using the full source pipeline processing capability (ie always generating 0/1
BasicDBObject cachedDoc = null;
String cachedDocUrl = buildScriptUrl(endpoint.parentSource.getKey(), entityIndex);
BasicDBObject cachedDoc_expired = null;
if (!isComplexSource(endpoint.parentSource)) {
// Check if the *doc* (not *API response*) generated from this endpoint/entity has been cached, check expiry if so
if (_cacheMode && ((null == endpoint.cacheTime_days) || (endpoint.cacheTime_days >= 0))) {
if (_DEBUG) _logger.debug("DEB: preQA6ya: Search Doc Cache: " + cachedDocUrl + " , " + endpoint.cacheTime_days);
BasicDBObject cachedDocQuery = new BasicDBObject(DocumentPojo.url_, cachedDocUrl);
cachedDocQuery.put(DocumentPojo.sourceKey_, endpoint.parentSource.getKey());
cachedDoc = (BasicDBObject) DbManager.getDocument().getMetadata().findOne(cachedDocQuery);
if (null != cachedDoc) {
// (quick check if we have a complex source in here)
String sourceUrl = cachedDoc.getString(DocumentPojo.sourceUrl_);
if (null != sourceUrl) { // switching from complex to simple source - delete the cached docs
if (_DEBUG) _logger.debug("DEB: preQA6yb: Clear Search Doc Cache: " + cachedDocUrl + " , " + sourceUrl);
cachedDocQuery.remove(DocumentPojo.url_);
cachedDocQuery.put(DocumentPojo.sourceUrl_, sourceUrl);
DbManager.getDocument().getMetadata().remove(cachedDocQuery);
cachedDoc = null;
}//TESTED (by hand)
else if (checkDocCache_isExpired(cachedDoc, endpoint)) {
cachedDoc_expired = cachedDoc;
cachedDoc = null;
}
}
}//TESTED (by hand)
}
if (null == _asyncRequestsPerQuery) {
// If we've got this far create a list to store the async requests
_asyncRequestsPerQuery = new LinkedList<FederatedRequest>();
}
if (null != cachedDoc) { // (simple sources only, by construction)
// Common params:
FederatedRequest requestOverview = new FederatedRequest();
requestOverview.endpointInfo = endpoint;
requestOverview.communityIdStrs = communityIdStrs;
requestOverview.requestParameter = entityValue;
requestOverview.queryIndex = entityIndex;
requestOverview.mergeKey = endpoint.parentSource.getKey();
if (_DEBUG) _logger.debug("DEB: preQA6z: Doc Cache: " + cachedDocUrl + " , " + cachedDoc);
requestOverview.cachedDoc = cachedDoc;
_asyncRequestsPerQuery.add(requestOverview);
}//TESTED (by hand)
else if (null != endpoint.importScript) {
BasicDBObject cachedVal = null;
if (_cacheMode) { // (source key not static, plus not sure it's desirable, so for simplicity just don't cache requests in test mode)
cachedVal = this.getCache(cachedDocUrl, endpoint);
}
// Common params:
FederatedRequest requestOverview = new FederatedRequest();
requestOverview.endpointInfo = endpoint;
requestOverview.communityIdStrs = communityIdStrs;
requestOverview.requestParameter = entityValue;
requestOverview.queryIndex = entityIndex;
requestOverview.mergeKey = endpoint.parentSource.getKey();
requestOverview.cachedDoc_expired = cachedDoc_expired;
if (null != cachedVal) {
if (checkIfNeedToClearCache(cachedVal, endpoint.parentSource)) {
if (_DEBUG) _logger.debug("DEB: preQA6aa: Clear cache: " + cachedDocUrl + " , " + cachedVal);
cachedVal = null;
}
}
requestOverview.cachedResult = cachedVal; // will often be null
if ((null == cachedVal) || isComplexSource(endpoint.parentSource)) {
if (null != cachedVal) {
if (_DEBUG) _logger.debug("DEB: preQA6ab: Complex Src Cache: " + cachedDocUrl + " , " + cachedVal);
}
if (endpoint.scriptlang.equalsIgnoreCase("external")) {
requestOverview.importThread = new FederatedScriptHarvest();
}
else {
requestOverview.importThread = new FederatedJythonHarvest();
}
requestOverview.importThread.queryEngine = this;
requestOverview.importThread.request = requestOverview;
requestOverview.importThread.start();
}
else {
if (_DEBUG) _logger.debug("DEB: preQA6a: Cache: " + cachedDocUrl + " , " + cachedVal);
}
// Launch thread
_asyncRequestsPerQuery.add(requestOverview);
}//TESTED (by hand)
else {
if (isComplexSource(endpoint.parentSource)) {
//DEBUG
if (_DEBUG) _logger.debug("DEB: preQA6ba: Build complex source, num requests = " + endpoint.requests.size());
FederatedRequest requestOverview = new FederatedRequest();
requestOverview.endpointInfo = endpoint;
requestOverview.communityIdStrs = communityIdStrs;
requestOverview.requestParameter = entityValue;
requestOverview.queryIndex = entityIndex;
requestOverview.mergeKey = endpoint.parentSource.getKey();
requestOverview.cachedDoc_expired = cachedDoc_expired;
requestOverview.importThread = new FederatedSimpleHarvest();
requestOverview.importThread.queryEngine = this;
requestOverview.importThread.request = requestOverview;
requestOverview.importThread.start();
// Launch thread
_asyncRequestsPerQuery.add(requestOverview);
}
else { // simple source
try {
for (SourceFederatedQueryConfigPojo.FederatedQueryEndpointUrl request: endpoint.requests) {
FederatedRequest requestOverview = createSimpleHttpEndpoint_includingCache(
entityValue, entityIndex, communityIdStrs,
endpoint, request, cachedDoc_expired);
//DEBUG
if (_DEBUG) _logger.debug("DEB: preQA6bb: Build request: " + request.endPointUrl);
_asyncRequestsPerQuery.add(requestOverview);
}//(end loop over multiple requests
}
catch (Exception e) {
_logger.error("Unknown error creating federated query for " + endpoint.titlePrefix + ": " + e.getMessage());
if (_testMode) {
throw new RuntimeException("Unknown error creating federated query for " + endpoint.titlePrefix + ": " + e.getMessage(), e);
}
}
}//(end if simple not complex)
}//(end cached doc vs script vs request mode for queries)
}//(end if this request is for this entity type)
else { // no entity matches - if in test mode then bomb out with useful error
if (_testMode) {
throw new RuntimeException("Specified entity: " + entityIndex + " not in set: " + Arrays.toString(endpoint.entityTypes.toArray()));
}
}
}//(end loop over endpoints)
}
@Override
public void postQueryActivities(ObjectId queryId, List<BasicDBObject> docs, ResponsePojo response)
{
boolean grabbedScores = false;
double aggregateSignif = 100.0;
double queryRelevance = 100.0;
double score = 100.0;
if (null != _asyncRequestsPerQuery) {
int added = 0;
BasicDBList bsonArray = new BasicDBList();
PeekingIterator<FederatedRequest> it = Iterators.peekingIterator(_asyncRequestsPerQuery.iterator());
while (it.hasNext()) {
// loop state:
BasicDBObject[] docOrDocs = new BasicDBObject[1];
docOrDocs[0] = null;
FederatedRequest request = it.next();
boolean isComplexSource = isComplexSource(request.endpointInfo.parentSource);
if (null == request.cachedDoc) { // no cached doc, simple source processing (OR ANY COMPLEX CASE BY CONSTRUCTION)
try {
if ((null == request.cachedResult) || isComplexSource) { // no cached api response, or complex
if (null != request.importThread) {
// 1) wait for the thread to finish
if (null == request.endpointInfo.queryTimeout_secs) {
request.endpointInfo.queryTimeout_secs = 300;
}
for (int timer = 0; timer < request.endpointInfo.queryTimeout_secs; timer++) {
try {
request.importThread.join(1000L);
if (!request.importThread.isAlive()) {
break;
}
}//TESTED (by hand)
catch (Exception e) {
//(carry on)
}
}
if (request.importThread.isAlive()) {
request.errorMessage = new RuntimeException("Script timed out");
}//TESTED (by hand)
// 2) Get the results
if (null != request.errorMessage) {
if (_testMode) {
throw new RuntimeException(request.errorMessage);
}
}
else if (isComplexSource) {
//DEBUG
if (_DEBUG) _logger.debug("DEB: postQA0: " + request.complexSourceProcResults.size());
handleComplexDocCaching(request, _cacheMode, _scoreStats);
// Get a list of docs
docOrDocs = ((BasicDBList)DocumentPojo.listToDb(request.complexSourceProcResults, DocumentPojo.listType())).toArray(new BasicDBObject[0]);
// (_API_ caching is exactly the same between cache and non-cache cases)
// (note that if null != complexSourceProcResults then follows that null != scriptResult)
String url = buildScriptUrl(request.mergeKey, request.queryIndex);
if (!(request.importThread instanceof FederatedSimpleHarvest) && _cacheMode) { // (don't cache python federated queries in test mode)
// (simple harvest caching is done separately)
this.cacheApiResponse(url, request.scriptResult, request.endpointInfo);
}
}//TESTED (by hand - single and multiple doc mode)
else if (null == request.scriptResult) {
if (_testMode) {
throw new RuntimeException("Script mode: no cached result found from: " + request.requestParameter);
}
}
else {
// (_API_ caching is exactly the same between cache and non-cache cases)
String url = buildScriptUrl(request.mergeKey, request.queryIndex);
if (_cacheMode) { // (don't cache python federated queries in test mode)
this.cacheApiResponse(url, request.scriptResult, request.endpointInfo);
}
bsonArray.add(request.scriptResult);
}
} // end script mode
else { // HTTP mode (also: must be simple source builder)
Response endpointResponse = request.responseFuture.get();
request.asyncClient.close();
request.asyncClient = null;
String jsonStr = endpointResponse.getResponseBody();
String url = endpointResponse.getUri().toURL().toString();
Object bsonUnknownType = com.mongodb.util.JSON.parse(jsonStr);
BasicDBObject bson = null;
if (bsonUnknownType instanceof BasicDBObject) {
bson = (BasicDBObject) bsonUnknownType;
}
else if (bsonUnknownType instanceof BasicDBList) {
bson = new BasicDBObject(SimpleFederatedCache.array_, bsonUnknownType);
}
else if (bsonUnknownType instanceof String) {
bson = new BasicDBObject(SimpleFederatedCache.value_, bsonUnknownType);
}
//DEBUG
if (_DEBUG) _logger.debug("DEB: postQA1: " + url + ": " + jsonStr);
if (null != bson) {
MongoDbUtil.enforceTypeNamingPolicy(bson, 0);
this.cacheApiResponse(url, bson, request.endpointInfo);
bsonArray.add(bson);
}
}//(end script vs request method)
}//TESTED (3.1, 4.2)
else { // (just used cached value)
//DEBUG
if (_DEBUG) _logger.debug("DEB: postQA2: " + request.cachedResult.toString());
bsonArray.add((BasicDBObject)request.cachedResult.get(SimpleFederatedCache.cachedJson_));
}//TESTED (4.1, 4.3)
}
catch (Exception e) {
//DEBUG
if (null == request.subRequest) {
_logger.error("Error with script: " + e.getMessage());
if (_testMode) {
throw new RuntimeException("Error with script: " + e.getMessage(), e);
}
}
else {
_logger.error("Error with " + request.subRequest.endPointUrl + ": " + e.getMessage());
if (_testMode) {
throw new RuntimeException("Error with " + request.subRequest.endPointUrl + ": " + e.getMessage(), e);
}
}
}
if (null == docOrDocs[0]) {
// (this next bit of logic can only occur in simple source cases by construction, phew)
if (!it.hasNext() || (request.mergeKey != it.peek().mergeKey)) { // deliberate ptr arithmetic
String url = buildScriptUrl(request.mergeKey, request.queryIndex);
//DEBUG
if (_DEBUG) _logger.debug("DEB: postQA3: " + url + ": " + bsonArray);
docOrDocs[0] = createDocFromJson(bsonArray, url, request, request.endpointInfo);
}
}
} // (end if no cached doc)
else { // cached doc, bypass lots of processing because no merging and doc already built (simple source processing)
docOrDocs[0] = request.cachedDoc;
}//TESTED (by hand)
if (null != docOrDocs[0]) for (BasicDBObject doc: docOrDocs) {
// Cache the document unless already cached (or caching disabled)
if ((null == request.cachedDoc) && _cacheMode && !isComplexSource &&
((null == request.endpointInfo.cacheTime_days) || (request.endpointInfo.cacheTime_days >= 0)))
{
simpleDocCache(request, doc);
}//TESTED (by hand, 3 cases: cached not expired, cached expired first time, cached expired multiple times)
if (!grabbedScores) {
if (!docs.isEmpty()) {
BasicDBObject topDoc = docs.get(0);
aggregateSignif = topDoc.getDouble(DocumentPojo.aggregateSignif_, aggregateSignif);
queryRelevance = topDoc.getDouble(DocumentPojo.queryRelevance_, queryRelevance);
score = topDoc.getDouble(DocumentPojo.score_, score);
grabbedScores = true;
// OK would also like to grab the original matching entity, if it exists
if (!isComplexSource) {
BasicDBList ents = (BasicDBList) topDoc.get(DocumentPojo.entities_);
if (null != ents) {
for (Object entObj: ents) {
BasicDBObject ent = (BasicDBObject)entObj;
String entIndex = ent.getString(EntityPojo.index_, "");
if (entIndex.equals(request.queryIndex)) {
ents = (BasicDBList) doc.get(DocumentPojo.entities_);
if (null != ents) {
ents.add(ent);
}
break;
}
}
}//TESTED (by hand)
}
}
}
doc.put(DocumentPojo.aggregateSignif_, aggregateSignif);
doc.put(DocumentPojo.queryRelevance_, queryRelevance);
doc.put(DocumentPojo.score_, score);
// Swap id and updateId, everything's been cached now:
// Handle update ids vs normal ids:
ObjectId updateId = (ObjectId) doc.get(DocumentPojo.updateId_);
if (null != updateId) { // swap the 2...
doc.put(DocumentPojo.updateId_, doc.get(DocumentPojo._id_));
doc.put(DocumentPojo._id_, updateId);
}//TESTED (by hand)
// If we're returning to a query then we'll adjust the doc format (some of the atomic fields become arrays)
if (!_testMode) {
convertDocToQueryFormat(doc, request.communityIdStrs);
}//TESTED (by hand)
docs.add(0, doc);
added++;
//(doc auto reset at top of loop)
//(end if built a doc from the last request/set of requests)
}//TESTED (3.1)
}//(end loop over federated requests)
if (null != response.getStats()) {
response.getStats().found += added;
}//TESTED (by hand)
}
}
/////////////////////////////////////////////////
// UTILITY
public FederatedRequest createSimpleHttpEndpoint_includingCache(
String entityValue, String entityIndex, String[] communityIdStrs,
SourceFederatedQueryConfigPojo endpoint,
SourceFederatedQueryConfigPojo.FederatedQueryEndpointUrl request,
BasicDBObject cachedDoc_expired) throws IOException
{
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
BoundRequestBuilder asyncRequest = null;
String postContent = null;
if (null != request.httpFields) {
postContent = request.httpFields.get("Content");
if (null == postContent)
postContent = request.httpFields.get("content");
}//TESTED (by hand, "http://httpbin.org/post", "httpFields": { "Content": "test" }
if (null == postContent) {
asyncRequest = asyncHttpClient.prepareGet(request.endPointUrl.replace("$1", entityValue));
}
else {
asyncRequest = asyncHttpClient.preparePost(request.endPointUrl.replace("$1", entityValue));
}//TESTED (by hand, "http://httpbin.org/post", "httpFields": { "Content": "test" }
if (null != request.urlParams) {
for (Map.Entry<String, String> keyValue: request.urlParams.entrySet()) {
asyncRequest = asyncRequest.addQueryParameter(keyValue.getKey(), keyValue.getValue().replace("$1", entityValue));
}
}//TESTED (1.5, 1.6, 3.*, 4.*)
if (null != request.httpFields) {
for (Map.Entry<String, String> keyValue: request.httpFields.entrySet()) {
if (!keyValue.getKey().equalsIgnoreCase("content")) {
asyncRequest = asyncRequest.addHeader(keyValue.getKey(), keyValue.getValue().replace("$1", entityValue));
}
}
}//TESTED (by hand, "http://httpbin.org/cookies", "httpFields": { "Cookie": "mycookie=test" }
if (null != postContent) {
asyncRequest = asyncRequest.setBody(postContent.replace("$1", entityValue));
}//TESTED (by hand, "http://httpbin.org/post", "httpFields": { "Content": "$1" }
// Common params:
FederatedRequest requestOverview = new FederatedRequest();
requestOverview.endpointInfo = endpoint;
requestOverview.communityIdStrs = communityIdStrs;
requestOverview.requestParameter = entityValue;
requestOverview.asyncClient = asyncHttpClient;
requestOverview.queryIndex = entityIndex;
requestOverview.mergeKey = endpoint.parentSource.getKey();
requestOverview.subRequest = request;
// Now check out the cache:
URI rawUri = asyncRequest.build().getRawURI();
String url = rawUri.toString();
if ((null == endpoint.parentSource.getOwnedByAdmin()) || !endpoint.parentSource.getOwnedByAdmin())
{
int port = rawUri.getPort();
if ((80 != port) && (443 != port) && (-1 != port)) {
_logger.error("Only admin can make requests on non-standard ports: " + url + ": " + port);
if (_testMode) {
asyncHttpClient.close();
throw new RuntimeException("Only admin can make requests on non-standard ports: " + url + ": " + port);
}
}
}//TESTED (by hand)
BasicDBObject cachedVal = this.getCache(url, endpoint);
if (null != cachedVal) {
if (checkIfNeedToClearCache(cachedVal, endpoint.parentSource)) {
//DEBUG
if (_DEBUG) _logger.debug("DEB: pre:CSHEb: Clear cache: " + url + " , " + cachedVal);
cachedVal = null;
}
}
requestOverview.cachedResult = cachedVal;
requestOverview.cachedDoc_expired = cachedDoc_expired;
if (null == cachedVal) {
requestOverview.responseFuture = asyncRequest.execute();
}
else {
//DEBUG
if (_DEBUG) _logger.debug("DEB: pre:CSHEb: Cache: " + url + " , " + cachedVal);
requestOverview.responseFuture = null;
asyncHttpClient.close();
}
return requestOverview;
}
public BasicDBObject createDocFromJson(BasicDBList jsonList, String url, FederatedRequest request, SourceFederatedQueryConfigPojo endpointInfo) {
BasicDBObject doc = null; // (don't create unless needed)
BasicDBList ents = null;
StringBuffer entVals = null;
HashSet<String> entDedup = null;
if (_testMode) { // In test mode, need to return the JSON even if no entities are specified
doc = new BasicDBObject();
}
if (null != endpointInfo.docConversionMap) {
for (Map.Entry<String, String> docInfo: endpointInfo.docConversionMap.entrySet()) {
for (Object jsonObj: jsonList) {
BasicDBObject json = (BasicDBObject)jsonObj;
try {
String key = docInfo.getKey();
// (allow user to not prepend array: if they don't want to)
if ((1 == json.size()) && json.containsKey((Object)"array")) {
if (!key.startsWith("array:") &&
!key.startsWith(":array") && !key.startsWith("$:array") &&
!key.startsWith("::") && !key.startsWith("$::"))
{
if (key.startsWith(":")) { // jpath
key = ":array" + key;
}
else if (key.startsWith("$:")) { // jpath
key = "$:array" + key.substring(1);
}
else {
key = "array:" + key;
}
}
}//TESTED (by hand)
if (key.startsWith(":")) { // jpath
key = "$" + key;
}
// NOTE: *not* org.json.JSONArray
JSONArray candidateEntities = null;
if (key.startsWith("$")) {
JSONArray candidateEntities_tmp = JsonPath.read(json.toString(), key.replace(':', '.'));
if (null != candidateEntities_tmp) {
candidateEntities = new JSONArray();
for (Object o: candidateEntities_tmp) {
if (o instanceof String) {
candidateEntities.add(o);
}
else if (o instanceof JSONArray) {
candidateEntities.addAll((JSONArray)o);
}
}//TESTED (displayUrl vs entities, 3.2)
}
//DEBUG
//System.out.println(candidateEntities);
}//(TESTED (permutations above by hand))
else {
String s = (String) MongoDbUtil.getProperty(json, key.replace(':', '.'));
if (null != s) {
candidateEntities = new JSONArray();
candidateEntities.add(s);
}
}//TESTED (3.1)
if (null != candidateEntities) for (int i = 0; i < candidateEntities.size(); ++i) {
Object o = candidateEntities.get(i);
if (!(o instanceof String)) {
continue;
}
String s = o.toString();
if (null == doc) {
doc = new BasicDBObject();
//(various fields added below)
}
if (docInfo.getValue().equalsIgnoreCase(DocumentPojo.displayUrl_)) {
doc.put(DocumentPojo.displayUrl_, s);
}//TESTED (3.1, 4.*)
else { // Entities!
if (null == ents) {
ents = new BasicDBList();
}
String index = s.toLowerCase() + "/" + docInfo.getValue().toLowerCase();
if (null == entDedup) {
entDedup = new HashSet<String>();
}
else if (entDedup.contains(index)) { // Entity deduplication
continue;
}//TESTED (3.2)
entDedup.add(index);
if (null == entVals) {
entVals = new StringBuffer(": ");
}
else {
entVals.append(", ");
}
entVals.append(s);
String dimension = null;
if (null != endpointInfo.typeToDimensionMap) {
try {
dimension = EntityPojo.Dimension.valueOf(endpointInfo.typeToDimensionMap.get(docInfo.getValue())).toString();
}
catch (Exception e) {}
}
if (null == dimension) {
dimension = EntityPojo.Dimension.What.toString();
}//TESTED (by hand)
// (alternative to "made up" values would be to go looking in the existing docs/ents?)
// (we'll try to avoid that for now...)
BasicDBObject ent = new BasicDBObject();
ent.put(EntityPojo.disambiguated_name_, s);
ent.put(EntityPojo.type_, docInfo.getValue());
ent.put(EntityPojo.dimension_, dimension);
ent.put(EntityPojo.relevance_, 1.0);
ent.put(EntityPojo.doccount_, 1L); // (ie relative to this query)
ent.put(EntityPojo.averageFreq_, 1.0);
ent.put(EntityPojo.datasetSignificance_, 10.0); // (ie relative to this query)
ent.put(EntityPojo.significance_, 10.0); // (ie relative to this query)
ent.put(EntityPojo.frequency_, 1.0);
ent.put(EntityPojo.index_, index);
ent.put(EntityPojo.queryCoverage_, 100.0); // (ie relative to this query)
ent.put(EntityPojo.totalfrequency_, 1.0); // (ie relative to this query)
ents.add(ent);
}//TESTED (3.1, 4.*)
}
}
catch (Exception e) {
//(do nothing? null or the wrong type)
//e.printStackTrace();
}
}//end loop over various JSON objects retrieved
}//(End loop over doc conversion elements)
}//TESTED (3.*, 4.*)
if ((null == ents) && !_testMode) { // don't return unless there are any entities
return null;
}
else if (null != doc) {
// Insert mandatory fields:
// (Note the query format is a little bit different, the following fields are converted to arrays:
// sourceKey, source, communityId, mediaType)
doc.put(DocumentPojo._id_, new ObjectId());
doc.put(DocumentPojo.url_, url);
doc.put(DocumentPojo.created_, new Date());
doc.put(DocumentPojo.modified_, new Date());
doc.put(DocumentPojo.publishedDate_, new Date());
doc.put(DocumentPojo.sourceKey_, endpointInfo.parentSource.getKey());
doc.put(DocumentPojo.source_, endpointInfo.parentSource.getTitle());
doc.put(DocumentPojo.communityId_, new ObjectId(request.communityIdStrs[0]));
doc.put(DocumentPojo.mediaType_, endpointInfo.parentSource.getMediaType());
doc.put(DocumentPojo.metadata_, new BasicDBObject("json", jsonList.toArray()));
if ((null != entVals) && (entVals.length() > 165)) { // (arbitrary length)
entVals.setLength(165);
entVals.append("...");
}
doc.put(DocumentPojo.title_, new StringBuffer(endpointInfo.titlePrefix).append(": ").append(request.requestParameter).append(entVals).toString());
doc.put(DocumentPojo.entities_, ents);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(jsonList.toString());
doc.put(DocumentPojo.description_, gson.toJson(je)); // (prettified JSON)
}//TESTED (3.*, 4.*)
return doc;
}
// Convert some of the doc fields to
private static BasicDBObject convertDocToQueryFormat(BasicDBObject doc, String[] communityIdStrs) {
doc.put(DocumentPojo.sourceKey_, Arrays.asList(doc.get(DocumentPojo.sourceKey_))); // (don't need to remove #N/#NN - fed queries can't have them)
doc.put(DocumentPojo.source_, Arrays.asList(doc.get(DocumentPojo.source_)));
doc.put(DocumentPojo.mediaType_, Arrays.asList(doc.get(DocumentPojo.mediaType_)));
doc.put(DocumentPojo.communityId_, communityIdStrs);
return doc;
}//TESTED (by hand)
private static String buildScriptUrl(String mergeKey, String entityIndex) {
String url = new StringBuilder().append("inf://federated/").append(mergeKey).append("/").append(entityIndex).toString();
return url;
}//TESTED (by hand)
/////////////////////////////////////////////////
// CACHE UTILITIES
public static boolean TEST_MODE_ONLY = false;
public static DBCollection getCacheCollection() {
if (TEST_MODE_ONLY) {
return MongoDbManager.getCollection("test", "fed_query_cache");
}
else {
return MongoDbManager.getIngest().getFederatedCache();
}
}
private static boolean _staticInitializer = false;
private static long _lastChecked = -1L;
private BasicDBObject getCache(String url, SourceFederatedQueryConfigPojo endpoint) {
if ((null != endpoint.cacheTime_days) && (endpoint.cacheTime_days <= 0)) { // cache disabled
return null;
}
DBCollection endpointCacheCollection = getCacheCollection();
if (!_staticInitializer) {
_staticInitializer = true;
endpointCacheCollection.ensureIndex(new BasicDBObject(SimpleFederatedCache.expiryDate_, 1));
}
BasicDBObject cacheObj = (BasicDBObject) endpointCacheCollection.findOne(new BasicDBObject(SimpleFederatedCache._id_, url));
if (null == cacheObj) {
return null;
}
// else found something, means there's stuff in the DB
// so check it's not too big:
Date now = new Date();
if ((-1 == _lastChecked) || (now.getTime() > (_lastChecked + (600L*1000L)))) { // (only check every 10 minutes)
if (endpointCacheCollection.count() > SimpleFederatedCache.QUERY_FEDERATION_CACHE_CLEANSE_SIZE) {
_lastChecked = now.getTime();
// Remove everything with expiry date older than now
endpointCacheCollection.remove(new BasicDBObject(SimpleFederatedCache.expiryDate_, new BasicDBObject(DbManager.lt_, new Date())));
}
}//TESTED (4.3)
Date expiryDate = cacheObj.getDate(SimpleFederatedCache.expiryDate_, now);
if (now.getTime() < expiryDate.getTime()) {
return cacheObj;
}
else {
return null;
}//TESTED (4.2)
}//TESTED (4.*)
private static final int DEFAULT_CACHE_TIME_DAYS = 5;
private void cacheApiResponse(String url, BasicDBObject toCacheJson, SourceFederatedQueryConfigPojo endpoint) {
int cacheTime_days = DEFAULT_CACHE_TIME_DAYS;
if (null != endpoint.cacheTime_days) {
cacheTime_days = endpoint.cacheTime_days;
}
if (cacheTime_days <= 0) { // Disable _request_ cache (to disable all caching include doc caching use -1)
return;
}
DBCollection endpointCacheCollection = getCacheCollection();
BasicDBObject toCacheObj = new BasicDBObject(SimpleFederatedCache._id_, url);
toCacheObj.put(SimpleFederatedCache.cachedJson_, toCacheJson);
toCacheObj.put(SimpleFederatedCache.expiryDate_, new Date(new Date().getTime() + cacheTime_days*3600L*24L*1000L));
toCacheObj.put(SimpleFederatedCache.created_, new Date());
endpointCacheCollection.save(toCacheObj);
}//TESTED (3.1, 4.*)
// Document level caching, although it effectively serves as a mostly redundant request cache,
// It's actually used to allow users to save federated query documents in their buckets
public static void simpleDocCache(FederatedRequest request, BasicDBObject doc) {
if (null != request.cachedDoc_expired) {
ObjectId updateId = request.cachedDoc_expired.getObjectId(DocumentPojo.updateId_);
if (null != updateId) {
doc.put(DocumentPojo.updateId_, updateId);
}
else {
doc.put(DocumentPojo.updateId_, request.cachedDoc_expired.getObjectId(DocumentPojo._id_));
}
BasicDBObject docUpdate = new BasicDBObject(DocumentPojo.url_, doc.getString(DocumentPojo.url_));
docUpdate.put(DocumentPojo.sourceKey_, doc.getString(DocumentPojo.sourceKey_));
DbManager.getDocument().getMetadata().remove(docUpdate);
//DEBUG
if (_DEBUG) _logger.debug("DEB: postQA4a: re-cached ... " + docUpdate.toString() + ": " + doc.getObjectId(DocumentPojo.updateId_));
}
else if (null == request.cachedDoc) { // if no currently cached doc, simply save what we have
//DEBUG
if (_DEBUG) _logger.debug("DEB: postQA4b: cached ... " + doc);
DbManager.getDocument().getMetadata().save(doc);
}
// (else already have a valid cached doc so nothing to do)
}
public static boolean checkDocCache_isExpired(BasicDBObject cachedDoc, SourceFederatedQueryConfigPojo endpoint) {
if (null == endpoint.cacheTime_days)
endpoint.cacheTime_days = DEFAULT_CACHE_TIME_DAYS;
Date now = new Date();
long cacheThreshold = cachedDoc.getDate(DocumentPojo.created_, now).getTime() + endpoint.cacheTime_days*3600L*24L*1000L;
if (cacheThreshold < now.getTime()) // (ie doc-creation-time + cache is earlier than now => time to decache)
{
//DEBUG
if (_DEBUG) _logger.debug("DEB: preQA6zz: Cache expired: " + cachedDoc.getString(DocumentPojo.url_) + ": " + new Date(cacheThreshold) + " vs " + now);
return true;
}
else
return false;
}//TESTED
private static BasicDBObject getCachedApiResponse(String scriptResult) {
Object parsedScriptResult;
BasicDBObject outResult;
try {
parsedScriptResult = com.mongodb.util.JSON.parse(scriptResult);
}
catch (Exception e) {
throw new RuntimeException("Error deserializing " + scriptResult + ": " + e.getMessage(), e);
}
if (parsedScriptResult instanceof BasicDBObject) {
outResult = (BasicDBObject) parsedScriptResult;
}
else if (parsedScriptResult instanceof BasicDBList) {
outResult = new BasicDBObject(SimpleFederatedCache.array_, parsedScriptResult);
}
else if (parsedScriptResult instanceof String) {
outResult = new BasicDBObject(SimpleFederatedCache.value_, parsedScriptResult);
}
else {
throw new RuntimeException("Error deserializing " + scriptResult + ": " + parsedScriptResult);
}
try {
MongoDbUtil.enforceTypeNamingPolicy(outResult, 0);
}
catch (Exception ee) {
throw new RuntimeException("Error deserializing " + scriptResult + ": " + ee.getMessage(), ee);
}
return outResult;
}//TESTED (c/p from tested code though I deleted the test cases)
private static boolean isComplexSource(SourcePojo src) {
return (null != src.getProcessingPipeline()) && (src.getProcessingPipeline().size() > 1);
}
private static boolean checkIfNeedToClearCache(BasicDBObject cachedVal, SourcePojo src)
{
BasicDBObject cachedJson = (BasicDBObject) cachedVal.get(SimpleFederatedCache.cachedJson_);
if (null == cachedJson) {
return true; // (corrupt cache)
}
boolean isComplexSrc = isComplexSource(src);
if (isComplexSrc) { // check API response
Date createdDate = (Date) cachedVal.get(SimpleFederatedCache.created_);
if (null == createdDate) {
return true; // (needs date for doc caching code so just remove from cache and re-create)
}
}
if ((1 == cachedJson.size()) && (cachedJson.get(SimpleFederatedCache.__infinite__value_) instanceof String)) {
// ie if complex source, return false - no need to clear cache
return !isComplexSrc;
}
else { // opposite
return isComplexSrc;
}
}//TESTED (by hand - all 4 combos)
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// (my own threading)
public abstract class FederatedHarvest extends Thread {
public FederatedRequest request;
public SimpleFederatedQueryEngine queryEngine;
}
public class FederatedJythonHarvest extends FederatedHarvest {
public void run() {
String scriptResult = null;
LinkedList<String> debugLog = queryEngine._testMode ? new LinkedList<String>() : null;
try {
if (null != request.cachedResult) { // we have a cached value but are in complex mode so can't immediately
BasicDBObject cachedJson = (BasicDBObject) request.cachedResult.get(SimpleFederatedCache.cachedJson_);
scriptResult = (String) cachedJson.get(SimpleFederatedCache.__infinite__value_);
}
else {
scriptResult = queryEngine.performImportPythonScript(request.endpointInfo.importScript, request.requestParameter, request.fullQuery, request.endpointInfo.parentSource.getOwnedByAdmin(), debugLog);
}
}
catch (Exception e) {
request.errorMessage = e;
return;
}
try {
if (isComplexSource(request.endpointInfo.parentSource)) {
DocumentPojo doc = new DocumentPojo();
// Fields that are specific to the federated query type:
doc.setFullText(scriptResult);
doc.setUrl(buildScriptUrl(request.mergeKey, request.queryIndex));
// (always cache complex source pipeline results like this)
request.scriptResult = new BasicDBObject(SimpleFederatedCache.__infinite__value_, scriptResult);
if ((null != debugLog) && !debugLog.isEmpty()) {
request.scriptResult.put("$logs", debugLog);
}
handleComplexDocProcessing(doc, request, _cacheMode);
}
else { // simple case:
// In this simple case, the output has to be JSON
request.scriptResult = getCachedApiResponse(scriptResult);
if ((null != debugLog) && !debugLog.isEmpty()) {
request.scriptResult.put("$logs", debugLog);
}
}//(END simple vs complex post processing case)
}
catch (Exception e) {
request.errorMessage = e;
return;
}
}
}//TESTED (by hand)
public class FederatedSimpleHarvest extends FederatedHarvest {
public void run() {
// 1) Kick off all the requests asynchronously
BasicDBList bsonArray = new BasicDBList();
StringBuffer sb = new StringBuffer();
try {
LinkedList<FederatedRequest> asyncRequestsPerQuery = new LinkedList<FederatedRequest>();
for (SourceFederatedQueryConfigPojo.FederatedQueryEndpointUrl httpRequest: request.endpointInfo.requests) {
FederatedRequest requestOverview = createSimpleHttpEndpoint_includingCache(
request.requestParameter, request.queryIndex, request.communityIdStrs,
request.endpointInfo, httpRequest, null);
if (_DEBUG) _logger.debug("DEB: FederatedSimpleHarvest: Build request: " + httpRequest.endPointUrl);
asyncRequestsPerQuery.add(requestOverview);
}//(end loop over multiple requests
//TESTED (by hand)
// 2) Combine the results (waiting asyncronously for the results) - see the mergeKey code equivalent for simple queries
while (!asyncRequestsPerQuery.isEmpty()) {
Iterator<FederatedRequest> it = asyncRequestsPerQuery.iterator();
while (it.hasNext()) {
FederatedRequest requestOverview = it.next();
if (null != requestOverview.cachedResult) { // cached result, note must be in format cachedJson.__infinite__value (else will have been discarded)
BasicDBObject jsonCache = (BasicDBObject) requestOverview.cachedResult.get(SimpleFederatedCache.cachedJson_);
if (null != jsonCache) {
String s = (String) jsonCache.get(SimpleFederatedCache.__infinite__value_);
if (null != s) {
//DEBUG
if (_DEBUG) _logger.debug("DEB: FederatedSimpleHarvest: found cached element: " + requestOverview.cachedResult);
bsonArray.add(s);
sb.append(s).append("\n\n");
it.remove();
continue;
}
}
}//TESTED (by hand)
//IF HERE THEN CACHE DIDN'T EXIST OR FAILED (see continue above)
if (requestOverview.responseFuture.isDone()) {
it.remove();
Response endpointResponse = requestOverview.responseFuture.get();
requestOverview.asyncClient.close();
requestOverview.asyncClient = null;
String jsonStr = endpointResponse.getResponseBody();
String url = endpointResponse.getUri().toURL().toString();
//DEBUG
if (_DEBUG) _logger.debug("DEB: FederatedSimpleHarvest: found new element: " + url + " = " + jsonStr);
BasicDBObject bson = new BasicDBObject(SimpleFederatedCache.__infinite__value_, jsonStr);
cacheApiResponse(url, bson, request.endpointInfo);
bsonArray.add(jsonStr);
sb.append(jsonStr).append("\n\n");
}//TESTED (by hand)
}
if (!asyncRequestsPerQuery.isEmpty()) { // wait 100ms to stop thrashing
try { Thread.sleep(100); } catch (Exception e) {}
}
} //TESTED (by hand)
}
catch (Exception e) {
request.errorMessage = e;
return;
}
// 3) Run the document processing
DocumentPojo doc = new DocumentPojo();
// Fields that are specific to the federated query type:
doc.setFullText(sb.toString());
if (bsonArray.size() > 1) {
doc.addToMetadata("__FEDERATED_REPLIES__", bsonArray.toArray());
}
doc.setUrl(buildScriptUrl(request.mergeKey, request.queryIndex));
// (always cache complex source pipeline results like this)
handleComplexDocProcessing(doc, request, _cacheMode);
}
}
public class FederatedScriptHarvest extends FederatedHarvest {
public void run() {
String scriptResult = null;
try {
if (null != request.cachedResult) { // we have a cached value but are in complex mode so can't immediately
BasicDBObject cachedJson = (BasicDBObject) request.cachedResult.get(SimpleFederatedCache.cachedJson_);
scriptResult = (String) cachedJson.get(SimpleFederatedCache.__infinite__value_);
}
else { // Use the TextExtractorExternalScript function:
TextExtractorExternalScript extractor = new TextExtractorExternalScript();
LinkedHashMap<String, String> dummyExtractorOptions = new LinkedHashMap<String, String>();
String[] args = request.endpointInfo.importScript.split("\\s+");
int i = 0;
for (String arg: args) {
arg = arg.replace("$1", request.requestParameter);
if (0 == i) {
dummyExtractorOptions.put("script", arg);
}
else {
dummyExtractorOptions.put("arg" + i, arg);
}
i++;
}
if (null != request.endpointInfo.queryTimeout_secs) {
dummyExtractorOptions.put("timeout", Long.toString(request.endpointInfo.queryTimeout_secs.longValue()*1000L));
//(convert to ms then to string)
}
SourcePojo dummySrc = new SourcePojo();
dummySrc.setOwnerId(request.endpointInfo.parentSource.getOwnerId());
dummySrc.setExtractorOptions(dummyExtractorOptions);
dummySrc.setCommunityIds(request.endpointInfo.parentSource.getCommunityIds());
DocumentPojo dummyDoc = new DocumentPojo();
dummyDoc.setTempSource(dummySrc);
extractor.extractText(dummyDoc);
scriptResult = dummyDoc.getFullText();
if (null == scriptResult) {
request.errorMessage = new RuntimeException("Unknown problem, script didn't return text: " + dummyExtractorOptions.toString());
return;
}
}
}
catch (Exception e) {
request.errorMessage = e;
return;
}
try {
if (isComplexSource(request.endpointInfo.parentSource)) {
DocumentPojo doc = new DocumentPojo();
// Fields that are specific to the federated query type:
doc.setFullText(scriptResult);
doc.setUrl(buildScriptUrl(request.mergeKey, request.queryIndex));
// (always cache complex source pipeline results like this)
request.scriptResult = new BasicDBObject(SimpleFederatedCache.__infinite__value_, scriptResult);
handleComplexDocProcessing(doc, request, _cacheMode);
}
else { // simple case:
// In this simple case, the output has to be JSON
request.scriptResult = getCachedApiResponse(scriptResult);
}//(END simple vs complex post processing case)
}
catch (Exception e) {
request.errorMessage = e;
return;
}
}
}
///////////////////////////////////////////////////////////////////////////////
private String performImportPythonScript(String importScript, String entityValue, AdvancedQueryPojo query, Boolean isSrcAdmin, LinkedList<String> debugLog) {
String modCode = importScript;
try {
// Create a return value
String fnName = "var" + new ObjectId();
// Pull all the imports, evaluate them outside the security manager
Pattern importRegex = Pattern.compile("^\\s*(?:import|from)\\s[^\n]+", Pattern.MULTILINE);
Matcher m = importRegex.matcher(importScript);
StringBuffer sbImports = new StringBuffer();
while (m.find()) {
sbImports.append(m.group()).append('\n');
}
if (null != query) {
_pyEngine.put("_query", query.toApi()); // full query
}
if (null != entityValue) {
_pyEngine.put("_entityValue", entityValue); // allow either entityValue
}
_pyEngine.eval(sbImports.toString());
// Logging function
if (null != debugLog) {
String logName = "log" + new ObjectId();
_pyEngine.put(logName, debugLog);
_pyEngine.eval("def ikanow_log(logmsg):\n " + logName + ".add(logmsg)\n\n");
}
else {
_pyEngine.eval("def ikanow_log(logmsg):\n pass\n\n");
}
// Enable SSL everywhere (https://wiki.python.org/jython/NewSocketModule#SSLSupport)
//http://tech.pedersen-live.com/2010/10/trusting-all-certificates-in-jython/
//didn't work: http://jython.xhaus.com/installing-an-all-trusting-security-provider-on-java-and-jython/
_pyEngine.eval(IOUtils.toString(SimpleFederatedQueryEngine.class.getResourceAsStream("JythonTrustManager.py")));
// Now run the script
modCode = m.replaceAll("");
modCode = modCode.replaceAll("\n([^\n]+)$", "\n" + fnName + " = " + "$1");
if ((null == isSrcAdmin) || !isSrcAdmin) {
_scriptingSecurityManager.eval(_pyEngine, modCode);
}
else {
_pyEngine.eval(modCode);
}
// Get return value
Object result = _pyEngine.get(fnName.toString());
//DEBUG
if (_DEBUG) _logger.debug("DEB: T1: Return val from script: " + result);
if (null == result) {
throw new RuntimeException("Null return from script - final line needs to evaluate expression to return, eg 'response.read()' or 'varname'");
}//TESTED (by hand)
return result.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
catch (Error ee) {
throw new RuntimeException(ee);
}
}//TESTED
///////////////////////////////////////////////////////////////////////////////
public static void handleComplexDocProcessing(DocumentPojo doc, FederatedRequest request, boolean cacheMode) {
List<DocumentPojo> docWrapper = null;
if (null != request.cachedResult) { // API result was cached, so docs might be
Date createdDate = request.cachedResult.getDate(SimpleFederatedCache.created_);
if ((null != request.endpointInfo.parentSource.getModified()) && (request.endpointInfo.parentSource.getModified().getTime() > createdDate.getTime())) {
//DEBUG
if (_DEBUG) _logger.debug("DEB: HCDP0: cache out of date, src=" + request.endpointInfo.parentSource.getModified() + " cache=" + createdDate);
request.cachedResult = null; // (clear cache)
}
if (null != request.cachedResult) { // see if we can get the docs from the DB instead of from the harvester
BasicDBObject query = new BasicDBObject(DocumentPojo.sourceKey_, request.endpointInfo.parentSource.getKey());
query.put(DocumentPojo.sourceUrl_, doc.getUrl());
DBCursor dbc = DbManager.getDocument().getMetadata().find(query);
if (dbc.hasNext()) {
docWrapper = DocumentPojo.listFromDb(dbc, DocumentPojo.listType());
if (null == docWrapper) { // (shouldn't ever happen)
request.cachedResult = null;
}
else {
//DEBUG
if (_DEBUG) _logger.debug("DEB: HCDP2: cache, found docs=" + docWrapper.size());
}
}
else { // last chance to clear cache
//DEBUG
if (_DEBUG) _logger.debug("DEB: HCDP3: empty cache from " + query);
request.cachedResult = null;
}
}
}//TESTED (by hand)
// Need to set this 1) to avoid the harvest controller from deduplicating and 2) so i can retrieve those docs
if (null == docWrapper) { // Go ahead and harvest these docs
doc.setSourceUrl(doc.getUrl());
doc.setId(new ObjectId());
doc.setSourceKey(request.endpointInfo.parentSource.getKey());
doc.setSource(request.endpointInfo.parentSource.getTitle());
doc.setMediaType(request.endpointInfo.parentSource.getMediaType());
doc.setTitle(request.endpointInfo.titlePrefix);
Date d = new Date();
doc.setCreated(d);
doc.setModified(d);
docWrapper = new ArrayList<DocumentPojo>(1);
ArrayList<DocumentPojo> dummyDocs = new ArrayList<DocumentPojo>(0);
docWrapper.add(doc);
try {
HarvestController hc = new HarvestController();
HarvestControllerPipeline hcp = new HarvestControllerPipeline();
hcp.extractSource_preProcessingPipeline(request.endpointInfo.parentSource, hc);
hcp.enrichSource_processingPipeline(request.endpointInfo.parentSource, docWrapper, dummyDocs, dummyDocs);
//DEBUG
if (_DEBUG) _logger.debug("DEB: HCDP4: created " + docWrapper.size() + " doc(s)");
}
catch (IOException e) {
throw new RuntimeException("Complex source processing", e);
}
}
request.complexSourceProcResults = docWrapper;
}
public static void handleComplexDocCaching(FederatedRequest request, boolean cacheMode, ScoringUtils scoreStats) {
List<DocumentPojo> docWrapper = request.complexSourceProcResults;
//In non-test mode .. Go through the list of docs and work out what the deal is with caching, ie remove docs + add update ids
//Also go through and set default scores for any entities that haven't been scored based on existing docs
BasicDBObject query = new BasicDBObject(DocumentPojo.sourceKey_, request.endpointInfo.parentSource.getKey());
BasicDBObject fields = new BasicDBObject(DocumentPojo.updateId_, 1); // (ie _id and updateId only)
String srcUrl = null;
for (DocumentPojo outDoc: docWrapper) {
if (null == srcUrl) {
srcUrl = outDoc.getSourceUrl();
}
// Always make the text non-transient, so gets stored
outDoc.makeFullTextNonTransient();
if (null == outDoc.getId()) {
outDoc.setId(new ObjectId());
}
if (cacheMode && (null == request.cachedResult)) { // (if result not previously cached)
// Step 1: deduplication
query.put(DocumentPojo.url_, outDoc.getUrl());
BasicDBObject outVal = (BasicDBObject) DbManager.getDocument().getMetadata().findOne(query, fields);
if (null != outVal) {
//DEBUG
if (_DEBUG) _logger.debug("DEB: HCDC1: update cache from : " + outVal + " for " + outDoc.getUrl());
// Use updateId if it exists, otherwise _id
ObjectId updateId = outVal.getObjectId(DocumentPojo.updateId_);
if (null == updateId) {
updateId = outVal.getObjectId(DocumentPojo._id_);
}
outDoc.setUpdateId(updateId);
}
}//TESTED (by hand - single and multiple docs mode)
// Step 2: add fake scores to all the entities that didn't get scores from the aggregation manager
if (null != outDoc.getEntities()) for (EntityPojo ent: outDoc.getEntities()) {
boolean fakeStats = true;
if (null != scoreStats) {
if (scoreStats.fillInEntityStatistics(ent)) {
fakeStats = false;
}
}
if (fakeStats) {
ent.setDoccount(1L);
ent.setTotalfrequency(1L);
ent.setDatasetSignificance(10.0);
ent.setSignificance(10.0);
ent.setQueryCoverage(100.0);
}
//DEBUG
if (_DEBUG) _logger.debug("DEB: HCDC2: entity: " + ent.getIndex() + " , sig=" + ent.getDatasetSignificance());
}//TESTED
if (null != outDoc.getAssociations()) for (AssociationPojo assoc: outDoc.getAssociations()) {
assoc.setAssoc_sig(10.0);
assoc.setDoccount(1L);
}
}//TESTED (by hand - overlapping and non-overlapping case)
if (cacheMode && (null == request.cachedResult)) { // (if result not previously cached)
//Remove old docs now we have new ones
DbManager.getDocument().getMetadata().remove(query); // remove everything with this specific URL (ie simple source)
query.remove(DocumentPojo.url_);
query.put(DocumentPojo.sourceUrl_, srcUrl);
DbManager.getDocument().getMetadata().remove(query); // remove everything with this specific _source_ URL (ie docs generated from this URL)
// Now cache all the existing docs:
@SuppressWarnings("unchecked")
ArrayList<Object> tmpDocList = (ArrayList<Object>) DocumentPojo.listToDb(docWrapper, DocumentPojo.listType());
DbManager.getDocument().getMetadata().insert(tmpDocList.toArray(new BasicDBObject[0]));
//DEBUG
if (_DEBUG) _logger.debug("DEB: HCDC3: remove/insert cache: " + query.toString());
}//TESTED (by hand - single and multiple docs)
}//TESTED
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// TEST UTILITIES
// Check 1.x test results
public void test_CheckIfQueryLaunched(String testName, boolean shouldWork) {
FederatedRequest request = null;
if (null != this._asyncRequestsPerQuery) {
if (!this._asyncRequestsPerQuery.isEmpty()) {
request = this._asyncRequestsPerQuery.peek();
if (this._asyncRequestsPerQuery.size() > 1) {
System.out.println("*** " + testName + ": + too many async requests");
System.exit(-1);
}
}
}
if (shouldWork) {
if (null == request) {
System.out.println("*** " + testName + ": Expected request, got none");
System.exit(-1);
}
}
else {
if (null != request) {
if (null != request.responseFuture) {
System.out.println("*** " + testName + ": incorrectly added " + request.requestParameter);
System.exit(-1);
}
else if ((null == request.cachedResult) && (null == request.cachedDoc)) {
System.out.println("*** " + testName + ": no request, not cached " + request.cachedResult);
System.exit(-1);
}
}
}
}//TESTED (by hand - who tests the tester?!)
public void test_CheckIfDocAdded(String testName, List<BasicDBObject> docs) {
// 1) Did a doc get added?
if (2 != docs.size()) {
System.out.println("*** " + testName + ": didn't add doc? " + docs.size());
System.exit(-1);
}
// 2) Was it the right doc?
BasicDBObject doc = docs.get(0);
doc.remove(DocumentPojo._id_);
doc.remove(DocumentPojo.created_);
doc.remove(DocumentPojo.modified_);
doc.remove(DocumentPojo.publishedDate_);
String docToCheck =
"{ \"displayUrl\" : \"http://test3_1\" , \"url\" : \"inf://federated/fakeendpoint.123/test3_1/testentityin\" , \"sourceKey\" : [ \"fakeendpoint.123\"] , \"source\" : [ \"fakeendpoint\"] , \"communityId\" : [ \"4c927585d591d31d7b37097a\"] , \"mediaType\" : [ \"Report\"] , \"metadata\" : { \"json\" : [ { \"test\" : { \"field\" : [ \"test3_1\" , \"test3_1\"] , \"field2\" : \"http://test3_1\"}}]} , \"title\" : \"fake endpoint: : test3_1: test3_1\" , \"entities\" : [ { \"disambiguated_name\" : \"test3_1\" , \"type\" : \"TestEntityOut\" , \"dimension\" : \"What\" , \"relevance\" : 1.0 , \"doccount\" : 1 , \"averageFreq\" : 1.0 , \"datasetSignificance\" : 10.0 , \"significance\" : 10.0 , \"frequency\" : 1.0 , \"index\" : \"test3_1/testentityout\" , \"queryCoverage\" : 100.0 , \"totalfrequency\" : 1.0}] , \"description\" : \"[\\n {\\n \\\"test\\\": {\\n \\\"field\\\": [\\n \\\"test3_1\\\",\\n \\\"test3_1\\\"\\n ],\\n \\\"field2\\\": \\\"http://test3_1\\\"\\n }\\n }\\n]\" , \"aggregateSignif\" : 115.0 , \"queryRelevance\" : 105.0 , \"score\" : 110.0}";
if (!docToCheck.equals(doc.toString())) {
System.out.println("*** " + testName + ": document incorrect:\n" + docToCheck + "\nVS\n" + doc.toString());
System.exit(-1);
}
// 3) Did the doc get cached?
DBCollection endpointCacheCollection = getCacheCollection();
String hardwiredCacheId = "http://localhost:8186/test/test3_1/?param1=test3_1";
BasicDBObject cachedVal = (BasicDBObject) endpointCacheCollection.findOne(new BasicDBObject(SimpleFederatedCache._id_, hardwiredCacheId));
if (null == cachedVal) {
System.out.println("*** " + testName + ": no cache for: " + doc.get(DocumentPojo.url_) + " / " + hardwiredCacheId);
System.exit(-1);
}
else {
Date expiryDate = cachedVal.getDate(SimpleFederatedCache.expiryDate_, null);
if ((null == expiryDate) || ((new Date().getTime() - expiryDate.getTime()) > 10*1000L)) {
System.out.println("*** " + testName + ": expiry date for: " + doc.get(DocumentPojo.url_) + ": " + expiryDate + " vs now= " + new Date());
System.exit(-1);
}
BasicDBObject cachedJson = (BasicDBObject) cachedVal.get(SimpleFederatedCache.cachedJson_);
Object docVal = null;
try {
Object[] docVals = (Object[] ) ((BasicDBObject)doc.get(DocumentPojo.metadata_)).get("json");
docVal = docVals[0];
}
catch (Exception e) {
@SuppressWarnings("rawtypes")
Collection docVals = (Collection) ((BasicDBObject)doc.get(DocumentPojo.metadata_)).get("json");
docVal = docVals.iterator().next();
}
if ((null == cachedJson) || !cachedJson.equals(docVal)) {
System.out.println("*** " + testName + ": cache: " + doc.get(DocumentPojo.url_) + ": cached val incorrect:\n" + docVal + "\nVS\n" + cachedJson);
System.exit(-1);
}
}
}//TESTED (by hand)
///////////////////////////////////////////////////////////////////////////////
// (general test utils)
// Reset state ready for next test
public void test_queryClear(boolean clearCacheAlso) {
if (null != this._asyncRequestsPerQuery) {
for (FederatedRequest req: this._asyncRequestsPerQuery) {
try {
req.responseFuture.get();
if (null != req.asyncClient) {
req.asyncClient.close();
}
}
catch (Exception e) {}
}
this._asyncRequestsPerQuery.clear();
}
if (clearCacheAlso) {
DBCollection endpointCacheCollection = getCacheCollection();
endpointCacheCollection.remove(new BasicDBObject());
}
}//TESTED (by hand - who tests the tester?!)
public void test_cacheExpire() {
DBCollection endpointCacheCollection = getCacheCollection();
DBCursor dbc = endpointCacheCollection.find();
for (DBObject cacheEntryObj: dbc) {
BasicDBObject cacheEntry = (BasicDBObject) cacheEntryObj;
cacheEntry.put(SimpleFederatedCache.expiryDate_, new Date(new Date().getTime() - 3600L*1000L)); // (ie expired an hour ago)
endpointCacheCollection.save(cacheEntry);
}
}
public void test_cacheClear(boolean clearApiCache, boolean clearDocCache, String key) {
// (DO NOT COMMENT THIS OUT)
SimpleFederatedQueryEngine.TEST_MODE_ONLY = true;
// Clear doc_metadata table before running
if (clearDocCache) {
MongoDbManager.getDocument().getMetadata().remove(new BasicDBObject(DocumentPojo.sourceKey_, key));
}
if (clearApiCache) {
// (note: this only deletes the test collection because of TEST_MODE_ONLY code)
SimpleFederatedQueryEngine.getCacheCollection().remove(new BasicDBObject()); // (clear test collection for testing)
}
}
public void test_cacheFill(String testName, boolean fill, boolean shouldBeFull) {
DBCollection endpointCacheCollection = getCacheCollection();
if (fill) {
for (long i = 0; i < (1 + SimpleFederatedCache.QUERY_FEDERATION_CACHE_CLEANSE_SIZE); ++i) {
SimpleFederatedCache fakeCacheElement = new SimpleFederatedCache();
fakeCacheElement.expiryDate = new Date(new Date().getTime() - 3600L*1000L); // (ie expired an hour ago)
fakeCacheElement._id = testName + "_" + i;
fakeCacheElement.cachedJson = new BasicDBObject();
endpointCacheCollection.save(fakeCacheElement.toDb());
}
_lastChecked = new Date(new Date().getTime() - 602L*1000L).getTime();
}
long count = endpointCacheCollection.count();
if (shouldBeFull) {
if (count < SimpleFederatedCache.QUERY_FEDERATION_CACHE_CLEANSE_SIZE) {
System.out.println("*** " + testName + ": cache should just contain many elements, not: " + count);
System.exit(-1);
}
}
else {
if (1 != count) {
System.out.println("*** " + testName + ": cache should just contain one element, not: " + count);
System.exit(-1);
}
}
}
}
| [
"apiggott@ikanow.com"
] | apiggott@ikanow.com |
8a7a3ded885877d7965f9c5646bb17071b63c165 | f0d25d83176909b18b9989e6fe34c414590c3599 | /app/src/main/java/com/google/android/gms/internal/ya.java | b8f7773d374464f4623bd4ff40f817ef8ba5275b | [] | no_license | lycfr/lq | e8dd702263e6565486bea92f05cd93e45ef8defc | 123914e7c0d45956184dc908e87f63870e46aa2e | refs/heads/master | 2022-04-07T18:16:31.660038 | 2020-02-23T03:09:18 | 2020-02-23T03:09:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 578 | java | package com.google.android.gms.internal;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
final class ya extends ThreadLocal<CharsetDecoder> {
ya() {
}
/* access modifiers changed from: protected */
public final /* synthetic */ Object initialValue() {
CharsetDecoder newDecoder = Charset.forName("UTF8").newDecoder();
newDecoder.onMalformedInput(CodingErrorAction.REPORT);
newDecoder.onUnmappableCharacter(CodingErrorAction.REPORT);
return newDecoder;
}
}
| [
"quyenlm.vn@gmail.com"
] | quyenlm.vn@gmail.com |
9fc01c5b87362098176c5efb9243fb04f44a37f1 | 6f2fe0c5e99340c48b281f247e9a84a8b654c2c2 | /src/main/java/com/bigsea/sell/dao/OrderDetailDao.java | 182dcdf0f3010ecfcb5e02864c6fcdd09c5cf7e1 | [] | no_license | bigseaa/sell_test | b3b70a69108e9f1c486ced3d67989e8756c46c78 | 1f537a3b84142ef0dbb468fc760eee69442416a2 | refs/heads/master | 2020-03-27T23:49:30.811423 | 2018-09-15T13:38:53 | 2018-09-15T13:38:53 | 147,349,919 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 299 | java | package com.bigsea.sell.dao;
import com.bigsea.sell.dataobject.OrderDetail;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface OrderDetailDao extends JpaRepository<OrderDetail, String> {
List<OrderDetail> findByOrOrderId(String orderId);
}
| [
"506798278@qq.com"
] | 506798278@qq.com |
c503c4ab509d89f1dad1f1fd1b8c190b58643345 | 370636660b7707da92f58953c3fc41fac55e763d | /JavaStringFunctions/src/com/vaibhav/StringIntern.java | d31c22d5ece2f3507dac0fef4e6b4d54cc4f1399 | [] | no_license | rautvaibhav56/JavaStringFunctions | 90f2aa7de170b4a9f3165ea57908a021dc0536cf | 215e7cddbc1fdbb5a0ff3072a3356f646c1db2a8 | refs/heads/master | 2023-01-06T10:20:37.036972 | 2020-10-26T14:41:14 | 2020-10-26T14:41:14 | 305,065,923 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 646 | java | package com.vaibhav;
//StringIntern=>It can be used to return string from memory,
//if it is created by new keyword. It creates exact copy of heap string object in string constant pool
public class StringIntern {
static String s1 = "hello";
static String s2 = new String("hello");
public static void m() {
System.out.println(s1.equals(s2));// true =>why true???
System.out.println(s1 == s2);// false
String s3 = s2.intern();// It returns string from memory, if it is created by new keyword.
System.out.println(s1 == s3);// true
}
public static void main(String[] args) {
StringIntern.m();
}
}
| [
"krishna@timus"
] | krishna@timus |
8a6983277255a94ebb2cb1359a4173a5b48638c0 | 82f559b5ccdab6f14e2965a3864e8cbf183c8201 | /app/src/main/java/org/android/framework/engine/http/HttpRequestCallBack.java | daef119d5e152c856f6f977b6ad86d0a38577538 | [] | no_license | shenyansycn/AndroidFrameWork | c88e7ba70c4eea4777949817b33a49add2ce0cfa | 4b470a776aa69ee0895f9089bce167cee9d92462 | refs/heads/master | 2016-09-12T19:50:33.910985 | 2016-05-03T09:40:58 | 2016-05-03T09:40:58 | 57,948,348 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 190 | java | package org.android.framework.engine.http;
/**
* Created by Administrator on 2014/5/21.
*/
public interface HttpRequestCallBack {
void onSuccess(Object object);
void onFail();
}
| [
"shenyansycn@gmail.com"
] | shenyansycn@gmail.com |
bc1245770467b73c29709477c7cf58f80fbfe264 | 47984d3b623e74e8029f3b8b7422893f1bfdfefa | /src/npc/Sugar.java | cc49d7f0744203b833e1c78809c0e8c4dfbdd017 | [] | no_license | SetosanMs/MapleStory2 | 71467682165a85f6b31ee16aecce009847ee27d9 | 311bd8fa3f832f2a34dee41d43e7daf9766044a3 | refs/heads/master | 2022-12-10T00:44:55.389534 | 2020-08-26T15:22:17 | 2020-08-26T15:22:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 656 | java | package npc;
import java.io.Serializable;
import map.MapleMap;
import map.PointMapName;
import map.UpdatedMapInfor;
import maplestory.Player;
public class Sugar extends Npc implements Serializable {
private static final long serialVersionUID = 1L;
public Sugar(String image, String name, PointMapName pointMapName) {
super(image, name, pointMapName);
}
public void clearEvent(Player player) {
}
public void requestQuest(Player player) {
}
@Override
public void normalEvent(Player player) {
if(process == 25) {
player.addUpdatedMap(new UpdatedMapInfor(new PointMapName(4, 9, "초보자의숲1"), MapleMap.MAP_PORTAL_STATE));
}
}
}
| [
"hwasub1115@naver.com"
] | hwasub1115@naver.com |
bdef65a4e161ad51f5b2a8c34d74484c8e4e8036 | 7aa6236506768613a769cdbc7c65bfdddef8f22c | /src/edu/sjsu/assignment3/Main.java | 485de28e33edaf2cbd73e65109df72a7b5a6b4af | [] | no_license | fuelunit/YL_Assignment3 | 9582955f2b340e620e718954a950148cb1da1c84 | dc7ed3765d4830d3643f0570f07cac4a2b6864af | refs/heads/master | 2023-06-24T22:00:38.622842 | 2021-07-24T17:10:06 | 2021-07-24T17:10:06 | 383,597,871 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,540 | java | /*
Author : Yipeng Liu
Project : Assignment 3
Class : Main
Date : 07/06/2021
*/
package edu.sjsu.assignment3;
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
// Part 2 Tests:
System.out.println("=== Assignment 3 Part 2 Tests ===");
// startDate and endDate
LocalDate startDate = LocalDate.parse("2021-06-01");
LocalDate endDate = LocalDate.parse("2021-08-05");
// test dates
LocalDate testDate1 = LocalDate.parse("2021-06-05");
LocalDate testDate2 = LocalDate.parse("2021-07-01");
LocalDate testDate3 = LocalDate.parse("2021-08-15");
// Example 1
System.out.println("--- Example 1 ---");
Appointment appointment1 = new OnetimeAppointment("Class starts",
startDate);
System.out.println("Test Date 1 is "
+ appointment1.occursOn(testDate1)); // false
System.out.println("Test Date 2 is "
+ appointment1.occursOn(testDate2)); // false
System.out.println("Test Date 3 is "
+ appointment1.occursOn(testDate3)); // false
// Example 2
System.out.println("--- Example 2 ---");
Appointment appointment2 = new DailyAppointment("Class",
startDate, endDate);
System.out.println("Test Date 1 is "
+ appointment2.occursOn(testDate1)); // true
System.out.println("Test Date 2 is "
+ appointment2.occursOn(testDate2)); // true
System.out.println("Test Date 3 is "
+ appointment2.occursOn(testDate3)); // false (after the end date)
// Example 3
System.out.println("--- Example 3 ---");
Appointment appointment3 = new MonthlyAppointment("Meeting",
startDate, endDate);
System.out.println("Test Date 1 is "
+ appointment3.occursOn(testDate1)); // false (day of month not same)
System.out.println("Test Date 2 is "
+ appointment3.occursOn(testDate2)); // true
System.out.println("Test Date 3 is "
+ appointment3.occursOn(testDate3)); // false (after the end date)s
// Part 3 Tests:
System.out.println("=== Assignment 3 Part 3 Tests ===");
System.out.println("appointment1 compared to appointment 2: "
+ appointment1.compareTo(appointment2));
// Part 4 Tests:
System.out.println("=== Assignment 3 Part 4 Tests ===");
}
}
| [
"yipeng.liu@sjsu.edu"
] | yipeng.liu@sjsu.edu |
34eee1826851b5a2cd7d776016ceee7568cf57ee | d73e0a733b9c3e3db13754ebcda9785f6b2beaba | /Symphonie/src15/fr/umlv/symphonie/GUI/menu/view/ItemView.java | d42a82fd842f51686cb1ac44a495ebcee7b30e18 | [] | no_license | BackupTheBerlios/notemanager | 1bc815fe6202719497cd136d6224c2b36804d0e3 | fd5d8f53408e1b4ae9505c0de9df324a4b2a8843 | refs/heads/master | 2020-12-24T15:22:58.994789 | 2005-03-26T12:55:01 | 2005-03-26T12:55:01 | 40,047,450 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 726 | java | /*
* Created on 19 mars 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package fr.umlv.symphonie.GUI.menu.view;
import fr.umlv.symphonie.GUI.GUICache;
import fr.umlv.symphonie.GUI.menu.AbstractGUIMenuItem;
/**
* @author everybody
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class ItemView extends AbstractGUIMenuItem {
public ItemView(GUICache cache) {
super(cache,"view");
}
/* (non-Javadoc)
* @see fr.umlv.symphonie.GUI.menu.MenuItem#setAction()
*/
public void setAction() {
// TODO Auto-generated method stub
}
}
| [
"dalton"
] | dalton |
fa1bca4e1fae8402edf4f121f60ebc2fd1373d7a | fd98b84c6b786f7781df8862630fb0e7e73fa49d | /Check you typing speed! /Main.java | 165c98b155bef3847453df1dd1fa2e1c48dd2936 | [] | no_license | mohan1072/Playground | 8c55f4636e457c1cd02c559440bae3fab4d1af1a | 80832c4697a6b71c98f8b104ae74b4443d3a769c | refs/heads/master | 2022-11-13T06:16:03.309258 | 2020-07-11T11:46:56 | 2020-07-11T11:46:56 | 273,424,114 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 136 | java | #include<iostream>
int main()
{
int id,marks;
std::cin>>id>>marks;
if(marks>0)
std::cout<<id<<" is eligible for reward.";
} | [
"67060596+mohan1072@users.noreply.github.com"
] | 67060596+mohan1072@users.noreply.github.com |
c1d6baafd2d6e43bb4142f55a74334fb2807a952 | 0b74e91d078f30a24c51bcb0e6c125adafece2d4 | /app/src/main/java/mymusic/com/mymusic/HomeMusic/MusicGrideAdapter.java | 040016f5200ee67f1411ed3bd816a1a3673c9226 | [] | no_license | wuyanhong3/MyMusic | b448fa63adc95ea8a0e96cdbb5f45beb3b9b80a1 | cd854e99cca9c2492134e45e6003d5db91828900 | refs/heads/master | 2021-05-04T07:09:18.922814 | 2016-10-26T03:22:24 | 2016-10-26T03:22:24 | 70,570,966 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,200 | java | package mymusic.com.mymusic.HomeMusic;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import mymusic.com.mymusic.R;
/**
* Created by Administrator on 2016/9/8.
*
* 动态添加内容
*
*/
public class MusicGrideAdapter extends BaseAdapter{
Uri albumArtUri = Uri
.parse("content://media/external/audio/albumart");
private LayoutInflater layoutInflater;
private ArrayList<MusicBean> musicList=new ArrayList<>();
private Context context;
public MusicGrideAdapter(Context context){
this.context=context;
this.layoutInflater=LayoutInflater.from(context);
}
public void setMusicList(ArrayList<MusicBean> musicList){
this.musicList=musicList;
notifyDataSetChanged();
}
@Override
public int getCount() {
return musicList.size();
}
@Override
public Object getItem(int position) {
return musicList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
HolderView holderView;
if(convertView==null){
convertView=layoutInflater.inflate(R.layout.home_musiclist_layout,null);
holderView=new HolderView();
holderView.musicName= (TextView) convertView.findViewById(R.id.home_music_list_title);
holderView.musicPhoto= (ImageView) convertView.findViewById(R.id.home_music_list_picture);
holderView.musicSinger= (TextView) convertView.findViewById(R.id.home_music_list_singer);
convertView.setTag(holderView);
}else{
holderView= (HolderView) convertView.getTag();
}
MusicBean musicBean= (MusicBean) getItem(position);
holderView.musicName.setText(musicBean.getTitle());
// Bitmap icon=BitmapUtil.getArtwork(context,musicBean.getId(),musicBean.getAlbumid(),false,true);
Bitmap icon=decodeSampledBitmapFromResource(musicBean.getImage(),convertView.getResources(),3,110,110);
holderView.musicPhoto.setImageBitmap(icon == null ? BitmapFactory.decodeResource(convertView.getResources(),R.mipmap.music1):icon);
holderView.musicSinger.setText(musicBean.getArtist());
return convertView;
}
/**
* 设置载入图片大小,防止图片占用内存过大;
* */
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// 源图片的高度和宽度
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// 计算出实际宽高和目标宽高的比率
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高
// 一定都会大于等于目标的宽和高。
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(String name, Resources res, int resId,
int reqWidth, int reqHeight) {
// 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
BitmapFactory.decodeFile(name,options);
// 调用上面定义的方法计算inSampleSize值
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// 使用获取到的inSampleSize值再次解析图片
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
// return BitmapFactory.decodeResource(res, resId, options);
return BitmapFactory.decodeFile(name,options);
}
class HolderView{
TextView musicName,musicSinger;
ImageView musicPhoto;
}
}
| [
"wyh9393@sina.com"
] | wyh9393@sina.com |
510f0f21dbfaad3dbf68d9fc980a0c09fbc6e1c6 | 752769cdbde5709ec894e46509ea26d072f63860 | /jsf-demos/mservice/src/main/java/com/jsf/service/OrderRestService.java | c30595d7fa608a11b20fa82df0e1eedcd9a0a3f7 | [
"BSD-3-Clause"
] | permissive | cjg208/JSF | dca375b472d16e2a7cb9ac56e939b63d60cc86cf | 693041b6bb6a1b753d3be072c8ee7d879622e6b5 | refs/heads/master | 2023-01-01T08:39:47.925873 | 2020-10-27T08:35:08 | 2020-10-27T08:35:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,177 | java | package com.jsf.service;
import com.jsf.model.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* Description: Feign方式实现,自带负载均衡
* User: xujunfei
* Date: 2018-02-27
* Time: 10:27
*/
// 如果接入网关(目前默认使用nacos),FeignClient设置为nc-gateway
@FeignClient(value = "ms-provider", fallback = OrderRestServiceHystrix.class)
public interface OrderRestService {
/**
* 下单服务
*
* @param userId
* @param productId
* @return
*/
@GetMapping("/order")
String order(@RequestParam("userId") Integer userId, @RequestParam("productId") Integer productId);
/**
* GET请求多个参数
*
* @param map
* @return
*/
@GetMapping("/get")
String get(@RequestParam Map<String, Object> map);
/**
* POST请求多个参数
*
* @param user
* @return
*/
@PostMapping("/post")
String post(@RequestBody User user);
@GetMapping("/getUserById/{id}")
User getUserById(@PathVariable("id") Integer id);
}
| [
"809573150@qq.com"
] | 809573150@qq.com |
7eeb0a97e499e9f2cb3d9d59c9f8644417d4222b | 12c766729bb082bf593578fa982981ef65c3fc9b | /SmartCity/src/sjtu/dclab/smartcity/ui/minzheng/CivilAffairHomeAty.java | 7f415bb8bb85d39fe1844d5dccd908a7c3045e7c | [] | no_license | m122469119/smartcity-android | 876ef5b64762ffe4562856d879d2426b88d1af17 | a89d55f28bb18370ba54b96fc268adc5f0c34456 | refs/heads/main | 2021-06-08T22:00:25.097541 | 2015-09-28T03:06:17 | 2015-09-28T03:06:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,613 | java | package sjtu.dclab.smartcity.ui.minzheng;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import sjtu.dclab.smartcity.R;
/**
* Created by hp on 2015/7/30.
*/
public class CivilAffairHomeAty extends Activity implements View.OnClickListener {
private ListView listView;
private ImageButton ib1,ib2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.civil_affair_home);
ib1 = (ImageButton)findViewById(R.id.civil_left);
ib1.setOnClickListener(this);
ib2 = (ImageButton)findViewById(R.id.civil_right);
this.ib2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(CivilAffairHomeAty.this, CivilAffairEditAty.class);
startActivity(intent);
}
});
listView = (ListView)findViewById(R.id.civil_affair_list);
SimpleAdapter adapter = new SimpleAdapter(this,getData(), R.layout.image_listitem,
new String[]{"title","info","img"},
new int[]{R.id.title, R.id.info, R.id.img});
listView.setAdapter(adapter);
}
private List<Map<String, Object>> getData(){
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("title", "高龄服务");
map.put("info", "example info...");
map.put("img", R.drawable.tmp_img);
list.add(map);
map = new HashMap<String, Object>();
map.put("title", "助残服务");
map.put("info", "example info...");
map.put("img", R.drawable.tmp_img);
list.add(map);
return list;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.civil_left:
CivilMenuWindow menuPopupWindow = new CivilMenuWindow(CivilAffairHomeAty.this);
menuPopupWindow.showPopupWindow(ib1);
break;
default:
break;
}
}
}
| [
"ernestyj@outlook.com"
] | ernestyj@outlook.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.