blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 7
332
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
50
| license_type
stringclasses 2
values | repo_name
stringlengths 7
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 557
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
684M
⌀ | star_events_count
int64 0
77.7k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 82
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
5.41M
| extension
stringclasses 11
values | content
stringlengths 7
5.41M
| authors
listlengths 1
1
| author
stringlengths 0
161
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1130f0a842f662bd8a034656ab4f617cca707e7f | 083085e170d572cb59ae0309c31dd362ca73875f | /app/src/main/java/com/luthfihariz/newsreader/BaseView.java | 909b8d185aa807faf215b08ba6049d2ace3dce3b | [
"MIT"
]
| permissive | luthfihariz/indigo | 24590d9923a7cabcca6e471e4cc45724d69137d0 | b189a05044db7d5af391cbe85c4621a069300518 | refs/heads/master | 2021-01-19T17:00:18.624115 | 2018-09-19T00:45:36 | 2018-09-19T00:45:36 | 101,033,871 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 155 | java | package com.luthfihariz.newsreader;
/**
* Created by luthfihariz on 10/23/16.
*/
public interface BaseView<P> {
void setPresenter(P presenter);
}
| [
"[email protected]"
]
| |
6668b92d3fa994fdc323502cf3c962fc4e50ec49 | e3cd511614581b285081c2e82830af656a5eab90 | /leetcode/editor/cn/[16]最接近的三数之和.java | 3788577a774c7eaa0699badd18e150cc922b1147 | []
| no_license | 0102-yang/leetcode | 147e385d6de29e8f354e172bfe1c1e6f9f142ae7 | 3ee7a3dc462279a1ad715847d4922a4d1b2cfada | refs/heads/master | 2023-09-03T12:41:43.755147 | 2021-11-12T14:10:01 | 2021-11-12T14:10:01 | 391,676,472 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,705 | java | package leetcode.editor.cn;
import java.util.Arrays;
/**
* @author yang
* @date 2021-10-13 22:48:40
*/
class ThreeSumClosest {
public static void main(String[] args) {
Solution solution = new ThreeSumClosest().new Solution();
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int len = nums.length;
int res = (Integer.MAX_VALUE) >> 1;
for (int i = 0; i < len; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int j = i + 1;
int k = len - 1;
while (j < k) {
int tmp = nums[i] + nums[j] + nums[k];
if (tmp == target) {
return target;
}
if (Math.abs(tmp - target) < Math.abs((res - target))) {
res = tmp;
}
if (tmp > target) {
int tmpK = k - 1;
while (j < tmpK && nums[tmpK] == nums[k]) {
--tmpK;
}
k = tmpK;
} else {
int tmpJ = j + 1;
while (tmpJ < k && nums[tmpJ] == nums[j]) {
++tmpJ;
}
j = tmpJ;
}
}
}
return res;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
| [
"[email protected]"
]
| |
a57d35389e0df32815d0001ece83dac947b03943 | 381543d48f5ba487dafce8d91e0c16ea0a069caa | /app/src/test/java/com/example/labinformatika/ExampleUnitTest.java | edc665ab96f9808f4a0752ad90476cb19b9485e3 | []
| no_license | taqbagus/KAPE | a64031df068b9ab61484044c49a7b66757334dd8 | 71cff9b6d3b459eb47272a4742ec089693cd74c1 | refs/heads/master | 2020-09-15T07:33:18.314057 | 2019-11-30T14:59:30 | 2019-11-30T14:59:30 | 223,380,961 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 387 | java | package com.example.labinformatika;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
]
| |
772bcfdcb242505d850f506a2240a5430dbb325a | b972f2a3c0b72114455fdfb092e869fc5e73535b | /src/lischdev/matsedel/MatsedelActivity.java | d5365f6508f2e7559a01a7f14b3b8ae1c5241099 | []
| no_license | PontusHanssen/DLG-Restaurangen--android-app- | 62ddfc96005f961038c3c8eec9ca27f5455d0815 | 54ded5a06d86512f0a13b944ca9c536960eb030b | refs/heads/master | 2023-04-27T14:50:25.930281 | 2012-03-16T11:37:11 | 2012-03-16T11:37:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,118 | java | package lischdev.matsedel;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Toast;
public class MatsedelActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView web = (WebView) findViewById(R.id.webView);
web.loadUrl("http://stonehammer.dyndns.org/matsedel/index.php?idag");
}
public void changePage(View view) {
switch(view.getId()) {
case R.id.idag:
refresh("idag");
break;
case R.id.vecka:
refresh("vecka");
break;
case R.id.termin:
refresh("alla");
break;
}
}
public void refresh(String page) {
WebView web = (WebView) findViewById(R.id.webView);
if(web.getUrl().toString() != "http://stonehammer.dyndns.org/matsedel/index.php?" + page) {
web.loadUrl("http://stonehammer.dyndns.org/matsedel/index.php?" + page);
}
}
} | [
"[email protected]"
]
| |
ae7d8c89b1a766cd4bd634ca0ecbbb6571f068a5 | e60405b816e6bf6c11673df92c62d972e8508a3b | /app/src/main/java/com/legado/preventagps/activities/vendedor/MapsActivity.java | de55382a25b9d4edbdc960aec67232afbe37267d | []
| no_license | legado24/preventa | 8997216a3bdb8361f99b2aded6d9efc1ba7b3e8e | 228a3c982fb8b1f36b504fb31265698125e7b0d9 | refs/heads/master | 2022-12-31T04:11:30.095055 | 2020-09-07T14:32:16 | 2020-09-07T14:32:16 | 306,215,078 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,032 | java | package com.legado.preventagps.activities.vendedor;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationAvailability;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.legado.preventagps.R;
import com.legado.preventagps.util.PermissionUtils;
import com.legado.preventagps.util.PermissionUtilss;
import com.legado.preventagps.util.SessionUsuario;
public class MapsActivity extends AppCompatActivity implements View.OnClickListener {
Button button;
/**
* FusedLocationProviderApi Save request parameters
*/
private LocationRequest mLocationRequest;
/**
* Provide callbacks for location events.
*/
private LocationCallback mLocationCallback;
/**
* An object representing the current location
*/
private Location mCurrentLocation;
//A client that handles connection / connection failures for Google locations
// (changed from play-services 11.0.0)
private FusedLocationProviderClient mFusedLocationClient;
private String provider;
private GoogleMap mMap;
private SessionUsuario session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
session = new SessionUsuario(getApplicationContext());
// provider = getIntent().getStringExtra("provider");
//provider = session.getProvider();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
checkMyPermissionLocation();
} else {
initGoogleMapLocation();
}
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
/*if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}*/
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
//mMap.setMyLocationEnabled(true);
}
});
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button:
// if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// System.out.println("s");
// return;
// }
FusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
// ActivityCompat.requestPermissions(this,
// new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
// REQUEST_LOCATION);
// Check Permissions Now
return;
}
Task task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Object o) {
System.out.println(o);
}
});
break;
}
}
private void checkMyPermissionLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//Permission Check
PermissionUtils.requestPermission(this);
} else {
//If you're authorized, start setting your location
initGoogleMapLocation();
}
}
private void initGoogleMapLocation() {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
/**
* Location Setting API to
*/
SettingsClient mSettingsClient = LocationServices.getSettingsClient(this);
/*
* Callback returning location result
*/
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult result) {
super.onLocationResult(result);
//mCurrentLocation = locationResult.getLastLocation();
mCurrentLocation = result.getLocations().get(0);
if(mCurrentLocation!=null)
{
Log.e("Location(Lat)==",""+mCurrentLocation.getLatitude());
Log.e("Location(Long)==",""+mCurrentLocation.getLongitude());
}
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()));
BitmapDescriptor icon = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE);
options.icon(icon);
Marker marker = mMap.addMarker(options);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(marker.getPosition(), 17));
/**
* To get location information consistently
* mLocationRequest.setNumUpdates(1) Commented out
* Uncomment the code below
*/
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
//Locatio nMeaning that all relevant information is available
@Override
public void onLocationAvailability(LocationAvailability availability) {
//boolean isLocation = availability.isLocationAvailable();
}
};
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(5000);
//To get location information only once here
mLocationRequest.setNumUpdates(3);
if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
//Accuracy is a top priority regardless of battery consumption
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}else{
//Acquired location information based on balance of battery and accuracy (somewhat higher accuracy)
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
/**
* Stores the type of location service the client wants to use. Also used for positioning.
*/
LocationSettingsRequest mLocationSettingsRequest = builder.build();
Task<LocationSettingsResponse> locationResponse = mSettingsClient.checkLocationSettings(mLocationSettingsRequest);
locationResponse.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.e("Response", "Successful acquisition of location information!!");
//
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
});
//When the location information is not set and acquired, callback
locationResponse.addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.e("onFailure", "Location environment check");
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
String errorMessage = "Check location setting";
Log.e("onFailure", errorMessage);
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
//If the request code does not match
if (requestCode != PermissionUtilss.REQUEST_CODE) {
return;
}
if (PermissionUtils.isPermissionGranted(new String[]{ Manifest.permission.ACCESS_FINE_LOCATION}, grantResults)) {
//If you have permission, go to the code to get the location value
initGoogleMapLocation();
} else {
Toast.makeText(this, "Stop apps without permission to use location information", Toast.LENGTH_SHORT).show();
//finish();
}
}
/**
* Remove location information
*/
@Override
public void onStop() {
super.onStop();
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}
} | [
"[email protected]"
]
| |
8bcdfff72c45f66ab6c0090bff15ac04f4754969 | 61933ff2f67b5df1e55b94d1d88f7c6840766ffd | /app/src/test/java/com/example/lenovo/showbox/ExampleUnitTest.java | e48d4d9d87f86c269ee9ec949ce2c0c1b3c5b3e5 | []
| no_license | treken/Show-Box | f1ffc9144e032b72134d54e510a284d5703826d6 | 58d74f4e2c450873dfa5d4961cf2b15e20efaad3 | refs/heads/master | 2020-04-19T00:10:47.663064 | 2017-11-05T07:15:16 | 2017-11-05T07:15:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 404 | java | package com.example.lenovo.showbox;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
]
| |
14a012dbc48edbe9dc98e3d429f7f254087d24e8 | d6e51f5c7600a251391b7b8015a9739a053ecd5f | /app/src/main/java/com/leyifu/firstcode/activity/FruitActivity.java | e80994c476edb60b911ac3f3c9c4895d94c6532d | [
"Apache-2.0"
]
| permissive | wyz1535/FirstCode | d5a5d72bb0ed9224df7c1ceb85582f92e289428a | 1b8d30f77fe28a1a64b9d53c17d2aff85e5b8dfc | refs/heads/master | 2021-06-25T17:03:20.617821 | 2017-08-29T02:05:05 | 2017-08-29T02:05:05 | 98,702,381 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,236 | java | package com.leyifu.firstcode.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.leyifu.firstcode.R;
public class FruitActivity extends AppCompatActivity {
private Toolbar toolbar;
private CollapsingToolbarLayout collapsingToolbarLayout;
private ImageView image_view;
private TextView text_view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fruit);
Intent intent = getIntent();
String fruit_name = intent.getStringExtra("fruit_name");
int fruit_image_id = intent.getIntExtra("fruit_image_id", 0);
toolbar = ((Toolbar) findViewById(R.id.toolbar));
collapsingToolbarLayout = ((CollapsingToolbarLayout) findViewById(R.id.collapsingToolbarLayout));
image_view = ((ImageView) findViewById(R.id.image_view));
text_view = ((TextView) findViewById(R.id.text_view));
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
collapsingToolbarLayout.setTitle(fruit_name);
Glide.with(this).load(fruit_image_id).into(image_view);
String fruitcontent = genrateFruitcontent(fruit_name);
text_view.setText(fruitcontent);
}
private String genrateFruitcontent(String fruit_name) {
StringBuilder fruitContent = new StringBuilder();
for (int i=0;i<500;i++) {
fruitContent.append(fruit_name);
}
return fruitContent.toString();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| [
"[email protected]"
]
| |
49d818566e8e6db88e33048f4bf4fb4536e95d4c | c26304a54824faa7c1b34bb7882ee7a335a8e7fb | /flink-table/flink-table-calcite-bridge/src/main/java/org/apache/flink/table/calcite/bridge/PlannerExternalQueryOperation.java | 00b01f777eff7b43d32d50b31b8e167eda5ab77d | [
"BSD-3-Clause",
"OFL-1.1",
"ISC",
"MIT",
"Apache-2.0"
]
| permissive | apache/flink | 905e0709de6389fc9212a7c48a82669706c70b4a | fbef3c22757a2352145599487beb84e02aaeb389 | refs/heads/master | 2023-09-04T08:11:07.253750 | 2023-09-04T01:33:25 | 2023-09-04T01:33:25 | 20,587,599 | 23,573 | 14,781 | Apache-2.0 | 2023-09-14T21:49:04 | 2014-06-07T07:00:10 | Java | UTF-8 | Java | false | false | 2,484 | 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.flink.table.calcite.bridge;
import org.apache.flink.annotation.Internal;
import org.apache.flink.table.catalog.ResolvedSchema;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.operations.OperationUtils;
import org.apache.flink.table.operations.QueryOperation;
import org.apache.flink.table.operations.QueryOperationVisitor;
import org.apache.calcite.rel.RelNode;
import java.util.Collections;
import java.util.List;
/**
* Wrapper for valid logical plans and resolved schema generated by Planner. It's mainly used by
* pluggable dialect which will generate Calcite RelNode in planning phase.
*/
@Internal
public class PlannerExternalQueryOperation implements QueryOperation {
private final RelNode calciteTree;
private final ResolvedSchema resolvedSchema;
public PlannerExternalQueryOperation(RelNode relNode, ResolvedSchema resolvedSchema) {
this.calciteTree = relNode;
this.resolvedSchema = resolvedSchema;
}
public RelNode getCalciteTree() {
return calciteTree;
}
@Override
public ResolvedSchema getResolvedSchema() {
return resolvedSchema;
}
@Override
public List<QueryOperation> getChildren() {
return Collections.emptyList();
}
@Override
public <T> T accept(QueryOperationVisitor<T> visitor) {
return visitor.visit(this);
}
@Override
public String asSummaryString() {
return OperationUtils.formatWithChildren(
"PlannerCalciteQueryOperation",
Collections.emptyMap(),
getChildren(),
Operation::asSummaryString);
}
}
| [
"[email protected]"
]
| |
0e05fa7419c9000b21d6707c5d7312184e653af5 | b9e648efbc2d74739689aead3259ec71d0686aab | /src/main/java/com/mycompany/managementsystem/Management/Teacher.java | eb916f8702fa2908ec9fb6e14f7bf05d9a757bf8 | []
| no_license | ufsj-dcomp/gestao-academica-MTulio2000 | ec34db37645541c6e72ee2afde01ef9d033186eb | 8221419f8fae0c57f7a478702d5d2bf359801868 | refs/heads/main | 2023-01-02T16:01:50.977844 | 2020-10-21T22:08:15 | 2020-10-21T22:08:15 | 303,825,511 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 309 | 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.mycompany.managementsystem.Management;
/**
*
* @author marco
*/
public class Teacher extends Person{
}
| [
"[email protected]"
]
| |
c28ca272f2b80f24987e3b4e616dec523d100962 | 1d5137bb92e48c0347752fabf875cb360be280ee | /w-server/src/main/java/utils/auth/JwtAssertionException.java | 46d7e4a3042d5d9eeef48ba5ae323e4bf592341e | []
| no_license | cpdevoto/code-exchange | 11a91fefe5e801480c2db0bccc11f893d6f43d32 | cdcca990fb5b9a7d89c155418885757b8ff140c6 | refs/heads/master | 2023-02-02T22:37:13.786122 | 2020-07-31T13:27:57 | 2020-07-31T13:27:57 | 65,395,461 | 0 | 1 | null | 2023-01-25T20:58:26 | 2016-08-10T15:47:37 | Java | UTF-8 | Java | false | false | 614 | java | package utils.auth;
public class JwtAssertionException extends JwtException {
private static final long serialVersionUID = 1L;
public JwtAssertionException() {}
public JwtAssertionException(String message) {
super(message);
}
public JwtAssertionException(Throwable cause) {
super(cause);
}
public JwtAssertionException(String message, Throwable cause) {
super(message, cause);
}
public JwtAssertionException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| [
"[email protected]"
]
| |
e52a34a43256a3efc0d1688b9c2493c3164d0129 | c6e4c765862b98d11f12f800789e0982a980e5d9 | /oap-server/server-library/library-util/src/test/java/org/apache/skywalking/oap/server/library/util/ResourceUtilsTest.java | 8ed8e229f4b17f362bb577482a8e86dd798e9a42 | [
"Apache-2.0",
"BSD-3-Clause"
]
| permissive | Fxdemon/incubator-skywalking | ba70e8a481c2613aa966e941a187f6eb140a67f2 | 89183fbc3830313566b58dbbab0a45cd94023141 | refs/heads/master | 2020-04-19T03:23:51.307175 | 2019-12-09T03:33:10 | 2019-12-09T03:33:10 | 152,511,085 | 2 | 0 | Apache-2.0 | 2019-01-28T01:10:09 | 2018-10-11T01:14:13 | Java | UTF-8 | Java | false | false | 1,168 | 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.skywalking.oap.server.library.util;
import org.junit.Test;
import java.io.FileNotFoundException;
/**
* @author kezhenxu94
*/
public class ResourceUtilsTest {
@Test(expected = FileNotFoundException.class)
public void shouldThrowWhenResourceNotFound() throws FileNotFoundException {
ResourceUtils.read("/not-existed");
}
} | [
"[email protected]"
]
| |
6cdd1da9a611546d114788870bda318cbf0cd999 | 97015cea1d000a5d07a0a6b1344be8d133446f97 | /BigDataOnline/src/bigdata/Pair.java | 30a810ef0b378527763c9b67f1293b160e12ebd7 | [
"Apache-2.0"
]
| permissive | jcastro-inf/Yelp-Review-Analysis-and-Recommendation | a3ea9945e1f93cd3f90e2d03bf80147e74e7f15c | fd5ae77aa596e33014ed3a5533d80529a8d1eb2b | refs/heads/master | 2021-01-22T14:46:01.344417 | 2015-01-30T04:14:44 | 2015-01-30T04:14:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 415 | java | package bigdata;
public class Pair<T1 extends Comparable<T1>, T2> implements Comparable<Pair<T1, T2>>
{
private T1 key;
private T2 value;
public Pair(T1 key, T2 value)
{
this.key = key;
this.value = value;
}
public T1 getKey()
{
return key;
}
public T2 getValue()
{
return value;
}
public int compareTo(Pair<T1, T2> o)
{
return key.compareTo(o.key);
}
}
| [
"[email protected]"
]
| |
4b5afc75cb0fb2808add64da11cff4afd0c35cf5 | 361297c696fe6974399f31aa5355c33244c32bd1 | /src/main/java/org/tco/tfm/mr/LocationTreeModel.java | f319f5e68da64f1318e3cebac6cf9e949883e92c | []
| no_license | chukago/mr | 156bad1ac983e66a71405a21ed09ccfdb62397fa | f3571a1c10a67e992b2c5782b404d820b8078dda | refs/heads/master | 2021-01-11T21:46:33.770277 | 2017-01-13T14:49:17 | 2017-01-13T14:49:17 | 78,847,889 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,709 | java | package org.tco.tfm.mr;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeNode;
import org.tco.tfm.mr.Common.LocationRec_t;
public class LocationTreeModel extends DefaultTreeModel {
private static final long serialVersionUID = 1L;
private static LocationTreeModel instance = null;
private DatabaseManager dbManager = DatabaseManager.getInstance();
static public LocationTreeModel getInstance() {
if (instance == null) {
instance = new LocationTreeModel(Utils.loadLocationTree());
}
return instance;
}
private LocationTreeModel(DefaultMutableTreeNode root) {
super(root);
}
public boolean addNode(String name, MutableTreeNode parent) {
for (int i = 0; i < parent.getChildCount(); ++i) {
DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)parent.getChildAt(i);
Common.LocationRec_t childData = (Common.LocationRec_t)childNode.getUserObject();
if (childData.name.compareToIgnoreCase(name) == 0) {
return false;
}
}
DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)parent;
Common.LocationRec_t parentData = (Common.LocationRec_t)parentNode.getUserObject();
Common.LocationRec_t newLocation = new Common.LocationRec_t(0, name, parentData.id);
if (!dbManager.saveLocationRecord(DatabaseManager.LOCATION_TABLE_NAME, newLocation)) {
System.out.println("Cannot save location in database");
return false;
}
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode();
newNode.setUserObject(newLocation);
insertNodeInto(newNode, parent, parent.getChildCount());
this.fireTreeNodesInserted(this, parentNode.getPath(),
new int[]{parent.getChildCount() - 1}, new DefaultMutableTreeNode[]{newNode});
return true;
}
public DefaultMutableTreeNode findNode(int id) {
DefaultMutableTreeNode root = (DefaultMutableTreeNode)this.getRoot();
Common.LocationRec_t rootData = (Common.LocationRec_t) root.getUserObject();
if (id == rootData.id) {
return root;
}
for (int i = 0; i < root.getChildCount(); ++i) {
DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)root.getChildAt(i);
Common.LocationRec_t childData = (Common.LocationRec_t)childNode.getUserObject();
if (childData.id == id) {
return childNode;
}
DefaultMutableTreeNode node = findNodeValue(id, childNode);
if (node != null) {
return node;
}
}
return null;
}
private DefaultMutableTreeNode findNodeValue(int id, DefaultMutableTreeNode parentNode) {
for (int i = 0; i < parentNode.getChildCount(); ++i) {
DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)parentNode.getChildAt(i);
Common.LocationRec_t childData = (Common.LocationRec_t)childNode.getUserObject();
if (childData.id == id) {
return childNode;
}
DefaultMutableTreeNode node = findNodeValue(id, childNode);
if (node != null) {
return node;
}
}
return null;
}
public String getNodeStringPath(int id) {
DefaultMutableTreeNode node = findNode(id);
TreeNode[] path = node.getPath();
if (path.length == 1) {
LocationRec_t nodeData = (Common.LocationRec_t) node.getUserObject();
return nodeData.name;
}
String result = new String();
for (int i = 1; i < path.length; ++i) {
DefaultMutableTreeNode n = (DefaultMutableTreeNode) path[i];
LocationRec_t nodeData = (Common.LocationRec_t) n.getUserObject();
result += nodeData.name;
if (i < path.length - 1) {
result += "/";
}
}
return result;
}
}
| [
"[email protected]"
]
| |
812e4123cb7bcb5cd75d64d315faee8beb0a9f78 | 42fab133ddfab16e0a5d9e3c4bbc8518b5561b36 | /Java10ComLineArgs/src/Hello.java | b34a47e61578b5eb68ed357ba7a71385c758f840 | []
| no_license | bit1394/Java | 35d96dc28d6e7c25f05b1c6f7d8224310d92bc90 | 97daa10a337980fb5b1c75cfe7f533c6008c3034 | refs/heads/master | 2021-01-22T01:04:49.522529 | 2016-09-08T14:42:07 | 2016-09-08T14:42:07 | 27,953,792 | 0 | 0 | null | null | null | null | WINDOWS-1251 | Java | false | false | 385 | java |
public class Hello {
public static void main (String [] args) {
String name = args [2]; //1-й элемент массива ARGS
// Он будет браться из аргумента командной строки
//1-й из введенных
// Run - Run configurations / Arguments >> вводим аргументы
System.out.print("Hello " + name);
}
}
| [
"[email protected]"
]
| |
20dfb14fee9274ce6a2e0dc4363e82e680231976 | 65f5416def2375abd995103831a66bf4e701adb6 | /Final Test/src/portfolioObject.java | fab91d8a0e31dd9b0bceb3f3e4becacbbd58da57 | []
| no_license | MaximUltimatum/HardCommaClass- | bcd1eab43ebea4fe507df58ae0a35a3f544c97d9 | 848d83f6b9e8b0caef45be992efc538d9e9ef878 | refs/heads/master | 2021-01-10T16:16:32.481205 | 2016-03-17T20:10:41 | 2016-03-17T20:10:41 | 48,186,424 | 1 | 0 | null | 2016-03-17T14:41:04 | 2015-12-17T16:46:20 | Java | UTF-8 | Java | false | false | 39 | java |
public class portfolioObject {
}
| [
"[email protected]"
]
| |
40b75213bdce5d8f430bea91b8bbf58718dc9b99 | 10d120d1889f141856b0010406a01e69c2f7495a | /src/main/java/eu/h2020/symbiote/enablerlogic/messaging/properties/RabbitConnectionProperties.java | eb119ff3dd020cae16b1c7b083671b3bb584b7e2 | []
| no_license | symbiote-h2020/EnablerLogic | 080c0bbfb11a647f3afd24ed250f07235cbed1e4 | 4f19035bdf74a81297d30cfdfa80bac1b891bbc3 | refs/heads/master | 2021-01-17T11:46:05.469473 | 2019-10-04T09:22:18 | 2019-10-04T09:22:18 | 84,044,648 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 544 | java | package eu.h2020.symbiote.enablerlogic.messaging.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@ConfigurationProperties(prefix = "rabbit", ignoreInvalidFields = true)
public class RabbitConnectionProperties {
private String host = "localhost";
private String username = "guest";
private String password = "guest";
private int replyTimeout = 5000;
}
| [
"[email protected]"
]
| |
cd07102a61d9fa2fb94ff1841bb9643bbbf47882 | 59fd299fbc2fed50fa8c4a5956ad9e01c8e0c2fa | /anp-web/src/main/java/com/mg/model/data/AnpTaskStorable.java | dd10ab7124101ca013ac0d744cae38d2176fc15f | []
| no_license | gurovmichael/anp | bc57423e89529c7b95eb9183dd294675cac1c688 | d20813dda669311c262a68eca817ae2e0dfb9ae3 | refs/heads/master | 2021-01-01T06:17:53.082904 | 2015-08-03T11:28:36 | 2015-08-03T11:28:36 | 33,626,921 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 508 | java | package com.mg.model.data;
import com.mg.model.data.enums.TaskType;
import java.sql.Date;
/**
* Created with IntelliJ IDEA.
* User: ми
* Date: 19.07.15
* Time: 22:28
* To change this template use File | Settings | File Templates.
*/
public class AnpTaskStorable
{
private long id;
private long objectId;
private long ownerId;
private TaskType taskType;
private Date created;
private Date deadline;
private String comment;
}
| [
"[email protected]"
]
| |
f304c5f400a04c5479b5a101627bca945d62a69e | feadb9294d9b4c141f604ae18f1df6df25210ece | /src/main/java/sk/infivi/pathfinding/graph/NodeType.java | c2912f590e37deac77ca01acef9fc3eb58c2f24e | []
| no_license | 0xVector/pathfinding | b2d0bf60b14943bec0270cfa4adca4b2bcfbd710 | e05d1b30dad4f9117f41493b8f5041b9990d18c3 | refs/heads/master | 2023-07-12T18:14:16.714581 | 2021-08-28T22:45:00 | 2021-08-28T22:45:00 | 391,334,673 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,526 | java | package sk.infivi.pathfinding.graph;
import org.bukkit.Material;
import java.util.EnumMap;
import static org.bukkit.Material.*;
public enum NodeType {
NORMAL (WHITE_CONCRETE, SEA_LANTERN, LIGHT_GRAY_CONCRETE, BLUE_CONCRETE, true),
START (LIME_CONCRETE, LIME_CONCRETE, LIME_CONCRETE, GREEN_CONCRETE, true),
END (PINK_CONCRETE, PINK_CONCRETE, PINK_CONCRETE, RED_CONCRETE, true),
WALL (BLACK_CONCRETE, GRAY_CONCRETE, BLACK_CONCRETE, GRAY_CONCRETE, false),
GAP (AIR, BLUE_STAINED_GLASS, LIGHT_BLUE_STAINED_GLASS, BLUE_STAINED_GLASS, false),
OTHER (BEDROCK, BEDROCK, BEDROCK, BEDROCK,false);
public final Material block;
public final Material selectedBlock;
public final Material visitedBlock;
public final Material pathBlock;
public final boolean walkable;
private final EnumMap<NodeState, Material> stateToMaterial;
NodeType(Material block, Material selectedBlock, Material visitedBlock, Material pathBlock, boolean walkable) {
this.block = block;
this.selectedBlock = selectedBlock;
this.visitedBlock = visitedBlock;
this.pathBlock = pathBlock;
this.walkable = walkable;
this.stateToMaterial = new EnumMap<>(NodeState.class);
stateToMaterial.put(NodeState.NORMAL, block);
stateToMaterial.put(NodeState.SELECTED, selectedBlock);
stateToMaterial.put(NodeState.VISITED, visitedBlock);
stateToMaterial.put(NodeState.PATH, pathBlock);
}
public Material getBlockForState(NodeState state) {
return stateToMaterial.getOrDefault(state, OTHER.block);
}
public static NodeType getTypeFromMaterial(Material blockMaterial) {
for (NodeType nodeType : values()) {
if (nodeType.block == blockMaterial
|| nodeType.selectedBlock == blockMaterial
|| nodeType.visitedBlock == blockMaterial
|| nodeType.pathBlock == blockMaterial) {
return nodeType;
}
}
return NodeType.OTHER;
}
public static Material cleanBlockType(Material highlightedBlock) {
for (NodeType nodeType : values()) {
if (nodeType.block == highlightedBlock
|| nodeType.selectedBlock == highlightedBlock
|| nodeType.visitedBlock == highlightedBlock
|| nodeType.pathBlock == highlightedBlock) {
return nodeType.block;
}
}
return NodeType.OTHER.block;
}
}
| [
"[email protected]"
]
| |
2647bb91bfd940031155e2fec1153ca4ba9a1ba9 | 31868b1f6101ce7abd6788629b9dfa3ce76c09ce | /src/main/java/com/hema/newretail/backstage/service/impl/UserPushInfoServiceImpl.java | 08ad864e7a534b70d882e6c813baec9df4c10f35 | []
| no_license | why168/cohh | 1ddf28f004b3f34f3c496d64c1545cba4e8678f1 | 3b18b386b4d84891cfe60f62bd46d30d55e6a10b | refs/heads/master | 2020-05-20T02:45:14.228392 | 2018-11-06T02:31:19 | 2018-11-06T02:31:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,031 | java | package com.hema.newretail.backstage.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.hema.newretail.backstage.common.mongodbpage.MongoDBPageModel;
import com.hema.newretail.backstage.common.mongodbpage.SpringbootMongoDBPageable;
import com.hema.newretail.backstage.common.utils.Response;
import com.hema.newretail.backstage.common.utils.TimeUtil;
import com.hema.newretail.backstage.entry.PushInfoData;
import com.hema.newretail.backstage.entry.UserFormIdData;
import com.hema.newretail.backstage.entry.UserManagerData;
import com.hema.newretail.backstage.service.IUserPushInfoService;
import com.mongodb.WriteResult;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.*;
/**
* 推送信息接口Service实现类
*/
@Service("userPushInfoService")
public class UserPushInfoServiceImpl implements IUserPushInfoService {
private static final Integer TWOHUNDRED = 200;
private static final String ACCESSTOKEN = "access_token";
private static final String TEMPLATEIDOVER="40037";
private static final String FORMIDOVER="41028";
private static final String FORMIDUSED="41029";
private static final String PAGESTATUS="41030";
private static final String OVERMAX="45009";
private static final String COLLECTION="userFormIdData";
private Logger logger = LoggerFactory.getLogger(UserPushInfoServiceImpl.class);
@Autowired
private MongoTemplate mongoTemplate;
@Value(value = "${weixin.appId}")
private String appId;
@Value(value = "${weixin.appSecret}")
private String appSecret;
@Value(value = "${weixin.templateId}")
private String templateId;
/**
*查询推送信息列表
* @param params{pageNum:int,pageSize:int}都是必填项
* @return
*/
@Override
public Response findAll(Map<String, Object> params) {
List<Map<String,Object>> result = new ArrayList<Map<String, Object>>();
//Todo 获取登录用户的信息
String admin = "admin";
SpringbootMongoDBPageable pageable = new SpringbootMongoDBPageable();
MongoDBPageModel pm=new MongoDBPageModel();
int pageSize = (int)params.get("pageSize");
int pageNum = (int)params.get("pageNum");
pm.setPagenumber(pageNum);
pm.setPagesize(pageSize);
Sort sort = new Sort(Sort.Direction.DESC,"pushTime");
pm.setSort(sort);
pageable.setPage(pm);
Criteria criteria = Criteria.where("operator").is(admin);
Query query = Query.query(criteria);
long total = mongoTemplate.count(query, PushInfoData.class,"pushInfoData");
List<PushInfoData> datas = mongoTemplate.find(query.with(pageable),PushInfoData.class,"pushInfoData");
for (PushInfoData data:datas){
Map<String,Object> pushInfo = new HashMap<String, Object>();
pushInfo.put("id",data.getId());
pushInfo.put("content",data.getContent());
pushInfo.put("operator",data.getOperator());
pushInfo.put("pushTimeStr", TimeUtil.getStringByDate(data.getPushTime()));
pushInfo.put("title",data.getTitle());
List<String> users = data.getUsers();
List<Map<String,Object>> userList = new ArrayList<Map<String, Object>>();
for (String user:users){
Map<String,Object> userMap = new HashMap<String, Object>();
UserManagerData userManagerData= mongoTemplate.findById(user,UserManagerData.class,"userManagementData");
if(userManagerData != null){
userMap.put("nickName",userManagerData.getNickname());
userMap.put("telephone",userManagerData.getPhoneNumber());
}
userList.add(userMap);
}
pushInfo.put("users",userList);
result.add(pushInfo);
}
return Response.success(result,total,pageSize,pageNum);
}
/**
* 根据id获取推送信息详情
* @param id
* @return
*/
@Override
public PushInfoData findOne(String id) {
return mongoTemplate.findById(id,PushInfoData.class,"pushInfoData");
}
/**
* 保存推送信息
* @param data
*/
@Override
public void save(PushInfoData data) {
mongoTemplate.insert(data,"pushInfoData");
}
/**
* 保存用户FormId
* @param data
*/
@Override
public void saveFormId(UserFormIdData data) {
mongoTemplate.insert(data,"userFormIdData");
}
/**
*根据用户openId查询用户FormId
* @param openId
* @return
*/
@Override
public UserFormIdData findOneByOpenId(String openId) {
Date date = new Date();
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_WEEK,-7);
Date beginTime = c.getTime();
Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC,"createTime"));
Criteria criteria = new Criteria();
criteria.andOperator(Criteria.where("openId").is(openId),Criteria.where("createTime").gte(beginTime).lte(date));
Query query = new Query(criteria);
query.with(sort).limit(1);
List<UserFormIdData> datas = mongoTemplate.find(query, UserFormIdData.class,"userFormIdData");
if(datas.size()>0){
return datas.get(0);
}else{
return null;
}
}
/**
* 获取微信认证信息AccessToken
* @return
*/
@Override
public String getAccessToken() {
String result = "";
CloseableHttpClient httpClient = HttpClients.createDefault();
System.out.println("appId:"+appId);
System.out.println("appSecret:"+appSecret);
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == TWOHUNDRED) {
String entity = EntityUtils.toString(httpResponse.getEntity());
JSONObject jsonObject = JSONObject.parseObject(entity);
if (jsonObject.get(ACCESSTOKEN)!=null){
result = jsonObject.getString("access_token");
}else {
result = "";
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 推送信息接口
* @param touser
* @param formId
* @param fillData
* @return
*/
@Override
public String sendTemplate(String touser, String formId, String[] fillData) {
String tepUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="
+ this.getAccessToken();
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(tepUrl);
// 装配post请求参数
JSONObject json = new JSONObject();
json.put("touser", touser);
json.put("template_id", templateId);
json.put("form_id", formId);
// json.put("emphasis_keyword", "keyword1.DATA");
JSONObject dataJson = new JSONObject();
for (int i = 0; i < fillData.length; i++) {
JSONObject sonDateJson = new JSONObject();
sonDateJson.put("value", fillData[i]);
dataJson.put("keyword" + (i + 1), sonDateJson);
}
json.put("data", dataJson);
String resultStr = "发送失败";
try {
StringEntity myEntity = new StringEntity(json.toJSONString(), ContentType.APPLICATION_JSON);
// 设置post求情参数
httpPost.setEntity(myEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == TWOHUNDRED) {
deleteFormIdData(formId);
// 发送成功
String resutlEntity = EntityUtils.toString(httpResponse.getEntity());
JSONObject resultTemplateDate = JSONObject.parseObject(resutlEntity);
if (resultTemplateDate.get(TEMPLATEIDOVER)!=null) {
resultStr = "template_id不正确";
}
if (resultTemplateDate.get(FORMIDOVER)!=null) {
resultStr = "form_id不正确,或者过期";
}
if (resultTemplateDate.get(FORMIDUSED)!=null) {
resultStr = "form_id已被使用";
}
if (resultTemplateDate.get(PAGESTATUS)!=null) {
resultStr = "page不正确";
}
if (resultTemplateDate.get(OVERMAX)!=null) {
resultStr = "接口调用超过限额(目前默认每个帐号日调用限额为100万)";
}
resultStr = "ok";
return resultStr;
} else {
// 发送失败
return resultStr;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (httpClient != null) {
// 释放资源
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultStr;
}
@Override
public void deleteFormIdData(String formId) {
Criteria criteria = Criteria.where("formId").in(formId);
if (criteria != null) {
Query query = new Query(criteria);
if (query != null && mongoTemplate.findOne(query, UserFormIdData.class,COLLECTION) != null){
WriteResult result = mongoTemplate.remove(mongoTemplate.findOne(query, UserFormIdData.class,"userFormIdData"));
logger.info(formId+"删除formId的结果是"+result.getN());
}
}
}
}
| [
"[email protected]"
]
| |
3d4ff38a41bc4a12185afb12117719ef7e3d8d10 | cbd6847c7ca824313cd708ed1e5c915d4db373e3 | /03_jdbc/src/main/java/_01_basic/Test08.java | 0390c17ca91be6c7269b3b48312950c529f7a7ed | []
| no_license | aaronppa/Mac-eclipse-workspace | 69a0fdc171c4d4ada5f99b512b09668960473e35 | fc194bd97b48e4f36027124376188126084913f4 | refs/heads/master | 2020-03-28T16:01:04.610312 | 2018-09-29T14:24:46 | 2018-09-29T14:24:46 | 148,650,541 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,176 | java | package _01_basic;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;
import util.DBProperties;
public class Test08 {
public static void main(String[] args) throws Exception{
Class.forName(DBProperties.driver);
Connection con = DriverManager.getConnection(
DBProperties.url,
DBProperties.user,
DBProperties.pass
);
Scanner sc = new Scanner(System.in);
System.out.println("게시물을 작성합니다.");
System.out.println("작성자: ");
String user = sc.nextLine();
System.out.println("제목 입력: ");
String title = sc.nextLine();
System.out.println("내용 입력: ");
String content = sc.nextLine();
StringBuffer sql = new StringBuffer();
sql.append("insert into tb_board");
sql.append("(no,title, content, writer) ");
sql.append("values(s_board_no.nextval,'"+title+"', '"+content+"', '"+user+"')");
System.out.println(sql.toString());
Statement stmt = con.createStatement();
int cnt = stmt.executeUpdate(sql.toString());
System.out.println(cnt+"개 행이 추가 입력되었습니다.");
sc.close();
} // main
} // end class
| [
"[email protected]"
]
| |
0e69bc07db9850d93bf8ffa5f86054434f985866 | cc8ee6ab909c8a0887452f7121199d8e85573807 | /src/main/java/com/seabox/tagsys/usertags/mybatis/dao/TagFavoriteDao.java | 5afc81f2fba3c4c0f555abbf7d28de63761d4b34 | []
| no_license | CN02233/SeaboxTag | 58a9a09e46ba56e2193a09bbd9d44ab1536b7f5b | 002d58f6ba67a4de0d55ed80bf28695b991e8553 | refs/heads/master | 2021-01-13T13:20:10.428097 | 2017-01-11T10:15:58 | 2017-01-11T10:15:58 | 78,605,899 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,205 | java | package com.seabox.tagsys.usertags.mybatis.dao;
import com.seabox.tagsys.usertags.entity.TagCategoryLastLevel;
import com.seabox.tagsys.usertags.entity.UserTagFavorite;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @author Changhua, Wu
* Created on: 1/23/16,10:37 AM
*/
@CacheNamespace(readWrite = false)
public interface TagFavoriteDao extends TagChangeAuditDao {
String SELECT_SQL_FOR_TAG_FAVORITE = "select " +
"f.user_id as user_id, " +
"f.tag_ctgy_id as tag_ctgy_id " // +
//"f.created_ts as created_ts, " +
//"f.updated_ts as updated_ts "
;
String TABLE_AND_ALIAS = " h62_user_tag_favorite f ";
String FROM_TABLE = " from " + TABLE_AND_ALIAS;
@Many
@Select({
SELECT_SQL_FOR_TAG_FAVORITE,
FROM_TABLE, ",", TagCategoryDao.TABLE_AND_ALIAS,
" where ",
TagCategoryDao.EXCLUDE_CONDITION_SQL,
" and f.tag_ctgy_id = c.tag_ctgy_id ",
})
List<UserTagFavorite> listAll();
/**
*
* @param userId
* @return list of Int, ID list of user's Favorite's tagCategory
*/
@Many
@Select({
SELECT_SQL_FOR_TAG_FAVORITE,
FROM_TABLE, ",", TagCategoryDao.TABLE_AND_ALIAS,
" where ",
TagCategoryDao.EXCLUDE_CONDITION_SQL,
" and c.tag_ctgy_id = f.tag_ctgy_id",
" and f.user_id = #{userId} "
} )
List<Integer> getFavoriteTagIDsByUser(@Param("userId") int userId);
@One
@Select({ "select count(1) as user_count ",
FROM_TABLE,
" where ",
" f.tag_ctgy_id = #{tagCategoryId}"
})
Integer getNumOfUsersWhoLoveTag(@Param("tagCategoryId") int tagCategoryId);
@Insert("insert into h62_user_tag_favorite (user_id, tag_ctgy_id) values (#{userId}, #{tagCategoryId})")
@Options(useCache = false, flushCache = true)
void addOneTagFavoriteByUserAndTag(@Param("userId") int userId, @Param("tagCategoryId") int tagCategoryId);
@Delete("delete from h62_user_tag_favorite where user_id = #{userId}")
@Options(useCache = false, flushCache = true)
void removeAllMyFavoriteByUser(@Param("userId") int userId);
@Delete("delete from h62_user_tag_favorite where user_id = #{userId} and tag_ctgy_id = #{tagCategoryId}")
@Options(useCache = false, flushCache = true)
void removeOneTagFavoriteByUserAndTag(@Param("userId") int userId, @Param("tagCategoryId") int tagCategoryId);
@One
@Select("select " +
"count(1) as result " +
" from h62_user_tag_favorite f where f.user_id = #{userId} and f.tag_ctgy_id = #{tagCategoryId}" )
boolean isTagFavoriteByUserAndTag(@Param("userId") int userId, @Param("tagCategoryId") int tagCategoryId);
/**
*
* @param userId
* @return list of Tag Category info, Object list of user's Favorite's tagCategory
*/
@Many
@Select({
TagCategoryDao.SELECT_SQL_FOR_CATEGORY,
FROM_TABLE, ",", TagCategoryDao.TABLE_AND_ALIAS,
" where ",
TagCategoryDao.EXCLUDE_CONDITION_SQL,
" and c.tag_ctgy_id = f.tag_ctgy_id",
" and f.user_id = #{userId} "
} )
List<TagCategoryLastLevel> getFavoriteTagsByUser(@Param("userId") int userId);
/**
*
* @param userId
* @return list of Tag Category info, Object list of user's Favorite's tagCategory
*/
@Many
@Select({
TagCategoryDao.SELECT_SQL_FOR_CATEGORY,
FROM_TABLE, ",", TagCategoryDao.TABLE_AND_ALIAS,
" where ",
TagCategoryDao.EXCLUDE_CONDITION_SQL,
" and c.tag_ctgy_id = f.tag_ctgy_id",
" and f.user_id = #{userId} ",
" and ( c.tag_ctgy_id like #{searchFilter} or c.tag_ctgy_nm like #{searchFilter} or c.tag_desc like #{searchFilter} ) "
} )
@Options(useCache = false)
List<TagCategoryLastLevel> getFavoriteTagsByUserWithSearchFilter(@Param("userId") int userId, @Param("searchFilter") String searchFilter);
}
| [
"[email protected]"
]
| |
be64444ca935b1a664f57e9db548993e3ae2d93e | 4951c921f88ac61e79e3d7fafbecbe1aa6ce36ee | /jportal_mcr_module/src/main/java/fsu/jportal/util/Pair.java | 4c925b28d438280489a0caa132c5681211d2e827 | []
| no_license | ThULB/jportal | 2a9e58074c1b1fac66ebc4998563e5ca33913e43 | ccf6988c25fb8352117155897cac186932c2d975 | refs/heads/main | 2021-06-10T03:22:45.481397 | 2020-09-02T07:04:18 | 2020-09-02T07:04:18 | 142,315,280 | 1 | 0 | null | 2020-08-03T15:49:42 | 2018-07-25T14:57:29 | Java | UTF-8 | Java | false | false | 1,995 | java | package fsu.jportal.util;
import java.util.Objects;
/**
* http://stackoverflow.com/questions/5303539/didnt-java-once-have-a-pair-class
*
* Container to ease passing around a tuple of two objects. This object provides a sensible
* implementation of equals(), returning true if equals() is true on each of the contained
* objects.
*/
public class Pair<Key, Value> {
protected final Key key;
protected final Value value;
/**
* Constructor for a Pair.
*
* @param key the first object in the Pair
* @param value the second object in the pair
*/
public Pair(Key key, Value value) {
this.key = key;
this.value = value;
}
public Key getKey() {
return key;
}
public Value getValue() {
return value;
}
/**
* Checks the two objects for equality by delegating to their respective
* {@link Object#equals(Object)} methods.
*
* @param o the {@link Pair} to which this one is to be checked for equality
* @return true if the underlying objects of the Pair are both considered
* equal
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) {
return false;
}
Pair<?, ?> p = (Pair<?, ?>) o;
return Objects.equals(p.key, key) && Objects.equals(p.value, value);
}
/**
* Compute a hash code using the hash codes of the underlying objects
*
* @return a hashcode of the Pair
*/
@Override
public int hashCode() {
return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode());
}
/**
* Convenience method for creating an appropriately typed pair.
*
* @param a the first object in the Pair
* @param b the second object in the pair
* @return a Pair that is templatized with the types of a and b
*/
public static <A, B> Pair<A, B> create(A a, B b) {
return new Pair<>(a, b);
}
} | [
"[email protected]"
]
| |
74feba4548f29ed81aa781537a5e8ff1b9764ada | 22957efc1fdc871cc7bac2ca1d61f14c7f6ca0d4 | /src/br/edu/unoesc/projetofinal/model/MorteMatriz.java | 142bb30487612f1a7ac9d0aaeababb1cdbe5d59e | []
| no_license | LuanZanchet/SuinoSoft | b79b46493e51215765026495d174ada2e0dc7f2d | 87e6bcd434cda6dcd8050b5db974b84f2e3c725e | refs/heads/master | 2021-01-18T18:12:24.839314 | 2016-01-02T19:36:27 | 2016-01-02T19:36:27 | 27,285,538 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 457 | java | package br.edu.unoesc.projetofinal.model;
import java.util.Date;
public class MorteMatriz extends Morte {
private Matriz matriz;
public MorteMatriz() {
}
public MorteMatriz(Integer codigo, Date data, Causa causa, Matriz matriz) {
this.setCodigo(codigo);
this.setData(data);
this.setCausa(causa);
this.matriz = matriz;
}
public Matriz getMatriz() {
return matriz;
}
public void setMatriz(Matriz matriz) {
this.matriz = matriz;
}
} | [
"[email protected]"
]
| |
304fe8b5cc5992b30b64a7b9e09a3aea8e2a6344 | 7fd8b13fd3c0a127a38d9b9f5235d7c62cfdc980 | /src/main/PageObjectCases/BasePage.java | c5aff229ccef5c5b4a69a02c1338109eb4381e80 | []
| no_license | gichubond23/Selenium-Tests | 7b27509b8e1027f12741c5cbebec18651dd35e47 | 452a469cf86055419ff5593d07a31c53e1df603c | refs/heads/master | 2020-04-01T08:47:35.023896 | 2018-11-03T21:22:48 | 2018-11-03T21:22:48 | 153,047,111 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,854 | java | import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
public class BasePage {
public static WebDriver driver;
public static Properties p;
public WebDriver initializedriver() throws IOException {
p = new Properties();
FileInputStream fis = new FileInputStream("C:\\Users\\giris\\IdeaProjects\\Selenium_Tests\\src\\main\\resources\\data.properties");
p.load(fis);
if (p.getProperty("browser").equals("firefox"))
{
System.setProperty("webdriver.gecko.driver","C:\\Software Downloads\\Selenium geckodriver firefox\\geckodriver.exe");
driver = new FirefoxDriver();
}
if (p.getProperty("browser").equals("chrome"))
{
System.setProperty("webdriver.chrome.driver","C:\\Software Downloads\\Selenium chromedriver chrome\\chromedriver.exe");
driver = new FirefoxDriver();
}
if (p.getProperty("browser").equals("IE"))
{
System.setProperty("webdriver.gecko.driver","C:\\Software Downloads\\Selenium IEdriver IE\\IEDriverServer.exe");
driver = new FirefoxDriver();
}
driver.manage().timeouts().implicitlyWait(Long.parseLong(p.getProperty("time")), TimeUnit.SECONDS);
return driver;
}
public void getScreenshot(String result) throws IOException {
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("C://Software Downloads//Selenium 3.1.3//Screenshots//"+result+"screenshot.jpg"));
}
}
| [
"[email protected]"
]
| |
02a40e3e67a1ec80f7f6c4295b13ecd535ff38c5 | ae91c254d926113d7bb963b216bd9884a0898e2b | /messages/connection/ObjectAveragePricesMessage.java | 33c607e6d449bf71d9e44fc71d0ea9af15858a72 | []
| no_license | Cooya/Tobby | 7defafc1c69894c4651395fa2b1470372b3a9cac | 0e56bc305c9ca9d7da4541ee30cd05f114a783c3 | refs/heads/master | 2020-03-13T13:42:08.531646 | 2017-10-03T18:56:06 | 2017-10-03T18:56:06 | 131,144,234 | 8 | 3 | null | null | null | null | UTF-8 | Java | false | false | 578 | java | package messages.connection;
import messages.NetworkMessage;
public class ObjectAveragePricesMessage extends NetworkMessage {
public int[] ids;
public int[] avgPrices;
@Override
public void serialize() {
}
@Override
public void deserialize() {
int nb = this.content.readShort();
this.ids = new int[nb];
for(int i = 0; i < nb; ++i)
this.ids[i] = this.content.readVarShort();
nb = this.content.readShort();
this.avgPrices = new int[nb];
for(int i = 0; i < nb; ++i)
this.avgPrices[i] = this.content.readVarInt();
}
} | [
"[email protected]"
]
| |
ef562fb73188180e9e7a7c3334c977deaba9a31a | 2479fb1af9e773ecffbb9c6be299c4ba562bb60a | /app/src/test/java/com/example/renataoliveira/sgcps_agendamentos/ExampleUnitTest.java | aa96913eedc5564136244e104f35461c5ed5bd51 | []
| no_license | rnataoliveira/sgcps-agendamentos | 1d04caf4fe58585e50b09d087bf874af580807bf | 416fd5c397e06d5920a9863a69bb7f82cc25b678 | refs/heads/master | 2021-04-06T01:48:21.202184 | 2018-05-15T04:05:24 | 2018-05-15T04:05:24 | 124,808,106 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 423 | java | package com.example.renataoliveira.sgcps_agendamentos;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
]
| |
60b96fb971db83f68b5b8f58e2ed32df0d27c9f8 | 8c9f9824c21e066a17d350ddd08d0e680729ea1f | /src/leetcode_inta/leetcode951_1000/Q994orangesRotting.java | 9e8c52ca7b84e0382a05ff52441699a207a8ae77 | []
| no_license | MyInta/exam | 273e7ae17799a5298a69339781d3e8803721ced0 | 0e5d7457bf32fdbfcc57a676cef71373187703fb | refs/heads/master | 2022-02-18T17:27:31.760150 | 2022-02-06T05:28:15 | 2022-02-06T05:28:15 | 196,821,928 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,772 | java | package leetcode_inta.leetcode951_1000;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author inta
* @date 2020/3/4
* @describe 在给定的网格中,每个单元格可以有以下三个值之一:
*
* 值 0 代表空单元格;
* 值 1 代表新鲜橘子;
* 值 2 代表腐烂的橘子。
* 每分钟,任何与腐烂的橘子(在 4 个正方向上)相邻的新鲜橘子都会腐烂。
*
* 返回直到单元格中没有新鲜橘子为止所必须经过的最小分钟数。如果不可能,返回 -1。
*
*
*
* 示例 1:
*
*
*
* 输入:[[2,1,1],[1,1,0],[0,1,1]]
* 输出:4
* 示例 2:
*
* 输入:[[2,1,1],[0,1,1],[1,0,1]]
* 输出:-1
* 解释:左下角的橘子(第 2 行, 第 0 列)永远不会腐烂,因为腐烂只会发生在 4 个正向上。
* 示例 3:
*
* 输入:[[0,2]]
* 输出:0
* 解释:因为 0 分钟时已经没有新鲜橘子了,所以答案就是 0 。
*
*
* 提示:
*
* 1 <= grid.length <= 10
* 1 <= grid[0].length <= 10
* grid[i][j] 仅为 0、1 或 2
*
*/
public class Q994orangesRotting {
public int orangesRotting(int[][] grid) {
int n = grid.length;
int m = grid[0].length;
int count = 0;
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < n; i ++) {
for (int j = 0; j < m; j ++) {
if (grid[i][j] == 2) {
queue.add(new int[]{i,j});
}
}
}
while (!queue.isEmpty()) {
int len = queue.size();
for (int i = 0; i < len; i ++) {
int[] temp = queue.poll();
int dx = temp[0], dy = temp[1];
if (dx > 0 && grid[dx - 1][dy] == 1) {
queue.add(new int[]{dx - 1, dy});
grid[dx - 1][dy] = 2;
}
if (dx < n - 1 && grid[dx + 1][dy] == 1) {
queue.add(new int[]{dx + 1, dy});
grid[dx + 1][dy] = 2;
}
if (dy > 0 && grid[dx][dy - 1] == 1) {
queue.add(new int[]{dx, dy - 1});
grid[dx][dy - 1] = 2;
}
if (dy < m - 1 && grid[dx][dy + 1] == 1) {
queue.add(new int[]{dx, dy + 1});
grid[dx][dy + 1] = 2;
}
}
if (!queue.isEmpty()) count ++;
}
//如果最终还含有新鲜橘子,说明染不到,返回-1
for (int i = 0; i < n; i ++) {
for (int j = 0; j < m; j ++) {
if (grid[i][j] == 1) {
return -1;
}
}
}
return count;
}
}
| [
"[email protected]"
]
| |
e30e908ff90538b6c0e9e1795c31d99421722c71 | a139763d8e04607bfe1b5793948a763035a7bf37 | /Xtext/org.unicam.myGrammar/src-gen/org/unicam/myGrammar/optGrammar/impl/UnitsLiteralImpl.java | edb9f078f8e98f75f30b718333599160c018933a | []
| no_license | samuelefioretti/master_project | 1efcd411d926e96a8953886b450deab99f26ace3 | c2fbb97af45e179637df6e6527afcce8a8c4af04 | refs/heads/master | 2020-08-03T17:01:47.746457 | 2020-04-11T14:16:08 | 2020-04-11T14:16:08 | 211,819,441 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,842 | java | /**
* generated by Xtext 2.21.0
*/
package org.unicam.myGrammar.optGrammar.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.unicam.myGrammar.optGrammar.OptGrammarPackage;
import org.unicam.myGrammar.optGrammar.UnitsLiteral;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Units Literal</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.unicam.myGrammar.optGrammar.impl.UnitsLiteralImpl#getValue <em>Value</em>}</li>
* </ul>
*
* @generated
*/
public class UnitsLiteralImpl extends MinimalEObjectImpl.Container implements UnitsLiteral
{
/**
* The default value of the '{@link #getValue() <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getValue()
* @generated
* @ordered
*/
protected static final String VALUE_EDEFAULT = null;
/**
* The cached value of the '{@link #getValue() <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getValue()
* @generated
* @ordered
*/
protected String value = VALUE_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected UnitsLiteralImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return OptGrammarPackage.Literals.UNITS_LITERAL;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getValue()
{
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setValue(String newValue)
{
String oldValue = value;
value = newValue;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, OptGrammarPackage.UNITS_LITERAL__VALUE, oldValue, value));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case OptGrammarPackage.UNITS_LITERAL__VALUE:
return getValue();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case OptGrammarPackage.UNITS_LITERAL__VALUE:
setValue((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case OptGrammarPackage.UNITS_LITERAL__VALUE:
setValue(VALUE_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case OptGrammarPackage.UNITS_LITERAL__VALUE:
return VALUE_EDEFAULT == null ? value != null : !VALUE_EDEFAULT.equals(value);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy()) return super.toString();
StringBuilder result = new StringBuilder(super.toString());
result.append(" (value: ");
result.append(value);
result.append(')');
return result.toString();
}
} //UnitsLiteralImpl
| [
"[email protected]"
]
| |
4cb50b9ca3a74858f5eeaf1da835f196fec1dc38 | 4c50b016520aecb1157c69a6887e2aa5e19c7ec5 | /farmProject/src/test/CropsTest.java | 1e355a1270921a7c96923da5f7df5f7231584424 | []
| no_license | cja128/sengProject | e5b9feccb579bb9190f2427015123bbb4b5643fe | c43cd5b095a4c7c7f8b352d8a41c71f8537e08b0 | refs/heads/master | 2022-06-09T06:42:29.721958 | 2020-05-06T10:49:42 | 2020-05-06T10:49:42 | 261,728,552 | 0 | 0 | null | 2020-05-06T10:42:22 | 2020-05-06T10:42:21 | null | UTF-8 | Java | false | false | 1,449 | java | package test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import farmProject.Crop;
class CropsTest {
private Crop testCrop;
@BeforeEach
public void init() {
testCrop = new Crop ("Carrot", 20.0, 10);
}
// Getters and setters
@Test
public void typeTest() {
assertEquals("Carrot", testCrop.getType());
}
@Test
public void worthTest() {
assertEquals(0, testCrop.getWorth());
// Rate increased but no new day
testCrop.increaseRate(1.0);
assertEquals(0, testCrop.getWorth());
// New day so crops have grown
testCrop.newDay(1.0);
assertEquals(400.0, testCrop.getWorth());
}
@Test
public void growthRateTest() {
assertEquals(0.2, testCrop.getRate());
testCrop.increaseRate(0.3);
assertEquals(0.5, testCrop.getRate());
// Ensuring growth rate does not go above 1.0
testCrop.increaseRate(1.1);
assertEquals(1.0, testCrop.getRate());
// Ensuring growth rate does not go below 0.0
testCrop.increaseRate(-1.1);
assertEquals(0.0, testCrop.getRate());
}
@Test
public void droughtTest() {
testCrop.halfQuantity();
assertEquals(5, testCrop.getQuantity());
// Ensures can't get decimal crops
testCrop.halfQuantity();
assertNotEquals(2.5, testCrop.getQuantity());
assertEquals(2, testCrop.getQuantity());
}
} | [
"user-00@user-00-PC"
]
| user-00@user-00-PC |
4dd93c245dfef1a990cbf27219b1cbd6a6114a4c | 038e5eebfe5fd159fdd2807b1bb78ec4741b04a5 | /core/src/main/java/y/core/models/HelloWorldModel.java | 592885437eba1a0ca76a8e32a47201dabceadc40 | []
| no_license | rajeswariakkiniguntla/aem | 007e45f74b82f4f50f860154cf62f4769c33da70 | fb5df15af1e3e9daed467f67dfe1af7f17095ed9 | refs/heads/master | 2020-03-09T01:05:44.378809 | 2018-04-07T07:50:58 | 2018-04-07T07:50:58 | 128,505,082 | 0 | 0 | null | 2018-04-07T07:50:59 | 2018-04-07T07:08:37 | Java | UTF-8 | Java | false | false | 1,503 | java | /*
* Copyright 2015 Adobe Systems Incorporated
*
* 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 y.core.models;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Default;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.settings.SlingSettingsService;
@Model(adaptables=Resource.class)
public class HelloWorldModel {
@Inject
private SlingSettingsService settings;
@Inject @Named("sling:resourceType") @Default(values="No resourceType")
protected String resourceType;
private String message;
@PostConstruct
protected void init() {
message = "\tHello World!\n";
message += "\tThis is instance: " + settings.getSlingId() + "\n";
message += "\tResource type is: " + resourceType + "\n";
}
public String getMessage() {
return message;
}
}
| [
"[email protected]"
]
| |
d9981afe006939b77b5533f8aac12fb54b291345 | fc22552aca250ba8f71c03567ac56ae00cd515fe | /src/main/java/bq/avro/BigQueryAvroUtils.java | 36c8b0e8d256f3cd3be21351e2c91c11071ca063 | []
| no_license | zakazai/bq-to-parquet | 22fd223b2f9e2e050ed498061f715392489c58c5 | aac87c2798484d9d9591bd1e9562b41a3c369669 | refs/heads/master | 2020-07-22T18:16:15.453741 | 2019-09-11T10:08:50 | 2019-09-11T10:08:50 | 207,286,259 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 18,979 | java | package bq.avro;
/*
* 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.
*/
import static java.time.temporal.ChronoField.HOUR_OF_DAY;
import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
import static java.time.temporal.ChronoField.NANO_OF_SECOND;
import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.MoreObjects.firstNonNull;
import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkNotNull;
import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Verify.verify;
import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Verify.verifyNotNull;
import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.api.services.bigquery.model.TableRow;
import com.google.api.services.bigquery.model.TableSchema;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatterBuilder;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
import org.apache.avro.Conversions;
import org.apache.avro.LogicalType;
import org.apache.avro.LogicalTypes;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import org.apache.avro.Schema.Type;
import org.apache.avro.generic.GenericRecord;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableCollection;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMultimap;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.io.BaseEncoding;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
/**
* A set of utilities for working with Avro files.
*
* <p>These utilities are based on the <a href="https://avro.apache.org/docs/1.8.1/spec.html">Avro
* 1.8.1</a> specification.
*/
class BigQueryAvroUtils {
/**
* Defines the valid mapping between BigQuery types and native Avro types.
*
* <p>Some BigQuery types are duplicated here since slightly different Avro records are produced
* when exporting data in Avro format and when reading data directly using the read API.
*/
public static final ImmutableMultimap<String, Type> BIG_QUERY_TO_AVRO_TYPES =
ImmutableMultimap.<String, Type>builder()
.put("STRING", Type.STRING)
.put("GEOGRAPHY", Type.STRING)
.put("BYTES", Type.BYTES)
.put("INTEGER", Type.LONG)
.put("FLOAT", Type.DOUBLE)
.put("NUMERIC", Type.BYTES)
.put("BOOLEAN", Type.BOOLEAN)
.put("TIMESTAMP", Type.LONG)
.put("RECORD", Type.RECORD)
.put("DATE", Type.STRING)
.put("DATE", Type.INT)
.put("DATETIME", Type.STRING)
.put("TIME", Type.STRING)
.put("TIME", Type.LONG)
.build();
/**
* Formats BigQuery seconds-since-epoch into String matching JSON export. Thread-safe and
* immutable.
*/
private static final DateTimeFormatter DATE_AND_SECONDS_FORMATTER =
DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZoneUTC();
@VisibleForTesting
static String formatTimestamp(Long timestampMicro) {
// timestampMicro is in "microseconds since epoch" format,
// e.g., 1452062291123456L means "2016-01-06 06:38:11.123456 UTC".
// Separate into seconds and microseconds.
long timestampSec = timestampMicro / 1_000_000;
long micros = timestampMicro % 1_000_000;
if (micros < 0) {
micros += 1_000_000;
timestampSec -= 1;
}
String dayAndTime = DATE_AND_SECONDS_FORMATTER.print(timestampSec * 1000);
if (micros == 0) {
return String.format("%s UTC", dayAndTime);
}
return String.format("%s.%06d UTC", dayAndTime, micros);
}
/**
* This method formats a BigQuery DATE value into a String matching the format used by JSON
* export. Date records are stored in "days since epoch" format, and BigQuery uses the proleptic
* Gregorian calendar.
*/
private static String formatDate(int date) {
return LocalDate.ofEpochDay(date).format(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE);
}
private static final java.time.format.DateTimeFormatter ISO_LOCAL_TIME_FORMATTER_MICROS =
new DateTimeFormatterBuilder()
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.appendLiteral('.')
.appendFraction(NANO_OF_SECOND, 6, 6, false)
.toFormatter();
private static final java.time.format.DateTimeFormatter ISO_LOCAL_TIME_FORMATTER_MILLIS =
new DateTimeFormatterBuilder()
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.appendLiteral('.')
.appendFraction(NANO_OF_SECOND, 3, 3, false)
.toFormatter();
private static final java.time.format.DateTimeFormatter ISO_LOCAL_TIME_FORMATTER_SECONDS =
new DateTimeFormatterBuilder()
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.toFormatter();
/**
* This method formats a BigQuery TIME value into a String matching the format used by JSON
* export. Time records are stored in "microseconds since midnight" format.
*/
private static String formatTime(long timeMicros) {
java.time.format.DateTimeFormatter formatter;
if (timeMicros % 1000000 == 0) {
formatter = ISO_LOCAL_TIME_FORMATTER_SECONDS;
} else if (timeMicros % 1000 == 0) {
formatter = ISO_LOCAL_TIME_FORMATTER_MILLIS;
} else {
formatter = ISO_LOCAL_TIME_FORMATTER_MICROS;
}
return LocalTime.ofNanoOfDay(timeMicros * 1000).format(formatter);
}
/**
* Utility function to convert from an Avro {@link GenericRecord} to a BigQuery {@link TableRow}.
*
* <p>See <a href="https://cloud.google.com/bigquery/exporting-data-from-bigquery#config">"Avro
* format"</a> for more information.
*/
static TableRow convertGenericRecordToTableRow(GenericRecord record, TableSchema schema) {
return convertGenericRecordToTableRow(record, schema.getFields());
}
private static TableRow convertGenericRecordToTableRow(
GenericRecord record, List<TableFieldSchema> fields) {
TableRow row = new TableRow();
for (TableFieldSchema subSchema : fields) {
// Per https://cloud.google.com/bigquery/docs/reference/v2/tables#schema, the name field
// is required, so it may not be null.
Field field = record.getSchema().getField(subSchema.getName());
Object convertedValue =
getTypedCellValue(field.schema(), subSchema, record.get(field.name()));
if (convertedValue != null) {
// To match the JSON files exported by BigQuery, do not include null values in the output.
row.set(field.name(), convertedValue);
}
}
return row;
}
@Nullable
private static Object getTypedCellValue(Schema schema, TableFieldSchema fieldSchema, Object v) {
// Per https://cloud.google.com/bigquery/docs/reference/v2/tables#schema, the mode field
// is optional (and so it may be null), but defaults to "NULLABLE".
String mode = firstNonNull(fieldSchema.getMode(), "NULLABLE");
switch (mode) {
case "REQUIRED":
return convertRequiredField(schema.getType(), schema.getLogicalType(), fieldSchema, v);
case "REPEATED":
return convertRepeatedField(schema, fieldSchema, v);
case "NULLABLE":
return convertNullableField(schema, fieldSchema, v);
default:
throw new UnsupportedOperationException(
"Parsing a field with BigQuery field schema mode " + fieldSchema.getMode());
}
}
private static List<Object> convertRepeatedField(
Schema schema, TableFieldSchema fieldSchema, Object v) {
Type arrayType = schema.getType();
verify(
arrayType == Type.ARRAY,
"BigQuery REPEATED field %s should be Avro ARRAY, not %s",
fieldSchema.getName(),
arrayType);
// REPEATED fields are represented as Avro arrays.
if (v == null) {
// Handle the case of an empty repeated field.
return new ArrayList<>();
}
@SuppressWarnings("unchecked")
List<Object> elements = (List<Object>) v;
ArrayList<Object> values = new ArrayList<>();
Type elementType = schema.getElementType().getType();
LogicalType elementLogicalType = schema.getElementType().getLogicalType();
for (Object element : elements) {
values.add(convertRequiredField(elementType, elementLogicalType, fieldSchema, element));
}
return values;
}
private static Object convertRequiredField(
Type avroType, LogicalType avroLogicalType, TableFieldSchema fieldSchema, Object v) {
// REQUIRED fields are represented as the corresponding Avro types. For example, a BigQuery
// INTEGER type maps to an Avro LONG type.
checkNotNull(v, "REQUIRED field %s should not be null", fieldSchema.getName());
// Per https://cloud.google.com/bigquery/docs/reference/v2/tables#schema, the type field
// is required, so it may not be null.
String bqType = fieldSchema.getType();
ImmutableCollection<Type> expectedAvroTypes = BIG_QUERY_TO_AVRO_TYPES.get(bqType);
verifyNotNull(expectedAvroTypes, "Unsupported BigQuery type: %s", bqType);
verify(
expectedAvroTypes.contains(avroType),
"Expected Avro schema types %s for BigQuery %s field %s, but received %s",
expectedAvroTypes,
bqType,
fieldSchema.getName(),
avroType);
// For historical reasons, don't validate avroLogicalType except for with NUMERIC.
// BigQuery represents NUMERIC in Avro format as BYTES with a DECIMAL logical type.
switch (bqType) {
case "STRING":
case "DATETIME":
case "GEOGRAPHY":
// Avro will use a CharSequence to represent String objects, but it may not always use
// java.lang.String; for example, it may prefer org.apache.avro.util.Utf8.
verify(v instanceof CharSequence, "Expected CharSequence (String), got %s", v.getClass());
return v.toString();
case "DATE":
if (avroType == Type.INT) {
verify(v instanceof Integer, "Expected Integer, got %s", v.getClass());
verifyNotNull(avroLogicalType, "Expected Date logical type");
verify(avroLogicalType instanceof LogicalTypes.Date, "Expected Date logical type");
return formatDate((Integer) v);
} else {
verify(v instanceof CharSequence, "Expected CharSequence (String), got %s", v.getClass());
return v.toString();
}
case "TIME":
if (avroType == Type.LONG) {
verify(v instanceof Long, "Expected Long, got %s", v.getClass());
verifyNotNull(avroLogicalType, "Expected TimeMicros logical type");
verify(
avroLogicalType instanceof LogicalTypes.TimeMicros,
"Expected TimeMicros logical type");
return formatTime((Long) v);
} else {
verify(v instanceof CharSequence, "Expected CharSequence (String), got %s", v.getClass());
return v.toString();
}
case "INTEGER":
verify(v instanceof Long, "Expected Long, got %s", v.getClass());
return ((Long) v).toString();
case "FLOAT":
verify(v instanceof Double, "Expected Double, got %s", v.getClass());
return v;
case "NUMERIC":
// NUMERIC data types are represented as BYTES with the DECIMAL logical type. They are
// converted back to Strings with precision and scale determined by the logical type.
verify(v instanceof ByteBuffer, "Expected ByteBuffer, got %s", v.getClass());
verifyNotNull(avroLogicalType, "Expected Decimal logical type");
verify(avroLogicalType instanceof LogicalTypes.Decimal, "Expected Decimal logical type");
BigDecimal numericValue =
new Conversions.DecimalConversion()
.fromBytes((ByteBuffer) v, Schema.create(avroType), avroLogicalType);
return numericValue.toString();
case "BOOLEAN":
verify(v instanceof Boolean, "Expected Boolean, got %s", v.getClass());
return v;
case "TIMESTAMP":
// TIMESTAMP data types are represented as Avro LONG types, microseconds since the epoch.
// Values may be negative since BigQuery timestamps start at 0001-01-01 00:00:00 UTC.
verify(v instanceof Long, "Expected Long, got %s", v.getClass());
return formatTimestamp((Long) v);
case "RECORD":
verify(v instanceof GenericRecord, "Expected GenericRecord, got %s", v.getClass());
return convertGenericRecordToTableRow((GenericRecord) v, fieldSchema.getFields());
case "BYTES":
verify(v instanceof ByteBuffer, "Expected ByteBuffer, got %s", v.getClass());
ByteBuffer byteBuffer = (ByteBuffer) v;
byte[] bytes = new byte[byteBuffer.limit()];
byteBuffer.get(bytes);
return BaseEncoding.base64().encode(bytes);
default:
throw new UnsupportedOperationException(
String.format(
"Unexpected BigQuery field schema type %s for field named %s",
fieldSchema.getType(), fieldSchema.getName()));
}
}
@Nullable
private static Object convertNullableField(
Schema avroSchema, TableFieldSchema fieldSchema, Object v) {
// NULLABLE fields are represented as an Avro Union of the corresponding type and "null".
verify(
avroSchema.getType() == Type.UNION,
"Expected Avro schema type UNION, not %s, for BigQuery NULLABLE field %s",
avroSchema.getType(),
fieldSchema.getName());
List<Schema> unionTypes = avroSchema.getTypes();
verify(
unionTypes.size() == 2,
"BigQuery NULLABLE field %s should be an Avro UNION of NULL and another type, not %s",
fieldSchema.getName(),
unionTypes);
if (v == null) {
return null;
}
Type firstType = unionTypes.get(0).getType();
if (!firstType.equals(Type.NULL)) {
return convertRequiredField(firstType, unionTypes.get(0).getLogicalType(), fieldSchema, v);
}
return convertRequiredField(
unionTypes.get(1).getType(), unionTypes.get(1).getLogicalType(), fieldSchema, v);
}
static Schema toGenericAvroSchema(String schemaName, List<TableFieldSchema> fieldSchemas) {
List<Field> avroFields = new ArrayList<>();
for (TableFieldSchema bigQueryField : fieldSchemas) {
avroFields.add(convertField(bigQueryField));
}
return Schema.createRecord(
schemaName,
"org.apache.beam.sdk.io.gcp.bigquery",
"Translated Avro Schema for " + schemaName,
false,
avroFields);
}
private static Field convertField(TableFieldSchema bigQueryField) {
Type avroType = BIG_QUERY_TO_AVRO_TYPES.get(bigQueryField.getType()).iterator().next();
Schema elementSchema;
if (avroType == Type.RECORD) {
elementSchema = toGenericAvroSchema(bigQueryField.getName(), bigQueryField.getFields());
} else {
elementSchema = Schema.create(avroType);
}
Schema fieldSchema;
if (bigQueryField.getMode() == null || "NULLABLE".equals(bigQueryField.getMode())) {
fieldSchema = Schema.createUnion(Schema.create(Type.NULL), elementSchema);
} else if ("REQUIRED".equals(bigQueryField.getMode())) {
fieldSchema = elementSchema;
} else if ("REPEATED".equals(bigQueryField.getMode())) {
fieldSchema = Schema.createArray(elementSchema);
} else {
throw new IllegalArgumentException(
String.format("Unknown BigQuery Field Mode: %s", bigQueryField.getMode()));
}
return new Field(
bigQueryField.getName(),
fieldSchema,
bigQueryField.getDescription(),
(Object) null /* Cast to avoid deprecated JsonNode constructor. */);
}
}
| [
"[email protected]"
]
| |
2d54cb7b017ba6e810780431a339165243b64c42 | 738c693a56d6f6abcab6cb97ec6e626202bb75d7 | /client/android/app/src/main/java/com/example/pc/iot/BackgroundWorker3.java | d2ee493a6a5c97ec30fa80d1802ab051e5686f5d | []
| no_license | shreymohan/SmartHome | d5b09ffc83bdcfee6001d8fdbb21b50e65ee0dc3 | a863a5289735177409808d4bf8241fbdb8e203da | refs/heads/master | 2021-05-09T20:29:50.128052 | 2018-01-24T03:44:09 | 2018-01-24T03:44:09 | 118,696,343 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,112 | java | package com.example.pc.iot;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by pc on 03/12/2016.
*/
/*public class BackgroundWorker3 extends AsyncTask<Void,Void,String> {
String postData;
BufferedWriter bufferedWriter;
private Context context;
public BackgroundWorker3(thermo thermo) {
}
//public BackgroundWorker1(Context c){this.context=context;}
protected String doInBackground(Integer... params) {
int setTemp = params[0];
String login_url = "http://192.168.1.3:8080/thermo1.php";
String st=Integer.toString(setTemp);
try {
URL url = new URL(login_url);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setDoInput(true);
InputStream inputStream = http.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line;
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
http.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result){
if(result!=null)
}
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
{
}*/
| [
"[email protected]"
]
| |
39a312e1ea6aec1ac35c5bd011dc05c5bb874135 | b85b3cba4372e876116e688e4237e848b34b47bf | /ts/TimeServerImpl.java | 8ecfb90ca231ebe2bdca37e1ed74f58faec16e40 | []
| no_license | lsilvs/NPDS_tutorial11 | f1df894ab6a38ca72e7fbcd6998537318d61bd3e | 2420f24627931373e2aa5c46555dce4133ecd904 | refs/heads/master | 2021-01-06T20:38:18.646430 | 2013-12-03T23:41:30 | 2013-12-03T23:41:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 580 | java | package ts;
import java.util.Date;
import javax.jws.WebService;
/**
* The @WebService property endpointInterface links the
* SIB (this class) to the SEI (ts.TimeServer).
* Note that the method implementations are not annotated
* as @WebMethods.
*/
@WebService(endpointInterface = "ts.TimeServer")
public class TimeServerImpl implements TimeServer {
public String getTimeAsString() {
System.out.println("Received a remote call for getTimeAsString.");
return new Date().toString();
}
public long getTimeAsElapsed() { return new Date().getTime(); }
}
| [
"[email protected]"
]
| |
ec2cd3daa8e9cb6fa5110b1c917553b29aa2b135 | 1c9f751a075a4c6fd18a8912f2c48a186944903b | /app/src/androidTest/java/com/example/adoptme/ExampleInstrumentedTest.java | aa15e0d8158bf30d37169fee229104d32efdfbad | []
| no_license | templario01/Adoptme | fbc44dda6e9f5541fb17a1f99d4bd799f7df2148 | 412a0b1277b78d535e47422beb8ff1e407866018 | refs/heads/master | 2021-08-27T22:55:04.683245 | 2021-08-26T05:12:11 | 2021-08-26T05:12:11 | 194,903,917 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 709 | java | package com.example.adoptme;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.adoptme", appContext.getPackageName());
}
}
| [
"[email protected]"
]
| |
45e8a51a4a21bceaba1cd78de90b92c5f388ad4f | 8c893a7a46a6c3aba276107ddca6967910a3f717 | /src/main/java/com/opstty/job/SortHeight.java | a9e3ce86ab1fbe86bd9d2a88cd9d660f0ad546a7 | []
| no_license | SDeRichter/LabJavaMapReduce | 0707db59d22a7ea1980eb977cd96673eb3614ef0 | d62ce86625a9e64f6a86b6f4b8743075d519d1c3 | refs/heads/main | 2023-01-07T19:59:06.567598 | 2020-11-12T21:54:57 | 2020-11-12T21:54:57 | 308,661,056 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,835 | java | package com.opstty.job;
import com.opstty.mapper.MaximumHeightMapper;
import com.opstty.mapper.NumberOfTreesBySpeciesMapper;
import com.opstty.reducer.MaximumHeightReducer;
import com.opstty.reducer.NumberOfTreesBySpeciesReducer;
import com.opstty.reducer.SortHeightReducer;
import org.apache.commons.math3.analysis.function.Max;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class SortHeight {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length < 2) {
System.err.println("Usage: SortHeight <in> [<in>...] <out>");
System.exit(2);
}
Job job = Job.getInstance(conf, "sortheight");
job.setJarByClass(MaximumHeight.class);
job.setMapperClass(MaximumHeightMapper.class);
job.setCombinerClass(SortHeightReducer.class);
job.setReducerClass(SortHeightReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(DoubleWritable.class);
for (int i = 0; i < otherArgs.length - 1; ++i) {
FileInputFormat.addInputPath(job, new Path(otherArgs[i]));
}
FileOutputFormat.setOutputPath(job,
new Path(otherArgs[otherArgs.length - 1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
| [
"[email protected]"
]
| |
a9f2639fb0677ed377cddfb24e6d37fff7138d12 | e38f4873809b579b9e321c46193725c1340bb0a3 | /src/main/java/org/kryptonmlt/content/provider/controllers/WebMvcConfig.java | 8a5a04480f5363052d1cdedb92fb40736fae30fe | []
| no_license | kryptonmlt/ContentProvider | 6bf2bc694e6edd16dfa597e546a467d93f6228d8 | 91d2f8260cf3aa72f79377d49f66240b8e531513 | refs/heads/master | 2020-06-10T12:15:13.581468 | 2016-12-13T16:07:49 | 2016-12-13T16:07:49 | 75,963,110 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 572 | java | package org.kryptonmlt.content.provider.controllers;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
*
* @author kurt
*/
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
| [
"[email protected]"
]
| |
a2bd4a7b18acd379c856d0d5e6be1dbd7c15820e | dd54232fa06dcd9457f91fe869462ea4d13eb83e | /dbDAOandTESTS/src/main/java/ua/epam/dao/EmployeeDao.java | 6f62b566105cb5ca2d3261f993331a75a767ece3 | []
| no_license | ipereverzieva/Tasks_Java | e7130d0e3fe4ad69a2096b3b01201c33b674d47f | d662e28c9221df46804e98466a6f28c4d05f75b6 | refs/heads/master | 2021-06-07T22:35:59.960613 | 2016-11-04T11:22:42 | 2016-11-04T11:22:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 171 | java | package ua.epam.dao;
import ua.epam.entities.Employee;
/**
* Created by Iryna_Poliakova on 10/4/2016.
*/
public interface EmployeeDao extends GenericDao<Employee> {
}
| [
"[email protected]"
]
| |
e73491c3b6b80e95504a7df0e8573979e802f945 | 2881ef2e48bb697c25bc3e32b7a159144d910af9 | /WOC Web/src/org/gr/woc/utils/MD5String.java | 45eb748a910dbe73dc8448daf15aa329ff58bb04 | []
| no_license | nkdxczh/Walk_on_Cloud | c5cf8f1f5e0d798a1925d9f0a24f0c5ba54cd608 | 4a58267c952eda004450d0725d41567f028d1508 | refs/heads/master | 2021-01-20T02:41:34.839567 | 2017-04-26T04:27:37 | 2017-04-26T04:27:37 | 89,437,691 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 1,090 | java | package org.gr.woc.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 功能:实现输入字符串返回一个经过加密的MD5的字符串值
* 开发时间:2014-7-23
* 作者:许精策
*
*
*/
public class MD5String {
//字节数据转换为字符串数据
private String byteToString(byte[] Byte){
String[] strString={"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b",
"c", "d", "e", "f"};
StringBuffer sBuffer=new StringBuffer();
for(int i=0;i<Byte.length;i++){
int ret=Byte[i];
if(ret<0)
ret+=256;
int iD1=ret/16;
int iD2=ret%16;
sBuffer.append(strString[iD1]+strString[iD2]);
}
return sBuffer.toString();
}
//输入字符串生成MD5值
public String getMD5(String str){
String result = null;
try {
MessageDigest md=MessageDigest.getInstance("MD5");
result=byteToString(md.digest(str.getBytes()));
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
| [
"[email protected]"
]
| |
43a4f0d55f1f2b32d19d6169d0b1158fbecd7f1f | 1074c97cdd65d38c8c6ec73bfa40fb9303337468 | /rda0105-agl-aus-java-a43926f304e3/xms-workflow/src/main/java/com/gms/xms/workflow/task/webship/UpdateCustomerDefaultSettingTask.java | 6ad16a2b0d9c42493dbcf66b6f570d715107d68f | []
| no_license | gahlawat4u/repoName | 0361859254766c371068e31ff7be94025c3e5ca8 | 523cf7d30018b7783e90db98e386245edad34cae | refs/heads/master | 2020-05-17T01:26:00.968575 | 2019-04-29T06:11:52 | 2019-04-29T06:11:52 | 183,420,568 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,874 | java | package com.gms.xms.workflow.task.webship;
import com.gms.xms.common.constants.Attributes;
import com.gms.xms.common.constants.ErrorCode;
import com.gms.xms.common.context.ContextBase;
import com.gms.xms.common.utils.GsonUtils;
import com.gms.xms.persistence.dao.CustomerDefaultSettingDao;
import com.gms.xms.txndb.vo.webship.CustomerDefaultSettingVo;
import com.gms.xms.workflow.core.Task;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Map;
/**
* Posted from UpdateCustomerDefaultSettingTask
* <p>
* Author DatTV Date Apr 1, 2015
*/
public class UpdateCustomerDefaultSettingTask implements Task {
private static final Log log = LogFactory.getLog(UpdateCustomerDefaultSettingTask.class);
@Override
public boolean execute(ContextBase context) throws Exception {
CustomerDefaultSettingDao customerDefaultSettingDao = new CustomerDefaultSettingDao();
try {
// Get additional information from the context to put into the service or dao.
Map<String, String> addInfo = GsonUtils.fromGson(context.get(Attributes.STR_ADD_INFO), new TypeToken<Map<String, String>>() {
}.getType());
CustomerDefaultSettingVo customerDefaultSettingVo = GsonUtils.fromGson(context.get(Attributes.CUSTOMER_DEFAULT_SETTING_OBJECT), CustomerDefaultSettingVo.class);
context.put(Attributes.ERROR_CODE, ErrorCode.SUCCESS);
customerDefaultSettingDao.update(addInfo, customerDefaultSettingVo);
} catch (Exception e) {
context.put(Attributes.ERROR_CODE, ErrorCode.ERROR);
context.put(Attributes.ERROR_MESSAGE, e.getMessage());
log.error(e.getMessage());
return false;
}
return true;
}
}
| [
"[email protected]"
]
| |
3da6fd905eb7c7b4ff39c3fb34fa6e5595e9f7c2 | 146d894001f83c4ebc80519cdc7611a06d30daf1 | /app/src/main/java/uom/edu/myapp/controller/StudentCGPA.java | 2741a08566d95637e2982ab678eea48b8aeb0b22 | []
| no_license | trsiddiqui/UnitTest | 07e1d030ad56c946bab482cbacd7fa9ebdf0f55c | 395ba3a8d37f4f6e4461bdbc0733e4210cb6139c | refs/heads/master | 2021-01-17T22:18:53.049659 | 2016-02-12T00:19:27 | 2016-02-12T00:19:27 | 51,614,759 | 0 | 1 | null | 2016-02-12T20:34:50 | 2016-02-12T20:34:49 | null | UTF-8 | Java | false | false | 196 | java | package uom.edu.myapp.controller;
import android.content.Context;
/**
* Created by Moein on 2/11/2016.
*/
public interface StudentCGPA {
public double getStudentCGPA(int id, Context c);
}
| [
"[email protected]"
]
| |
7ff388adceda0849880c56bce74d736c3a0e2975 | 1ce5a14774e6e4966087adf88829bb694e530cb2 | /app/src/main/java/com/meetme/cameracolors/ColorsView.java | 91189dcdec04bdad27b202d0d006657bbd6ad725 | []
| no_license | briandherbert/ColorReader | ca1f355abeef0bc2a76caa4d115791708e5320ed | e8ee5497bacc9e22deb40f61b267f55c22dae332 | refs/heads/master | 2021-01-10T14:23:53.571654 | 2016-01-13T20:30:27 | 2016-01-13T20:30:27 | 47,306,623 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,220 | java | package com.meetme.cameracolors;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import static com.meetme.cameracolors.Constants.*;
/**
* TODO: document your custom view class.
*/
public class ColorsView extends View {
static final String TAG = ColorsView.class.getSimpleName();
int width = 0;
int height = 0;
int squareSize;
int halfSquare;
int gridSize;
String message = "";
// [chunkIdx][bytes]
byte[][] colorBytes;
long mDrawStartTime = 0;
long mLastChunkUpdateTime = 0;
int mCurrentChunkIdx = 0;
Paint paint = new Paint();
Paint redPaint = new Paint();
Paint greenPaint = new Paint();
Paint bluePaint = new Paint();
Paint whitePaint = new Paint();
int[] counts = {0, 0, 0, 0};
public ColorsView(Context context) {
super(context);
init();
}
public ColorsView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ColorsView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public void init() {
colorBytes = new byte[1][CHARS_PER_CHUNK * COLORS_PER_CHAR];
for (int i = 0; i < colorBytes[0].length; i++) {
colorBytes[0][i] = BLACK_BYTE;
}
redPaint.setColor(Color.RED);
greenPaint.setColor(Color.GREEN);
bluePaint.setColor(Color.BLUE);
}
public void setMessage(String msg) {
mCurrentChunkIdx = 0;
message = msg;
convertStringToColorBytes(message);
Log.v(TAG, "message " + message + "\ncolorBytes size " + colorBytes.length);
}
public void convertStringToColorBytes(String str) {
byte[] bytes = stringToBytesASCII(str);
int adjustedCharsPerChunk = CHARS_PER_CHUNK - (IS_CHECKSUMMING ? 1 : 0);
int numChunks = (int) Math.ceil(bytes.length / (double) adjustedCharsPerChunk);
Log.v(TAG, "num chunks : " + numChunks + " byte length " + bytes.length + " chars per chunk " + CHARS_PER_CHUNK);
colorBytes = new byte[numChunks][CHARS_PER_CHUNK * COLORS_PER_CHAR];
for (int c = 0; c < colorBytes.length; c++) {
for (int i = 0; i < colorBytes[c].length; i ++) {
colorBytes[c][i] = BLACK_BYTE;
}
}
byte b;
byte colorByte;
int idx;
int chunkIdx = 0;
for (int i = 0; i < bytes.length; i++) {
b = bytes[i];
chunkIdx = i / adjustedCharsPerChunk;
for (int j = 0; j < COLORS_PER_CHAR; j++) {
idx = ((i % adjustedCharsPerChunk) * COLORS_PER_CHAR) + j;
colorByte = (byte) ((b >> (j * 2)) & 0b11);
// TODO: This will only work for 4 colors!!
//Log.v(TAG, "Assigning byte at " + idx + " to " + colorByte);
counts[colorByte]++;
colorBytes[chunkIdx][idx] = colorByte;
}
}
invalidate();
}
public static byte[] stringToBytesASCII(String str) {
char[] buffer = str.toCharArray();
byte[] b = new byte[buffer.length];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) buffer[i];
}
return b;
}
@Override
protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld) {
super.onSizeChanged(xNew, yNew, xOld, yOld);
width = xNew;
height = yNew;
if (width > 0) {
int shortSide = Math.min(width, height);
squareSize = shortSide / (NUM_SQUARES_PER_SIDE + 1);
halfSquare = squareSize / 2;
gridSize = NUM_SQUARES_PER_SIDE * squareSize;
}
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(halfSquare, 0, halfSquare + gridSize, halfSquare, redPaint);
canvas.drawRect(0, halfSquare, halfSquare, halfSquare + gridSize, greenPaint);
canvas.drawRect(halfSquare, gridSize + halfSquare, halfSquare + gridSize, gridSize + squareSize, bluePaint);
canvas.drawRect(gridSize + halfSquare, halfSquare, gridSize + squareSize, halfSquare + gridSize, bluePaint);
int idx;
byte colorByte;
for (int y = 0; y < NUM_SQUARES_PER_SIDE; y++) {
for (int x = 0; x < NUM_SQUARES_PER_SIDE; x++) {
idx = Math.min(y * NUM_SQUARES_PER_SIDE + x, colorBytes[mCurrentChunkIdx].length - 1);
colorByte = colorBytes[mCurrentChunkIdx][idx];
//Log.v(TAG, "Drawing byte at " + idx + " to " + colorByte);
paint.setColor(colorFromByte(colorByte));
canvas.drawRect(halfSquare + x * squareSize,
halfSquare + y * squareSize,
halfSquare + x * squareSize + squareSize,
halfSquare + y * squareSize + squareSize,
paint);
}
}
if (mDrawStartTime == 0) {
mDrawStartTime = System.currentTimeMillis();
} else {
elapsed = (int) (System.currentTimeMillis() - mDrawStartTime);
newChunkIdx = (elapsed / MS_PER_MESSAGE) % colorBytes.length;
if (newChunkIdx != mCurrentChunkIdx) {
//Log.v(TAG, "drawing chunk " + mCurrentChunkIdx + " after " + elapsed);
mCurrentChunkIdx = newChunkIdx;
}
}
if (!message.isEmpty()) invalidate();
// removeCallbacks(updateChunkRunnable);
// postDelayed(updateChunkRunnable, MS_PER_MESSAGE / 2);
}
int elapsed = 0;
int newChunkIdx = 0;
Handler handler = new Handler();
final Runnable updateChunkRunnable = new Runnable() {
@Override
public void run() {
invalidate();
}
};
}
| [
"[email protected]"
]
| |
27d8a6144bee1e92c463c9d14bf2aca7ae211fcf | 7ceafb397501c016c1c434a9b8bec9bb9f8abd08 | /discovery/src/main/java/com/ibm/watson/discovery/v1/model/CreateTokenizationDictionaryOptions.java | f956fca788a931379e22b4338909908de7a4805e | [
"Apache-2.0"
]
| permissive | kanazawaLri/java-sdk | 0cdf1faa1b417a4da2ba56fd635f52bcc2ce8ad9 | 31e119269fbd8cc8c813f61913f11be1e0835edb | refs/heads/master | 2020-07-18T10:37:10.387401 | 2019-10-07T03:27:19 | 2019-10-07T03:27:19 | 206,228,148 | 0 | 0 | Apache-2.0 | 2019-09-04T04:03:17 | 2019-09-04T04:03:17 | null | UTF-8 | Java | false | false | 4,972 | java | /*
* Copyright 2018 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.ibm.watson.discovery.v1.model;
import java.util.ArrayList;
import java.util.List;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
import com.ibm.cloud.sdk.core.util.Validator;
/**
* The createTokenizationDictionary options.
*/
public class CreateTokenizationDictionaryOptions extends GenericModel {
private String environmentId;
private String collectionId;
private List<TokenDictRule> tokenizationRules;
/**
* Builder.
*/
public static class Builder {
private String environmentId;
private String collectionId;
private List<TokenDictRule> tokenizationRules;
private Builder(CreateTokenizationDictionaryOptions createTokenizationDictionaryOptions) {
this.environmentId = createTokenizationDictionaryOptions.environmentId;
this.collectionId = createTokenizationDictionaryOptions.collectionId;
this.tokenizationRules = createTokenizationDictionaryOptions.tokenizationRules;
}
/**
* Instantiates a new builder.
*/
public Builder() {
}
/**
* Instantiates a new builder with required properties.
*
* @param environmentId the environmentId
* @param collectionId the collectionId
*/
public Builder(String environmentId, String collectionId) {
this.environmentId = environmentId;
this.collectionId = collectionId;
}
/**
* Builds a CreateTokenizationDictionaryOptions.
*
* @return the createTokenizationDictionaryOptions
*/
public CreateTokenizationDictionaryOptions build() {
return new CreateTokenizationDictionaryOptions(this);
}
/**
* Adds an tokenizationRules to tokenizationRules.
*
* @param tokenizationRules the new tokenizationRules
* @return the CreateTokenizationDictionaryOptions builder
*/
public Builder addTokenizationRules(TokenDictRule tokenizationRules) {
Validator.notNull(tokenizationRules, "tokenizationRules cannot be null");
if (this.tokenizationRules == null) {
this.tokenizationRules = new ArrayList<TokenDictRule>();
}
this.tokenizationRules.add(tokenizationRules);
return this;
}
/**
* Set the environmentId.
*
* @param environmentId the environmentId
* @return the CreateTokenizationDictionaryOptions builder
*/
public Builder environmentId(String environmentId) {
this.environmentId = environmentId;
return this;
}
/**
* Set the collectionId.
*
* @param collectionId the collectionId
* @return the CreateTokenizationDictionaryOptions builder
*/
public Builder collectionId(String collectionId) {
this.collectionId = collectionId;
return this;
}
/**
* Set the tokenizationRules.
* Existing tokenizationRules will be replaced.
*
* @param tokenizationRules the tokenizationRules
* @return the CreateTokenizationDictionaryOptions builder
*/
public Builder tokenizationRules(List<TokenDictRule> tokenizationRules) {
this.tokenizationRules = tokenizationRules;
return this;
}
}
private CreateTokenizationDictionaryOptions(Builder builder) {
Validator.notEmpty(builder.environmentId, "environmentId cannot be empty");
Validator.notEmpty(builder.collectionId, "collectionId cannot be empty");
environmentId = builder.environmentId;
collectionId = builder.collectionId;
tokenizationRules = builder.tokenizationRules;
}
/**
* New builder.
*
* @return a CreateTokenizationDictionaryOptions builder
*/
public Builder newBuilder() {
return new Builder(this);
}
/**
* Gets the environmentId.
*
* The ID of the environment.
*
* @return the environmentId
*/
public String environmentId() {
return environmentId;
}
/**
* Gets the collectionId.
*
* The ID of the collection.
*
* @return the collectionId
*/
public String collectionId() {
return collectionId;
}
/**
* Gets the tokenizationRules.
*
* An array of tokenization rules. Each rule contains, the original `text` string, component `tokens`, any alternate
* character set `readings`, and which `part_of_speech` the text is from.
*
* @return the tokenizationRules
*/
public List<TokenDictRule> tokenizationRules() {
return tokenizationRules;
}
}
| [
"[email protected]"
]
| |
16612cde631226c73be1aef0a9b03edd5fa55f95 | 676b4b87933765c97bcaea41131adf4f6a659116 | /src/main/java/io/github/foundationgames/sandwichable/items/InfoTooltipBlockItem.java | 256a3322b5ce9067fa2308dc63398c6cc56e7be4 | [
"MIT"
]
| permissive | FoundationGames/Sandwichable | de3e12d6039bbbb3d8d920734a21ead7389d5fab | afedce3c95040c79858c025ab171b19f968efbf8 | refs/heads/1.18.2 | 2023-08-29T15:22:48.377118 | 2022-06-28T06:40:58 | 2022-06-28T06:40:58 | 253,937,504 | 34 | 37 | MIT | 2023-06-05T05:30:29 | 2020-04-07T23:40:37 | Java | UTF-8 | Java | false | false | 996 | java | package io.github.foundationgames.sandwichable.items;
import io.github.foundationgames.sandwichable.util.Util;
import net.minecraft.block.Block;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.client.resource.language.I18n;
import net.minecraft.item.BlockItem;
import net.minecraft.item.ItemStack;
import net.minecraft.text.LiteralText;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.Formatting;
import net.minecraft.world.World;
import java.util.List;
public class InfoTooltipBlockItem extends BlockItem {
public InfoTooltipBlockItem(Block block, Settings settings) {
super(block, settings);
}
@Override
public void appendTooltip(ItemStack stack, World world, List<Text> tooltip, TooltipContext context) {
super.appendTooltip(stack, world, tooltip, context);
Util.appendInfoTooltip(tooltip, this.getTranslationKey());
}
}
| [
"[email protected]"
]
| |
9d308b46a56f1c168fadc81d4fdb22044fa1d240 | de3a388ff2b99257486eed6e191cfab3ea57cc57 | /src/main/java/com/pakmall/controller/BoardController.java | 225e0711de9c9417438016e4917d6af1fc9c01b4 | []
| no_license | rbdudek86/pakmall | 9238daa97885007ef776bfe59f788d28dacd8858 | 99f8ab019610ced875c7d5227ef9e3bd7afcd9af | refs/heads/master | 2023-06-26T08:26:10.241393 | 2021-07-16T13:20:08 | 2021-07-16T13:20:08 | 366,240,902 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,936 | java | package com.pakmall.controller;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
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.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.pakmall.domain.BoardVO;
import com.pakmall.domain.ReplyVO;
import com.pakmall.dto.Criteria;
import com.pakmall.dto.PageDTO;
import com.pakmall.service.BoardService;
import com.pakmall.service.ReplyService;
import lombok.Setter;
import lombok.extern.log4j.Log4j;
@Controller
@Log4j
@RequestMapping("/board/*")
public class BoardController {
@Setter(onMethod_ = @Autowired)
private BoardService boardService;
@Setter(onMethod_ = @Autowired)
private ReplyService replyService;
// 게시판 리스트
@RequestMapping(value = "/board_list",method = {RequestMethod.GET, RequestMethod.POST})
public void board_list (@ModelAttribute("cri") Criteria cri, Model model, BoardVO vo) throws Exception{
List<BoardVO> boardList = boardService.getBoardList(cri);
System.out.println(boardList);
model.addAttribute("boardList", boardList);
int total = boardService.getTotalCountList(cri);
System.out.println("total=============" + total);
model.addAttribute("total", total);
model.addAttribute("pageMaker", new PageDTO(cri, total));
}
// 게시판 리스트2 폼
@GetMapping("/board_list2")
public void board_list2() {
}
// 게시글 등록 페이지
@GetMapping("/board_register")
public void board_register() {
}
// 게시글 등록
@PostMapping("/board_register")
public String board_register(BoardVO vo, RedirectAttributes rttr) throws Exception {
boardService.board_register(vo);
return "redirect:/board/board_list";
}
// 게시글 상세
@GetMapping("/board_detail")
public String board_detail(BoardVO vo, Model model) throws Exception {
BoardVO detail = boardService.board_detail(vo);
System.out.println("detail========" + detail);
model.addAttribute("detail", detail);
return "/board/board_detail";
}
// 게시글 상세 ajax
@GetMapping("/board_detail2")
public String board_detail2(@ModelAttribute("cri") Criteria cri, @RequestParam("bd_num")long bd_num, BoardVO board, ReplyVO vo, Model model) throws Exception {
model.addAttribute("bd_num", board.getBd_num());
System.out.println("vo.getBd_num()=========" + board.getBd_num());
int total = replyService.getTotalCountList(bd_num);
System.out.println("total===========" + total);
cri.setBd_num(board.getBd_num());
System.out.println("cri.setBd_num==========" + cri.getBd_num());
System.out.println("#{pageNum}=====" + cri.getPageNum());
System.out.println("#{amount}==========" + cri.getAmount());
// 댓글리스트
List<ReplyVO> replyList = replyService.reply_getList(cri);
System.out.println("댓글리스트===========" + replyList);
model.addAttribute("replyList", replyList);
model.addAttribute("pageMaker", new PageDTO(cri, total));
return "/board/board_detail2";
}
@ResponseBody
@GetMapping("/ajaxDetail")
public ResponseEntity<BoardVO> ajaxDetail(BoardVO vo, HttpSession session) throws Exception {
ResponseEntity<BoardVO> entity = null;
BoardVO detail = boardService.board_detail(vo);
System.out.println("detail===========" + detail);
if(detail != null) {
entity = new ResponseEntity<BoardVO>(detail,HttpStatus.OK);
}else {
entity = new ResponseEntity<BoardVO>(HttpStatus.OK);
}
return entity;
}
// 게시글 수정
@PostMapping("/board_update")
public String board_update(BoardVO vo, RedirectAttributes rttr) throws Exception {
System.out.println("vo===========" + vo);
boardService.board_update(vo);
return "redirect:/board/board_list";
}
// 게시글 삭제
@ResponseBody
@PostMapping("/board_delete")
public ResponseEntity<String> board_delete(long bd_num) throws Exception{
System.out.println("bd_num===========" + bd_num);
ResponseEntity<String> entity = null;
int resultCnt = boardService.board_delete(bd_num);
// 성공하면 resultCnt = 1
if(resultCnt > 0) {
entity = new ResponseEntity<String>("SUCCESS", HttpStatus.OK);
}else {
entity = new ResponseEntity<String>(HttpStatus.OK);
}
return entity;
}
}
| [
"[email protected]"
]
| |
d42b2259e24ef5177d793d94d98ba1b98f1ea91e | 02e4fdca6960cdf2f1e07da8e352fb240ee947c2 | /src/main/java/squedgy/lavasources/tileentity/TileEntityEnergyGenerator.java | a3c4d7ae15bd7ccc049f8004ed3da32b62bacc0b | []
| no_license | squedgy/LavaSources | 19c578a2b42b652d030cc18ed443c2d8664616a3 | 7e4c15227e626087de1c0fdb4ee9138a62bd2bdb | refs/heads/master | 2020-03-30T22:55:46.366304 | 2018-10-05T07:11:29 | 2018-10-05T07:11:29 | 151,683,619 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,047 | java | package squedgy.lavasources.tileentity;
import java.util.Objects;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.energy.IEnergyStorage;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import squedgy.lavasources.LavaSources;
import squedgy.lavasources.block.BlockEnergyGenerator;
import squedgy.lavasources.capabilities.ModEnergyStorage;
import squedgy.lavasources.enums.EnumUpgradeTier;
import squedgy.lavasources.generic.IPersistentInventory;
import squedgy.lavasources.generic.IUpgradeable;
import squedgy.lavasources.init.ModFluids;
/**
*
* @author David
*/
public class TileEntityEnergyGenerator extends TileEntity implements ITickable, IUpgradeable, IPersistentInventory {
//<editor-fold defaultstate="collapsed" desc=". . . . Fields">
protected ModEnergyStorage energy;
protected EnumFacing facing;
protected EnumUpgradeTier tier;
protected int generated;
protected boolean destroyedByCreative;
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=". . . . Constructors">
public TileEntityEnergyGenerator(EnumUpgradeTier tier){
this.tier = tier;
updateTierRelatedComponents(0, EnumFacing.NORTH);
energy.receive = false;
}
public TileEntityEnergyGenerator(){
this(EnumUpgradeTier.BASIC);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=". . . . ITickable/helper methods">
@Override
public void update() {
if(this.getPowered()){
energy.receive = true;
energy.receiveEnergy(generated, false);
energy.receive = false;
}
int pushable = Math.min(energy.getMaxExtracted(), energy.getEnergyStored());
if(pushable > 0){
for(EnumFacing testFacing : EnumFacing.values()){
TileEntity test = getWorld().getTileEntity(getPos().offset(testFacing));
if(test != null){
IEnergyStorage handler = test.getCapability(CapabilityEnergy.ENERGY, testFacing.getOpposite());
if(handler != null && handler.canReceive()){
pushable -= handler.receiveEnergy(pushable, false);
}
}
if(pushable == 0) break;
}
}
}
public boolean getPowered() {
return getWorld().isBlockPowered(getPos());
}
public EnumFacing getFacing() {
return this.facing;
}
public void setFacing(EnumFacing facing){
this.facing = facing;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=". . . . TileEntity overrides">
@Override
public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt ){
readFromNBT(pkt.getNbtCompound());
}
@Override
public SPacketUpdateTileEntity getUpdatePacket(){
NBTTagCompound compound = new NBTTagCompound();
writeToNBT(compound);
return new SPacketUpdateTileEntity(getPos(), 1, compound);
}
@Override
public NBTTagCompound getUpdateTag() {
NBTTagCompound tag = super.getUpdateTag();
return writeToNBT(tag);
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
super.writeToNBT(compound);
return writeItem(compound);
}
@Override
public void readFromNBT(NBTTagCompound compound) {
super.readFromNBT(compound); //To change body of generated methods, choose Tools | Templates.
tier = EnumUpgradeTier.values()[compound.getInteger("tier")];
updateTierRelatedComponents();
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing) {
if(capability == CapabilityEnergy.ENERGY)
return (T) energy;
return super.getCapability(capability, facing); //To change body of generated methods, choose Tools | Templates.
}
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing) {
if(capability == CapabilityEnergy.ENERGY)
return true;
return super.hasCapability(capability, facing);
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=". . . . IUpgradeable Overrides">
@Override
public boolean upgrade(EnumUpgradeTier tier) {
boolean ret = false;
if(tier.LEVEL > this.tier.LEVEL){
this.energy = tier.getEnergyTier().getEnergyStorage((energy != null) ? energy.getPowerStored() : 0);
energy.receive = false;
this.generated = tier.getEnergyTier().getGenerated();
this.tier = tier;
ret = true;
markDirty();
}
return ret;
}
@Override
public EnumUpgradeTier getCurrentTier() {
return tier;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=". . . . Persistent Inventory">
@Override
public boolean shouldDropSpecial() {
return this.energy.getEnergyStored() > 0 || this.tier.LEVEL > 0;
}
@Override
public boolean isDestroyedByCreative() {
return destroyedByCreative;
}
@Override
public void setDestroyedByCreative(boolean destroyedByCreative) {
this.destroyedByCreative = destroyedByCreative;
}
@Override
public NBTTagCompound writeItem(NBTTagCompound compound) {
compound.setInteger("tier", tier.LEVEL);
compound.setInteger("stored", energy.getPowerStored());
compound.setInteger("facing", facing.getHorizontalIndex());
return compound;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc=". . . . Helpers">
public EnumUpgradeTier getTier(){ return tier; }
private void updateTierRelatedComponents(){ updateTierRelatedComponents( energy.getEnergyStored(), facing ); }
private void updateTierRelatedComponents(int energyStored, EnumFacing facing){
this.energy = this.tier.getEnergyTier().getEnergyStorage(energyStored);
this.generated = this.tier.getEnergyTier().GENERATED;
this.facing = facing;
}
//</editor-fold>
}
| [
"[email protected]"
]
| |
55c2c1845c80e3463e9ee3fe549275cc9244d8a4 | 1b7c8ea7d46d9602a0019c88892f26e11cadddde | /src/Solver.java | 144d9bdcd4fbfa01ffb308d89657dc0ecfc8096e | []
| no_license | KindlerJC/Thesis | ea789937b9cba128619cecd2a627636c84b8192e | dcae0f39c9f611cc2c6fd5eac450cd4a30ffd3a0 | refs/heads/master | 2022-06-26T07:22:55.200158 | 2020-05-07T16:01:56 | 2020-05-07T16:01:56 | 238,279,253 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,503 | java | public class Solver
{
private Vector[] tree;
private boolean[] finalSet;
public AdjacencyList adjList;
public WimerTable wimerTable;
private Vector initialVector;
public Solver(String edgeFile, String tableFile, boolean isList)
{
adjList = new AdjacencyList(edgeFile);
wimerTable = new WimerTable(tableFile, isList);
initialVector = wimerTable.getInitialVector();
tree = new Vector[adjList.getSize()];
for (int i = 0; i < tree.length; i++)
tree[i] = new Vector(initialVector, i);
finalSet = new boolean[adjList.getSize()];
}
public void run(boolean listFormat)
{
runRoot(listFormat, 0);
}
public void runRoot(boolean listFormat, int root)
{
var finalVector = getFinalVector(root);
var bestEntry = listFormat ? wimerTable.getBestEntryList(finalVector) : wimerTable.getBestEntry(finalVector);
int setSize = bestEntry.getSize();
System.out.println("Root: " + root);
if (setSize == -1)
{
System.out.println("No valid set returned.");
return;
}
System.out.println("Set size: " + bestEntry.getSize());
findSet(finalVector, bestEntry.getComp().getCase());
}
public void printSet()
{
for (int i = 0; i < finalSet.length; i++)
if (finalSet[i])
System.out.printf("%d is in the set\n", i);
}
public Vector getFinalVector(int root)
{
var parents = adjList.getParentArray(root);
var order = adjList.getTraversalOrder(root);
Vector a, b;
int parent, current;
for (int i = 0; i < order.length - 1; i++)
{
current = order[i];
parent = parents[current];
a = tree[parent];
b = tree[current];
tree[parent] = wimerTable.compose(a, b);
tree[parent].position = parent;
}
return tree[root];
}
void findSet(Vector ptr, int comp)
{
var currentComp = ptr.entryAt(comp);
if (ptr.getLeft() == null) // If the vector has no left component it has no right component either
{
var size = initialVector.entryAt(comp).getSize();
if (size == 1)
finalSet[ptr.position] = true;
return;
}
findSet(ptr.getLeft(), currentComp.getParentCase());
findSet(ptr.getRight(), currentComp.getChildCase());
}
}
| [
"[email protected]"
]
| |
5c79b01a4b26dddb28294eb6cd59be0e3fd14de8 | e12387bfcb3729f33ce264cd2ea3ec0aee4c0952 | /MyAirBnB Spring/src/main/java/it/unisalento/myairbnb/entities/Commento.java | 8f9efa03f0b7cfc7d3d7a404e457288ecae20f45 | []
| no_license | luigipaiano/software_engigneering | c386e2e6f2193c90956969e4cc4dca7477617403 | b6344d391586e6a33540bacbe15d5f112edfae41 | refs/heads/master | 2021-01-04T19:11:45.513203 | 2020-02-15T14:32:42 | 2020-02-15T14:32:42 | 240,724,304 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,148 | java | // Generated with g9.
package it.unisalento.myairbnb.entities;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Version;
@Entity(name="commento")
public class Commento implements Serializable {
/** Primary key. */
protected static final String PK = "idcommento";
/**
* The optimistic lock. Available via standard bean get/set operations.
*/
@Column(name="LOCK_FLAG")
private Integer lockFlag;
/**
* Access method for the lockFlag property.
*
* @return the current value of the lockFlag property
*/
public Integer getLockFlag() {
return lockFlag;
}
/**
* Sets the value of the lockFlag property.
*
* @param aLockFlag the new value of the lockFlag property
*/
public void setLockFlag(Integer aLockFlag) {
lockFlag = aLockFlag;
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(unique=true, nullable=false, precision=10)
private int idcommento;
private Timestamp data;
@Column(precision=10)
private int tipo;
@Column(precision=10)
private int val;
@Column(length=255)
private String descrizione;
@ManyToOne
@JoinColumn(name="idacquirente")
private Acquirente acquirente;
@ManyToOne
@JoinColumn(name="idproposta")
private Proposta proposta;
/** Default constructor. */
public Commento() {
super();
}
/**
* Access method for idcommento.
*
* @return the current value of idcommento
*/
public int getIdcommento() {
return idcommento;
}
/**
* Setter method for idcommento.
*
* @param aIdcommento the new value for idcommento
*/
public void setIdcommento(int aIdcommento) {
idcommento = aIdcommento;
}
/**
* Access method for data.
*
* @return the current value of data
*/
public Timestamp getData() {
return data;
}
/**
* Setter method for data.
*
* @param aData the new value for data
*/
public void setData(Timestamp aData) {
data = aData;
}
/**
* Access method for tipo.
*
* @return the current value of tipo
*/
public int getTipo() {
return tipo;
}
/**
* Setter method for tipo.
*
* @param aTipo the new value for tipo
*/
public void setTipo(int aTipo) {
tipo = aTipo;
}
/**
* Access method for val.
*
* @return the current value of val
*/
public int getVal() {
return val;
}
/**
* Setter method for val.
*
* @param aVal the new value for val
*/
public void setVal(int aVal) {
val = aVal;
}
/**
* Access method for descrizione.
*
* @return the current value of descrizione
*/
public String getDescrizione() {
return descrizione;
}
/**
* Setter method for descrizione.
*
* @param aDescrizione the new value for descrizione
*/
public void setDescrizione(String aDescrizione) {
descrizione = aDescrizione;
}
/**
* Access method for acquirente.
*
* @return the current value of acquirente
*/
public Acquirente getAcquirente() {
return acquirente;
}
/**
* Setter method for acquirente.
*
* @param aAcquirente the new value for acquirente
*/
public void setAcquirente(Acquirente aAcquirente) {
acquirente = aAcquirente;
}
/**
* Access method for proposta.
*
* @return the current value of proposta
*/
public Proposta getProposta() {
return proposta;
}
/**
* Setter method for proposta.
*
* @param aProposta the new value for proposta
*/
public void setProposta(Proposta aProposta) {
proposta = aProposta;
}
/**
* Compares the key for this instance with another Commento.
*
* @param other The object to compare to
* @return True if other object is instance of class Commento and the key objects are equal
*/
private boolean equalKeys(Object other) {
if (this==other) {
return true;
}
if (!(other instanceof Commento)) {
return false;
}
Commento that = (Commento) other;
if (this.getIdcommento() != that.getIdcommento()) {
return false;
}
return true;
}
/**
* Compares this instance with another Commento.
*
* @param other The object to compare to
* @return True if the objects are the same
*/
@Override
public boolean equals(Object other) {
if (!(other instanceof Commento)) return false;
return this.equalKeys(other) && ((Commento)other).equalKeys(this);
}
/**
* Returns a hash code for this instance.
*
* @return Hash code
*/
@Override
public int hashCode() {
int i;
int result = 17;
i = getIdcommento();
result = 37*result + i;
return result;
}
/**
* Returns a debug-friendly String representation of this instance.
*
* @return String representation of this instance
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer("[Commento |");
sb.append(" idcommento=").append(getIdcommento());
sb.append("]");
return sb.toString();
}
/**
* Return all elements of the primary key.
*
* @return Map of key names to values
*/
public Map<String, Object> getPrimaryKey() {
Map<String, Object> ret = new LinkedHashMap<String, Object>(6);
ret.put("idcommento", Integer.valueOf(getIdcommento()));
return ret;
}
}
| [
""
]
| |
cb8be866e8863cb7579a2a458b82f7576ac4b152 | bf86c8b10ed0baceca394a32fd72ba0cb8fb3651 | /app/src/test/java/com/example/agoodman/killersuggestionapp/ExampleUnitTest.java | abccfb49fc8edd2628e5b38f7aa0b141bf2ea314 | []
| no_license | agoodman42/KillerSuggestionApp | 48cc1b7cce662355e353095108117a4ec9b09c71 | 5a2c498452ebc3d85f6feb23c0b1a7ab8b8fa83b | refs/heads/master | 2021-01-22T05:32:49.723555 | 2017-06-11T03:12:18 | 2017-06-11T03:12:18 | 92,475,096 | 0 | 2 | null | 2017-06-11T03:12:19 | 2017-05-26T05:21:17 | Java | UTF-8 | Java | false | false | 418 | java | package com.example.agoodman.killersuggestionapp;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
]
| |
81ff4d9d6370bcccc37b163f5d036e0bce120fde | a8528c4cc38a7e69a38b5efcf04a9afedea7db47 | /employee-service/src/test/java/io/edrb/employeeservice/employeeservice/service/EmployeeServiceTest.java | c169764b726be01ef4fbb7ee98ce6745caab13be | []
| no_license | edrb2409/spring-event-microservices-sample | bf3d5c0e71ad42a8ffe08271c07c1e528c549846 | bea1fdf20376ae58600fd39a82c5d1a3eec9ef18 | refs/heads/master | 2020-05-17T17:28:27.789950 | 2019-04-28T04:05:47 | 2019-04-28T04:05:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,548 | java | package io.edrb.employeeservice.employeeservice.service;
import io.edrb.employeeservice.employeeservice.exception.DepartmentNotFoundException;
import io.edrb.employeeservice.employeeservice.exception.EmployeeNotFoundException;
import io.edrb.employeeservice.employeeservice.exception.NotUniqueEmailException;
import io.edrb.employeeservice.employeeservice.model.Department;
import io.edrb.employeeservice.employeeservice.model.Employee;
import io.edrb.employeeservice.employeeservice.repository.DepartmentRepository;
import io.edrb.employeeservice.employeeservice.repository.EmployeeRepository;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.sql.Date;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.util.Optional;
import java.util.UUID;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
public class EmployeeServiceTest {
private EmployeeService service;
@Mock EmployeeRepository repository;
@Mock DepartmentRepository departmentRepository;
@BeforeEach void init_() {
service = new DefaultEmployeeService(repository, departmentRepository);
}
@Test void shouldCreateNewEmployee() {
String id = UUID.randomUUID().toString();
when(repository.save(getEmployeeForCreating())).thenReturn(getEmployee(id));
when(departmentRepository.findByName("IT")).thenReturn(Optional.of(it()));
Employee employeeCreated = service.create(getEmployeeForCreating());
Assertions.assertEquals(id, employeeCreated.getId());
}
@Test void shouldRaiseAnExceptionWhenEmailIsNotUniqueOnCreation() {
when(repository.save(getEmployeeForCreating())).thenThrow(NotUniqueEmailException.class);
when(departmentRepository.findByName("IT")).thenReturn(Optional.of(it()));
Assertions.assertThrows(NotUniqueEmailException.class,
() -> service.create(getEmployeeForCreating()));
}
@Test void shouldRaiseAnExceptionWhenDepartmentIsNotFound() {
when(departmentRepository.findByName("IT")).thenReturn(Optional.empty());
Assertions.assertThrows(DepartmentNotFoundException.class,
() -> service.create(getEmployeeForCreating()));
}
@Test void shouldUpdateAnEmployee() {
String id = UUID.randomUUID().toString();
when(repository.findById(id)).thenReturn(Optional.of(getEmployee(id)));
when(departmentRepository.findByName("IT")).thenReturn(Optional.of(it()));
when(repository.save(getEmployee(id))).thenReturn(getEmployee(id));
Employee employeeCreated = service.update(id, getEmployee(id));
Assertions.assertEquals(id, employeeCreated.getId());
}
@Test void shouldRaiseAnExceptionWhenEmailIsNotUniqueOnUpdate() {
String id = UUID.randomUUID().toString();
when(repository.findById(id)).thenReturn(Optional.of(getEmployee(id)));
when(departmentRepository.findByName("IT")).thenReturn(Optional.of(it()));
when(repository.save(getEmployee(id))).thenThrow(NotUniqueEmailException.class);
Assertions.assertThrows(NotUniqueEmailException.class,
() -> service.update(id, getEmployee(id)));
}
@Test void shouldRaiseAnExceptionWhenEmployeeDoesNotExistsOnUpdate() {
when(repository.findById("12")).thenReturn(Optional.empty());
Assertions.assertThrows(EmployeeNotFoundException.class,
() -> service.update("12", getEmployee("12")));
}
@Test void shouldGetAEmployeeById() {
when(repository.findById("123")).thenReturn(Optional.of(getEmployee("123")));
Assertions.assertEquals("123", service.getById("123").getId());
}
@Test void shouldRaiseAnExceptionWhenEmployeeDoesNotExistsOnGetById() {
when(repository.findById("12")).thenReturn(Optional.empty());
Assertions.assertThrows(EmployeeNotFoundException.class,
() -> service.getById("12"));
}
@Test void shouldDeleteAEmployee() {
when(repository.findById("123")).thenReturn(Optional.of(getEmployee("123")));
// verify(repository, times(1)).deleteById("123");
service.delete("123");
}
@Test void shouldRaiseAnExceptionWhenEmployeeDoesNotExistsOnDelete() {
when(repository.findById("123")).thenReturn(Optional.of(getEmployee("123")));
service.delete("123");
}
private Employee getEmployeeForCreating() {
return Employee.builder()
.birthday(Date.from(LocalDate.of(1986, Month.SEPTEMBER, 24).atStartOfDay(ZoneId.of("UTC")).toInstant()))
.department(Department.builder().id(1L).name("IT").build())
.email("[email protected]")
.fullname("me some")
.build();
}
private Employee getEmployee(String id) {
return Employee.builder()
.birthday(Date.from(LocalDate.of(1986, Month.SEPTEMBER, 24).atStartOfDay(ZoneId.of("UTC")).toInstant()))
.department(Department.builder().id(1L).name("IT").build())
.email("[email protected]")
.fullname("me some")
.id(id)
.build();
}
private Department it() {
return Department.builder()
.id(1L)
.name("IT")
.build();
}
}
| [
"[email protected]"
]
| |
bb377b4eaa193408ac219526eebe9054143afe98 | 71abdd26d4dd84c8871c26b60d93020d721686fa | /cspp2-assignments/m4/Assignment-4/Solution.java | 6af134ab19b64393c8ab90ac97c808282773596a | []
| no_license | Abhilash11Addanki/cspp2 | 499871b791fd4595d5c6293613184f7b89367516 | 2976de976fd429778e14a9f20a60467d588cdb28 | refs/heads/master | 2020-03-27T08:29:22.568223 | 2018-09-23T14:21:03 | 2018-09-23T14:21:03 | 146,259,798 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 869 | java | /**
* author : @abhilash
* Date 30 Aug 2018
*/
import java.util.Scanner;
/**
* Class for solution.
*/
public final class Solution {
/**
* Constructs the object.
*/
private Solution() {
}
/**
* main method.
* @param args The arguments
*/
public static void main(final String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String reverse = reverseString(s);
System.out.println(reverse);
}
/**
* reverseString method.
* @param str The string.
* @return { description_of_the_return_value }
*/
static String reverseString(final String str) {
String[] s = str.split("");
String res = "";
for (int i = s.length - 1; i >= 0; i--) {
res += s[i];
}
return res;
}
}
| [
"[email protected]"
]
| |
34d6e217b088f414b02563342bd7df83b7d10725 | 224c01f0be2d5e45a02a9bf2f32a79d236f25306 | /src/lite/ast/LiteCall.java | 60cdd3a5bc4df0c00b0f331a2167e7310d1a701c | [
"Unlicense"
]
| permissive | duangsuse-valid-projects/Lite | 0bbae453c7295b1e84e0d57146a589b9dc7a56ef | 431d9aea4fb1bcb9332ce379bb799f075196fb42 | refs/heads/master | 2021-06-24T23:09:10.585387 | 2020-11-06T12:13:44 | 2020-11-06T12:13:44 | 132,313,263 | 2 | 0 | Unlicense | 2020-11-06T12:13:45 | 2018-05-06T06:35:27 | Java | UTF-8 | Java | false | false | 3,537 | java | package lite.ast;
import lite.Interpreter;
import lite.LiteBlock;
import lite.LiteNode;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
/**
* A call to function(block)value/Java class constructor/Lite object(hash)
* <p>
* Hashtable()
* String("hello")
* def a
* puts
* a()
* <p>
* '@b = do |i| puts i
* '@b(1)
* <p>
* identifier/class '(' params ')'
*
* @author duangsuse
* @since 1.0
*/
public class LiteCall extends LiteNode {
/**
* The identifier to call
*/
public LiteIdentifier identifier;
/**
* The call args
*/
public ArrayList<LiteNode> args = new ArrayList<>();
/**
* Blank constructor
*/
public LiteCall() {
}
/**
* Quick constructor
*
* @param ident identifier for call
* @param argv arguments
*/
public LiteCall(LiteIdentifier ident, ArrayList<LiteNode> argv) {
this.identifier = ident;
this.args = argv;
}
/**
* Call the identifier, may be a Class/lite object/block
*
* @param context lite interpreter context
* @return return result/new object
*/
@Override
public Object eval(Interpreter context) {
// get called object
Object idValue = identifier.eval(context);
// get arguments
Object[] arguments = new Object[args.size()];
Object ret = null;
for (int i = 0; i < args.size(); i++)
arguments[i] = args.get(i).eval(context);
// get argument classes
Class[] argumentClasses = new Class[arguments.length];
for (int i = 0; i < arguments.length; i++)
argumentClasses[i] = arguments[i].getClass();
// invoke
if (idValue instanceof Class) {
try {
// try construct this class
Constructor ctor = ((Class<?>) idValue).getDeclaredConstructor(argumentClasses);
ret = ctor.newInstance(arguments);
} catch (NoSuchMethodException e) {
context.error("Failed to get constructor for class " + identifier);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
context.error("Failed to call constructor: " + e);
context.set("err", e);
e.printStackTrace();
}
} else if (idValue instanceof LiteBlock) {
if (((LiteBlock) idValue).argNames.size() != arguments.length) {
context.error("Argument size mismatch: expected " + arguments.length + " but actual " + ((LiteBlock) idValue).argNames.size());
return null;
}
context.enterScope();
for (int i = 0; i < ((LiteBlock) idValue).argNames.size(); i++) {
context.scopePut(((LiteBlock) idValue).argNames.get(i), arguments[i]);
}
ret = ((LiteNode) idValue).eval(context);
context.leaveScope();
} else {
context.error("Failed to call " + identifier + ": Not a JavaClass or LiteBlock");
}
return ret;
}
/**
* call literal string
*
* @return identifier(args)
*/
@Override
public String toString() {
StringBuilder ret = new StringBuilder(identifier.toString());
ret.append("( ");
for (LiteNode i : args)
ret.append(i.toString()).append(' ');
ret.append(')');
return ret.toString();
}
}
| [
"[email protected]"
]
| |
a80c862e36bee233d6d54c5309f5be4ddc806c08 | a1be0880535fae263fbd110f8a82332c36b9e804 | /HelloWorld.java | e371b3832240df019bb437a1feed52153473ac47 | []
| no_license | d5d5/cui | bfb563b6ca32838d4c358c7e33eee2a567f5461a | 3b4dd7dbf1d711a07236c82466136dda4c3b9daa | refs/heads/master | 2020-07-28T01:47:09.499625 | 2019-09-28T07:25:34 | 2019-09-28T07:25:34 | 209,272,654 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 105 | java | public class HelloWorld{
public static void main(String[]args){
System.out.println("hello world");
}
} | [
"y孟彬傻”git config --global user.email y孟彬傻”"
]
| y孟彬傻”git config --global user.email y孟彬傻” |
5404fa38914a9ace0e5cc1f3b13b306ca3b15b9c | f8d31528e4dca2a6340b434bffd5ba6a2cacafcd | /jdk9src/src/main/java/com/sun/tools/javac/resources/version.java | 2571e859a0b6152fcf2af50ea918fbda3e7555df | []
| no_license | uptonking/jdksrc | 1871ad9c312845f6873d741db2f13837f046232d | d628a733240986c59d96185acef84283e1b5aff5 | refs/heads/master | 2021-09-15T00:10:18.103059 | 2018-03-03T12:31:24 | 2018-03-03T12:31:24 | 109,384,307 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 342 | java | package com.sun.tools.javac.resources;
public final class version extends java.util.ListResourceBundle {
protected final Object[][] getContents() {
return new Object[][] {
{ "full", "9-internal+0-2016-04-14-195246.buildd.src" },
{ "jdk", "9" },
{ "release", "9-internal" },
};
}
}
| [
"[email protected]"
]
| |
57a06442fe5e61709da208fd2c7288aafa7690e6 | aa0e8285b9b6b02f899f18f80169a89e6ce0dc19 | /workspace_softqin/softqin-framework/src/main/java/com/huixin/framework/repository/DSTreadLocal.java | b78c6bcea386ca098bbcc7fc81bfe5afae619797 | []
| no_license | xiaoronghao/text | 1d7b34f2c60f1bd70e7ebca58c3b6b7d128280c0 | 24cf932dea69dde0096efeab1a27ea8ecaec6267 | refs/heads/master | 2022-12-23T11:03:36.502298 | 2019-09-23T07:33:19 | 2019-09-23T07:33:19 | 210,252,764 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 506 | java | package com.huixin.framework.repository;
import org.springframework.util.Assert;
public class DSTreadLocal {
private static final ThreadLocal<DSType> dsTypeContextHolder = new ThreadLocal<DSType>();
public static DSType getDsTypeContextHolder() {
return dsTypeContextHolder.get();
}
public static void setDsTypeContextHolder(DSType dsType){
Assert.notNull(dsType);
dsTypeContextHolder.set(dsType);
}
public static void clearDsTypeContextHolder(){
dsTypeContextHolder.remove();
}
}
| [
"[email protected]"
]
| |
f4e39fe5dc7934b33142d382085672e9b59debba | f5e1170aef3951cc3c39722525251a1d8ce31d26 | /app/src/main/java/com/jiupin/jiupinhui/view/IBeforeChatActivityView.java | 0e218a285406814e4f05e6d239aeed50ce6bb5ab | []
| no_license | jygzdx/JiuPinHui | 8b492cca06e44060fae5a8c1ac30cb7a0c43eddd | d00b4b2c0f63d44720366c9ddfccb0a9d6230129 | refs/heads/master | 2021-01-19T14:25:20.578580 | 2017-09-14T09:51:52 | 2017-09-14T09:51:52 | 88,161,610 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 718 | java | package com.jiupin.jiupinhui.view;
import com.jiupin.jiupinhui.entity.ChatEntity;
import java.util.List;
/**
* 作者:czb on 2017/6/28 11:38
*/
public interface IBeforeChatActivityView {
/**
* 设置聊天信息
*
* @param chatList 聊天信息
* @param hint 提示信息
*/
void setChatList(List<ChatEntity> chatList, String hint);
/**
* 继续提问,成功返回
*
* @param chatList 聊天信息
* @param hint 提示信息
*/
void sendChatSuccess(List<ChatEntity> chatList, String hint);
/**
* 关闭提问
*
* @param chatList 聊天信息
*
*/
void closeChatSuccess(List<ChatEntity> chatList);
}
| [
"[email protected]"
]
| |
39904c900ef4453a1d7b131866162ca13a4e87fa | 855d2333b6384ff94ac7296f2109c82debba77c0 | /src/test/java/sandkev/differencer/DiffMatchPatchTest.java | 8731db674792e05ab67aa4364cb589ee235ed8fc | []
| no_license | kizwid/differencer | 4809769f28b0ade1770c1d2cd918f7df824f0c64 | 7ecdf53d4b67f1d68b857166696605c0cd401c00 | refs/heads/master | 2022-04-12T05:34:12.272250 | 2019-12-08T20:05:30 | 2019-12-08T20:05:30 | 113,684,866 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 51,317 | java | package sandkev.differencer;
import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static sandkev.differencer.DiffMatchPatch.Diff;
import static sandkev.differencer.DiffMatchPatch.LinesToCharsResult;
import static sandkev.differencer.DiffMatchPatch.Operation;
import static sandkev.differencer.DiffMatchPatch.Patch;
/*
* Test harness for DiffMatchPatch.java
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* 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 name.fraser.neil.plaintext;
//public class DiffMatchPatch_test extends TestCase {
public class DiffMatchPatchTest extends TestCase {
private DiffMatchPatch dmp;
private Operation DELETE = Operation.DELETE;
private Operation EQUAL = Operation.EQUAL;
private Operation INSERT = Operation.INSERT;
protected void setUp() {
// Create an instance of the DiffMatchPatch object.
dmp = new DiffMatchPatch();
}
// DIFF TEST FUNCTIONS
public void testDiffCommonPrefix() {
// Detect any common prefix.
assertEquals("diff_commonPrefix: Null case.", 0, dmp.diff_commonPrefix("abc", "xyz"));
assertEquals("diff_commonPrefix: Non-null case.", 4, dmp.diff_commonPrefix("1234abcdef", "1234xyz"));
assertEquals("diff_commonPrefix: Whole case.", 4, dmp.diff_commonPrefix("1234", "1234xyz"));
}
public void testDiffCommonSuffix() {
// Detect any common suffix.
assertEquals("diff_commonSuffix: Null case.", 0, dmp.diff_commonSuffix("abc", "xyz"));
assertEquals("diff_commonSuffix: Non-null case.", 4, dmp.diff_commonSuffix("abcdef1234", "xyz1234"));
assertEquals("diff_commonSuffix: Whole case.", 4, dmp.diff_commonSuffix("1234", "xyz1234"));
}
public void testDiffCommonOverlap() {
// Detect any suffix/prefix overlap.
assertEquals("diff_commonOverlap: Null case.", 0, dmp.diff_commonOverlap("", "abcd"));
assertEquals("diff_commonOverlap: Whole case.", 3, dmp.diff_commonOverlap("abc", "abcd"));
assertEquals("diff_commonOverlap: No overlap.", 0, dmp.diff_commonOverlap("123456", "abcd"));
assertEquals("diff_commonOverlap: Overlap.", 3, dmp.diff_commonOverlap("123456xxx", "xxxabcd"));
// Some overly clever languages (C#) may treat ligatures as equal to their
// component letters. E.g. U+FB01 == 'fi'
assertEquals("diff_commonOverlap: Unicode.", 0, dmp.diff_commonOverlap("fi", "\ufb01i"));
}
public void testDiffHalfmatch() {
// Detect a halfmatch.
dmp.Diff_Timeout = 1;
assertNull("diff_halfMatch: No match #1.", dmp.diff_halfMatch("1234567890", "abcdef"));
assertNull("diff_halfMatch: No match #2.", dmp.diff_halfMatch("12345", "23"));
assertArrayEquals("diff_halfMatch: Single Match #1.", new String[]{"12", "90", "a", "z", "345678"}, dmp.diff_halfMatch("1234567890", "a345678z"));
assertArrayEquals("diff_halfMatch: Single Match #2.", new String[]{"a", "z", "12", "90", "345678"}, dmp.diff_halfMatch("a345678z", "1234567890"));
assertArrayEquals("diff_halfMatch: Single Match #3.", new String[]{"abc", "z", "1234", "0", "56789"}, dmp.diff_halfMatch("abc56789z", "1234567890"));
assertArrayEquals("diff_halfMatch: Single Match #4.", new String[]{"a", "xyz", "1", "7890", "23456"}, dmp.diff_halfMatch("a23456xyz", "1234567890"));
assertArrayEquals("diff_halfMatch: Multiple Matches #1.", new String[]{"12123", "123121", "a", "z", "1234123451234"}, dmp.diff_halfMatch("121231234123451234123121", "a1234123451234z"));
assertArrayEquals("diff_halfMatch: Multiple Matches #2.", new String[]{"", "-=-=-=-=-=", "x", "", "x-=-=-=-=-=-=-="}, dmp.diff_halfMatch("x-=-=-=-=-=-=-=-=-=-=-=-=", "xx-=-=-=-=-=-=-="));
assertArrayEquals("diff_halfMatch: Multiple Matches #3.", new String[]{"-=-=-=-=-=", "", "", "y", "-=-=-=-=-=-=-=y"}, dmp.diff_halfMatch("-=-=-=-=-=-=-=-=-=-=-=-=y", "-=-=-=-=-=-=-=yy"));
// Optimal diff would be -q+x=H-i+e=lloHe+Hu=llo-Hew+y not -qHillo+x=HelloHe-w+Hulloy
assertArrayEquals("diff_halfMatch: Non-optimal halfmatch.", new String[]{"qHillo", "w", "x", "Hulloy", "HelloHe"}, dmp.diff_halfMatch("qHilloHelloHew", "xHelloHeHulloy"));
dmp.Diff_Timeout = 0;
assertNull("diff_halfMatch: Optimal no halfmatch.", dmp.diff_halfMatch("qHilloHelloHew", "xHelloHeHulloy"));
}
public void testDiffLinesToChars() {
// Convert lines down to characters.
ArrayList<String> tmpVector = new ArrayList<String>();
tmpVector.add("");
tmpVector.add("alpha\n");
tmpVector.add("beta\n");
assertLinesToCharsResultEquals("diff_linesToChars: Shared lines.", new LinesToCharsResult("\u0001\u0002\u0001", "\u0002\u0001\u0002", tmpVector), dmp.diff_linesToChars("alpha\nbeta\nalpha\n", "beta\nalpha\nbeta\n"));
tmpVector.clear();
tmpVector.add("");
tmpVector.add("alpha\r\n");
tmpVector.add("beta\r\n");
tmpVector.add("\r\n");
assertLinesToCharsResultEquals("diff_linesToChars: Empty string and blank lines.", new LinesToCharsResult("", "\u0001\u0002\u0003\u0003", tmpVector), dmp.diff_linesToChars("", "alpha\r\nbeta\r\n\r\n\r\n"));
tmpVector.clear();
tmpVector.add("");
tmpVector.add("a");
tmpVector.add("b");
assertLinesToCharsResultEquals("diff_linesToChars: No linebreaks.", new LinesToCharsResult("\u0001", "\u0002", tmpVector), dmp.diff_linesToChars("a", "b"));
// More than 256 to reveal any 8-bit limitations.
int n = 300;
tmpVector.clear();
StringBuilder lineList = new StringBuilder();
StringBuilder charList = new StringBuilder();
for (int x = 1; x < n + 1; x++) {
tmpVector.add(x + "\n");
lineList.append(x + "\n");
charList.append(String.valueOf((char) x));
}
assertEquals(n, tmpVector.size());
String lines = lineList.toString();
String chars = charList.toString();
assertEquals(n, chars.length());
tmpVector.add(0, "");
assertLinesToCharsResultEquals("diff_linesToChars: More than 256.", new LinesToCharsResult(chars, "", tmpVector), dmp.diff_linesToChars(lines, ""));
}
public void testDiffCharsToLines() {
// First check that Diff equality works.
assertTrue("diff_charsToLines: Equality #1.", new Diff(EQUAL, "a").equals(new Diff(EQUAL, "a")));
assertEquals("diff_charsToLines: Equality #2.", new Diff(EQUAL, "a"), new Diff(EQUAL, "a"));
// Convert chars up to lines.
LinkedList<Diff> diffs = diffList(new Diff(EQUAL, "\u0001\u0002\u0001"), new Diff(INSERT, "\u0002\u0001\u0002"));
ArrayList<String> tmpVector = new ArrayList<String>();
tmpVector.add("");
tmpVector.add("alpha\n");
tmpVector.add("beta\n");
dmp.diff_charsToLines(diffs, tmpVector);
assertEquals("diff_charsToLines: Shared lines.", diffList(new Diff(EQUAL, "alpha\nbeta\nalpha\n"), new Diff(INSERT, "beta\nalpha\nbeta\n")), diffs);
// More than 256 to reveal any 8-bit limitations.
int n = 300;
tmpVector.clear();
StringBuilder lineList = new StringBuilder();
StringBuilder charList = new StringBuilder();
for (int x = 1; x < n + 1; x++) {
tmpVector.add(x + "\n");
lineList.append(x + "\n");
charList.append(String.valueOf((char) x));
}
assertEquals(n, tmpVector.size());
String lines = lineList.toString();
String chars = charList.toString();
assertEquals(n, chars.length());
tmpVector.add(0, "");
diffs = diffList(new Diff(DELETE, chars));
dmp.diff_charsToLines(diffs, tmpVector);
assertEquals("diff_charsToLines: More than 256.", diffList(new Diff(DELETE, lines)), diffs);
}
public void testDiffCleanupMerge() {
// Cleanup a messy diff.
LinkedList<Diff> diffs = diffList();
dmp.diff_cleanupMerge(diffs);
assertEquals("diff_cleanupMerge: Null case.", diffList(), diffs);
diffs = diffList(new Diff(EQUAL, "a"), new Diff(DELETE, "b"), new Diff(INSERT, "c"));
dmp.diff_cleanupMerge(diffs);
assertEquals("diff_cleanupMerge: No change case.", diffList(new Diff(EQUAL, "a"), new Diff(DELETE, "b"), new Diff(INSERT, "c")), diffs);
diffs = diffList(new Diff(EQUAL, "a"), new Diff(EQUAL, "b"), new Diff(EQUAL, "c"));
dmp.diff_cleanupMerge(diffs);
assertEquals("diff_cleanupMerge: Merge equalities.", diffList(new Diff(EQUAL, "abc")), diffs);
diffs = diffList(new Diff(DELETE, "a"), new Diff(DELETE, "b"), new Diff(DELETE, "c"));
dmp.diff_cleanupMerge(diffs);
assertEquals("diff_cleanupMerge: Merge deletions.", diffList(new Diff(DELETE, "abc")), diffs);
diffs = diffList(new Diff(INSERT, "a"), new Diff(INSERT, "b"), new Diff(INSERT, "c"));
dmp.diff_cleanupMerge(diffs);
assertEquals("diff_cleanupMerge: Merge insertions.", diffList(new Diff(INSERT, "abc")), diffs);
diffs = diffList(new Diff(DELETE, "a"), new Diff(INSERT, "b"), new Diff(DELETE, "c"), new Diff(INSERT, "d"), new Diff(EQUAL, "e"), new Diff(EQUAL, "f"));
dmp.diff_cleanupMerge(diffs);
assertEquals("diff_cleanupMerge: Merge interweave.", diffList(new Diff(DELETE, "ac"), new Diff(INSERT, "bd"), new Diff(EQUAL, "ef")), diffs);
diffs = diffList(new Diff(DELETE, "a"), new Diff(INSERT, "abc"), new Diff(DELETE, "dc"));
dmp.diff_cleanupMerge(diffs);
assertEquals("diff_cleanupMerge: Prefix and suffix detection.", diffList(new Diff(EQUAL, "a"), new Diff(DELETE, "d"), new Diff(INSERT, "b"), new Diff(EQUAL, "c")), diffs);
diffs = diffList(new Diff(EQUAL, "x"), new Diff(DELETE, "a"), new Diff(INSERT, "abc"), new Diff(DELETE, "dc"), new Diff(EQUAL, "y"));
dmp.diff_cleanupMerge(diffs);
assertEquals("diff_cleanupMerge: Prefix and suffix detection with equalities.", diffList(new Diff(EQUAL, "xa"), new Diff(DELETE, "d"), new Diff(INSERT, "b"), new Diff(EQUAL, "cy")), diffs);
diffs = diffList(new Diff(EQUAL, "a"), new Diff(INSERT, "ba"), new Diff(EQUAL, "c"));
dmp.diff_cleanupMerge(diffs);
assertEquals("diff_cleanupMerge: Slide edit left.", diffList(new Diff(INSERT, "ab"), new Diff(EQUAL, "ac")), diffs);
diffs = diffList(new Diff(EQUAL, "c"), new Diff(INSERT, "ab"), new Diff(EQUAL, "a"));
dmp.diff_cleanupMerge(diffs);
assertEquals("diff_cleanupMerge: Slide edit right.", diffList(new Diff(EQUAL, "ca"), new Diff(INSERT, "ba")), diffs);
diffs = diffList(new Diff(EQUAL, "a"), new Diff(DELETE, "b"), new Diff(EQUAL, "c"), new Diff(DELETE, "ac"), new Diff(EQUAL, "x"));
dmp.diff_cleanupMerge(diffs);
assertEquals("diff_cleanupMerge: Slide edit left recursive.", diffList(new Diff(DELETE, "abc"), new Diff(EQUAL, "acx")), diffs);
diffs = diffList(new Diff(EQUAL, "x"), new Diff(DELETE, "ca"), new Diff(EQUAL, "c"), new Diff(DELETE, "b"), new Diff(EQUAL, "a"));
dmp.diff_cleanupMerge(diffs);
assertEquals("diff_cleanupMerge: Slide edit right recursive.", diffList(new Diff(EQUAL, "xca"), new Diff(DELETE, "cba")), diffs);
}
public void testDiffCleanupSemanticLossless() {
// Slide diffs to match logical boundaries.
LinkedList<Diff> diffs = diffList();
dmp.diff_cleanupSemanticLossless(diffs);
assertEquals("diff_cleanupSemanticLossless: Null case.", diffList(), diffs);
diffs = diffList(new Diff(EQUAL, "AAA\r\n\r\nBBB"), new Diff(INSERT, "\r\nDDD\r\n\r\nBBB"), new Diff(EQUAL, "\r\nEEE"));
dmp.diff_cleanupSemanticLossless(diffs);
assertEquals("diff_cleanupSemanticLossless: Blank lines.", diffList(new Diff(EQUAL, "AAA\r\n\r\n"), new Diff(INSERT, "BBB\r\nDDD\r\n\r\n"), new Diff(EQUAL, "BBB\r\nEEE")), diffs);
diffs = diffList(new Diff(EQUAL, "AAA\r\nBBB"), new Diff(INSERT, " DDD\r\nBBB"), new Diff(EQUAL, " EEE"));
dmp.diff_cleanupSemanticLossless(diffs);
assertEquals("diff_cleanupSemanticLossless: Line boundaries.", diffList(new Diff(EQUAL, "AAA\r\n"), new Diff(INSERT, "BBB DDD\r\n"), new Diff(EQUAL, "BBB EEE")), diffs);
diffs = diffList(new Diff(EQUAL, "The c"), new Diff(INSERT, "ow and the c"), new Diff(EQUAL, "at."));
dmp.diff_cleanupSemanticLossless(diffs);
assertEquals("diff_cleanupSemanticLossless: Word boundaries.", diffList(new Diff(EQUAL, "The "), new Diff(INSERT, "cow and the "), new Diff(EQUAL, "cat.")), diffs);
diffs = diffList(new Diff(EQUAL, "The-c"), new Diff(INSERT, "ow-and-the-c"), new Diff(EQUAL, "at."));
dmp.diff_cleanupSemanticLossless(diffs);
assertEquals("diff_cleanupSemanticLossless: Alphanumeric boundaries.", diffList(new Diff(EQUAL, "The-"), new Diff(INSERT, "cow-and-the-"), new Diff(EQUAL, "cat.")), diffs);
diffs = diffList(new Diff(EQUAL, "a"), new Diff(DELETE, "a"), new Diff(EQUAL, "ax"));
dmp.diff_cleanupSemanticLossless(diffs);
assertEquals("diff_cleanupSemanticLossless: Hitting the start.", diffList(new Diff(DELETE, "a"), new Diff(EQUAL, "aax")), diffs);
diffs = diffList(new Diff(EQUAL, "xa"), new Diff(DELETE, "a"), new Diff(EQUAL, "a"));
dmp.diff_cleanupSemanticLossless(diffs);
assertEquals("diff_cleanupSemanticLossless: Hitting the end.", diffList(new Diff(EQUAL, "xaa"), new Diff(DELETE, "a")), diffs);
diffs = diffList(new Diff(EQUAL, "The xxx. The "), new Diff(INSERT, "zzz. The "), new Diff(EQUAL, "yyy."));
dmp.diff_cleanupSemanticLossless(diffs);
assertEquals("diff_cleanupSemanticLossless: Sentence boundaries.", diffList(new Diff(EQUAL, "The xxx."), new Diff(INSERT, " The zzz."), new Diff(EQUAL, " The yyy.")), diffs);
}
public void testDiffCleanupSemantic() {
// Cleanup semantically trivial equalities.
LinkedList<Diff> diffs = diffList();
dmp.diff_cleanupSemantic(diffs);
assertEquals("diff_cleanupSemantic: Null case.", diffList(), diffs);
diffs = diffList(new Diff(DELETE, "ab"), new Diff(INSERT, "cd"), new Diff(EQUAL, "12"), new Diff(DELETE, "e"));
dmp.diff_cleanupSemantic(diffs);
assertEquals("diff_cleanupSemantic: No elimination #1.", diffList(new Diff(DELETE, "ab"), new Diff(INSERT, "cd"), new Diff(EQUAL, "12"), new Diff(DELETE, "e")), diffs);
diffs = diffList(new Diff(DELETE, "abc"), new Diff(INSERT, "ABC"), new Diff(EQUAL, "1234"), new Diff(DELETE, "wxyz"));
dmp.diff_cleanupSemantic(diffs);
assertEquals("diff_cleanupSemantic: No elimination #2.", diffList(new Diff(DELETE, "abc"), new Diff(INSERT, "ABC"), new Diff(EQUAL, "1234"), new Diff(DELETE, "wxyz")), diffs);
diffs = diffList(new Diff(DELETE, "a"), new Diff(EQUAL, "b"), new Diff(DELETE, "c"));
dmp.diff_cleanupSemantic(diffs);
assertEquals("diff_cleanupSemantic: Simple elimination.", diffList(new Diff(DELETE, "abc"), new Diff(INSERT, "b")), diffs);
diffs = diffList(new Diff(DELETE, "ab"), new Diff(EQUAL, "cd"), new Diff(DELETE, "e"), new Diff(EQUAL, "f"), new Diff(INSERT, "g"));
dmp.diff_cleanupSemantic(diffs);
assertEquals("diff_cleanupSemantic: Backpass elimination.", diffList(new Diff(DELETE, "abcdef"), new Diff(INSERT, "cdfg")), diffs);
diffs = diffList(new Diff(INSERT, "1"), new Diff(EQUAL, "A"), new Diff(DELETE, "B"), new Diff(INSERT, "2"), new Diff(EQUAL, "_"), new Diff(INSERT, "1"), new Diff(EQUAL, "A"), new Diff(DELETE, "B"), new Diff(INSERT, "2"));
dmp.diff_cleanupSemantic(diffs);
assertEquals("diff_cleanupSemantic: Multiple elimination.", diffList(new Diff(DELETE, "AB_AB"), new Diff(INSERT, "1A2_1A2")), diffs);
diffs = diffList(new Diff(EQUAL, "The c"), new Diff(DELETE, "ow and the c"), new Diff(EQUAL, "at."));
dmp.diff_cleanupSemantic(diffs);
assertEquals("diff_cleanupSemantic: Word boundaries.", diffList(new Diff(EQUAL, "The "), new Diff(DELETE, "cow and the "), new Diff(EQUAL, "cat.")), diffs);
diffs = diffList(new Diff(DELETE, "abcxx"), new Diff(INSERT, "xxdef"));
dmp.diff_cleanupSemantic(diffs);
assertEquals("diff_cleanupSemantic: No overlap elimination.", diffList(new Diff(DELETE, "abcxx"), new Diff(INSERT, "xxdef")), diffs);
diffs = diffList(new Diff(DELETE, "abcxxx"), new Diff(INSERT, "xxxdef"));
dmp.diff_cleanupSemantic(diffs);
assertEquals("diff_cleanupSemantic: Overlap elimination.", diffList(new Diff(DELETE, "abc"), new Diff(EQUAL, "xxx"), new Diff(INSERT, "def")), diffs);
diffs = diffList(new Diff(DELETE, "xxxabc"), new Diff(INSERT, "defxxx"));
dmp.diff_cleanupSemantic(diffs);
assertEquals("diff_cleanupSemantic: Reverse overlap elimination.", diffList(new Diff(INSERT, "def"), new Diff(EQUAL, "xxx"), new Diff(DELETE, "abc")), diffs);
diffs = diffList(new Diff(DELETE, "abcd1212"), new Diff(INSERT, "1212efghi"), new Diff(EQUAL, "----"), new Diff(DELETE, "A3"), new Diff(INSERT, "3BC"));
dmp.diff_cleanupSemantic(diffs);
assertEquals("diff_cleanupSemantic: Two overlap eliminations.", diffList(new Diff(DELETE, "abcd"), new Diff(EQUAL, "1212"), new Diff(INSERT, "efghi"), new Diff(EQUAL, "----"), new Diff(DELETE, "A"), new Diff(EQUAL, "3"), new Diff(INSERT, "BC")), diffs);
}
public void testDiffCleanupEfficiency() {
// Cleanup operationally trivial equalities.
dmp.Diff_EditCost = 4;
LinkedList<Diff> diffs = diffList();
dmp.diff_cleanupEfficiency(diffs);
assertEquals("diff_cleanupEfficiency: Null case.", diffList(), diffs);
diffs = diffList(new Diff(DELETE, "ab"), new Diff(INSERT, "12"), new Diff(EQUAL, "wxyz"), new Diff(DELETE, "cd"), new Diff(INSERT, "34"));
dmp.diff_cleanupEfficiency(diffs);
assertEquals("diff_cleanupEfficiency: No elimination.", diffList(new Diff(DELETE, "ab"), new Diff(INSERT, "12"), new Diff(EQUAL, "wxyz"), new Diff(DELETE, "cd"), new Diff(INSERT, "34")), diffs);
diffs = diffList(new Diff(DELETE, "ab"), new Diff(INSERT, "12"), new Diff(EQUAL, "xyz"), new Diff(DELETE, "cd"), new Diff(INSERT, "34"));
dmp.diff_cleanupEfficiency(diffs);
assertEquals("diff_cleanupEfficiency: Four-edit elimination.", diffList(new Diff(DELETE, "abxyzcd"), new Diff(INSERT, "12xyz34")), diffs);
diffs = diffList(new Diff(INSERT, "12"), new Diff(EQUAL, "x"), new Diff(DELETE, "cd"), new Diff(INSERT, "34"));
dmp.diff_cleanupEfficiency(diffs);
assertEquals("diff_cleanupEfficiency: Three-edit elimination.", diffList(new Diff(DELETE, "xcd"), new Diff(INSERT, "12x34")), diffs);
diffs = diffList(new Diff(DELETE, "ab"), new Diff(INSERT, "12"), new Diff(EQUAL, "xy"), new Diff(INSERT, "34"), new Diff(EQUAL, "z"), new Diff(DELETE, "cd"), new Diff(INSERT, "56"));
dmp.diff_cleanupEfficiency(diffs);
assertEquals("diff_cleanupEfficiency: Backpass elimination.", diffList(new Diff(DELETE, "abxyzcd"), new Diff(INSERT, "12xy34z56")), diffs);
dmp.Diff_EditCost = 5;
diffs = diffList(new Diff(DELETE, "ab"), new Diff(INSERT, "12"), new Diff(EQUAL, "wxyz"), new Diff(DELETE, "cd"), new Diff(INSERT, "34"));
dmp.diff_cleanupEfficiency(diffs);
assertEquals("diff_cleanupEfficiency: High cost elimination.", diffList(new Diff(DELETE, "abwxyzcd"), new Diff(INSERT, "12wxyz34")), diffs);
dmp.Diff_EditCost = 4;
}
public void testDiffPrettyHtml() {
// Pretty print.
LinkedList<Diff> diffs = diffList(new Diff(EQUAL, "a\n"), new Diff(DELETE, "<B>b</B>"), new Diff(INSERT, "c&d"));
assertEquals("diff_prettyHtml:", "<span>a¶<br></span><del style=\"background:#ffe6e6;\"><B>b</B></del><ins style=\"background:#e6ffe6;\">c&d</ins>", dmp.diff_prettyHtml(diffs));
}
public void testDiffText() {
// Compute the source and destination texts.
LinkedList<Diff> diffs = diffList(new Diff(EQUAL, "jump"), new Diff(DELETE, "s"), new Diff(INSERT, "ed"), new Diff(EQUAL, " over "), new Diff(DELETE, "the"), new Diff(INSERT, "a"), new Diff(EQUAL, " lazy"));
assertEquals("diff_text1:", "jumps over the lazy", dmp.diff_text1(diffs));
assertEquals("diff_text2:", "jumped over a lazy", dmp.diff_text2(diffs));
}
public void testDiffDelta() {
// Convert a diff into delta string.
LinkedList<Diff> diffs = diffList(new Diff(EQUAL, "jump"), new Diff(DELETE, "s"), new Diff(INSERT, "ed"), new Diff(EQUAL, " over "), new Diff(DELETE, "the"), new Diff(INSERT, "a"), new Diff(EQUAL, " lazy"), new Diff(INSERT, "old dog"));
String text1 = dmp.diff_text1(diffs);
assertEquals("diff_text1: Base text.", "jumps over the lazy", text1);
String delta = dmp.diff_toDelta(diffs);
assertEquals("diff_toDelta:", "=4\t-1\t+ed\t=6\t-3\t+a\t=5\t+old dog", delta);
// Convert delta string into a diff.
assertEquals("diff_fromDelta: Normal.", diffs, dmp.diff_fromDelta(text1, delta));
// Generates error (19 < 20).
try {
dmp.diff_fromDelta(text1 + "x", delta);
fail("diff_fromDelta: Too long.");
} catch (IllegalArgumentException ex) {
// Exception expected.
}
// Generates error (19 > 18).
try {
dmp.diff_fromDelta(text1.substring(1), delta);
fail("diff_fromDelta: Too short.");
} catch (IllegalArgumentException ex) {
// Exception expected.
}
// Generates error (%c3%xy invalid Unicode).
try {
dmp.diff_fromDelta("", "+%c3%xy");
fail("diff_fromDelta: Invalid character.");
} catch (IllegalArgumentException ex) {
// Exception expected.
}
// Test deltas with special characters.
diffs = diffList(new Diff(EQUAL, "\u0680 \000 \t %"), new Diff(DELETE, "\u0681 \001 \n ^"), new Diff(INSERT, "\u0682 \002 \\ |"));
text1 = dmp.diff_text1(diffs);
assertEquals("diff_text1: Unicode text.", "\u0680 \000 \t %\u0681 \001 \n ^", text1);
delta = dmp.diff_toDelta(diffs);
assertEquals("diff_toDelta: Unicode.", "=7\t-7\t+%DA%82 %02 %5C %7C", delta);
assertEquals("diff_fromDelta: Unicode.", diffs, dmp.diff_fromDelta(text1, delta));
// Verify pool of unchanged characters.
diffs = diffList(new Diff(INSERT, "A-Z a-z 0-9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , # "));
String text2 = dmp.diff_text2(diffs);
assertEquals("diff_text2: Unchanged characters.", "A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? : @ & = + $ , # ", text2);
delta = dmp.diff_toDelta(diffs);
assertEquals("diff_toDelta: Unchanged characters.", "+A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? : @ & = + $ , # ", delta);
// Convert delta string into a diff.
assertEquals("diff_fromDelta: Unchanged characters.", diffs, dmp.diff_fromDelta("", delta));
}
public void testDiffXIndex() {
// Translate a location in text1 to text2.
LinkedList<Diff> diffs = diffList(new Diff(DELETE, "a"), new Diff(INSERT, "1234"), new Diff(EQUAL, "xyz"));
assertEquals("diff_xIndex: Translation on equality.", 5, dmp.diff_xIndex(diffs, 2));
diffs = diffList(new Diff(EQUAL, "a"), new Diff(DELETE, "1234"), new Diff(EQUAL, "xyz"));
assertEquals("diff_xIndex: Translation on deletion.", 1, dmp.diff_xIndex(diffs, 3));
}
public void testDiffLevenshtein() {
LinkedList<Diff> diffs = diffList(new Diff(DELETE, "abc"), new Diff(INSERT, "1234"), new Diff(EQUAL, "xyz"));
assertEquals("Levenshtein with trailing equality.", 4, dmp.diff_levenshtein(diffs));
diffs = diffList(new Diff(EQUAL, "xyz"), new Diff(DELETE, "abc"), new Diff(INSERT, "1234"));
assertEquals("Levenshtein with leading equality.", 4, dmp.diff_levenshtein(diffs));
diffs = diffList(new Diff(DELETE, "abc"), new Diff(EQUAL, "xyz"), new Diff(INSERT, "1234"));
assertEquals("Levenshtein with middle equality.", 7, dmp.diff_levenshtein(diffs));
}
public void testDiffBisect() {
// Normal.
String a = "cat";
String b = "map";
// Since the resulting diff hasn't been normalized, it would be ok if
// the insertion and deletion pairs are swapped.
// If the order changes, tweak this test as required.
LinkedList<Diff> diffs = diffList(new Diff(DELETE, "c"), new Diff(INSERT, "m"), new Diff(EQUAL, "a"), new Diff(DELETE, "t"), new Diff(INSERT, "p"));
assertEquals("diff_bisect: Normal.", diffs, dmp.diff_bisect(a, b, Long.MAX_VALUE));
// Timeout.
diffs = diffList(new Diff(DELETE, "cat"), new Diff(INSERT, "map"));
assertEquals("diff_bisect: Timeout.", diffs, dmp.diff_bisect(a, b, 0));
}
public void testDiffMain() {
// Perform a trivial diff.
LinkedList<Diff> diffs = diffList();
assertEquals("diff_main: Null case.", diffs, dmp.diff_main("", "", false));
diffs = diffList(new Diff(EQUAL, "abc"));
assertEquals("diff_main: Equality.", diffs, dmp.diff_main("abc", "abc", false));
diffs = diffList(new Diff(EQUAL, "ab"), new Diff(INSERT, "123"), new Diff(EQUAL, "c"));
assertEquals("diff_main: Simple insertion.", diffs, dmp.diff_main("abc", "ab123c", false));
diffs = diffList(new Diff(EQUAL, "a"), new Diff(DELETE, "123"), new Diff(EQUAL, "bc"));
assertEquals("diff_main: Simple deletion.", diffs, dmp.diff_main("a123bc", "abc", false));
diffs = diffList(new Diff(EQUAL, "a"), new Diff(INSERT, "123"), new Diff(EQUAL, "b"), new Diff(INSERT, "456"), new Diff(EQUAL, "c"));
assertEquals("diff_main: Two insertions.", diffs, dmp.diff_main("abc", "a123b456c", false));
diffs = diffList(new Diff(EQUAL, "a"), new Diff(DELETE, "123"), new Diff(EQUAL, "b"), new Diff(DELETE, "456"), new Diff(EQUAL, "c"));
assertEquals("diff_main: Two deletions.", diffs, dmp.diff_main("a123b456c", "abc", false));
// Perform a real diff.
// Switch off the timeout.
dmp.Diff_Timeout = 0;
diffs = diffList(new Diff(DELETE, "a"), new Diff(INSERT, "b"));
assertEquals("diff_main: Simple case #1.", diffs, dmp.diff_main("a", "b", false));
diffs = diffList(new Diff(DELETE, "Apple"), new Diff(INSERT, "Banana"), new Diff(EQUAL, "s are a"), new Diff(INSERT, "lso"), new Diff(EQUAL, " fruit."));
assertEquals("diff_main: Simple case #2.", diffs, dmp.diff_main("Apples are a fruit.", "Bananas are also fruit.", false));
diffs = diffList(new Diff(DELETE, "a"), new Diff(INSERT, "\u0680"), new Diff(EQUAL, "x"), new Diff(DELETE, "\t"), new Diff(INSERT, "\000"));
assertEquals("diff_main: Simple case #3.", diffs, dmp.diff_main("ax\t", "\u0680x\000", false));
diffs = diffList(new Diff(DELETE, "1"), new Diff(EQUAL, "a"), new Diff(DELETE, "y"), new Diff(EQUAL, "b"), new Diff(DELETE, "2"), new Diff(INSERT, "xab"));
assertEquals("diff_main: Overlap #1.", diffs, dmp.diff_main("1ayb2", "abxab", false));
diffs = diffList(new Diff(INSERT, "xaxcx"), new Diff(EQUAL, "abc"), new Diff(DELETE, "y"));
assertEquals("diff_main: Overlap #2.", diffs, dmp.diff_main("abcy", "xaxcxabc", false));
diffs = diffList(new Diff(DELETE, "ABCD"), new Diff(EQUAL, "a"), new Diff(DELETE, "="), new Diff(INSERT, "-"), new Diff(EQUAL, "bcd"), new Diff(DELETE, "="), new Diff(INSERT, "-"), new Diff(EQUAL, "efghijklmnopqrs"), new Diff(DELETE, "EFGHIJKLMNOefg"));
assertEquals("diff_main: Overlap #3.", diffs, dmp.diff_main("ABCDa=bcd=efghijklmnopqrsEFGHIJKLMNOefg", "a-bcd-efghijklmnopqrs", false));
diffs = diffList(new Diff(INSERT, " "), new Diff(EQUAL, "a"), new Diff(INSERT, "nd"), new Diff(EQUAL, " [[Pennsylvania]]"), new Diff(DELETE, " and [[New"));
assertEquals("diff_main: Large equality.", diffs, dmp.diff_main("a [[Pennsylvania]] and [[New", " and [[Pennsylvania]]", false));
dmp.Diff_Timeout = 0.1f; // 100ms
String a = "`Twas brillig, and the slithy toves\nDid gyre and gimble in the wabe:\nAll mimsy were the borogoves,\nAnd the mome raths outgrabe.\n";
String b = "I am the very model of a modern major general,\nI've information vegetable, animal, and mineral,\nI know the kings of England, and I quote the fights historical,\nFrom Marathon to Waterloo, in order categorical.\n";
// Increase the text lengths by 1024 times to ensure a timeout.
for (int x = 0; x < 10; x++) {
a = a + a;
b = b + b;
}
long startTime = System.currentTimeMillis();
dmp.diff_main(a, b);
long endTime = System.currentTimeMillis();
// Test that we took at least the timeout period.
assertTrue("diff_main: Timeout min.", dmp.Diff_Timeout * 1000 <= endTime - startTime);
// Test that we didn't take forever (be forgiving).
// Theoretically this test could fail very occasionally if the
// OS task swaps or locks up for a second at the wrong moment.
assertTrue("diff_main: Timeout max.", dmp.Diff_Timeout * 1000 * 2 > endTime - startTime);
dmp.Diff_Timeout = 0;
// Test the linemode speedup.
// Must be long to pass the 100 char cutoff.
a = "1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n";
b = "abcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\n";
assertEquals("diff_main: Simple line-mode.", dmp.diff_main(a, b, true), dmp.diff_main(a, b, false));
a = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
b = "abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij";
assertEquals("diff_main: Single line-mode.", dmp.diff_main(a, b, true), dmp.diff_main(a, b, false));
a = "1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n";
b = "abcdefghij\n1234567890\n1234567890\n1234567890\nabcdefghij\n1234567890\n1234567890\n1234567890\nabcdefghij\n1234567890\n1234567890\n1234567890\nabcdefghij\n";
String[] texts_linemode = diff_rebuildtexts(dmp.diff_main(a, b, true));
String[] texts_textmode = diff_rebuildtexts(dmp.diff_main(a, b, false));
assertArrayEquals("diff_main: Overlap line-mode.", texts_textmode, texts_linemode);
// Test null inputs.
try {
dmp.diff_main(null, null);
fail("diff_main: Null inputs.");
} catch (IllegalArgumentException ex) {
// Error expected.
}
}
// MATCH TEST FUNCTIONS
public void testMatchAlphabet() {
// Initialise the bitmasks for Bitap.
Map<Character, Integer> bitmask;
bitmask = new HashMap<Character, Integer>();
bitmask.put('a', 4);
bitmask.put('b', 2);
bitmask.put('c', 1);
assertEquals("match_alphabet: Unique.", bitmask, dmp.match_alphabet("abc"));
bitmask = new HashMap<Character, Integer>();
bitmask.put('a', 37);
bitmask.put('b', 18);
bitmask.put('c', 8);
assertEquals("match_alphabet: Duplicates.", bitmask, dmp.match_alphabet("abcaba"));
}
public void testMatchBitap() {
// Bitap algorithm.
dmp.Match_Distance = 100;
dmp.Match_Threshold = 0.5f;
assertEquals("match_bitap: Exact match #1.", 5, dmp.match_bitap("abcdefghijk", "fgh", 5));
assertEquals("match_bitap: Exact match #2.", 5, dmp.match_bitap("abcdefghijk", "fgh", 0));
assertEquals("match_bitap: Fuzzy match #1.", 4, dmp.match_bitap("abcdefghijk", "efxhi", 0));
assertEquals("match_bitap: Fuzzy match #2.", 2, dmp.match_bitap("abcdefghijk", "cdefxyhijk", 5));
assertEquals("match_bitap: Fuzzy match #3.", -1, dmp.match_bitap("abcdefghijk", "bxy", 1));
assertEquals("match_bitap: Overflow.", 2, dmp.match_bitap("123456789xx0", "3456789x0", 2));
assertEquals("match_bitap: Before start match.", 0, dmp.match_bitap("abcdef", "xxabc", 4));
assertEquals("match_bitap: Beyond end match.", 3, dmp.match_bitap("abcdef", "defyy", 4));
assertEquals("match_bitap: Oversized pattern.", 0, dmp.match_bitap("abcdef", "xabcdefy", 0));
dmp.Match_Threshold = 0.4f;
assertEquals("match_bitap: Threshold #1.", 4, dmp.match_bitap("abcdefghijk", "efxyhi", 1));
dmp.Match_Threshold = 0.3f;
assertEquals("match_bitap: Threshold #2.", -1, dmp.match_bitap("abcdefghijk", "efxyhi", 1));
dmp.Match_Threshold = 0.0f;
assertEquals("match_bitap: Threshold #3.", 1, dmp.match_bitap("abcdefghijk", "bcdef", 1));
dmp.Match_Threshold = 0.5f;
assertEquals("match_bitap: Multiple select #1.", 0, dmp.match_bitap("abcdexyzabcde", "abccde", 3));
assertEquals("match_bitap: Multiple select #2.", 8, dmp.match_bitap("abcdexyzabcde", "abccde", 5));
dmp.Match_Distance = 10; // Strict location.
assertEquals("match_bitap: Distance test #1.", -1, dmp.match_bitap("abcdefghijklmnopqrstuvwxyz", "abcdefg", 24));
assertEquals("match_bitap: Distance test #2.", 0, dmp.match_bitap("abcdefghijklmnopqrstuvwxyz", "abcdxxefg", 1));
dmp.Match_Distance = 1000; // Loose location.
assertEquals("match_bitap: Distance test #3.", 0, dmp.match_bitap("abcdefghijklmnopqrstuvwxyz", "abcdefg", 24));
}
public void testMatchMain() {
// Full match.
assertEquals("match_main: Equality.", 0, dmp.match_main("abcdef", "abcdef", 1000));
assertEquals("match_main: Null text.", -1, dmp.match_main("", "abcdef", 1));
assertEquals("match_main: Null pattern.", 3, dmp.match_main("abcdef", "", 3));
assertEquals("match_main: Exact match.", 3, dmp.match_main("abcdef", "de", 3));
assertEquals("match_main: Beyond end match.", 3, dmp.match_main("abcdef", "defy", 4));
assertEquals("match_main: Oversized pattern.", 0, dmp.match_main("abcdef", "abcdefy", 0));
dmp.Match_Threshold = 0.7f;
assertEquals("match_main: Complex match.", 4, dmp.match_main("I am the very model of a modern major general.", " that berry ", 5));
dmp.Match_Threshold = 0.5f;
// Test null inputs.
try {
dmp.match_main(null, null, 0);
fail("match_main: Null inputs.");
} catch (IllegalArgumentException ex) {
// Error expected.
}
}
// PATCH TEST FUNCTIONS
public void testPatchObj() {
// Patch Object.
Patch p = new Patch();
p.start1 = 20;
p.start2 = 21;
p.length1 = 18;
p.length2 = 17;
p.diffs = diffList(new Diff(EQUAL, "jump"), new Diff(DELETE, "s"), new Diff(INSERT, "ed"), new Diff(EQUAL, " over "), new Diff(DELETE, "the"), new Diff(INSERT, "a"), new Diff(EQUAL, "\nlaz"));
String strp = "@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n";
assertEquals("Patch: toString.", strp, p.toString());
}
public void testPatchFromText() {
assertTrue("patch_fromText: #0.", dmp.patch_fromText("").isEmpty());
String strp = "@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n";
assertEquals("patch_fromText: #1.", strp, dmp.patch_fromText(strp).get(0).toString());
assertEquals("patch_fromText: #2.", "@@ -1 +1 @@\n-a\n+b\n", dmp.patch_fromText("@@ -1 +1 @@\n-a\n+b\n").get(0).toString());
assertEquals("patch_fromText: #3.", "@@ -1,3 +0,0 @@\n-abc\n", dmp.patch_fromText("@@ -1,3 +0,0 @@\n-abc\n").get(0).toString());
assertEquals("patch_fromText: #4.", "@@ -0,0 +1,3 @@\n+abc\n", dmp.patch_fromText("@@ -0,0 +1,3 @@\n+abc\n").get(0).toString());
// Generates error.
try {
dmp.patch_fromText("Bad\nPatch\n");
fail("patch_fromText: #5.");
} catch (IllegalArgumentException ex) {
// Exception expected.
}
}
public void testPatchToText() {
String strp = "@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n";
List<Patch> patches;
patches = dmp.patch_fromText(strp);
assertEquals("patch_toText: Single.", strp, dmp.patch_toText(patches));
strp = "@@ -1,9 +1,9 @@\n-f\n+F\n oo+fooba\n@@ -7,9 +7,9 @@\n obar\n-,\n+.\n tes\n";
patches = dmp.patch_fromText(strp);
assertEquals("patch_toText: Dual.", strp, dmp.patch_toText(patches));
}
public void testPatchAddContext() {
dmp.Patch_Margin = 4;
Patch p;
p = dmp.patch_fromText("@@ -21,4 +21,10 @@\n-jump\n+somersault\n").get(0);
dmp.patch_addContext(p, "The quick brown fox jumps over the lazy dog.");
assertEquals("patch_addContext: Simple case.", "@@ -17,12 +17,18 @@\n fox \n-jump\n+somersault\n s ov\n", p.toString());
p = dmp.patch_fromText("@@ -21,4 +21,10 @@\n-jump\n+somersault\n").get(0);
dmp.patch_addContext(p, "The quick brown fox jumps.");
assertEquals("patch_addContext: Not enough trailing context.", "@@ -17,10 +17,16 @@\n fox \n-jump\n+somersault\n s.\n", p.toString());
p = dmp.patch_fromText("@@ -3 +3,2 @@\n-e\n+at\n").get(0);
dmp.patch_addContext(p, "The quick brown fox jumps.");
assertEquals("patch_addContext: Not enough leading context.", "@@ -1,7 +1,8 @@\n Th\n-e\n+at\n qui\n", p.toString());
p = dmp.patch_fromText("@@ -3 +3,2 @@\n-e\n+at\n").get(0);
dmp.patch_addContext(p, "The quick brown fox jumps. The quick brown fox crashes.");
assertEquals("patch_addContext: Ambiguity.", "@@ -1,27 +1,28 @@\n Th\n-e\n+at\n quick brown fox jumps. \n", p.toString());
}
@SuppressWarnings("deprecation")
public void testPatchMake() {
LinkedList<Patch> patches;
patches = dmp.patch_make("", "");
assertEquals("patch_make: Null case.", "", dmp.patch_toText(patches));
String text1 = "The quick brown fox jumps over the lazy dog.";
String text2 = "That quick brown fox jumped over a lazy dog.";
String expectedPatch = "@@ -1,8 +1,7 @@\n Th\n-at\n+e\n qui\n@@ -21,17 +21,18 @@\n jump\n-ed\n+s\n over \n-a\n+the\n laz\n";
// The second patch must be "-21,17 +21,18", not "-22,17 +21,18" due to rolling context.
patches = dmp.patch_make(text2, text1);
assertEquals("patch_make: Text2+Text1 inputs.", expectedPatch, dmp.patch_toText(patches));
expectedPatch = "@@ -1,11 +1,12 @@\n Th\n-e\n+at\n quick b\n@@ -22,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n";
patches = dmp.patch_make(text1, text2);
assertEquals("patch_make: Text1+Text2 inputs.", expectedPatch, dmp.patch_toText(patches));
LinkedList<Diff> diffs = dmp.diff_main(text1, text2, false);
patches = dmp.patch_make(diffs);
assertEquals("patch_make: Diff input.", expectedPatch, dmp.patch_toText(patches));
patches = dmp.patch_make(text1, diffs);
assertEquals("patch_make: Text1+Diff inputs.", expectedPatch, dmp.patch_toText(patches));
patches = dmp.patch_make(text1, text2, diffs);
assertEquals("patch_make: Text1+Text2+Diff inputs (deprecated).", expectedPatch, dmp.patch_toText(patches));
patches = dmp.patch_make("`1234567890-=[]\\;',./", "~!@#$%^&*()_+{}|:\"<>?");
assertEquals("patch_toText: Character encoding.", "@@ -1,21 +1,21 @@\n-%601234567890-=%5B%5D%5C;',./\n+~!@#$%25%5E&*()_+%7B%7D%7C:%22%3C%3E?\n", dmp.patch_toText(patches));
diffs = diffList(new Diff(DELETE, "`1234567890-=[]\\;',./"), new Diff(INSERT, "~!@#$%^&*()_+{}|:\"<>?"));
assertEquals("patch_fromText: Character decoding.", diffs, dmp.patch_fromText("@@ -1,21 +1,21 @@\n-%601234567890-=%5B%5D%5C;',./\n+~!@#$%25%5E&*()_+%7B%7D%7C:%22%3C%3E?\n").get(0).diffs);
text1 = "";
for (int x = 0; x < 100; x++) {
text1 += "abcdef";
}
text2 = text1 + "123";
expectedPatch = "@@ -573,28 +573,31 @@\n cdefabcdefabcdefabcdefabcdef\n+123\n";
patches = dmp.patch_make(text1, text2);
assertEquals("patch_make: Long string with repeats.", expectedPatch, dmp.patch_toText(patches));
// Test null inputs.
try {
dmp.patch_make(null);
fail("patch_make: Null inputs.");
} catch (IllegalArgumentException ex) {
// Error expected.
}
}
public void testPatchSplitMax() {
// Assumes that Match_MaxBits is 32.
LinkedList<Patch> patches;
patches = dmp.patch_make("abcdefghijklmnopqrstuvwxyz01234567890", "XabXcdXefXghXijXklXmnXopXqrXstXuvXwxXyzX01X23X45X67X89X0");
dmp.patch_splitMax(patches);
assertEquals("patch_splitMax: #1.", "@@ -1,32 +1,46 @@\n+X\n ab\n+X\n cd\n+X\n ef\n+X\n gh\n+X\n ij\n+X\n kl\n+X\n mn\n+X\n op\n+X\n qr\n+X\n st\n+X\n uv\n+X\n wx\n+X\n yz\n+X\n 012345\n@@ -25,13 +39,18 @@\n zX01\n+X\n 23\n+X\n 45\n+X\n 67\n+X\n 89\n+X\n 0\n", dmp.patch_toText(patches));
patches = dmp.patch_make("abcdef1234567890123456789012345678901234567890123456789012345678901234567890uvwxyz", "abcdefuvwxyz");
String oldToText = dmp.patch_toText(patches);
dmp.patch_splitMax(patches);
assertEquals("patch_splitMax: #2.", oldToText, dmp.patch_toText(patches));
patches = dmp.patch_make("1234567890123456789012345678901234567890123456789012345678901234567890", "abc");
dmp.patch_splitMax(patches);
assertEquals("patch_splitMax: #3.", "@@ -1,32 +1,4 @@\n-1234567890123456789012345678\n 9012\n@@ -29,32 +1,4 @@\n-9012345678901234567890123456\n 7890\n@@ -57,14 +1,3 @@\n-78901234567890\n+abc\n", dmp.patch_toText(patches));
patches = dmp.patch_make("abcdefghij , h : 0 , t : 1 abcdefghij , h : 0 , t : 1 abcdefghij , h : 0 , t : 1", "abcdefghij , h : 1 , t : 1 abcdefghij , h : 1 , t : 1 abcdefghij , h : 0 , t : 1");
dmp.patch_splitMax(patches);
assertEquals("patch_splitMax: #4.", "@@ -2,32 +2,32 @@\n bcdefghij , h : \n-0\n+1\n , t : 1 abcdef\n@@ -29,32 +29,32 @@\n bcdefghij , h : \n-0\n+1\n , t : 1 abcdef\n", dmp.patch_toText(patches));
}
public void testPatchAddPadding() {
LinkedList<Patch> patches;
patches = dmp.patch_make("", "test");
assertEquals("patch_addPadding: Both edges full.", "@@ -0,0 +1,4 @@\n+test\n", dmp.patch_toText(patches));
dmp.patch_addPadding(patches);
assertEquals("patch_addPadding: Both edges full.", "@@ -1,8 +1,12 @@\n %01%02%03%04\n+test\n %01%02%03%04\n", dmp.patch_toText(patches));
patches = dmp.patch_make("XY", "XtestY");
assertEquals("patch_addPadding: Both edges partial.", "@@ -1,2 +1,6 @@\n X\n+test\n Y\n", dmp.patch_toText(patches));
dmp.patch_addPadding(patches);
assertEquals("patch_addPadding: Both edges partial.", "@@ -2,8 +2,12 @@\n %02%03%04X\n+test\n Y%01%02%03\n", dmp.patch_toText(patches));
patches = dmp.patch_make("XXXXYYYY", "XXXXtestYYYY");
assertEquals("patch_addPadding: Both edges none.", "@@ -1,8 +1,12 @@\n XXXX\n+test\n YYYY\n", dmp.patch_toText(patches));
dmp.patch_addPadding(patches);
assertEquals("patch_addPadding: Both edges none.", "@@ -5,8 +5,12 @@\n XXXX\n+test\n YYYY\n", dmp.patch_toText(patches));
}
public void testPatchApply() {
dmp.Match_Distance = 1000;
dmp.Match_Threshold = 0.5f;
dmp.Patch_DeleteThreshold = 0.5f;
LinkedList<Patch> patches;
patches = dmp.patch_make("", "");
Object[] results = dmp.patch_apply(patches, "Hello world.");
boolean[] boolArray = (boolean[]) results[1];
String resultStr = results[0] + "\t" + boolArray.length;
assertEquals("patch_apply: Null case.", "Hello world.\t0", resultStr);
patches = dmp.patch_make("The quick brown fox jumps over the lazy dog.", "That quick brown fox jumped over a lazy dog.");
results = dmp.patch_apply(patches, "The quick brown fox jumps over the lazy dog.");
boolArray = (boolean[]) results[1];
resultStr = results[0] + "\t" + boolArray[0] + "\t" + boolArray[1];
assertEquals("patch_apply: Exact match.", "That quick brown fox jumped over a lazy dog.\ttrue\ttrue", resultStr);
results = dmp.patch_apply(patches, "The quick red rabbit jumps over the tired tiger.");
boolArray = (boolean[]) results[1];
resultStr = results[0] + "\t" + boolArray[0] + "\t" + boolArray[1];
assertEquals("patch_apply: Partial match.", "That quick red rabbit jumped over a tired tiger.\ttrue\ttrue", resultStr);
results = dmp.patch_apply(patches, "I am the very model of a modern major general.");
boolArray = (boolean[]) results[1];
resultStr = results[0] + "\t" + boolArray[0] + "\t" + boolArray[1];
assertEquals("patch_apply: Failed match.", "I am the very model of a modern major general.\tfalse\tfalse", resultStr);
patches = dmp.patch_make("x1234567890123456789012345678901234567890123456789012345678901234567890y", "xabcy");
results = dmp.patch_apply(patches, "x123456789012345678901234567890-----++++++++++-----123456789012345678901234567890y");
boolArray = (boolean[]) results[1];
resultStr = results[0] + "\t" + boolArray[0] + "\t" + boolArray[1];
assertEquals("patch_apply: Big delete, small change.", "xabcy\ttrue\ttrue", resultStr);
patches = dmp.patch_make("x1234567890123456789012345678901234567890123456789012345678901234567890y", "xabcy");
results = dmp.patch_apply(patches, "x12345678901234567890---------------++++++++++---------------12345678901234567890y");
boolArray = (boolean[]) results[1];
resultStr = results[0] + "\t" + boolArray[0] + "\t" + boolArray[1];
assertEquals("patch_apply: Big delete, big change 1.", "xabc12345678901234567890---------------++++++++++---------------12345678901234567890y\tfalse\ttrue", resultStr);
dmp.Patch_DeleteThreshold = 0.6f;
patches = dmp.patch_make("x1234567890123456789012345678901234567890123456789012345678901234567890y", "xabcy");
results = dmp.patch_apply(patches, "x12345678901234567890---------------++++++++++---------------12345678901234567890y");
boolArray = (boolean[]) results[1];
resultStr = results[0] + "\t" + boolArray[0] + "\t" + boolArray[1];
assertEquals("patch_apply: Big delete, big change 2.", "xabcy\ttrue\ttrue", resultStr);
dmp.Patch_DeleteThreshold = 0.5f;
// Compensate for failed patch.
dmp.Match_Threshold = 0.0f;
dmp.Match_Distance = 0;
patches = dmp.patch_make("abcdefghijklmnopqrstuvwxyz--------------------1234567890", "abcXXXXXXXXXXdefghijklmnopqrstuvwxyz--------------------1234567YYYYYYYYYY890");
results = dmp.patch_apply(patches, "ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567890");
boolArray = (boolean[]) results[1];
resultStr = results[0] + "\t" + boolArray[0] + "\t" + boolArray[1];
assertEquals("patch_apply: Compensate for failed patch.", "ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567YYYYYYYYYY890\tfalse\ttrue", resultStr);
dmp.Match_Threshold = 0.5f;
dmp.Match_Distance = 1000;
patches = dmp.patch_make("", "test");
String patchStr = dmp.patch_toText(patches);
dmp.patch_apply(patches, "");
assertEquals("patch_apply: No side effects.", patchStr, dmp.patch_toText(patches));
patches = dmp.patch_make("The quick brown fox jumps over the lazy dog.", "Woof");
patchStr = dmp.patch_toText(patches);
dmp.patch_apply(patches, "The quick brown fox jumps over the lazy dog.");
assertEquals("patch_apply: No side effects with major delete.", patchStr, dmp.patch_toText(patches));
patches = dmp.patch_make("", "test");
results = dmp.patch_apply(patches, "");
boolArray = (boolean[]) results[1];
resultStr = results[0] + "\t" + boolArray[0];
assertEquals("patch_apply: Edge exact match.", "test\ttrue", resultStr);
patches = dmp.patch_make("XY", "XtestY");
results = dmp.patch_apply(patches, "XY");
boolArray = (boolean[]) results[1];
resultStr = results[0] + "\t" + boolArray[0];
assertEquals("patch_apply: Near edge exact match.", "XtestY\ttrue", resultStr);
patches = dmp.patch_make("y", "y123");
results = dmp.patch_apply(patches, "x");
boolArray = (boolean[]) results[1];
resultStr = results[0] + "\t" + boolArray[0];
assertEquals("patch_apply: Edge partial match.", "x123\ttrue", resultStr);
}
private void assertArrayEquals(String error_msg, Object[] a, Object[] b) {
List<Object> list_a = Arrays.asList(a);
List<Object> list_b = Arrays.asList(b);
assertEquals(error_msg, list_a, list_b);
}
private void assertLinesToCharsResultEquals(String error_msg,
LinesToCharsResult a, LinesToCharsResult b) {
assertEquals(error_msg, a.chars1, b.chars1);
assertEquals(error_msg, a.chars2, b.chars2);
assertEquals(error_msg, a.lineArray, b.lineArray);
}
// Construct the two texts which made up the diff originally.
private static String[] diff_rebuildtexts(LinkedList<Diff> diffs) {
String[] text = {"", ""};
for (Diff myDiff : diffs) {
if (myDiff.operation != Operation.INSERT) {
text[0] += myDiff.text;
}
if (myDiff.operation != Operation.DELETE) {
text[1] += myDiff.text;
}
}
return text;
}
// Private function for quickly building lists of diffs.
private static LinkedList<Diff> diffList(Diff... diffs) {
LinkedList<Diff> myDiffList = new LinkedList<Diff>();
for (Diff myDiff : diffs) {
myDiffList.add(myDiff);
}
return myDiffList;
}
} | [
"[email protected]"
]
| |
0d1a6394cf331556e685e251e9332bffda8fdd4b | 4aec3d83fac01703004233b371b928bd520eff11 | /uno/src/Ejemplos_Abstrac/Nadador.java | 98d4bcac0aa1a98cbfdadc05f21e71e4e34d535b | []
| no_license | CarlosContrerasS/trabajos | f10dbd6b9e766a819fb5d0266e2440073181bd26 | 5e0dd08273a1df38b4aefef52851fce1555a1104 | refs/heads/master | 2021-01-04T04:34:13.042496 | 2020-03-14T00:14:27 | 2020-03-14T00:14:27 | 240,387,957 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 146 | java | package Ejemplos_Abstrac;
public interface Nadador {
public default void nadar() {
System.out.println("la persona nada");
}
}
| [
"[email protected]"
]
| |
913428d03d6208bc90a6f373d84f856b4dee9883 | 51e5771ba2e78577c3e746c47c6011b5fc4ca790 | /src/main/java/com/devenger/bhaipaisadega/repository/PaymentRepository.java | a0a0365a13279b099c830895942f036a8e9e2c55 | []
| no_license | ejaz86/bhaipisadega | f17de1755d649c77eab90d78abeff22f0f1ff9a4 | eda9f18e39657ffa68527ba3deed8e7158972887 | refs/heads/master | 2020-09-27T19:34:36.102919 | 2019-12-08T04:01:01 | 2019-12-08T04:01:01 | 226,593,493 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 388 | java | package com.devenger.bhaipaisadega.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.devenger.bhaipaisadega.model.Payment;
public interface PaymentRepository extends JpaRepository<Payment, Long> {
List<Payment> findByLoanIdOrderByCreatedAtDesc(Long loanId);
List<Payment> findByLendIdOrderByCreatedAtDesc(Long lendId);
}
| [
"[email protected]"
]
| |
2d3c17f4c03bf5b8bf6267d54ade6d19325cd3e6 | 78a0dc1be47877910f61dcbac065b318db389ed7 | /src/main/java/cn/ibdsr/web/modular/platform/shop/account/service/IShopAcctOperateService.java | 38a8fd04c5a3563ed92e9276c975ae7a673b3134 | []
| no_license | wangdeming/eshop-admin | 1d3f4b5062bafd8a8a3a3349f5768e8e98be1ea0 | d2112ca85236ab812d8f9bbb5e78333db73e99e9 | refs/heads/master | 2022-09-19T16:04:35.420487 | 2020-06-04T03:12:46 | 2020-06-04T03:12:46 | 269,248,516 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,039 | java | package cn.ibdsr.web.modular.platform.shop.account.service;
import cn.ibdsr.web.modular.platform.shop.account.transfer.AccountOperDTO;
import java.util.List;
import java.util.Map;
/**
* 店铺账户操作管理Service
*
* @author XuZhipeng
* @Date 2019-02-26 11:26:18
*/
public interface IShopAcctOperateService {
/**
* 查询店铺名称和账户名
*
* @param accountId 店铺账号ID
* @return
*/
Map<String, Object> getShopNameAndAccount(Long accountId);
/**
* 添加账户操作记录
*
* @param accountOperDTO
* @param operateCode 操作码(1-冻结;2-解冻;)
*/
void addAcctOperRecord(AccountOperDTO accountOperDTO, Integer operateCode);
/**
* 获取店铺账户操作记录列表
*
* @param accountId 店铺账户ID
* @return
*/
List<Map<String, Object>> listOperRecords(Long accountId);
/**
* 注销店铺账号
*
* @param accountId 店铺账号ID
*/
void cancel(Long accountId);
}
| [
"[email protected]"
]
| |
adc4be8c096068cb8db44a0990c64f63ea2ba8d5 | 1d43dcf0aa5fa3c8a23df59ae3619183b94679ff | /src/main/java/com/zhangzebo/dto/CommentDTO.java | 0a0181d7e32627de4686c75b7dee02804757e35f | []
| no_license | Zeebo0/bowenblog | 573c9fb2ec88262e6bcc0728615eb381154d063f | 62592f95a6af295659e4ff8bdf742dec2fe6da8a | refs/heads/master | 2023-01-01T03:32:57.776062 | 2020-10-24T08:17:02 | 2020-10-24T08:17:02 | 298,956,150 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 391 | java | package com.zhangzebo.dto;
import com.zhangzebo.model.User;
import lombok.Data;
@Data
public class CommentDTO {
private Long id;
private Long parentId;
private Integer type;
private Long commentator;
private Long gmtCreate;
private Long gmtModified;
private Long likeCount;
private String content;
private User user;
private Integer commentCount;
}
| [
"[email protected]"
]
| |
3b4601f123147f105c8c8890ccb4a7877f045e5a | 1d0fca558f68ebe051fbceea56ef3464d30b9dc5 | /Eclipse wenjian/窗口化/src/SS/P211p1.java | f63b0894c41e68e18a1a80aaa09f08b530a934c5 | []
| no_license | swgao/demo | 23fce6850a69d3689dd3478dd49246dc6005a439 | 20d3faa6230dc0c9f48021454dbddcb38e20f9ca | refs/heads/master | 2022-12-21T20:12:04.439698 | 2020-07-03T15:52:01 | 2020-07-03T15:52:01 | 233,381,489 | 1 | 0 | null | 2022-12-15T23:26:43 | 2020-01-12T11:27:49 | Java | UTF-8 | Java | false | false | 529 | java | package SS;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class P211p1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame jf = new JFrame();
Container cp= jf.getContentPane();
cp.setLayout(new FlowLayout());
jf.setVisible(true);
JButton bt = new JButton("Button1");
JButton bt1 = new JButton("Button2");
JButton bt2 = new JButton("Button3");
jf.add(bt);
jf.add(bt1);
jf.add(bt2);
jf.pack();
}
}
| [
"[email protected]"
]
| |
e2c63f2e6e07529562f8abd7e40ad09747b2622f | 102a59e582313d074ef6c44f1e88a600f712e678 | /src/design_pattern/adapter/Target.java | d61af582159dcdd7b5d12561685c3a11ba151a7b | []
| no_license | papayamomo/mina-learning | 75515b78da077aa9ac802bc1b36d78b125ede582 | ed632b835ff3abb59a45dfb06a5801e828721036 | refs/heads/master | 2021-01-21T00:44:46.521962 | 2013-12-27T11:39:14 | 2013-12-27T11:39:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 87 | java | package design_pattern.adapter;
public interface Target {
public void request();
}
| [
"[email protected]"
]
| |
9ec66e333778ffa45f6099314268ede2477c0ede | dc515812a85070e31922195200530bdfe67a3ef5 | /QuickApp/app/src/main/java/com/lenovo/quickapp/uitl/StatusBarUtil.java | a2ec1da7e8e1ebc35a58ccd0bc526b473f09d36b | []
| no_license | sxj84877171/TestDemo | 9c281f64e035f4ad938b031f85b3015a41e392f8 | b79d2e1ee88f21d352cbc917619fdea3be237fc7 | refs/heads/master | 2021-01-20T20:03:50.910347 | 2016-08-23T05:54:51 | 2016-08-23T05:54:51 | 65,529,756 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 17,129 | java | package com.lenovo.quickapp.uitl;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
public class StatusBarUtil {
private StatusBarUtil(){
throw new UnsupportedOperationException("No Impl");
}
public static final int DEFAULT_STATUS_BAR_ALPHA = 112;
/**
* 设置状态栏颜色
*
*
* @param activity 需要设置的 activity
* @param color 状态栏颜色值
*/
public static void setColor(Activity activity, int color) {
setColor(activity, color, DEFAULT_STATUS_BAR_ALPHA);
}
/**
* 设置状态栏颜色
*
* @param activity 需要设置的activity
* @param color 状态栏颜色值
* @param statusBarAlpha 状态栏透明度
*/
public static void setColor(Activity activity, int color, int statusBarAlpha) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.getWindow().setStatusBarColor(calculateStatusColor(color, statusBarAlpha));
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 生成一个状态栏大小的矩形
View statusView = createStatusBarView(activity, color, statusBarAlpha);
// 添加 statusView 到布局中
ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
decorView.addView(statusView);
setRootView(activity);
}
}
/**
* 设置状态栏纯色 不加半透明效果
*
* @param activity 需要设置的 activity
* @param color 状态栏颜色值
*/
public static void setColorNoTranslucent(Activity activity, int color) {
setColor(activity, color, 0);
}
/**
* 设置状态栏颜色(5.0以下无半透明效果,不建议使用)
*
* @param activity 需要设置的 activity
* @param color 状态栏颜色值
*/
public static void setColorDiff(Activity activity, int color) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
return;
}
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 生成一个状态栏大小的矩形
View statusView = createStatusBarView(activity, color);
// 添加 statusView 到布局中
ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView();
decorView.addView(statusView);
setRootView(activity);
}
/**
* 使状态栏半透明
*
* 适用于图片作为背景的界面,此时需要图片填充到状态栏
*
* @param activity 需要设置的activity
*/
public static void setTranslucent(Activity activity) {
setTranslucent(activity, DEFAULT_STATUS_BAR_ALPHA);
}
public static void setTranslucentBackground(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = activity.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
/**
* 使状态栏半透明
*
* 适用于图片作为背景的界面,此时需要图片填充到状态栏
*
* @param activity 需要设置的activity
* @param statusBarAlpha 状态栏透明度
*/
public static void setTranslucent(Activity activity, int statusBarAlpha) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
return;
}
setTransparent(activity);
addTranslucentView(activity, statusBarAlpha);
}
/**
* 设置状态栏全透明
*
* @param activity 需要设置的activity
*/
public static void setTransparent(Activity activity) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
return;
}
transparentStatusBar(activity);
setRootView(activity);
}
/**
* 使状态栏透明(5.0以上半透明效果,不建议使用)
*
* 适用于图片作为背景的界面,此时需要图片填充到状态栏
*
* @param activity 需要设置的activity
*/
public static void setTranslucentDiff(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// 设置状态栏透明
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
setRootView(activity);
}
}
/**
* 为DrawerLayout 布局设置状态栏变色
*
* @param activity 需要设置的activity
* @param drawerLayout DrawerLayout
* @param color 状态栏颜色值
*/
public static void setColorForDrawerLayout(Activity activity, DrawerLayout drawerLayout, int color) {
setColorForDrawerLayout(activity, drawerLayout, color, DEFAULT_STATUS_BAR_ALPHA);
}
/**
* 为DrawerLayout 布局设置状态栏颜色,纯色
*
* @param activity 需要设置的activity
* @param drawerLayout DrawerLayout
* @param color 状态栏颜色值
*/
public static void setColorNoTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout, int color) {
setColorForDrawerLayout(activity, drawerLayout, color, 0);
}
/**
* 为DrawerLayout 布局设置状态栏变色
*
* @param activity 需要设置的activity
* @param drawerLayout DrawerLayout
* @param color 状态栏颜色值
* @param statusBarAlpha 状态栏透明度
*/
public static void setColorForDrawerLayout(Activity activity, DrawerLayout drawerLayout, int color, int statusBarAlpha) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
} else {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
// 生成一个状态栏大小的矩形
View statusBarView = createStatusBarView(activity, color);
// 添加 statusBarView 到布局中
ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0);
contentLayout.addView(statusBarView, 0);
// 内容布局不是 LinearLayout 时,设置padding top
if (!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) {
contentLayout.getChildAt(1).setPadding(0, getStatusBarHeight(activity), 0, 0);
}
// 设置属性
ViewGroup drawer = (ViewGroup) drawerLayout.getChildAt(1);
drawerLayout.setFitsSystemWindows(false);
contentLayout.setFitsSystemWindows(false);
contentLayout.setClipToPadding(true);
drawer.setFitsSystemWindows(false);
addTranslucentView(activity, statusBarAlpha);
}
/**
* 为DrawerLayout 布局设置状态栏变色(5.0以下无半透明效果,不建议使用)
*
* @param activity 需要设置的activity
* @param drawerLayout DrawerLayout
* @param color 状态栏颜色值
*/
public static void setColorForDrawerLayoutDiff(Activity activity, DrawerLayout drawerLayout, int color) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 生成一个状态栏大小的矩形
View statusBarView = createStatusBarView(activity, color);
// 添加 statusBarView 到布局中
ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0);
contentLayout.addView(statusBarView, 0);
// 内容布局不是 LinearLayout 时,设置padding top
if (!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) {
contentLayout.getChildAt(1).setPadding(0, getStatusBarHeight(activity), 0, 0);
}
// 设置属性
ViewGroup drawer = (ViewGroup) drawerLayout.getChildAt(1);
drawerLayout.setFitsSystemWindows(false);
contentLayout.setFitsSystemWindows(false);
contentLayout.setClipToPadding(true);
drawer.setFitsSystemWindows(false);
}
}
/**
* 为 DrawerLayout 布局设置状态栏透明
*
* @param activity 需要设置的activity
* @param drawerLayout DrawerLayout
*/
public static void setTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout) {
setTranslucentForDrawerLayout(activity, drawerLayout, DEFAULT_STATUS_BAR_ALPHA);
}
/**
* 为 DrawerLayout 布局设置状态栏透明
*
* @param activity 需要设置的activity
* @param drawerLayout DrawerLayout
*/
public static void setTranslucentForDrawerLayout(Activity activity, DrawerLayout drawerLayout, int statusBarAlpha) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
return;
}
setTransparentForDrawerLayout(activity, drawerLayout);
addTranslucentView(activity, statusBarAlpha);
}
/**
* 为 DrawerLayout 布局设置状态栏透明
*
* @param activity 需要设置的activity
* @param drawerLayout DrawerLayout
*/
public static void setTransparentForDrawerLayout(Activity activity, DrawerLayout drawerLayout) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
} else {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0);
// 内容布局不是 LinearLayout 时,设置padding top
if (!(contentLayout instanceof LinearLayout) && contentLayout.getChildAt(1) != null) {
contentLayout.getChildAt(1).setPadding(0, getStatusBarHeight(activity), 0, 0);
}
// 设置属性
ViewGroup drawer = (ViewGroup) drawerLayout.getChildAt(1);
drawerLayout.setFitsSystemWindows(false);
contentLayout.setFitsSystemWindows(false);
contentLayout.setClipToPadding(true);
drawer.setFitsSystemWindows(false);
}
/**
* 为 DrawerLayout 布局设置状态栏透明(5.0以上半透明效果,不建议使用)
*
* @param activity 需要设置的activity
* @param drawerLayout DrawerLayout
*/
public static void setTranslucentForDrawerLayoutDiff(Activity activity, DrawerLayout drawerLayout) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// 设置状态栏透明
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 设置内容布局属性
ViewGroup contentLayout = (ViewGroup) drawerLayout.getChildAt(0);
contentLayout.setFitsSystemWindows(true);
contentLayout.setClipToPadding(true);
// 设置抽屉布局属性
ViewGroup vg = (ViewGroup) drawerLayout.getChildAt(1);
vg.setFitsSystemWindows(false);
// 设置 DrawerLayout 属性
drawerLayout.setFitsSystemWindows(false);
}
}
/**
* 添加半透明矩形条
*
* @param activity 需要设置的 activity
* @param statusBarAlpha 透明值
*/
private static void addTranslucentView(Activity activity, int statusBarAlpha) {
ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
// 移除半透明矩形,以免叠加
if (contentView.getChildCount() > 1) {
contentView.removeViewAt(1);
}
contentView.addView(createTranslucentStatusBarView(activity, statusBarAlpha));
}
/**
* 生成一个和状态栏大小相同的彩色矩形条
*
* @param activity 需要设置的 activity
* @param color 状态栏颜色值
* @return 状态栏矩形条
*/
private static View createStatusBarView(Activity activity, int color) {
// 绘制一个和状态栏一样高的矩形
View statusBarView = new View(activity);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
getStatusBarHeight(activity));
statusBarView.setLayoutParams(params);
statusBarView.setBackgroundColor(color);
return statusBarView;
}
/**
* 生成一个和状态栏大小相同的半透明矩形条
*
* @param activity 需要设置的activity
* @param color 状态栏颜色值
* @param alpha 透明值
* @return 状态栏矩形条
*/
private static View createStatusBarView(Activity activity, int color, int alpha) {
// 绘制一个和状态栏一样高的矩形
View statusBarView = new View(activity);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
getStatusBarHeight(activity));
statusBarView.setLayoutParams(params);
statusBarView.setBackgroundColor(calculateStatusColor(color, alpha));
return statusBarView;
}
/**
* 设置根布局参数
*/
private static void setRootView(Activity activity) {
ViewGroup rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);
rootView.setFitsSystemWindows(true);
rootView.setClipToPadding(true);
}
/**
* 使状态栏透明
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
private static void transparentStatusBar(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
} else {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
/**
* 创建半透明矩形 View
*
* @param alpha 透明值
* @return 半透明 View
*/
private static View createTranslucentStatusBarView(Activity activity, int alpha) {
// 绘制一个和状态栏一样高的矩形
View statusBarView = new View(activity);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
getStatusBarHeight(activity));
statusBarView.setLayoutParams(params);
statusBarView.setBackgroundColor(Color.argb(alpha, 0, 0, 0));
return statusBarView;
}
/**
* 获取状态栏高度
*
* @param context context
* @return 状态栏高度
*/
private static int getStatusBarHeight(Context context) {
// 获得状态栏高度
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
return context.getResources().getDimensionPixelSize(resourceId);
}
/**
* 计算状态栏颜色
*
* @param color color值
* @param alpha alpha值
* @return 最终的状态栏颜色
*/
private static int calculateStatusColor(int color, int alpha) {
float a = 1 - alpha / 255f;
int red = color >> 16 & 0xff;
int green = color >> 8 & 0xff;
int blue = color & 0xff;
red = (int) (red * a + 0.5);
green = (int) (green * a + 0.5);
blue = (int) (blue * a + 0.5);
return 0xff << 24 | red << 16 | green << 8 | blue;
}
} | [
"[email protected]"
]
| |
5da9b9a85b38cee55a6382bc36b9cf6dfc1926eb | b07f31138d1964e2ef6d2b1a4685623e8d9ba756 | /jar/freemarker/ext/beans/EnumerationModel.java | 1d42bac595ea231c72fdc6c3307a87194985351a | []
| no_license | worgent/yiming-mall | 364072c676ef6b9dc153344755c78981efc773ee | 545aecf48eaa531dc2b1fb7c8cad77970e2e92a1 | refs/heads/master | 2021-06-24T14:18:29.320720 | 2017-09-11T14:04:47 | 2017-09-11T14:04:47 | 103,140,528 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 5,681 | java | /*
* Copyright (c) 2003 The Visigoth Software Society. 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 acknowledgement:
* "This product includes software developed by the
* Visigoth Software Society (http://www.visigoths.org/)."
* Alternately, this acknowledgement may appear in the software itself,
* if and wherever such third-party acknowledgements normally appear.
*
* 4. Neither the name "FreeMarker", "Visigoth", nor any of the names of the
* project contributors may be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "FreeMarker" or "Visigoth"
* nor may "FreeMarker" or "Visigoth" appear in their names
* without prior written permission of the Visigoth Software Society.
*
* 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 VISIGOTH SOFTWARE SOCIETY 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 Visigoth Software Society. For more
* information on the Visigoth Software Society, please see
* http://www.visigoths.org/
*/
package freemarker.ext.beans;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import freemarker.template.TemplateCollectionModel;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateModelIterator;
/**
* <p>A class that adds {@link freemarker.template.TemplateModelIterator} functionality to the
* {@link java.util.Enumeration} interface implementers.
* </p> <p>Using the model as a collection model is NOT thread-safe, as
* enumerations are inherently not thread-safe.
* Further, you can iterate over it only once. Attempts to call the
* {@link #iterator()} method after it was already driven to the end once will
* throw an exception.</p>
* @author Attila Szegedi
* @version $Id: EnumerationModel.java,v 1.24 2003/06/03 13:21:32 szegedia Exp $
*/
public class EnumerationModel
extends
BeanModel
implements
TemplateModelIterator,
TemplateCollectionModel
{
private boolean accessed = false;
/**
* Creates a new model that wraps the specified enumeration object.
* @param enumeration the enumeration object to wrap into a model.
* @param wrapper the {@link freemarker.ext.beans.BeansWrapper} associated with this model.
* Every model has to have an associated {@link freemarker.ext.beans.BeansWrapper} instance. The
* model gains many attributes from its wrapper, including the caching
* behavior, method exposure level, method-over-item shadowing policy etc.
*/
public EnumerationModel(Enumeration enumeration, BeansWrapper wrapper)
{
super(enumeration, wrapper);
}
/**
* This allows the enumeration to be used in a <tt><foreach></tt> block.
* @return "this"
*/
public TemplateModelIterator iterator() throws TemplateModelException
{
synchronized(this) {
if(accessed) {
throw new TemplateModelException(
"This collection is stateful and can not be iterated over the" +
" second time.");
}
accessed = true;
}
return this;
}
/**
* Calls underlying {@link java.util.Enumeration#nextElement()}.
*/
public boolean hasNext() {
return ((Enumeration)object).hasMoreElements();
}
/**
* Calls underlying {@link java.util.Enumeration#nextElement()} and wraps the result.
*/
public TemplateModel next()
throws
TemplateModelException
{
try {
return wrap(((Enumeration)object).nextElement());
}
catch(NoSuchElementException e) {
throw new TemplateModelException(
"No more elements in the enumeration.");
}
}
/**
* Returns {@link java.util.Enumeration#hasMoreElements()}. Therefore, an
* enumeration that has no more element evaluates to false, and an
* enumeration that has further elements evaluates to true.
*/
public boolean getAsBoolean() {
return hasNext();
}
}
| [
"[email protected]"
]
| |
bced59630d21f564b33d3553212753dbb376282e | 5d126c2c0af5ba75b28bddb8833d825bf1c152d4 | /microcloud-consumer-hystrix/src/main/java/com/caxins/microcloud/Consumer_feign_StartSpringCloudApplication.java | cbb945c62e73d521cdd8c6c2f3d1e77072d5cb18 | []
| no_license | yejunxiang/microcloud | a64e442c444b72b1606cdc2031f95c44c0afcb13 | e4d0b74e3fd4ea513f5a8edec7abe3c9fef41f49 | refs/heads/master | 2020-04-05T00:20:43.651001 | 2018-11-06T14:28:41 | 2018-11-06T14:28:41 | 156,393,484 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 695 | java | package com.caxins.microcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@EnableEurekaClient
@ComponentScan("com.caxins.service,com.caxins.microcloud")
@EnableFeignClients(basePackages={"com.caxins.service"})
public class Consumer_feign_StartSpringCloudApplication {
public static void main(String[] args) {
SpringApplication.run(Consumer_feign_StartSpringCloudApplication.class,args);
}
}
| [
"[email protected]"
]
| |
30f57cba2cc78ca84b6b55147b59028e14fd0ca6 | 08d2d02cb495f85f579c64e59049e01b7179a928 | /app/src/main/java/com/example/letchat/UserFragment.java | 908db2aee816ff9566f42749969ddd0620816f34 | []
| no_license | android-app-development-course/LetChat | ffa01e1e269720f9068c9cec5b39e20bf81359e8 | 2a013128bb9fc0ca0555fe6970091e6456c5f741 | refs/heads/master | 2020-08-28T21:49:28.295983 | 2020-01-05T15:20:29 | 2020-01-05T15:20:29 | 217,830,850 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 834 | java | package com.example.letchat;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class UserFragment extends Fragment {
public UserFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_user, container, false);
}
}
| [
"[email protected]"
]
| |
2c02de8d4c833eab57d59cdc0b9224b50681e5a1 | b15dba3360bab0e9366a5c17aa3f846f17eb7cc7 | /app/src/main/java/com/samyotech/testofindia/database/TestAdapter.java | d0a0e432428e17965f23a3902b836fb0c232df7c | []
| no_license | amitsharmarepos/TasteofIndore | d9b1e48281265888fef702cce4c7cf6556f46d43 | baa18d99113b37dca442c9709a6d7ffa0b2ff253 | refs/heads/master | 2022-02-10T13:33:45.579682 | 2017-03-14T17:31:46 | 2017-03-14T17:31:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,434 | java | package com.samyotech.testofindia.database; /**
* Created by Varun on 7/27/2016.
*/
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.io.IOException;
public class TestAdapter
{
protected static final String TAG = "DataAdapter";
private final Context mContext;
private SQLiteDatabase mDb;
private DataBaseHelper mDbHelper;
public TestAdapter(Context context)
{
this.mContext = context;
mDbHelper = new DataBaseHelper(mContext);
}
public TestAdapter createDatabase() throws SQLException
{
try
{
mDbHelper.createDataBase();
}
catch (IOException mIOException)
{
Log.e(TAG, mIOException.toString() + " UnableToCreateDatabase");
throw new Error("UnableToCreateDatabase");
}
return this;
}
public TestAdapter open() throws SQLException
{
try
{
mDbHelper.openDataBase();
mDbHelper.close();
mDb = mDbHelper.getReadableDatabase();
}
catch (SQLException mSQLException)
{
Log.e(TAG, "open >>"+ mSQLException.toString());
throw mSQLException;
}
return this;
}
public void close()
{
mDbHelper.close();
}
public Cursor getTestData( )
{
try
{
String sql ="SELECT * FROM category";
Cursor mCur = mDb.rawQuery(sql, null);
if (mCur!=null)
{
mCur.moveToNext();
}
return mCur;
}
catch (SQLException mSQLException)
{
Log.e(TAG, "getTestData >>"+ mSQLException.toString());
throw mSQLException;
}
}
public Cursor getData(String id )
{
try
{
String sql ="SELECT * FROM dish where categoryid="+id+"";
Log.e(TAG, sql);
Cursor mCur = mDb.rawQuery(sql, null);
if (mCur!=null)
{
mCur.moveToNext();
}
return mCur;
}
catch (SQLException mSQLException)
{
Log.e(TAG, "getDatahhhhhhhhhhhhhhhhhhhhhhhh >>"+ mSQLException.toString());
throw mSQLException;
}
}
} | [
"[email protected]"
]
| |
3a6235ac3b6fa7b62c6fb97ae49f2785ea3fd111 | 99184095d86ca40cedb7d8fd8107c45bc9730354 | /inspector/an-inspector/ForgeModule/src/io/trigger/forge/android/modules/topbar/API.java | 7e3765d47fb28e335cbeb2a55c524698af900c66 | [
"BSD-2-Clause"
]
| permissive | trigger-corp/trigger.io-topbar | 63509197c4f8756eacf08c6036d48d186e223c1d | 4c91109800f49621b399468845bad5981f4f739b | refs/heads/master | 2021-05-24T04:26:33.388121 | 2020-09-23T09:09:41 | 2020-09-23T09:09:41 | 14,593,143 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 10,045 | java | package io.trigger.forge.android.modules.topbar;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.JsonArray;
import java.io.IOException;
import java.io.InputStream;
import io.trigger.forge.android.core.ForgeApp;
import io.trigger.forge.android.core.ForgeFile;
import io.trigger.forge.android.core.ForgeStorage;
import io.trigger.forge.android.core.ForgeTask;
import io.trigger.forge.android.core.ForgeViewController;
import io.trigger.forge.android.util.BitmapUtil;
public class API {
public static void show(final ForgeTask task) {
ForgeViewController.setNavigationBarHidden(false, new Runnable() {
public void run() {
task.success();
}
});
}
public static void hide(final ForgeTask task) {
ForgeViewController.setNavigationBarHidden(true, new Runnable() {
public void run() {
task.success();
}
});
}
public static void setTitle(final ForgeTask task) {
task.performUI(new Runnable() {
public void run() {
Util.setTitle(ForgeApp.getActivity(), task.params.get("title").getAsString());
task.success();
}
});
}
public static void setTitleImage(final ForgeTask task) {
task.performUI(new Runnable() {
public void run() {
try {
Util.setTitleImage(ForgeApp.getActivity(), task.params.get("icon"));
task.success();
} catch (IOException e) {
task.error(e);
}
}
});
}
public static void setTint(final ForgeTask task) {
task.performUI(new Runnable() {
public void run() {
JsonArray colorArray = task.params.getAsJsonArray("color");
int color = Color.argb(colorArray.get(3).getAsInt(), colorArray.get(0).getAsInt(), colorArray.get(1).getAsInt(), colorArray.get(2).getAsInt());
ColorDrawable bgColor = new ColorDrawable(color);
ForgeViewController.navigationBar.setBackgroundDrawable(bgColor);
task.success();
}
});
}
public static void setTitleTint(final ForgeTask task) {
task.performUI(new Runnable() {
public void run() {
JsonArray colorArray = task.params.getAsJsonArray("color");
int color = Color.argb(colorArray.get(3).getAsInt(), colorArray.get(0).getAsInt(), colorArray.get(1).getAsInt(), colorArray.get(2).getAsInt());
ColorDrawable bgColor = new ColorDrawable(color);
if (Util.titleText != null) {
Util.titleText.setTextColor(color);
}
task.success();
}
});
}
public static void addButton(final ForgeTask task) {
task.performUI(new Runnable() {
public void run() {
try {
DisplayMetrics metrics = new DisplayMetrics();
((Activity) ForgeApp.getActivity()).getWindowManager().getDefaultDisplay().getMetrics(metrics);
final int margin = Math.round(metrics.density * 4);
int tint = 0xFF1C8DD9;
if (task.params.has("tint")) {
JsonArray colorArray = task.params.getAsJsonArray("tint");
tint = Color.argb(colorArray.get(3).getAsInt(), colorArray.get(0).getAsInt(), colorArray.get(1).getAsInt(), colorArray.get(2).getAsInt());
}
final LinearLayout button = new LinearLayout(ForgeApp.getActivity());
button.setLongClickable(true);
button.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
// Highlight
v.setAlpha(0.3f);
} else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
// Unhighlight
v.setAlpha(1);
// Send event
if (task.params.has("type") && task.params.get("type").getAsString().toLowerCase().equals("back")) {
// TODO: Add a method to ForgeActivity to do this.
if (ForgeApp.getActivity().webView.canGoBack()) {
ForgeApp.getActivity().webView.goBack();
}
} else {
ForgeApp.event("topbar.buttonPressed." + task.callid);
}
}
return false;
}
});
button.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 48));
button.setGravity(Gravity.CENTER);
if (task.params.has("text")) {
TextView text = new TextView(ForgeApp.getActivity());
text.setText(task.params.get("text").getAsString());
text.setTextColor(tint);
text.setTextSize(TypedValue.COMPLEX_UNIT_PX, metrics.density * 18);
text.setGravity(Gravity.CENTER);
text.setPadding(margin * 2, margin, margin * 2, margin);
button.addView(text);
} else if (task.params.has("icon")) {
ImageView image = new ImageView(ForgeApp.getActivity());
image.setScaleType(ImageView.ScaleType.CENTER);
ForgeFile forgeFile = new ForgeFile(ForgeStorage.EndpointId.Source, task.params.get("icon").getAsString());
AssetFileDescriptor fileDescriptor = ForgeStorage.getFileDescriptor(forgeFile);
InputStream inputStream = fileDescriptor.createInputStream();
Drawable icon;
if (task.params.has("prerendered") && task.params.get("prerendered").getAsBoolean()) {
icon = BitmapUtil.scaledDrawableFromStream(ForgeApp.getActivity(), inputStream, 0, 32);
} else {
icon = BitmapUtil.scaledDrawableFromStreamWithTint(ForgeApp.getActivity(), inputStream, 0, 32, tint);
}
image.setImageDrawable(icon);
image.setPadding(margin * 2, 1, margin * 2, 1);
button.addView(image);
} else {
task.error("Invalid parameters sent to forge.topbar.addButton", "BAD_INPUT", null);
return;
}
if (!(task.params.has("position") && task.params.get("position").getAsString().toLowerCase().equals("left")) && Util.right == null) {
if (Util.right != null) {
task.error("Button already exists in position: left", "EXPECTED_FAILURE", null);
return;
}
Util.right = button;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.rightMargin = Math.round(metrics.density * 9);
params.topMargin = Math.round(metrics.density * 9);
ForgeViewController.navigationBar.addView(button, params);
} else {
if (Util.left != null) {
task.error("Button already exists in position: right", "EXPECTED_FAILURE", null);
return;
}
Util.left = button;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.leftMargin = Math.round(metrics.density * 9);
params.topMargin = Math.round(metrics.density * 9);
ForgeViewController.navigationBar.addView(button, params);
}
task.success(task.callid);
} catch (IOException e) {
task.error(e);
}
}
});
}
public static void removeButtons(final ForgeTask task) {
task.performUI(new Runnable() {
public void run() {
if (Util.left != null) {
ForgeViewController.navigationBar.removeView(Util.left);
Util.left = null;
}
if (Util.right != null) {
ForgeViewController.navigationBar.removeView(Util.right);
Util.right = null;
}
task.success();
}
});
}
}
| [
"[email protected]"
]
| |
bb37779eef1571c0feebc2300f7dfc26cf3a1b85 | 065db1a1890981e6aaa824cc40f23273ec949c7f | /demo/src/main/java/ConsoleInterface.java | 4c80f5fe7127ed7c71963f1bfd4c6479e991b25e | []
| no_license | ZhangJun2017/AmfParserV2 | 22461f2e780bdb9f74037ee61f98893d52fa9be6 | c8d75053c4a14d4827244ad6001e6019421fe325 | refs/heads/master | 2022-02-26T17:55:02.589809 | 2019-10-26T06:26:25 | 2019-10-26T06:26:25 | 197,906,891 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,984 | java | import flex.messaging.io.ArrayCollection;
import flex.messaging.io.amf.ASObject;
import flex.messaging.io.amf.client.AMFConnection;
import flex.messaging.io.amf.client.exceptions.ClientStatusException;
import flex.messaging.io.amf.client.exceptions.ServerStatusException;
import io.zhangjun2017.amfparser.common.CallableAsInterface;
import io.zhangjun2017.amfparser.common.Config;
import io.zhangjun2017.amfparser.common.Status;
import io.zhangjun2017.amfparser.common.StatusException;
import io.zhangjun2017.amfparser.common.utils.Tools;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* demo/
* Description:
*
* @author:ZhangJun2017
* @date:2019/8/22
*/
public class ConsoleInterface implements CallableAsInterface {
public static void main(String[] args) throws StatusException {
new ConsoleInterface().amfGet(new Config(new ConsoleInterface()).put("url", "http://etreport.iclassmate.cn:8082/SchoolCenter/messagebroker/amf").put("command", "multiExamServiceNew.getAllStudentMultiExam").put("args", new Object[]{19868, "21812140", "token right here,just for debug,do not ban me!"}));
}
@Override
public void output(String s) {
System.out.print("\n" + s);
}
@Override
public void outputNNL(String s) {
System.out.print(s);
}
@Override
public String getDeviceId() {
return null;
}
@Override
public Status rawHttpGet(String url) throws StatusException {
try {
Response response = new OkHttpClient().newCall(new Request.Builder().url(url).build()).execute();
return new Status().setStatusCode(response.code()).setStatusMsg(response.body().string());
} catch (Exception e) {
throw new StatusException(-1, "Exception happened.", e.toString());
}
}
@Override
public String httpGet(String url) throws StatusException {
try {
Response response = new OkHttpClient().newCall(new Request.Builder().url(url).build()).execute();
if (response.code() != 200) {
throw new StatusException(-2, "Response code wrong.", "Server returns " + response.code() + ".");
}
return response.body().string();
} catch (Exception e) {
throw new StatusException(-1, "Exception happened.", e.toString());
}
}
@Override
public Config amfGet(Config config) throws StatusException {
try {
AMFConnection amfConnection = new AMFConnection();
amfConnection.connect(config.get("url").toString());
ArrayCollection root = ((ArrayCollection) amfConnection.call(config.get("command").toString(), (Object[]) config.get("args")));
if (root.size() == 0) {
throw new StatusException(-3, "Server return null.", "No more details.");
}
return new Config().put("data",root);
} catch (ClientStatusException e) {
throw new StatusException(-1, "Something bad happened.", e.toString());
} catch (ServerStatusException e) {
throw new StatusException(-2, "Something bad happened.", e.toString());
}
}
@Override
public void throwException(StatusException e) {
//DEBUG MODE ON
//RELEASE:System.err.println("[" + e.getErrCode + ":" + e.getUserFriendlyMsg() + "]\n" + e.getMsg());
//DEBUG:
e.printStackTrace();
}
@Override
public String demo(CallableAsInterface mInterface) throws StatusException {
return Tools.parseJson(mInterface.httpGet(Tools.parseJson(mInterface.httpGet(Value.gitee_main_config)).get("prefix").getAsString() + Value.main_suffix)).get("eachVersionConfigServer").getAsString();
}
@Override
public void demo2(CallableAsInterface callableAsInterface) throws StatusException {
System.err.println(callableAsInterface.httpGet(callableAsInterface.demo(callableAsInterface)));
}
}
| [
"[email protected]"
]
| |
f7f412d979ede944ff53d2da999a7249c40dd11f | 11a6b794084ca4611e41fff6cc5420d956eaaeea | /lib/FlamerLib/RangeBar/gen/com/edmodo/rangebar/BuildConfig.java | 1f446e9f346984a7a0bd85ad9bd56187ba54efc6 | []
| no_license | zaggaz/flamerandroid | 1f2841f1ce441f3178882cf3f3ab6d23fb07275b | 65c1ebd11be2c8cf63dd1081eedb76b50a1ecf84 | refs/heads/master | 2020-04-06T07:07:24.079434 | 2015-09-23T02:02:57 | 2015-09-23T02:02:57 | 42,972,265 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 161 | java | /** Automatically generated file. DO NOT MODIFY */
package com.edmodo.rangebar;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | [
"[email protected]"
]
| |
8e6cbf68000e8555bdc8fecf0f50725924f5f704 | d2496a6d5e45aa4266231a74918c75393d856b3e | /何卓坤-1552743/CausalitySearch/backend/CausalitySearch/src/main/java/edu/tongji/xlab/causality/edu/cmu/tetrad/algcomparison/examples/ExampleCompareSimulation.java | 668ae79dc31d1af27c5877f9690f86e652fdf212 | []
| no_license | XLab-Tongji/aiops-2018-anomaly-detection | fa7496364ef1e42e34830ac1e58a0def4f9e85b3 | 1bce82666a5f92f62eeb651e06ec57cb61e11ce2 | refs/heads/master | 2021-08-08T06:31:06.406527 | 2019-01-02T09:05:14 | 2019-01-02T09:05:14 | 149,739,411 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,151 | java | ///////////////////////////////////////////////////////////////////////////////
// For information as to what this class does, see the Javadoc, below. //
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, //
// 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph //
// Ramsey, and Clark Glymour. //
// //
// This program is free software; you can redistribute it and/or modify //
// it under the terms of the GNU General Public License as published by //
// the Free Software Foundation; either version 2 of the License, or //
// (at your option) any later version. //
// //
// This program is distributed in the hope that it will be useful, //
// but WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
// GNU General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program; if not, write to the Free Software //
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //
///////////////////////////////////////////////////////////////////////////////
package edu.cmu.tetrad.algcomparison.examples;
import edu.cmu.tetrad.algcomparison.Comparison;
import edu.cmu.tetrad.algcomparison.algorithm.Algorithms;
import edu.cmu.tetrad.algcomparison.algorithm.oracle.pattern.*;
import edu.cmu.tetrad.algcomparison.graph.RandomForward;
import edu.cmu.tetrad.algcomparison.independence.FisherZ;
import edu.cmu.tetrad.algcomparison.score.MVPBicScore;
import edu.cmu.tetrad.algcomparison.score.SemBicScore;
import edu.cmu.tetrad.algcomparison.simulation.SemSimulation;
import edu.cmu.tetrad.algcomparison.simulation.Simulations;
import edu.cmu.tetrad.algcomparison.statistic.*;
import edu.cmu.tetrad.util.Parameters;
/**
* An example script to simulate data and run a comparison analysis on it.
*
* @author jdramsey
*/
public class ExampleCompareSimulation {
public static void main(String... args) {
Parameters parameters = new Parameters();
https://arxiv.org/abs/1607.08110
parameters.set("numRuns", 10);
parameters.set("numMeasures", 100);
parameters.set("avgDegree", 4, 6);
parameters.set("sampleSize", 500);
parameters.set("alpha", 1e-4, 1e-3, 1e-2);
Statistics statistics = new Statistics();
statistics.add(new AdjacencyPrecision());
statistics.add(new AdjacencyRecall());
statistics.add(new ArrowheadPrecision());
statistics.add(new ArrowheadRecall());
statistics.add(new MathewsCorrAdj());
statistics.add(new MathewsCorrArrow());
statistics.add(new F1Adj());
statistics.add(new F1Arrow());
statistics.add(new SHD());
statistics.add(new ElapsedTime());
statistics.setWeight("AP", 1.0);
statistics.setWeight("AR", 0.5);
Algorithms algorithms = new Algorithms();
algorithms.add(new Pc(new FisherZ()));
algorithms.add(new Cpc(new FisherZ(), new Fges(new SemBicScore(), false)));
algorithms.add(new PcStable(new FisherZ()));
algorithms.add(new CpcStable(new FisherZ()));
Simulations simulations = new Simulations();
simulations.add(new SemSimulation(new RandomForward()));
Comparison comparison = new Comparison();
comparison.setShowAlgorithmIndices(true);
comparison.setShowSimulationIndices(true);
comparison.setSortByUtility(true);
comparison.setShowUtilities(true);
comparison.setParallelized(true);
comparison.compareFromSimulations("comparison", simulations, algorithms, statistics, parameters);
}
}
| [
"[email protected]"
]
| |
eb6006d790b70f1b6f17ec2a431f1846bcb16286 | 77f0f149b231418ef8d9e7c8d44bf6bfd738f996 | /src/main/java/com/yucei/admin/YuceiAdminApplication.java | c2568c1b879ff8512e54cdd0b477d8abb4b3a33b | [
"Apache-2.0"
]
| permissive | wrong1111/springboot2 | d640578695e0fcd76685fdb5a7dabde90701cbaf | 4f29a2575656a6d6dd72123c099d9b91f332b38c | refs/heads/master | 2020-04-02T03:45:05.143564 | 2018-10-21T06:57:56 | 2018-10-21T06:57:56 | 153,982,270 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 327 | java | package com.yucei.admin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class YuceiAdminApplication {
public static void main(String[] args) {
SpringApplication.run(YuceiAdminApplication.class, args);
}
}
| [
"[email protected]"
]
| |
735aebe0f30f600d32643f3a7ed5b86ae4ec6780 | 693e5affd31dc63cfb1a52a72e99f3c509578d07 | /st-server/src/main/java/cc/gooto/service/impl/NavigationBarServiceImpl.java | 8fbadeb794f1bd2c46bed4df84ebac4939a83397 | []
| no_license | devpei/System_Test | 3acbbd31a0201806b1e8c1f6f804ba47df15ce8a | 227eded5906e0e41f9ecdd6c108afb5fc0862bfa | refs/heads/master | 2023-01-14T03:51:27.587920 | 2019-05-24T10:46:36 | 2019-05-24T10:46:36 | 181,307,855 | 0 | 0 | null | 2023-01-07T04:56:45 | 2019-04-14T12:47:22 | Java | UTF-8 | Java | false | false | 428 | java | package cc.gooto.service.impl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cc.gooto.entity.NavigationBarTest;
import cc.gooto.mapper.NavigationBarMapper;
import cc.gooto.service.NavigationBarService;
@Service
public class NavigationBarServiceImpl extends ServiceImpl<NavigationBarMapper, NavigationBarTest>
implements NavigationBarService {
}
| [
"[email protected]"
]
| |
b2edfcc6a43bdb6b78d3d83dfa1b97f9caa360a1 | c97fb7bbe5df56b110aa4f68f747f4e527c7f9d8 | /src/dictionaryController/DictionaryApp.java | 8eac2bc540cf2228221012fbad32a734aa427271 | []
| no_license | vuquangkhtn/dictionary | 443cddfc4db2b98888009484872174fd6b2d275b | de29d4f6943f7af903b083ce1fa09f56d7ce9b77 | refs/heads/master | 2020-12-30T13:09:08.163305 | 2017-05-15T11:58:59 | 2017-05-15T11:58:59 | 91,332,633 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,895 | 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 dictionaryController;
import dictionaryData.Word;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
/**
*
* @author VuQuang
*/
public class DictionaryApp implements DictionaryAction{
public static final String FOLDER_DU_LIEU = "Docs/";
public static final String FOLDER_ANH_VIET = FOLDER_DU_LIEU+"AnhViet/";
public static final String FOLDER_VIET_ANH = FOLDER_DU_LIEU+"VietAnh/";
private DictionaryManagement AnhVietDict;
private DictionaryManagement VietAnhDict;
private DictType type;
public DictionaryApp() {
AnhVietDict = new DictionaryManagement(
FOLDER_ANH_VIET+ "Anh_Viet.xml",
FOLDER_ANH_VIET+ "Anh_Viet_Favorite.xml",
FOLDER_ANH_VIET+ "Anh_Viet_History.xml"
);
VietAnhDict = new DictionaryManagement(
FOLDER_VIET_ANH+ "Viet_Anh.xml",
FOLDER_VIET_ANH+ "Viet_Anh_Favorite.xml",
FOLDER_VIET_ANH+ "Viet_Anh_History.xml"
);
type = DictType.ANH_VIET;
}
public boolean isAnhViet() {
return type == DictType.ANH_VIET;
}
@Override
public boolean chuyenDoiNgonNgu() {
switch(this.type) {
case ANH_VIET:
{
this.type = DictType.VIET_ANH;
return true;
}
case VIET_ANH:
{
this.type = DictType.ANH_VIET;
return true;
}
default:
return false;
}
}
@Override
public List<String> traCuuTu(String tuTraCuu) {
switch(type) {
case ANH_VIET:
{
return AnhVietDict.traCuuTu(tuTraCuu);
}
case VIET_ANH:
{
return VietAnhDict.traCuuTu(tuTraCuu);
}
default:
{
return null;
}
}
}
public Word traCuuTuChinhXac(String tuTraCuu) {
switch(type) {
case ANH_VIET:
{
return AnhVietDict.traCuuTuChinhXac(tuTraCuu);
}
case VIET_ANH:
{
return VietAnhDict.traCuuTuChinhXac(tuTraCuu);
}
default:
{
return null;
}
}
}
public List<String> dsTuYeuThich() {
switch(type) {
case ANH_VIET:
{
return AnhVietDict.dsTuYeuThich();
}
case VIET_ANH:
{
return VietAnhDict.dsTuYeuThich();
}
default:
{
return null;
}
}
}
@Override
public String luuLaiTuYeuThich(String tuYeuThich) {
switch(type) {
case ANH_VIET:
{
return AnhVietDict.luuLaiTuYeuThich(tuYeuThich);
}
case VIET_ANH:
{
return VietAnhDict.luuLaiTuYeuThich(tuYeuThich);
}
default:
{
return null;
}
}
}
@Override
public HashMap<String, Integer> thongKeTanSuatTraCuu(GregorianCalendar beginDay, GregorianCalendar endDay) {
switch(type) {
case ANH_VIET:
{
return AnhVietDict.thongKeTanSuatTraCuu(beginDay, endDay);
}
case VIET_ANH:
{
return VietAnhDict.thongKeTanSuatTraCuu(beginDay, endDay);
}
default:
{
return null;
}
}
}
}
| [
"[email protected]"
]
| |
4201bf47d573443462d639789cf8e9dd145ad3dc | a8f3b7921f9f0e6508571fac4cdf7836c5cce176 | /src/web_erp/dao/DepartmentDao.java | 50f03f8acec170a38ab997bd0acf05b443142d10 | []
| no_license | stpn94/web_erp | ef78f09871ebdcc7f33d3774053cbc40b2f7b8a6 | cb61e2db8edc3aa6e76cf87d892ac94f1aa9e472 | refs/heads/master | 2023-04-03T23:43:58.137958 | 2021-04-06T03:46:08 | 2021-04-06T03:46:08 | 353,921,300 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 467 | java | package web_erp.dao;
import java.util.List;
import web_erp.dto.Department;
/*
* Data Access Object
* C(insert)
* R(select, select where)
* U(update)
* D(delete)
*/
public interface DepartmentDao {
List<Department> selectDepartmentByAll();
Department selectDepartmentByNo(Department department);
int insertDepartment(Department department);
int updateDepartment(Department department);
int deleteDepartment(int DepartmentNo);
}
| [
"[email protected]"
]
| |
d883d99c443b5d4b3bad66e5aa846622da1586e4 | d32629291f9c2fb8e5935fb14976318c05009eea | /opendevice-core/src/main/java/br/com/criativasoft/opendevice/core/discovery/DiscoveryClientService.java | 39ddb563ba0be10495c1846f3890b2a23699d1bc | []
| no_license | OpenDevice/OpenDevice | ff51d1ff4b14e4dadb6bf71a5e975dca7c97347a | 92381cc029e6b2b42d78ec517239535bfe89b962 | refs/heads/master | 2023-08-06T09:56:25.214772 | 2022-07-26T10:45:47 | 2022-07-26T10:45:47 | 21,923,997 | 73 | 29 | null | 2023-07-25T14:00:05 | 2014-07-17T01:16:17 | JavaScript | UTF-8 | Java | false | false | 6,803 | java | /*
* *****************************************************************************
* Copyright (c) 2013-2014 CriativaSoft (www.criativasoft.com.br)
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ricardo JL Rufino - Initial API and Implementation
* *****************************************************************************
*/
package br.com.criativasoft.opendevice.core.discovery;
import br.com.criativasoft.opendevice.connection.discovery.DiscoveryListener;
import br.com.criativasoft.opendevice.connection.discovery.NetworkDeviceInfo;
import br.com.criativasoft.opendevice.core.command.CommandStreamSerializer;
import br.com.criativasoft.opendevice.core.command.CommandType;
import br.com.criativasoft.opendevice.core.command.DiscoveryResponse;
import br.com.criativasoft.opendevice.core.command.SimpleCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.*;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
public class DiscoveryClientService implements Runnable {
private static final int DISCOVERY_PORT = DiscoveryServiceImpl.DISCOVERY_PORT;
private Logger log = LoggerFactory.getLogger(DiscoveryClientService.class);
private long timeout;
private boolean closeOnFinish = true;
private String deviceName;
private DatagramSocket socket;
private DiscoveryListener listener;
private Set<NetworkDeviceInfo> devices = new HashSet<NetworkDeviceInfo>();
final CommandStreamSerializer serializer = new CommandStreamSerializer();
public DiscoveryClientService(long timeout, String deviceName, DiscoveryListener listener, DatagramSocket socket) {
this.timeout = timeout;
this.deviceName = deviceName;
this.listener = listener;
this.socket = socket;
this.closeOnFinish = false; // shared instance.
}
@Override
public void run() {
try {
scan();
} catch (IOException e) {
log.error("Could not send discovery request", e);
}
}
public void scan() throws IOException {
if (socket == null) {
socket = new DatagramSocket(DISCOVERY_PORT);
socket.setBroadcast(true);
socket.setSoTimeout((int) timeout);
}
sendDiscoveryRequest(socket);
listenForResponses(socket);
}
/**
* Send a broadcast UDP packet containing a request for boxee services to
* announce themselves.
*
* @throws IOException
*/
private void sendDiscoveryRequest(DatagramSocket socket) throws IOException {
byte[] bytes = serializer.serialize(new SimpleCommand(CommandType.DISCOVERY_REQUEST, 0));
log.debug("Send discover request... ");
DatagramPacket packet = new DatagramPacket(bytes, bytes.length, getBroadcastAddress(), DISCOVERY_PORT);
socket.send(packet);
}
/**
* Listen on socket for responses, timing out after timeout
*
* @param socket socket on which the announcement request was sent
* @throws IOException
*/
private void listenForResponses(DatagramSocket socket) throws IOException {
byte[] buf = new byte[64];
try {
while (true) {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.setSoTimeout((int) timeout);
socket.receive(packet);
log.debug("Received response from <<" + packet.getAddress().getHostAddress() + ">> " + new String(packet.getData()));
if (!isLocalIP(packet.getAddress())) {
final DiscoveryResponse response = (DiscoveryResponse) serializer.parse(packet.getData());
NetworkDeviceInfo deviceInfo = response.getDeviceInfo();
deviceInfo.setIp(packet.getAddress().getHostAddress());
log.info("Found Device: " + deviceInfo);
if (deviceName == null || "*".equals(deviceName) || deviceName.equals(deviceInfo.getName())) {
devices.add(deviceInfo);
notifyListeners(deviceInfo);
}
if (deviceName != null && deviceInfo.getName().equals(deviceName)) {
break;
}
}
}
} catch (SocketTimeoutException e) {
log.debug("Scan timeout");
} catch (Exception e) {
log.error(e.getMessage(), e);
}
if (this.closeOnFinish) {
socket.close();
}
}
/**
* Calculate the broadcast IP we need to send the packet along. If we send it
* to 255.255.255.255, it never gets sent. I guess this has something to do
* with the mobile network not wanting to do broadcast.
*/
private InetAddress getBroadcastAddress() throws IOException {
System.setProperty("java.net.preferIPv4Stack", "true");
InetAddress broadcast = null;
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface network = interfaces.nextElement();
if (network.isLoopback() || !network.isUp())
continue;
for (InterfaceAddress interfaceAddress : network.getInterfaceAddresses()) {
broadcast = interfaceAddress.getBroadcast();
if (broadcast == null)
continue;
break;
}
}
return broadcast;
}
private boolean isLocalIP(InetAddress address) throws IOException {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface network = interfaces.nextElement();
if (network.isLoopback() || !network.isUp()) {
continue;
}
Enumeration<InetAddress> inetAddresses = network.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress netAddress = inetAddresses.nextElement();
if (address.getHostAddress().equals(netAddress.getHostAddress()))
return true;
}
}
return false;
}
private void notifyListeners(NetworkDeviceInfo deviceInfo) {
if (listener != null) listener.onDiscoveryDevice(deviceInfo);
}
public Set<NetworkDeviceInfo> getDevices() {
return devices;
}
}
| [
"[email protected]"
]
| |
2fffe458c8f7027cb19e548ca0ff752111d9330f | 5456663349ace1b3553735c5178f806e7f08b765 | /algorithm/src/com/sort/Sorts.java | b1710f43932adc5b81cb4795191680c7664d5d1d | []
| no_license | zhuweiwu/J2SE | 6753d0846962dd74a35751aecd001ef922df4d22 | 9b110b36491ab68d571ff6a4332bd45be7e98f6f | refs/heads/master | 2021-01-20T04:11:52.097207 | 2014-03-17T05:40:50 | 2014-03-17T05:40:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,384 | java | package com.sort;
/**
* Util class of sort: bubblesort, insertsort, selectsort
* @author zhuwei wu
* 2014-2-21
*/
public class Sorts {
private static int[] arrTemp;
/**
* Bubble Sort
*
* O(N^2)
*
* @param arr[]
* @return arr[]
*/
public static int[] bubbleSort(int[] arr){
arrTemp = arr.clone();
int len = arrTemp.length;
int out, in;
for(out=len-1; out>1; out--){ //outer loop from arr[n] to arr[2]
for(in=0; in<out; in++){ //inter loop from arr[0] to arr[n-1]
if(arrTemp[in]>arrTemp[in+1]){
// int temp = arrTemp[in];
// arrTemp[in] = arrTemp[in+1];
// arrTemp[in+1] = temp;
swap(in, in+1);
}
}
}
return arrTemp;
}
/**
* Select Sort: less swap times than bubble sort
*
* O(N^2)
*
* @param arr[]
* @return arr[]
*/
public static int[] selectSort(int[] arr){
arrTemp = arr.clone();
int len = arrTemp.length;
int out, in, min;
for(out=0; out<len-1; out++){//outloop from arr[0] to arr[n-1]
min = out;
for(in=out+1; in<len; in++){ //interloop from arr[out+1] to arr[n]
if(arrTemp[in] < arrTemp[min]){
min = in;
}
}
// int temp = arrTemp[min];
// arrTemp[min] = arrTemp[out];
// arrTemp[out] = temp;
swap(min, out);
}
return arrTemp;
}
/**
* Insert Sort:
* Advantage: twice fast than Bubble Sort, somewhat faster than select sort in normal situation
* Disadvantage: inverse arr will run no faster.
*
* O(N^2)
*
* @param arr[]
* @return arr[]
*/
public static int[] insertSort(int[] arr){
arrTemp = arr.clone();
int len = arrTemp.length;
int in, out;
for(out=1; out<len; out++){
int temp = arrTemp[out];
in = out;
while(in>0 && arrTemp[in-1] >= temp){
arrTemp[in] = arrTemp[in-1];
--in;
}
arrTemp[in] = temp;
}
return arrTemp;
}
/**
* Binary Insert Sort:
* when the length is LARGE, it will decrease the compare times
*
* O(N^2)
* @param arr
* @return
*/
public static int[] binInsertSort(int[] arr){
arrTemp = arr.clone();
for (int i = 0; i < arrTemp.length; i++) {
int temp = arrTemp[i];
int left = 0;
int right = i-1;
int mid = 0;
while(left<=right){
mid = (left+right)/2;
if(temp<arrTemp[mid]){
right = mid-1;
}else{
left = mid+1;
}
}
for (int j = i-1; j >= left; j--) {
arrTemp[j+1] = arrTemp[j];
}
if(left != i){
arrTemp[left] = temp;
}
}
return arrTemp;
}
/**
* Shell Sort:
* improve insert sort
*
* O(nlogn)
*
* @param arr
* @return
*/
public static int[] shellSort(int[] arr){
arrTemp = arr.clone();
int dis = arrTemp.length;
while(true){
dis = dis/2;
for(int x=0; x<dis; x++){
for(int i=x+dis; i<arrTemp.length; i=i+dis){
int temp = arrTemp[i];
int j;
for(j=i-dis; j>=0 && arrTemp[j]>temp; j=j-dis){
arrTemp[j+dis] = arrTemp[j];
}
arrTemp[j+dis] = temp;
}
}
if(dis == 1){
break;
}
}
return arrTemp;
}
/**
* Heap Sort
*
* O(n log n)
* @param arr
* @return
*/
public static int[] heapSort(int[] arr){
arrTemp = arr.clone();
if(arrTemp == null || arrTemp.length <= 1){
return arrTemp;
}
buildMaxHeap(arrTemp);
for(int i=arrTemp.length-1; i>=1; i--){
swap(i, 0);
maxHeap(arrTemp, i, 0);
}
return arrTemp;
}
private static void buildMaxHeap(int[] arr){
if(arr == null || arr.length <= 1){
return;
}
int half = arr.length /2;
for(int i=half; i>=0; i--){
maxHeap(arr, arrTemp.length, i);
}
}//a method of heap sort
private static void maxHeap(int[] arr, int heapSize, int index){
int left = index * 2 + 1;
int right = index * 2 + 2;
int largest = index;
if (left < heapSize && arrTemp[left] > arrTemp[index]) {
largest = left;
}
if (right < heapSize && arrTemp[right] > arrTemp[largest]) {
largest = right;
}
if (index != largest) {
swap(index, largest);
maxHeap(arrTemp, heapSize, largest);
}
}// a method of heap sort
/**
* Quick Sort
*
* O(n log n)
*
* An Example of Quick Sort:
*
*0--- 57 68 59 52 72 28 96 33 24 19
* |ref |
*1--- 19 68 59 52 72 28 96 33 24 57
* | |
*2--- 19 57 59 52 72 28 96 33 24 68
* | |
*3--- 19 24 59 52 72 28 96 33 57 68
* | |
*4--- 19 24 57 52 72 28 96 33 59 68
* | |
*5--- 19 24 33 52 72 28 96 57 59 68
* | |
*6--- 19 24 33 52 72 28 96 57 59 68
* | |
*7--- 19 24 33 52 57 28 96 72 59 68
* | |
*8---[19 24 33 52 28] 57 [96 72 59 68]
* part1 part2
*
* @param arr
* @return
*/
public static int[] quickSort(int[] arr){
arrTemp = arr.clone();
if(arrTemp.length <= 1 || arrTemp == null){
return arrTemp;
}
divideArr4QuickSort(arrTemp, 0, arrTemp.length-1);
return arrTemp;
}
private static void divideArr4QuickSort(int[] arr, int low, int high){
if(low < high){
int mid = getMiddle(arr, low, high);
divideArr4QuickSort(arr,0,mid-1);
divideArr4QuickSort(arr, mid+1, high);
}
}//a divide method of quick sort
private static int getMiddle(int[] arr, int low, int high){
int temp = arr[low];
while(low < high){
while(low < high && arr[high] >= temp){
high--;
}
arr[low] = arr[high];
while(low < high && arr[low] <= temp){
low++;
}
arr[high] = arr[low];
}
arr[low] = temp;
return low;
}//a method of quick sort
/**
* Merge Sort:
*
* O(n log n)
*
* @param arr
* @return
*/
public static int[] mergeSort(int[] arr){
arrTemp = arr.clone();
if(arrTemp.length <= 1 || arrTemp == null){
return arrTemp;
}
divideArr4MergeSort(arrTemp, 0, arrTemp.length-1);
return arrTemp;
}
private static void divideArr4MergeSort(int[] arr, int left, int right){
if(left < right){
int middle = (left + right)/2;
divideArr4MergeSort(arr, left, middle);
divideArr4MergeSort(arr, middle+1, right);
merge(arr, left, middle, right);
}
}// a method of merge sort
private static void merge(int[] arr, int left, int middle, int right){
int[] tmpArr = new int[arr.length];
int mid = middle + 1;
int tmp = left;
int third = left;
while(left<=middle && right>=mid){
if(arr[left]<=arr[mid]){
tmpArr[third++] = arr[left++];
}else {
tmpArr[third++] = arr[mid++];
}
}
while(left <= middle){
tmpArr[third++] = arr[left++];
}
while(mid <= right){
tmpArr[third++] = arr[mid++];
}
while(tmp <= right){
arr[tmp] = tmpArr[tmp++];
}
}// a method of merge sort
private static void swap(int index1, int index2){
int temp = arrTemp[index1];
arrTemp[index1] = arrTemp[index2];
arrTemp[index2] = temp;
}
}
| [
"[email protected]"
]
| |
779f4d64d113888602cfa9ad27f38b91cc04fd30 | baba7ae4f32f0e680f084effcd658890183e7710 | /MutationFramework/muJava/src/mujava/op/basic/Arithmetic_OP.java | b9e7c5733ad7bed2b4c452ca31630bf74545e3d2 | [
"Apache-2.0"
]
| permissive | TUBS-ISF/MutationAnalysisForDBC-FormaliSE21 | 75972c823c3c358494d2a2e9ec12e0a00e26d771 | de825bc9e743db851f5ec1c5133dca3f04d20bad | refs/heads/main | 2023-04-22T21:29:28.165271 | 2021-05-17T07:43:22 | 2021-05-17T07:43:22 | 368,096,901 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,028 | java | /**
* Copyright (C) 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package src.mujava.op.basic;
import openjava.mop.*;
import openjava.ptree.*;
/**
* <p> </p>
* @author Yu-Seung Ma
* @version 1.0
*/
public class Arithmetic_OP extends MethodLevelMutator
{
public Arithmetic_OP(FileEnvironment file_env, CompilationUnit comp_unit)
{
super( file_env, comp_unit );
}
/**
* Determine whether a given expression is of arithmetic type
* @param p
* @return
* @throws ParseTreeException
*/
public boolean isArithmeticType(Expression p) throws ParseTreeException
{
OJClass type = getType(p);
if ( type == OJSystem.INT || type == OJSystem.DOUBLE || type == OJSystem.FLOAT
|| type == OJSystem.LONG || type == OJSystem.SHORT
|| type == OJSystem.CHAR || type == OJSystem.BYTE )
{
return true;
}
return false;
}
/**
* Determine whether a given expression has a binary arithmetic operator
* @param p
* @return
* @throws ParseTreeException
*/
public boolean hasBinaryArithmeticOp( BinaryExpression p ) throws ParseTreeException
{
int op_type = p.getOperator();
if ( (op_type == BinaryExpression.TIMES) || (op_type == BinaryExpression.DIVIDE)
|| (op_type == BinaryExpression.MOD) || (op_type == BinaryExpression.PLUS)
|| (op_type == BinaryExpression.MINUS))
return true;
else
return false;
}
}
| [
"[email protected]"
]
| |
435118136dd86b17f3294bc32b6d02fcc02d5c98 | f92ef4d17785c8570c124116ce2cba1f5091503c | /src/test/java/comparatorComparable/Student2.java | 038aca323618be6b9e1f37d1c2b122ade2979e20 | []
| no_license | Qhubaib/SeleniumJavaInterviewExtentReportsCode | ea27e9f2d987cdabade4277ed6a4315353e2ada6 | 8bdc23cbe0efbefc61b2e948c11086bd7f9c978f | refs/heads/master | 2023-05-13T16:31:39.465293 | 2020-02-02T19:05:40 | 2020-02-02T19:05:40 | 228,238,642 | 0 | 0 | null | 2023-05-09T18:17:43 | 2019-12-15T19:24:08 | Java | UTF-8 | Java | false | false | 330 | java | package comparatorComparable;
public class Student2 {
int id;
String name;
int rollno;
public Student2(int id,String name,int rollno)
{
this.id=id;
this.name=name;
this.rollno=rollno;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", rollno=" + rollno + "]";
}
}
| [
"[email protected]"
]
| |
bd018ef17c6f86104e8bbb6a451ac2ae1f306c4a | 0337340f8044e8c8b6aa677a4c0bd751ffbe33ca | /src/main/java/ivan/vatlin/http/services/DemoService.java | 61d6ec3c23f7967d21785476caa9d4fb1aa405bc | []
| no_license | MadVodka/HTTP | 2a4b9a5407a8394eb10cbb4ad8edbf174b1c68ed | e819af763016df87125154116fe455a99636a206 | refs/heads/master | 2020-07-18T23:52:34.525266 | 2019-09-04T14:27:08 | 2019-09-04T14:27:08 | 206,337,537 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 85 | java | package ivan.vatlin.http.services;
public interface DemoService {
void run();
}
| [
"[email protected]"
]
| |
5bc8da8364360a55f9ff11a8472af83f235b9ea0 | f7248c3f414b326fbd18e934a29c7d306e4bb878 | /08-CollectionsStreamsFilters-01/src/main/java/com/example/lambda/robocallexample/RoboCallTest01.java | 8d2092635b8d306837a372e2deac66c0681c94e5 | []
| no_license | tlacuache987/java-ocp-01 | 839d84893e492d00f3eca2bec23a5a1ac2e5396c | 24a13a2f81a6470e1c600de3c34a39264c9296e5 | refs/heads/master | 2020-08-21T20:54:06.127049 | 2019-11-27T04:24:32 | 2019-11-27T04:24:32 | 216,243,050 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 555 | java | package com.example.lambda.robocallexample;
import java.util.List;
/**
*
* @author MikeW
*/
public class RoboCallTest01 {
public static void main(String[] args) {
List<Person> pl = Person.createShortList();
RoboCall01 robo = new RoboCall01();
System.out.println("\n==== RoboCall Test 01 ====");
System.out.println("\n=== Calling all Drivers ===");
robo.callDrivers(pl);
System.out.println("\n=== Emailing all Draftees ===");
robo.emailDraftees(pl);
System.out.println("\n=== Mail all Pilots ===");
robo.mailPilots(pl);
}
}
| [
"[email protected]"
]
| |
b0621f0081dd216dc439fc2776b0d482069aaf8f | b2c5d05159ff8f4f73581721750c2518bb31ce00 | /src/com/sevogle/DateConverter.java | 4945c55504c2cdd016b7925c17c97d8803c9be86 | []
| no_license | hivepoint/log-tool | baa23b11666edd676e9349884057f9a9f0034cdb | 36fd77377f8c0f8f0f09e53f3960d3ac6554b366 | refs/heads/master | 2022-08-12T06:08:33.663600 | 2014-01-26T19:44:24 | 2014-01-26T19:44:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,088 | java | package com.sevogle;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.Date;
import java.text.DateFormat;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class DateConverter extends JFrame {
private static final long serialVersionUID = 1L;
/**
* @param args
*/
public static void main(String[] args) {
DateConverter dateConverter = new DateConverter();
dateConverter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
DateConverter() {
Container container = getContentPane();
container.setLayout(new FlowLayout());
JLabel lblDate = new JLabel("Date:");
container.add(lblDate);
final JTextField txtDateLong = new JTextField(25);
container.add(txtDateLong);
final JTextField lblResult = new JTextField("RESULT", 25);
lblResult.setEditable(false);
container.add(lblResult);
txtDateLong.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
convert(txtDateLong, lblResult);
}
});
txtDateLong.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
convert(txtDateLong, lblResult);
}
@Override
public void keyReleased(KeyEvent e) {
convert(txtDateLong, lblResult);
}
@Override
public void keyPressed(KeyEvent e) {
convert(txtDateLong, lblResult);
}
});
txtDateLong.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
convert(txtDateLong, lblResult);
}
@Override
public void mousePressed(MouseEvent e) {
convert(txtDateLong, lblResult);
}
@Override
public void mouseExited(MouseEvent e) {
convert(txtDateLong, lblResult);
}
@Override
public void mouseEntered(MouseEvent e) {
convert(txtDateLong, lblResult);
}
@Override
public void mouseClicked(MouseEvent e) {
convert(txtDateLong, lblResult);
}
});
this.setSize(400, 100);
setVisible(true);
}
protected void convert(final JTextField txtDateLong, final JTextField lblResult) {
String txt = txtDateLong.getText();
try {
long parseLong = Long.parseLong(txt);
lblResult.setText(DateFormat.getDateTimeInstance().format(new Date(parseLong)));
} catch (NumberFormatException e1) {
lblResult.setText(e1.getMessage());
}
}
}
| [
"[email protected]"
]
| |
62e5436d7af78663a2a0d1bf083a6f91ad362d6d | a40b12b572c665a5fd1f805723173f43798a6c3d | /src/main/java/com/gabrielduarte/designpatterns/discount/DiscountToBudgetWithMoreThanFiveItems.java | e0f18efe5543714f1f67df86fd802cbf077c8686 | []
| no_license | gabrielmduarte/design-patterns | deb0fa57c0c6aa474ca89cf53afe8034f57a0275 | fdd1a84550dedbce88c048fb5185319b8d8f9621 | refs/heads/master | 2023-03-22T05:39:00.760434 | 2021-03-20T04:18:33 | 2021-03-20T04:18:33 | 349,612,234 | 0 | 0 | null | 2021-03-20T04:18:34 | 2021-03-20T03:00:36 | Java | UTF-8 | Java | false | false | 539 | java | package com.gabrielduarte.designpatterns.discount;
import com.gabrielduarte.designpatterns.domain.Budget;
import java.math.BigDecimal;
public class DiscountToBudgetWithMoreThanFiveItems extends Discount {
public DiscountToBudgetWithMoreThanFiveItems(Discount next) {
super(next);
}
public BigDecimal calculate(final Budget budget) {
if (budget.getNumberOfItems() > 5) {
return budget.getValue().multiply(BigDecimal.valueOf(0.1));
}
return getNext().calculate(budget);
}
}
| [
"[email protected]"
]
| |
e1c0ef0439e447690b5fd0163fa4f770f38a6257 | f21b12b2a515bfd2723372ff74b67ce9a73599ec | /tcc-dto-ddo/src/main/java/org/ihtsdo/otf/tcc/dto/JaxbForDto.java | a87f0f31eb03e0b6823476441fc3484aba898ade | []
| no_license | Apelon-VA/va-ochre | 44d0ee08a9bb6bb917efb36d8ba9093bad9fb216 | 677355de5a2a7f25fb59f08182633689075c7b93 | refs/heads/develop | 2020-12-24T14:00:41.848798 | 2015-10-01T07:20:00 | 2015-10-01T07:20:00 | 33,519,478 | 2 | 1 | null | 2015-06-26T14:14:18 | 2015-04-07T03:18:28 | Java | UTF-8 | Java | false | false | 8,610 | java | package org.ihtsdo.otf.tcc.dto;
import org.ihtsdo.otf.tcc.dto.component.TtkComponentChronicle;
import org.ihtsdo.otf.tcc.dto.component.TtkRevision;
import org.ihtsdo.otf.tcc.dto.component.TtkStamp;
import org.ihtsdo.otf.tcc.dto.component.attribute.TtkConceptAttributesChronicle;
import org.ihtsdo.otf.tcc.dto.component.attribute.TtkConceptAttributesRevision;
import org.ihtsdo.otf.tcc.dto.component.description.TtkDescriptionChronicle;
import org.ihtsdo.otf.tcc.dto.component.description.TtkDescriptionRevision;
import org.ihtsdo.otf.tcc.dto.component.identifier.TtkIdentifier;
import org.ihtsdo.otf.tcc.dto.component.identifier.TtkIdentifierLong;
import org.ihtsdo.otf.tcc.dto.component.identifier.TtkIdentifierString;
import org.ihtsdo.otf.tcc.dto.component.identifier.TtkIdentifierUuid;
import org.ihtsdo.otf.tcc.dto.component.media.TtkMediaChronicle;
import org.ihtsdo.otf.tcc.dto.component.media.TtkMediaRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.logicgraph.TtkLogicGraphMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.logicgraph.TtkLogicGraphRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_array_of_bytearray.TtkRefexArrayOfByteArrayMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_array_of_bytearray.TtkRefexArrayOfByteArrayRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_boolean.TtkRefexBooleanMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_boolean.TtkRefexBooleanRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_int.TtkRefexIntMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_int.TtkRefexIntRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_long.TtkRefexLongMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_long.TtkRefexLongRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_member.TtkRefexMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_member.TtkRefexRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_string.TtkRefexStringMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_string.TtkRefexStringRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid.TtkRefexUuidMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid.TtkRefexUuidRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_boolean.TtkRefexUuidBooleanMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_boolean.TtkRefexUuidBooleanRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_float.TtkRefexUuidFloatMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_float.TtkRefexUuidFloatRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_int.TtkRefexUuidIntMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_long.TtkRefexUuidLongMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_long.TtkRefexUuidLongRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_string.TtkRefexUuidStringMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_string.TtkRefexUuidStringRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_uuid.TtkRefexUuidUuidMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_uuid.TtkRefexUuidUuidRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_uuid_string.TtkRefexUuidUuidStringMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_uuid_string.TtkRefexUuidUuidStringRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_uuid_uuid.TtkRefexUuidUuidUuidMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_uuid_uuid.TtkRefexUuidUuidUuidRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_uuid_uuid_float.TtkRefexUuidUuidUuidFloatMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_uuid_uuid_float.TtkRefexUuidUuidUuidFloatRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_uuid_uuid_int.TtkRefexUuidUuidUuidIntMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_uuid_uuid_int.TtkRefexUuidUuidUuidIntRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_uuid_uuid_long.TtkRefexUuidUuidUuidLongMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_uuid_uuid_long.TtkRefexUuidUuidUuidLongRevision;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_uuid_uuid_string.TtkRefexUuidUuidUuidStringMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refex.type_uuid_uuid_uuid_string.TtkRefexUuidUuidUuidStringRevision;
import org.ihtsdo.otf.tcc.dto.component.refexDynamic.TtkRefexDynamicMemberChronicle;
import org.ihtsdo.otf.tcc.dto.component.refexDynamic.TtkRefexDynamicRevision;
import org.ihtsdo.otf.tcc.dto.component.relationship.TtkRelationshipChronicle;
import org.ihtsdo.otf.tcc.dto.component.relationship.TtkRelationshipRevision;
import org.ihtsdo.otf.tcc.dto.taxonomy.Taxonomy;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
import java.io.DataOutputStream;
/**
* Created by kec on 2/15/15.
*/
public class JaxbForDto {
private static JAXBContext singleton;
public static JAXBContext get() throws JAXBException {
if (singleton == null) {
singleton = JAXBContext.newInstance(
TtkConceptChronicle.class,
TtkStamp.class,
TtkRevision.class,
TtkComponentChronicle.class,
TtkConceptAttributesChronicle.class,
TtkConceptAttributesRevision.class,
TtkDescriptionChronicle.class,
TtkDescriptionRevision.class,
TtkIdentifier.class,
TtkIdentifierLong.class,
TtkIdentifierString.class,
TtkIdentifierUuid.class,
TtkMediaChronicle.class,
TtkMediaRevision.class,
TtkLogicGraphMemberChronicle.class,
TtkLogicGraphRevision.class,
TtkRefexArrayOfByteArrayMemberChronicle.class,
TtkRefexArrayOfByteArrayRevision.class,
TtkRefexBooleanMemberChronicle.class,
TtkRefexBooleanRevision.class,
TtkRefexIntMemberChronicle.class,
TtkRefexIntRevision.class,
TtkRefexLongMemberChronicle.class,
TtkRefexLongRevision.class,
TtkRefexMemberChronicle.class,
TtkRefexRevision.class,
TtkRefexStringMemberChronicle.class,
TtkRefexStringRevision.class,
TtkRefexUuidMemberChronicle.class,
TtkRefexUuidRevision.class,
TtkRefexUuidBooleanMemberChronicle.class,
TtkRefexUuidBooleanRevision.class,
TtkRefexUuidFloatMemberChronicle.class,
TtkRefexUuidFloatRevision.class,
TtkRefexUuidIntMemberChronicle.class,
TtkRefexUuidLongMemberChronicle.class,
TtkRefexUuidLongRevision.class,
TtkRefexUuidStringMemberChronicle.class,
TtkRefexUuidStringRevision.class,
TtkRefexUuidUuidMemberChronicle.class,
TtkRefexUuidUuidRevision.class,
TtkRefexUuidUuidStringMemberChronicle.class,
TtkRefexUuidUuidStringRevision.class,
TtkRefexUuidUuidUuidMemberChronicle.class,
TtkRefexUuidUuidUuidRevision.class,
TtkRefexUuidUuidUuidStringMemberChronicle.class,
TtkRefexUuidUuidUuidStringRevision.class,
TtkRefexUuidUuidUuidFloatMemberChronicle.class,
TtkRefexUuidUuidUuidFloatRevision.class,
TtkRefexUuidUuidUuidIntMemberChronicle.class,
TtkRefexUuidUuidUuidIntRevision.class,
TtkRefexUuidUuidUuidLongMemberChronicle.class,
TtkRefexUuidUuidUuidLongRevision.class,
TtkRefexDynamicMemberChronicle.class,
TtkRefexDynamicRevision.class,
TtkRelationshipChronicle.class,
TtkRelationshipRevision.class,
Wrapper.class
);
}
return singleton;
}
}
| [
"[email protected]"
]
| |
424a2ff6327356947eb05239f16b529695877574 | 12f790d6b841fdcd93d10ccfc1274fd746743ed1 | /PosApplication/src/org/surzyn/posApplication/servlet/LoginServlet.java | 8afa157477d85bdb0ab7abc721dfc2b693cd6ff3 | []
| no_license | airensurzyn/PosApplication | a2d2f6c83e04ada842c619e5cd6cc153ab506192 | 49bed5fe114427030177ef10b2b0a3207b242acd | refs/heads/master | 2021-05-29T19:21:56.095168 | 2015-11-06T17:01:48 | 2015-11-06T17:01:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,122 | java | package org.surzyn.posApplication.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.surzyn.posApplication.service.LoginService;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("userId");
String password = request.getParameter("password");
LoginService ls = new LoginService();
request.getSession().setAttribute("user", username);
if(ls.authenticate(username, password)){
response.sendRedirect("tableView.jsp");
return;
}else{
response.sendRedirect("login.jsp");
return;
}
}
}
| [
"[email protected]"
]
| |
37a2211ffefe84462897af171059fac543d3d14c | e4aea93f2988e2cf1be4f96a39f6cc3328cbbd50 | /src/com/flagleader/builder/dialogs/d/y.java | 3e4220a5a9fd81fbff25544385dcc01fd51a91b6 | []
| no_license | lannerate/ruleBuilder | 18116282ae55e9d56e9eb45d483520f90db4a1a6 | b5d87495990aa1988adf026366e92f7cbb579b19 | refs/heads/master | 2016-09-05T09:13:43.879603 | 2013-11-10T08:32:58 | 2013-11-10T08:32:58 | 14,231,127 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,622 | java | package com.flagleader.builder.dialogs.d;
import com.flagleader.builder.widget.p;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
class y extends MouseAdapter
{
y(v paramv)
{
}
public void mouseDoubleClick(MouseEvent paramMouseEvent)
{
if (v.b(this.a) != null)
{
Point localPoint = new Point(paramMouseEvent.x, paramMouseEvent.y);
v.a(this.a, v.a(this.a).getItem(localPoint));
if (v.c(this.a) == null)
return;
for (int i = 1; i <= 2; i++)
{
Rectangle localRectangle = v.c(this.a).getBounds(i);
if (!localRectangle.contains(localPoint))
continue;
Text localText = new p().a(v.a(this.a), 4);
localText.setText(v.c(this.a).getText(i));
v.a(this.a, v.c(this.a), localText, v.d(this.a), i);
localText.setFocus();
}
}
}
public void mouseDown(MouseEvent paramMouseEvent)
{
if (paramMouseEvent.button == 1)
{
Point localPoint = new Point(paramMouseEvent.x, paramMouseEvent.y);
TableItem localTableItem = v.a(this.a).getItem(localPoint);
if (localTableItem == null)
v.a(this.a).setSelection(new TableItem[0]);
}
}
}
/* Location: D:\Dev_tools\ruleEngine\rbuilder.jar
* Qualified Name: com.flagleader.builder.dialogs.d.y
* JD-Core Version: 0.6.0
*/ | [
"[email protected]"
]
| |
5a2614ba3839e79b4ec51b24cb8b9aa6ec22c6f5 | 479aae993925074143c2935c5a2d8017bdf259f6 | /hdfstest/src/main/java/com/wyd/hdfs/rackaware/MyRackAware.java | 49ce619231a969a6c0ab80056fe828588337b0b5 | []
| no_license | wyd90/hadooptest | c9595bfa2617b9ab41d78565eea8223d582bf189 | 1223c71f3902cd766e3fe1128d6940aec4edc7a7 | refs/heads/master | 2022-06-25T23:15:42.395300 | 2019-06-07T16:07:49 | 2019-06-07T16:07:49 | 190,768,112 | 0 | 0 | null | 2022-06-21T01:14:41 | 2019-06-07T15:34:47 | Java | UTF-8 | Java | false | false | 1,820 | java | package com.wyd.hdfs.rackaware;
import org.apache.hadoop.net.DNSToSwitchMapping;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MyRackAware implements DNSToSwitchMapping {
public List<String> resolve(List<String> list) {
List<String> names = new ArrayList<String>();
try {
FileWriter fw = new FileWriter("/root/rackaware.txt",true);
for(String str : list){
System.out.println(str);
fw.write(str);
if("192.168.56.101".equals(str)){
names.add("/rack1/node1");
} else if("192.168.56.102".equals(str)) {
names.add("/rack1/node2");
} else if("192.168.56.103".equals(str)){
names.add("/rack2/node3");
} else if("192.168.56.104".equals(str)){
names.add("/rack2/node4");
} else if("192.168.56.105".equals(str)){
names.add("/rack3/node5");
} else if("node1".equals(str)){
names.add("/rack1/node1");
}else if("node2".equals(str)) {
names.add("/rack1/node2");
} else if("node3".equals(str)){
names.add("/rack2/node3");
} else if("node4".equals(str)){
names.add("/rack2/node4");
} else if("node5".equals(str)){
names.add("/rack3/node5");
}
}
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
return names;
}
public void reloadCachedMappings() {
}
public void reloadCachedMappings(List<String> list) {
}
}
| [
"[email protected]"
]
| |
1053d64c64e091cb352b1548ef62c248d2092c80 | 9b9c3236cc1d970ba92e4a2a49f77efcea3a7ea5 | /L2J_Mobius_CT_2.4_Epilogue/java/org/l2jmobius/gameserver/model/skills/SkillChannelizer.java | 73e3a0c179b08e05fd822b14bcab516eb1f745f8 | []
| no_license | BETAJIb/ikol | 73018f8b7c3e1262266b6f7d0a7f6bbdf284621d | f3709ea10be2d155b0bf1dee487f53c723f570cf | refs/heads/master | 2021-01-05T10:37:17.831153 | 2019-12-24T22:23:02 | 2019-12-24T22:23:02 | 240,993,482 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,850 | java | /*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.l2jmobius.gameserver.model.skills;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.l2jmobius.commons.concurrent.ThreadPool;
import org.l2jmobius.gameserver.data.xml.impl.SkillData;
import org.l2jmobius.gameserver.enums.ShotType;
import org.l2jmobius.gameserver.geoengine.GeoEngine;
import org.l2jmobius.gameserver.model.WorldObject;
import org.l2jmobius.gameserver.model.actor.Creature;
import org.l2jmobius.gameserver.model.actor.instance.PlayerInstance;
import org.l2jmobius.gameserver.network.SystemMessageId;
import org.l2jmobius.gameserver.network.serverpackets.MagicSkillLaunched;
import org.l2jmobius.gameserver.util.Util;
/**
* Skill Channelizer implementation.
* @author UnAfraid
*/
public class SkillChannelizer implements Runnable
{
private static final Logger LOGGER = Logger.getLogger(SkillChannelizer.class.getName());
private final Creature _channelizer;
private List<Creature> _channelized;
private Skill _skill;
private volatile ScheduledFuture<?> _task = null;
public SkillChannelizer(Creature channelizer)
{
_channelizer = channelizer;
}
public Creature getChannelizer()
{
return _channelizer;
}
public List<Creature> getChannelized()
{
return _channelized;
}
public boolean hasChannelized()
{
return _channelized != null;
}
public void startChanneling(Skill skill)
{
// Verify for same status.
if (isChanneling())
{
LOGGER.warning("Character: " + _channelizer + " is attempting to channel skill but he already does!");
return;
}
// Start channeling.
_skill = skill;
_task = ThreadPool.scheduleAtFixedRate(this, skill.getChannelingTickInitialDelay(), skill.getChannelingTickInterval());
}
public void stopChanneling()
{
// Verify for same status.
if (!isChanneling())
{
LOGGER.warning("Character: " + _channelizer + " is attempting to stop channel skill but he does not!");
return;
}
// Cancel the task and unset it.
_task.cancel(true);
_task = null;
// Cancel target channelization and unset it.
if (_channelized != null)
{
for (Creature creature : _channelized)
{
creature.getSkillChannelized().removeChannelizer(_skill.getChannelingSkillId(), _channelizer);
}
_channelized = null;
}
// unset skill.
_skill = null;
}
public Skill getSkill()
{
return _skill;
}
public boolean isChanneling()
{
return _task != null;
}
@Override
public void run()
{
if (!isChanneling())
{
return;
}
final Skill skill = _skill;
if (skill == null)
{
return;
}
try
{
if (skill.getMpPerChanneling() > 0)
{
// Validate mana per tick.
if (_channelizer.getCurrentMp() < skill.getMpPerChanneling())
{
if (_channelizer.isPlayer())
{
_channelizer.sendPacket(SystemMessageId.YOUR_SKILL_WAS_DEACTIVATED_DUE_TO_LACK_OF_MP);
}
_channelizer.abortCast();
return;
}
// Reduce mana per tick
_channelizer.reduceCurrentMp(skill.getMpPerChanneling());
}
// Apply channeling skills on the targets.
if (skill.getChannelingSkillId() > 0)
{
final Skill baseSkill = SkillData.getInstance().getSkill(skill.getChannelingSkillId(), 1);
if (baseSkill == null)
{
LOGGER.warning(getClass().getSimpleName() + ": skill " + skill + " couldn't find effect id skill: " + skill.getChannelingSkillId() + " !");
_channelizer.abortCast();
return;
}
final List<Creature> targetList = new ArrayList<>();
for (WorldObject chars : skill.getTargetList(_channelizer))
{
if (chars.isCreature())
{
targetList.add((Creature) chars);
((Creature) chars).getSkillChannelized().addChannelizer(skill.getChannelingSkillId(), _channelizer);
}
}
if (targetList.isEmpty())
{
return;
}
_channelized = targetList;
for (Creature creature : _channelized)
{
if (!Util.checkIfInRange(skill.getEffectRange(), _channelizer, creature, true))
{
continue;
}
else if (!GeoEngine.getInstance().canSeeTarget(_channelizer, creature))
{
continue;
}
else
{
final int maxSkillLevel = SkillData.getInstance().getMaxLevel(skill.getChannelingSkillId());
final int skillLevel = Math.min(creature.getSkillChannelized().getChannerlizersSize(skill.getChannelingSkillId()), maxSkillLevel);
if (skillLevel == 0)
{
continue;
}
final BuffInfo info = creature.getEffectList().getBuffInfoBySkillId(skill.getChannelingSkillId());
if ((info == null) || (info.getSkill().getLevel() < skillLevel))
{
final Skill channelingSkill = SkillData.getInstance().getSkill(skill.getChannelingSkillId(), skillLevel);
if (channelingSkill == null)
{
LOGGER.warning(getClass().getSimpleName() + ": Non existent channeling skill requested: " + skill);
_channelizer.abortCast();
return;
}
// Update PvP status
if (creature.isPlayable() && _channelizer.isPlayer() && channelingSkill.isBad())
{
((PlayerInstance) _channelizer).updatePvPStatus(creature);
}
channelingSkill.applyEffects(_channelizer, creature);
// Reduce shots.
if (skill.useSpiritShot())
{
_channelizer.setChargedShot(_channelizer.isChargedShot(ShotType.BLESSED_SPIRITSHOTS) ? ShotType.BLESSED_SPIRITSHOTS : ShotType.SPIRITSHOTS, false);
}
else
{
_channelizer.setChargedShot(ShotType.SOULSHOTS, false);
}
// Shots are re-charged every cast.
_channelizer.rechargeShots(skill.useSoulShot(), skill.useSpiritShot());
}
_channelizer.broadcastPacket(new MagicSkillLaunched(_channelizer, skill.getId(), skill.getLevel(), creature));
}
}
}
}
catch (Exception e)
{
LOGGER.log(Level.WARNING, "Error while channelizing skill: " + skill + " channelizer: " + _channelizer + " channelized: " + _channelized + "; ", e);
}
}
}
| [
"[email protected]"
]
| |
ff566a02fc2957edbfc421ad3f044e557707689d | 201dac5610e86ae4e5c10b6522d1cd912e70b8aa | /Gmall/gmall-parent/gmall-mbg/src/main/java/cn/wendaocp/gmall/cms/service/impl/TopicCategoryServiceImpl.java | 118644371555ffe6376f76fa9bc89bc8561af063 | []
| no_license | lq1990/myJava | e0506e25d562970b1ce93d23adcb514ae8641d06 | 6b8d200633744912dd93a6122d748e4d39d01541 | refs/heads/master | 2023-01-06T20:06:38.010795 | 2020-03-14T15:11:00 | 2020-03-14T15:11:00 | 163,006,968 | 0 | 0 | null | 2023-01-05T00:52:12 | 2018-12-24T16:17:58 | JavaScript | UTF-8 | Java | false | false | 564 | java | package cn.wendaocp.gmall.cms.service.impl;
import cn.wendaocp.gmall.cms.entity.TopicCategory;
import cn.wendaocp.gmall.cms.mapper.TopicCategoryMapper;
import cn.wendaocp.gmall.cms.service.TopicCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 话题分类表 服务实现类
* </p>
*
* @author lq
* @since 2020-02-24
*/
@Service
public class TopicCategoryServiceImpl extends ServiceImpl<TopicCategoryMapper, TopicCategory> implements TopicCategoryService {
}
| [
"[email protected]"
]
| |
d009bed4ca3d76ace11ece381a987d6141378f1b | 3b879697f95083083d0f14eba90301f52c6ed67f | /src/main/java/com/livingprogress/mentorme/remote/services/GeocodingService.java | 5abf36eccaa6f4283e5ceb603714dcc0999fd66e | []
| no_license | elfman/HPE-LP-MentorMe-Services | d0d1df3731259e6b81f5330f3fb31e3c2352f8fb | 43b078f42f47da6e647ea3ed582bdbd8d16420a1 | refs/heads/develop | 2021-01-21T20:38:14.144745 | 2017-05-25T14:00:32 | 2017-05-26T05:15:22 | 92,260,314 | 0 | 0 | null | 2017-05-24T06:57:14 | 2017-05-24T06:57:14 | null | UTF-8 | Java | false | false | 607 | java | package com.livingprogress.mentorme.remote.services;
import com.google.maps.model.GeocodingResult;
import com.livingprogress.mentorme.exceptions.MentorMeException;
/**
* The geocoding service.Implementation should be effectively thread-safe.
*/
public interface GeocodingService {
/**
* Convert provided address info into Longitude and Latitude Coordinates.
* @param address the address info.
* @return the geocoding result.
* @throws MentorMeException if any other error occurred during operation
*/
GeocodingResult geocode(String address) throws MentorMeException;
}
| [
"[email protected]"
]
| |
9bc1024e51fb8bcad66a9cefaa96b731fc5ad5ad | 032cc10183b1aac1010a6a57694ccad08bf12bc5 | /src/main/java/io/kielbi/sda/sda/jpa_17/entity/Skill.java | 92e40d705ce974b7c4ca74598ccb3ffbf37d6513 | []
| no_license | kielbi12/sda.jpa_17 | f551f2ab59264164df5c122ac1e2762f3d69c2ba | 9824a36d8caa533e3cf361ac448aa22eceecf564 | refs/heads/master | 2020-09-25T20:03:38.098765 | 2019-12-08T08:54:21 | 2019-12-08T08:54:21 | 226,078,168 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 622 | java | package io.kielbi.sda.sda.jpa_17.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import java.util.Objects;
@Entity
public class Skill extends AbstractEntity<Long> {
@Column(unique = true)
private String name;
public String getName() {
return name;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), name);
}
@Override
public String toString() {
return "Skill{" +
"name='" + name + '\'' +
'}';
}
public void setName(String name) {
this.name = name;
}
}
| [
"[email protected]"
]
| |
14e4b3fafc8d338d013fa49ae12e919719e48dce | a88880b41fa1b5ec51a7ec75643039b683edd25e | /client/src/main/java/com/endava/rest/util/CustomRequestFilter.java | 22220a38b3f8fd3e7658d906cb695fe3c586f27c | []
| no_license | aistoica/rest-framework | 6c270b4a051d5ed66369a6cb68bd004ad0ac041d | 60bd2a7b99d1adb936113136ba5578a3f5269bc4 | refs/heads/master | 2021-01-01T06:30:56.582057 | 2017-07-17T07:24:00 | 2017-07-17T07:24:00 | 97,446,655 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 926 | java | package com.endava.rest.util;
import com.endava.rest.BaseController;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
/**
* Created by astoica on 7/3/2015.
*/
public class CustomRequestFilter implements Filter {
private BaseController baseController;
public CustomRequestFilter(BaseController baseController) {
this.baseController = baseController;
}
@Override
public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
if(baseController.getUser() != null) {
requestSpec.header("user", baseController.getUser());
}
return ctx.next(requestSpec, responseSpec);
}
}
| [
"[email protected]"
]
| |
8f4462b5f907660a49916fa70ab8df951790b411 | 839f8cd7cb1a8bd81ee637edfee938ff1c8b8bd0 | /jib-core/src/main/java/com/google/cloud/tools/jib/builder/steps/PushLayersStep.java | 9c25dd4949e1044640609e49b4e9e2b774e7db67 | [
"Apache-2.0"
]
| permissive | gintautassulskus/jib | ee7a16bece5f45275470bf3a85972be659c8bae5 | fd05e74b18059c0d4e96c65390142728844a0880 | refs/heads/master | 2020-04-02T01:21:26.413283 | 2018-10-20T23:22:54 | 2018-10-20T23:22:54 | 153,851,221 | 0 | 0 | Apache-2.0 | 2018-10-19T23:15:44 | 2018-10-19T23:15:44 | null | UTF-8 | Java | false | false | 4,008 | java | /*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.cloud.tools.jib.builder.steps;
import com.google.cloud.tools.jib.async.AsyncStep;
import com.google.cloud.tools.jib.async.NonBlockingSteps;
import com.google.cloud.tools.jib.blob.BlobDescriptor;
import com.google.cloud.tools.jib.builder.TimerEventDispatcher;
import com.google.cloud.tools.jib.cache.CacheEntry;
import com.google.cloud.tools.jib.configuration.BuildConfiguration;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
class PushLayersStep
implements AsyncStep<ImmutableList<AsyncStep<PushBlobStep>>>,
Callable<ImmutableList<AsyncStep<PushBlobStep>>> {
private static final String DESCRIPTION = "Setting up to push layers";
private final BuildConfiguration buildConfiguration;
private final AuthenticatePushStep authenticatePushStep;
private final AsyncStep<? extends ImmutableList<? extends AsyncStep<? extends CacheEntry>>>
cacheEntryStep;
private final ListeningExecutorService listeningExecutorService;
private final ListenableFuture<ImmutableList<AsyncStep<PushBlobStep>>> listenableFuture;
PushLayersStep(
ListeningExecutorService listeningExecutorService,
BuildConfiguration buildConfiguration,
AuthenticatePushStep authenticatePushStep,
AsyncStep<? extends ImmutableList<? extends AsyncStep<? extends CacheEntry>>>
cacheEntryStep) {
this.listeningExecutorService = listeningExecutorService;
this.buildConfiguration = buildConfiguration;
this.authenticatePushStep = authenticatePushStep;
this.cacheEntryStep = cacheEntryStep;
listenableFuture =
Futures.whenAllSucceed(cacheEntryStep.getFuture()).call(this, listeningExecutorService);
}
@Override
public ListenableFuture<ImmutableList<AsyncStep<PushBlobStep>>> getFuture() {
return listenableFuture;
}
@Override
public ImmutableList<AsyncStep<PushBlobStep>> call() throws ExecutionException {
try (TimerEventDispatcher ignored =
new TimerEventDispatcher(buildConfiguration.getEventDispatcher(), DESCRIPTION)) {
ImmutableList<? extends AsyncStep<? extends CacheEntry>> cacheEntry =
NonBlockingSteps.get(cacheEntryStep);
// Constructs a PushBlobStep for each layer.
ImmutableList.Builder<AsyncStep<PushBlobStep>> pushBlobStepsBuilder = ImmutableList.builder();
for (AsyncStep<? extends CacheEntry> cachedLayerStep : cacheEntry) {
ListenableFuture<PushBlobStep> pushBlobStepFuture =
Futures.whenAllSucceed(cachedLayerStep.getFuture())
.call(() -> makePushBlobStep(cachedLayerStep), listeningExecutorService);
pushBlobStepsBuilder.add(() -> pushBlobStepFuture);
}
return pushBlobStepsBuilder.build();
}
}
private PushBlobStep makePushBlobStep(AsyncStep<? extends CacheEntry> cacheEntryStep)
throws ExecutionException {
CacheEntry cacheEntry = NonBlockingSteps.get(cacheEntryStep);
return new PushBlobStep(
listeningExecutorService,
buildConfiguration,
authenticatePushStep,
new BlobDescriptor(cacheEntry.getLayerSize(), cacheEntry.getLayerDigest()),
cacheEntry.getLayerBlob());
}
}
| [
"[email protected]"
]
| |
30b82aeb8568ef05901bfb0a4e10e759b96ff7a0 | f88ab225f8dda42410cb11bce2608a07aeeb7f35 | /recursion/Subhesh/Find_if_there_is_a_path_of_more_than_k_lengh.java | 0e73bc93b0a5c5d8220fe20e61d63ddce33aa183 | []
| no_license | arunnayan/IP_questionSet | 32b64c305edb88348c7626b2b42ab9d6529d4cb5 | 7a35951c5754ba4ca567c1357249f66e23fbe42c | refs/heads/master | 2023-03-16T18:38:51.385676 | 2019-08-01T12:10:35 | 2019-08-01T12:10:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,894 | java | package BackTracking;
import java.util.ArrayList;
import java.util.HashSet;
public class Find_if_there_is_a_path_of_more_than_k_lengh {
public static void main(String[] args) {
ArrayList<ArrayList<Pair>> list = new ArrayList<>();
ArrayList<Pair> list0 = new ArrayList<>();
list0.add(new Pair(1, 10));
list0.add(new Pair(3, 20));
ArrayList<Pair> list1 = new ArrayList<>();
list1.add(new Pair(0, 10));
list1.add(new Pair(2, 10));
ArrayList<Pair> list2 = new ArrayList<>();
list2.add(new Pair(1, 10));
list2.add(new Pair(3, 10));
ArrayList<Pair> list3 = new ArrayList<>();
list3.add(new Pair(0, 20));
list3.add(new Pair(2, 10));
ArrayList<Pair> list4 = new ArrayList<>();
list4.add(new Pair(3, 15));
list4.add(new Pair(5, 2));
list4.add(new Pair(6, 5));
ArrayList<Pair> list5 = new ArrayList<>();
list5.add(new Pair(4, 2));
list5.add(new Pair(6, 7));
ArrayList<Pair> list6 = new ArrayList<>();
list6.add(new Pair(5, 7));
list6.add(new Pair(4, 5));
list.add(list0);
list.add(list1);
list.add(list2);
list.add(list3);
list.add(list4);
list.add(list5);
list.add(list6);
boolean[] visited = new boolean[list.size()];
int src = 0;
visited[src] = true;
System.out.println(dfs(list, visited, src, 0, 59));
}
private static boolean dfs(ArrayList<ArrayList<Pair>> list, boolean[] visited, int src, int csf, int k) {
if (csf >= k) {
return true;
}
ArrayList<Pair> nbr = list.get(src);
for (int i = 0; i < nbr.size(); i++) {
Pair pair = nbr.get(i);
if (visited[pair.vtx] == false) {
visited[pair.vtx] = true;
boolean ans = dfs(list, visited, pair.vtx, csf + pair.wt, k);
visited[pair.vtx] = false;
if (ans == true) {
return true;
}
}
}
return false;
}
public static class Pair {
int vtx;
int wt;
public Pair(int vtx, int wt) {
this.vtx = vtx;
this.wt = wt;
}
}
}
| [
"[email protected]"
]
| |
8b3f51494908bbddde2eb0fed0590be3db990c9b | 71357831063be836bb0bde969902726cbc2e0419 | /lms/src/main/java/com/covalense/lms/dto/BookInfoBean.java | 0a42d93a3427fbe4e85ff9260b15e4b52852c904 | []
| no_license | ramesh1796/ELF-06June19-Covalanse-RameshY | 56f375d73647c3c47072447768d2a7fa8af1eefb | 60af6c20c37abfd732f57c7594cb1f22e6aa436f | refs/heads/master | 2022-12-24T15:07:31.536588 | 2019-07-14T12:15:22 | 2019-07-14T12:15:22 | 192,526,708 | 0 | 0 | null | 2022-12-15T23:49:16 | 2019-06-18T11:28:18 | Rich Text Format | UTF-8 | Java | false | false | 2,465 | java | package com.covalense.lms.dto;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonProperty;
@SuppressWarnings("serial")
//@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "user-id")
@Entity
@Table(name = "book_info")
public class BookInfoBean implements Serializable{
@Id
@JsonProperty(value = "book_id")
@Column(name="book_id")
private int bookId;
@JsonProperty(value = "book_name")
@Column(name="book_name")
private int bookName;
@JsonProperty(value = "catagory")
@Column(name="catagory")
private int catagory;
@JsonProperty(value = "author")
@Column(name="author")
private int author;
@JsonProperty(value = "publisher")
@Column(name="publisher")
private int publisher;
@JsonProperty(value = "price")
@Column(name="price")
private int price;
@JsonProperty(value = "edition")
@Column(name="edition")
private int edition;
@JsonProperty(value = "rating")
@Column(name="rating")
private int rating;
@JsonProperty(value = "language")
@Column(name="language")
private int language;
@JsonProperty(value = "no_of_copies")
@Column(name="no_of_copies")
private int noc;
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public int getBookName() {
return bookName;
}
public void setBookName(int bookName) {
this.bookName = bookName;
}
public int getCatagory() {
return catagory;
}
public void setCatagory(int catagory) {
this.catagory = catagory;
}
public int getAuthor() {
return author;
}
public void setAuthor(int author) {
this.author = author;
}
public int getPublisher() {
return publisher;
}
public void setPublisher(int publisher) {
this.publisher = publisher;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getEdition() {
return edition;
}
public void setEdition(int edition) {
this.edition = edition;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public int getLanguage() {
return language;
}
public void setLanguage(int language) {
this.language = language;
}
public int getNoc() {
return noc;
}
public void setNoc(int noc) {
this.noc = noc;
}
}
| [
"[email protected]"
]
| |
fe7abaca755728b117112f8109cbeb73d2aef40c | 34c641b52393f2f03887dc7d252344b689e8d213 | /src/com/Licht/_08/PredicateTest2.java | d21caa2afc728e835962beb5dfdaa2fb40512517 | []
| no_license | LichtMiao/Crazy-java | 8049fc51a97bab9d575abbbcd29f826908231216 | 434c7a7258bd45484ec6d7411c1238b3c83c0b4e | refs/heads/master | 2021-01-25T14:22:29.141290 | 2018-07-01T15:17:29 | 2018-07-01T15:17:29 | 123,686,958 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,330 | java | /*
*Predicate统计出现“疯狂”字符串的图书数量
*统计出现“Java”字符串的图书数量
*统计书名长度大于10的图书数量
*/
package com.Licht._08;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.function.Predicate;
public class PredicateTest2{
public static void main(String[] args){
//创建集合
Collection books = new HashSet();
books.add(new String("轻量级Java EE企业应用实战"));
books.add(new String("疯狂Java讲义"));
books.add(new String("疯狂iOS讲义"));
books.add(new String("疯狂Ajax讲义"));
books.add(new String("疯狂Android讲义"));
//传入三个Lamda表达式,其目标类型都是Predicate
System.out.println(calAll(books, ele -> ((String)ele).contains("疯狂")));
System.out.println(calAll(books, ele -> ((String)ele).contains("Java")));
System.out.println(calAll(books, ele -> ((String)ele).length() > 10));
}
//calAll()方法,使用Predicate判断每个集合元素是否满足特定条件
public static int calAll(Collection books, Predicate p){
int total = 0;
for (Object obj : books){
//使用Predicate的test()方法判断该对象是否满足Predicate指定条件
if(p.test(obj)){
total++;
}
}
return total;
}
} | [
"[email protected]"
]
| |
ce36590c5da108730f9de8229e4944da692da3ec | 7c0943e448e061d45d2cb23f5d231d7c0c2e4dcd | /ck-flow-client/src/main/java/com/yqkj/client/dto/request/deploy/DelopyRequest.java | a31946261bf19efd8f55f2ef6751bce2a84dc03e | []
| no_license | SCYangChao/ck-common-flow | ddf37c1cecf515013f886c48e765e0b5db514bbb | 8e57152d77666136142efa19dbd6f08abe420158 | refs/heads/master | 2022-07-23T01:44:52.940860 | 2019-12-02T01:30:36 | 2019-12-02T01:30:36 | 199,601,342 | 2 | 0 | null | 2022-07-07T23:54:43 | 2019-07-30T07:42:46 | JavaScript | UTF-8 | Java | false | false | 548 | java | package com.yqkj.client.dto.request.deploy;
import lombok.Data;
import java.io.Serializable;
/**
*
* class_name: DelopyRequest
* describe: do
* @author: [email protected]
* creat_date: 上午10:05
*
**/
@Data
public class DelopyRequest implements Serializable {
/**
* 系统编码
*/
private String sysCode;
/**
* 流程发布名称
*/
private String name;
/**
* 流程定义
*/
private String xml;
/**
* 流程功能描述
*/
private String describe;
}
| [
"[email protected]"
]
| |
e4e26f4d978aab9b2c5f25d8d83e74e915e5129d | 65419002c96b612fd62cc738d94fd86b6af5076e | /abstractfactory/src/main/java/product2/ImportFile.java | 6ab5c2aa7d0a0db16ba87d48a29cc333bb01cd76 | []
| no_license | Laishiji/designpattern | a37c1b2448880ee88d80e73697120cabba956f36 | ccafddf9623af80cae2296717eb1ba48826cbe47 | refs/heads/main | 2023-01-05T14:57:25.605341 | 2020-11-07T05:57:36 | 2020-11-07T05:57:36 | 309,647,376 | 5 | 0 | null | null | null | null | UTF-8 | Java | false | false | 94 | java | package product2;
public interface ImportFile {
public Object importFile(String path);
}
| [
"[email protected]"
]
| |
9c8073221556961a3f9cfe04e16f639376229e59 | 2ea33f61617e7bc46e221d53bc76379815add0c7 | /RoomSchedulerRachelB/src/ReservationEntry.java | 418044327c94552728f01a8b8952a43aa2a727bb | []
| no_license | rachelbe/roomscheduler | 3f1e2038e92dbf177b7bdf5cbffc97c34a7898fe | f69a373b5f5da767af877a3ac6f3628af953cda3 | refs/heads/master | 2022-12-01T02:23:59.358025 | 2020-08-12T03:03:18 | 2020-08-12T03:03:18 | 286,888,216 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,665 | 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.
*
* @author RachelBrooks
*/
import java.sql.Timestamp;
import java.sql.Date;
public class ReservationEntry
{
private String name;
private int seats;
private Date date;
private String room;
private Timestamp timestamp;
public ReservationEntry(String name, String room, Date date, int seats , Timestamp timestamp)
{
setName(name);
getName();
setSeats(seats);
getSeats();
setDate(date);
getDate();
setRoom(room);
getRoom();
getTimestamp();
setTimestamp(timestamp);
}
public void setName(String name)
{
this.name= name;
}
public String getName()
{
return name;
}
public void setSeats(int seats)
{
this.seats= seats;
}
public int getSeats()
{
return seats;
}
public void setDate(Date date)
{
this.date = date;
}
public Date getDate()
{
return date;
}
public void setRoom(String room)
{
this.room= room;
}
public String getRoom(){
return room;
}
public void setTimestamp(Timestamp timestamp)
{
this.timestamp = timestamp;
}
public Timestamp getTimestamp()
{
return timestamp;
}
}
| [
"[email protected]"
]
| |
81d7e3e04c7ffd0470e81f38d7e52c5b213de119 | bbf7581a33c2b54cf7ba6990840ac4920b7755c9 | /src/javaSE/ch03/IncDec.java | 7b5746af1c5677d29fbec2f01497060cab08e5f3 | []
| no_license | a84302486/javaHomeWork | 9d6d753471bef5638d3da39a76df5f2b5d24f0d2 | c605e01cbcb252f804d2a3c96f0d3a39014342c4 | refs/heads/master | 2021-01-12T05:38:19.559155 | 2017-01-06T05:45:12 | 2017-01-06T05:45:12 | 77,153,264 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 510 | java | package javaSE.ch03;
public class IncDec {
public static void main(String[] args) {
int x = 5;
int y;
System.out.println("x=5");
++x;
System.out.println("++X=" + x);
x = 5;
x++;
System.out.println("x++=" + x);
x = 5;
y = ++x;
System.out.println("y=++x=,y=" + y + ",x=" + x);
x = 5;
y = ++x;
System.out.println("y=x++=,y=" + y + ",x=" + x);
x = 5;
y = x++ * 4;
System.out.println("y=x++*4,y=" + y);
x = 5;
y = ++x * 4;
System.out.println("y=++x*4,y=" + y);
}
}
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.