text
stringlengths
10
2.72M
package org.hibernate.benchmarks.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Target; @Inherited @Target( ElementType.TYPE ) public @interface BenchmarkQueries { BenchmarkQuery[] value(); }
package com.pointinside.android.app.util; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.Drawable; import com.pointinside.android.app.ui.GoogleMapActivity; import com.pointinside.android.app.widget.GoogleMapOverlay; import com.pointinside.android.app.widget.GoogleOverlayItem; import com.pointinside.android.app.widget.VenueGeoPoint; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.concurrent.CopyOnWriteArrayList; public class OverlayUtils { public static final String DEFAULT_MARKER = "Default"; public static int addGoogleOverlaysForVisibleArea(CopyOnWriteArrayList<GoogleOverlayItem> paramCopyOnWriteArrayList, GoogleMapOverlay paramGoogleMapOverlay) { ArrayList localArrayList = new ArrayList(); LatLongRect localLatLongRect = LocationHelper.getMapArea(); if ((localLatLongRect == null) || (paramCopyOnWriteArrayList == null)) { return 0; } int i = LocationHelper.toInt(localLatLongRect.getLatitudeSpan()) / 2; int j = LocationHelper.toInt(localLatLongRect.getLongitudeSpan()) / 2; if (i > 90000000.0D) { i = 90000000; } if (j > 180000000.0D) { j = 180000000; } int k = i + LocationHelper.toInt(localLatLongRect.getLatitudeCenter()); int m = LocationHelper.toInt(localLatLongRect.getLongitudeCenter()) - j; int n = LocationHelper.toInt(localLatLongRect.getLatitudeCenter()) - i; int i1 = j + LocationHelper.toInt(localLatLongRect.getLongitudeCenter()); if (k > 90000000.0D) { k = 89999999; } if (n < -90000000.0D) { n = -89999999; } if (m < -180000000.0D) { m = -179999999; } if (i1 > 180000000.0D) { i1 = 179999999; } VenueGeoPoint localVenueGeoPoint1 = new VenueGeoPoint(k, m); VenueGeoPoint localVenueGeoPoint2 = new VenueGeoPoint(n, i1); int i2 = Collections.binarySearch(paramCopyOnWriteArrayList, localVenueGeoPoint1, localVenueGeoPoint1); if (i2 < 0) { i2 = -1 + -i2; } int i3 = paramCopyOnWriteArrayList.size(); int i4 = 0; if (i2 >= 0) {} for (;;) { if (i2 >= i3) { paramGoogleMapOverlay.addAllOverlays(localArrayList); return i4; } GoogleOverlayItem localGoogleOverlayItem; localGoogleOverlayItem = (GoogleOverlayItem)paramCopyOnWriteArrayList.get(i2); if(localGoogleOverlayItem.getLongitudeE6() > localVenueGeoPoint2.getLongitudeE6()) { if (localGoogleOverlayItem.isActive()) { break; } } if ((localGoogleOverlayItem.getLatitudeE6() <= localVenueGeoPoint1.getLatitudeE6()) && (localGoogleOverlayItem.getLatitudeE6() >= localVenueGeoPoint2.getLatitudeE6())) { localGoogleOverlayItem.setActive(true); localArrayList.add(localGoogleOverlayItem); i4++; } i2++; } return i4; } public static void deactivateOverlays(CopyOnWriteArrayList<GoogleOverlayItem> paramCopyOnWriteArrayList) { Iterator localIterator = paramCopyOnWriteArrayList.iterator(); for (;;) { if (!localIterator.hasNext()) { return; } ((GoogleOverlayItem)localIterator.next()).setActive(false); } } public static HashMap<String, Drawable> getDealMarkerDrawableMap(Context paramContext) { HashMap localHashMap = new HashMap(); Resources localResources = paramContext.getResources(); localHashMap.put("Default", localResources.getDrawable(2130837690)); localHashMap.putAll(DealsUtils.getPinDrawables(localResources)); return localHashMap; } public static GoogleOverlayItem getOverlayItem(CopyOnWriteArrayList<GoogleOverlayItem> paramCopyOnWriteArrayList, String paramString) { if (paramString == null) { return null; } Iterator localIterator = paramCopyOnWriteArrayList.iterator(); GoogleOverlayItem localGoogleOverlayItem; do { if (!localIterator.hasNext()) { return null; } localGoogleOverlayItem = (GoogleOverlayItem)localIterator.next(); } while (!paramString.equals(localGoogleOverlayItem.getVenueUUID())); return localGoogleOverlayItem; } public static HashMap<String, Drawable> getVenueMarkerDrawableMap(Context paramContext) { HashMap localHashMap = new HashMap(); Resources localResources = paramContext.getResources(); localHashMap.put("Default", localResources.getDrawable(2130837686)); localHashMap.put(String.valueOf(4), localResources.getDrawable(2130837686)); localHashMap.put(String.valueOf(2), localResources.getDrawable(2130837687)); localHashMap.put(String.valueOf(1), localResources.getDrawable(2130837692)); return localHashMap; } public static int hideVenueOverlaysForDeals(Collection<GoogleMapActivity.MapDeal> paramCollection, GoogleMapOverlay paramGoogleMapOverlay) { int i = 0; Iterator localIterator = paramCollection.iterator(); for (;;) { if (!localIterator.hasNext()) { return i; } GoogleMapActivity.MapDeal localMapDeal = (GoogleMapActivity.MapDeal)localIterator.next(); if (localMapDeal.getVenueUUID() != null) { GoogleOverlayItem localGoogleOverlayItem = paramGoogleMapOverlay.removeOverlay(localMapDeal.getGeoCode()); if (localGoogleOverlayItem != null) { i++; localGoogleOverlayItem.setActive(false); } } } } } /* Location: D:\xinghai\dex2jar\classes-dex2jar.jar * Qualified Name: com.pointinside.android.app.util.OverlayUtils * JD-Core Version: 0.7.0.1 */
package gil.server; import java.io.IOException; import java.net.InetAddress; public class PingTestServer { public static String sendPingRequest(String ipAddress) throws IOException { InetAddress inetAddress = InetAddress.getByName(ipAddress); System.out.println("Sending Ping Request to " + ipAddress); if (inetAddress.isReachable(5000)) return "Server is reachable"; else return "Sorry! We can't reach to this server"; } }
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.context; import jakarta.servlet.ServletConfig; import jakarta.servlet.ServletContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.lang.Nullable; /** * Interface to be implemented by configurable web application contexts. * Supported by {@link ContextLoader} and * {@link org.springframework.web.servlet.FrameworkServlet}. * * <p>Note: The setters of this interface need to be called before an * invocation of the {@link #refresh} method inherited from * {@link org.springframework.context.ConfigurableApplicationContext}. * They do not cause an initialization of the context on their own. * * @author Juergen Hoeller * @since 05.12.2003 * @see #refresh * @see ContextLoader#createWebApplicationContext * @see org.springframework.web.servlet.FrameworkServlet#createWebApplicationContext */ public interface ConfigurableWebApplicationContext extends WebApplicationContext, ConfigurableApplicationContext { /** * Prefix for ApplicationContext ids that refer to context path and/or servlet name. */ String APPLICATION_CONTEXT_ID_PREFIX = WebApplicationContext.class.getName() + ":"; /** * Name of the ServletConfig environment bean in the factory. * @see jakarta.servlet.ServletConfig */ String SERVLET_CONFIG_BEAN_NAME = "servletConfig"; /** * Set the ServletContext for this web application context. * <p>Does not cause an initialization of the context: refresh needs to be * called after the setting of all configuration properties. * @see #refresh() */ void setServletContext(@Nullable ServletContext servletContext); /** * Set the ServletConfig for this web application context. * Only called for a WebApplicationContext that belongs to a specific Servlet. * @see #refresh() */ void setServletConfig(@Nullable ServletConfig servletConfig); /** * Return the ServletConfig for this web application context, if any. */ @Nullable ServletConfig getServletConfig(); /** * Set the namespace for this web application context, * to be used for building a default context config location. * The root web application context does not have a namespace. */ void setNamespace(@Nullable String namespace); /** * Return the namespace for this web application context, if any. */ @Nullable String getNamespace(); /** * Set the config locations for this web application context in init-param style, * i.e. with distinct locations separated by commas, semicolons or whitespace. * <p>If not set, the implementation is supposed to use a default for the * given namespace or the root web application context, as appropriate. */ void setConfigLocation(String configLocation); /** * Set the config locations for this web application context. * <p>If not set, the implementation is supposed to use a default for the * given namespace or the root web application context, as appropriate. */ void setConfigLocations(String... configLocations); /** * Return the config locations for this web application context, * or {@code null} if none specified. */ @Nullable String[] getConfigLocations(); }
package io.pivotal.racquetandroid.fragment; import com.squareup.otto.Bus; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.support.v4.SupportFragmentTestUtil; import java.util.List; import javax.inject.Inject; import io.pivotal.racquetandroid.BuildConfig; import io.pivotal.racquetandroid.MockRacquetRestService; import io.pivotal.racquetandroid.RacquetApplication; import io.pivotal.racquetandroid.RacquetRestService; import io.pivotal.racquetandroid.TestApplicationComponent; import io.pivotal.racquetandroid.event.DismissRecordMatchEvent; import io.pivotal.racquetandroid.event.FetchedMatchesEvent; import io.pivotal.racquetandroid.event.MatchUpdatedEvent; import io.pivotal.racquetandroid.model.Club; import io.pivotal.racquetandroid.model.response.Match; import io.pivotal.racquetandroid.util.ModelBuilder; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; @Config(constants = BuildConfig.class) @RunWith(RobolectricGradleTestRunner.class) public class FeedFragmentTest { @Inject RacquetRestService restService; @Inject Bus bus; MockRacquetRestService mockRestService; private FeedFragment fragment; @Before public void setup() { Club club = ModelBuilder.getClub(1, "pivotal-sydney"); fragment = FeedFragment.newInstance(club); ((TestApplicationComponent) RacquetApplication.getApplication().getApplicationComponent()).inject(this); mockRestService = (MockRacquetRestService) restService; } @Test public void onViewCreated_shouldFetchMatches() { List<Match> matches = ModelBuilder.getMatches(5, "p1", "p2"); mockRestService.addResponse(matches, true); SupportFragmentTestUtil.startFragment(fragment); assertThat(fragment.adapter.getItemCount()).isEqualTo(5); } @Test public void pullToRefresh_shouldRepopulateResults() { SupportFragmentTestUtil.startFragment(fragment); assertThat(fragment.adapter.getItemCount()).isEqualTo(0); List<Match> matches = ModelBuilder.getMatches(5, "p1", "p2"); mockRestService.addResponse(matches, true); fragment.onRefresh(); assertThat(fragment.adapter.getItemCount()).isEqualTo(5); verify(bus, atLeastOnce()).post(isA(FetchedMatchesEvent.class)); } @Test public void onMatchUpdatedEvent_shouldInsertMatch() throws Exception { SupportFragmentTestUtil.startFragment(fragment); bus.post(new MatchUpdatedEvent(ModelBuilder.getMatch("winner", "loser"))); assertThat(fragment.adapter.getItemCount()).isEqualTo(1); bus.post(new DismissRecordMatchEvent()); assertThat(fragment.adapter.getItemCount()).isEqualTo(1); } }
package com.masters.service; import com.masters.dao.AdvertRepository; import com.masters.dao.CategoryRepository; import com.masters.dao.CompanyRepository; import com.masters.dao.UserRepository; import com.masters.entity.Advert; import com.masters.entity.Category; import com.masters.entity.Company; import com.masters.entity.User; import com.masters.service.dto.AdvertDTO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Service public class AdvertService { @Autowired private AdvertRepository advertRepository; @Autowired private UserRepository userRepository; @Autowired private CategoryRepository categoryRepository; @Autowired private CompanyRepository companyRepository; @Autowired private AdvertMapper advertMapper; public List<AdvertDTO> getAllAdverts() { List<Advert> adverts = new ArrayList<>(); advertRepository.findAll().forEach(adverts::add); return adverts.stream().map(o -> new AdvertDTO(o)).collect(Collectors.toList()); } public List<AdvertDTO> getByCategoryAndLocalization(String categoryName, String localization) { Category category = categoryRepository.findByCategoryName(categoryName); List<Advert> adv; if(categoryName.length() != 0 && localization.length() != 0) { adv = advertRepository.findByCategoryAndAdLocalization(category, localization); } else if(categoryName.length() == 0 && localization.length() != 0) { adv = advertRepository.findAdvertsByAdLocalization(localization); } else if(localization.length() == 0 && categoryName.length() != 0) { adv = advertRepository.findAdvertsByCategory(category); } else { return getAllAdverts(); } return adv.stream().map(o -> new AdvertDTO(o)).collect(Collectors.toList()); } public Advert getByLocalization(String localization) { Company companyLocalization = companyRepository.findByCity(localization); if(companyLocalization == null) { return null; } return advertRepository.findByCompany(companyLocalization); } public Advert getByCategory(String name) { Category categoryName = categoryRepository.findByCategoryName(name); if(categoryName == null) { return null; } return advertRepository.findByCategory(categoryName); } public AdvertDTO getAdvertById(long id) { Advert advert = advertRepository.findOne(id); return new AdvertDTO(advert); } public List<AdvertDTO> getAllUserAdverts(String username) { Optional<User> user = userRepository.findUserByEmail(username); Optional<List<Advert>> adverts = advertRepository.findAllByUser( user.orElseThrow(() -> new UsernameNotFoundException("Wrong username"))); return adverts.orElseThrow(() -> new UsernameNotFoundException("User don't have any adverts")) .stream().map(AdvertDTO::new).collect(Collectors.toList()); } public Advert createAdvert(AdvertDTO advertDTO) { Advert ad = advertMapper.AdvertDTOtoAdvert(advertDTO); advertRepository.save(ad); return ad; } public void deleteAdvert(long id) { //todo nie da sie usuanac dziwne polaczenie z userem advertRepository.delete(id); } public AdvertDTO updateAdvert(AdvertDTO advertDTO) { Advert advert = advertRepository.findOne(advertDTO.getId()); Optional<User> user = userRepository.findUserByEmail(advertDTO.getUser()); Optional<Company> company = companyRepository. findFirstByCompanyNameAndCityAndStreetAndPostcode( advertDTO.getCompanyName(), advertDTO.getCity(), advertDTO.getStreet(), advertDTO.getPostcode()); Category category = categoryRepository.findByCategoryName(advertDTO.getCategory()); advert.setId(advertDTO.getId()); advert.setSalaryMin(advertDTO.getSalaryMin()); advert.setSalaryMax(advertDTO.getSalaryMax()); advert.setCompany(company.orElse(companyRepository.save(advertMapper.AdvertDTOtoCompany(advertDTO)))); advert.setCategory(category); advert.setDescription(advertDTO.getDescription()); advert.setTitle(advertDTO.getTitle()); advert.setAdLocalization(advertDTO.getLocalization()); advert.setOffertEmail(advertDTO.getOffertEmail()); advert.setUser(user.get()); advertRepository.save(advert); //TODO problem with update category return new AdvertDTO(advert); } }
package com.esum.comp.smail; import com.esum.framework.core.component.code.ComponentCode; public class SMailCode extends ComponentCode { public static final String ERROR_UNKNOWN_ERROR = "SMAIL99"; public static final String ERROR_INVALID_ADDRESS = "SMAIL01"; public static final String ERROR_UNSUPPORTED_ENCODING = "SMAIL02"; public static final String ERROR_MESSAGING_ERROR = "SMAIL03"; public static final String ERROR_IO_ERROR = "SMAIL04"; public static final String ERROR_NO_SUCH_PROVIDER = "SMAIL05"; public static final String ERROR_PARSING_ERROR = "SMAIL06"; public static final String ERROR_COMPONENT_INFO = "SMAIL07"; public static final String ERROR_SQL_QUERY = "SMAIL08"; public static final String ERROR_CONFIG_FILE = "SMAIL09"; public static final String ERROR_MAIL_START = "SMAIL10"; public static final String ERROR_USER_MAIL_INFO = "SMAIL11"; public static final String ERROR_QUEUE_INIT = "SMAIL12"; public static final String ERROR_SPLIT_CLASS = "SMAIL13"; public static final String ERROR_NOT_FOUND_MAIL_INFO = "SMAIL14"; public static final String ERROR_NOFOUND_SERVER = "SMAIL15"; public static final String ERROR_SEND_EVENT = "SMAIL16"; public static final String ERROR_NOTFOUND_CONTENT_TYPE = "SMAIL17"; }
/* * Copyright (c) 2013-2014, Neuro4j.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neuro4j.studio.core; import org.eclipse.emf.ecore.EFactory; /** * <!-- begin-user-doc --> * The <b>Factory</b> for the model. * It provides a create method for each non-abstract class of the model. * <!-- end-user-doc --> * * @see org.neuro4j.studio.core.Neuro4jPackage * @generated */ public interface Neuro4jFactory extends EFactory { /** * The singleton instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */ Neuro4jFactory eINSTANCE = org.neuro4j.studio.core.impl.Neuro4jFactoryImpl.init(); /** * Returns a new object of class '<em>Document Root</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Document Root</em>'. * @generated */ DocumentRoot createDocumentRoot(); /** * Returns a new object of class '<em>Network</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Network</em>'. * @generated */ Network createNetwork(); /** * Returns a new object of class '<em>Action Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Action Node</em>'. * @generated */ ActionNode createActionNode(); /** * Returns a new object of class '<em>Join Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Join Node</em>'. * @generated */ JoinNode createJoinNode(); /** * Returns a new object of class '<em>Decision Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Decision Node</em>'. * @generated */ DecisionNode createDecisionNode(); /** * Returns a new object of class '<em>Loop Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Loop Node</em>'. * @generated */ LoopNode createLoopNode(); /** * Returns a new object of class '<em>Call Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Call Node</em>'. * @generated */ CallNode createCallNode(); /** * Returns a new object of class '<em>Start Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Start Node</em>'. * @generated */ StartNode createStartNode(); /** * Returns a new object of class '<em>End Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>End Node</em>'. * @generated */ EndNode createEndNode(); /** * Returns a new object of class '<em>Mapper Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Mapper Node</em>'. * @generated */ MapperNode createMapperNode(); /** * Returns a new object of class '<em>Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Node</em>'. * @generated */ Node createNode(); /** * Returns a new object of class '<em>Key Value Pair</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Key Value Pair</em>'. * @generated */ KeyValuePair createKeyValuePair(); /** * Returns a new object of class '<em>In Out Parameter</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>In Out Parameter</em>'. * @generated */ InOutParameter createInOutParameter(); /** * Returns a new object of class '<em>Follow By Relation Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Follow By Relation Node</em>'. * @generated */ FollowByRelationNode createFollowByRelationNode(); /** * Returns a new object of class '<em>Logic Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Logic Node</em>'. * @generated */ LogicNode createLogicNode(); /** * Returns a new object of class '<em>Operator Output</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Operator Output</em>'. * @generated */ OperatorOutput createOperatorOutput(); /** * Returns a new object of class '<em>Operator Input</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Operator Input</em>'. * @generated */ OperatorInput createOperatorInput(); /** * Returns a new object of class '<em>View Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>View Node</em>'. * @generated */ ViewNode createViewNode(); /** * Returns a new object of class '<em>Note Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Note Node</em>'. * @generated */ NoteNode createNoteNode(); /** * Returns a new object of class '<em>Standard Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return a new object of class '<em>Standard Node</em>'. * @generated */ StandardNode createStandardNode(); /** * Returns the package supported by this factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * * @return the package supported by this factory. * @generated */ Neuro4jPackage getNeuro4jPackage(); } // Neuro4jFactory
package Runner; import org.junit.runner.RunWith; import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; @RunWith(Cucumber.class) @CucumberOptions(features = "classpath:features", glue = "StepDef", tags ="", plugin = {"pretty","html:target/html/report.html"}, monochrome = true, publish=true, dryRun=false) public class TestRunner { }
package Ex1; public class Retangulo extends Quadrilatero implements Diagonal { public Retangulo (String nome, double base, double altura) { super(nome,base,altura); } @Override public double diagonal() { return Math.sqrt(Math.pow(this.base,2) + Math.pow(this.altura,2)); } @Override public double perimetro() { return this.perimetro; } @Override public double area() { // TODO Auto-generated method stub return area; } }
package com.Social.Movement3; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.support.v4.widget.DrawerLayout; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.ShareActionProvider; import com.flurry.android.FlurryAgent; public class MainActivity extends FragmentActivity { final String[] menuEntries = { "現場文字轉播","English Transcript","關於g0v"}; // ,"English Live","議場內 樓上", "議場內 樓上(Apple)", // "議場內 樓下(五六)","議場內 樓下(音地)","青島東 北側(g0v)","濟南路 機動(g0v)","濟南路 南測","議會外(Apple)" final String[] fragments = { "com.Social.Movement3.LiveNote","com.Social.Movement3.EnglishTranscript","com.Social.Movement3.About" }; // "com.Social.Movement3.vEnglish","com.Social.Movement3.vly2f","com.Social.Movement3.vly2fApple", // "com.Social.Movement3.vly1f56","com.Social.Movement3.vly1fMusic","com.Social.Movement3.lyOutIslandNorthg0v", // "com.Social.Movement3.lyOutIsGSouthg0v","com.Social.Movement3.lyOutIsGSouth2","com.Social.Movement3.lyOutApple" private ActionBarDrawerToggle drawerToggle; private ShareActionProvider mShareActionProvider; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // PushService.setDefaultPushCallback(this, MainActivity.class); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActionBar() .getThemedContext(), android.R.layout.simple_list_item_1, menuEntries); final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); final ListView navList = (ListView) findViewById(R.id.left_drawer); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); drawerToggle = new ActionBarDrawerToggle(this, drawer, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) { /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { } }; drawer.setDrawerListener(drawerToggle); navList.setAdapter(adapter); navList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int pos, long id) { drawer.setDrawerListener(new DrawerLayout.SimpleDrawerListener() { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); FragmentTransaction tx = getSupportFragmentManager() .beginTransaction(); tx.replace(R.id.content_frame, Fragment.instantiate( MainActivity.this, fragments[pos])); tx.commit(); } }); drawer.closeDrawer(navList); } }); FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); //Screen Start tx.replace(R.id.content_frame,Fragment.instantiate(MainActivity.this, fragments[0])); tx.commit(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (drawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); // Locate MenuItem with ShareActionProvider MenuItem item = menu.findItem(R.id.menu_share); // // Fetch and store ShareActionProvider mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.menu_share).getActionProvider(); mShareActionProvider.setShareIntent(getDefaultShareIntent()); return true; } private Intent getDefaultShareIntent() { // TODO Auto-generated method stub String playStoreLink = "https://play.google.com/store/apps/details?id=" + getPackageName(); String yourShareText = "Pray for Taiwan, Build from http://g0v.toady, "+" Install this app " + playStoreLink; Intent intent = new Intent(Intent.ACTION_SEND); // intent.setComponent(new ComponentName("jp.naver.line.android", // "com.facebook.katana")); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, "跟我一起到g0v關注黑箱服貿協議"); intent.putExtra(Intent.EXTRA_TEXT, yourShareText); return intent; } // Call to update the share intent private void setShareIntent(Intent shareIntent) { if (mShareActionProvider != null) { mShareActionProvider.setShareIntent(shareIntent); } } // @Override // public void onStart() { // super.onStart(); // // The rest of your onStart() code. // EasyTracker.getInstance(this).activityStart(this); // Add this method. // } // @Override // public void onStop() { // super.onStop(); // // The rest of your onStop() code. // EasyTracker.getInstance(this).activityStop(this); // Add this method. //} // public void onStart() // { // super.onStart(); // FlurryAgent.onStartSession(this, "XFSDYMVRWPS72Z595YZY"); // // your code // } // public void onStop() // { // super.onStop(); // FlurryAgent.onEndSession(this); // // your code // } }
import java.util.*; public class StringExpressionValue { public int calculate(String s) { String nonBlank = s.replace(" ", ""); Deque<Integer> nums = new ArrayDeque<>(); Deque<Character> operator = new ArrayDeque<>(); for (int index = 0; index < nonBlank.length(); ) { if (nonBlank.charAt(index) == '*' || nonBlank.charAt(index) == '/') { char op = nonBlank.charAt(index); int o1 = nums.pollLast(); int o2 = nextInt(nonBlank, ++index); while (index < nonBlank.length() && !isOprand(nonBlank, index)) index++; if (op == '*') nums.addLast(o1 * o2); if (op == '/') nums.addLast(o1 / o2); } else if (nonBlank.charAt(index) == '+' || nonBlank.charAt(index) == '-') { operator.addLast(nonBlank.charAt(index)); ++index; } else { nums.addLast(nextInt(nonBlank, index)); while (index < nonBlank.length() && !isOprand(nonBlank, index)) { index++; } } } while (!operator.isEmpty()) { char op = operator.pollFirst(); int o1 = nums.pollFirst(); int o2 = nums.pollFirst(); if (op == '+') nums.addFirst(o2 + o1); if (op == '-') nums.addFirst(o1 - o2); } return nums.pollFirst(); } private static int nextInt(String s, int index) { char c = s.charAt(index); if (c < '0' || c > '9') return -1; int result = 0; while (c >= '0' && c <= '9') { result = result * 10 + (c - '0'); if (index == s.length() - 1) break; c = s.charAt(++index); } return result; } private static boolean isOprand(String s, int index) { char c = s.charAt(index); return c == '+' || c == '-' || c == '*' || c == '/'; } //使用正则表达式匹配选取各个数、符号 //Runtime > 1000ms public int calculate(String s, boolean useRegex, boolean useSwitch) { String nonBlank = s.replace(" ", ""); String[] numString = nonBlank.split("\\+|\\-|\\*|\\/"); List oprandString = Arrays.asList(nonBlank.split("[0-9]+")); List<Integer> nums = new ArrayList<>(); List<Character> oprands = new ArrayList<>(); for (Object o : numString) nums.add(Integer.parseInt((String) o)); for (int i = 1; i < oprandString.size(); ++i) oprands.add(((String) oprandString.get(i)).charAt(0)); for (int index = 0; index < oprands.size(); ++index) { if (oprands.get(index) == '*' || oprands.get(index) == '/') { int op1 = nums.get(index); int op2 = nums.get(index + 1); char op = oprands.get(index); if (op == '*') nums.set(index, op1 * op2); else nums.set(index, op1 / op2); nums.remove(index + 1); oprands.remove(index); index--; } } for (int index = 0; index < oprands.size(); ++index) { if (oprands.get(index) == '+' || oprands.get(index) == '-') { int op1 = nums.get(index); int op2 = nums.get(index + 1); char op = oprands.get(index); if (op == '+') nums.set(index, op1 + op2); else nums.set(index, op1 - op2); nums.remove(index + 1); oprands.remove(index); index--; } } return nums.get(0); } public static void main(String[] args) { System.out.println( new StringExpressionValue(). calculate(" 15 / 3 - 2 + 1 ", true, false)); } }
package com.projeto.atribuicaoreferencia; import colecoes.ImprimirTexto; import javax.swing.*; public class Main { public static void main(String[] args) { ImprimirTexto texto = new ImprimirTexto(); //Demonstração curso DIO Estrutura de dados //Nas variáveis o java copia o valor para cada variável int a = 1; int b = a; texto.tituloCentro("Usando variáveis"); System.out.println("Inteiro a = " + a + "\nInteiro b = "+b); a = 2; System.out.println("Inteiro a = " + a + "\nInteiro b = "+b); //O java copia a referência para o objeto texto.tituloCentro("Usando Objetos"); MeuObj obja = new MeuObj(1); MeuObj objb = obja; System.out.println("Objeto a = "+ obja.toString() + "\nObjeto b = "+ objb); obja.setNum(2); System.out.println("Objeto a = "+ obja.toString() + "\nObjeto b = "+ objb); } }
package com.himanshu.springboot2.angular; import com.himanshu.springboot2.angular.orders.service.CustomerService; import com.himanshu.springboot2.angular.orders.service.UserRoleService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.annotation.Bean; import org.springframework.transaction.annotation.EnableTransactionManagement; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.StreamSupport; @SpringBootApplication(scanBasePackages = {"com.himanshu.springboot2"}, exclude = DataSourceAutoConfiguration.class) public class Main { private static Logger logger = LoggerFactory.getLogger(Main.class); public static void main(String[] args) { System.setProperty("jdbc.inmem.db", "true"); //Forcing to run in in-mem db mode. SpringApplication app = new SpringApplicationBuilder(Main.class).logStartupInfo(true).build(); app.run(args); } /*@Bean public CommandLineRunner demo(CustomerService customerService) { return (args) -> { StreamSupport.stream(customerService.listAll().spliterator(), false) .map(customer -> customer.toString()) .forEach(logger::info); Runnable r1 = () -> logger.info(customerService.getAndUpdateCustomerCountry(1l, "India").toString()); Runnable r2 = () -> logger.info(customerService.getAndUpdateCustomerCountry(1l, "United States").toString()); ExecutorService executorService = Executors.newFixedThreadPool(2); List<Runnable> runnables = new ArrayList<>(); runnables.add(r1); runnables.add(r2); StreamSupport.stream(runnables.spliterator(), false).forEach(executorService::submit); executorService.awaitTermination(100, TimeUnit.SECONDS); System.exit(0); }; }*/ /*@Bean public CommandLineRunner demoItems(CustomerService customerService) { return (args) -> { StreamSupport.stream(customerService.getItems().spliterator(), false) .map(item -> item.toString()) .forEach(logger::info); System.exit(0); }; }*/ /*@Bean public CommandLineRunner demoOrders(CustomerService customerService) { return (args) -> { StreamSupport.stream(customerService.getOrders().spliterator(), false) .map(order -> order.toString()) .forEach(logger::info); System.exit(0); }; }*/ /*@Bean public CommandLineRunner demoOrders(CustomerService customerService) { return (args) -> { StreamSupport.stream(customerService.getOrdersViaJoinFetch().spliterator(), false) .map(order -> order.toString()) .forEach(logger::info); System.exit(0); }; }*/ @Bean public CommandLineRunner demoOrders(UserRoleService userRoleService) { return (args) -> { StreamSupport.stream(userRoleService.getUsers().spliterator(), false) .map(user -> user.toString()) .forEach(logger::info); System.exit(0); }; } }
package org.antran.saletax.internal; import org.antran.saletax.api.IAmount; import org.antran.saletax.api.ICart; import org.antran.saletax.api.ICartCalculator; import org.antran.saletax.api.ICartItem; import org.antran.saletax.api.ITaxPolicy; public class DefaultSaleTaxCalculator implements ICartCalculator { private final ITaxPolicy[] taxPolicies; public DefaultSaleTaxCalculator(ITaxPolicy[] taxPolicies) { this.taxPolicies = taxPolicies; } public IAmount calculate(ICart cart) { IAmount saleTax = Amount.ZERO; for (ICartItem item : cart) { for (ITaxPolicy policy : taxPolicies) { IAmount tax = policy.tax(item); saleTax = saleTax.add(tax); } } return saleTax; } }
/** * All rights Reserved, Designed By www.tydic.com * @Title: ItemServiceImpl.java * @Package com.taotao.rest.service.impl * @Description: TODO(用一句话描述该文件做什么) * @author: axin * @date: 2019年2月14日 下午9:48:21 * @version V1.0 * @Copyright: 2019 www.hao456.top Inc. All rights reserved. */ package com.taotao.rest.service.impl; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import com.taotao.common.pojo.TaotaoResult; import com.taotao.common.utils.JsonUtils; import com.taotao.mapper.TbItemDescMapper; import com.taotao.mapper.TbItemMapper; import com.taotao.mapper.TbItemParamItemMapper; import com.taotao.pojo.TbItem; import com.taotao.pojo.TbItemDesc; import com.taotao.pojo.TbItemParamItem; import com.taotao.pojo.TbItemParamItemExample; import com.taotao.rest.dao.JedisClient; import com.taotao.rest.service.ItemService; /** * @Description: TODO * @ClassName: ItemServiceImpl * @author: Axin * @date: 2019年2月14日 下午9:48:21 * @Copyright: 2019 www.hao456.top Inc. All rights reserved. */ @Service public class ItemServiceImpl implements ItemService { @Autowired private TbItemMapper itemMapper; @Autowired private TbItemDescMapper itemDescMapper; @Autowired private TbItemParamItemMapper itemParamItemMapper; @Autowired private JedisClient jedisClient; @Value("${REDIS_ITEM_KEY}") private String REDIS_ITEM_KEY; //过期时间 @Value("${REDIS_ITEM_EXPIRE}") private Integer REDIS_ITEM_EXPIRE; @Override public TaotaoResult getItemBaseInfo(long itemId) { //添加缓存逻辑 //从缓存中取商品信息,商品id对应的信息 try { String string = jedisClient.get(REDIS_ITEM_KEY + ":" + itemId + ":base"); //判断是否有值 if(StringUtils.isNotEmpty(string)){ //把string转换成java对象 TbItem item = JsonUtils.jsonToPojo(string, TbItem.class); return TaotaoResult.ok(item); } } catch (Exception e) { e.printStackTrace(); } //从数据库中查询信息 TbItem item = this.itemMapper.selectByPrimaryKey(itemId); try { //把商品信息写入缓存 //redis中的hash类型的key不能设置过期时间,如果还对key进行分类可以使用折中的方案。 //key的命名方式: //hao456:javaee16:01=zhangsan jedisClient.set(REDIS_ITEM_KEY + ":" + itemId + ":base", JsonUtils.objectToJson(item)); //设置key的有效期 jedisClient.expire(REDIS_ITEM_KEY + ":" + itemId + ":base", REDIS_ITEM_EXPIRE); } catch (Exception e) { e.printStackTrace(); } return TaotaoResult.ok(item); } /* (non-Javadoc) * @see com.taotao.rest.service.ItemService#getItemDesc(long) */ @Override public TaotaoResult getItemDesc(long itemId) { //添加缓存逻辑 // 从缓存中取商品信息,商品id对应的信息 try { String string = jedisClient.get(REDIS_ITEM_KEY + ":" + itemId + ":desc"); // 判断是否有值 if (StringUtils.isNotEmpty(string)) { // 把string转换成java对象 TbItemDesc item = JsonUtils.jsonToPojo(string, TbItemDesc.class); return TaotaoResult.ok(item); } } catch (Exception e) { e.printStackTrace(); } TbItemDesc itemDesc = this.itemDescMapper.selectByPrimaryKey(itemId); try { jedisClient.set(REDIS_ITEM_KEY + ":" + itemId + ":desc", JsonUtils.objectToJson(itemDesc)); //设置key的有效期 jedisClient.expire(REDIS_ITEM_KEY + ":" + itemId + ":desc", REDIS_ITEM_EXPIRE); } catch (Exception e) { e.printStackTrace(); } return TaotaoResult.ok(itemDesc); } /* (non-Javadoc) * @see com.taotao.rest.service.ItemService#getItemParam(long) */ @Override public TaotaoResult getItemParam(long itemId) { // 从缓存中取商品信息,商品id对应的信息 try { String string = jedisClient.get(REDIS_ITEM_KEY + ":" + itemId + ":param"); // 判断是否有值 if (StringUtils.isNotEmpty(string)) { // 把string转换成java对象 TbItemParamItem paramItem = JsonUtils.jsonToPojo(string, TbItemParamItem.class); return TaotaoResult.ok(paramItem); } } catch (Exception e) { e.printStackTrace(); } TbItemParamItemExample example = new TbItemParamItemExample(); example.createCriteria().andItemIdEqualTo(itemId); List<TbItemParamItem> list = itemParamItemMapper.selectByExampleWithBLOBs(example); if(!CollectionUtils.isEmpty(list)){ TbItemParamItem paramItem = list.get(0); try { jedisClient.set(REDIS_ITEM_KEY + ":" + itemId + ":param", JsonUtils.objectToJson(paramItem)); //设置key的有效期 jedisClient.expire(REDIS_ITEM_KEY + ":" + itemId + ":param", REDIS_ITEM_EXPIRE); } catch (Exception e) { e.printStackTrace(); } return TaotaoResult.ok(paramItem); } return TaotaoResult.build(400, "无此商品规格"); } }
package com.bnade.wow.controller; import com.bnade.wow.entity.Wowtoken; import com.bnade.wow.repository.WowtokenRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * 时光徽章 * Created by liufeng0103@163.com on 2017/6/6. */ @RestController @RequestMapping("/wowtokens") public class WowtokenController { @Autowired private WowtokenRepository wowtokenRepository; /** * 获取所有的时光徽章历史记录 * @return 时光徽章列表 */ @RequestMapping public List<Wowtoken> findAll() { return wowtokenRepository.findAll(); } }
package com.ftf.phi.network; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.OutputStream; public class Restful { private Route baseRoute; public Restful(){ baseRoute = new Route(); } public void packet(JSONObject data, OutputStream writer) throws JSONException { try { baseRoute.packet(data.getString("uri"), data, writer); } catch (IOException e) { e.printStackTrace(); } } public void addMethod(String route, String method, Method callback){ this.baseRoute.addMethod(route.substring(1), method, callback); } //Function for creating routes public void get(String route, Method method){ this.addMethod(route, "get", method); } public void put(String route, Method method){ this.addMethod(route, "put", method); } public void post(String route, Method method){ this.addMethod(route, "post", method); } public void delete(String route, Method method){ this.addMethod(route, "delete", method); } } class Route { private static boolean matchRoute(String route1, String route2){ //TODO: fancy route formatting return route1.equals(route2); } private String route; private Route[] subRoutes; private Method get; private Method put; private Method post; private Method delete; Route(){ this(""); } private Route(String route){ int end = route.indexOf("/"); if(end != -1){ this.subRoutes = new Route[]{ new Route(route.substring(end)) }; this.route = route.substring(0, end); } else{ this.route = route; } } void packet(String route, JSONObject data, OutputStream writer) throws IOException, JSONException { //Check to see if there is more to the route int end = route.indexOf("/"); if(end != -1){ //If there is more to the route: ///Go through all subRoutes and see if any of them match the next part of the route String nextStep = route.substring(0, end); for(int i = this.subRoutes.length - 1; i > -1; i--){ Route subRotute = this.subRoutes[i]; //If the sub route matches the target route then use it if(matchRoute(subRotute.route, nextStep)){ subRotute.packet(route.substring(end), data, writer); return; } } //If we didn't find a route write a 404 error writer.write("{\"stat\":404}".getBytes()); } else { //If we are at the end of the route find the method that we want to use Method targetMethod = null; switch(data.getString("method")){ case "get": targetMethod = this.get; break; case "put": targetMethod = this.put; break; case "post": targetMethod = this.post; break; case "delete": targetMethod = this.delete; break; } //If the method was not found then send a 405 error if(targetMethod == null){ writer.write("{\"stat\":405}".getBytes()); } //If it was found then run the target method else{ try { targetMethod.run(data, writer); } catch(Exception e) { writer.write("{\"stat\":500}".getBytes()); } } } } void addMethod(String route, String method, Method callback){ //Check to see if there is more to the route int end = route.indexOf("/"); if(end != -1){ //If there is more to the route: ///Go through all subRoutes and see if any of them match the next part of the route String nextStep = route.substring(0, end); for(int i = this.subRoutes.length - 1; i > -1; i--){ Route subRotute = this.subRoutes[i]; //If the sub route matches the target route then use it if(matchRoute(subRotute.route, nextStep)){ subRotute.addMethod(route.substring(end), method, callback); return; } } //If we didn't find the route then create it and add it to the array Route newRoute = new Route(route); newRoute.addMethod(route.substring(end), method,callback); Route[] newSubRoutes = new Route[this.subRoutes.length + 1]; System.arraycopy(this.subRoutes, 0, newSubRoutes, 0, this.subRoutes.length); newSubRoutes[this.subRoutes.length] = newRoute; this.subRoutes = newSubRoutes; } else { //If we are at the end of the route find the method that we want to use switch(method){ case "get": this.get = callback; break; case "put": this.put = callback; break; case "post": this.post = callback; break; case "delete": this.delete = callback; break; } } } }
package com.beans; // Generated Nov 15, 2012 12:05:33 AM by Hibernate Tools 3.2.1.GA import java.util.Date; /** * TblProject generated by hbm2java */ public class TblProject implements java.io.Serializable { private int projectId; private String projectName; private String projectImage; private String projectContentDetail; private String projectDescription; private String startDate; private String endDate; private Integer projectProcessStatus; private Byte projectStatus; public TblProject() { } public TblProject(int projectId) { this.projectId = projectId; } public TblProject(int projectId, String projectName, String projectImage, String projectContentDetail, String projectDescription, String startDate, String endDate, Integer projectProcessStatus, Byte projectStatus) { this.projectId = projectId; this.projectName = projectName; this.projectImage = projectImage; this.projectContentDetail = projectContentDetail; this.projectDescription = projectDescription; this.startDate = startDate; this.endDate = endDate; this.projectProcessStatus = projectProcessStatus; this.projectStatus = projectStatus; } public int getProjectId() { return this.projectId; } public void setProjectId(int projectId) { this.projectId = projectId; } public String getProjectName() { return this.projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getProjectImage() { return this.projectImage; } public void setProjectImage(String projectImage) { this.projectImage = projectImage; } public String getProjectContentDetail() { return this.projectContentDetail; } public void setProjectContentDetail(String projectContentDetail) { this.projectContentDetail = projectContentDetail; } public String getProjectDescription() { return this.projectDescription; } public void setProjectDescription(String projectDescription) { this.projectDescription = projectDescription; } public String getStartDate() { return this.startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return this.endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public Integer getProjectProcessStatus() { return this.projectProcessStatus; } public void setProjectProcessStatus(Integer projectProcessStatus) { this.projectProcessStatus = projectProcessStatus; } public Byte getProjectStatus() { return this.projectStatus; } public void setProjectStatus(Byte projectStatus) { this.projectStatus = projectStatus; } }
package solo; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectList; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.util.Collection; import javax.imageio.ImageIO; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.annotations.XYDrawableAnnotation; import org.jfree.chart.annotations.XYPointerAnnotation; import org.jfree.chart.annotations.XYShapeAnnotation; import org.jfree.chart.annotations.XYTextAnnotation; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.util.Rotation; import com.graphbuilder.geom.Geom; public class TrackSegment { private static final char[] MAX_DOUBLE_STRING = {'1','.','7','9','7','6','9','3','1','3','4','8','6','2','3','1','5','7','E','3','0','8'}; public final static int STRT = 0; public final static int LFT = -1; public final static int RGT = 1; // private final static int LEFTSTART = 0; // private final static int LEFTEND=1; // private final static int RIGHTSTART = 2; // private final static int RIGHTEND=3; // public final static double MAXRADIUS = 1000; public final static double EPSILON = 0.001; private final static double MINLENGTH = 0.01; private static final int PRECISION_DIGIT = 6; private static final double PRECISION = 1000000.0d; private static final int int10pow[] = { 1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000 }; private static final long long10pow[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L, 1000000000000000L, 10000000000000000L, 100000000000000000L, 1000000000000000000L }; int type; double centerx; double centery; double length;/**< Length in meters of the middle of the track */ double distanceFromLocalOrigin; double radius; /**< Radius in meters of the middle of the track (>0) */ double arc; /**< Arc in rad of the curve (>0) */ double startX,startY,endX,endY; private static final char[] buf = new char[300]; private static final String TAB = " "; private static final String[] headers = {"TrackSegment (type = ",TAB+"centerx = ",TAB+"centery = ",TAB+"length = ",TAB+"dist = ",TAB+"radius = ","arc = ",TAB+"startX = ",TAB+"startY = ",TAB+"endX = ",TAB+"endY = "," )"}; private static final char[] tp = headers[0].toCharArray(); private static final char[] cntrx = headers[1].toCharArray(); private static final char[] cntry = headers[2].toCharArray(); private static final char[] lngth = headers[3].toCharArray(); private static final char[] dist = headers[4].toCharArray(); private static final char[] rad = headers[5].toCharArray(); private static final char[] sX = headers[7].toCharArray(); private static final char[] sY = headers[8].toCharArray(); private static final char[] eX = headers[9].toCharArray(); private static final char[] eY = headers[10].toCharArray(); private static final char[] fin = headers[11].toCharArray(); static { System.arraycopy(tp, 0, buf, 0, tp.length); } /** * Copy Constructor * * @param trackSegment a <code>TrackSegment</code> object */ public TrackSegment(TrackSegment trackSegment) { this.type = trackSegment.type; this.centerx = trackSegment.centerx; this.centery = trackSegment.centery; this.length = trackSegment.length; this.distanceFromLocalOrigin = trackSegment.distanceFromLocalOrigin; this.radius = trackSegment.radius; this.arc = trackSegment.arc; this.startX = trackSegment.startX; this.startY = trackSegment.startY; this.endX = trackSegment.endX; this.endY = trackSegment.endY; } public TrackSegment(Segment trackSegment) { this.type = trackSegment.type; this.centerx = (trackSegment.center!=null) ? trackSegment.center.x : 0; this.centery = (trackSegment.center!=null) ? trackSegment.center.y : 0; this.length = trackSegment.length; this.distanceFromLocalOrigin = trackSegment.dist; this.radius = trackSegment.radius; this.arc = trackSegment.arc; this.startX = (trackSegment.start!=null) ? trackSegment.start.x : 0; this.startY = (trackSegment.start!=null) ? trackSegment.start.y : 0; this.endX = (trackSegment.end!=null) ? trackSegment.end.x : 0; this.endY = (trackSegment.end!=null) ? trackSegment.end.y : 0; } public TrackSegment() { } public final static TrackSegment createStraightSeg(double dist,double startX,double startY,double endX,double endY){ double radius = Double.MAX_VALUE; startX = Math.round(startX*PRECISION)/PRECISION; startY = Math.round(startY*PRECISION)/PRECISION; endX = Math.round(endX*PRECISION)/PRECISION; endY = Math.round(endY*PRECISION)/PRECISION; double arc = -1; double dx = endX-startX; double dy = endY - startY; double length = Math.sqrt(dx*dx+dy*dy); double centerx = (startX+endX)/2.0d; double centery = (startY+endY)/2.0d; int type = STRT; return new TrackSegment(type,centerx,centery,length,dist,radius,arc,startX,startY,endX,endY); } public final static TrackSegment createTurnSeg(double dist,double centerx,double centery,double radius,double startX,double startY,double endX,double endY,double x2,double y2){ Vector2D v1 = new Vector2D(startX-centerx,startY-centery); Vector2D v2 = new Vector2D(endX-centerx,endY-centery); // Vector2D v3 = new Vector2D(x2-centerx,y2-centery); double angle = Vector2D.angle(v1, v2); if (angle<-Math.PI) angle += 2*Math.PI; else if (angle>Math.PI) angle -= 2*Math.PI; // double a = v1.angle(v3); //System.out.println(" "+v1.length()+" "+v2.length()+" "+v3.length()); // System.out.println(a+" "+angle); // if (angle*a>0 && angle/a<1) // angle = (-Math.PI*2+angle)%(Math.PI*2); // else if (angle*a<0) // angle = (-Math.PI*2+angle)%(Math.PI*2); double arc = Math.abs(angle); double length = radius*arc; int type = (angle<0) ? LFT : RGT; return new TrackSegment(type,centerx,centery,length,dist,radius,angle,startX,startY,endX,endY); } public final static TrackSegment createTurnSeg(double centerx,double centery,double radius,double startX,double startY,double endX,double endY){ Vector2D v1 = new Vector2D(startX-centerx,startY-centery); Vector2D v2 = new Vector2D(endX-centerx,endY-centery); double angle = Vector2D.angle(v1, v2); // angle = (-Math.PI*2+angle)%(Math.PI*2); if (angle<-Math.PI) angle += 2*Math.PI; else if (angle>Math.PI) angle -= 2*Math.PI; double arc = Math.abs(angle); double length = radius*arc; int type = (angle<0) ? LFT : RGT; return new TrackSegment(type,centerx,centery,length,0,radius,angle,startX,startY,endX,endY); } // public final static int getTurn(double centerx,double centery,double radius,double startX,double startY,double endX,double endY){ // double ax = startX-centerx; // double ay = startY-centery; // double bx = endX-centerx; // double by = endY-centery; // double angle = -Math.atan2(by, bx)+Math.atan2(ay, ax); //// angle = (-Math.PI*2+angle)%(Math.PI*2); // if (angle<-Math.PI) // angle += 2*Math.PI; // else if (angle>Math.PI) // angle -= 2*Math.PI; // // return (angle<0) ? LFT : RGT; // } public final static double distance(double x1,double y1,double x2,double y2){ double dx = x1-x2; double dy = y1-y2; return Math.sqrt(dx*dx+dy*dy); } public static ObjectArrayList<TrackSegment> createSeg(double[] ex,double[] ey){ if (ex==null || ey==null || ex.length!=ey.length || ex.length<2) return null; ObjectArrayList<TrackSegment> rs = new ObjectArrayList<TrackSegment>(); int len = ex.length; int i=0; double dist=0; double xx=ex[0]; double yy=ey[0]; while (i<len-1){ double[] result = new double[3]; double x1 = xx; double x2 = ex[i+1]; double y1 = yy; double y2 = ey[i+1]; if (i==len-2){ TrackSegment ts = TrackSegment.createStraightSeg(dist, x1, y1, x2, y2); rs.add(ts); dist+=ts.length; break; } double x3 = ex[i+2]; double y3 = ey[i+2]; boolean isCircle = Geom.getCircle(x1, y1, x2, y2, x3, y3, result); double radius = (isCircle) ? Math.sqrt(result[2]) : Double.MAX_VALUE; int j=i+3; if (!isCircle || radius>Segment.MAX_RADIUS-1){//is a straight line double allowedDist = Math.max(EPSILON, Geom.ptLineDistSq(x1, y1, x2, y2, x3, y3, null)); double dt2 = distance(x1, y1, x2, y2); double dt3 = distance(x1, y1, x3, y3); double maxd = 0; if (dt2>dt3){ maxd = dt2; xx = x2; yy = y2; } else { maxd = dt3; xx = x3; yy = y3; } for (j=i+3;j<len;++j){ double x = ex[j]; double y = ey[j]; if (Geom.ptLineDistSq(x1, y1, x2, y2, x, y, null)>allowedDist) break; double dt = distance(x1, y1, x, y); if (dt>maxd){ maxd = dt; xx = x; yy = y; } } j--; if (distance(x1, y1, xx, yy)>MINLENGTH){ TrackSegment ts = TrackSegment.createStraightSeg(dist, x1, y1, xx, yy); rs.add(ts); dist+=ts.length; } else { xx = x1; yy = y1; } } else { double ox = result[0]; double oy = result[1]; double maxa = -100000; Vector2D start = new Vector2D(x1-ox,y1-oy); double a2 = new Vector2D(x2-ox,y2-oy).angle(start); double a3 = new Vector2D(x3-ox,y3-oy).angle(start); if (maxa<Math.abs(a2)){ maxa = Math.abs(a2); xx = x2; yy = y2; }; if (maxa<Math.abs(a3)){ maxa = Math.abs(a3); xx = x3; yy = y3; }; for (j=i+3;j<len;++j){ double dx = ex[j]-ox; double dy = ey[j]-oy; if (Math.abs(Math.sqrt(dx*dx+dy*dy)-radius)>EPSILON) break; double a = new Vector2D(dx,dy).angle(start); if (maxa<Math.abs(a)){ maxa = a; xx = ex[j]; yy = ey[j]; }; } j--; TrackSegment ts = TrackSegment.createTurnSeg(dist, ox, oy, radius, x1, y1, xx, yy,x2,y2); if (ts.length>MINLENGTH){ rs.add(ts); dist += ts.length; } else { xx = x1; yy = y1; } } i = j; }//end of while return rs; } public static Vector2D findPointInSegAtDistToPoint(double dist,Vector2D p,TrackSegment ts){ if (ts==null || p==null || dist<=0) return null; double d1 = distance(ts.startX, ts.startY, p.x, p.y); double d2 = distance(ts.endX, ts.endY, p.x, p.y); if ((d1>=dist-EPSILON) && (d1<=dist+EPSILON)) return new Vector2D(ts.startX,ts.startY); if ((d2>=dist-EPSILON) && (d2<=dist+EPSILON)) return new Vector2D(ts.endX,ts.endY); double x1 = ts.startX; double y1 = ts.startY; double x2 = ts.endX; double y2 = ts.endY; if (ts.type==STRT){ if (d1<dist && d2<dist) return null; double[] rs = new double[4]; int sz = Geom.getLineSegCircleIntersection(x1, y1, x2, y2, p.x, p.y, dist,rs); if (sz==0) return null; return new Vector2D(rs[0],rs[1]); }; double d = distance(ts.centerx, ts.centery, p.x, p.y); if (d>dist+ts.radius) return null; double[] rs = Geom.getArcCircleIntersection(ts.centerx, ts.centery,x1,y1,ts.arc, p.x, p.y, dist); if (rs==null) return null; return new Vector2D(rs[0],rs[1]); } public static Vector2D findPointAtDistToPoint(double dist, Vector2D p,ObjectList<TrackSegment> v){ if (v==null || v.size()==0) return null; for (TrackSegment t:v){ Vector2D rs=findPointInSegAtDistToPoint(dist,p,t); if (rs!=null) return rs; } return null; } public static ObjectList<TrackSegment> createSeg(ObjectList<Vector2D> vo,double dist){ if (vo==null || vo.size()<1) return null; Vector2D[] v = new Vector2D[vo.size()]; int i=0; for (Vector2D vv:vo){ v[i++] = new Vector2D(vv.x,vv.y); } return createSeg(v,dist); } public static ObjectList<TrackSegment> createSeg(Vector2D[] v,double dist){ if (v==null || v.length<2) return null; ObjectArrayList<TrackSegment> rs = new ObjectArrayList<TrackSegment>(); int len = v.length; int i=0; double xx=v[0].x; double yy=v[0].y; while (i<len-1){ double[] result = new double[3]; double x1 = xx; double x2 = v[i+1].x; double y1 = yy; double y2 = v[i+1].y; if (i==len-2){ TrackSegment ts = TrackSegment.createStraightSeg(dist, x1, y1, x2, y2); rs.add(ts); dist+=ts.length; break; } double x3 = v[i+2].x; double y3 = v[i+2].y; boolean isCircle = Geom.getCircle(x1, y1, x2, y2, x3, y3, result); double radius = (isCircle) ? Math.sqrt(result[2]) : Double.MAX_VALUE; int j=i+3; if (!isCircle || radius>Segment.MAX_RADIUS){//is a straight line double allowedDist = Math.max(EPSILON, Geom.ptLineDistSq(x1, y1, x2, y2, x3, y3, null)); double dt2 = distance(x1, y1, x2, y2); double dt3 = distance(x1, y1, x3, y3); double maxd = 0; if (dt2>dt3){ maxd = dt2; xx = x2; yy = y2; } else { maxd = dt3; xx = x3; yy = y3; } for (j=i+3;j<len;++j){ double x = v[j].x; double y = v[j].y; if (Geom.ptLineDistSq(x1, y1, x2, y2, x, y, null)>allowedDist) break; double dt = distance(x1, y1, x, y); if (dt>maxd){ maxd = dt; xx = x; yy = y; } } j--; if (distance(x1, y1, xx, yy)>MINLENGTH){ TrackSegment ts = TrackSegment.createStraightSeg(dist, x1, y1, xx, yy); rs.add(ts); dist+=ts.length; } else { xx = x1; yy = y1; } } else { double ox = result[0]; double oy = result[1]; double maxa = -100000; Vector2D start = new Vector2D(x1-ox,y1-oy); double a2 = new Vector2D(x2-ox,y2-oy).angle(start); double a3 = new Vector2D(x3-ox,y3-oy).angle(start); if (maxa<Math.abs(a2)){ maxa = Math.abs(a2); xx = x2; yy = y2; }; if (maxa<Math.abs(a3)){ maxa = Math.abs(a3); xx = x3; yy = y3; }; for (j=i+3;j<len;++j){ double dx = v[j].x-ox; double dy = v[j].y-oy; if (Math.abs(Math.sqrt(dx*dx+dy*dy)-radius)>EPSILON) break; double a = new Vector2D(dx,dy).angle(start); if (maxa<Math.abs(a)){ maxa = a; xx = v[j].x; yy = v[j].y; }; } j--; TrackSegment ts = TrackSegment.createTurnSeg(dist, ox, oy, radius, x1, y1, xx, yy,x2,y2); if (ts.length>MINLENGTH){ rs.add(ts); dist += ts.length; } else { xx = x1; yy = y1; } } i = j; }//end of while return rs; } public static ObjectList<TrackSegment> segmentize(Collection<Vector2D> v,double dist){ Vector2D[] vv = new Vector2D[v.size()]; v.toArray(vv); return segmentize(vv, dist); } public static ObjectList<TrackSegment> segmentize(Vector2D[] v,double dist){ if (v==null || v.length<2) return null; ObjectArrayList<TrackSegment> rs = new ObjectArrayList<TrackSegment>(); int len = v.length; int i=0; double allowedDist = EPSILON*EPSILON; double xx=v[0].x; double yy=v[0].y; TrackSegment ts = null; while (i<len-1){ double[] result = new double[3]; double x1 = xx; double x2 = v[i+1].x; double y1 = yy; double y2 = v[i+1].y; if (i==len-2){ // TrackSegment s = TrackSegment.createStraightSeg(0, x1, y1, x2, y2); // if (ts!=null) // s.distanceFromLocalOrigin = getDistNextSegment(ts, s); // ts = s; // rs.add(ts); // dist+=ts.length; break; } double x3 = v[i+2].x; double y3 = v[i+2].y; boolean isCircle = Geom.getCircle(x1, y1, x2, y2, x3, y3, result); double radius = (isCircle) ? Math.sqrt(result[2]) : Double.MAX_VALUE; int j=i+3; if (!isCircle || radius>Segment.MAX_RADIUS-1){//is a straight line for (j=i+3;j<len;++j){ double x = v[j].x; double y = v[j].y; if (Geom.ptLineDistSq(x1, y1, x2, y2, x, y, null)>allowedDist) break; } if (j>len) break; xx = v[j-1].x; yy = v[j-1].y; TrackSegment s = TrackSegment.createStraightSeg(dist, x1, y1, xx, yy); if (ts!=null) s.distanceFromLocalOrigin = getDistNextSegment(ts, s); ts = s; rs.add(ts); if (j>=len) break; xx = v[j].x; yy = v[j].y; } else { int r = (int)Math.round(radius); int maxj = -1; int maxr = r; double maxk = -1; Vector2D pp = null; Vector2D t = new Vector2D(x1+x2,y1+y2).times(0.5d); Vector2D q = new Vector2D(result[0],result[1]); double d = t.distanceSq(v[i]); if (i>len-3) return rs; if (i==len-3){ radius = r; Vector2D p = t.plus(q.minus(t).normalised().times(Math.sqrt(radius*radius-d))); TrackSegment s = TrackSegment.createTurnSeg(dist, p.x, p.y, radius, x1, y1, x3, y3,x2,y2); if (ts!=null) s.distanceFromLocalOrigin = getDistNextSegment(ts, s); ts = s; rs.add(ts); return rs; } int lim = 5; for (int rr = r-1;rr<=r+1;++rr){ radius = rr; Vector2D p = t.plus(q.minus(t).normalised().times(Math.sqrt(radius*radius-d))); double ox = p.x; double oy = p.y; boolean ok = false; int k = (rr==r) ? 1 : 0; int ti = 0; for (j=i+1;j<len;++j){ double dx = v[j].x-ox; double dy = v[j].y-oy; // System.out.print(Math.abs(Math.sqrt(dx*dx+dy*dy)-radius)+" "); if (Math.abs(Math.sqrt(dx*dx+dy*dy)-radius)>=0.01d || j==len-1){ if (j<3) break; double a1 = v[j-3].x; double a2 = v[j-2].x; double a3 = v[j-1].x; double b1 = v[j-3].y; double b2 = v[j-2].y; double b3 = v[j-1].y; double[] rrr = new double[3]; Geom.getCircle(a1, b1, a2, b2, a3, b3, rrr); rrr[2] = Math.sqrt(rrr[2]); int tr = (int)Math.round(rrr[2]); if (Math.abs(rr-tr)<=1) ok = true; if (ti<lim){ ti++; if (tr==rr) k++; } break; } if (j>i+3 && ti<lim){ ti++; double a1 = v[j-3].x; double a2 = v[j-2].x; double a3 = v[j-1].x; double b1 = v[j-3].y; double b2 = v[j-2].y; double b3 = v[j-1].y; double[] rrr = new double[3]; Geom.getCircle(a1, b1, a2, b2, a3, b3, rrr); rrr[2] = Math.sqrt(rrr[2]); int tr = (int)Math.round(rrr[2]); if (Math.abs(rr-tr)>3) { ok = false; break; } if (tr==rr) k++; } } // System.out.println(); if (j<i+3) continue; if (j>len) break; if (ok){ if (j>maxj){ maxj = j; maxr = rr; pp = p; maxk = (k+0.0d)/(ti+0.0d); } else if (j==maxj && maxk<(k+0.0d)/(ti+0.0d)){ maxr = rr; pp = p; maxk = (k+0.0d)/(ti+0.0d); } } } if (j<i+3 || maxj<0) { i++; xx = v[i].x; yy = v[i].y; continue; } j = maxj; radius = maxr; if (j==i+3){ if (j>len-3){ if (v[i].distance(v[i+1])>v[i+2].distance(v[i+3])){ i++; xx = v[i].x; yy = v[i].y; continue; } } } xx = v[j-1].x; yy = v[j-1].y; TrackSegment s = TrackSegment.createTurnSeg(dist, pp.x, pp.y, radius, x1, y1, xx, yy,x2,y2); if (ts!=null) s.distanceFromLocalOrigin = getDistNextSegment(ts, s); ts = s; rs.add(ts); if (j>=len) break; xx = v[j].x; yy = v[j].y; } i = j; }//end of while return rs; } public static boolean isMiddle(Vector2D p, Vector2D p1, Vector2D p2){ return (p.x<= Math.max(p1.x, p2.x) && p.x>= Math.min(p1.x, p2.x) && (p.y<=Math.max(p1.y, p2.y)) && p.y >= Math.min(p1.y, p2.y)); } public static double getDistNextSegment(TrackSegment ts,TrackSegment n){ double dist = ts.length+ts.distanceFromLocalOrigin; double[] r = new double[3]; Vector2D s = new Vector2D(ts.endX,ts.endY); Vector2D e = new Vector2D(n.startX,n.startY); if (ts.type==0 && n.type == 0 ){ Geom.getLineLineIntersection(ts.startX, ts.startY, ts.endX, ts.endY, n.startX, n.startY, n.endX, n.endY, r); Vector2D p = new Vector2D(r[0],r[1]); dist += p.distance(ts.endX, ts.endY)+p.distance(n.startX, n.startY); } else if (ts.type==0){ r = Geom.getLineCircleIntersection(ts.startX, ts.startY, ts.endX, ts.endY, n.centerx, n.centery, n.radius); if (r==null) { r = new double[3]; Geom.ptLineDistSq(ts.startX, ts.startY, ts.endX, ts.endY, n.centerx, n.centery, r); } Vector2D p = new Vector2D(r[0],r[1]); if (r.length>=4 && !isMiddle(p, s, e)) p = new Vector2D(r[2],r[3]); Vector2D c = new Vector2D(n.centerx,n.centery); double angle = Vector2D.angle(p.minus(c), new Vector2D(n.startX-n.centerx,n.startY-n.centery)); if (angle>Math.PI) angle -= Math.PI*2; else if (angle<-Math.PI) angle += Math.PI*2; dist += p.distance(ts.endX, ts.endY)+Math.abs(angle)*n.radius; } else if (n.type==0){ r = Geom.getLineCircleIntersection(n.startX, n.startY, n.endX, n.endY, ts.centerx, ts.centery, ts.radius); if (r==null) { r = new double[3]; Geom.ptLineDistSq(n.startX, n.startY, n.endX, n.endY, ts.centerx, ts.centery, r); } Vector2D p = new Vector2D(r[0],r[1]); if (r.length>=4 && !isMiddle(p, s, e)) p = new Vector2D(r[2],r[3]); Vector2D c = new Vector2D(ts.centerx,ts.centery); double angle = Vector2D.angle(p.minus(c), new Vector2D(ts.startX-ts.centerx,ts.startY-ts.centery)); if (angle>Math.PI) angle -= Math.PI*2; else if (angle<-Math.PI) angle += Math.PI*2; dist += p.distance(e)+Math.abs(angle)*ts.radius; } else { r = Geom.getCircleCircleIntersection(ts.centerx, ts.centery, ts.radius, n.centerx, n.centery, n.radius); if (r!=null){ Vector2D p = new Vector2D(r[0],r[1]); if (r.length>=4 && !isMiddle(p, s, e)) p = new Vector2D(r[2],r[3]); Vector2D c = new Vector2D(n.centerx,n.centery); double angle = Vector2D.angle(p.minus(c), new Vector2D(n.startX-n.centerx,n.startY-n.centery)); if (angle>Math.PI) angle -= Math.PI*2; else if (angle<-Math.PI) angle += Math.PI*2; dist += Math.abs(angle)*n.radius; c = new Vector2D(ts.centerx,ts.centery); angle = Vector2D.angle(p.minus(c), new Vector2D(ts.startX-ts.centerx,ts.startY-ts.centery)); if (angle>Math.PI) angle -= Math.PI*2; else if (angle<-Math.PI) angle += Math.PI*2; dist += Math.abs(angle)*ts.radius; } } return dist; } public static ObjectList<TrackSegment> segmentize(Vector2D[] v,double dist,ObjectList<Segment> track){ if (v==null || v.length<2) return null; ObjectArrayList<TrackSegment> rs = new ObjectArrayList<TrackSegment>(); int len = v.length; int i=0; double allowedDist = EPSILON*EPSILON; double xx=v[0].x; double yy=v[0].y; TrackSegment ts = null; while (i<len-1){ double[] result = new double[3]; double x1 = xx; double x2 = v[i+1].x; double y1 = yy; double y2 = v[i+1].y; if (i==len-2){ TrackSegment s = TrackSegment.createStraightSeg(0, x1, y1, x2, y2); if (ts!=null) s.distanceFromLocalOrigin = getDistNextSegment(ts, s); rs.add(ts); dist+=ts.length; break; } double x3 = v[i+2].x; double y3 = v[i+2].y; boolean isCircle = Geom.getCircle(x1, y1, x2, y2, x3, y3, result); double radius = (isCircle) ? Math.sqrt(result[2]) : Double.MAX_VALUE; int j=i+3; if (!isCircle || radius>Segment.MAX_RADIUS-1){//is a straight line for (j=i+3;j<len;++j){ double x = v[j].x; double y = v[j].y; if (Geom.ptLineDistSq(x1, y1, x2, y2, x, y, null)>allowedDist) break; } if (j>len) break; xx = v[j-1].x; yy = v[j-1].y; TrackSegment s = TrackSegment.createStraightSeg(0, x1, y1, xx, yy); if (ts!=null) s.distanceFromLocalOrigin = getDistNextSegment(ts, s); ts = s; rs.add(ts); dist+=ts.length; if (j>=len) break; xx = v[j].x; yy = v[j].y; } else { int r = (int)Math.round(radius); int maxj = -1; int maxr = r; Vector2D pp = null; for (int rr = r-1;rr<=r-1;++rr){ radius = rr; Vector2D p = new Vector2D(x1+x3,y1+y3).times(0.5d); Vector2D q = new Vector2D(result[0],result[1]); p = p.plus(q.minus(p).normalised().times(radius)); double ox = p.x; double oy = p.y; for (j=i+4;j<len;++j){ double dx = v[j].x-ox; double dy = v[j].y-oy; if (Math.abs(Math.sqrt(dx*dx+dy*dy)-radius)>=0.1d) break; } if (j>len) break; if (j>maxj){ maxj = j; maxr = rr; pp = new Vector2D(ox,oy); } } j = maxj; radius = maxr; xx = v[j-1].x; yy = v[j-1].y; TrackSegment s = TrackSegment.createTurnSeg(0, pp.x, pp.y, radius, x1, y1, xx, yy,x2,y2); if (ts!=null) s.distanceFromLocalOrigin = getDistNextSegment(ts, s); ts = s; rs.add(ts); dist += ts.length; if (j>=len) break; xx = v[j].x; yy = v[j].y; } i = j; }//end of while return rs; } public static void line(double xx0, double yy0, double xx1, double yy1,XYSeries series) { int x0 = (int)Math.round(xx0*10); int y0 = (int)Math.round(yy0*10); int x1 = (int)Math.round(xx1*10); int y1 = (int)Math.round(yy1*10); int dy = y1 - y0; int dx = x1 - x0; int stepx, stepy; if (dy < 0) { dy = -dy; stepy = -1; } else { stepy = 1; } if (dx < 0) { dx = -dx; stepx = -1; } else { stepx = 1; } dy <<= 1; // dy is now 2*dy dx <<= 1; // dx is now 2*dx series.add(x0/10.0d, y0/10.0d); if (dx > dy) { int fraction = dy - (dx >> 1); // same as 2*dy - dx while (x0 != x1) { if (fraction >= 0) { y0 += stepy; fraction -= dx; // same as fraction -= 2*dx } x0 += stepx; fraction += dy; // same as fraction -= 2*dy series.add( x0/10.0d, y0/10.0d); } } else { int fraction = dx - (dy >> 1); while (y0 != y1) { if (fraction >= 0) { x0 += stepx; fraction -= dy; } y0 += stepy; fraction += dx; series.add( x0/10.0d, y0/10.0d); } } } public static void circle(double xx,double yy,double r,XYSeries series) { long x = Math.round(xx*10); long y = Math.round(yy*10); long radius = Math.round(r*10); long discriminant = (5 - radius<<2)>>2 ; long i = 0, j = radius ; while (i<=j) { series.add((x+i)/10.d,(y-j)/10.d) ; series.add((x+j)/10.d,(y-i)/10.d) ; series.add((x+i)/10.d,(y+j)/10.d) ; series.add((x+j)/10.d,(y+i)/10.d) ; series.add((x-i)/10.d,(y-j)/10.d) ; series.add((x-j)/10.d,(y-i)/10.d) ; series.add((x-i)/10.d,(y+j)/10.d) ; series.add((x-j)/10.d,(y+i)/10.d) ; i++ ; if (discriminant<0) { discriminant += (i<<1) + 1 ; } else { j-- ; discriminant += 1+ (i - j)<<1 ; } } } public static void arc(double xx,double yy,double r,double startX,double startY,double arc,XYSeries series) { Vector2D center = new Vector2D(xx,yy); Vector2D start = new Vector2D(startX,startY).minus(center); double length = Math.abs(arc*r); int num = (int)(length*2); if (num<1) num=1; arc = -arc; double step = arc/num; double angle = 0.0d; Vector2D point = null; for (int i=0;i<num;++i){ point = start.rotated(angle).plus(center); series.add(point.x,point.y); angle += step; } } public static TrackSegment cutOff(TrackSegment ts,double dist){ if (ts.distanceFromLocalOrigin+ts.length<dist) return null; if (ts.distanceFromLocalOrigin>dist) return ts; double d = dist-ts.distanceFromLocalOrigin; if (ts.type==STRT){ // TrackSegment t = TrackSegment.createStraightSeg(dist, ts.startX, ts.startY-d, ts.endX, ts.endY-d); } else { double arc = d/ts.radius; if (ts.type==LFT) arc = -arc; Vector2D center = new Vector2D(ts.centerx,ts.centery); Vector2D v = new Vector2D(ts.startX-ts.centerx,ts.startY-ts.centery); v = center.plus(v.rotated(-arc)); Vector2D e = new Vector2D(ts.endX-ts.centerx,ts.endY-ts.centery); e = center.plus(e.rotated(-arc)); return TrackSegment.createTurnSeg(dist, ts.centerx, ts.centery, ts.radius, v.x, v.y, e.x, e.y, center.x, center.y); } return null; } public static void drawTrack(ObjectList<TrackSegment> ts,final String title,double dist){ XYSeries series = new XYSeries("Curve"); if (ts==null) return; for (TrackSegment t : ts){ if (t.distanceFromLocalOrigin+t.length<dist) continue; t= TrackSegment.cutOff(t, dist); if (t.type==STRT){ line(t.startX, t.startY, t.endX, t.endY, series); } else { arc(t.centerx, t.centery, t.radius, t.startX,t.startY,t.arc,series); } } XYDataset xyDataset = new XYSeriesCollection(series); // Create plot and show it final JFreeChart chart = ChartFactory.createScatterPlot(title, "x", "y", xyDataset, PlotOrientation.VERTICAL, false, true, false ); chart.getXYPlot().getDomainAxis().setRange(-60.0,60.0); chart.getXYPlot().getRangeAxis().setRange(-10.0,110.0); Thread p = new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub try{ BufferedImage image = chart.createBufferedImage(500, 500); ImageIO.write(image, "png", new File(title+".png")); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }); p.start(); } public static double cnvAngle(double angle){ return -angle; } public static void addEdgeCircle(XYPlot xyPlot,ObjectList<TrackSegment> ts){ // BasicStroke bs = new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL, // 1.0f, new float[] {2.0f, 10.0f}, 0.0f); for (TrackSegment t : ts){ if (t.type==STRT){ // line(t.startX, t.startY, t.endX, t.endY, series); Line2D line = new Line2D.Double(t.startX, t.startY, t.endX, t.endY); XYShapeAnnotation lineAnnotation = new XYShapeAnnotation(line); xyPlot.addAnnotation(lineAnnotation); } else if (t.arc!=0 && t.radius>0){ double cnx = t.centerx; double cny = t.centery; double w = t.radius; Ellipse2D circle = new Ellipse2D.Double(cnx-w, cny-w, w*2, w*2); XYShapeAnnotation arcAnnotation = new XYShapeAnnotation(circle); xyPlot.addAnnotation(arcAnnotation); // arc(t.centerx, t.centery, t.radius, t.startX,t.startY,t.arc,series); // series.add(t.centerx,t.centery); } }//*/ } public static void drawArrowLabel(XYPlot xyPlot,String text,double x, double y,double angle,int fontsize){ // final CircleDrawer cd = new CircleDrawer(Color.red, new BasicStroke(1.0f), null); final XYPointerAnnotation pointer = new XYPointerAnnotation(text, x, y, angle); pointer.setFont(new java.awt.Font("Arial", java.awt.Font.BOLD, fontsize)); xyPlot.addAnnotation(pointer); } public static void drawText(XYPlot xyPlot,String text,double x, double y,int fontsize){ // final CircleDrawer cd = new CircleDrawer(Color.red, new BasicStroke(1.0f), null); final XYTextAnnotation pointer = new XYTextAnnotation(text,x,y); pointer.setFont(new java.awt.Font("Arial", java.awt.Font.BOLD, fontsize)); xyPlot.addAnnotation(pointer); } public static void drawText(XYPlot xyPlot,String text,double x, double y,int fontsize,Color col){ // final CircleDrawer cd = new CircleDrawer(Color.red, new BasicStroke(1.0f), null); final XYTextAnnotation pointer = new XYTextAnnotation(text,x,y); pointer.setFont(new java.awt.Font("Arial", java.awt.Font.BOLD, fontsize)); pointer.setPaint(col); xyPlot.addAnnotation(pointer); } public static void drawLine(XYPlot xyPlot,double startX,double startY,double endX,double endY){ Line2D line = new Line2D.Double(startX, startY, endX, endY); XYShapeAnnotation lineAnnotation = new XYShapeAnnotation(line); xyPlot.addAnnotation(lineAnnotation); } public static void drawLine(XYPlot xyPlot,double startX,double startY,double endX,double endY,Color color){ Line2D line = new Line2D.Double(startX, startY, endX, endY); BasicStroke bs = new BasicStroke(); XYShapeAnnotation lineAnnotation = new XYShapeAnnotation(line,bs,color); xyPlot.addAnnotation(lineAnnotation); } public static void drawLine(XYPlot xyPlot,double startX,double startY,double endX,double endY,Stroke bs){ Line2D line = new Line2D.Double(startX, startY, endX, endY); XYShapeAnnotation lineAnnotation = new XYShapeAnnotation(line,bs,Color.GRAY); xyPlot.addAnnotation(lineAnnotation); } public static void drawRectangle (XYPlot xyPlot,double lx,double ly,double rx,double ry){ Rectangle2D rectangle = new Rectangle2D.Double(lx,ly,rx,ry); XYShapeAnnotation rectangleAnnotation = new XYShapeAnnotation(rectangle); xyPlot.addAnnotation(rectangleAnnotation); } public static void drawRectangle (XYPlot xyPlot,double lx,double ly,double rx,double ry,double angle,Color color){ BasicStroke bs = new BasicStroke(); Rectangle2D rectangle = new Rectangle2D.Double(lx,ly,rx,ry); AffineTransform at = AffineTransform.getRotateInstance(angle, lx, ry); Shape newShape = at.createTransformedShape(rectangle); XYShapeAnnotation rectangleAnnotation = new XYShapeAnnotation(newShape,bs,color,color); xyPlot.addAnnotation(rectangleAnnotation); } public static void drawCircle(XYPlot xyPlot,double cnx,double cny,double w){ Ellipse2D circle = new Ellipse2D.Double(cnx-w, cny-w, w*2, w*2); XYShapeAnnotation arcAnnotation = new XYShapeAnnotation(circle); xyPlot.addAnnotation(arcAnnotation); } public static void drawCircle(XYPlot xyPlot,double cnx,double cny,double w,Color color){ BasicStroke bs = new BasicStroke(); Ellipse2D circle = new Ellipse2D.Double(cnx-w, cny-w, w*2, w*2); XYShapeAnnotation arcAnnotation = new XYShapeAnnotation(circle,bs,color); xyPlot.addAnnotation(arcAnnotation); } public static void drawCircle(XYPlot xyPlot,double cnx,double cny,double w,Stroke bs){ Ellipse2D circle = new Ellipse2D.Double(cnx-w, cny-w, w*2, w*2); XYShapeAnnotation arcAnnotation = new XYShapeAnnotation(circle,bs,Color.GRAY); xyPlot.addAnnotation(arcAnnotation); } public static void drawCircle(XYPlot xyPlot,double cnx,double cny,double w,Stroke bs,Color color){ Ellipse2D circle = new Ellipse2D.Double(cnx-w, cny-w, w*2, w*2); XYShapeAnnotation arcAnnotation = new XYShapeAnnotation(circle,bs,color); xyPlot.addAnnotation(arcAnnotation); } public static void drawArc(XYPlot xyPlot,double cnx,double cny,double w, double startX,double startY,double endX,double endY){ double startAngle = Math.toDegrees(Math.atan2(startY-cny, startX-cnx)); double angle = Vector2D.angle(startX-cnx,startY-cny,endX-cnx,endY-cny); if (angle<-Math.PI) angle += 2*Math.PI; else if (angle>Math.PI) angle -= 2*Math.PI; // double arc = Math.abs(angle); double arcSz = Math.toDegrees(angle); Arc2D arc = new Arc2D.Double(cnx-w,cny-w,w*2,w*2,cnvAngle(startAngle),arcSz,Arc2D.OPEN); XYShapeAnnotation arcAnnotation = new XYShapeAnnotation(arc); xyPlot.addAnnotation(arcAnnotation); } public static void drawArc(XYPlot xyPlot,double cnx,double cny,double w, double startX,double startY,double endX,double endY,Stroke bs){ double startAngle = Math.toDegrees(Math.atan2(startY-cny, startX-cnx)); double angle = Vector2D.angle(startX-cnx,startY-cny,endX-cnx,endY-cny); if (angle<-Math.PI) angle += 2*Math.PI; else if (angle>Math.PI) angle -= 2*Math.PI; // double arc = Math.abs(angle); double arcSz = Math.toDegrees(angle); Arc2D arc = new Arc2D.Double(cnx-w,cny-w,w*2,w*2,cnvAngle(startAngle),arcSz,Arc2D.OPEN); XYShapeAnnotation arcAnnotation = new XYShapeAnnotation(arc,bs,Color.GRAY); xyPlot.addAnnotation(arcAnnotation); } public static void addEdge(XYPlot xyPlot,ObjectList<TrackSegment> ts){ BasicStroke bs = new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] {2.0f, 10.0f}, 0.0f); for (TrackSegment t : ts){ if (t.type==STRT){ // line(t.startX, t.startY, t.endX, t.endY, series); drawLine(xyPlot, t.startX, t.startY, t.endX+0.001, t.endY+0.001); } else if (t.radius>=0){ double cnx = t.centerx; double cny = t.centery; double w = t.radius; // if (t.type==-1){ // Ellipse2D circle = new Ellipse2D.Double(cnx-w, cny-w, w*2, w*2); // XYShapeAnnotation arcAnnotation = new XYShapeAnnotation(circle); // xyPlot.addAnnotation(arcAnnotation); // } else { drawArc(xyPlot, cnx, cny, w, t.startX, t.startY, t.endX, t.endY); // } // arc(t.centerx, t.centery, t.radius, t.startX,t.startY,t.arc,series); // series.add(t.centerx,t.centery); } }//*/ } public static void arrow(XYPlot xyPlot,double x, double y,double angle){ // final CircleDrawer cd = new CircleDrawer(Color.red, new BasicStroke(1.0f), null); final XYPointerAnnotation pointer = new XYPointerAnnotation("", x, y, angle); pointer.setTipRadius(0); pointer.setArrowWidth(10); xyPlot.addAnnotation(pointer); } public static void arrow(XYPlot xyPlot,double x, double y,double angle,double arrowLen){ // final CircleDrawer cd = new CircleDrawer(Color.red, new BasicStroke(1.0f), null); final XYPointerAnnotation pointer = new XYPointerAnnotation("", x, y, angle); pointer.setTipRadius(0); pointer.setBaseRadius(arrowLen); pointer.setArrowWidth(10); xyPlot.addAnnotation(pointer); } public static void addEdgeArrow(XYPlot xyPlot,ObjectList<TrackSegment> ts){ BasicStroke bs = new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] {2.0f, 10.0f}, 0.0f); for (TrackSegment t : ts){ if (t.type==STRT){ // line(t.startX, t.startY, t.endX, t.endY, series); drawLine(xyPlot, t.startX, t.startY, t.endX+0.001, t.endY+0.001); arrow(xyPlot, t.startX, t.startY, -Math.atan2(t.endY-t.startY, t.endX-t.startX),0.5); arrow(xyPlot, t.endX, t.endY, Math.PI-Math.atan2(t.endY-t.startY, t.endX-t.startX),0.5); } else if (t.radius>=0){ double cnx = t.centerx; double cny = t.centery; double w = t.radius; // if (t.type==-1){ // Ellipse2D circle = new Ellipse2D.Double(cnx-w, cny-w, w*2, w*2); // XYShapeAnnotation arcAnnotation = new XYShapeAnnotation(circle); // xyPlot.addAnnotation(arcAnnotation); // } else { double offset = Math.PI*0.5*t.type; drawArc(xyPlot, cnx, cny, w, t.startX, t.startY, t.endX, t.endY); double angle = -Math.atan2(t.startY-t.centery, t.startX-t.centerx)+offset; arrow(xyPlot,t.startX,t.startY,angle,0.5); angle = -Math.PI*0.5+Math.atan2(t.endY-t.centerx, t.endX-t.centerx)+offset; arrow(xyPlot,t.endX,t.endY,angle,0.5); // } // arc(t.centerx, t.centery, t.radius, t.startX,t.startY,t.arc,series); // series.add(t.centerx,t.centery); } }//*/ } public static void drawTrack(ObjectList<TrackSegment> ts,final String title,boolean addEdge){ XYSeries series = new XYSeries("Curve"); if (ts==null) return; // for (int i=0;i<numPointLeft;++i){ // series.add(leftEgdeX[i], leftEgdeY[i]); // } /*for (TrackSegment t : ts){ if (t.type==STRT){ line(t.startX, t.startY, t.endX, t.endY, series); } else { arc(t.centerx, t.centery, t.radius, t.startX,t.startY,t.arc,series); series.add(t.centerx,t.centery); } }//*/ // double toMiddle = CircleDriver2.toMiddle; // series.add(CircleDriver2.toMiddle,0); // series.add(0,0); // // double px = -1; // double py = -6; // series.add(px,py); // for (int i=0;i<numPointRight;++i){ // series.add(rightEgdeX[i], rightEgdeY[i]); // } int nL = CircleDriver2.edgeDetector.nLsz; int nR = CircleDriver2.edgeDetector.nRsz; Vector2D[] left = EdgeDetector.nleft; Vector2D[] right = EdgeDetector.nright; for (int i=0;i<nL;++i){ series.add(left[i].x, left[i].y); } for (int i=0;i<nR;++i){ series.add(right[i].x, right[i].y); } series.add(CircleDriver2.edgeDetector.originalHighest.x,CircleDriver2.edgeDetector.originalHighest.y); XYDataset xyDataset = new XYSeriesCollection(series); // Create plot and show it final JFreeChart chart = ChartFactory.createScatterPlot("", "x", "y", xyDataset, PlotOrientation.VERTICAL, false, true, false ); XYPlot xyPlot = chart.getXYPlot(); xyPlot.getDomainAxis().setRange(-25.0,25.0); xyPlot.getRangeAxis().setRange(-5.0,105.0); if (addEdge) addEdge(xyPlot, CircleDriver2.trackData); Thread p = new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub try{ BufferedImage image = chart.createBufferedImage(500, 500); ImageIO.write(image, "png", new File(title+".png")); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }); p.start(); } public TrackSegment(int type, double centerx, double centery, double length, double distanceFromLocalOrigin, double radius, double arc, double startX, double startY, double endX, double endY) { this.type = type; this.centerx = centerx; this.centery = centery; this.length = length; this.distanceFromLocalOrigin = distanceFromLocalOrigin; this.radius = radius; this.arc = arc; this.startX = startX; this.startY = startY; this.endX = endX; this.endY = endY; } public void copy(int type, double centerx, double centery, double length, double distanceFromLocalOrigin, double radius, double arc, double startX, double startY, double endX, double endY) { this.type = type; this.centerx = centerx; this.centery = centery; this.length = length; this.distanceFromLocalOrigin = distanceFromLocalOrigin; this.radius = radius; this.arc = arc; this.startX = startX; this.startY = startY; this.endX = endX; this.endY = endY; } /** * @return the type */ public int getType() { return type; } /** * @param type the type to set */ public void setType(int type) { this.type = type; } /** * @return the centerx */ public double getCenterx() { return centerx; } /** * @param centerx the centerx to set */ public void setCenterx(double centerx) { this.centerx = centerx; } /** * @return the centery */ public double getCentery() { return centery; } /** * @param centery the centery to set */ public void setCentery(double centery) { this.centery = centery; } /** * @return the length */ public double getLength() { return length; } /** * @param length the length to set */ public void setLength(double length) { this.length = length; } /** * @return the distanceFromLocalOrigin */ public double getDistanceFromLocalOrigin() { return distanceFromLocalOrigin; } /** * @param distanceFromLocalOrigin the distanceFromLocalOrigin to set */ public void setDistanceFromLocalOrigin(double distanceFromLocalOrigin) { this.distanceFromLocalOrigin = distanceFromLocalOrigin; } /** * @return the radius */ public double getRadius() { return radius; } /** * @param radius the radius to set */ public void setRadius(double radius) { this.radius = radius; } /** * @return the arc */ public double getArc() { return arc; } /** * @param arc the arc to set */ public void setArc(double arc) { this.arc = arc; } /** * @return the startX */ public double getStartX() { return startX; } /** * @param startX the startX to set */ public void setStartX(double startX) { this.startX = startX; } /** * @return the startY */ public double getStartY() { return startY; } /** * @param startY the startY to set */ public void setStartY(double startY) { this.startY = startY; } /** * @return the endX */ public double getEndX() { return endX; } /** * @param endX the endX to set */ public void setEndX(double endX) { this.endX = endX; } /** * @return the endY */ public double getEndY() { return endY; } /** * @param endY the endY to set */ public void setEndY(double endY) { this.endY = endY; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof TrackSegment)) return false; final TrackSegment other = (TrackSegment) obj; if (Double.doubleToLongBits(arc) != Double.doubleToLongBits(other.arc)) return false; if (Double.doubleToLongBits(centerx) != Double .doubleToLongBits(other.centerx)) return false; if (Double.doubleToLongBits(centery) != Double .doubleToLongBits(other.centery)) return false; if (Double.doubleToLongBits(distanceFromLocalOrigin) != Double .doubleToLongBits(other.distanceFromLocalOrigin)) return false; if (Double.doubleToLongBits(endX) != Double .doubleToLongBits(other.endX)) return false; if (Double.doubleToLongBits(endY) != Double .doubleToLongBits(other.endY)) return false; if (Double.doubleToLongBits(length) != Double .doubleToLongBits(other.length)) return false; if (Double.doubleToLongBits(radius) != Double .doubleToLongBits(other.radius)) return false; if (Double.doubleToLongBits(startX) != Double .doubleToLongBits(other.startX)) return false; if (Double.doubleToLongBits(startY) != Double .doubleToLongBits(other.startY)) return false; if (type != other.type) return false; return true; } /** * Constructs a <code>String</code> with all attributes * in name = value format. * * @return a <code>String</code> representation * of this object. */ public Vector2D[] getSegIntersection(double x1,double y1,double x2,double y2){ double[] r = null; if (type==STRT){ r = new double[3]; Object rs = Geom.getSegSegIntersection(x1, y1, x2, y2, startX, startY, endX, endY, r); if (rs!=null && rs != Geom.PARALLEL){ return new Vector2D[]{new Vector2D(r[0],r[1])}; } } else { r = Geom.getSegArcIntersection(x1, y1, x2, y2, centerx, centery, radius, arc, startX, startY, endX, endY); if (r==null || r.length<2) return null; Vector2D[] rs = new Vector2D[r.length/2]; for (int i = 0;i<rs.length;++i) rs[i] = new Vector2D(r[i*2],r[i*2+1]); return rs; } return null; } private static final int int2string(int ivalue,char[] s,int from){ if (ivalue==0){ s[from++]='0'; return from; } int ndigits = 0; if (ivalue<0) { s[from++] ='-'; ivalue = -ivalue; } while (ivalue>=int10pow[ndigits]) ndigits++; int digitno = from+ndigits-1; int c =ivalue%10; while ( ivalue != 0){ s[digitno--] = (char)(c+'0'); ivalue /= 10; c = ivalue%10; } return from+ndigits; } private static final int double2string(double val,char[] s,int from){ if (val==Double.MAX_VALUE){ System.arraycopy(MAX_DOUBLE_STRING, 0, s, from, MAX_DOUBLE_STRING.length); return from+MAX_DOUBLE_STRING.length; } long lval = Math.round(val*PRECISION); if (lval==0) { s[from++]='0'; return from; } if (lval<0){ s[from++] = '-'; lval = -lval; } int ndigits = 0; int rt = 0; int dotIndex; if (lval<=1000000000){ int ivalue = (int)lval; while (ivalue>=int10pow[ndigits]) ndigits++; dotIndex = ndigits-PRECISION_DIGIT; if (dotIndex<=0) { s[from++]='0'; s[from++]='.'; while (dotIndex++<0) s[from++]='0'; int digitno = from+ndigits-1; rt = digitno; rt++; int c =ivalue%10; while ( c == 0 ){ digitno--; rt--; ivalue /= 10; c = ivalue%10; } while ( ivalue != 0){ s[digitno--] = (char)(c+'0'); ivalue /= 10; c = ivalue%10; } } else { int c =ivalue%10; while ( c == 0 && ndigits>dotIndex){ ndigits--; ivalue /= 10; c = ivalue%10; } int digitno = from+ndigits; rt = digitno+1; if (ndigits==dotIndex) { digitno--; rt--; s[digitno--] = (char)(c+'0'); ivalue /= 10; c = ivalue%10; while ( ivalue != 0){ s[digitno--] = (char)(c+'0'); ivalue /= 10; c = ivalue%10; } return rt; } while ( ivalue != 0){ if (ndigits==dotIndex) { s[digitno--] = '.'; ndigits--; } ndigits--; s[digitno--] = (char)(c+'0'); ivalue /= 10; c = ivalue%10; } } } else { while (lval>=long10pow[ndigits]) ndigits++; dotIndex = ndigits-PRECISION_DIGIT; if (dotIndex<=0) { s[from++]='0'; s[from++]='.'; while (dotIndex++<0) s[from++]='0'; int digitno = from+ndigits-1; rt = digitno; rt++; int c =(int)(lval%10L); while ( c == 0 ){ digitno--; rt--; lval /= 10; c =(int)(lval%10L); } while ( lval != 0){ s[digitno--] = (char)(c+'0'); lval /= 10; c =(int)(lval%10L); } } else { int c =(int)(lval%10L); while ( c == 0 && ndigits>dotIndex){ ndigits--; lval /= 10; c =(int)(lval%10L); } int digitno = from+ndigits; rt = digitno+1; if (lval<=Integer.MAX_VALUE){ int ivalue = (int)lval; if (ndigits==dotIndex) { digitno--; rt--; s[digitno--] = (char)(c+'0'); ivalue /= 10; c = ivalue%10; while ( ivalue != 0){ s[digitno--] = (char)(c+'0'); ivalue /= 10; c = ivalue%10; } return rt; } while ( ivalue != 0){ if (ndigits==dotIndex) { s[digitno--] = '.'; ndigits--; } ndigits--; s[digitno--] = (char)(c+'0'); ivalue /= 10; c = ivalue%10; } } else { if (ndigits==dotIndex) { digitno--; rt--; s[digitno--] = (char)(c+'0'); lval /= 10; c =(int)(lval%10L); while ( lval != 0){ s[digitno--] = (char)(c+'0'); lval /= 10; c =(int)(lval%10L); } return rt; } while ( lval != 0){ if (ndigits==dotIndex) { s[digitno--] = '.'; ndigits--; } ndigits--; s[digitno--] = (char)(c+'0'); lval /= 10; c =(int)(lval%10L); } } } } return rt; } @Override public String toString() { int len = tp.length; len = int2string(this.type, buf, len); System.arraycopy(cntrx, 0, buf, len, cntrx.length); len+=cntrx.length; len = double2string(this.centerx, buf, len); System.arraycopy(cntry, 0, buf, len, cntry.length); len+=cntry.length; len = double2string(this.centery, buf, len); System.arraycopy(lngth, 0, buf, len, lngth.length); len+=lngth.length; len = double2string(this.length, buf, len); System.arraycopy(dist, 0, buf, len, dist.length); len+=dist.length; len = double2string(this.distanceFromLocalOrigin, buf, len); System.arraycopy(rad, 0, buf, len, rad.length); len+=rad.length; len = double2string(this.radius, buf, len); System.arraycopy(sX, 0, buf, len, sX.length); len+=sX.length; len = double2string(this.startX, buf, len); System.arraycopy(sY, 0, buf, len, sY.length); len+=sY.length; len = double2string(this.startY, buf, len); System.arraycopy(eX, 0, buf, len, eX.length); len+=eX.length; len = double2string(this.endX, buf, len); System.arraycopy(eY, 0, buf, len, eY.length); len+=eY.length; len = double2string(this.endY, buf, len); System.arraycopy(fin, 0, buf, len, fin.length); len+=fin.length; return new String(buf,0,len); } public static ObjectArrayList<TrackSegment> combine(TrackSegment a, TrackSegment b){ ObjectArrayList<TrackSegment> rs = new ObjectArrayList<TrackSegment>(); double dist1 = a.distanceFromLocalOrigin; double l1 = a.length; double dist2 = b.distanceFromLocalOrigin; double l2 = b.length; if (a.type==b.type){ if (a.type!=STRT){ if (dist1+l1<dist2){ rs.add(a); rs.add(b); return rs; } else if (dist2+l2<dist1){ rs.add(b); rs.add(a); return rs; } } if (Math.abs(a.radius-b.radius)<=0.1){ double d = Math.min(dist1, dist2); double e = Math.max(dist1+l1, dist2+l2); double l = e-d; double r = Math.round(a.radius); double startX = (dist1<dist2) ? a.startX : b.startX; double startY = (dist1<dist2) ? a.startY : b.startY; Vector2D v = new Vector2D(startX-a.centerx,startY-a.centery); Vector2D center = new Vector2D(a.centerx,a.centery); double arc = (r==0) ? 0 : l/r; if (a.type==LFT) arc = -arc; if (arc!=0) v = center.plus(v.rotated(arc)); else v = v.plus(new Vector2D(0,l)); double endX = v.x; double endY = v.y; TrackSegment ts = (a.type==STRT) ? createStraightSeg(d, 0, 0, 0, e) : createTurnSeg(d, a.centerx, a.centery, a.radius, startX, startY, endX, endY, a.centerx, a.centery); rs.add(ts); } else { rs.add(a); // rs.add(b); } } else { if (dist1>dist2+l2){ rs.add(b); rs.add(a); } else if (dist2>dist1+l1){ rs.add(a); rs.add(b); } else if (dist1+l1>dist2+l2){ rs.add(a); } else { rs.add(a); } } return rs; } }
import java.util.Scanner; public class CurrencyConverter { public static void main(String[] args) { Scanner scan = new Scanner(System.in); double money = Double.parseDouble(scan.nextLine()); String inputCurrency = scan.nextLine(); String outputCurrency = scan.nextLine(); if (inputCurrency.equals("USD")) { money = money * 1.79549; } else if (inputCurrency.equals("EUR")) { money = money * 1.95583; } else if (inputCurrency.equals("GBP")) { money = money * 2.53405; } if (outputCurrency.equals("USD")) { money = money / 1.79549; } else if (outputCurrency.equals("EUR")) { money = money / 1.95583; } else if (outputCurrency.equals("GBP")) { money = money / 2.53405; } System.out.printf("%.2f %s", money, outputCurrency); } }
package kr.co.shop.batch.member.repository.master; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Mapper; import kr.co.shop.batch.member.model.master.MbMember; import kr.co.shop.batch.member.repository.master.base.BaseMbMemberDao; @Mapper public interface MbMemberDao extends BaseMbMemberDao { /** * 기본 insert, update, delete 메소드는 BaseMbMemberDao 클래스에 구현 되어있습니다. * BaseMbMemberDao는 절대 수정 불가 하며 새로운 메소드 추가 하실 경우에는 해당 소스에서 작업 하시면 됩니다. * */ public MbMember selectByPrimaryKey(MbMember mbMember) throws Exception; /** * * @Desc : 휴대폰 번호로 수신거부 회원 정보 조회 * @Method Name : selectMerberList * @Date : 2019. 3. 13. * @Author : choi * @param mbMember * @return * @throws Exception */ public List<MbMember> selectMerberList(MbMember mbMember) throws Exception; /** * * @Desc : 회원정보 sns 수신여부 업데이트 * @Method Name : updateMerberSnsYn * @Date : 2019. 3. 13. * @Author : choi * @param newUser * @throws Exception */ public void updateMerberSnsYn(MbMember newUser) throws Exception; public List<MbMember> selectLongUnusedUserList(Map<String, Object> map) throws Exception; /** * @Desc : 휴면회원알림여부 업데이트 * @Method Name : updateInactMemberAlertYn * @Date : 2019. 5. 10. * @Author : 유성민 * @param mbMember * @return * @throws Exception */ public int updateInactMemberAlertYn(MbMember mbMember) throws Exception; /** * @Desc :변경이력순번 nextval * @Method Name : selectChngHistSeqNextVal * @Date : 2019. 5. 16. * @Author : 유성민 * @param memberNo * @return */ public int selectChngHistSeqNextVal(String memberNo) throws Exception; /** * @Desc : * @Method Name : selectIfMemberOnlineCount * @Date : 2019. 6. 28. * @Author : 유성민 * @param safeKey * @param safeKeySeq * @return */ public int selectIfMemberOnlineCount(String safeKey, String safeKeySeq) throws Exception; }
package com.hackathon.androidserver; import android.Manifest; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.telephony.SmsManager; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import com.hackathon.androidserver.model.FlightList; import com.hackathon.androidserver.network.GetDataService; import com.hackathon.androidserver.network.RetrofitClientInstance; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity { private static final int READ_SMS_PERMISSIONS_REQUEST = 1; private static final int SEND_SMS_PERMISSIONS_REQUEST = 0; private ArrayAdapter arrayAdapter; private ListView messages; private Button button; private GetDataService ListingService; List<String> messageList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); registerReceiver(broadcastReceiver, new IntentFilter("broadCastName")); getPermissionToReadSMS(); messages = (ListView) findViewById(R.id.Messages); Button apiCallButton=(Button)findViewById(R.id.button); arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, messageList); messages.setAdapter(arrayAdapter); ListingService = RetrofitClientInstance.getRetrofitInstance().create(GetDataService.class); apiCallButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { callListingAPI("1","9048050286"); } }); } BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Bundle b = intent.getExtras(); String messageBody = b.getString("messageBody"); String messageAddress = b.getString("messageAddress"); String str = "SMS From: " + messageAddress + "\n" + messageBody + "\n"; callListingAPI(messageBody,messageAddress); arrayAdapter.add(str); arrayAdapter.notifyDataSetChanged(); Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); } }; private void callListingAPI(String messageBody, final String messageAddress) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(messageBody).append("$").append(messageAddress); com.hackathon.androidserver.model.Message message=new com.hackathon.androidserver.model.Message(); message.setMobileNumber(messageAddress); message.setSearchCriteria(messageBody); if(messageBody.trim().length()==1) { message.setRepriceKey(messageBody); message.setSearchCriteria(null); } else{ message.setRepriceKey(null); } Call<List<FlightList>> call = ListingService.callFlightListingAPI(message); call.enqueue(new Callback<List<FlightList>>() { @Override public void onResponse(Call<List<FlightList>> call, Response<List<FlightList>> response) { List<FlightList>resultTest=response.body(); if(resultTest!=null && resultTest.size()>0) { StringBuilder messageText = new StringBuilder(); for (FlightList i : resultTest) { if (i.getId() != null) { messageText.append(i.getId()).append(")"); } if (i.getAirlines() != null) { messageText.append(i.getAirlines()); } if (i.getDeparture() != null) { messageText.append(i.getDeparture()); } if (i.getArrival() != null) { messageText.append(i.getArrival()); } if (i.getTotalcost() != null) { messageText.append(i.getTotalcost()); } if(i.getBookingConfirmationNumber()!=null){ messageText.append(i.getBookingConfirmationNumber()); } messageText.append("\n"); sendTextMessage(messageAddress, messageText.toString()); } Toast.makeText(getApplicationContext(),"success"+messageText.toString(),Toast.LENGTH_SHORT).show(); } Log.e("Response",response.body().get(0).getAirlines()); } @Override public void onFailure(Call<List<FlightList>> call, Throwable t) { Toast.makeText(getApplicationContext(),"fail",Toast.LENGTH_SHORT).show(); } }); } @SuppressLint("NewApi") @TargetApi(Build.VERSION_CODES.M) public void getPermissionToReadSMS() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) { if (shouldShowRequestPermissionRationale( Manifest.permission.READ_SMS)) { Toast.makeText(this, "Please allow permission!", Toast.LENGTH_SHORT).show(); } requestPermissions(new String[]{Manifest.permission.READ_SMS}, READ_SMS_PERMISSIONS_REQUEST); requestPermissions(new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSIONS_REQUEST); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { if (requestCode == READ_SMS_PERMISSIONS_REQUEST) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "Read SMS permission granted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Read SMS permission denied", Toast.LENGTH_SHORT).show(); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } public List<String> refreshSmsInbox() { messageList.clear(); ContentResolver contentResolver = getContentResolver(); Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null); int indexBody = smsInboxCursor.getColumnIndex("body"); int indexAddress = smsInboxCursor.getColumnIndex("address"); if (indexBody < 0 || !smsInboxCursor.moveToFirst()) { messageList.add("message empty"); return messageList; } do { String str = "SMS From: " + smsInboxCursor.getString(indexAddress) + "\n" + smsInboxCursor.getString(indexBody) + "\n"; messageList.add(str); arrayAdapter.add(str); } while (smsInboxCursor.moveToNext()); return messageList; } public void sendTextMessage(String address,String response){ SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(address, null, response, null, null); } }
/* AbstractWebApp.java Purpose: Description: History: Wed Mar 15 17:28:15 2006, Created by tomyeh Copyright (C) 2006 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.zk.ui.impl; import java.io.InputStream; import org.zkoss.lang.Library; import org.zkoss.util.Utils; import org.zkoss.util.logging.Log; import org.zkoss.io.Files; import org.zkoss.zk.Version; import org.zkoss.zk.ui.WebApp; import org.zkoss.zk.ui.Session; import org.zkoss.zk.ui.UiException; import org.zkoss.zk.ui.util.Configuration; import org.zkoss.zk.ui.metainfo.DefinitionLoaders; import org.zkoss.zk.ui.http.SimpleUiFactory; import org.zkoss.zk.ui.http.SimpleSessionCache; import org.zkoss.zk.ui.sys.WebAppCtrl; import org.zkoss.zk.ui.sys.SessionCtrl; import org.zkoss.zk.ui.sys.UiEngine; import org.zkoss.zk.ui.sys.UiFactory; import org.zkoss.zk.ui.sys.DesktopCacheProvider; import org.zkoss.zk.ui.sys.DesktopCache; import org.zkoss.zk.ui.sys.FailoverManager; import org.zkoss.zk.ui.sys.IdGenerator; import org.zkoss.zk.ui.sys.SessionCache; import org.zkoss.zk.ui.impl.SessionDesktopCacheProvider; import org.zkoss.zk.ui.impl.UiEngineImpl; import org.zkoss.zk.au.AuDecoder; /** * A skeletal implementation of {@link WebApp}. * * @author tomyeh */ abstract public class AbstractWebApp implements WebApp, WebAppCtrl { private static final Log log = Log.lookup(AbstractWebApp.class); private String _appnm; private Configuration _config; private UiEngine _engine; private DesktopCacheProvider _provider; private UiFactory _factory; private FailoverManager _failover; private IdGenerator _idgen; private SessionCache _sesscache; private AuDecoder _audec; private static String _build; /** Constructor. * * <p>Note: after constructed, it is not initialized completely. * For example, {@link #getConfiguration} returns null. * * <p>WebManager will initialize it later such as initializing * a {@link Configuration} instance by loading zk.xml, * and then calling {@link #init}. */ protected AbstractWebApp() { } public String getAppName() { return _appnm != null ? _appnm: "ZK"; } public void setAppName(String name) { _appnm = name != null ? name: ""; } public final String getVersion() { return Version.RELEASE; } public final String getBuild() { return _build == null ? loadBuild(): _build; } public int getSubversion(int portion) { return Utils.getSubversion(getVersion(), portion); } public final Configuration getConfiguration() { return _config; } public Object getAttribute(String name, boolean recurse) { return getAttribute(name); } public boolean hasAttribute(String name, boolean recurse) { return hasAttribute(name); } public Object setAttribute(String name, Object value, boolean recurse) { return setAttribute(name, value); } public Object removeAttribute(String name, boolean recurse) { return removeAttribute(name); } //WebAppCtrl// public void init(Object context, Configuration config) { if (_config != null) throw new IllegalStateException("Cannot be initialized twice"); if (config == null) throw new IllegalArgumentException("null"); final WebApp oldwapp = config.getWebApp(); if (oldwapp != null && oldwapp != this) throw new IllegalArgumentException("config already belongs to other Web app, "+oldwapp); _config = config; if (_appnm == null) _appnm = _config.getPreference("org.zkoss.zk.ui.WebApp.name", "ZK"); _config.setWebApp(this); Class cls = _config.getUiEngineClass(); if (cls == null) { _engine = new UiEngineImpl(); } else { try { _engine = (UiEngine)cls.newInstance(); } catch (Exception ex) { throw UiException.Aide.wrap(ex, "Unable to construct "+cls); } } cls = _config.getDesktopCacheProviderClass(); if (cls == null) { _provider = new SessionDesktopCacheProvider(); } else { try { _provider = (DesktopCacheProvider)cls.newInstance(); } catch (Exception ex) { throw UiException.Aide.wrap(ex, "Unable to construct "+cls); } } cls = _config.getUiFactoryClass(); if (cls == null) { _factory = new SimpleUiFactory(); } else { try { _factory = (UiFactory)cls.newInstance(); } catch (Exception ex) { throw UiException.Aide.wrap(ex, "Unable to construct "+cls); } } cls = _config.getFailoverManagerClass(); if (cls != null) { try { _failover = (FailoverManager)cls.newInstance(); } catch (Exception ex) { throw UiException.Aide.wrap(ex, "Unable to construct "+cls); } } cls = _config.getIdGeneratorClass(); if (cls != null) { try { _idgen = (IdGenerator)cls.newInstance(); } catch (Exception ex) { throw UiException.Aide.wrap(ex, "Unable to construct "+cls); } } cls = _config.getSessionCacheClass(); if (cls == null) { _sesscache = new SimpleSessionCache(); } else { try { _sesscache = (SessionCache)cls.newInstance(); } catch (Exception ex) { throw UiException.Aide.wrap(ex, "Unable to construct "+cls); } } cls = _config.getAuDecoderClass(); if (cls != null) { try { _audec = (AuDecoder)cls.newInstance(); } catch (Exception ex) { throw UiException.Aide.wrap(ex, "Unable to construct "+cls); } } _engine.start(this); _provider.start(this); _factory.start(this); if (_failover != null) { try { _failover.start(this); } catch (AbstractMethodError ex) { //backward compatible } } _sesscache.init(this); _config.invokeWebAppInits(); } public void destroy() { try { _config.invokeWebAppCleanups(); } catch (Throwable ex) { ex.printStackTrace(); //not using log since it might be cleaned up } try { _config.detroyRichlets(); } catch (Throwable ex) { ex.printStackTrace(); //not using log since it might be cleaned up } try { _sesscache.destroy(this); } catch (NoClassDefFoundError ex) { //Bug 3046360 } catch (AbstractMethodError ex) { //backward compatible } catch (Throwable ex) { ex.printStackTrace(); //not using log since it might be cleaned up } try { _factory.stop(this); } catch (Throwable ex) { ex.printStackTrace(); //not using log since it might be cleaned up } try { _provider.stop(this); } catch (Throwable ex) { ex.printStackTrace(); //not using log since it might be cleaned up } try { _engine.stop(this); } catch (Throwable ex) { ex.printStackTrace(); //not using log since it might be cleaned up } if (_failover != null) { try { _failover.stop(this); } catch (NoClassDefFoundError ex) { //Bug 3046360 } catch (AbstractMethodError ex) { //backward compatible } catch (Throwable ex) { ex.printStackTrace(); //not using log since it might be cleaned up } _failover = null; } _factory = null; // _provider = null; //Provider might be stopped before sessionDidActivate is called (Tomcat 5.5.2) _engine = null; _sesscache = null; try { org.zkoss.util.Cleanups.cleanup(); } catch (NoClassDefFoundError ex) { //Bug 3046360 } catch (Throwable ex) { ex.printStackTrace(); //not using log since it might be cleaned up } //we don't reset _config since WebApp cannot be re-inited after stop } public final UiEngine getUiEngine() { return _engine; } public void setUiEngine(UiEngine engine) { if (engine == null) throw new IllegalArgumentException(); _engine.stop(this); _engine = engine; _engine.start(this); } public DesktopCache getDesktopCache(Session sess) { return _provider.getDesktopCache(sess); } public DesktopCacheProvider getDesktopCacheProvider() { return _provider; } public void setDesktopCacheProvider(DesktopCacheProvider provider) { if (provider == null) throw new IllegalArgumentException(); _provider.stop(this); _provider = provider; _provider.start(this); } public UiFactory getUiFactory() { return _factory; } public void setUiFactory(UiFactory factory) { if (factory == null) throw new IllegalArgumentException(); _factory.stop(this); _factory = factory; _factory.start(this); } public FailoverManager getFailoverManager() { return _failover; } public void setFailoverManager(FailoverManager failover) { if (_failover != null) _failover.stop(this); _failover = failover; if (_failover != null) _failover.start(this); } public IdGenerator getIdGenerator() { return _idgen; } public void setIdGenerator(IdGenerator idgen) { _idgen = idgen; } public SessionCache getSessionCache() { return _sesscache; } public void setSessionCache(SessionCache cache) { if (cache == null) throw new IllegalArgumentException(); _sesscache.destroy(this); _sesscache = cache; _sesscache.init(this); } public AuDecoder getAuDecoder() { return _audec; } public void setAuDecoder(AuDecoder audec) { _audec = audec; } /** Invokes {@link #getDesktopCacheProvider}'s * {@link DesktopCacheProvider#sessionWillPassivate}. */ public void sessionWillPassivate(Session sess) { if (_provider != null) _provider.sessionWillPassivate(sess); //Provider might be stopped before sessionDidActivate is called (Tomcat 5.5.2) } /** Invokes {@link #getDesktopCacheProvider}'s * {@link DesktopCacheProvider#sessionDidActivate}. */ public void sessionDidActivate(Session sess) { _provider.sessionDidActivate(sess); } public void sessionDestroyed(Session sess) { try { getDesktopCacheProvider().sessionDestroyed(sess); } catch (Throwable ex) { log.warning("Failed to cleanup session", ex); } try { getSessionCache().remove(sess); } catch (Throwable ex) { log.warning("Failed to cleanup session", ex); } try { ((SessionCtrl)sess).onDestroyed(); //after called, sess.getNativeSession() is null! } catch (Throwable ex) { log.warning("Failed to cleanup session", ex); } } /** Loads the build identifier. * This method is used only Internally */ synchronized public static String loadBuild() { if (_build == null) { final String FILE = "/metainfo/zk/build"; InputStream is = Thread.currentThread() .getContextClassLoader().getResourceAsStream(FILE); if (is == null) { is = AbstractWebApp.class.getResourceAsStream(FILE); if (is == null) return _build = ""; //done; } try { _build = new String(Files.readAll(is)).trim(); } catch (Exception ex) { _build = "error"; } finally { try {is.close();} catch (Throwable ex) {} } } return _build; } }
package com.imthe.god.util; import com.google.common.base.Strings; import com.imthe.god.base.APIMetadata; import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Created by pardhamavilla on 11/7/16. */ public class HttpClient { private static final Logger LOG = LoggerFactory.getLogger(HttpClient.class); public final HttpResponse executeHttpPostRequest(APIMetadata apiMetadata) throws IOException { HttpPost httpPost = new HttpPost(apiMetadata.getAPI()); httpPost.addHeader("Content-Type", apiMetadata.getContentType()); String userName = apiMetadata.getUserName(); String metadataAuthToken = apiMetadata.getAuthToken(); boolean isAuthTokenPresent = !Strings.isNullOrEmpty(metadataAuthToken) || !Strings.isNullOrEmpty(userName); if (isAuthTokenPresent) { String effectiveAuthToken = metadataAuthToken != null ? metadataAuthToken : "Basic " + new Base64().encodeToString((userName + ":" + apiMetadata.getPassword()).getBytes()); httpPost.addHeader("Authorization", effectiveAuthToken); } // add extra parameters in headers Map<String, String> extraHeaderParameters = apiMetadata.getHeaderParameters(); if (extraHeaderParameters != null && !extraHeaderParameters.isEmpty()) { for (String headerKey : extraHeaderParameters.keySet()) { String headerValue = extraHeaderParameters.get(headerKey); httpPost.addHeader(headerKey, headerValue); } } if (!Strings.isNullOrEmpty(apiMetadata.getParameterName())) { List<NameValuePair> nameValuePairs = new ArrayList(); nameValuePairs.add(new BasicNameValuePair(apiMetadata.getParameterName(), apiMetadata.getRequest())); // add extra parameters in request or payload Map<String, String> requestParameters = apiMetadata.getRequestParameters(); if (requestParameters != null) { for (String key : requestParameters.keySet()) { nameValuePairs.add(new BasicNameValuePair(key, requestParameters.get(key))); } } httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); } else { StringEntity params = new StringEntity(apiMetadata.getRequest()); httpPost.setEntity(params); } String authorizationHeader = !isAuthTokenPresent ? "null" : httpPost.getFirstHeader("Authorization").getValue(); return HttpClientBuilder.create().build().execute(httpPost); } }
package ru.job4j; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** *Test. * *@author Alexandr Sedykh *@version $ld$ *@since 05.02.18 */ public class CalculateTest { /** *Test echo. */ @Test public void whenTakeNameThenTreeEchoPlusName() { String input = "Alexandr Sedykh"; String expect = "Echo, echo, echo: Alexandr Sedykh"; Calculate calc = new Calculate(); String result = calc.echo(input); assertThat(result, is(expect)); } }
package com.lsjr.zizi.mvp.home.session.adapter; import android.content.Context; import android.net.Uri; import android.view.Gravity; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import com.andview.adapter.ABaseRefreshAdapter; import com.andview.adapter.BaseRecyclerHolder; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.imagepipeline.common.ResizeOptions; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.imagepipeline.request.ImageRequestBuilder; import com.lsjr.zizi.R; import com.lsjr.zizi.mvp.upload.FreshImaCallBack; import com.ymz.baselibrary.utils.L_; import com.ymz.baselibrary.utils.UIUtils; import java.util.List; /** * 创建人:$ gyymz1993 * 创建时间:2017/8/24 14:47 */ public class SelectPhotoAdapter extends ABaseRefreshAdapter<String> { private List<String> mData; private final static int maxImageSize = 9; private FreshImaCallBack freshImgCallBack;//针对三种操作逻辑所自定义的回调 public SelectPhotoAdapter(Context context, List<String> datas, int itemLayoutId) { super(context, datas, itemLayoutId); mData=datas; } @Override protected void convert(BaseRecyclerHolder convertView, String filePaht, int position) { // convertView = LayoutInflater.from(context).inflate(R.layout.item_gridview, null); L_.e("convert------->"+mData.size()); LinearLayout rootLy=convertView.getView(R.id.id_root_ly); SimpleDraweeView sdvItemShowImg = convertView.getView(R.id.sdvItemShowImg); ImageView ivDeleteImg = convertView.getView(R.id.ivDeleteImg); ImageView ivItemAdd = convertView.getView(R.id.ivItemAdd); FrameLayout rlItemShow = convertView.getView(R.id.rlItemShow); ivItemAdd.setVisibility(View.VISIBLE); rlItemShow.setVisibility(View.VISIBLE); if (mData.size()>=maxImageSize){ showImg(convertView,filePaht,position); }else { if (position == mData.size() - 1) { rlItemShow.setVisibility(View.GONE); ivItemAdd.setVisibility(View.VISIBLE); } else { if (mData.size() > 1) { showImg(convertView,filePaht,position); } } } //放在外面用于更新position sdvItemShowImg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { freshImgCallBack.previewImag(position);//预览图片 } }); ivDeleteImg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { freshImgCallBack.updateGvIgShow(position);//更新数据 } }); ivItemAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { freshImgCallBack.openGallery();//打开相册放在里面即可 } }); LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(UIUtils.WHD()[0]/4,UIUtils.WHD()[0]/4); layoutParams.gravity= Gravity.CENTER; rootLy.setLayoutParams(layoutParams); } //显示图片 private void showImg(BaseRecyclerHolder convertView,String filePaht,int position) { SimpleDraweeView sdvItemShowImg = convertView.getView(R.id.sdvItemShowImg); // convertView.getView(R.id.ivItemAdd).setVisibility(View.GONE); convertView.getView(R.id.ivItemAdd).setVisibility(View.GONE); if (position == mData.size() - 1) { convertView.getView(R.id.rlItemShow).setVisibility(View.GONE); }else { convertView.getView(R.id.rlItemShow).setVisibility(View.VISIBLE); //设置图片 ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse("file://" + filePaht)) .setProgressiveRenderingEnabled(true) .setResizeOptions(new ResizeOptions(100, 100)) .build(); DraweeController controller = Fresco.newDraweeControllerBuilder() .setImageRequest(request) .setAutoPlayAnimations(true) .setTapToRetryEnabled(true) .setOldController(sdvItemShowImg.getController()) .build(); sdvItemShowImg.setController(controller); } } /** * 设置回调 * * @param callBack freshImgCallBack */ public void setImgShowFresh(FreshImaCallBack callBack) { freshImgCallBack = callBack; } }
package com.pack.dao; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.pack.entity.Admin; import com.pack.entity.BatchAllocation; import com.pack.entity.Login; @Repository public class AdminDaoImpl implements AdminDao { @Autowired private SessionFactory sessionFactory; public String loginAdmin(Login login) { // TODO Auto-generated method stub String page = null; Session s = this.sessionFactory.openSession(); Transaction t = s.beginTransaction(); Query q = s.createQuery("from Login l where l.username=:username and l.password=:password"); q.setParameter("username", login.getUsername()); q.setParameter("password", login.getPassword()); Login l1 = (Login) q.uniqueResult(); if (l1 != null) page = "Home"; else page = "denied"; t.commit(); return page; } public void addBatch(BatchAllocation batchAllocation) { // TODO Auto-generated method stub this.sessionFactory.getCurrentSession().save(batchAllocation); } public void addAdmin(Admin admin) { this.sessionFactory.getCurrentSession().save(admin); Session s = this.sessionFactory.openSession(); Transaction t = s.beginTransaction(); Login login=new Login(); login.setUsername(admin.getId()); login.setPassword(admin.getPassword()); this.sessionFactory.getCurrentSession().save(login); } }
package com.github.kemonoske.drophub.ui; import com.github.kemonoske.drophub.core.HubClient; import com.github.kemonoske.drophub.core.HubServer; import com.github.kemonoske.drophub.core.Parcel; import com.github.kemonoske.drophub.ui.components.UndecoratedStage; import javafx.application.Application; import javafx.application.Platform; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.input.DragEvent; import javafx.scene.input.Dragboard; import javafx.scene.input.TransferMode; import javafx.stage.Stage; import java.io.File; public class Main extends Application { HubClient client; TrayManager trayManager = null; @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("/fxml/main.fxml")); UndecoratedStage stage = new UndecoratedStage(root); stage.setWindowTitle("DropHub"); stage.show(); root.setOnDragOver(fileDragHandler); root.setOnDragDropped(fileDropHandler); //trayManager = new TrayManager(primaryStage); Platform.setImplicitExit(false); //Stuff for data transfer goes here HubServer server = new HubServer(8992); server.start(); client = new HubClient("127.0.0.1", 8992); } public static void main(String[] args) throws Exception { launch(args); } private EventHandler<DragEvent> fileDragHandler = new EventHandler<DragEvent>() { @Override public void handle(DragEvent event) { Dragboard db = event.getDragboard(); if (db.hasFiles()) { event.acceptTransferModes(TransferMode.MOVE); } else { event.consume(); } } }; private EventHandler<DragEvent> fileDropHandler = new EventHandler<DragEvent>() { @Override public void handle(DragEvent event) { Dragboard db = event.getDragboard(); boolean success = false; if (db.hasFiles()) { success = true; //TODO: Add support for multiple files handling String filePath = null; File file = db.getFiles().get(0); client.send(new Parcel(file.getAbsolutePath(), "world")); } event.setDropCompleted(success); event.consume(); } }; }
package application.model; public class Song implements Comparable<Song> { private String name; private String artist; private String album; private int year; public Song(String name, String artist, String album, int year) { super(); this.name = name; this.artist = artist; this.album = album; this.year = year; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getArtist() { return artist; } public void setArtist(String artist) { this.artist = artist; } public String getAlbum() { return album; } public void setAlbum(String album) { this.album = album; } public int getYear(){ return year; } public void setYear(int year){ this.year = year; } public int isSame(Song o){ if(o.name.equalsIgnoreCase(this.name) && o.artist.equalsIgnoreCase(this.artist)) { return 1; } return -1; } @Override public int compareTo(Song o) { return this.name.compareTo(o.name); } public String toString() { return name; } @Override public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } return (this.name == ((Song) obj).name && this.artist == ((Song) obj).artist); } @Override public int hashCode() { return 7 + 5*name.hashCode() * artist.hashCode(); // 5 and 7 are random prime numbers } }
package com.example.buildpc.Adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.example.buildpc.ActivityListItem.BuildPCListSSDActivity; import com.example.buildpc.Dialog.DialogInfo; import com.example.buildpc.Main.MainBuild; import com.example.buildpc.Model.Model_SSD; import com.example.buildpc.R; import com.squareup.picasso.Picasso; import java.text.DecimalFormat; import java.util.ArrayList; public class SSD_Adapter extends ArrayAdapter<Model_SSD> { private Context context; private int resource; private ArrayList<Model_SSD> model_ssdArrayList; ImageButton icon_info_ssd; DialogInfo dialogInfo; public SSD_Adapter(@NonNull Context context, int resource, @NonNull ArrayList<Model_SSD> objects) { super(context, resource, objects); this.context = context; this.resource = resource; this.model_ssdArrayList = objects; } private String urlApi = "http://android-api.thaolx.com"; @NonNull public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { convertView = LayoutInflater.from(context).inflate(R.layout.buildpc_layout_ssd,parent,false); ImageView imageView_ssd = convertView.findViewById(R.id.image_ssd); TextView textView_name_ssd = convertView.findViewById(R.id.textView_name_ssd); TextView textView_brand_ssd = convertView.findViewById(R.id.textView_brand_ssd); TextView textView_size_ssd = convertView.findViewById(R.id.textView_size_ssd); TextView textView_port_ssd = convertView.findViewById(R.id.textView_port_ssd); TextView textView_price_ssd = convertView.findViewById(R.id.textView_price_sdd); icon_info_ssd = convertView.findViewById(R.id.icon_info_sdd); final Model_SSD model_ssd = model_ssdArrayList.get(position); Picasso.with(context).load(urlApi+model_ssd.getImageSSD()).into(imageView_ssd); textView_name_ssd.setText(model_ssd.getName()); textView_brand_ssd.setText(model_ssd.getBrand()); textView_size_ssd.setText(model_ssd.getSize()); textView_port_ssd.setText(model_ssd.getPort()); String s = (new DecimalFormat("#,###.##"+" VNĐ")).format(model_ssd.getPrice()); textView_price_ssd.setText(s); icon_info_ssd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialogInfo.showDialog(context, BuildPCListSSDActivity.getInstance(), urlApi, model_ssd.getImageSSD(), model_ssd.getName(), "Port " + model_ssd.getPort(), model_ssd.getSize(), model_ssd.getBrand(), model_ssd.getDescription(), model_ssd.getPrice()); } }); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MainBuild.cart.setSsdID(model_ssd.getID()); BuildPCListSSDActivity.getInstance().finish(); } }); convertView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { dialogInfo.showDialog(context, BuildPCListSSDActivity.getInstance(), urlApi, model_ssd.getImageSSD(), model_ssd.getName(), "Port " + model_ssd.getPort(), model_ssd.getSize(), model_ssd.getBrand(), model_ssd.getDescription(), model_ssd.getPrice()); return false; } }); return convertView; } }
package com.example.Bank_App_5.models; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class SavingsAccount extends BankAccount { public SavingsAccount() { super(); } public SavingsAccount(double openBalance) { super(openBalance, 0.01); } public SavingsAccount(long accountNumber, double openingBalance, double interestRate, Date accountOpenedOn) { super(accountNumber, openingBalance, interestRate, accountOpenedOn); } public String toString() { return "Savings Account Balance: $" + balance + "\n" + "Savings Account Interest Rate: " + interestRate + "\n" + "Savings Account Balance in 3 years: $" + futureValue(3); } public static SavingsAccount readFromString(String accountData) throws ParseException, NumberFormatException { String[] holding = accountData.split(","); SimpleDateFormat date = new SimpleDateFormat("dd/MM/yyyy"); long accountNumber = Long.parseLong(holding[0]); double balance = Double.parseDouble(holding[1]); double interestRate = Double.parseDouble(holding[2]); Date accountOpenedOn = date.parse(holding[3]); return new SavingsAccount(accountNumber, balance, interestRate, accountOpenedOn); } }
package com.model.service.impl; import com.model.dao.BrandDao; import com.model.dao.impl.BrandDaoImpl; import com.model.data.Brand; import com.model.service.BrandService; public class BrandServiceImpl extends ServiceImpl<Brand> implements BrandService { private BrandDao brandDao; public BrandServiceImpl() { this.brandDao = new BrandDaoImpl(); this.setDao(this.brandDao); } }
package com.zhicai.byteera.service.serversdk; public abstract class BaseHandlerClass { public void handle(byte[] buffer){ onSuccess(buffer); } public abstract void onSuccess(byte[] buffer); }
package ur.api_ur.api_data_obj; /** * Created by redjack on 15/10/30. */ public class URLocationSpot { public enum LocType { NORMAL, FULL_AREA, SPECIFIC_AREA, BEACON; public String stateValue() { return String.valueOf(this.ordinal()); } public static LocType fromOrder(String order) { return fromOrder(Integer.valueOf(order)); } public static LocType fromOrder(int order) { if (order == NORMAL.ordinal()) return NORMAL; else if (order == FULL_AREA.ordinal()) return FULL_AREA; else if (order == SPECIFIC_AREA.ordinal())return SPECIFIC_AREA; else return BEACON; } } public String name; public float lat; public float lon; /** 公尺 */ public float radius; public int getRadius() { if (radius > 1500) return 1500; else if (radius < 500) return 500; else return (int) radius; } }
package org.elasticsearch.plugin.zentity; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import io.zentity.common.Json; import io.zentity.common.StreamUtil; import joptsimple.internal.Strings; import org.apache.http.Consts; import org.apache.http.entity.ContentType; import org.apache.http.nio.entity.NStringEntity; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; import org.junit.Test; import java.util.List; import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class ResolutionActionBulkIT extends AbstractActionITCase { private static final ContentType NDJSON_TYPE = ContentType.create("application/x-ndjson", Consts.UTF_8); private static final String TEST_PAYLOAD_JOB_TERMS_JSON = "{" + " \"terms\": [ \"a_00\" ]," + " \"scope\": {" + " \"include\": {" + " \"indices\": [ \"zentity_test_index_a\", \"zentity_test_index_b\", \"zentity_test_index_c\" ]," + " \"resolvers\": [ \"resolver_a\", \"resolver_b\" ]" + " }" + " }" + "}"; private static final String TEST_PAYLOAD_JOB_EXPLANATION_JSON = "{" + " \"attributes\": {" + " \"attribute_a\": [ \"a_00\" ]," + " \"attribute_type_date\": {" + " \"values\": [ \"1999-12-31T23:59:57.0000\" ]," + " \"params\": {" + " \"format\" : \"yyyy-MM-dd'T'HH:mm:ss.0000\"," + " \"window\" : \"1d\"" + " }" + " }" + " }," + " \"scope\": {" + " \"include\": {" + " \"indices\": [ \"zentity_test_index_a\" ]" + " }" + " }" + "}"; @Test public void testBulkResolutionWithMalformed() throws Exception { int testResourceSet = TEST_RESOURCES_A; prepareTestResources(testResourceSet); try { String endpoint = "_zentity/resolution/_bulk"; Request req = new Request("POST", endpoint); String[] reqBodyLines = new String[]{ "malformed json", TEST_PAYLOAD_JOB_TERMS_JSON, "{ \"entity_type\": \"unknown\" }", // unknown entity type TEST_PAYLOAD_JOB_TERMS_JSON, "{ \"entity_type\": \"zentity_test_entity_a\" }", "", // empty body "{ \"entity_type\": \"zentity_test_entity_a\" }", TEST_PAYLOAD_JOB_EXPLANATION_JSON }; String reqBody = Strings.join(reqBodyLines, "\n"); req.setEntity(new NStringEntity(reqBody, NDJSON_TYPE)); req.addParameter("_explanation", "false"); req.addParameter("_source", "true"); Response response = client.performRequest(req); assertEquals(response.getStatusLine().getStatusCode(), 200); JsonNode json = Json.ORDERED_MAPPER.readTree(response.getEntity().getContent()); // check shape assertTrue(json.isObject()); assertTrue(json.has("errors")); assertTrue(json.get("errors").isBoolean()); assertTrue(json.has("took")); assertTrue(json.get("took").isNumber()); assertTrue(json.has("items")); assertTrue(json.get("items").isArray()); // check the values assertTrue(json.get("took").asLong() > 0); assertTrue(json.get("errors").booleanValue()); ArrayNode items = (ArrayNode) json.get("items"); assertEquals(4, items.size()); // should have three failures List<JsonNode> failures = StreamUtil.fromIterator(items.iterator()) .limit(3) .collect(Collectors.toList()); failures.forEach((item) -> { assertTrue(item.has("error")); assertTrue(item.get("error").isObject()); assertTrue(item.has("hits")); assertTrue(item.get("hits").isObject()); JsonNode hits = item.get("hits"); assertTrue(hits.has("hits")); assertTrue(hits.get("hits").isArray()); assertTrue(hits.get("hits").isEmpty()); assertTrue(item.has("took")); assertTrue(item.get("took").isNumber()); }); } finally { destroyTestResources(testResourceSet); } } @Test public void testBulkResolution() throws Exception { int testResourceSet = TEST_RESOURCES_A; prepareTestResources(testResourceSet); try { String endpoint = "_zentity/resolution/zentity_test_entity_a/_bulk"; Request req = new Request("POST", endpoint); String[] reqBodyLines = new String[]{ "{\"_source\": false}", // override source TEST_PAYLOAD_JOB_TERMS_JSON, "{\"_explanation\": true}", // override explanation TEST_PAYLOAD_JOB_EXPLANATION_JSON }; String reqBody = Strings.join(reqBodyLines, "\n"); req.setEntity(new NStringEntity(reqBody, NDJSON_TYPE)); req.addParameter("_explanation", "false"); req.addParameter("_source", "true"); Response response = client.performRequest(req); assertEquals(response.getStatusLine().getStatusCode(), 200); JsonNode json = Json.ORDERED_MAPPER.readTree(response.getEntity().getContent()); // check shape assertTrue(json.isObject()); assertTrue(json.has("errors")); assertTrue(json.get("errors").isBoolean()); assertTrue(json.has("took")); assertTrue(json.get("took").isNumber()); assertTrue(json.has("items")); assertTrue(json.get("items").isArray()); // check the values assertFalse(json.get("errors").booleanValue()); assertTrue(json.get("took").asLong() > 0); ArrayNode items = (ArrayNode) json.get("items"); assertEquals(2, items.size()); items.forEach((item) -> { assertTrue(item.has("hits")); assertTrue(item.get("hits").isObject()); JsonNode hits = item.get("hits"); assertTrue(hits.has("hits")); assertTrue(hits.get("hits").isArray()); assertTrue(item.has("took")); assertTrue(item.get("took").isNumber()); }); JsonNode termsResult = items.get(0); assertTrue(termsResult.get("hits").get("total").asInt() > 0); JsonNode firstTermHit = termsResult.get("hits").get("hits").get(0); assertFalse(firstTermHit.has("_source")); assertFalse(firstTermHit.has("_explanation")); JsonNode explanationResult = items.get(1); assertTrue(explanationResult.get("hits").get("total").asInt() > 0); JsonNode firstExplanationHit = explanationResult.get("hits").get("hits").get(0); assertTrue(firstExplanationHit.has("_source")); assertTrue(firstExplanationHit.has("_explanation")); } finally { destroyTestResources(testResourceSet); } } }
package com.GestiondesClub.entities; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonBackReference; @Entity @Table(name="sponseur") @NamedQuery(name="Sponseur.findAll", query="SELECT s FROM Sponseur s") public class Sponseur { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", updatable = false, nullable = false) private Long id; @Column(name="raison_sociale",unique = true , nullable = false) private String raisonSociale; @Column(name="url_site_sponseur") private String urlSiteSponseur; @Column(name="logo_sponseur") private String logoSponseur = "no_image.jpg"; @Column(name="active") private boolean active = true; @JsonBackReference(value="sponsor") @OneToMany(mappedBy="sponseur") private List<EvenementSponseur> lesEvenement; public Sponseur() { super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getRaisonSociale() { return raisonSociale; } public void setRaisonSociale(String raisonSociale) { this.raisonSociale = raisonSociale; } public String getUrlSiteSponseur() { return urlSiteSponseur; } public void setUrlSiteSponseur(String urlSiteSponseur) { this.urlSiteSponseur = urlSiteSponseur; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public String getLogoSponseur() { return logoSponseur; } public void setLogoSponseur(String logoSponseur) { this.logoSponseur = logoSponseur; } public List<EvenementSponseur> getLesEvenement() { return lesEvenement; } public void setLesEvenement(List<EvenementSponseur> lesEvenement) { this.lesEvenement = lesEvenement; } @Override public String toString() { return "Sponseur [id=" + id + ", raisonSociale=" + raisonSociale + ", urlSiteSponseur=" + urlSiteSponseur + ", logo_Sponseur=" + logoSponseur + "]"; } }
package baseDriverClass; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.openqa.selenium.WebDriver; public class BaseWebDriver { public static WebDriver driver; public static Properties properties; public static Logger logger=Logger.getLogger(BaseWebDriver.class); public BaseWebDriver(){ PropertyConfigurator.configure("log4j.properties"); try { properties = new Properties(); FileInputStream ip = new FileInputStream(System.getProperty("user.dir")+ "./Config/config.properties"); properties.load(ip); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } /* * log=new Properties(); FileInputStream logIP = null; try { logIP = new * FileInputStream(System.getProperty("user.dir")+ * "./LogData/log4j.properties"); } catch (FileNotFoundException e) { // TODO * Auto-generated catch block e.printStackTrace(); } try { log.load(logIP); } * catch (IOException e) { // TODO Auto-generated catch block * e.printStackTrace(); } */ } public static void initialization(){ String browserName = properties.getProperty("browser"); String driverLocation=properties.getProperty("location"); if(browserName.equals("Chrome")){ System.setProperty("webdriver.chrome.driver", driverLocation); } } }
import java.io.*; class Skolebok extends Bok { private int klassetrinn; private String skolefag; public Skolebok(){} public Skolebok( String f, String t,int sider, double p, int kt, String fag ) { super( f, t, sider, p ); klassetrinn = kt; skolefag = fag; } public String toString() { String s = super.toString(); s += "; trinn: " + klassetrinn; s += ", " + skolefag; return s; } public void skrivTilFil(DataOutputStream output) throws IOException{ output.writeUTF("Skolebok"); super.skrivTilFil(output); output.writeUTF(skolefag); output.writeInt(klassetrinn); } public void lesFraFil(DataInputStream input) throws IOException{ super.lesFraFil(input); skolefag = input.readUTF(); klassetrinn = input.readInt(); } }
package employeeScheduler.model; import java.time.DayOfWeek; import java.util.ArrayList; /** * Model representing the characteristics of schedule. */ public class ScheduleModel { private ArrayList<Shift> shifts; private ArrayList<EmployeeModel> employeePreferences; private Integer scheduleDaysNumber; public ScheduleModel(ArrayList<Shift> shifts, ArrayList<EmployeeModel> employeePreferences, Integer scheduleDaysNumber) { this.shifts = shifts; this.employeePreferences = employeePreferences; this.scheduleDaysNumber = scheduleDaysNumber; } public ArrayList<Shift> getShifts() { return shifts; } public void setShifts(ArrayList<Shift> shifts) { this.shifts = shifts; } public ArrayList<EmployeeModel> getEmployeePreferences() { return employeePreferences; } public void setEmployeePreferences(ArrayList<EmployeeModel> employeePreferences) { this.employeePreferences = employeePreferences; } public Integer getScheduleDaysNumber() { return scheduleDaysNumber; } public void setScheduleDaysNumber(Integer scheduleDaysNumber) { this.scheduleDaysNumber = scheduleDaysNumber; } }
package com.easyclean.easyclean; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.DatePicker; import android.widget.TextView; import android.widget.TimePicker; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.text.DateFormat; import java.util.Calendar; import java.util.GregorianCalendar; public class PickUpActivity extends AppCompatActivity { private FirebaseAuth mAuth; DatabaseReference transactionReference; Transaction transaction; DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM); final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); TextView textPickUpDate, textPickUpTime, textDeliveryDate, textDeliveryTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pick_up); Toolbar myToolbar = findViewById(R.id.my_toolbar); setSupportActionBar(myToolbar); mAuth = FirebaseAuth.getInstance(); transactionReference = FirebaseDatabase.getInstance().getReference("Transactions"); transaction = (Transaction) getIntent().getSerializableExtra("transaction"); textPickUpDate = findViewById(R.id.text_pick_up_date); textPickUpTime = findViewById(R.id.text_pick_up_time); textDeliveryDate = findViewById(R.id.text_delivery_date); textDeliveryTime = findViewById(R.id.text_delivery_time); setPickUpTime(hour, minute); setDeliveryTime(hour, minute); setPickUpDate(year,month,day); setDeliveryDate(year,month,day); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_logout: mAuth.signOut(); startActivity(new Intent(this, LoginActivity.class)); finish(); return true; default: return super.onOptionsItemSelected(item); } } public void onClick(View view){ switch (view.getId()){ case R.id.button_back: finish(); break; case R.id.button_next: save(); break; case R.id.layout_pick_up_date: datePicker(); break; case R.id.layout_pick_up_time: timePicker(); break; default: break; } } private void timePicker() { TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hoursOfDay, int minute) { setPickUpTime(hoursOfDay, minute); setDeliveryTime(hoursOfDay, minute); } }, hour, minute, true); timePickerDialog.show(); } private void datePicker() { DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int day) { setPickUpDate(year,month,day); setDeliveryDate(year,month,day); } }, year,month,day); datePickerDialog.show(); } private String dateFormater(int year, int month, int day){ Calendar cal = new GregorianCalendar(year, month, day); return dateFormat.format(cal.getTime()); } private void setPickUpDate(int year, int month, int day){ textPickUpDate.setText(dateFormater(year,month,day)); } private void setPickUpTime(int hour, int minute){ textPickUpTime.setText(hour+":"+minute); } private void setDeliveryDate(int year, int month, int day){ if (transaction.type.equals("regular")){ day+=3; }else{ day+=1; } textDeliveryDate.setText(dateFormater(year,month,day)); } private void setDeliveryTime(int hour, int minute){ textDeliveryTime.setText(hour+":"+minute); } private void save() { transaction.pickUpDate = textPickUpDate.getText().toString(); transaction.pickUpTime = textPickUpTime.getText().toString(); transaction.deliveryDate = textDeliveryDate.getText().toString(); transaction.deliveryTime = textDeliveryTime.getText().toString(); Intent intent = new Intent(this, SummaryActivity.class); intent.putExtra("transaction", transaction); startActivity(intent); } }
package com.brainacademy.dao; public class Main { public static void main(String[] args) { User user = new User(); user.setId(1L); user.setAge(29); user.setEmail("some@mail.net"); user.setName("Vasya"); UserDao userDao = new UserDao(); userDao.save(user); User user1 = userDao.findOne(1L); System.out.println("User found: " + user1.getName()); } }
package model; public class movieBean { private String movie_id; //영화아이디(고유값) private String movie_name; //영화제목 private String movie_class; //등급 private String movie_genre; //장르 private String movie_url; //영화포스터url private int movie_audience; //관객수 public String getMovie_id() { return movie_id; } public void setMovie_id(String movie_id) { this.movie_id = movie_id; } public String getMovie_name() { return movie_name; } public void setMovie_name(String movie_name) { this.movie_name = movie_name; } public String getMovie_class() { return movie_class; } public void setMovie_class(String movie_class) { this.movie_class = movie_class; } public String getMovie_genre() { return movie_genre; } public void setMovie_genre(String movie_genre) { this.movie_genre = movie_genre; } public String getMovie_url() { return movie_url; } public void setMovie_url(String movie_url) { this.movie_url = movie_url; } public int getMovie_audience() { return movie_audience; } public void setMovie_audience(int movie_audience) { this.movie_audience = movie_audience; } }
public class FizzBuzz { private String[] listNumbers; public FizzBuzz() { listNumbers = new String[100]; generatePositions(); } public int getLength() { return listNumbers.length; } private void generatePositions(){ for(int i =0; i < listNumbers.length;i++){ listNumbers[i]= generatePosition(i+1); } } private String generatePosition(int position){ if(isFizzBuzz(position)){ return "FizzBuzz"; } if (isFizz(position)) { return "Fizz"; } if (isBuzz(position)) { return "Buzz"; } return String.valueOf(position); } public String getPositionList(int position){ return listNumbers[position-1]; } private boolean isBuzz(int position) { return (position % 5 == 0) || (String.valueOf(position).contains("5")) ; } private boolean isFizz(int position) { return (position % 3 == 0) || (String.valueOf(position).contains("3")); } private boolean isFizzBuzz(int position) { return (isFizz(position) && isBuzz(position)); } }
public class Return { public static void main(String[] args) { add1(2,2); add2(2,4); System.out.println(add2(2,4)); } static void add1(int num1, int num2){ System.out.println(num1 + num2); } static int add2(int num1,int num2){ return num1 + num2; } }
package component.AI; import message.CMessage; import message.Message; import org.newdawn.slick.GameContainer; import org.newdawn.slick.geom.Vector2f; import org.newdawn.slick.state.StateBasedGame; import component.CJBox2D; import component.Component; import entity.EntityContainer; import entity.Player; public abstract class CAI extends Component { Vector2f velocity; Player player; CJBox2D jbox; @Override public void setDependencies() { this.player = EntityContainer.getPlayer(); this.jbox = (CJBox2D) owner.getComponent("JBox2D"); } @Override public void readMessage(Message message) { // TODO Auto-generated method stub } @Override public void readMessage(CMessage message) { if (message.getText() == "ComponentAdded"){ if (message.getSource().getId() == "JBox2D"){ this.jbox = (CJBox2D) message.getSource(); } } } @Override public void update(GameContainer gc, StateBasedGame sb, int delta) { } public Vector2f getVelocity() { return velocity; } public void setVelocity(Vector2f velocity) { this.velocity = velocity; } }
package algo; /** * Created by orca on 2018/12/27. * */ public class Main { public static void printMatrix(int[][] matrix){ int i; for( i = 0 ;i<matrix.length;i++){ for(int j = 0 ;j<matrix[i].length;j++){ System.out.print(matrix[i][j]+" "); } System.out.println(); } } public static void main(String args[]){ } }
package com.lsm.boot.shiro.controller; import com.lsm.boot.shiro.model.User; import com.lsm.boot.shiro.util.ShiroUtils; import com.lsm.boot.shiro.vo.Result; import com.lsm.boot.shiro.vo.ResultCode; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.crypto.hash.Sha256Hash; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller @Slf4j public class LoginController { //首页 @RequestMapping(value="/index", method = RequestMethod.GET) public String index() { return "index"; } @RequestMapping(value="/login", method = RequestMethod.GET) public String login() { return "/login"; } @RequestMapping(value="/ajaxLogin",method=RequestMethod.POST) @ResponseBody public Result<Boolean> submitLogin(User user) { try { Subject subject = ShiroUtils.getSubject(); String passwordEncrypt = new Sha256Hash(user.getPassword()).toHex(); UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), passwordEncrypt); subject.login(token); return new Result<>(ResultCode.C200.getCode(), ResultCode.C200.getDesc(), true); } catch (AccountException e) { return new Result<>(ResultCode.C500.getCode(), ResultCode.C200.getDesc(), true); } } @RequestMapping(value="/logout",method =RequestMethod.GET) @ResponseBody public Result<Boolean> logout(){ try { SecurityUtils.getSubject().logout(); } catch (Exception e) { log.error(e.getMessage(), e); return new Result<>(ResultCode.C500.getCode(), ResultCode.C200.getDesc(), true); } return new Result<>(ResultCode.C200.getCode(), ResultCode.C200.getDesc(), true); } }
package com.ihq.capitalpool.userserver.Controller; import com.ihq.capitalpool.common.RestResult; import com.ihq.capitalpool.userserver.Entity.User; import com.ihq.capitalpool.userserver.Entity.UserTemp; import com.ihq.capitalpool.userserver.Service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping("/user") @CrossOrigin public class RegisterController { @Autowired UserService userService; @PostMapping("/register") @ResponseBody public RestResult RegisterUser(@Validated @RequestBody UserTemp userTemp) { userService.RegisterUser(userTemp); return new RestResult(); } @GetMapping("/active/{id}/{active_code}") public String ActiveUser(@PathVariable Integer id, @PathVariable String active_code, Model model) { model.addAttribute("msg", userService.ActiveUser(id, active_code)); return "jumpToLogin"; } @GetMapping("/detail/upd") @ResponseBody public RestResult selectByUsernamePassword(@RequestParam String username, @RequestParam String password) { return new RestResult(userService.selectByUsernamePassword(username, password)); } @GetMapping("/detail/uuid") @ResponseBody public RestResult selectByUsernamePassword(@RequestParam String uuid) { return new RestResult(userService.selectByUUID(uuid)); } @PutMapping("/update") @ResponseBody public RestResult updateUserInfo() { return new RestResult(); } @PutMapping("/cancel") @ResponseBody public RestResult CancelUser() { return new RestResult(); } }
package math; import java.util.HashSet; import java.util.Set; import org.junit.Test; public class Pow { @Test public void test_pow() { Set<PostStatType> postStatTypes = new HashSet<>(); postStatTypes.add(PostStatType.TEXT); postStatTypes.add(PostStatType.LARGE_TEXT); postStatTypes.add(PostStatType.HASHTAG); int pst = PostStatType.getStatType(postStatTypes); String str = ""; if ((pst & (0x1<<PostStatType.TEXT.getNum())) != 0) str += "PLAIN,"; if ((pst & (0x1<<PostStatType.LARGE_TEXT.getNum())) != 0) str += "LARGE_TEXT,"; if ((pst & (0x1<<PostStatType.TEXT_CARD.getNum())) != 0) str += "TEXTCARD,"; System.out.println(str); } }
package com.cakupan.xslt.example; import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.File; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.cakupan.xslt.data.CoverageFile; import com.cakupan.xslt.instrument.InstrumentXSLT; import com.cakupan.xslt.util.XSLTCakupanUtil; public class XSLTTest { @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); @Before public void setUp() throws Exception { System.setProperty("javax.xml.transform.TransformerFactory", "com.cakupan.xslt.transform.SaxonCakupanTransformerInstrumentFactoryImpl"); // System.setProperty("javax.xml.transform.TransformerFactory","com.cakupan.xslt.transform.XalanTransformerInstrumentFactoryImpl"); System.setProperty("cakupan.dir", temporaryFolder.getRoot().getAbsolutePath()); } @After public void tearDown() { XSLTCakupanUtil.cleanCoverageStats(); } @Test public void testTransformation() throws Exception { File xsltFile = new File("test", "coverage-simple.xsl"); InstrumentXSLT instrumentXslt = new InstrumentXSLT(); instrumentXslt.initCoverageMap(xsltFile.getPath()); XSLTCakupanUtil.dumpCoverageStats(); XSLTCakupanUtil.cleanCoverageStats(); Source xml = new StreamSource(new File("test", "coverage-simple.xml")); // use always the URL of the XSLT Source xsl = new StreamSource(xsltFile.toURI().toURL().toString()); String result = doXSLT(xml, xsl); XSLTCakupanUtil.generateCoverageReport(); XSLTCakupanUtil.generateEmmaReport(); // check transformation result assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?><f>hello</f>", result); // check coverage // expect covered: 1-7, 13 CoverageFile coverageFile = XSLTCakupanUtil.getCoverageMap().get("coverage-simple.xsl"); assertEquals(1, coverageFile.getLine(3).getLineCount()); assertEquals(1, coverageFile.getLine(4).getLineCount()); assertEquals(1, coverageFile.getLine(5).getLineCount()); // expect not covered: 8-12 assertEquals(0, coverageFile.getLine(8).getLineCount()); assertEquals(0, coverageFile.getLine(9).getLineCount()); assertEquals(0, coverageFile.getLine(10).getLineCount()); } private static String doXSLT(Source xml, Source xsl) throws TransformerConfigurationException, TransformerException { // Prepare transformer ByteArrayOutputStream transformOut = new ByteArrayOutputStream(); Result result = new StreamResult(transformOut); TransformerFactory transFact = TransformerFactory.newInstance(); // Perform Transform Transformer trans = transFact.newTransformer(xsl); trans.transform(xml, result); return transformOut.toString(); } }
package com.example.demo; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface ExameRepository extends CrudRepository<Exame, Long> { }
package com.example.shoji.bakingapp.ui; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.design.widget.Snackbar; import android.support.test.espresso.IdlingResource; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ProgressBar; import com.example.shoji.bakingapp.BuildConfig; import com.example.shoji.bakingapp.IdlingResource.SimpleIdlingResource; import com.example.shoji.bakingapp.R; import com.example.shoji.bakingapp.backgroundtask.FetchRecipesListener; import com.example.shoji.bakingapp.backgroundtask.QueryRecipesListener; import com.example.shoji.bakingapp.data.RecipesListAdapter; import com.example.shoji.bakingapp.pojo.Recipe; import com.example.shoji.bakingapp.utils.BakerUtils; import com.example.shoji.bakingapp.utils.NetworkUtils; import java.util.ArrayList; import timber.log.Timber; public class MainActivity extends AppCompatActivityEx implements FetchRecipesListener.OnLoadFinishedListener, QueryRecipesListener.OnLoadFinishedListener, RecipesListAdapter.OnClickListener { private static final String SAVE_INSTANCE_STATE_RECIPE_DATA = "recipe-data"; private final static String SAVE_INSTANCE_STATE_LIST_POSITION = "list-position"; private ProgressBar mProgressBar; private boolean mIsTabletMode; private RecipesListAdapter mRecipeListAdapter; private RecyclerView mRecipeListRecyclerView; @Nullable private SimpleIdlingResource mIdlingResource; @Override protected void onCreate(Bundle savedInstanceState) { if(savedInstanceState == null) { if(BuildConfig.DEBUG) Timber.plant(new Timber.DebugTree()); Timber.d("Logging With Timber"); } super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* check if sw600dp layout was loaded. If so, it will enable table mode */ mIsTabletMode = (findViewById(R.id.activity_main_sw600dp_layout) != null); mProgressBar = findViewById(R.id.activity_main_progressbar); createRecipesListRecyclerView(); // Get the IdlingResource instance mIdlingResource = getIdlingResource(); if(mIdlingResource != null) { mIdlingResource.setIdleState(false); } if(containsSavedInstanceState(savedInstanceState)) { restoreListInstanceState(savedInstanceState); } else { mProgressBar.setVisibility(View.VISIBLE); if(NetworkUtils.isNetworkConnected(this)) { BakerUtils.fetchRecipes(this, getSupportLoaderManager(), this); } else { BakerUtils.queryRecipes(this, getSupportLoaderManager(), this); } } } private void createRecipesListRecyclerView() { Context context = this; mRecipeListRecyclerView = findViewById(R.id.activity_main_recipes_recycler_view); RecyclerView.LayoutManager layoutManager; if(mIsTabletMode) { int numColumns = getResources().getInteger(R.integer.activity_main_layout_num_columns); layoutManager = new GridLayoutManager(context, numColumns); } else { layoutManager = new LinearLayoutManager(context); } mRecipeListRecyclerView.setLayoutManager(layoutManager); mRecipeListRecyclerView.setHasFixedSize(true); RecipesListAdapter.OnClickListener onClickRecipeHandler = this; mRecipeListAdapter = new RecipesListAdapter(onClickRecipeHandler); mRecipeListRecyclerView.setAdapter(mRecipeListAdapter); } /* after json fetching is finished */ @Override public void onFetchRecipesFinished() { BakerUtils.queryRecipes(this, getSupportLoaderManager(), this); } /* after db query is finished */ @Override public void onQueryRecipesFinished(ArrayList<Recipe> result) { mProgressBar.setVisibility(View.INVISIBLE); if(result == null || result.size() == 0) { showSnackbar(R.id.activity_main_recipes_recycler_view, R.string.error_no_network_short, Snackbar.LENGTH_LONG); } else swapAdapterData(result); if(mIdlingResource != null) { mIdlingResource.setIdleState(true); } } public void swapAdapterData(ArrayList<Recipe> newRecipeList) { mRecipeListAdapter.setRecipeList(newRecipeList); mRecipeListAdapter.notifyDataSetChanged(); } /* Checks and restore previous data */ private boolean containsSavedInstanceState(Bundle savedInstanceState) { boolean result = false; if(savedInstanceState != null) { if(savedInstanceState.containsKey(SAVE_INSTANCE_STATE_RECIPE_DATA)) { ArrayList<Recipe> savedRecipeList = savedInstanceState.getParcelableArrayList(SAVE_INSTANCE_STATE_RECIPE_DATA); swapAdapterData(savedRecipeList); result = true; } } return result; } private void restoreListInstanceState(Bundle savedInstanceState) { if(savedInstanceState.containsKey(SAVE_INSTANCE_STATE_LIST_POSITION)) { Parcelable listState = savedInstanceState .getParcelable(SAVE_INSTANCE_STATE_LIST_POSITION); mRecipeListRecyclerView.getLayoutManager() .onRestoreInstanceState(listState); } if(mIdlingResource != null) { mIdlingResource.setIdleState(true); } } @Override public void onClick(Recipe recipe) { Timber.d("TAPPED ON: %s", recipe.getName()); Intent intent = new Intent(this, RecipeActivity.class); intent.putExtra(RecipeActivity.EXTRA_RECIPE_DATA, recipe); startActivity(intent); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(SAVE_INSTANCE_STATE_LIST_POSITION, mRecipeListRecyclerView.getLayoutManager() .onSaveInstanceState()); outState.putParcelableArrayList(SAVE_INSTANCE_STATE_RECIPE_DATA, mRecipeListAdapter.getRecipeList()); } @VisibleForTesting @NonNull public SimpleIdlingResource getIdlingResource() { if (mIdlingResource == null) { mIdlingResource = new SimpleIdlingResource(); } return mIdlingResource; } }
package pkgbexportedqualified; public class BFromModuleButExportedQualified { public String doIt(String input) { return "from pkgbexportedqualified.BFromModuleButExportedQualified, " + input; } }
package com.ledungcobra.entites; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "COURSE_REGISTRATION_SESSION") @Getter @Setter @NoArgsConstructor @EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = false) public class CourseRegistrationSession extends BaseEntity { @Id @Column(name = "CSR_ID") @GeneratedValue(strategy = GenerationType.IDENTITY) @EqualsAndHashCode.Include private Long id; @Column(name = "START_DATE", nullable = false) private Date startDate; @Column(name = "END_DATE", nullable = false) private Date endDate; @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST}) @JoinColumn(name = "SEMESTER_ID", foreignKey = @ForeignKey(name = "FK_COURSE_REGISTRATION_SESSION_SEMESTER")) private Semester semester; public CourseRegistrationSession(Date startDate, Date endDate) { this.startDate = startDate; this.endDate = endDate; } }
package com.merrisonhotel.dao; import java.util.List; import com.merrisonhotel.model.Customer; public interface CustomerDao { public Boolean add(Customer customer); public List<Customer> getCustomers(); public Customer getModelFromConsole(); }
package com.ider.ytb_tv.ui.views; import android.content.Context; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.TextClock; /** * Created by ider-eric on 2016/4/5. */ public class GoClock extends TextClock { public GoClock(Context context) { super(context); initStyle(context); } public GoClock(Context context, AttributeSet attr) { super(context, attr); initStyle(context); } public void initStyle(Context context) { Typeface fontFace = Typeface.createFromAsset(context.getAssets(), "Fonts/DIN-LIGHT.OTF"); setTypeface(fontFace); } public boolean is24Format() { String timeFormat = android.provider.Settings.System.getString(this.getContext().getContentResolver(), android.provider.Settings.System.TIME_12_24); return timeFormat.equals("24"); } }
/** * Created with IntelliJ IDEA. * Description: * User: 张先生 * Date: 2021-04-24 * Time: 9:59 */ public class TextDemo { private float f=1.0f; int m=12; static int n=1; public static void main(String args[]){ TextDemo t=new TextDemo(); } /* class Test{ public String toString() { System.out.print("aaa"); return "bbb"; } } public static void main(String[] args) { System.out.println(new Test()); } */ /* static int cnt = 6; static{ cnt += 9; } public static void main(String[] args){ System.out.println("cnt =" + cnt); } static{ cnt /=3; }; */ /* private int count; public static void main(String[] args) { TextDemo test=new TextDemo(88); System.out.println(test.count); } TextDemo(int a) { count=a; }*/ /* private static int x = 100;// 2 public static void main(String args[]) {// 3 TextDemo hsl = new TextDemo();// 4 hsl.x++;// 5 TextDemo hs2 = new TextDemo();// 6 hs2.x++;// 7 hsl = new TextDemo();// 8 hsl.x++;// 9 TextDemo.x--;// 10 System.out.println(" x=" + x);// 11 }*/ }
import java.util.Scanner; public class As5Q10 { public static void main(String[] args) { int i=0; Scanner sc=new Scanner(System.in); System.out.println("Who is the inventor of JAVA?"); for(i=1;i<=3;i++) { String a=sc.nextLine(); if(a.equalsIgnoreCase("James Gosling")) { System.out.println("Good"); break; else { System.out.println("Try Again"); } } if(i==4) { System.out.println("James Gosling is the inventor of JAVA"); } } }
package de.tuberlin.dima.minidb.qexec; import de.tuberlin.dima.minidb.core.DataTuple; import de.tuberlin.dima.minidb.core.DataType; import de.tuberlin.dima.minidb.parser.OutputColumn.AggregationType; public class G10GroupByOperator implements GroupByOperator { private PhysicalPlanOperator child; private int[] groupColumnIndices; private int[] aggColumnIndices; private int[] groupColumnOutputPositions; private int[] aggregateColumnOutputPosition; private Aggregate[] aggregates; private DataTuple groupTuple; private boolean hasNext; public G10GroupByOperator(PhysicalPlanOperator child, int[] groupColumnIndices, int[] aggColumnIndices, AggregationType[] aggregateFunctions, DataType[] aggColumnTypes, int[] groupColumnOutputPositions, int[] aggregateColumnOutputPosition) { this.child = child; this.groupColumnIndices = groupColumnIndices; this.aggColumnIndices = aggColumnIndices; this.groupColumnOutputPositions = groupColumnOutputPositions; this.aggregateColumnOutputPosition = aggregateColumnOutputPosition; aggregates = new Aggregate[aggColumnIndices.length]; for( int i = 0; i < aggColumnIndices.length; i++) { aggregates[i] = new Aggregate(aggregateFunctions[i], aggColumnTypes[i]); } } @Override public void open(DataTuple correlatedTuple) throws QueryExecutionException { child.open(correlatedTuple); groupTuple = child.next(); hasNext = groupTuple != null || groupColumnIndices.length == 0; if (groupTuple != null) { for( int i = 0; i <aggColumnIndices.length; i++) { aggregates[i].aggregate(groupTuple.getField(aggColumnIndices[i])); } } } @Override public DataTuple next() throws QueryExecutionException { DataTuple currentTuple; if (!hasNext) return null; while ((currentTuple = child.next()) != null) { boolean sameGroup = true; for( int i : groupColumnIndices) { if ( ! currentTuple.getField(i).equals(groupTuple.getField(i))) sameGroup = false; } if( !sameGroup) { DataTuple outputTuple = getOutputTuple(); groupTuple = currentTuple; for( int i = 0; i <aggColumnIndices.length; i++) { aggregates[i].reset(); aggregates[i].aggregate(currentTuple.getField(aggColumnIndices[i])); } return outputTuple; } else { for( int i = 0; i <aggColumnIndices.length; i++) { aggregates[i].aggregate(currentTuple.getField(aggColumnIndices[i])); } } } hasNext = false; return getOutputTuple(); } @Override public void close() throws QueryExecutionException { // TODO Auto-generated method stub } private DataTuple getOutputTuple() { DataTuple outputTuple = new DataTuple(groupColumnOutputPositions.length); for (int i = 0; i < groupColumnOutputPositions.length; i++) { int index = groupColumnOutputPositions[i]; if (index != -1) { outputTuple.assignDataField(groupTuple.getField(groupColumnIndices[index]), i); } } for (int i = 0; i < aggregateColumnOutputPosition.length; i++) { int index = aggregateColumnOutputPosition[i]; if (index != -1) { outputTuple.assignDataField(aggregates[index].getAggregate(), i); } } return outputTuple; } }
package aliens; public class Main { public static void main(String[] args) { //Creazione giocatore Giocatore g1 = new Giocatore("Phil", 30); Giocatore g2 = new Giocatore("Tiri", 30); //Creazione gruppo alieni Alieno a1 = new Alieno("Marziano", 15); Alieno a2 = new Alieno("Venusiano", 8); Alieno a3 = new Alieno("Plutoniano", 3); Alieno a4 = new Alieno("Luniano", 5); //Creazione gioco Gioco game1 = new Gioco(g1, new Alieno[] {a1,a2,a3,a4}); //Creazione gioco2, con creazione sul momento del gruppo alieni. Gioco game2 = new Gioco(g2, new Alieno[] {new Alieno("Plum", 25), new Alieno("Skip", 2)}); System.out.println("Totale danno: " + game1.damage()); System.out.println("Vivo: " + game1.isAlive(g1)); System.out.println("Totale danno: " + game2.damage()); System.out.println("Vivo: " + game2.isAlive(g2)); } }
package com.forever.service; /** * @Description: * @Author: zhang * @Date: 2019/6/18 */ public interface IHelloService { public String hello(String name); }
package com.huy8895.dictionaryapi.helper; import com.huy8895.dictionaryapi.model.enums.HtmlTag; import com.huy8895.dictionaryapi.model.word.Category; import com.huy8895.dictionaryapi.model.word.Part; import org.jsoup.nodes.Element; import org.springframework.stereotype.Component; @Component public class ElementHelper { public Category convertElementH2(Element element){ if (element.tagName().equals(HtmlTag.H2.getTag())) { Category category = new Category(); category.setName(element.text()); return category; } return null; } public Part convertElementH3(Element element){ if (element.tagName().equals(HtmlTag.H3.getTag())) { Part part = new Part(); return part; } return null; } }
package ru.krivocraft.tortoise.core.search; import ru.krivocraft.tortoise.core.model.Track; import java.util.List; import java.util.function.Consumer; final class AddIfNotAdded implements Consumer<Track.Reference> { private final List<Track.Reference> references; AddIfNotAdded(List<Track.Reference> references) { this.references = references; } @Override public void accept(Track.Reference reference) { if (!references.contains(reference)) { references.add(reference); } } }
package com.example.bootcamp.commons; public class ResponseMessage { public static final String OK = "ok"; public static final String SUCCESS = "Success"; public static final String FAILED = "Failed"; public static final String DATA_VALIDATION_ERROR = "Data Validation Error"; public static final String INTERNAL_ERROR = "Failure due to the server not responding at this time. Please try again later. "; public static final String ACCESS_DENIED = "Forbiden Access Denied!"; public static final String NO_DATA_FOUND = "No Data Found"; public static final String EMAIL_ALREADY_EXISTS ="The provided email is already registered and they should try to login instead or use another email to register. "; public static final String PHONE_ALREADY_EXISTS ="The provided phone number is already registered and should try to login instead or use another phone number to register. "; public static final String REGISTERATION_FAILURE ="Registeration Failed. Please Try Again!"; public static final String REGISTERATION_SUCCESS ="Thank you for signing up."; public static final String EMAIL_NOT_FOUND ="Your email entered is not registered with us. Please provide a valid email."; public static final String EMAIL_OR_PHONE_NOT_FOUND ="This email/phone number entered is not registered with us. Please provide a valid email/phone number"; public static final String RESET_LINK_SUCCESS ="An email has been sent with a reset link. Please check your inbox."; public static final String EMAIL_OR_RESET_LINK_INVALID =" Invalid email or link.Please provide valid link"; public static final String RESET_LINK_EXPIRED ="Your Link has Expired.Please try generating new link"; public static final String RESET_LINK_VERIFIED ="Your Link verified successfully."; public static final String OLD_PASSWORD_INCORRECT ="Your Old Password is incorrect."; public static final String MATCH_FAIL ="Your New Password doesn't match Confirm Password"; public static final String RESET_PASSWORD_SUCCESS ="Password updated successfully"; }
package id.barkost.waris; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.DisplayMetrics; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ScrollView; public class Materi extends Activity { public Button a1, a2, a3, a4, a5, a6, a7, a8, a9, a10; public ScrollView scroll; Animation anim1, anim2, anim; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.materi); DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int width = displaymetrics.widthPixels; int height = displaymetrics.heightPixels; int new_h = height / 11; int new_w = width; a1 = (Button) findViewById(R.id.mat_definisi); a2 = (Button) findViewById(R.id.mat_hadits); a3 = (Button) findViewById(R.id.mat_hak); a4 = (Button) findViewById(R.id.mat_rukun); a5 = (Button) findViewById(R.id.mat_sebab); a6 = (Button) findViewById(R.id.mat_penghalang); a7 = (Button) findViewById(R.id.mat_masalah); a8 = (Button) findViewById(R.id.mat_ayat); a9 = (Button) findViewById(R.id.mat_ahli); a10 = (Button) findViewById(R.id.mat_pohon); a1.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h)); a2.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h)); a3.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h)); a4.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h)); a5.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h)); a6.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h)); a7.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h)); a8.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h)); a9.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h)); a10.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h)); a1.setVisibility(View.GONE); a2.setVisibility(View.GONE); a3.setVisibility(View.GONE); a4.setVisibility(View.GONE); a5.setVisibility(View.GONE); a6.setVisibility(View.GONE); a7.setVisibility(View.GONE); a8.setVisibility(View.GONE); a9.setVisibility(View.GONE); a10.setVisibility(View.GONE); trans(); } public void trans() { anim1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_from_right); anim2 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_from_left); new Handler().postDelayed(new Runnable() { @Override public void run() { a1.setVisibility(View.VISIBLE); a2.setVisibility(View.VISIBLE); a3.setVisibility(View.VISIBLE); a4.setVisibility(View.VISIBLE); a5.setVisibility(View.VISIBLE); a6.setVisibility(View.VISIBLE); a7.setVisibility(View.VISIBLE); a8.setVisibility(View.VISIBLE); a9.setVisibility(View.VISIBLE); a10.setVisibility(View.VISIBLE); a1.setAnimation(anim1); a2.setAnimation(anim2); a3.setAnimation(anim1); a4.setAnimation(anim2); a5.setAnimation(anim1); a6.setAnimation(anim2); a7.setAnimation(anim1); a8.setAnimation(anim2); a9.setAnimation(anim1); a10.setAnimation(anim2); } }, 800); } public void onClick(View view) { switch (view.getId()) { case R.id.mat_definisi: MateriCnt.pos = 0; call(); break; case R.id.mat_hadits: MateriCnt.pos = 1; call(); break; case R.id.mat_hak: MateriCnt.pos = 2; call(); break; case R.id.mat_rukun: MateriCnt.pos = 3; call(); break; case R.id.mat_sebab: MateriCnt.pos = 4; call(); break; case R.id.mat_penghalang: MateriCnt.pos = 5; call(); break; case R.id.mat_masalah: Intent c = new Intent(Materi.this, MateriMasalah.class); startActivity(c); overridePendingTransition(R.anim.slide_from_right, R.anim.stand); break; case R.id.mat_ayat: Intent i = new Intent(Materi.this, MateriAyat.class); startActivity(i); overridePendingTransition(R.anim.slide_from_right, R.anim.stand); break; case R.id.mat_ahli: Intent a = new Intent(Materi.this, MateriAhli.class); startActivity(a); overridePendingTransition(R.anim.slide_from_right, R.anim.stand); break; case R.id.mat_pohon: Intent d = new Intent(Materi.this, MateriPohon.class); startActivity(d); overridePendingTransition(R.anim.slide_from_right, R.anim.stand); break; default: break; } } public void call(){ Intent i = new Intent(Materi.this, MateriCnt.class); startActivity(i); overridePendingTransition(R.anim.slide_from_right, R.anim.stand); } public void onBackPressed() { finish(); overridePendingTransition(R.anim.stand, R.anim.exit_to_bottom); } }
package com.xwj.point; public interface HelloService { public void sayHello(String name); }
package tw.org.iii.AbnerJava; public class Try_Catch_Finally { public static void main(String[] args) { // TODO Auto-generated method stub Finally obj1 = new Finally(); obj1.m1(); } } //-----try-catch-finally共有3大結構 //-----1.try - catch -----catch可多個 //-----2.try - catch -----catch可多個 - finally //-----3.try - finally class Finally { void m1(){ int a = 10 ; int b = 3; try { System.out.println(a/b); return; } catch(Exception e) { System.out.println("Catch"); } finally { //-----加上finally可以保證在這個try-catch結束後一定會執行finally裡面的程式 //-----如例try裡面加上return 導致 [Game Over] 不會被執行 但finally中的程式仍然被執行 System.out.println("Finally"); } System.out.println("Game Over"); } }
package calTracker.demo.calTracker.Services; import calTracker.demo.calTracker.Models.Snack; import calTracker.demo.calTracker.Repos.SnackRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class SnackService { @Autowired SnackRepo snackRepo; public boolean save(Snack snack){ snackRepo.save(snack); return true; } public List<Snack> dailySnacks(String date){ return snackRepo.findByDate(date); } }
package pl.bykowski.springbootdata; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.datepicker.DatePicker; import com.vaadin.flow.component.html.Image; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.router.Route; import org.springframework.beans.factory.annotation.Autowired; import javax.xml.soap.Text; import java.time.LocalDate; @Route("corpse") public class CorpseGui extends VerticalLayout { @Autowired private CorpseRepo corpseRepo; private TextField textFieldName = new TextField("Name"); private ComboBox<CorpseSize> comboBox = new ComboBox<>("Body size"); private DatePicker datePicker = new DatePicker("Date of death"); private Button button = new Button("co łaska, ale nie mniej niż 150zł"); private Image image = new Image(); public CorpseGui() { comboBox.setItems(CorpseSize.values()); image.setSrc("http://www.gify.net/data/media/631/skarbonka-ruchomy-obrazek-0019.gif"); button.addClickListener(clickEvent -> addCorpse()); add(textFieldName); add(comboBox); add(datePicker); add(button); add(image); image.setVisible(false); } public void addCorpse() { Corpse corpse = new Corpse(); corpse.setName(textFieldName.getValue()); corpse.setCorpseSize(comboBox.getValue()); corpse.setDateOfDeath(datePicker.getValue()); corpseRepo.save(corpse); image.setVisible(true); } }
package fr.apocalypse.gestionpersonnage; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.widget.EditText; public class AddDialog extends DialogFragment { public static final String ARG_NAME = "AddDialog.name"; private String name; public AddDialog() { super(); this.name = "[null]"; listener = new AddDialog.AddDialogListener(){ @Override public void onDialogPositiveClick(DialogFragment dialog) { } @Override public void onDialogNegativeClick(DialogFragment dialog) { } }; } @NonNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { // Use the Builder class for convenient dialog construction AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(name); builder.setView(R.layout.add) .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { listener.onDialogPositiveClick(AddDialog.this); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { listener.onDialogNegativeClick(AddDialog.this); } }); return builder.create(); } public void setName(String name) { this.name = name; } public String getName() { return this.name; } public int getValue(){ EditText edit = getDialog().findViewById(R.id.edit_value); return Integer.parseInt(edit.getText().toString()); } /* The activity that creates an instance of this dialog fragment must * implement this interface in order to receive event callbacks. * Each method passes the DialogFragment in case the host needs to query it. */ public interface AddDialogListener { public void onDialogPositiveClick(DialogFragment dialog); public void onDialogNegativeClick(DialogFragment dialog); } // Use this instance of the interface to deliver action events AddDialog.AddDialogListener listener; }
package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class user_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.List<String> _jspx_dependants; private org.apache.jasper.runtime.TagHandlerPool _jspx_tagPool_c_out_value_nobody; private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector; public java.util.List<String> getDependants() { return _jspx_dependants; } public void _jspInit() { _jspx_tagPool_c_out_value_nobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); } public void _jspDestroy() { _jspx_tagPool_c_out_value_nobody.release(); } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=utf-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write(" <!-- scriplet utilizado para poder colocar codigo java dentro do jsp -->\n"); out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"); out.write("<html>\n"); out.write(" <head>\n"); out.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n"); out.write(" <link type=\"text/css\"\n"); out.write(" href=\"css/ui-lightness/jquery-ui-1.8.18.custom.css\" rel=\"stylesheet\" />\n"); out.write(" <script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-1.7.1.js\"></script>\n"); out.write(" <script type=\"text/javascript\" src=\"http://www.godtur.no/godtur/js/jquery-ui-1.8.18.custom.min.js\"></script>\n"); out.write("\n"); out.write(" <title>Add new user</title>\n"); out.write(" </head>\n"); out.write(" <body>\n"); out.write("\n"); out.write(" <form method=\"POST\" action='ControllerIes' name=\"frmAddIes\"> <!-- formulario que irar receber os dados de entrada e irar mandar pelo metodo post ao controlador(ControllerIes)onde por meio da dao e util irar mandar para o banco de dados-->\n"); out.write(" User ID : <input type=\"text\" readonly=\"readonly\" name=\"userid\"\n"); out.write(" value=\""); if (_jspx_meth_c_out_0(_jspx_page_context)) return; out.write("\" /> <br /> \n"); out.write(" Cod IES : <input\n"); out.write(" type=\"text\" name=\"cod_ies\"\n"); out.write(" value=\""); if (_jspx_meth_c_out_1(_jspx_page_context)) return; out.write("\" /> <br /> \n"); out.write(" Razao Social : <input\n"); out.write(" type=\"text\" name=\"razao_social\"\n"); out.write(" value=\""); if (_jspx_meth_c_out_2(_jspx_page_context)) return; out.write("\" /> <br />\n"); out.write(" CNPJ : <input\n"); out.write(" type=\"text\" name=\"cnpj\"\n"); out.write(" value=\""); if (_jspx_meth_c_out_3(_jspx_page_context)) return; out.write("\" /> <br /> \n"); out.write("\n"); out.write(" Email : <input type=\"text\" name=\"email\" size=\"20\"\n"); out.write(" value=\""); if (_jspx_meth_c_out_4(_jspx_page_context)) return; out.write("\" /> <br />\n"); out.write("\n"); out.write(" Endereço : <input type=\"text\" name=\"endereco\"\n"); out.write(" value=\""); if (_jspx_meth_c_out_5(_jspx_page_context)) return; out.write("\" /> <br />\n"); out.write("\n"); out.write(" Senha : <input type=\"text\" name=\"senha\"\n"); out.write(" value=\""); if (_jspx_meth_c_out_6(_jspx_page_context)) return; out.write("\" /> <br />\n"); out.write("\n"); out.write(" <input type=\"submit\" value=\"Submit\" />\n"); out.write("\n"); out.write(" <script> alert(\"Cadastrado com Sucesso !\");\n"); out.write(" </script>\n"); out.write(" </form>\n"); out.write(" </body>\n"); out.write("</html>\n"); out.write("\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } private boolean _jspx_meth_c_out_0(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // c:out org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_0 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class); _jspx_th_c_out_0.setPageContext(_jspx_page_context); _jspx_th_c_out_0.setParent(null); _jspx_th_c_out_0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ies.userid}", java.lang.Object.class, (PageContext)_jspx_page_context, null)); int _jspx_eval_c_out_0 = _jspx_th_c_out_0.doStartTag(); if (_jspx_th_c_out_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_0); return true; } _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_0); return false; } private boolean _jspx_meth_c_out_1(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // c:out org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_1 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class); _jspx_th_c_out_1.setPageContext(_jspx_page_context); _jspx_th_c_out_1.setParent(null); _jspx_th_c_out_1.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ies.cod_ies}", java.lang.Object.class, (PageContext)_jspx_page_context, null)); int _jspx_eval_c_out_1 = _jspx_th_c_out_1.doStartTag(); if (_jspx_th_c_out_1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_1); return true; } _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_1); return false; } private boolean _jspx_meth_c_out_2(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // c:out org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_2 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class); _jspx_th_c_out_2.setPageContext(_jspx_page_context); _jspx_th_c_out_2.setParent(null); _jspx_th_c_out_2.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ies.razao_social}", java.lang.Object.class, (PageContext)_jspx_page_context, null)); int _jspx_eval_c_out_2 = _jspx_th_c_out_2.doStartTag(); if (_jspx_th_c_out_2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_2); return true; } _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_2); return false; } private boolean _jspx_meth_c_out_3(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // c:out org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_3 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class); _jspx_th_c_out_3.setPageContext(_jspx_page_context); _jspx_th_c_out_3.setParent(null); _jspx_th_c_out_3.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ies.cnpj}", java.lang.Object.class, (PageContext)_jspx_page_context, null)); int _jspx_eval_c_out_3 = _jspx_th_c_out_3.doStartTag(); if (_jspx_th_c_out_3.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_3); return true; } _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_3); return false; } private boolean _jspx_meth_c_out_4(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // c:out org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_4 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class); _jspx_th_c_out_4.setPageContext(_jspx_page_context); _jspx_th_c_out_4.setParent(null); _jspx_th_c_out_4.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ies.email}", java.lang.Object.class, (PageContext)_jspx_page_context, null)); int _jspx_eval_c_out_4 = _jspx_th_c_out_4.doStartTag(); if (_jspx_th_c_out_4.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_4); return true; } _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_4); return false; } private boolean _jspx_meth_c_out_5(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // c:out org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_5 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class); _jspx_th_c_out_5.setPageContext(_jspx_page_context); _jspx_th_c_out_5.setParent(null); _jspx_th_c_out_5.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ies.endereco}", java.lang.Object.class, (PageContext)_jspx_page_context, null)); int _jspx_eval_c_out_5 = _jspx_th_c_out_5.doStartTag(); if (_jspx_th_c_out_5.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_5); return true; } _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_5); return false; } private boolean _jspx_meth_c_out_6(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // c:out org.apache.taglibs.standard.tag.rt.core.OutTag _jspx_th_c_out_6 = (org.apache.taglibs.standard.tag.rt.core.OutTag) _jspx_tagPool_c_out_value_nobody.get(org.apache.taglibs.standard.tag.rt.core.OutTag.class); _jspx_th_c_out_6.setPageContext(_jspx_page_context); _jspx_th_c_out_6.setParent(null); _jspx_th_c_out_6.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${ies.senha}", java.lang.Object.class, (PageContext)_jspx_page_context, null)); int _jspx_eval_c_out_6 = _jspx_th_c_out_6.doStartTag(); if (_jspx_th_c_out_6.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_6); return true; } _jspx_tagPool_c_out_value_nobody.reuse(_jspx_th_c_out_6); return false; } }
package projetos.testes; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import cdp.projetos.Produtividade; public class ProdutividadeTest { private Produtividade minhaProd; @Before public void setUp() throws Exception { minhaProd = new Produtividade("patentes", 20); } @Test public void testGetProdutividade() { assertEquals("patentes", minhaProd.getProdutividade()); assertNotEquals("PATENTES", minhaProd.getProdutividade()); } @Test public void testGetQuantidade() { assertEquals(20, minhaProd.getQuantidade()); assertNotEquals(15, minhaProd.getQuantidade()); } }
import java.util.*; /* * 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 Enneacle */ public class ArrayTest { public static int[] whatHappens(int A[]) { int []B = new int[A.length]; for (int i=0; i<A.length; i++) { B[i]=A[i]*2; } return B; } public static void main(String args[]) { int A[] = {10,20,30}; int B[] = new int[A.length]; B = whatHappens(A); System.out.println(B[0]); } }
package org.isc.certanalysis.service; import org.isc.certanalysis.domain.NotificationGroup; import org.isc.certanalysis.repository.NotificationGroupRepository; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @author p.dzeviarylin */ @Service @Transactional public class NotificationGroupService { public final static String NOTIFICATION_GROUPS_ALL = "notificationGroupsAll"; private final NotificationGroupRepository notificationGroupRepository; public NotificationGroupService(NotificationGroupRepository notificationGroupRepository) { this.notificationGroupRepository = notificationGroupRepository; } @Transactional(readOnly = true) @Cacheable(value = NOTIFICATION_GROUPS_ALL, key = "'notificationGroupsAll'") public List<NotificationGroup> findAll() { return notificationGroupRepository.findAll(); } }
package com.github.iam20.core; import com.pi4j.wiringpi.SoftPwm; import lombok.extern.slf4j.Slf4j; @Slf4j public class MachineController extends Thread { private String control; private static final int PIN_NUMBER = 1; public MachineController(String control) { this.control = control; } @Override public void run() { super.run(); SoftPwm.softPwmCreate(PIN_NUMBER, 0, 100); log.info("LED CONTROL"); log.info("DIMMING = " + control); if (control.equals("ON")) { SoftPwm.softPwmWrite(PIN_NUMBER, 100); log.info("Pin number {}", PIN_NUMBER); log.info("ON"); } else { SoftPwm.softPwmWrite(PIN_NUMBER, 0); log.info("Pin number {}", PIN_NUMBER); log.info("OFF"); } } }
package calculating.methods.composite.formuls; import java.util.function.Function; /** * Created by Ольга on 19.11.2016. */ public class Rectangle { private Double segmentStart; private Double segmentEnd; private int numberOfSegments; private Function<Double, Double> func; public Rectangle(Double segmentStart, Double segmentEnd, int numberOfSegments, Function<Double, Double> func) { this.segmentStart = segmentStart; this.segmentEnd = segmentEnd; this.numberOfSegments = numberOfSegments; this.func = func; } public Double calculateIntegral() { Double result = 0.0; for (int k = 0; k < numberOfSegments; k++) { result += getStep() * func.apply((getZk(k) + getZk(k + 1)) / 2); } return result; } private Double getStep() { return (segmentEnd - segmentStart) / numberOfSegments; } private Double getZk(int k) { return segmentStart + getStep() * k; } }
import java.util.Scanner; public class BMR_Finder { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double BMR_W, BMR_M; //BMR for both women and man double weight, height; int age; System.out.println("Please input your weight in pounds"); weight = sc.nextDouble(); System.out.println("Please input your height in inches"); height = sc.nextDouble(); System.out.println("Please input your age"); age = sc.nextInt(); BMR_W = 655 + (4.3 * weight) + (4.7 * height) - (4.7 * age); BMR_M = 66 + (6.3 * weight) + (12.9 * height) - (6.8 * age); System.out.println("BMR for a Woman: " +BMR_W); System.out.println("BMR for a Man: " +BMR_M); } }
package com.cinema.biz.service.impl; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cinema.biz.dao.SimDeviceMapper; import com.cinema.biz.model.SimDevice; import com.cinema.biz.model.base.TSimDevice; import com.cinema.biz.service.SimDeviceService; @Service public class SimDeviceServiceImpl implements SimDeviceService { @Autowired private SimDeviceMapper simDeviceDao; /**列表*/ @Override public List<SimDevice> getList(Map<String, Object> paraMap) { return simDeviceDao.getList(paraMap); } /**添加*/ @Override public int insert(TSimDevice t) { return simDeviceDao.insertSelective(t); } /**更新*/ @Override public int update(TSimDevice t) { return simDeviceDao.updateByPrimaryKeySelective(t); } /**删除*/ @Override public int delete(String deviceId) { return simDeviceDao.deleteByPrimaryKey(deviceId); } }
package org.point85.domain.file; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.UUID; import org.point85.domain.polling.PollingClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class to connect to a file share server and poll for new files for the * specified source id. * */ public class FileEventClient extends PollingClient { // logger private static final Logger logger = LoggerFactory.getLogger(FileEventClient.class); // not localizable public static final String READY_FOLDER = "ready"; public static final String PROCESSING_FOLDER = "processing"; public static final String PASS_FOLDER = "pass"; public static final String FAIL_FOLDER = "fail"; private static final String ERROR_EXT = ".error"; // service handling the queried data private FileEventListener eventListener; // file service private FileService fileService; // files being worked on private List<String> inProcessFiles = new ArrayList<>(); public FileEventClient() { super(); this.fileService = new FileService(); } public FileEventClient(FileEventListener eventListener, FileEventSource eventSource, List<String> sourceIds, List<Integer> pollingPeriods) { super(eventSource, sourceIds, pollingPeriods); this.fileService = new FileService(); this.eventListener = eventListener; } public FileService getFileService() { return fileService; } public String readFile(File file) throws Exception { return fileService.readFile(file); } @Override protected void onPoll(String sourceId) { if (logger.isInfoEnabled()) { logger.info("Querying for new files for source " + sourceId); } // query file server for new files String filePath = getFileEventSource().getNetworkPath(sourceId) + File.separator + READY_FOLDER; List<File> files = fileService.getFiles(filePath); eventListener.resolveFileEvents(this, sourceId, files); } public FileEventSource getFileEventSource() { return (FileEventSource) dataSource; } @Override public int hashCode() { return Objects.hash(dataSource.getId()); } @Override public boolean equals(Object other) { if (!(other instanceof FileEventClient)) { return false; } FileEventClient otherClient = (FileEventClient) other; return getFileEventSource().getId().equals(otherClient.getFileEventSource().getId()); } public void moveFileToReadyFolder(File file, FileEventSource source, String sourceId) throws Exception { String toPath = source.getHost() + File.separator + sourceId + File.separator + FileEventClient.READY_FOLDER + File.separator + file.getName(); // make sure that directory is there if (!fileService.createDirectory(toPath)) { throw new Exception("Cannot create directory " + toPath); } fileService.moveFile(file, toPath); } public void moveFile(File file, String fromFolder, String toFolder) throws Exception { this.moveFile(file, fromFolder, toFolder, null); } public void moveFile(File file, String fromFolder, String toFolder, Exception e) throws Exception { // path in ready folder String path = file.getCanonicalPath(); String source = path.replace(READY_FOLDER, fromFolder); String destination = path.replace(READY_FOLDER, toFolder); // move the file to the destination folder fileService.moveFile(source, destination); if (e != null) { int idx = destination.lastIndexOf(File.separator); String errorPath = destination.substring(0, idx); // write a file with the error content fileService.writeFile(errorPath, file.getName() + ERROR_EXT, e.getClass().getSimpleName() + "\n" + e.getMessage()); } } public void writeFile(FileEventSource source, String sourceId, String folder, String content) throws Exception { String pathName = source.getHost() + File.separator + sourceId + File.separator + folder; fileService.writeFile(pathName, UUID.randomUUID().toString(), content); } public synchronized boolean fileIsProcessing(File file) { if (inProcessFiles.contains(file.getName())) { // already being worked on return true; } inProcessFiles.add(file.getName()); return false; } public synchronized void stopProcessing(File file) { inProcessFiles.remove(file.getName()); } }
package tui; public class UserTUI { }
package com.meetingapp.android.activities.notification; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.LinearLayout; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.gson.Gson; import com.meetingapp.android.R; import com.meetingapp.android.activities.base.BaseActivity; import com.meetingapp.android.activities.info_meeting.InfoMeetingActivity; import com.meetingapp.android.adapters.notifications.NotificationsAdapter; import com.meetingapp.android.callback.OnMeetingClickListener; import com.meetingapp.android.constants.Constants; import com.meetingapp.android.fragments.home.NotificationsCountChanged; import com.meetingapp.android.model.Contact; import com.meetingapp.android.model.MeetingModels; import com.meetingapp.android.model.Participant; import org.greenrobot.eventbus.EventBus; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; import static com.meetingapp.android.constants.Constants.REQUEST_CONTACTS_PERMISSION; import static com.meetingapp.android.constants.Constants.URL_MEETING; /** * This function is used to open the Notification from the home screen **/ public class NotificationActivity extends BaseActivity implements OnMeetingClickListener { @BindView(R.id.rv_list) RecyclerView notificationsList; @BindView(R.id.no_notification_LL) LinearLayout noNotificationLL; private String currentUser; private Unbinder unbinder; private FirebaseDatabase mDatabase; private DatabaseReference mDatabaseReference; private NotificationsAdapter adapter; private ArrayList<MeetingModels> mMeetingModels; private HashMap<String, Contact> mListContactsPhone; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_notifications); init(); setupDefaults(); setupEvents(); } @Override public void onResume() { super.onResume(); adapter.setOnMeetingClickListener(this); } @Override public void onPause() { super.onPause(); adapter.setOnMeetingClickListener(null); } @Override protected void onDestroy() { unbinder.unbind(); super.onDestroy(); } /** * This callback is used for when the user allows or deny permission */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { if (requestCode == REQUEST_CONTACTS_PERMISSION) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { initContactsList(); if (adapter != null) adapter.notifyDataSetChanged(); } else { setProgressMessage(getString(R.string.permission_denied)); } } else super.onRequestPermissionsResult(requestCode, permissions, grantResults); } /** * This function is used for redirecting the info meeting screen */ @Override public void onMeetingClick(MeetingModels meeting) { Intent intent = new Intent(this, InfoMeetingActivity.class); Gson gson = new Gson(); String json = gson.toJson(meeting); getApp().getAppPreference().setEventJson(json); startActivity(intent); } private void init() { unbinder = ButterKnife.bind(this); getApp().getAppComponent().inject(this); mDatabase = FirebaseDatabase.getInstance(); mListContactsPhone = new HashMap<>(); mMeetingModels = new ArrayList<>(); String event = getApp().getAppPreference().getEventJson(); initFirebase(event); adapter = new NotificationsAdapter(mMeetingModels, mListContactsPhone); notificationsList.setLayoutManager(new LinearLayoutManager(this)); notificationsList.setAdapter(adapter); currentUser = getApp().getAppPreference().getPhoneNo(); } private void setupDefaults() { setTitle("Notifications"); if (isPermissionGranted()) { initContactsList(); } else { requestPermission(); } } private void setupEvents() { } /** * Access the Meeting database */ private void initFirebase(String event) { mDatabaseReference = mDatabase.getReference(URL_MEETING); mDatabaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { mMeetingModels.clear(); for (DataSnapshot noteDataSnapshot : dataSnapshot.getChildren()) { MeetingModels meetingModels = noteDataSnapshot.getValue(MeetingModels.class); if (isValidMeetingModel(meetingModels)) { mMeetingModels.add(meetingModels); } } if (adapter != null) { getApp().getAppPreference().setNotificationSize(mMeetingModels.size()); EventBus.getDefault().postSticky(new NotificationsCountChanged()); sortData(); adapter.notifyDataSetChanged(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } /** * This function is used for sort the Meeting by the date */ private void sortData() { Collections.sort(mMeetingModels, new Comparator<MeetingModels>() { @Override public int compare(MeetingModels lhs, MeetingModels rhs) { return lhs.getLastChangeDate() > rhs.getLastChangeDate() ? -1 : 1; } }); if (mMeetingModels.size() > 0) { noNotificationLL.setVisibility(View.GONE); notificationsList.setVisibility(View.VISIBLE); } else { noNotificationLL.setVisibility(View.VISIBLE); notificationsList.setVisibility(View.GONE); } } /** * Validate current meeting item, make sure it's notification worthy. */ private boolean isValidMeetingModel(MeetingModels meetingModels) { if (meetingModels == null || currentUser == null || currentUser.length() == 0) return false; for (Participant participant : meetingModels.getParticipants()) { if (currentUser.equalsIgnoreCase(participant.getPhone())) { if (Constants.STATUS_PENDING.equalsIgnoreCase(participant.getStatus()) || Constants.STATUS_UPDATED.equalsIgnoreCase(participant.getStatus()) || Constants.STATUS_CANCELED.equalsIgnoreCase(participant.getStatus())) return true; } } return false; } /** * This function is used for checking the permission for accessing the contacts */ private boolean isPermissionGranted() { int permissionCheck = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS); return permissionCheck == PackageManager.PERMISSION_GRANTED; } /** * This funstion is used for requesting the contact permission */ private void requestPermission() { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS}, REQUEST_CONTACTS_PERMISSION); } /** * This function is used for getting the device contact list */ public void initContactsList() { mListContactsPhone.clear(); Cursor phones = this.getContentResolver().query(ContactsContract.CommonDataKinds .Phone.CONTENT_URI, null, null, null, null); if (phones == null) { return; } while (phones.moveToNext()) { String name = phones.getString(phones .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); String phone = phones.getString(phones .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); String photo = phones.getString (phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI)); if (photo != null) { mListContactsPhone.put(phone, new Contact(name, phone, Uri.parse(photo))); } } phones.close(); } }
package payhelper; public class PayTester { public static void main(String[] args) { Pay p = new Pay("transit", 15, "MRT", "cash"); Pay p1 = new Pay("food", 60, "breakfast", "cash"); } }
package main.java.ru.meeting.spring.controller; import main.java.ru.meeting.db.entity.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpSession; import java.util.Map; /** * Created by tseyler on 07.06.15. */ @Controller @RequestMapping(value = "/index") public class IndexController { @RequestMapping(method = RequestMethod.GET) public String viewRegistration(Map<String , Object> model, HttpSession httpSession) { System.out.println(model); Object user = httpSession.getAttribute("userForm"); if (user != null) { System.out.println((User)user); return "profile"; } User userForm = new User(); model.put("userForm", userForm); return "index"; } @RequestMapping(method = RequestMethod.POST) public String processRegistration(@ModelAttribute("userForm") User user, Map<String, Object> model, HttpSession httpSession) { User cur = Checker.checkForLogin(user); if (cur == null) { return "index"; } httpSession.setAttribute("userForm", cur); System.out.println("before profile!!!!"); model.put("userForm", cur); return "profile"; } }
package ejercicio17.a17_bibliotecabd; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void añadir(View v){ Intent intent=new Intent(this,AltaActivity.class); this.startActivity(intent); } public void mostrarTodos(View v){ Intent intent=new Intent(this,MostrarActivity.class); this.startActivity(intent); } public void borrarLibro(View v){ Intent intent=new Intent(this,BorrarActivity.class); this.startActivity(intent); } public void mostrarISBN(View v){ Intent intent=new Intent(this,IsbnActivity.class); this.startActivity(intent); } public void salir(View v){ this.finish(); } }
package com.chess; import java.util.ArrayList; import com.chess.Pieces.*; public class Board { private Square[][] squares; private boolean whitePlays; private ArrayList<Piece> wCaptured, bCaptured; private ArrayList<Move> mHistory; private ArrayList<Square[][]> moveHistory; private String[] files={"A","B","C","D","E","F","G","H"}; public Board(){ wCaptured=new ArrayList<>(); bCaptured=new ArrayList<>(); mHistory=new ArrayList<>(); moveHistory =new ArrayList<>(); whitePlays=true; squares=new Square[8][8]; squares[0][0]=new Square(new Rook(0, 0, Color.WHITE)); squares[0][1]=new Square(new Knight(0, 1, Color.WHITE)); squares[0][2]=new Square(new Bishop(0, 2, Color.WHITE)); squares[0][3]=new Square(new Queen(0, 3, Color.WHITE)); squares[0][4]=new Square(new King(0, 4, Color.WHITE)); squares[0][5]=new Square(new Bishop(0, 5, Color.WHITE)); squares[0][6]=new Square(new Knight(0, 6, Color.WHITE)); squares[0][7]=new Square(new Rook(0, 7, Color.WHITE)); for(int i=0; i<8; i++){ squares[1][i] = new Square(new Pawn(1,i,Color.WHITE)); } for(int i=2;i<6;i++){ for(int j=0;j<8; j++){ squares[i][j]=new Square(); } } for(int i=0; i<8; i++){ squares[6][i] = new Square(new Pawn(6,i,Color.BLACK)); } squares[7][0]=new Square(new Rook(7, 0, Color.BLACK)); squares[7][1]=new Square(new Knight(7, 1, Color.BLACK)); squares[7][2]=new Square(new Bishop(7, 2, Color.BLACK)); squares[7][3]=new Square(new Queen(7, 3, Color.BLACK)); squares[7][4]=new Square(new King(7, 4, Color.BLACK)); squares[7][5]=new Square(new Bishop(7, 5, Color.BLACK)); squares[7][6]=new Square(new Knight(7, 6, Color.BLACK)); squares[7][7]=new Square(new Rook(7, 7, Color.BLACK)); } public void printBoard(){ for (int i = -1; i < 9; i++) { for (int j = -1; j < 9; j++) { if(i==-1){ if(j==-1 || j==8){System.out.printf("%4s","");} else{System.out.printf("%-4s",("|"+files[j]));} } else if(i==8){ if(j==-1 || j==8){System.out.printf("%4s","");} else{System.out.printf("%-4s",("|"+files[j]));} } else if(j==-1 || j==8){System.out.printf("%-4s",("|"+(i+1)));} else{ if(squares[i][j].getPiece()!=null){ System.out.printf("%-4s",("|"+squares[i][j].getPiece().getString())); } else{System.out.printf("%-4s","|");} } } System.out.println(); } } public Vector getTile(String tile){ int rank=Integer.parseInt(tile.substring(1)); return getTile(tile.substring(0,1), rank); } public Vector getTile(String f, int r){ int file=fileIndex(f); if(file==-1 || r>8 || r<1) return null; // return board[r-1][file]; return new Vector(r-1, file); } public int fileIndex(String f){ for (int i=0; i<files.length; i++) { if((files[i]).equalsIgnoreCase(f)){return i;} } return -1; } public Square getSquare(int x, int y){return squares[x][y];} public ArrayList<Move> getMoves(Vector v){ if(v==null) return null; getSquare(v.x,v.y).getPiece().possibleMoves(this); ArrayList<Move> m= getSquare(v.x,v.y).getPiece().getCaptures(); m.addAll(getSquare(v.x, v.y).getPiece().getMoves()); return m; } public boolean isCheck(Color color){ for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if(squares[i][j].isOccupied() && squares[i][j].getPiece().getColor()!=color){ Piece p=squares[i][j].getPiece(); p.possibleMoves(this); ArrayList<Move> moves=p.getCheck(); if(moves.size()!=0) return true; } } } return false; } public void makeMove(Move move){ // System.out.print(move.getString()); Square square=squares[move.getX1()][move.getY1()]; Square destSquare=squares[move.getX2()][move.getY2()]; Piece piece=square.getPiece(); // if(move.isCapture()) System.out.println(" | "+piece.getString()+" | C"); // else System.out.println(" | "+piece.getString()); // move.setFirstMove(!piece.hasMoved()); // if(piece==null) return; piece.move(move.getX2(), move.getY2()); //castling if(move.isCastling()){ moveHistory.add(squares); mHistory.add(move); squares[move.getX2()][move.getY2()]=square; squares[move.getX1()][move.getY1()]=new Square(); squares[move.getX2()][move.getY2()].setPiece(piece); piece=squares[move.getCX1()][move.getCY1()].getPiece(); if(move.getCY1()==7){ piece.move(move.getX1(),move.getY1()+1); squares[move.getX1()][move.getY1()+1]=squares[move.getCX1()][move.getCY1()]; squares[move.getCX1()][move.getCY1()]=new Square(); squares[move.getX1()][move.getY1()+1].setPiece(piece); } else if(move.getCY1()==0){ piece.move(move.getX1(), move.getY1()-1); squares[move.getX1()][move.getY1()-1]=squares[move.getCX1()][move.getCY1()]; squares[move.getCX1()][move.getCY1()]=new Square(); squares[move.getX1()][move.getY1()-1].setPiece(piece); } whitePlays=!whitePlays; return; } //pawn promotion if(square.getPiece().getValue()==10 && square.getPiece().getColor()==Color.WHITE && move.getX2()==7){ if(move.isCapture()){ bCaptured.add(destSquare.getPiece()); } moveHistory.add(squares); mHistory.add(move); squares[move.getX2()][move.getY2()]=new Square(new Queen(move.getX2(), move.getY2(), Color.WHITE)); squares[move.getX1()][move.getY1()]=new Square(); whitePlays=!whitePlays; return; } if(square.getPiece().getValue()==10 && square.getPiece().getColor()==Color.BLACK && move.getX2()==0){ if(move.isCapture()){ wCaptured.add(destSquare.getPiece()); } moveHistory.add(squares); mHistory.add(move); squares[move.getX2()][move.getY2()]=new Square(new Queen(move.getX2(), move.getY2(), Color.BLACK)); squares[move.getX1()][move.getY1()]=new Square(); whitePlays=!whitePlays; return; } if(square.getPiece().getColor()==Color.WHITE && whitePlays){ if(move.isCapture()){ if(squares[move.getX2()][move.getY2()].getPiece().getValue()!=200){ mHistory.add(move); moveHistory.add(squares); bCaptured.add(destSquare.getPiece()); squares[move.getX2()][move.getY2()]=square; squares[move.getX1()][move.getY1()]=new Square(); squares[move.getX2()][move.getY2()].setPiece(piece); whitePlays=!whitePlays; } } else{ mHistory.add(move); moveHistory.add(squares); squares[move.getX2()][move.getY2()]=square; squares[move.getX1()][move.getY1()]=new Square(); squares[move.getX2()][move.getY2()].setPiece(piece); whitePlays=!whitePlays; } } else if(square.getPiece().getColor()==Color.BLACK && !whitePlays){ if(move.isCapture()){ if(squares[move.getX2()][move.getY2()].getPiece().getValue()!=200){ moveHistory.add(squares); mHistory.add(move); wCaptured.add(destSquare.getPiece()); squares[move.getX2()][move.getY2()]=square; squares[move.getX1()][move.getY1()]=new Square(); squares[move.getX2()][move.getY2()].setPiece(piece); whitePlays=!whitePlays; } } else{ moveHistory.add(squares); mHistory.add(move); squares[move.getX2()][move.getY2()]=square; squares[move.getX1()][move.getY1()]=new Square(); squares[move.getX2()][move.getY2()].setPiece(piece); whitePlays=!whitePlays; } } else return; } public void undo(){ // if(spare==null) return; // squares=spare; // whitePlays=!whitePlays; if(mHistory.size()==0) return; // Square[][] sq=moveHistory.remove(moveHistory.size()-1); // squares=sq; // whitePlays=!whitePlays; Move m=mHistory.remove(mHistory.size()-1); moveHistory.remove(moveHistory.size()-1); // if(m.getX1()==4 && m.getY1()==5 && m.isCapture()){ // System.out.print("Hello! "+mHistory.size()+"$ "); // System.out.println(m.getString()); // } Piece piece=squares[m.getX2()][m.getY2()].getPiece(); if(m.isCastling()){ piece=squares[m.getX2()][m.getY2()].getPiece(); piece.undo(m.getX1(), m.getY1(), true); squares[m.getX1()][m.getY1()]=squares[m.getX2()][m.getY2()]; squares[m.getX2()][m.getY2()]=new Square(); squares[m.getX1()][m.getY1()].setPiece(piece); piece=squares[m.getX1()][m.getY1()+1].getPiece(); if(m.getCY1()==7){ piece.undo(m.getCX1(),m.getCY1(), true); squares[m.getCX1()][m.getCY1()]=squares[m.getX1()][m.getY1()+1]; squares[m.getX1()][m.getY1()+1]=new Square(); squares[m.getCX1()][m.getCY1()].setPiece(piece); } else if(m.getCY1()==1){ piece.undo(m.getCX1(),m.getCY1(), true); squares[m.getCX1()][m.getCY1()]=squares[m.getX1()][m.getY1()-1]; squares[m.getX1()][m.getY1()-1]=new Square(); squares[m.getCX1()][m.getCY1()].setPiece(piece); } whitePlays=!whitePlays; return; } if(m.isPromoting()){ if(m.getX2()==7){ squares[m.getX2()][m.getY2()]=new Square(); Piece p=new Pawn(m.getX1(),m.getY1(),Color.WHITE); p.setMoved(true); Square sq=new Square(p); squares[m.getX1()][m.getY1()]=sq; if(m.isCapture()){ piece=bCaptured.remove(bCaptured.size()-1); squares[m.getX2()][m.getY2()].setPiece(piece); } whitePlays=!whitePlays; } else if(m.getX2()==0){ squares[m.getX2()][m.getY2()]=new Square(); Piece p=new Pawn(m.getX1(),m.getY1(),Color.BLACK); p.setMoved(true); Square sq=new Square(p); squares[m.getX1()][m.getY1()]=sq; if(m.isCapture()){ piece=wCaptured.remove(wCaptured.size()-1); squares[m.getX2()][m.getY2()].setPiece(piece); } whitePlays=!whitePlays; } return; } if(m.isFirstMove()){ piece=squares[m.getX2()][m.getY2()].getPiece(); piece.undo(m.getX1(), m.getY1(), true); squares[m.getX1()][m.getY1()]=squares[m.getX2()][m.getY2()]; squares[m.getX2()][m.getY2()]=new Square(); squares[m.getX1()][m.getY1()].setPiece(piece); whitePlays=!whitePlays; } else{ piece=squares[m.getX2()][m.getY2()].getPiece(); piece.undo(m.getX1(), m.getY1(), false); squares[m.getX1()][m.getY1()]=squares[m.getX2()][m.getY2()]; squares[m.getX2()][m.getY2()]=new Square(); squares[m.getX1()][m.getY1()].setPiece(piece); whitePlays=!whitePlays; } if(m.isCapture()){ if(squares[m.getX1()][m.getY1()].getPiece().getColor()==Color.WHITE){ piece=bCaptured.remove(bCaptured.size()-1); squares[m.getX2()][m.getY2()]=new Square(piece); } else{ piece=wCaptured.remove(wCaptured.size()-1); squares[m.getX2()][m.getY2()]=new Square(piece); } } // if(whist){ // piece=wCaptured.remove(wCaptured.size()-1); // squares[m.getX2()][m.getY2()].setPiece(piece); // squares[m.getX2()][m.getY2()].Occupy();; // } // if(bhist){ // piece=bCaptured.remove(bCaptured.size()-1); // squares[m.getX2()][m.getY2()].setPiece(piece); // squares[m.getX2()][m.getY2()].Occupy(); // } } public boolean isCastlingPossible(Color c, Move m, Move m2){ int x=m.getX2(), y=m.getY2(); int x2=m2.getX2(),y2=m2.getY2(); int x1=-1, y1=-1; if(squares[m.getX2()][m.getY2()].getPiece()!=null) return false; if(squares[m2.getX2()][m2.getY2()].getPiece()!=null) return false; ArrayList<Piece> opPieces=new ArrayList<>(); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if(squares[i][j].getPiece()==null) continue; if(squares[i][j].getPiece().getValue()==200){ if(squares[i][j].getPiece().getColor()==c){ x1=i; x2=j; } else continue; } if(squares[i][j].isOccupied() && squares[i][j].getPiece().getColor()!=c){ opPieces.add(squares[i][j].getPiece()); } } } for (Piece piece : opPieces) { piece.possibleMoves(this); for (Move move : piece.getMoves()) { if(move.getX2()==x1 && move.getY2()==y1) return false; if(move.getX2()==x && move.getY2()==y) return false; if(move.getX2()==x2 && move.getY2()==y2) return false; } } return true; } public ArrayList<Move> getMoves(Color c){ ArrayList<Move> res=new ArrayList<>(); // int k=1; for(int i=0; i<8; i++){ for(int j=0;j<8;j++){ if(squares[i][j].getPiece()==null) continue; Piece piece=squares[i][j].getPiece(); if(piece.getColor()==c){ piece.possibleMoves(this); // res.addAll(piece.getCaptures()); ArrayList<Move> moves=piece.getMoves(); if(moves.size()!=0){ res.addAll(moves); // System.out.println(piece.getString()+k); // k++; } // for (Move move : piece.getCaptures()) { // res.add(move); // } // for(Move move: piece.getMoves()){ // res.add(move); // } } } } return res; } public ArrayList<Move> getValidatedMoves(Color c){ ArrayList<Move> res=new ArrayList<>(); for(int i=0; i<8; i++){ for(int j=0;j<8;j++){ if(squares[i][j].getPiece()==null) continue; Piece piece=squares[i][j].getPiece(); if(piece.getColor()==c){ piece.possibleMoves(this); ArrayList<Move> moves=piece.getMoves(); for (Move move : moves) { if(!isCheckAfter(c, move)) res.add(move); } } } } return res; } public boolean isCheckAfter(Color c, Move m){ makeMove(m); boolean res=isCheck(c); undo(); return res; } public boolean isPinned(int x, int y, Color c){ squares[x][y].Unoccupy(); boolean res=isCheck(c); squares[x][y].Occupy(); return res; } public ArrayList<Square> getThreats(int r, int f, Color c){ ArrayList<Square> res=new ArrayList<>(); int x=-1, y=-1; // find the position of the king and get opposition's pieces on the board ArrayList<Square> opPieces=new ArrayList<>(); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if(squares[i][j].isOccupied() && squares[i][j].getPiece().getValue()==200 && squares[i][j].getPiece().getColor()==c){ x=i; y=j; } if(squares[i][j].isOccupied() && squares[i][j].getPiece().getColor()!=c){ opPieces.add(squares[i][j]); } } } squares[r][f].Unoccupy(); for (Square square : opPieces) { Square sq=square; sq.getPiece().possibleMoves(this); for (Move move : sq.getPiece().getCheck()) { if(move.getX2()==x && move.getY2()==y) res.add(sq); } } squares[r][f].Occupy(); return res; } public Board clone(){ Board b=new Board(); b.bCaptured=this.bCaptured; b.wCaptured=this.wCaptured; b.mHistory=this.mHistory; b.moveHistory=this.moveHistory; b.whitePlays=this.whitePlays; b.squares=this.squares; return b; } }
package slimeknights.tconstruct.smeltery.item; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import slimeknights.mantle.item.ItemBlockMeta; import slimeknights.tconstruct.smeltery.tileentity.TileChannel; public class ItemChannel extends ItemBlockMeta { public ItemChannel(Block block) { super(block); } // this is all because mojang does not pass side hit into onBlockPlacedBy. This is a bit easier than calculating that after the fact and less hacky that storing it between functions @Override public boolean placeBlockAt(ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, IBlockState newState) { //Ceramics.log.info("test"); boolean result = super.placeBlockAt(stack, player, world, pos, side, hitX, hitY, hitZ, newState); if(result) { TileEntity te = world.getTileEntity(pos); // if we have a channel, update it sensitive to our sneaking and the side hit if(te instanceof TileChannel) { ((TileChannel) te).onPlaceBlock(side, player.isSneaking()); } } return result; } }
package com.lenovohit.hcp.test.appointment; import static org.junit.Assert.*; import java.util.List; import javax.annotation.Resource; import org.junit.Test; import com.lenovohit.core.manager.GenericManager; import com.lenovohit.hcp.base.model.Department; import com.lenovohit.hcp.base.model.Dictionary; import com.lenovohit.hcp.test.BaseTest; public class BaseModuleTest extends BaseTest { @Resource private GenericManager<Dictionary, String> dictionaryManager; @Resource private GenericManager<Department, String> departmentManager; @Test public void testFindPops() { String hosId = "H31AAAA001"; StringBuilder sql = new StringBuilder("from Department where 1=1 and hosId = ? and isRegdept = '1'"); List<Department> departments = departmentManager.find(sql.toString(), hosId); assertEquals(8, departments.size()); } }
/* * Welcome to use the TableGo Tools. * * http://vipbooks.iteye.com * http://blog.csdn.net/vipbooks * http://www.cnblogs.com/vipbooks * * Author:bianj * Email:edinsker@163.com * Version:5.8.0 */ package com.lenovohit.hwe.base.model; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; /** * BASE_REGION * * @author zyus * @version 1.0.0 2017-12-14 */ @Entity @Table(name = "BASE_REGION") public class Region extends AuditableModel implements java.io.Serializable { /** 版本号 */ private static final long serialVersionUID = -4592326007128517077L; /** 父id */ private String 父id; /** name */ private String name; /** shortName */ private String shortName; /** longitude */ private BigDecimal longitude; /** latitude */ private BigDecimal latitude; /** 等级(1省/直辖市,2地级市,3区县,4镇/街道) */ private Integer level; /** sort */ private Integer sort; /** 状态(0启用/1禁用) */ private String status; /** * 获取父id * * @return 父id */ @Column(name = "父ID", nullable = true, length = 32) public String get父id() { return this.父id; } /** * 设置父id * * @param 父id */ public void set父id(String 父id) { this.父id = 父id; } /** * 获取name * * @return name */ @Column(name = "NAME", nullable = true, length = 50) public String getName() { return this.name; } /** * 设置name * * @param name */ public void setName(String name) { this.name = name; } /** * 获取shortName * * @return shortName */ @Column(name = "SHORT_NAME", nullable = true, length = 50) public String getShortName() { return this.shortName; } /** * 设置shortName * * @param shortName */ public void setShortName(String shortName) { this.shortName = shortName; } /** * 获取longitude * * @return longitude */ @Column(name = "LONGITUDE", nullable = true) public BigDecimal getLongitude() { return this.longitude; } /** * 设置longitude * * @param longitude */ public void setLongitude(BigDecimal longitude) { this.longitude = longitude; } /** * 获取latitude * * @return latitude */ @Column(name = "LATITUDE", nullable = true) public BigDecimal getLatitude() { return this.latitude; } /** * 设置latitude * * @param latitude */ public void setLatitude(BigDecimal latitude) { this.latitude = latitude; } /** * 获取等级(1省/直辖市,2地级市,3区县,4镇/街道) * * @return 等级(1省/直辖市 */ @Column(name = "LEVEL", nullable = true, length = 10) public Integer getLevel() { return this.level; } /** * 设置等级(1省/直辖市,2地级市,3区县,4镇/街道) * * @param level * 等级(1省/直辖市 */ public void setLevel(Integer level) { this.level = level; } /** * 获取sort * * @return sort */ @Column(name = "SORT", nullable = true, length = 10) public Integer getSort() { return this.sort; } /** * 设置sort * * @param sort */ public void setSort(Integer sort) { this.sort = sort; } /** * 获取状态(0启用/1禁用) * * @return 状态(0启用/1禁用) */ @Column(name = "STATUS", nullable = true, length = 1) public String getStatus() { return this.status; } /** * 设置状态(0启用/1禁用) * * @param status * 状态(0启用/1禁用) */ public void setStatus(String status) { this.status = status; } }
package task; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import status.Status; public class New_Feature extends Task{ //SUBATAREAS? public New_Feature(String nombreTask, String descripcionTask, int complejidad, LinkedList<Task> dependencias, ArrayList<Status> historicoEstado, LinkedList<Task> subtareas, Date fechaFinalizacion, boolean subtarea) { super(nombreTask, descripcionTask, complejidad, dependencias, historicoEstado, subtareas, fechaFinalizacion, subtarea); } public void setIdTask() { this.idTask = "MEJ"+ Math.random(); } /** * Se calcula la estimacion en base a las tareas de las que depende y el valor inicial de complejidad * @return complejidad inicial (si es dependiente de alguna US o task) o el valor inicial de complejidad si no depende de nada */ public int getEstimacion() { Iterator<Task> listIterator = dependencias.iterator(); int a=0; while (listIterator.hasNext()) { a=listIterator.next().getComplejidad()+(int)Math.round(listIterator.next().getComplejidad()*0.5); } if (a==0) return getComplejidad(); else return a; } /** * Metodo para saber si puede tener dependencias o no * @return 1 si puede, 0 si no puede */ public int permisoDependencias() { return 1; } /** * Crea un arreglo con los tipos de dependencias que puede tener * @param tipo Arreglo con los tipos de dependencias que puede tener * @param maxCant maxima cantidad de dependencias que puede tener, 999 indica que no hay limite */ public void tipoDependencias (ArrayList<String> tipo, int maxCant) { tipo.add("User Story"); tipo.add("Task"); maxCant=1; } /** * Metodo para saber si puede tener subtareas o no * @return 1 si puede, 0 si no puede */ public int permisoSubtarea() { return 1; } /** * Crea un arreglo con los tipos de dependencias que puede tener * @param tipo Arreglo con los tipos de subtareas que puede tener * @param maxCant maxima cantidad de subatareas que puede tener, 999 indica que no hay limite */ public void tipoSubtareas (ArrayList<String> tipo, int maxCant) { tipo.add("Task"); maxCant=999; } }
package com.spreadtrum.android.eng; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; public class engineeringmodel extends PreferenceActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.layout.main); } public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { return false; } }
package com.jvschool.dao.api; import com.jvschool.model.RoleEntity; public interface RoleDAO { RoleEntity getRoleByName(String nameRole); void addRole(RoleEntity role); }
package ServerCode; import SharedCode.Operations; import java.rmi.AlreadyBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; public class Server extends UnicastRemoteObject { protected Server() throws RemoteException { } public static void main(String[] args){ System.out.println("Server Starting up"); try { Registry registry = LocateRegistry.getRegistry(); registry.bind("Operations",new Operations()); } catch (RemoteException e) { e.printStackTrace(); } catch (AlreadyBoundException e) { e.printStackTrace(); } } }
package com.swethasantosh.countriescapitals; import android.content.Intent; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.widget.DrawerLayout; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.FrameLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; public class MainActivity2 extends Navigation_main { private DrawerLayout drawerlayout; RadioGroup r; TextView textmsg; private ActionBarDrawerToggle drawerlistener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FrameLayout contentFrameLayout = (FrameLayout) findViewById(R.id.framelayout); //Remember this is the FrameLayout area within your activity_main.xml getLayoutInflater().inflate(R.layout.activity_main_activity2, contentFrameLayout); /* drawerlayout = (DrawerLayout)findViewById(R.id.drawerlayout); drawerlistener = new ActionBarDrawerToggle(this, drawerlayout, R.drawable.ic_drawer,R.string.drawer_open,R.string.drawer_close); drawerlayout.setDrawerListener(drawerlistener);*/ //setContentView(R.layout.activity_main_activity2); //textmsg = (TextView)findViewById(R.id.textmsg); } public void onRadioButtonClicked(View v) { boolean checked = ((RadioButton)v).isChecked(); switch (v.getId()) { case R.id.radioButton: if(checked) { Intent intent1 = new Intent(getApplicationContext(),Africa.class); startActivity(intent1); break; } case R.id.radioButton2: if(checked) { Intent intent2 = new Intent(getApplicationContext(),Asiamainactivity.class); startActivity(intent2); break; } case R.id.radioButton3: if(checked) { Intent intent3 = new Intent(getApplicationContext(),EuropeMainActivity.class); startActivity(intent3); break; } case R.id.radioButton4: if(checked) { Intent intent4 = new Intent(getApplicationContext(),NorthAmericaMainActivity.class); startActivity(intent4); break; } case R.id.radioButton5: if(checked) { Intent intent5 = new Intent(getApplicationContext(), SouthAmerica.class); startActivity(intent5); break; } case R.id.radioButton6: if(checked) { Intent intent6 = new Intent(getApplicationContext(), AusraliaMainActivity.class); startActivity(intent6); break; } case R.id.radioButton7: if(checked) { Intent intent7 = new Intent(getApplicationContext(),Allcountriesadapter.class); startActivity(intent7); break; } case R.id.radioButton8: if(checked) { Intent intent8 = new Intent(getApplicationContext(), Imagequiz.class); startActivity(intent8); break; } case R.id.radioButton9: if(checked) { Intent intent9 = new Intent(getApplicationContext(), ContinentwiseQuiz.class); startActivity(intent9); break; } case R.id.radioButton10: if(checked) { Intent intent10 = new Intent(getApplicationContext(), Antarctica.class); startActivity(intent10); break; } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main_activity2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package com.git.cloud.resmgt.common.model; public enum DeviceStatusEnum { DEVICE_STATUS_BUILDING("BUILDING"), // 构建中 DEVICE_STATUS_CHANGING("CHANGING"), // 扩容中 DEVICE_STATUS_RECYCLEING("RECYCLEING"), // 回收中 DEVICE_STATUS_ONLINE("ONLINE"), // 已上线 DEVICE_STATUS_OFFLINE("OFFLINE") // 已下线 ; private final String value; private DeviceStatusEnum(String value) { this.value = value; } public String getValue() { return value; } public static DeviceStatusEnum fromString(String value) { if (value != null) { for (DeviceStatusEnum c : DeviceStatusEnum.values()) { if (value.equalsIgnoreCase(c.value)) { return c; } } } return null; } }
package com.pmm.sdgc.model; import javax.persistence.Embeddable; import java.io.Serializable; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; /** * * @author acg */ @Embeddable public class UserTemplateAcessoPk implements Serializable{ @ManyToOne @JoinColumn(name = "idusermenu", referencedColumnName = "id") @NotFound(action = NotFoundAction.IGNORE) private UserMenu userMenu; @ManyToOne @JoinColumn(name = "idusertemplate", referencedColumnName = "id") @NotFound(action = NotFoundAction.IGNORE) private UserTemplate userTemplate; public UserMenu getUserMenu() { return userMenu; } public void setUserMenu(UserMenu userMenu) { this.userMenu = userMenu; } public UserTemplate getUserTemplate() { return userTemplate; } public void setUserTemplate(UserTemplate userTemplate) { this.userTemplate = userTemplate; } }
package com.semanticsquare.thrillio.entities; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import com.semanticsquare.thrillio.constants.BookGenre; import com.semanticsquare.thrillio.managers.BookmarkManager; public class BookTest { @Test public void testIsKidFriendlyEligible() { // Test 1 Book book = BookmarkManager.getInstance().createBook(4000, "Walden", 1854, "Wilder Publications", new String[] {"Henry David Thoreau"}, BookGenre.PHILOSOPHY,4.3); boolean isKidFriendlyEligible = book.isKidFriendlyEligible(); assertFalse(isKidFriendlyEligible,"For Philisophy Genre - isKidFriendlyEligible should return false"); // Test 2 book = BookmarkManager.getInstance().createBook(4000, "Walden", 1854, "Wilder Publications", new String[] {"Henry David Thoreau"}, BookGenre.SELF_HELP,4.3); isKidFriendlyEligible = book.isKidFriendlyEligible(); assertFalse(isKidFriendlyEligible,"For Self help Genre - isKidFriendlyEligible should return false"); } }
package bunge; import bunge.cord.network.BinaryStream; import bunge.cord.network.protocol.ConnectionPacket; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; /** * Created by ASUS on 19/02/2018. */ public class Test { public static void main(String[] args){ try { Socket socket = new Socket("localhost", 1111); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); ConnectionPacket pk = new ConnectionPacket(); pk.name = "Teste"; pk.serverId = 10000L; pk.slots = 30; pk.encode(); out.writeByte(pk.pid()); byte[] buffer = pk.getBuffer(); out.writeInt(buffer.length); out.write(buffer); } catch (IOException e) { e.printStackTrace(); } } }
package com.nextLevel.hero.SYSTEM.controller; import java.util.Iterator; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; 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.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.nextLevel.hero.SYSTEM.model.dto.NewMemberDTO; import com.nextLevel.hero.SYSTEM.model.service.SystemManagerService; import com.nextLevel.hero.member.model.dto.UserImpl; import com.nextLevel.hero.mngBasicInformation.model.dto.MngBasicInformationDTO; @Controller @RequestMapping("/systemManager") public class SystemManagerController { private final SystemManagerService systemManagerService; @Autowired private PasswordEncoder passwordEncoder; @Autowired public SystemManagerController(SystemManagerService systemManagerService) { this.systemManagerService = systemManagerService; } @GetMapping("/userList") public ModelAndView userList(ModelAndView mv) { /* 생성된 계정 리스트 */ List<NewMemberDTO> controlClientList = systemManagerService.selectControlClientList(); System.out.println(controlClientList); mv.addObject("clientList",controlClientList); mv.setViewName("systemManager/userList"); return mv; } @GetMapping("/createUser") public ModelAndView createUser( ModelAndView mv) { mv.setViewName("systemManager/createUser"); return mv; } @RequestMapping(value="/memberIdCheck", method=RequestMethod.POST) @ResponseBody public int memberIdCheck(@RequestParam String memberId) { int idCheck = 0; List<String> memberIdList = systemManagerService.selectMemberIdList(); System.out.println(memberIdList); for(String id : memberIdList) { if(id.equals(memberId)) { idCheck ++; } } System.out.println("id check" + idCheck); return idCheck; } @PostMapping("/insertNewMember") public ModelAndView insertNewMember(ModelAndView mv,NewMemberDTO newMemberDTO,RedirectAttributes rttr) { /* 사업자 등록번호 병합 */ newMemberDTO.setCompanyRegistrationNo(newMemberDTO.getCompanyRegistrationNo1()+"-"+newMemberDTO.getCompanyRegistrationNo2()+"-"+newMemberDTO.getCompanyRegistrationNo3()); /* 비밀번호 암호화 */ String encodedPassword = passwordEncoder.encode(newMemberDTO.getMemberPasswordCheck()); /* 암호화된 비밀번호를 저장 */ newMemberDTO.setMemberPasswordCheck(encodedPassword); int result = systemManagerService.insertNewMember(newMemberDTO); if(result > 0) { rttr.addFlashAttribute("successMessage", "계정 생성에 성공하였습니다!"); }else { rttr.addFlashAttribute("failedMessage", "계정 생성에 실패하였습니다!"); } mv.setViewName("redirect:/systemManager/createUser"); return mv; } }
package be.odisee.se4.hetnest.domain; import lombok.AccessLevel; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Entity @Table(name = "BROUWSELS") @Data @RequiredArgsConstructor @NoArgsConstructor(access= AccessLevel.PRIVATE,force=true) public class Brouwsel { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private final long id; @OneToMany private Set<BrouwLogSnapshot> BrouwLogSnapshots = new HashSet<BrouwLogSnapshot>(); @OneToMany private Set<BrouwselIngredient> BrouwselIngredienten = new HashSet<BrouwselIngredient>(); private int status; @ManyToOne private Recept m_Recept; }