text
stringlengths
10
2.72M
package com.tencent.mm.plugin.fav.a; public enum m$b { Sight(1), AdUrl(2), Chat(3), TalkChat(4), Fav(5); public int value; private m$b(int i) { this.value = 0; this.value = i; } }
/*package cn.ssh.fast; //import org.csource.fastdfs.ClientGlobal; //import org.csource.fastdfs.StorageClient; //import org.csource.fastdfs.StorageServer; //import org.csource.fastdfs.TrackerClient; //import org.csource.fastdfs.TrackerServer; import org.junit.Test; import cn.ssh.common.utils.FastDFSClient; public class FastDfsTest { */ //@Test // public void testUpload() throws Exception { // //创建一个配置文件。文件名任意。内容就是tracker服务器的地址。 // //使用全局对象加载配置文件。 // ClientGlobal.init("D:/eclipse works/ssh-manager-web/src/main/resources/conf/client.conf"); //// ClientGlobal.init("D:/eclipse works/ssh-manager-web/src/main/resources/conf/client.conf"); // //创建一个TrackerClient对象 // TrackerClient trackerClient = new TrackerClient(); // //通过TrackClient获得一个TrackerServer对象 // TrackerServer trackerServer = trackerClient.getConnection(); // //创建一个StrorageServer的引用,可以是null // StorageServer storageServer = null; // //创建一个StorageClient,参数需要TrackerServer和StrorageServer // StorageClient storageClient = new StorageClient(trackerServer, storageServer); // //使用StorageClient上传文件。 // String[] strings=storageClient.upload_file("D:/phototest/me.jpg","jpg",null); // // for (String string : strings) { // System.out.println(string); // } // // } /* @Test public void testFastDfsClient() throws Exception { FastDFSClient fastDFSClient = new FastDFSClient("D:/eclipse works/ssh-manager-web/src/main/resources/conf/client.conf"); String string = fastDFSClient.uploadFile("D:/phototest/me.jpg"); System.out.println(string); }*/ //}
package com.junior.stouring.tabsswipefragments; import com.junior.stouring.R; import com.junior.stouring.TouringPlace; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class OffersFragment extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_offers, container, false); TouringPlace tP = getArguments().getParcelable("TP"); TextView displayPlaceInfo = (TextView) view.findViewById(R.id.tpname); displayPlaceInfo.setText("Les offres de " + tP.getName() + " seront ajoutées ici"); return view; } }
package com.example.myapplication; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ListView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RequestQueue queue = Volley.newRequestQueue(this); // JsonArrayRequest JsonArrayRequest=new JsonArrayRequest(Request.Method.GET, "http://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=26bcf9bd9a644b13b53beef835bb6418", null, new Listener < JSONArray >() { // @Override // public void onResponse(JSONArray response) { // TextView textView=(TextView) findViewById(R.id.text); // textView.setText(response.toString()); // } // } // , new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // Toast.makeText(MainActivity.this,"fucking wrong", LENGTH_SHORT).show(); // } // }); // // queue.add(JsonArrayRequest); final ArrayList<objectes> arrayList=new ArrayList <>(); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,"https://reqres.in/api/users?page=2", null, new Response.Listener < JSONObject >() { @Override public void onResponse(JSONObject response) { JSONArray jsonArray = null; try { jsonArray = response.getJSONArray("data"); Log.d("neeraj","response is:" + jsonArray.toString()); for (int i=0;i<jsonArray.length();i++) { JSONObject currentobject=jsonArray.getJSONObject(i); int ids=currentobject.getInt("id"); String emails=currentobject.getString("email"); String firsts=currentobject.getString("first_name"); String lasts=currentobject.getString("last_name"); String avatars=currentobject.getString("avatar"); objectes ne=new objectes(ids,emails,firsts,lasts,avatars); arrayList.add(ne); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(MainActivity.this, "this is fucking wrong", Toast.LENGTH_SHORT).show(); } }); queue.add(jsonObjectRequest); adapter<objectes> arrayAdapter=new adapter<objectes>(MainActivity.this,arrayList); final ListView list=(ListView) findViewById(R.id.listview); list.setAdapter(arrayAdapter); } }
package com.rekoe.msg; import com.rekoe.model.gameobjects.client.Client; import com.rekoe.msg.cs.CSLoginMessage; /** * @author 科技㊣²º¹³ * Feb 16, 2013 2:35:33 PM * http://www.rekoe.com * QQ:5382211 */ public class SCMessageRecognizer implements IMessageRecognizer<Integer> { @Override public BaseIoMessage<Client> createMessage(Integer type) { switch(type) { case MessageType.CS_LOGIN:{ return new CSLoginMessage(); } } return null; } }
package hirondelle.web4j.security; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.*; import hirondelle.web4j.util.Util; import hirondelle.web4j.model.ModelUtil; import hirondelle.web4j.util.EscapeChars; import hirondelle.web4j.util.Consts; import hirondelle.web4j.BuildImpl; import hirondelle.web4j.TESTAll; import java.util.logging.Logger; /** Models free-form text entered by the user, and protects your application from <a href='http://www.owasp.org/index.php/Cross_Site_Scripting'>Cross Site Scripting</a> (XSS). <P>Free-form text refers to text entered by the end user. It differs from other data in that its content is not tightly constrained. Examples of free-form text might include a user name, a description of something, a comment, and so on. If you model free-form text as a simple <tt>String</tt>, then when presenting that text in a web page, you must take special precautions against Cross Site Scripting attacks, by escaping special characters. When modeling such data as <tt>SafeText</tt>, however, such special steps are not needed, since the escaping is built directly into its {@link #toString} method. <P>It is worth noting that there are two defects with JSTL' s handling of this problem : <ul> <li>the {@code <c:out>} tag <em>escapes only 5 of the 12 special characters</em> identified by the Open Web App Security Project as being a concern. <li>used in a JSP, the Expression Language allows pleasingly concise presentation, but <em>does not escape special characters in any way</em>. Even when one is aware of this, it is easy to forget to take precautions against Cross Site Scripting attacks. </ul> <P>Using <tt>SafeText</tt> will protect you from both of these defects. Since the correct escaping is built into {@link #toString}, you may freely use JSP Expression Language, without needing to do any escaping in the view. Note that if you use {@code <c:out>} with <tt>SafeText</tt> (not recommeded), then you must use <tt>escapeXml='false'</tt> to avoid double-escaping of special characters. <P>There are various ways of presenting text : <ul> <li>as HTML (most common) - use {@link #toString()} to escape a large number of special characters. <li>as XML - use {@link #getXmlSafe()} to escape 5 special characters. <li>as JavaScript Object Notation (JSON) - use {@link #getJsonSafe()} to escape a number of special characters <li>as plain text - use {@link #getRawString()} to do no escaping at all. </ul> <h4>Checking For Vulnerabilities Upon Startup</h4> WEB4J will perform checks for Cross-Site Scripting vulnerabilities upon startup, by scanning your application's classes for <tt>public</tt> Model Objects having <tt>public getXXX</tt> methods that return a <tt>String</tt>. It will log such occurrences to encourage you to investigate them further. <P><em>Design Notes :</em><br> This class is <tt>final</tt>, immutable, {@link Serializable}, and {@link Comparable}, in imitation of the other building block classes such as {@link String}, {@link Integer}, and so on. <P>The reason why protection against Cross-Site Scripting is not implemented as a Servlet Filter is because a filter would have no means of distinguishing between safe and unsafe markup. <P>One might object to escaping special characters in the Model, instead of in the View. However, from a practical point of view, it seems more likely that the programmer will remember to use <tt>SafeText</tt> once in the Model, than remember to do the escaping repeatedly in the View. */ public final class SafeText implements Serializable, Comparable<SafeText> { /** Returns <tt>true</tt> only if the given character is always escaped by {@link #toString()}. For the list of characters, see {@link EscapeChars#forHTML(String)}. <P>Recommended that your implementation of {@link PermittedCharacters} use this method. This will allow you to accept many special characters in your list of permissible characters. */ public static boolean isEscaped(int aCodePoint){ return ESCAPED_CODE_POINTS.contains(aCodePoint); } /** Constructor. @param aText free-form text input by the end user, which may contain Cross Site Scripting attacks. Non-null. The text is trimmed by this constructor. */ public SafeText(String aText) { fText = Util.trimPossiblyNull(aText); validateState(); } /** Factory method. Simply a slightly more compact way of building an object, as opposed to 'new'. */ public static SafeText from(String aText){ return new SafeText(aText); } /** Return the text in a form safe for an HTML document. Passes the raw text through {@link EscapeChars#forHTML(String)}. */ @Override public String toString(){ if( ! Util.textHasContent(fEscapedForHTML) ){ fEscapedForHTML = EscapeChars.forHTML(fText); } return fEscapedForHTML; } /** Return the (trimmed) text passed to the constructor. */ public String getRawString(){ return fText; } /** Return the text in a form safe for an XML element. <P>Arbitrary text can be rendered safely in an XML document in two ways : <ul> <li>using a <tt>CDATA</tt> block <li>escaping special characters {@code &, <, >, ", '}. </ul> <P>This method will escape the above five special characters, and replace them with character entities, using {@link EscapeChars#forXML(String)} */ public String getXmlSafe(){ return EscapeChars.forXML(fText); } /** Return the text in a form safe for <a href='http://www.json.org/'>JSON</a> (JavaScript Object Notation) data. <P>This method is intended for the <i>data</i> elements of JSON. It is intended for <i>values</i> of things, not for their <i>names</i>. Typically, only the values will come from end user input, while the names will be hard-coded. */ public String getJsonSafe(){ return EscapeChars.forJSON(fText); } @Override public boolean equals(Object aThat){ Boolean result = ModelUtil.quickEquals(this, aThat); if ( result == null ){ SafeText that = (SafeText)aThat; result = ModelUtil.equalsFor(this.getSignificantFields(), that.getSignificantFields()); } return result; } @Override public int hashCode(){ if ( fHashCode == 0){ fHashCode = ModelUtil.hashCodeFor(getSignificantFields()); } return fHashCode; } public int compareTo(SafeText aThat){ final int EQUAL = 0; if ( this == aThat ) return EQUAL; int comparison = this.fText.compareTo(aThat.fText); if ( comparison != EQUAL ) return comparison; return EQUAL; } // PRIVATE // /** @serial */ private final String fText; /** The return value of toString, cached like fHashCode. */ private String fEscapedForHTML; private int fHashCode; private static final Logger fLogger = Util.getLogger(SafeText.class); private Object[] getSignificantFields(){ return new Object[] {fText}; } /** During deserialization, this method cannot be called, since the implementation of PermittedChars is null. */ private void validateState() { if (fText == null){ throw new NullPointerException("Free form text cannot be null."); } String badCharacters = findBadCharacters(fText); if( Util.textHasContent(badCharacters) ) { throw new IllegalArgumentException("Unpermitted character(s) in text: " + Util.quote(badCharacters) ); } } private String findBadCharacters(String aArbitraryText){ String result = Consts.EMPTY_STRING; //default StringBuilder badCharacters = new StringBuilder(); PermittedCharacters whitelist = getPermittedChars(); int idx = 0; int length = aArbitraryText.length(); while ( idx < length ) { int codePoint = aArbitraryText.codePointAt(idx); if( ! whitelist.isPermitted(codePoint) ) { fLogger.severe("Bad Code Point : " + codePoint); char[] badChar = Character.toChars(codePoint); badCharacters.append(String.valueOf(badChar)); } idx = idx + Character.charCount(codePoint); } if( Util.textHasContent(badCharacters.toString()) ) { result = badCharacters.toString(); fLogger.severe("Bad Characters found in request, disallowed by PermittedCharacters implementation: " + result); } return result; } private PermittedCharacters getPermittedChars(){ return BuildImpl.forPermittedCharacters(); } /** For evolution of this class, see Sun guidelines : http://java.sun.com/j2se/1.5.0/docs/guide/serialization/spec/version.html#6678 */ private static final long serialVersionUID = 7526472295633676147L; /** Always treat de-serialization as a full-blown constructor, by validating the final state of the de-serialized object. */ private void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException, IOException { aInputStream.defaultReadObject(); //partial validation only, without looking for 'bad' characters (BuildImpl not available): if (fText == null){ throw new NullPointerException("Free form text cannot be null."); } } /** This is the default implementation of writeObject. Customise if necessary. */ private void writeObject(ObjectOutputStream aOutputStream) throws IOException { aOutputStream.defaultWriteObject(); } /** List of characters that this class will always escape. */ private static List<Character> ESCAPED = Arrays.asList( '<', '>' , '&' , '"' , '\t' , '!' , '#' , '$' , '%' , '\'' , '(' , ')' , '*' , '+' , ',' , '-' , '.' , '/' , ':' , ';' , '=' , '?' , '@' , '[' , '\\' , ']' , '^' , '_' , '`' , '{' , '|' , '}' , '~' ); /** As above, but translated into a form that uses code points. */ private static List<Integer> ESCAPED_CODE_POINTS = new ArrayList<Integer>(); static { for (Character character : ESCAPED){ ESCAPED_CODE_POINTS.add(Character.toString(character).codePointAt(0)); } } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.acceleratorfacades.cmsitems.attributeconverters; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.when; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.cmsfacades.data.MediaData; import de.hybris.platform.core.model.media.MediaContainerModel; import de.hybris.platform.core.model.media.MediaFormatModel; import de.hybris.platform.core.model.media.MediaModel; import de.hybris.platform.servicelayer.dto.converter.Converter; import java.util.Arrays; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @UnitTest @RunWith(MockitoJUnitRunner.class) public class MediaContainerAttributeToDataRenderingContentConverterTest { private static final String MEDIA_CODE = "media-code"; private static final String MEDIA_FORMAT = "media-format"; @InjectMocks private MediaContainerAttributeToDataRenderingContentConverter converter; @Mock private Converter<MediaModel, MediaData> mediaModelConverter; @Mock private MediaContainerModel source; @Mock private MediaModel media; @Mock private MediaFormatModel mediaFormat; @Before public void setup() { when(media.getCode()).thenReturn(MEDIA_CODE); when(media.getMediaFormat()).thenReturn(mediaFormat); when(source.getMedias()).thenReturn(Arrays.asList(media)); when(mediaFormat.getQualifier()).thenReturn(MEDIA_FORMAT); } @Test public void whenConvertNullValueReturnsNull() { final Map<String, MediaData> map = converter.convert(null); assertThat(map, nullValue()); } @Test public void whenConvertingValidContainerModelShouldReturnValidMap() { final MediaData mediaData = new MediaData(); mediaData.setCode(MEDIA_CODE); when(mediaModelConverter.convert(media)).thenReturn(mediaData); final Map<String, MediaData> map = converter.convert(source); assertThat(map.keySet(), not(empty())); assertThat(map.keySet(), hasItem(MEDIA_FORMAT)); assertThat(map.get(MEDIA_FORMAT), is(mediaData)); } }
package com.github.frostyaxe.cucumber.stepdefs; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import com.github.frostyaxe.cucumber.controllers.BaseController; import com.github.frostyaxe.cucumber.dataclasses.FlightSearchDataClass; import com.github.frostyaxe.cucumber.pages.ExpediaSearch; import com.github.frostyaxe.cucumber.pages.ExpediaSearch.FlightSearch; import com.github.frostyaxe.cucumber.pojos.FlightSearchPojo; import io.cucumber.datatable.DataTable; import io.cucumber.java8.En; public class ExpediaFlightSearchStepDefs implements En { BaseController controller = null; public ExpediaFlightSearchStepDefs(BaseController controller) { this.controller = controller; ExpediaSearch expediaSearchPageObj = new ExpediaSearch(controller); FlightSearch flightSearch = expediaSearchPageObj.getFlightSearchObj(); /** * <b>Description:</b> This method opens the Expedia Homepage in the browser. * * @author Abhishek Prajapati * @Email prajapatiabhishek1996@gmail.com */ Given("User is on Expedia Homepage", () -> { controller.getDriver().get("https://www.expedia.co.in/"); // Opens URL in the web browser. controller.getDriver().manage().window().maximize(); // Maximizes the web browser window. controller.getDriver().manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); }); /** * <b>Description:</b> This method verifies whether user is landed on the homepage or not. * * @author Abhishek Prajapati * @email prajapatiabhishek1996@gmail.com */ Given("User is able to see the Expedia HomePage", () -> { String pageTitle = controller.getDriver().getTitle(); String pageUrl = controller.getDriver().getCurrentUrl(); String expectedTitle = "Expedia Travel: Vacations, Cheap Flights, Airline Tickets & Airfares"; String expectedUrl = "https://www.expedia.co.in/"; Assert.assertEquals(pageTitle, expectedTitle); Assert.assertEquals(pageUrl, expectedUrl); } ); When("User clicks on the Flights tab button", () -> { new WebDriverWait(controller.getDriver(), 10).until(ExpectedConditions.visibilityOf(flightSearch.getFlightTabButton())); flightSearch.getFlightTabButton().click(); }); And("Enters the required details in the form fields", (DataTable table) -> { List<Map<String, String>> flightSearchFormData = table.transpose().asMaps(String.class, String.class); flightSearchFormData.forEach( dataMap -> { List<WebElement> elements = new ArrayList<>(); FlightSearchDataClass dataClass = new FlightSearchDataClass(dataMap.get("flightData")); FlightSearchPojo flightData = dataClass.getPojo(); new WebDriverWait(controller.getDriver(), 10).until(ExpectedConditions.visibilityOf(flightSearch.getFlyingFromTextField())); flightSearch.getFlyingFromTextField().sendKeys(flightData.getFrom()); elements.add(flightSearch.getFlyingFromTextField()); flightSearch.getFlyingToTextField().sendKeys(flightData.getTo()); elements.add(flightSearch.getFlyingToTextField()); flightSearch.getDepartingTextField().sendKeys(flightData.getDeparture()); elements.add(flightSearch.getDepartingTextField()); flightSearch.getReturningTextField().sendKeys(flightData.getReturning()); elements.add(flightSearch.getReturningTextField()); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } elements.forEach( element -> {element.clear();} ); } ); } ); Then("User verifies the outcome", () -> { System.out.println("User verfifies the outcomess"); }); } }
package com.tencent.mm.plugin.nearby.ui; import android.content.Intent; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import com.tencent.mm.model.au; import com.tencent.mm.model.bl; import com.tencent.mm.model.c; import com.tencent.mm.plugin.messenger.foundation.a.a.h.a; import com.tencent.mm.sdk.platformtools.bi; class NearbyPersonalInfoUI$2 implements OnMenuItemClickListener { final /* synthetic */ NearbyPersonalInfoUI lCt; NearbyPersonalInfoUI$2(NearbyPersonalInfoUI nearbyPersonalInfoUI) { this.lCt = nearbyPersonalInfoUI; } public final boolean onMenuItemClick(MenuItem menuItem) { bl IC; if (NearbyPersonalInfoUI.a(this.lCt) != -1) { IC = bl.IC(); IC.sex = NearbyPersonalInfoUI.a(this.lCt); bl.a(IC); } IC = bl.ID(); if (IC == null) { NearbyPersonalInfoUI.b(this.lCt); } else { String oV = bi.oV(IC.getProvince()); bi.oV(IC.getCity()); int i = IC.sex; if (bi.oW(oV) || i == 0) { NearbyPersonalInfoUI.b(this.lCt); } else { this.lCt.startActivity(new Intent(this.lCt, NearbyFriendsUI.class)); bl IC2 = bl.IC(); if (i != -1) { IC2.sex = i; } au.HU(); c.FQ().b(new a(1, bl.a(IC2))); this.lCt.finish(); } } return true; } }
package com.kevin.spring5.tutorial.samples.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; /** * 首页 * @author: wangyong * @date: 2019/11/24 0:08 */ @RestController @Slf4j public class IndexController { @GetMapping("/") public Mono<String> index(ServerHttpRequest request, ServerHttpResponse response) { return Mono.just("hello,spring webflux..."); } }
/** * Helios, OpenSource Monitoring * Brought to you by the Helios Development Group * * Copyright 2007, Helios Development Group and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package com.heliosapm.script.compilers.groovy; import groovy.lang.GroovyClassLoader; import javax.script.ScriptContext; import javax.script.ScriptEngine; import org.codehaus.groovy.jsr223.GroovyScriptEngineFactory; import com.heliosapm.jmx.config.Configuration; /** * <p>Title: ConfigurableGroovyScriptEngineFactory</p> * <p>Description: An extension of the jsr223 Groovy ScriptEngineFactory that supports configuring the compiler options</p> * <p>Company: Helios Development Group LLC</p> * @author Whitehead (nwhitehead AT heliosdev DOT org) * <p><code>com.heliosapm.script.compilers.groovy.ConfigurableGroovyScriptEngineFactory</code></p> */ public class ConfigurableGroovyScriptEngineFactory extends GroovyScriptEngineFactory { /** The customized groovy class loader */ protected final GroovyClassLoader groovyClassLoader; /** The customizable compilation */ protected final GroovyCompilationCustomizer compilationCustomizer = new GroovyCompilationCustomizer(); /** * Creates a new ConfigurableGroovyScriptEngineFactory */ public ConfigurableGroovyScriptEngineFactory() { groovyClassLoader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader(), compilationCustomizer.getDefaultConfig(), true); } /** * {@inheritDoc} * @see org.codehaus.groovy.jsr223.GroovyScriptEngineFactory#getEngineName() */ @Override public String getEngineName() { return "Configurable " + super.getEngineName(); } /** * {@inheritDoc} * @see org.codehaus.groovy.jsr223.GroovyScriptEngineFactory#getScriptEngine() */ @Override public ScriptEngine getScriptEngine() { final ScriptEngine se = new ConfigurableGroovyScriptEngineImpl(groovyClassLoader); Configuration cfg = new Configuration(); se.setBindings(cfg, ScriptContext.ENGINE_SCOPE); return se; } }
/** * © Copyright IBM Corporation 2015 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.ibm.watson.developer_cloud.android.speech_to_text.v1.opus; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.NativeLibrary; import com.sun.jna.Pointer; import com.sun.jna.PointerType; import com.sun.jna.ptr.FloatByReference; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.PointerByReference; import com.sun.jna.ptr.ShortByReference; /** * JNA Wrapper for library <b>opus</b><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public interface JNAOpus extends Library { public static final String JNA_LIBRARY_NAME = "opus"; public static final NativeLibrary JNA_NATIVE_LIB = NativeLibrary.getInstance(JNAOpus.JNA_LIBRARY_NAME); public static final JNAOpus INSTANCE = (JNAOpus)Native.loadLibrary(JNAOpus.JNA_LIBRARY_NAME, JNAOpus.class); // ****** Constants /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_LSB_DEPTH_REQUEST = (int)4037; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_APPLICATION_REQUEST = (int)4001; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_FORCE_CHANNELS_REQUEST = (int)4023; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_VBR_REQUEST = (int)4007; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_BANDWIDTH_REQUEST = (int)4009; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_BITRATE_REQUEST = (int)4002; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_BANDWIDTH_REQUEST = (int)4008; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SIGNAL_MUSIC = (int)3002; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_RESET_STATE = (int)4028; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_FRAMESIZE_2_5_MS = (int)5001; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_COMPLEXITY_REQUEST = (int)4011; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_FRAMESIZE_40_MS = (int)5005; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_PACKET_LOSS_PERC_REQUEST = (int)4014; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_VBR_CONSTRAINT_REQUEST = (int)4021; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_INBAND_FEC_REQUEST = (int)4012; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_APPLICATION_RESTRICTED_LOWDELAY = (int)2051; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_BANDWIDTH_FULLBAND = (int)1105; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_VBR_REQUEST = (int)4006; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_BANDWIDTH_SUPERWIDEBAND = (int)1104; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_FORCE_CHANNELS_REQUEST = (int)4022; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_APPLICATION_VOIP = (int)2048; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SIGNAL_VOICE = (int)3001; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_FINAL_RANGE_REQUEST = (int)4031; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_BUFFER_TOO_SMALL = (int)-2; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_COMPLEXITY_REQUEST = (int)4010; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_FRAMESIZE_ARG = (int)5000; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_LOOKAHEAD_REQUEST = (int)4027; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_INBAND_FEC_REQUEST = (int)4013; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_BITRATE_MAX = (int)-1; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_FRAMESIZE_5_MS = (int)5002; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_BAD_ARG = (int)-1; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_PITCH_REQUEST = (int)4033; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_SIGNAL_REQUEST = (int)4024; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_FRAMESIZE_20_MS = (int)5004; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_APPLICATION_AUDIO = (int)2049; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_DTX_REQUEST = (int)4017; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_FRAMESIZE_10_MS = (int)5003; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_LSB_DEPTH_REQUEST = (int)4036; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_UNIMPLEMENTED = (int)-5; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_PACKET_LOSS_PERC_REQUEST = (int)4015; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_INVALID_STATE = (int)-6; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_EXPERT_FRAME_DURATION_REQUEST = (int)4040; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_FRAMESIZE_60_MS = (int)5006; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_BITRATE_REQUEST = (int)4003; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_INTERNAL_ERROR = (int)-3; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_MAX_BANDWIDTH_REQUEST = (int)4004; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_VBR_CONSTRAINT_REQUEST = (int)4020; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_MAX_BANDWIDTH_REQUEST = (int)4005; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_BANDWIDTH_NARROWBAND = (int)1101; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_GAIN_REQUEST = (int)4034; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_PREDICTION_DISABLED_REQUEST = (int)4042; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_APPLICATION_REQUEST = (int)4000; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_SET_DTX_REQUEST = (int)4016; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_BANDWIDTH_MEDIUMBAND = (int)1102; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_SAMPLE_RATE_REQUEST = (int)4029; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_EXPERT_FRAME_DURATION_REQUEST = (int)4041; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_AUTO = (int)-1000; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_SIGNAL_REQUEST = (int)4025; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_LAST_PACKET_DURATION_REQUEST = (int)4039; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_PREDICTION_DISABLED_REQUEST = (int)4043; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_GET_GAIN_REQUEST = (int)4045; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_BANDWIDTH_WIDEBAND = (int)1103; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_INVALID_PACKET = (int)-4; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_ALLOC_FAIL = (int)-7; /** <i>native declaration : /tmp/opus_defines.h</i> */ public static final int OPUS_OK = (int)0; /** <i>native declaration : /tmp/opus_multistream.h</i> */ public static final int OPUS_MULTISTREAM_GET_DECODER_STATE_REQUEST = (int)5122; /** <i>native declaration : /tmp/opus_multistream.h</i> */ public static final int OPUS_MULTISTREAM_GET_ENCODER_STATE_REQUEST = (int)5120; /** * Gets the size of an <code>OpusEncoder</code> structure.<br> * @param[in] channels <tt>int</tt>: Number of channels.<br> * This must be 1 or 2.<br> * @returns The size in bytes.<br> * Original signature : <code>int opus_encoder_get_size(int)</code><br> * <i>native declaration : /tmp/opus.h:134</i> */ int opus_encoder_get_size(int channels); /** * Allocates and initializes an encoder state.<br> * There are three coding modes:<br> * * @ref OPUS_APPLICATION_VOIP gives best quality at a given bitrate for voice<br> * signals. It enhances the input signal by high-pass filtering and<br> * emphasizing formants and harmonics. Optionally it includes in-band<br> * forward error correction to protect against packet loss. Use this<br> * mode for typical VoIP applications. Because of the enhancement,<br> * even at high bitrates the output may sound different from the input.<br> * * @ref OPUS_APPLICATION_AUDIO gives best quality at a given bitrate for most<br> * non-voice signals like music. Use this mode for music and mixed<br> * (music/voice) content, broadcast, and applications requiring less<br> * than 15 ms of coding delay.<br> * * @ref OPUS_APPLICATION_RESTRICTED_LOWDELAY configures low-delay mode that<br> * disables the speech-optimized mode in exchange for slightly reduced delay.<br> * This mode can only be set on an newly initialized or freshly reset encoder<br> * because it changes the codec delay.<br> * * This is useful when the caller knows that the speech-optimized modes will not be needed (use with caution).<br> * @param [in] Fs <tt>opus_int32</tt>: Sampling rate of input signal (Hz)<br> * This must be one of 8000, 12000, 16000,<br> * 24000, or 48000.<br> * @param [in] channels <tt>int</tt>: Number of channels (1 or 2) in input signal<br> * @param [in] application <tt>int</tt>: Coding mode (@ref OPUS_APPLICATION_VOIP/@ref OPUS_APPLICATION_AUDIO/@ref OPUS_APPLICATION_RESTRICTED_LOWDELAY)<br> * @param [out] error <tt>int*</tt>: @ref opus_errorcodes<br> * @note Regardless of the sampling rate and number channels selected, the Opus encoder<br> * can switch to a lower audio bandwidth or number of channels if the bitrate<br> * selected is too low. This also means that it is safe to always use 48 kHz stereo input<br> * and let the encoder optimize the encoding.<br> * Original signature : <code>OpusEncoder* opus_encoder_create(opus_int32, int, int, int*)</code><br> * <i>native declaration : /tmp/opus.h:171</i> */ PointerByReference opus_encoder_create(int Fs, int channels, int application, IntBuffer error); /** * Initializes a previously allocated encoder state<br> * The memory pointed to by st must be at least the size returned by opus_encoder_get_size().<br> * This is intended for applications which use their own allocator instead of malloc.<br> * @see opus_encoder_create(),opus_encoder_get_size()<br> * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL.<br> * @param [in] st <tt>OpusEncoder*</tt>: Encoder state<br> * @param [in] Fs <tt>opus_int32</tt>: Sampling rate of input signal (Hz)<br> * This must be one of 8000, 12000, 16000,<br> * 24000, or 48000.<br> * @param [in] channels <tt>int</tt>: Number of channels (1 or 2) in input signal<br> * @param [in] application <tt>int</tt>: Coding mode (OPUS_APPLICATION_VOIP/OPUS_APPLICATION_AUDIO/OPUS_APPLICATION_RESTRICTED_LOWDELAY)<br> * @retval #OPUS_OK Success or @ref opus_errorcodes<br> * Original signature : <code>int opus_encoder_init(OpusEncoder*, opus_int32, int, int)</code><br> * <i>native declaration : /tmp/opus.h:191</i> */ int opus_encoder_init(PointerByReference st, int Fs, int channels, int application); /** * Encodes an Opus frame.<br> * @param [in] st <tt>OpusEncoder*</tt>: Encoder state<br> * @param [in] pcm <tt>opus_int16*</tt>: Input signal (interleaved if 2 channels). length is frame_size*channels*sizeof(opus_int16)<br> * @param [in] frame_size <tt>int</tt>: Number of samples per channel in the<br> * input signal.<br> * This must be an Opus frame size for<br> * the encoder's sampling rate.<br> * For example, at 48 kHz the permitted<br> * values are 120, 240, 480, 960, 1920,<br> * and 2880.<br> * Passing in a duration of less than<br> * 10 ms (480 samples at 48 kHz) will<br> * prevent the encoder from using the LPC<br> * or hybrid modes.<br> * @param [out] data <tt>unsigned char*</tt>: Output payload.<br> * This must contain storage for at<br> * least \a max_data_bytes.<br> * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated<br> * memory for the output<br> * payload. This may be<br> * used to impose an upper limit on<br> * the instant bitrate, but should<br> * not be used as the only bitrate<br> * control. Use #OPUS_SET_BITRATE to<br> * control the bitrate.<br> * @returns The length of the encoded packet (in bytes) on success or a<br> * negative error code (see @ref opus_errorcodes) on failure.<br> * Original signature : <code>opus_int32 opus_encode(OpusEncoder*, const opus_int16*, int, unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:226</i> */ int opus_encode(PointerByReference st, ShortBuffer pcm, int frame_size, ByteBuffer data, int max_data_bytes); /** * Encodes an Opus frame.<br> * @param [in] st <tt>OpusEncoder*</tt>: Encoder state<br> * @param [in] pcm <tt>opus_int16*</tt>: Input signal (interleaved if 2 channels). length is frame_size*channels*sizeof(opus_int16)<br> * @param [in] frame_size <tt>int</tt>: Number of samples per channel in the<br> * input signal.<br> * This must be an Opus frame size for<br> * the encoder's sampling rate.<br> * For example, at 48 kHz the permitted<br> * values are 120, 240, 480, 960, 1920,<br> * and 2880.<br> * Passing in a duration of less than<br> * 10 ms (480 samples at 48 kHz) will<br> * prevent the encoder from using the LPC<br> * or hybrid modes.<br> * @param [out] data <tt>unsigned char*</tt>: Output payload.<br> * This must contain storage for at<br> * least \a max_data_bytes.<br> * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated<br> * memory for the output<br> * payload. This may be<br> * used to impose an upper limit on<br> * the instant bitrate, but should<br> * not be used as the only bitrate<br> * control. Use #OPUS_SET_BITRATE to<br> * control the bitrate.<br> * @returns The length of the encoded packet (in bytes) on success or a<br> * negative error code (see @ref opus_errorcodes) on failure.<br> * Original signature : <code>opus_int32 opus_encode(OpusEncoder*, const opus_int16*, int, unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:226</i> */ int opus_encode(PointerByReference st, ShortByReference pcm, int frame_size, Pointer data, int max_data_bytes); /** * Encodes an Opus frame from floating point input.<br> * @param [in] st <tt>OpusEncoder*</tt>: Encoder state<br> * @param [in] pcm <tt>float*</tt>: Input in float format (interleaved if 2 channels), with a normal range of +/-1.0.<br> * Samples with a range beyond +/-1.0 are supported but will<br> * be clipped by decoders using the integer API and should<br> * only be used if it is known that the far end supports<br> * extended dynamic range.<br> * length is frame_size*channels*sizeof(float)<br> * @param [in] frame_size <tt>int</tt>: Number of samples per channel in the<br> * input signal.<br> * This must be an Opus frame size for<br> * the encoder's sampling rate.<br> * For example, at 48 kHz the permitted<br> * values are 120, 240, 480, 960, 1920,<br> * and 2880.<br> * Passing in a duration of less than<br> * 10 ms (480 samples at 48 kHz) will<br> * prevent the encoder from using the LPC<br> * or hybrid modes.<br> * @param [out] data <tt>unsigned char*</tt>: Output payload.<br> * This must contain storage for at<br> * least \a max_data_bytes.<br> * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated<br> * memory for the output<br> * payload. This may be<br> * used to impose an upper limit on<br> * the instant bitrate, but should<br> * not be used as the only bitrate<br> * control. Use #OPUS_SET_BITRATE to<br> * control the bitrate.<br> * @returns The length of the encoded packet (in bytes) on success or a<br> * negative error code (see @ref opus_errorcodes) on failure.<br> * Original signature : <code>opus_int32 opus_encode_float(OpusEncoder*, const float*, int, unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:267</i> */ int opus_encode_float(PointerByReference st, float pcm[], int frame_size, ByteBuffer data, int max_data_bytes); /** * Encodes an Opus frame from floating point input.<br> * @param [in] st <tt>OpusEncoder*</tt>: Encoder state<br> * @param [in] pcm <tt>float*</tt>: Input in float format (interleaved if 2 channels), with a normal range of +/-1.0.<br> * Samples with a range beyond +/-1.0 are supported but will<br> * be clipped by decoders using the integer API and should<br> * only be used if it is known that the far end supports<br> * extended dynamic range.<br> * length is frame_size*channels*sizeof(float)<br> * @param [in] frame_size <tt>int</tt>: Number of samples per channel in the<br> * input signal.<br> * This must be an Opus frame size for<br> * the encoder's sampling rate.<br> * For example, at 48 kHz the permitted<br> * values are 120, 240, 480, 960, 1920,<br> * and 2880.<br> * Passing in a duration of less than<br> * 10 ms (480 samples at 48 kHz) will<br> * prevent the encoder from using the LPC<br> * or hybrid modes.<br> * @param [out] data <tt>unsigned char*</tt>: Output payload.<br> * This must contain storage for at<br> * least \a max_data_bytes.<br> * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated<br> * memory for the output<br> * payload. This may be<br> * used to impose an upper limit on<br> * the instant bitrate, but should<br> * not be used as the only bitrate<br> * control. Use #OPUS_SET_BITRATE to<br> * control the bitrate.<br> * @returns The length of the encoded packet (in bytes) on success or a<br> * negative error code (see @ref opus_errorcodes) on failure.<br> * Original signature : <code>opus_int32 opus_encode_float(OpusEncoder*, const float*, int, unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:267</i> */ int opus_encode_float(PointerByReference st, FloatByReference pcm, int frame_size, Pointer data, int max_data_bytes); /** * Frees an <code>OpusEncoder</code> allocated by opus_encoder_create().<br> * @param[in] st <tt>OpusEncoder*</tt>: State to be freed.<br> * Original signature : <code>void opus_encoder_destroy(OpusEncoder*)</code><br> * <i>native declaration : /tmp/opus.h:278</i> */ void opus_encoder_destroy(PointerByReference st); /** * Perform a CTL function on an Opus encoder.<br> * * Generally the request and subsequent arguments are generated<br> * by a convenience macro.<br> * @param st <tt>OpusEncoder*</tt>: Encoder state.<br> * @param request This and all remaining parameters should be replaced by one<br> * of the convenience macros in @ref opus_genericctls or<br> * @ref opus_encoderctls.<br> * @see opus_genericctls<br> * @see opus_encoderctls<br> * Original signature : <code>int opus_encoder_ctl(OpusEncoder*, int, null)</code><br> * <i>native declaration : /tmp/opus.h:291</i> */ int opus_encoder_ctl(PointerByReference st, int request, Object... varargs); /** * Gets the size of an <code>OpusDecoder</code> structure.<br> * @param [in] channels <tt>int</tt>: Number of channels.<br> * This must be 1 or 2.<br> * @returns The size in bytes.<br> * Original signature : <code>int opus_decoder_get_size(int)</code><br> * <i>native declaration : /tmp/opus.h:369</i> */ int opus_decoder_get_size(int channels); /** * Allocates and initializes a decoder state.<br> * @param [in] Fs <tt>opus_int32</tt>: Sample rate to decode at (Hz).<br> * This must be one of 8000, 12000, 16000,<br> * 24000, or 48000.<br> * @param [in] channels <tt>int</tt>: Number of channels (1 or 2) to decode<br> * @param [out] error <tt>int*</tt>: #OPUS_OK Success or @ref opus_errorcodes<br> * * Internally Opus stores data at 48000 Hz, so that should be the default<br> * value for Fs. However, the decoder can efficiently decode to buffers<br> * at 8, 12, 16, and 24 kHz so if for some reason the caller cannot use<br> * data at the full sample rate, or knows the compressed data doesn't<br> * use the full frequency range, it can request decoding at a reduced<br> * rate. Likewise, the decoder is capable of filling in either mono or<br> * interleaved stereo pcm buffers, at the caller's request.<br> * Original signature : <code>OpusDecoder* opus_decoder_create(opus_int32, int, int*)</code><br> * <i>native declaration : /tmp/opus.h:386</i> */ PointerByReference opus_decoder_create(int Fs, int channels, IntBuffer error); /** * Initializes a previously allocated decoder state.<br> * The state must be at least the size returned by opus_decoder_get_size().<br> * This is intended for applications which use their own allocator instead of malloc. @see opus_decoder_create,opus_decoder_get_size<br> * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL.<br> * @param [in] st <tt>OpusDecoder*</tt>: Decoder state.<br> * @param [in] Fs <tt>opus_int32</tt>: Sampling rate to decode to (Hz).<br> * This must be one of 8000, 12000, 16000,<br> * 24000, or 48000.<br> * @param [in] channels <tt>int</tt>: Number of channels (1 or 2) to decode<br> * @retval #OPUS_OK Success or @ref opus_errorcodes<br> * Original signature : <code>int opus_decoder_init(OpusDecoder*, opus_int32, int)</code><br> * <i>native declaration : /tmp/opus.h:403</i> */ int opus_decoder_init(PointerByReference st, int Fs, int channels); /** * Decode an Opus packet.<br> * @param [in] st <tt>OpusDecoder*</tt>: Decoder state<br> * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss<br> * @param [in] len <tt>opus_int32</tt>: Number of bytes in payload*<br> * @param [out] pcm <tt>opus_int16*</tt>: Output signal (interleaved if 2 channels). length<br> * is frame_size*channels*sizeof(opus_int16)<br> * @param [in] frame_size Number of samples per channel of available space in \a pcm.<br> * If this is less than the maximum packet duration (120ms; 5760 for 48kHz), this function will<br> * not be capable of decoding some packets. In the case of PLC (data==NULL) or FEC (decode_fec=1),<br> * then frame_size needs to be exactly the duration of audio that is missing, otherwise the<br> * decoder will not be in the optimal state to decode the next incoming packet. For the PLC and<br> * FEC cases, frame_size <b>must</b> be a multiple of 2.5 ms.<br> * @param [in] decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band forward error correction data be<br> * decoded. If no such data is available, the frame is decoded as if it were lost.<br> * @returns Number of decoded samples or @ref opus_errorcodes<br> * Original signature : <code>int opus_decode(OpusDecoder*, const unsigned char*, opus_int32, opus_int16*, int, int)</code><br> * <i>native declaration : /tmp/opus.h:425</i> */ int opus_decode(PointerByReference st, byte data[], int len, ShortBuffer pcm, int frame_size, int decode_fec); /** * Decode an Opus packet.<br> * @param [in] st <tt>OpusDecoder*</tt>: Decoder state<br> * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss<br> * @param [in] len <tt>opus_int32</tt>: Number of bytes in payload*<br> * @param [out] pcm <tt>opus_int16*</tt>: Output signal (interleaved if 2 channels). length<br> * is frame_size*channels*sizeof(opus_int16)<br> * @param [in] frame_size Number of samples per channel of available space in \a pcm.<br> * If this is less than the maximum packet duration (120ms; 5760 for 48kHz), this function will<br> * not be capable of decoding some packets. In the case of PLC (data==NULL) or FEC (decode_fec=1),<br> * then frame_size needs to be exactly the duration of audio that is missing, otherwise the<br> * decoder will not be in the optimal state to decode the next incoming packet. For the PLC and<br> * FEC cases, frame_size <b>must</b> be a multiple of 2.5 ms.<br> * @param [in] decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band forward error correction data be<br> * decoded. If no such data is available, the frame is decoded as if it were lost.<br> * @returns Number of decoded samples or @ref opus_errorcodes<br> * Original signature : <code>int opus_decode(OpusDecoder*, const unsigned char*, opus_int32, opus_int16*, int, int)</code><br> * <i>native declaration : /tmp/opus.h:425</i> */ int opus_decode(PointerByReference st, Pointer data, int len, ShortByReference pcm, int frame_size, int decode_fec); /** * Decode an Opus packet with floating point output.<br> * @param [in] st <tt>OpusDecoder*</tt>: Decoder state<br> * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss<br> * @param [in] len <tt>opus_int32</tt>: Number of bytes in payload<br> * @param [out] pcm <tt>float*</tt>: Output signal (interleaved if 2 channels). length<br> * is frame_size*channels*sizeof(float)<br> * @param [in] frame_size Number of samples per channel of available space in \a pcm.<br> * If this is less than the maximum packet duration (120ms; 5760 for 48kHz), this function will<br> * not be capable of decoding some packets. In the case of PLC (data==NULL) or FEC (decode_fec=1),<br> * then frame_size needs to be exactly the duration of audio that is missing, otherwise the<br> * decoder will not be in the optimal state to decode the next incoming packet. For the PLC and<br> * FEC cases, frame_size <b>must</b> be a multiple of 2.5 ms.<br> * @param [in] decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band forward error correction data be<br> * decoded. If no such data is available the frame is decoded as if it were lost.<br> * @returns Number of decoded samples or @ref opus_errorcodes<br> * Original signature : <code>int opus_decode_float(OpusDecoder*, const unsigned char*, opus_int32, float*, int, int)</code><br> * <i>native declaration : /tmp/opus.h:450</i> */ int opus_decode_float(PointerByReference st, byte data[], int len, FloatBuffer pcm, int frame_size, int decode_fec); /** * Decode an Opus packet with floating point output.<br> * @param [in] st <tt>OpusDecoder*</tt>: Decoder state<br> * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss<br> * @param [in] len <tt>opus_int32</tt>: Number of bytes in payload<br> * @param [out] pcm <tt>float*</tt>: Output signal (interleaved if 2 channels). length<br> * is frame_size*channels*sizeof(float)<br> * @param [in] frame_size Number of samples per channel of available space in \a pcm.<br> * If this is less than the maximum packet duration (120ms; 5760 for 48kHz), this function will<br> * not be capable of decoding some packets. In the case of PLC (data==NULL) or FEC (decode_fec=1),<br> * then frame_size needs to be exactly the duration of audio that is missing, otherwise the<br> * decoder will not be in the optimal state to decode the next incoming packet. For the PLC and<br> * FEC cases, frame_size <b>must</b> be a multiple of 2.5 ms.<br> * @param [in] decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band forward error correction data be<br> * decoded. If no such data is available the frame is decoded as if it were lost.<br> * @returns Number of decoded samples or @ref opus_errorcodes<br> * Original signature : <code>int opus_decode_float(OpusDecoder*, const unsigned char*, opus_int32, float*, int, int)</code><br> * <i>native declaration : /tmp/opus.h:450</i> */ int opus_decode_float(PointerByReference st, Pointer data, int len, FloatByReference pcm, int frame_size, int decode_fec); /** * Perform a CTL function on an Opus decoder.<br> * * Generally the request and subsequent arguments are generated<br> * by a convenience macro.<br> * @param st <tt>OpusDecoder*</tt>: Decoder state.<br> * @param request This and all remaining parameters should be replaced by one<br> * of the convenience macros in @ref opus_genericctls or<br> * @ref opus_decoderctls.<br> * @see opus_genericctls<br> * @see opus_decoderctls<br> * Original signature : <code>int opus_decoder_ctl(OpusDecoder*, int, null)</code><br> * <i>native declaration : /tmp/opus.h:470</i> */ int opus_decoder_ctl(PointerByReference st, int request, Object... varargs); /** * Frees an <code>OpusDecoder</code> allocated by opus_decoder_create().<br> * @param[in] st <tt>OpusDecoder*</tt>: State to be freed.<br> * Original signature : <code>void opus_decoder_destroy(OpusDecoder*)</code><br> * <i>native declaration : /tmp/opus.h:475</i> */ void opus_decoder_destroy(PointerByReference st); /** * Parse an opus packet into one or more frames.<br> * Opus_decode will perform this operation internally so most applications do<br> * not need to use this function.<br> * This function does not copy the frames, the returned pointers are pointers into<br> * the input packet.<br> * @param [in] data <tt>char*</tt>: Opus packet to be parsed<br> * @param [in] len <tt>opus_int32</tt>: size of data<br> * @param [out] out_toc <tt>char*</tt>: TOC pointer<br> * @param [out] frames <tt>char*[48]</tt> encapsulated frames<br> * @param [out] size <tt>opus_int16[48]</tt> sizes of the encapsulated frames<br> * @param [out] payload_offset <tt>int*</tt>: returns the position of the payload within the packet (in bytes)<br> * @returns number of frames<br> * Original signature : <code>int opus_packet_parse(const unsigned char*, opus_int32, unsigned char*, const unsigned char*[48], opus_int16[48], int*)</code><br> * <i>native declaration : /tmp/opus.h:490</i> */ int opus_packet_parse(byte data[], int len, ByteBuffer out_toc, byte frames[], ShortBuffer size, IntBuffer payload_offset); /** * Gets the bandwidth of an Opus packet.<br> * @param [in] data <tt>char*</tt>: Opus packet<br> * @retval OPUS_BANDWIDTH_NARROWBAND Narrowband (4kHz bandpass)<br> * @retval OPUS_BANDWIDTH_MEDIUMBAND Mediumband (6kHz bandpass)<br> * @retval OPUS_BANDWIDTH_WIDEBAND Wideband (8kHz bandpass)<br> * @retval OPUS_BANDWIDTH_SUPERWIDEBAND Superwideband (12kHz bandpass)<br> * @retval OPUS_BANDWIDTH_FULLBAND Fullband (20kHz bandpass)<br> * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type<br> * Original signature : <code>int opus_packet_get_bandwidth(const unsigned char*)</code><br> * <i>native declaration : /tmp/opus.h:508</i> */ int opus_packet_get_bandwidth(byte data[]); /** * Gets the number of samples per frame from an Opus packet.<br> * @param [in] data <tt>char*</tt>: Opus packet.<br> * This must contain at least one byte of<br> * data.<br> * @param [in] Fs <tt>opus_int32</tt>: Sampling rate in Hz.<br> * This must be a multiple of 400, or<br> * inaccurate results will be returned.<br> * @returns Number of samples per frame.<br> * Original signature : <code>int opus_packet_get_samples_per_frame(const unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:519</i> */ int opus_packet_get_samples_per_frame(byte data[], int Fs); /** * Gets the number of channels from an Opus packet.<br> * @param [in] data <tt>char*</tt>: Opus packet<br> * @returns Number of channels<br> * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type<br> * Original signature : <code>int opus_packet_get_nb_channels(const unsigned char*)</code><br> * <i>native declaration : /tmp/opus.h:526</i> */ int opus_packet_get_nb_channels(byte data[]); /** * Gets the number of frames in an Opus packet.<br> * @param [in] packet <tt>char*</tt>: Opus packet<br> * @param [in] len <tt>opus_int32</tt>: Length of packet<br> * @returns Number of frames<br> * @retval OPUS_BAD_ARG Insufficient data was passed to the function<br> * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type<br> * Original signature : <code>int opus_packet_get_nb_frames(const unsigned char[], opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:535</i> */ int opus_packet_get_nb_frames(byte packet[], int len); /** * Gets the number of samples of an Opus packet.<br> * @param [in] packet <tt>char*</tt>: Opus packet<br> * @param [in] len <tt>opus_int32</tt>: Length of packet<br> * @param [in] Fs <tt>opus_int32</tt>: Sampling rate in Hz.<br> * This must be a multiple of 400, or<br> * inaccurate results will be returned.<br> * @returns Number of samples<br> * @retval OPUS_BAD_ARG Insufficient data was passed to the function<br> * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type<br> * Original signature : <code>int opus_packet_get_nb_samples(const unsigned char[], opus_int32, opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:547</i> */ int opus_packet_get_nb_samples(byte packet[], int len, int Fs); /** * Gets the number of samples of an Opus packet.<br> * @param [in] dec <tt>OpusDecoder*</tt>: Decoder state<br> * @param [in] packet <tt>char*</tt>: Opus packet<br> * @param [in] len <tt>opus_int32</tt>: Length of packet<br> * @returns Number of samples<br> * @retval OPUS_BAD_ARG Insufficient data was passed to the function<br> * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type<br> * Original signature : <code>int opus_decoder_get_nb_samples(const OpusDecoder*, const unsigned char[], opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:557</i> */ int opus_decoder_get_nb_samples(PointerByReference dec, byte packet[], int len); /** * Gets the number of samples of an Opus packet.<br> * @param [in] dec <tt>OpusDecoder*</tt>: Decoder state<br> * @param [in] packet <tt>char*</tt>: Opus packet<br> * @param [in] len <tt>opus_int32</tt>: Length of packet<br> * @returns Number of samples<br> * @retval OPUS_BAD_ARG Insufficient data was passed to the function<br> * @retval OPUS_INVALID_PACKET The compressed data passed is corrupted or of an unsupported type<br> * Original signature : <code>int opus_decoder_get_nb_samples(const OpusDecoder*, const unsigned char[], opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:557</i> */ int opus_decoder_get_nb_samples(PointerByReference dec, Pointer packet, int len); /** * Applies soft-clipping to bring a float signal within the [-1,1] range. If<br> * the signal is already in that range, nothing is done. If there are values<br> * outside of [-1,1], then the signal is clipped as smoothly as possible to<br> * both fit in the range and avoid creating excessive distortion in the<br> * process.<br> * @param [in,out] pcm <tt>float*</tt>: Input PCM and modified PCM<br> * @param [in] frame_size <tt>int</tt> Number of samples per channel to process<br> * @param [in] channels <tt>int</tt>: Number of channels<br> * @param [in,out] softclip_mem <tt>float*</tt>: State memory for the soft clipping process (one float per channel, initialized to zero)<br> * Original signature : <code>void opus_pcm_soft_clip(float*, int, int, float*)</code><br> * <i>native declaration : /tmp/opus.h:569</i> */ void opus_pcm_soft_clip(FloatBuffer pcm, int frame_size, int channels, FloatBuffer softclip_mem); /** * Gets the size of an <code>OpusRepacketizer</code> structure.<br> * @returns The size in bytes.<br> * Original signature : <code>int opus_repacketizer_get_size()</code><br> * <i>native declaration : /tmp/opus.h:719</i> */ int opus_repacketizer_get_size(); /** * (Re)initializes a previously allocated repacketizer state.<br> * The state must be at least the size returned by opus_repacketizer_get_size().<br> * This can be used for applications which use their own allocator instead of<br> * malloc().<br> * It must also be called to reset the queue of packets waiting to be<br> * repacketized, which is necessary if the maximum packet duration of 120 ms<br> * is reached or if you wish to submit packets with a different Opus<br> * configuration (coding mode, audio bandwidth, frame size, or channel count).<br> * Failure to do so will prevent a new packet from being added with<br> * opus_repacketizer_cat().<br> * @see opus_repacketizer_create<br> * @see opus_repacketizer_get_size<br> * @see opus_repacketizer_cat<br> * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state to<br> * (re)initialize.<br> * @returns A pointer to the same repacketizer state that was passed in.<br> * Original signature : <code>OpusRepacketizer* opus_repacketizer_init(OpusRepacketizer*)</code><br> * <i>native declaration : /tmp/opus.h:738</i> */ PointerByReference opus_repacketizer_init(PointerByReference rp); /** * Allocates memory and initializes the new repacketizer with<br> * opus_repacketizer_init().<br> * Original signature : <code>OpusRepacketizer* opus_repacketizer_create()</code><br> * <i>native declaration : /tmp/opus.h:743</i> */ PointerByReference opus_repacketizer_create(); /** * Frees an <code>OpusRepacketizer</code> allocated by<br> * opus_repacketizer_create().<br> * @param[in] rp <tt>OpusRepacketizer*</tt>: State to be freed.<br> * Original signature : <code>void opus_repacketizer_destroy(OpusRepacketizer*)</code><br> * <i>native declaration : /tmp/opus.h:749</i> */ void opus_repacketizer_destroy(PointerByReference rp); /** * Add a packet to the current repacketizer state.<br> * This packet must match the configuration of any packets already submitted<br> * for repacketization since the last call to opus_repacketizer_init().<br> * This means that it must have the same coding mode, audio bandwidth, frame<br> * size, and channel count.<br> * This can be checked in advance by examining the top 6 bits of the first<br> * byte of the packet, and ensuring they match the top 6 bits of the first<br> * byte of any previously submitted packet.<br> * The total duration of audio in the repacketizer state also must not exceed<br> * 120 ms, the maximum duration of a single packet, after adding this packet.<br> * * The contents of the current repacketizer state can be extracted into new<br> * packets using opus_repacketizer_out() or opus_repacketizer_out_range().<br> * * In order to add a packet with a different configuration or to add more<br> * audio beyond 120 ms, you must clear the repacketizer state by calling<br> * opus_repacketizer_init().<br> * If a packet is too large to add to the current repacketizer state, no part<br> * of it is added, even if it contains multiple frames, some of which might<br> * fit.<br> * If you wish to be able to add parts of such packets, you should first use<br> * another repacketizer to split the packet into pieces and add them<br> * individually.<br> * @see opus_repacketizer_out_range<br> * @see opus_repacketizer_out<br> * @see opus_repacketizer_init<br> * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state to which to<br> * add the packet.<br> * @param[in] data <tt>const unsigned char*</tt>: The packet data.<br> * The application must ensure<br> * this pointer remains valid<br> * until the next call to<br> * opus_repacketizer_init() or<br> * opus_repacketizer_destroy().<br> * @param len <tt>opus_int32</tt>: The number of bytes in the packet data.<br> * @returns An error code indicating whether or not the operation succeeded.<br> * @retval #OPUS_OK The packet's contents have been added to the repacketizer<br> * state.<br> * @retval #OPUS_INVALID_PACKET The packet did not have a valid TOC sequence,<br> * the packet's TOC sequence was not compatible<br> * with previously submitted packets (because<br> * the coding mode, audio bandwidth, frame size,<br> * or channel count did not match), or adding<br> * this packet would increase the total amount of<br> * audio stored in the repacketizer state to more<br> * than 120 ms.<br> * Original signature : <code>int opus_repacketizer_cat(OpusRepacketizer*, const unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:798</i> */ int opus_repacketizer_cat(PointerByReference rp, byte data[], int len); /** * Add a packet to the current repacketizer state.<br> * This packet must match the configuration of any packets already submitted<br> * for repacketization since the last call to opus_repacketizer_init().<br> * This means that it must have the same coding mode, audio bandwidth, frame<br> * size, and channel count.<br> * This can be checked in advance by examining the top 6 bits of the first<br> * byte of the packet, and ensuring they match the top 6 bits of the first<br> * byte of any previously submitted packet.<br> * The total duration of audio in the repacketizer state also must not exceed<br> * 120 ms, the maximum duration of a single packet, after adding this packet.<br> * * The contents of the current repacketizer state can be extracted into new<br> * packets using opus_repacketizer_out() or opus_repacketizer_out_range().<br> * * In order to add a packet with a different configuration or to add more<br> * audio beyond 120 ms, you must clear the repacketizer state by calling<br> * opus_repacketizer_init().<br> * If a packet is too large to add to the current repacketizer state, no part<br> * of it is added, even if it contains multiple frames, some of which might<br> * fit.<br> * If you wish to be able to add parts of such packets, you should first use<br> * another repacketizer to split the packet into pieces and add them<br> * individually.<br> * @see opus_repacketizer_out_range<br> * @see opus_repacketizer_out<br> * @see opus_repacketizer_init<br> * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state to which to<br> * add the packet.<br> * @param[in] data <tt>const unsigned char*</tt>: The packet data.<br> * The application must ensure<br> * this pointer remains valid<br> * until the next call to<br> * opus_repacketizer_init() or<br> * opus_repacketizer_destroy().<br> * @param len <tt>opus_int32</tt>: The number of bytes in the packet data.<br> * @returns An error code indicating whether or not the operation succeeded.<br> * @retval #OPUS_OK The packet's contents have been added to the repacketizer<br> * state.<br> * @retval #OPUS_INVALID_PACKET The packet did not have a valid TOC sequence,<br> * the packet's TOC sequence was not compatible<br> * with previously submitted packets (because<br> * the coding mode, audio bandwidth, frame size,<br> * or channel count did not match), or adding<br> * this packet would increase the total amount of<br> * audio stored in the repacketizer state to more<br> * than 120 ms.<br> * Original signature : <code>int opus_repacketizer_cat(OpusRepacketizer*, const unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:798</i> */ int opus_repacketizer_cat(PointerByReference rp, Pointer data, int len); /** * Construct a new packet from data previously submitted to the repacketizer<br> * state via opus_repacketizer_cat().<br> * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state from which to<br> * construct the new packet.<br> * @param begin <tt>int</tt>: The index of the first frame in the current<br> * repacketizer state to include in the output.<br> * @param end <tt>int</tt>: One past the index of the last frame in the<br> * current repacketizer state to include in the<br> * output.<br> * @param[out] data <tt>const unsigned char*</tt>: The buffer in which to<br> * store the output packet.<br> * @param maxlen <tt>opus_int32</tt>: The maximum number of bytes to store in<br> * the output buffer. In order to guarantee<br> * success, this should be at least<br> * <code>1276</code> for a single frame,<br> * or for multiple frames,<br> * <code>1277*(end-begin)</code>.<br> * However, <code>1*(end-begin)</code> plus<br> * the size of all packet data submitted to<br> * the repacketizer since the last call to<br> * opus_repacketizer_init() or<br> * opus_repacketizer_create() is also<br> * sufficient, and possibly much smaller.<br> * @returns The total size of the output packet on success, or an error code<br> * on failure.<br> * @retval #OPUS_BAD_ARG <code>[begin,end)</code> was an invalid range of<br> * frames (begin < 0, begin >= end, or end ><br> * opus_repacketizer_get_nb_frames()).<br> * @retval #OPUS_BUFFER_TOO_SMALL \a maxlen was insufficient to contain the<br> * complete output packet.<br> * Original signature : <code>opus_int32 opus_repacketizer_out_range(OpusRepacketizer*, int, int, unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:832</i> */ int opus_repacketizer_out_range(PointerByReference rp, int begin, int end, ByteBuffer data, int maxlen); /** * Construct a new packet from data previously submitted to the repacketizer<br> * state via opus_repacketizer_cat().<br> * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state from which to<br> * construct the new packet.<br> * @param begin <tt>int</tt>: The index of the first frame in the current<br> * repacketizer state to include in the output.<br> * @param end <tt>int</tt>: One past the index of the last frame in the<br> * current repacketizer state to include in the<br> * output.<br> * @param[out] data <tt>const unsigned char*</tt>: The buffer in which to<br> * store the output packet.<br> * @param maxlen <tt>opus_int32</tt>: The maximum number of bytes to store in<br> * the output buffer. In order to guarantee<br> * success, this should be at least<br> * <code>1276</code> for a single frame,<br> * or for multiple frames,<br> * <code>1277*(end-begin)</code>.<br> * However, <code>1*(end-begin)</code> plus<br> * the size of all packet data submitted to<br> * the repacketizer since the last call to<br> * opus_repacketizer_init() or<br> * opus_repacketizer_create() is also<br> * sufficient, and possibly much smaller.<br> * @returns The total size of the output packet on success, or an error code<br> * on failure.<br> * @retval #OPUS_BAD_ARG <code>[begin,end)</code> was an invalid range of<br> * frames (begin < 0, begin >= end, or end ><br> * opus_repacketizer_get_nb_frames()).<br> * @retval #OPUS_BUFFER_TOO_SMALL \a maxlen was insufficient to contain the<br> * complete output packet.<br> * Original signature : <code>opus_int32 opus_repacketizer_out_range(OpusRepacketizer*, int, int, unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:832</i> */ int opus_repacketizer_out_range(PointerByReference rp, int begin, int end, Pointer data, int maxlen); /** * Return the total number of frames contained in packet data submitted to<br> * the repacketizer state so far via opus_repacketizer_cat() since the last<br> * call to opus_repacketizer_init() or opus_repacketizer_create().<br> * This defines the valid range of packets that can be extracted with<br> * opus_repacketizer_out_range() or opus_repacketizer_out().<br> * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state containing the<br> * frames.<br> * @returns The total number of frames contained in the packet data submitted<br> * to the repacketizer state.<br> * Original signature : <code>int opus_repacketizer_get_nb_frames(OpusRepacketizer*)</code><br> * <i>native declaration : /tmp/opus.h:844</i> */ int opus_repacketizer_get_nb_frames(PointerByReference rp); /** * Construct a new packet from data previously submitted to the repacketizer<br> * state via opus_repacketizer_cat().<br> * This is a convenience routine that returns all the data submitted so far<br> * in a single packet.<br> * It is equivalent to calling<br> * @code<br> * opus_repacketizer_out_range(rp, 0, opus_repacketizer_get_nb_frames(rp),<br> * data, maxlen)<br> * @endcode<br> * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state from which to<br> * construct the new packet.<br> * @param[out] data <tt>const unsigned char*</tt>: The buffer in which to<br> * store the output packet.<br> * @param maxlen <tt>opus_int32</tt>: The maximum number of bytes to store in<br> * the output buffer. In order to guarantee<br> * success, this should be at least<br> * <code>1277*opus_repacketizer_get_nb_frames(rp)</code>.<br> * However,<br> * <code>1*opus_repacketizer_get_nb_frames(rp)</code><br> * plus the size of all packet data<br> * submitted to the repacketizer since the<br> * last call to opus_repacketizer_init() or<br> * opus_repacketizer_create() is also<br> * sufficient, and possibly much smaller.<br> * @returns The total size of the output packet on success, or an error code<br> * on failure.<br> * @retval #OPUS_BUFFER_TOO_SMALL \a maxlen was insufficient to contain the<br> * complete output packet.<br> * Original signature : <code>opus_int32 opus_repacketizer_out(OpusRepacketizer*, unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:875</i> */ int opus_repacketizer_out(PointerByReference rp, ByteBuffer data, int maxlen); /** * Construct a new packet from data previously submitted to the repacketizer<br> * state via opus_repacketizer_cat().<br> * This is a convenience routine that returns all the data submitted so far<br> * in a single packet.<br> * It is equivalent to calling<br> * @code<br> * opus_repacketizer_out_range(rp, 0, opus_repacketizer_get_nb_frames(rp),<br> * data, maxlen)<br> * @endcode<br> * @param rp <tt>OpusRepacketizer*</tt>: The repacketizer state from which to<br> * construct the new packet.<br> * @param[out] data <tt>const unsigned char*</tt>: The buffer in which to<br> * store the output packet.<br> * @param maxlen <tt>opus_int32</tt>: The maximum number of bytes to store in<br> * the output buffer. In order to guarantee<br> * success, this should be at least<br> * <code>1277*opus_repacketizer_get_nb_frames(rp)</code>.<br> * However,<br> * <code>1*opus_repacketizer_get_nb_frames(rp)</code><br> * plus the size of all packet data<br> * submitted to the repacketizer since the<br> * last call to opus_repacketizer_init() or<br> * opus_repacketizer_create() is also<br> * sufficient, and possibly much smaller.<br> * @returns The total size of the output packet on success, or an error code<br> * on failure.<br> * @retval #OPUS_BUFFER_TOO_SMALL \a maxlen was insufficient to contain the<br> * complete output packet.<br> * Original signature : <code>opus_int32 opus_repacketizer_out(OpusRepacketizer*, unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:875</i> */ int opus_repacketizer_out(PointerByReference rp, Pointer data, int maxlen); /** * Pads a given Opus packet to a larger size (possibly changing the TOC sequence).<br> * @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the<br> * packet to pad.<br> * @param len <tt>opus_int32</tt>: The size of the packet.<br> * This must be at least 1.<br> * @param new_len <tt>opus_int32</tt>: The desired size of the packet after padding.<br> * This must be at least as large as len.<br> * @returns an error code<br> * @retval #OPUS_OK \a on success.<br> * @retval #OPUS_BAD_ARG \a len was less than 1 or new_len was less than len.<br> * @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet.<br> * Original signature : <code>int opus_packet_pad(unsigned char*, opus_int32, opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:889</i> */ int opus_packet_pad(ByteBuffer data, int len, int new_len); /** * Remove all padding from a given Opus packet and rewrite the TOC sequence to<br> * minimize space usage.<br> * @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the<br> * packet to strip.<br> * @param len <tt>opus_int32</tt>: The size of the packet.<br> * This must be at least 1.<br> * @returns The new size of the output packet on success, or an error code<br> * on failure.<br> * @retval #OPUS_BAD_ARG \a len was less than 1.<br> * @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet.<br> * Original signature : <code>opus_int32 opus_packet_unpad(unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus.h:902</i> */ int opus_packet_unpad(ByteBuffer data, int len); /** * Pads a given Opus multi-stream packet to a larger size (possibly changing the TOC sequence).<br> * @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the<br> * packet to pad.<br> * @param len <tt>opus_int32</tt>: The size of the packet.<br> * This must be at least 1.<br> * @param new_len <tt>opus_int32</tt>: The desired size of the packet after padding.<br> * This must be at least 1.<br> * @param nb_streams <tt>opus_int32</tt>: The number of streams (not channels) in the packet.<br> * This must be at least as large as len.<br> * @returns an error code<br> * @retval #OPUS_OK \a on success.<br> * @retval #OPUS_BAD_ARG \a len was less than 1.<br> * @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet.<br> * Original signature : <code>int opus_multistream_packet_pad(unsigned char*, opus_int32, opus_int32, int)</code><br> * <i>native declaration : /tmp/opus.h:918</i> */ int opus_multistream_packet_pad(ByteBuffer data, int len, int new_len, int nb_streams); /** * Remove all padding from a given Opus multi-stream packet and rewrite the TOC sequence to<br> * minimize space usage.<br> * @param[in,out] data <tt>const unsigned char*</tt>: The buffer containing the<br> * packet to strip.<br> * @param len <tt>opus_int32</tt>: The size of the packet.<br> * This must be at least 1.<br> * @param nb_streams <tt>opus_int32</tt>: The number of streams (not channels) in the packet.<br> * This must be at least 1.<br> * @returns The new size of the output packet on success, or an error code<br> * on failure.<br> * @retval #OPUS_BAD_ARG \a len was less than 1 or new_len was less than len.<br> * @retval #OPUS_INVALID_PACKET \a data did not contain a valid Opus packet.<br> * Original signature : <code>opus_int32 opus_multistream_packet_unpad(unsigned char*, opus_int32, int)</code><br> * <i>native declaration : /tmp/opus.h:933</i> */ int opus_multistream_packet_unpad(ByteBuffer data, int len, int nb_streams); public static class OpusDecoder extends PointerType { public OpusDecoder(Pointer address) { super(address); } public OpusDecoder() { super(); } }; public static class OpusEncoder extends PointerType { public OpusEncoder(Pointer address) { super(address); } public OpusEncoder() { super(); } }; public static class OpusRepacketizer extends PointerType { public OpusRepacketizer(Pointer address) { super(address); } public OpusRepacketizer() { super(); } }; /** * Converts an opus error code into a human readable string.<br> * * @param[in] error <tt>int</tt>: Error number<br> * @returns Error string<br> * Original signature : <code>char* opus_strerror(int)</code><br> * <i>native declaration : /tmp/opus_defines.h:712</i> */ String opus_strerror(int error); /** * Gets the libopus version string.<br> * * @returns Version string<br> * Original signature : <code>char* opus_get_version_string()</code><br> * <i>native declaration : /tmp/opus_defines.h:718</i> */ String opus_get_version_string(); //******************** Multi Stream Support /** * Gets the size of an OpusMSEncoder structure.<br> * @param streams <tt>int</tt>: The total number of streams to encode from the<br> * input.<br> * This must be no more than 255.<br> * @param coupled_streams <tt>int</tt>: Number of coupled (2 channel) streams<br> * to encode.<br> * This must be no larger than the total<br> * number of streams.<br> * Additionally, The total number of<br> * encoded channels (<code>streams +<br> * coupled_streams</code>) must be no<br> * more than 255.<br> * @returns The size in bytes on success, or a negative error code<br> * (see @ref opus_errorcodes) on error.<br> * Original signature : <code>opus_int32 opus_multistream_encoder_get_size(int, int)</code><br> * <i>native declaration : /tmp/opus_multistream.h:202</i> */ int opus_multistream_encoder_get_size(int streams, int coupled_streams); /** * Original signature : <code>opus_int32 opus_multistream_surround_encoder_get_size(int, int)</code><br> * <i>native declaration : /tmp/opus_multistream.h:207</i> */ int opus_multistream_surround_encoder_get_size(int channels, int mapping_family); /** * Allocates and initializes a multistream encoder state.<br> * Call opus_multistream_encoder_destroy() to release<br> * this object when finished.<br> * @param Fs <tt>opus_int32</tt>: Sampling rate of the input signal (in Hz).<br> * This must be one of 8000, 12000, 16000,<br> * 24000, or 48000.<br> * @param channels <tt>int</tt>: Number of channels in the input signal.<br> * This must be at most 255.<br> * It may be greater than the number of<br> * coded channels (<code>streams +<br> * coupled_streams</code>).<br> * @param streams <tt>int</tt>: The total number of streams to encode from the<br> * input.<br> * This must be no more than the number of channels.<br> * @param coupled_streams <tt>int</tt>: Number of coupled (2 channel) streams<br> * to encode.<br> * This must be no larger than the total<br> * number of streams.<br> * Additionally, The total number of<br> * encoded channels (<code>streams +<br> * coupled_streams</code>) must be no<br> * more than the number of input channels.<br> * @param[in] mapping <code>const unsigned char[channels]</code>: Mapping from<br> * encoded channels to input channels, as described in<br> * @ref opus_multistream. As an extra constraint, the<br> * multistream encoder does not allow encoding coupled<br> * streams for which one channel is unused since this<br> * is never a good idea.<br> * @param application <tt>int</tt>: The target encoder application.<br> * This must be one of the following:<br> * <dl><br> * <dt>#OPUS_APPLICATION_VOIP</dt><br> * <dd>Process signal for improved speech intelligibility.</dd><br> * <dt>#OPUS_APPLICATION_AUDIO</dt><br> * <dd>Favor faithfulness to the original input.</dd><br> * <dt>#OPUS_APPLICATION_RESTRICTED_LOWDELAY</dt><br> * <dd>Configure the minimum possible coding delay by disabling certain modes<br> * of operation.</dd><br> * </dl><br> * @param[out] error <tt>int *</tt>: Returns #OPUS_OK on success, or an error<br> * code (see @ref opus_errorcodes) on<br> * failure.<br> * Original signature : <code>OpusMSEncoder* opus_multistream_encoder_create(opus_int32, int, int, int, const unsigned char*, int, int*)</code><br> * <i>native declaration : /tmp/opus_multistream.h:256</i> */ PointerByReference opus_multistream_encoder_create(int Fs, int channels, int streams, int coupled_streams, byte mapping[], int application, IntBuffer error); /** * Original signature : <code>OpusMSEncoder* opus_multistream_surround_encoder_create(opus_int32, int, int, int*, int*, unsigned char*, int, int*)</code><br> * <i>native declaration : /tmp/opus_multistream.h:266</i> */ PointerByReference opus_multistream_surround_encoder_create(int Fs, int channels, int mapping_family, IntBuffer streams, IntBuffer coupled_streams, ByteBuffer mapping, int application, IntBuffer error); /** * Initialize a previously allocated multistream encoder state.<br> * The memory pointed to by \a st must be at least the size returned by<br> * opus_multistream_encoder_get_size().<br> * This is intended for applications which use their own allocator instead of<br> * malloc.<br> * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL.<br> * @see opus_multistream_encoder_create<br> * @see opus_multistream_encoder_get_size<br> * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state to initialize.<br> * @param Fs <tt>opus_int32</tt>: Sampling rate of the input signal (in Hz).<br> * This must be one of 8000, 12000, 16000,<br> * 24000, or 48000.<br> * @param channels <tt>int</tt>: Number of channels in the input signal.<br> * This must be at most 255.<br> * It may be greater than the number of<br> * coded channels (<code>streams +<br> * coupled_streams</code>).<br> * @param streams <tt>int</tt>: The total number of streams to encode from the<br> * input.<br> * This must be no more than the number of channels.<br> * @param coupled_streams <tt>int</tt>: Number of coupled (2 channel) streams<br> * to encode.<br> * This must be no larger than the total<br> * number of streams.<br> * Additionally, The total number of<br> * encoded channels (<code>streams +<br> * coupled_streams</code>) must be no<br> * more than the number of input channels.<br> * @param[in] mapping <code>const unsigned char[channels]</code>: Mapping from<br> * encoded channels to input channels, as described in<br> * @ref opus_multistream. As an extra constraint, the<br> * multistream encoder does not allow encoding coupled<br> * streams for which one channel is unused since this<br> * is never a good idea.<br> * @param application <tt>int</tt>: The target encoder application.<br> * This must be one of the following:<br> * <dl><br> * <dt>#OPUS_APPLICATION_VOIP</dt><br> * <dd>Process signal for improved speech intelligibility.</dd><br> * <dt>#OPUS_APPLICATION_AUDIO</dt><br> * <dd>Favor faithfulness to the original input.</dd><br> * <dt>#OPUS_APPLICATION_RESTRICTED_LOWDELAY</dt><br> * <dd>Configure the minimum possible coding delay by disabling certain modes<br> * of operation.</dd><br> * </dl><br> * @returns #OPUS_OK on success, or an error code (see @ref opus_errorcodes)<br> * on failure.<br> * Original signature : <code>int opus_multistream_encoder_init(OpusMSEncoder*, opus_int32, int, int, int, const unsigned char*, int)</code><br> * <i>native declaration : /tmp/opus_multistream.h:325</i> */ int opus_multistream_encoder_init(PointerByReference st, int Fs, int channels, int streams, int coupled_streams, byte mapping[], int application); /** * Initialize a previously allocated multistream encoder state.<br> * The memory pointed to by \a st must be at least the size returned by<br> * opus_multistream_encoder_get_size().<br> * This is intended for applications which use their own allocator instead of<br> * malloc.<br> * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL.<br> * @see opus_multistream_encoder_create<br> * @see opus_multistream_encoder_get_size<br> * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state to initialize.<br> * @param Fs <tt>opus_int32</tt>: Sampling rate of the input signal (in Hz).<br> * This must be one of 8000, 12000, 16000,<br> * 24000, or 48000.<br> * @param channels <tt>int</tt>: Number of channels in the input signal.<br> * This must be at most 255.<br> * It may be greater than the number of<br> * coded channels (<code>streams +<br> * coupled_streams</code>).<br> * @param streams <tt>int</tt>: The total number of streams to encode from the<br> * input.<br> * This must be no more than the number of channels.<br> * @param coupled_streams <tt>int</tt>: Number of coupled (2 channel) streams<br> * to encode.<br> * This must be no larger than the total<br> * number of streams.<br> * Additionally, The total number of<br> * encoded channels (<code>streams +<br> * coupled_streams</code>) must be no<br> * more than the number of input channels.<br> * @param[in] mapping <code>const unsigned char[channels]</code>: Mapping from<br> * encoded channels to input channels, as described in<br> * @ref opus_multistream. As an extra constraint, the<br> * multistream encoder does not allow encoding coupled<br> * streams for which one channel is unused since this<br> * is never a good idea.<br> * @param application <tt>int</tt>: The target encoder application.<br> * This must be one of the following:<br> * <dl><br> * <dt>#OPUS_APPLICATION_VOIP</dt><br> * <dd>Process signal for improved speech intelligibility.</dd><br> * <dt>#OPUS_APPLICATION_AUDIO</dt><br> * <dd>Favor faithfulness to the original input.</dd><br> * <dt>#OPUS_APPLICATION_RESTRICTED_LOWDELAY</dt><br> * <dd>Configure the minimum possible coding delay by disabling certain modes<br> * of operation.</dd><br> * </dl><br> * @returns #OPUS_OK on success, or an error code (see @ref opus_errorcodes)<br> * on failure.<br> * Original signature : <code>int opus_multistream_encoder_init(OpusMSEncoder*, opus_int32, int, int, int, const unsigned char*, int)</code><br> * <i>native declaration : /tmp/opus_multistream.h:325</i> */ int opus_multistream_encoder_init(PointerByReference st, int Fs, int channels, int streams, int coupled_streams, Pointer mapping, int application); /** * Original signature : <code>int opus_multistream_surround_encoder_init(OpusMSEncoder*, opus_int32, int, int, int*, int*, unsigned char*, int)</code><br> * <i>native declaration : /tmp/opus_multistream.h:335</i> */ int opus_multistream_surround_encoder_init(PointerByReference st, int Fs, int channels, int mapping_family, IntBuffer streams, IntBuffer coupled_streams, ByteBuffer mapping, int application); /** * Original signature : <code>int opus_multistream_surround_encoder_init(OpusMSEncoder*, opus_int32, int, int, int*, int*, unsigned char*, int)</code><br> * <i>native declaration : /tmp/opus_multistream.h:335</i> */ int opus_multistream_surround_encoder_init(PointerByReference st, int Fs, int channels, int mapping_family, IntByReference streams, IntByReference coupled_streams, Pointer mapping, int application); /** * Encodes a multistream Opus frame.<br> * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state.<br> * @param[in] pcm <tt>const opus_int16*</tt>: The input signal as interleaved<br> * samples.<br> * This must contain<br> * <code>frame_size*channels</code><br> * samples.<br> * @param frame_size <tt>int</tt>: Number of samples per channel in the input<br> * signal.<br> * This must be an Opus frame size for the<br> * encoder's sampling rate.<br> * For example, at 48 kHz the permitted values<br> * are 120, 240, 480, 960, 1920, and 2880.<br> * Passing in a duration of less than 10 ms<br> * (480 samples at 48 kHz) will prevent the<br> * encoder from using the LPC or hybrid modes.<br> * @param[out] data <tt>unsigned char*</tt>: Output payload.<br> * This must contain storage for at<br> * least \a max_data_bytes.<br> * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated<br> * memory for the output<br> * payload. This may be<br> * used to impose an upper limit on<br> * the instant bitrate, but should<br> * not be used as the only bitrate<br> * control. Use #OPUS_SET_BITRATE to<br> * control the bitrate.<br> * @returns The length of the encoded packet (in bytes) on success or a<br> * negative error code (see @ref opus_errorcodes) on failure.<br> * Original signature : <code>int opus_multistream_encode(OpusMSEncoder*, const opus_int16*, int, unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus_multistream.h:376</i> */ int opus_multistream_encode(PointerByReference st, ShortBuffer pcm, int frame_size, ByteBuffer data, int max_data_bytes); /** * Encodes a multistream Opus frame.<br> * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state.<br> * @param[in] pcm <tt>const opus_int16*</tt>: The input signal as interleaved<br> * samples.<br> * This must contain<br> * <code>frame_size*channels</code><br> * samples.<br> * @param frame_size <tt>int</tt>: Number of samples per channel in the input<br> * signal.<br> * This must be an Opus frame size for the<br> * encoder's sampling rate.<br> * For example, at 48 kHz the permitted values<br> * are 120, 240, 480, 960, 1920, and 2880.<br> * Passing in a duration of less than 10 ms<br> * (480 samples at 48 kHz) will prevent the<br> * encoder from using the LPC or hybrid modes.<br> * @param[out] data <tt>unsigned char*</tt>: Output payload.<br> * This must contain storage for at<br> * least \a max_data_bytes.<br> * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated<br> * memory for the output<br> * payload. This may be<br> * used to impose an upper limit on<br> * the instant bitrate, but should<br> * not be used as the only bitrate<br> * control. Use #OPUS_SET_BITRATE to<br> * control the bitrate.<br> * @returns The length of the encoded packet (in bytes) on success or a<br> * negative error code (see @ref opus_errorcodes) on failure.<br> * Original signature : <code>int opus_multistream_encode(OpusMSEncoder*, const opus_int16*, int, unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus_multistream.h:376</i> */ int opus_multistream_encode(PointerByReference st, ShortByReference pcm, int frame_size, Pointer data, int max_data_bytes); /** * Encodes a multistream Opus frame from floating point input.<br> * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state.<br> * @param[in] pcm <tt>const float*</tt>: The input signal as interleaved<br> * samples with a normal range of<br> * +/-1.0.<br> * Samples with a range beyond +/-1.0<br> * are supported but will be clipped by<br> * decoders using the integer API and<br> * should only be used if it is known<br> * that the far end supports extended<br> * dynamic range.<br> * This must contain<br> * <code>frame_size*channels</code><br> * samples.<br> * @param frame_size <tt>int</tt>: Number of samples per channel in the input<br> * signal.<br> * This must be an Opus frame size for the<br> * encoder's sampling rate.<br> * For example, at 48 kHz the permitted values<br> * are 120, 240, 480, 960, 1920, and 2880.<br> * Passing in a duration of less than 10 ms<br> * (480 samples at 48 kHz) will prevent the<br> * encoder from using the LPC or hybrid modes.<br> * @param[out] data <tt>unsigned char*</tt>: Output payload.<br> * This must contain storage for at<br> * least \a max_data_bytes.<br> * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated<br> * memory for the output<br> * payload. This may be<br> * used to impose an upper limit on<br> * the instant bitrate, but should<br> * not be used as the only bitrate<br> * control. Use #OPUS_SET_BITRATE to<br> * control the bitrate.<br> * @returns The length of the encoded packet (in bytes) on success or a<br> * negative error code (see @ref opus_errorcodes) on failure.<br> * Original signature : <code>int opus_multistream_encode_float(OpusMSEncoder*, const float*, int, unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus_multistream.h:421</i> */ int opus_multistream_encode_float(PointerByReference st, float pcm[], int frame_size, ByteBuffer data, int max_data_bytes); /** * Encodes a multistream Opus frame from floating point input.<br> * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state.<br> * @param[in] pcm <tt>const float*</tt>: The input signal as interleaved<br> * samples with a normal range of<br> * +/-1.0.<br> * Samples with a range beyond +/-1.0<br> * are supported but will be clipped by<br> * decoders using the integer API and<br> * should only be used if it is known<br> * that the far end supports extended<br> * dynamic range.<br> * This must contain<br> * <code>frame_size*channels</code><br> * samples.<br> * @param frame_size <tt>int</tt>: Number of samples per channel in the input<br> * signal.<br> * This must be an Opus frame size for the<br> * encoder's sampling rate.<br> * For example, at 48 kHz the permitted values<br> * are 120, 240, 480, 960, 1920, and 2880.<br> * Passing in a duration of less than 10 ms<br> * (480 samples at 48 kHz) will prevent the<br> * encoder from using the LPC or hybrid modes.<br> * @param[out] data <tt>unsigned char*</tt>: Output payload.<br> * This must contain storage for at<br> * least \a max_data_bytes.<br> * @param [in] max_data_bytes <tt>opus_int32</tt>: Size of the allocated<br> * memory for the output<br> * payload. This may be<br> * used to impose an upper limit on<br> * the instant bitrate, but should<br> * not be used as the only bitrate<br> * control. Use #OPUS_SET_BITRATE to<br> * control the bitrate.<br> * @returns The length of the encoded packet (in bytes) on success or a<br> * negative error code (see @ref opus_errorcodes) on failure.<br> * Original signature : <code>int opus_multistream_encode_float(OpusMSEncoder*, const float*, int, unsigned char*, opus_int32)</code><br> * <i>native declaration : /tmp/opus_multistream.h:421</i> */ int opus_multistream_encode_float(PointerByReference st, FloatByReference pcm, int frame_size, Pointer data, int max_data_bytes); /** * Frees an <code>OpusMSEncoder</code> allocated by<br> * opus_multistream_encoder_create().<br> * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state to be freed.<br> * Original signature : <code>void opus_multistream_encoder_destroy(OpusMSEncoder*)</code><br> * <i>native declaration : /tmp/opus_multistream.h:433</i> */ void opus_multistream_encoder_destroy(PointerByReference st); /** * Perform a CTL function on a multistream Opus encoder.<br> * * Generally the request and subsequent arguments are generated by a<br> * convenience macro.<br> * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state.<br> * @param request This and all remaining parameters should be replaced by one<br> * of the convenience macros in @ref opus_genericctls,<br> * @ref opus_encoderctls, or @ref opus_multistream_ctls.<br> * @see opus_genericctls<br> * @see opus_encoderctls<br> * @see opus_multistream_ctls<br> * Original signature : <code>int opus_multistream_encoder_ctl(OpusMSEncoder*, int, null)</code><br> * <i>native declaration : /tmp/opus_multistream.h:447</i> */ int opus_multistream_encoder_ctl(PointerByReference st, int request, Object... varargs); /** * Gets the size of an <code>OpusMSDecoder</code> structure.<br> * @param streams <tt>int</tt>: The total number of streams coded in the<br> * input.<br> * This must be no more than 255.<br> * @param coupled_streams <tt>int</tt>: Number streams to decode as coupled<br> * (2 channel) streams.<br> * This must be no larger than the total<br> * number of streams.<br> * Additionally, The total number of<br> * coded channels (<code>streams +<br> * coupled_streams</code>) must be no<br> * more than 255.<br> * @returns The size in bytes on success, or a negative error code<br> * (see @ref opus_errorcodes) on error.<br> * Original signature : <code>opus_int32 opus_multistream_decoder_get_size(int, int)</code><br> * <i>native declaration : /tmp/opus_multistream.h:469</i> */ int opus_multistream_decoder_get_size(int streams, int coupled_streams); /** * Allocates and initializes a multistream decoder state.<br> * Call opus_multistream_decoder_destroy() to release<br> * this object when finished.<br> * @param Fs <tt>opus_int32</tt>: Sampling rate to decode at (in Hz).<br> * This must be one of 8000, 12000, 16000,<br> * 24000, or 48000.<br> * @param channels <tt>int</tt>: Number of channels to output.<br> * This must be at most 255.<br> * It may be different from the number of coded<br> * channels (<code>streams +<br> * coupled_streams</code>).<br> * @param streams <tt>int</tt>: The total number of streams coded in the<br> * input.<br> * This must be no more than 255.<br> * @param coupled_streams <tt>int</tt>: Number of streams to decode as coupled<br> * (2 channel) streams.<br> * This must be no larger than the total<br> * number of streams.<br> * Additionally, The total number of<br> * coded channels (<code>streams +<br> * coupled_streams</code>) must be no<br> * more than 255.<br> * @param[in] mapping <code>const unsigned char[channels]</code>: Mapping from<br> * coded channels to output channels, as described in<br> * @ref opus_multistream.<br> * @param[out] error <tt>int *</tt>: Returns #OPUS_OK on success, or an error<br> * code (see @ref opus_errorcodes) on<br> * failure.<br> * Original signature : <code>OpusMSDecoder* opus_multistream_decoder_create(opus_int32, int, int, int, const unsigned char*, int*)</code><br> * <i>native declaration : /tmp/opus_multistream.h:503</i> */ PointerByReference opus_multistream_decoder_create(int Fs, int channels, int streams, int coupled_streams, byte mapping[], IntBuffer error); /** * Intialize a previously allocated decoder state object.<br> * The memory pointed to by \a st must be at least the size returned by<br> * opus_multistream_encoder_get_size().<br> * This is intended for applications which use their own allocator instead of<br> * malloc.<br> * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL.<br> * @see opus_multistream_decoder_create<br> * @see opus_multistream_deocder_get_size<br> * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state to initialize.<br> * @param Fs <tt>opus_int32</tt>: Sampling rate to decode at (in Hz).<br> * This must be one of 8000, 12000, 16000,<br> * 24000, or 48000.<br> * @param channels <tt>int</tt>: Number of channels to output.<br> * This must be at most 255.<br> * It may be different from the number of coded<br> * channels (<code>streams +<br> * coupled_streams</code>).<br> * @param streams <tt>int</tt>: The total number of streams coded in the<br> * input.<br> * This must be no more than 255.<br> * @param coupled_streams <tt>int</tt>: Number of streams to decode as coupled<br> * (2 channel) streams.<br> * This must be no larger than the total<br> * number of streams.<br> * Additionally, The total number of<br> * coded channels (<code>streams +<br> * coupled_streams</code>) must be no<br> * more than 255.<br> * @param[in] mapping <code>const unsigned char[channels]</code>: Mapping from<br> * coded channels to output channels, as described in<br> * @ref opus_multistream.<br> * @returns #OPUS_OK on success, or an error code (see @ref opus_errorcodes)<br> * on failure.<br> * Original signature : <code>int opus_multistream_decoder_init(OpusMSDecoder*, opus_int32, int, int, int, const unsigned char*)</code><br> * <i>native declaration : /tmp/opus_multistream.h:546</i> */ int opus_multistream_decoder_init(PointerByReference st, int Fs, int channels, int streams, int coupled_streams, byte mapping[]); /** * Intialize a previously allocated decoder state object.<br> * The memory pointed to by \a st must be at least the size returned by<br> * opus_multistream_encoder_get_size().<br> * This is intended for applications which use their own allocator instead of<br> * malloc.<br> * To reset a previously initialized state, use the #OPUS_RESET_STATE CTL.<br> * @see opus_multistream_decoder_create<br> * @see opus_multistream_deocder_get_size<br> * @param st <tt>OpusMSEncoder*</tt>: Multistream encoder state to initialize.<br> * @param Fs <tt>opus_int32</tt>: Sampling rate to decode at (in Hz).<br> * This must be one of 8000, 12000, 16000,<br> * 24000, or 48000.<br> * @param channels <tt>int</tt>: Number of channels to output.<br> * This must be at most 255.<br> * It may be different from the number of coded<br> * channels (<code>streams +<br> * coupled_streams</code>).<br> * @param streams <tt>int</tt>: The total number of streams coded in the<br> * input.<br> * This must be no more than 255.<br> * @param coupled_streams <tt>int</tt>: Number of streams to decode as coupled<br> * (2 channel) streams.<br> * This must be no larger than the total<br> * number of streams.<br> * Additionally, The total number of<br> * coded channels (<code>streams +<br> * coupled_streams</code>) must be no<br> * more than 255.<br> * @param[in] mapping <code>const unsigned char[channels]</code>: Mapping from<br> * coded channels to output channels, as described in<br> * @ref opus_multistream.<br> * @returns #OPUS_OK on success, or an error code (see @ref opus_errorcodes)<br> * on failure.<br> * Original signature : <code>int opus_multistream_decoder_init(OpusMSDecoder*, opus_int32, int, int, int, const unsigned char*)</code><br> * <i>native declaration : /tmp/opus_multistream.h:546</i> */ int opus_multistream_decoder_init(PointerByReference st, int Fs, int channels, int streams, int coupled_streams, Pointer mapping); /** * Decode a multistream Opus packet.<br> * @param st <tt>OpusMSDecoder*</tt>: Multistream decoder state.<br> * @param[in] data <tt>const unsigned char*</tt>: Input payload.<br> * Use a <code>NULL</code><br> * pointer to indicate packet<br> * loss.<br> * @param len <tt>opus_int32</tt>: Number of bytes in payload.<br> * @param[out] pcm <tt>opus_int16*</tt>: Output signal, with interleaved<br> * samples.<br> * This must contain room for<br> * <code>frame_size*channels</code><br> * samples.<br> * @param frame_size <tt>int</tt>: The number of samples per channel of<br> * available space in \a pcm.<br> * If this is less than the maximum packet duration<br> * (120 ms; 5760 for 48kHz), this function will not be capable<br> * of decoding some packets. In the case of PLC (data==NULL)<br> * or FEC (decode_fec=1), then frame_size needs to be exactly<br> * the duration of audio that is missing, otherwise the<br> * decoder will not be in the optimal state to decode the<br> * next incoming packet. For the PLC and FEC cases, frame_size<br> * <b>must</b> be a multiple of 2.5 ms.<br> * @param decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band<br> * forward error correction data be decoded.<br> * If no such data is available, the frame is<br> * decoded as if it were lost.<br> * @returns Number of samples decoded on success or a negative error code<br> * (see @ref opus_errorcodes) on failure.<br> * Original signature : <code>int opus_multistream_decode(OpusMSDecoder*, const unsigned char*, opus_int32, opus_int16*, int, int)</code><br> * <i>native declaration : /tmp/opus_multistream.h:584</i> */ int opus_multistream_decode(PointerByReference st, byte data[], int len, ShortBuffer pcm, int frame_size, int decode_fec); /** * Decode a multistream Opus packet.<br> * @param st <tt>OpusMSDecoder*</tt>: Multistream decoder state.<br> * @param[in] data <tt>const unsigned char*</tt>: Input payload.<br> * Use a <code>NULL</code><br> * pointer to indicate packet<br> * loss.<br> * @param len <tt>opus_int32</tt>: Number of bytes in payload.<br> * @param[out] pcm <tt>opus_int16*</tt>: Output signal, with interleaved<br> * samples.<br> * This must contain room for<br> * <code>frame_size*channels</code><br> * samples.<br> * @param frame_size <tt>int</tt>: The number of samples per channel of<br> * available space in \a pcm.<br> * If this is less than the maximum packet duration<br> * (120 ms; 5760 for 48kHz), this function will not be capable<br> * of decoding some packets. In the case of PLC (data==NULL)<br> * or FEC (decode_fec=1), then frame_size needs to be exactly<br> * the duration of audio that is missing, otherwise the<br> * decoder will not be in the optimal state to decode the<br> * next incoming packet. For the PLC and FEC cases, frame_size<br> * <b>must</b> be a multiple of 2.5 ms.<br> * @param decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band<br> * forward error correction data be decoded.<br> * If no such data is available, the frame is<br> * decoded as if it were lost.<br> * @returns Number of samples decoded on success or a negative error code<br> * (see @ref opus_errorcodes) on failure.<br> * Original signature : <code>int opus_multistream_decode(OpusMSDecoder*, const unsigned char*, opus_int32, opus_int16*, int, int)</code><br> * <i>native declaration : /tmp/opus_multistream.h:584</i> */ int opus_multistream_decode(PointerByReference st, Pointer data, int len, ShortByReference pcm, int frame_size, int decode_fec); /** * Decode a multistream Opus packet with floating point output.<br> * @param st <tt>OpusMSDecoder*</tt>: Multistream decoder state.<br> * @param[in] data <tt>const unsigned char*</tt>: Input payload.<br> * Use a <code>NULL</code><br> * pointer to indicate packet<br> * loss.<br> * @param len <tt>opus_int32</tt>: Number of bytes in payload.<br> * @param[out] pcm <tt>opus_int16*</tt>: Output signal, with interleaved<br> * samples.<br> * This must contain room for<br> * <code>frame_size*channels</code><br> * samples.<br> * @param frame_size <tt>int</tt>: The number of samples per channel of<br> * available space in \a pcm.<br> * If this is less than the maximum packet duration<br> * (120 ms; 5760 for 48kHz), this function will not be capable<br> * of decoding some packets. In the case of PLC (data==NULL)<br> * or FEC (decode_fec=1), then frame_size needs to be exactly<br> * the duration of audio that is missing, otherwise the<br> * decoder will not be in the optimal state to decode the<br> * next incoming packet. For the PLC and FEC cases, frame_size<br> * <b>must</b> be a multiple of 2.5 ms.<br> * @param decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band<br> * forward error correction data be decoded.<br> * If no such data is available, the frame is<br> * decoded as if it were lost.<br> * @returns Number of samples decoded on success or a negative error code<br> * (see @ref opus_errorcodes) on failure.<br> * Original signature : <code>int opus_multistream_decode_float(OpusMSDecoder*, const unsigned char*, opus_int32, float*, int, int)</code><br> * <i>native declaration : /tmp/opus_multistream.h:622</i> */ int opus_multistream_decode_float(PointerByReference st, byte data[], int len, FloatBuffer pcm, int frame_size, int decode_fec); /** * Decode a multistream Opus packet with floating point output.<br> * @param st <tt>OpusMSDecoder*</tt>: Multistream decoder state.<br> * @param[in] data <tt>const unsigned char*</tt>: Input payload.<br> * Use a <code>NULL</code><br> * pointer to indicate packet<br> * loss.<br> * @param len <tt>opus_int32</tt>: Number of bytes in payload.<br> * @param[out] pcm <tt>opus_int16*</tt>: Output signal, with interleaved<br> * samples.<br> * This must contain room for<br> * <code>frame_size*channels</code><br> * samples.<br> * @param frame_size <tt>int</tt>: The number of samples per channel of<br> * available space in \a pcm.<br> * If this is less than the maximum packet duration<br> * (120 ms; 5760 for 48kHz), this function will not be capable<br> * of decoding some packets. In the case of PLC (data==NULL)<br> * or FEC (decode_fec=1), then frame_size needs to be exactly<br> * the duration of audio that is missing, otherwise the<br> * decoder will not be in the optimal state to decode the<br> * next incoming packet. For the PLC and FEC cases, frame_size<br> * <b>must</b> be a multiple of 2.5 ms.<br> * @param decode_fec <tt>int</tt>: Flag (0 or 1) to request that any in-band<br> * forward error correction data be decoded.<br> * If no such data is available, the frame is<br> * decoded as if it were lost.<br> * @returns Number of samples decoded on success or a negative error code<br> * (see @ref opus_errorcodes) on failure.<br> * Original signature : <code>int opus_multistream_decode_float(OpusMSDecoder*, const unsigned char*, opus_int32, float*, int, int)</code><br> * <i>native declaration : /tmp/opus_multistream.h:622</i> */ int opus_multistream_decode_float(PointerByReference st, Pointer data, int len, FloatByReference pcm, int frame_size, int decode_fec); /** * Perform a CTL function on a multistream Opus decoder.<br> * * Generally the request and subsequent arguments are generated by a<br> * convenience macro.<br> * @param st <tt>OpusMSDecoder*</tt>: Multistream decoder state.<br> * @param request This and all remaining parameters should be replaced by one<br> * of the convenience macros in @ref opus_genericctls,<br> * @ref opus_decoderctls, or @ref opus_multistream_ctls.<br> * @see opus_genericctls<br> * @see opus_decoderctls<br> * @see opus_multistream_ctls<br> * Original signature : <code>int opus_multistream_decoder_ctl(OpusMSDecoder*, int, null)</code><br> * <i>native declaration : /tmp/opus_multistream.h:643</i> */ int opus_multistream_decoder_ctl(PointerByReference st, int request, Object... varargs); /** * Frees an <code>OpusMSDecoder</code> allocated by<br> * opus_multistream_decoder_create().<br> * @param st <tt>OpusMSDecoder</tt>: Multistream decoder state to be freed.<br> * Original signature : <code>void opus_multistream_decoder_destroy(OpusMSDecoder*)</code><br> * <i>native declaration : /tmp/opus_multistream.h:649</i> */ void opus_multistream_decoder_destroy(PointerByReference st); public static class OpusMSEncoder extends PointerType { public OpusMSEncoder(Pointer address) { super(address); } public OpusMSEncoder() { super(); } }; public static class OpusMSDecoder extends PointerType { public OpusMSDecoder(Pointer address) { super(address); } public OpusMSDecoder() { super(); } }; // ******************** Custom Support /** * Creates a new mode struct. This will be passed to an encoder or<br> * decoder. The mode MUST NOT BE DESTROYED until the encoders and<br> * decoders that use it are destroyed as well.<br> * @param [in] Fs <tt>int</tt>: Sampling rate (8000 to 96000 Hz)<br> * @param [in] frame_size <tt>int</tt>: Number of samples (per channel) to encode in each<br> * packet (64 - 1024, prime factorization must contain zero or more 2s, 3s, or 5s and no other primes)<br> * @param [out] error <tt>int*</tt>: Returned error code (if NULL, no error will be returned)<br> * @return A newly created mode<br> * Original signature : <code>OpusCustomMode* opus_custom_mode_create(opus_int32, int, int*)</code><br> * <i>native declaration : /tmp/opus_custom.h:120</i> */ PointerByReference opus_custom_mode_create(int Fs, int frame_size, IntBuffer error); /** * Destroys a mode struct. Only call this after all encoders and<br> * decoders using this mode are destroyed as well.<br> * @param [in] mode <tt>OpusCustomMode*</tt>: Mode to be freed.<br> * Original signature : <code>void opus_custom_mode_destroy(OpusCustomMode*)</code><br> * <i>native declaration : /tmp/opus_custom.h:126</i> */ void opus_custom_mode_destroy(PointerByReference mode); /** * Gets the size of an OpusCustomEncoder structure.<br> * @param [in] mode <tt>OpusCustomMode *</tt>: Mode configuration<br> * @param [in] channels <tt>int</tt>: Number of channels<br> * @returns size<br> * Original signature : <code>int opus_custom_encoder_get_size(const OpusCustomMode*, int)</code><br> * <i>native declaration : /tmp/opus_custom.h:137</i> */ int opus_custom_encoder_get_size(PointerByReference mode, int channels); /** * Creates a new encoder state. Each stream needs its own encoder<br> * state (can't be shared across simultaneous streams).<br> * @param [in] mode <tt>OpusCustomMode*</tt>: Contains all the information about the characteristics of<br> * the stream (must be the same characteristics as used for the<br> * decoder)<br> * @param [in] channels <tt>int</tt>: Number of channels<br> * @param [out] error <tt>int*</tt>: Returns an error code<br> * @return Newly created encoder state.<br> * Original signature : <code>OpusCustomEncoder* opus_custom_encoder_create(const OpusCustomMode*, int, int*)</code><br> * <i>native declaration : /tmp/opus_custom.h:173</i> */ PointerByReference opus_custom_encoder_create(PointerByReference mode, int channels, IntBuffer error); /** * Creates a new encoder state. Each stream needs its own encoder<br> * state (can't be shared across simultaneous streams).<br> * @param [in] mode <tt>OpusCustomMode*</tt>: Contains all the information about the characteristics of<br> * the stream (must be the same characteristics as used for the<br> * decoder)<br> * @param [in] channels <tt>int</tt>: Number of channels<br> * @param [out] error <tt>int*</tt>: Returns an error code<br> * @return Newly created encoder state.<br> * Original signature : <code>OpusCustomEncoder* opus_custom_encoder_create(const OpusCustomMode*, int, int*)</code><br> * <i>native declaration : /tmp/opus_custom.h:173</i> */ PointerByReference opus_custom_encoder_create(PointerByReference mode, int channels, IntByReference error); /** * Destroys a an encoder state.<br> * @param[in] st <tt>OpusCustomEncoder*</tt>: State to be freed.<br> * Original signature : <code>void opus_custom_encoder_destroy(OpusCustomEncoder*)</code><br> * <i>native declaration : /tmp/opus_custom.h:183</i> */ void opus_custom_encoder_destroy(PointerByReference st); /** * Encodes a frame of audio.<br> * @param [in] st <tt>OpusCustomEncoder*</tt>: Encoder state<br> * @param [in] pcm <tt>float*</tt>: PCM audio in float format, with a normal range of +/-1.0.<br> * Samples with a range beyond +/-1.0 are supported but will<br> * be clipped by decoders using the integer API and should<br> * only be used if it is known that the far end supports<br> * extended dynamic range. There must be exactly<br> * frame_size samples per channel.<br> * @param [in] frame_size <tt>int</tt>: Number of samples per frame of input signal<br> * @param [out] compressed <tt>char *</tt>: The compressed data is written here. This may not alias pcm and must be at least maxCompressedBytes long.<br> * @param [in] maxCompressedBytes <tt>int</tt>: Maximum number of bytes to use for compressing the frame<br> * (can change from one frame to another)<br> * @return Number of bytes written to "compressed".<br> * If negative, an error has occurred (see error codes). It is IMPORTANT that<br> * the length returned be somehow transmitted to the decoder. Otherwise, no<br> * decoding is possible.<br> * Original signature : <code>int opus_custom_encode_float(OpusCustomEncoder*, const float*, int, unsigned char*, int)</code><br> * <i>native declaration : /tmp/opus_custom.h:202</i> */ int opus_custom_encode_float(PointerByReference st, float pcm[], int frame_size, ByteBuffer compressed, int maxCompressedBytes); /** * Encodes a frame of audio.<br> * @param [in] st <tt>OpusCustomEncoder*</tt>: Encoder state<br> * @param [in] pcm <tt>float*</tt>: PCM audio in float format, with a normal range of +/-1.0.<br> * Samples with a range beyond +/-1.0 are supported but will<br> * be clipped by decoders using the integer API and should<br> * only be used if it is known that the far end supports<br> * extended dynamic range. There must be exactly<br> * frame_size samples per channel.<br> * @param [in] frame_size <tt>int</tt>: Number of samples per frame of input signal<br> * @param [out] compressed <tt>char *</tt>: The compressed data is written here. This may not alias pcm and must be at least maxCompressedBytes long.<br> * @param [in] maxCompressedBytes <tt>int</tt>: Maximum number of bytes to use for compressing the frame<br> * (can change from one frame to another)<br> * @return Number of bytes written to "compressed".<br> * If negative, an error has occurred (see error codes). It is IMPORTANT that<br> * the length returned be somehow transmitted to the decoder. Otherwise, no<br> * decoding is possible.<br> * Original signature : <code>int opus_custom_encode_float(OpusCustomEncoder*, const float*, int, unsigned char*, int)</code><br> * <i>native declaration : /tmp/opus_custom.h:202</i> */ int opus_custom_encode_float(PointerByReference st, FloatByReference pcm, int frame_size, Pointer compressed, int maxCompressedBytes); /** * Encodes a frame of audio.<br> * @param [in] st <tt>OpusCustomEncoder*</tt>: Encoder state<br> * @param [in] pcm <tt>opus_int16*</tt>: PCM audio in signed 16-bit format (native endian).<br> * There must be exactly frame_size samples per channel.<br> * @param [in] frame_size <tt>int</tt>: Number of samples per frame of input signal<br> * @param [out] compressed <tt>char *</tt>: The compressed data is written here. This may not alias pcm and must be at least maxCompressedBytes long.<br> * @param [in] maxCompressedBytes <tt>int</tt>: Maximum number of bytes to use for compressing the frame<br> * (can change from one frame to another)<br> * @return Number of bytes written to "compressed".<br> * If negative, an error has occurred (see error codes). It is IMPORTANT that<br> * the length returned be somehow transmitted to the decoder. Otherwise, no<br> * decoding is possible.<br> * Original signature : <code>int opus_custom_encode(OpusCustomEncoder*, const opus_int16*, int, unsigned char*, int)</code><br> * <i>native declaration : /tmp/opus_custom.h:223</i> */ int opus_custom_encode(PointerByReference st, ShortBuffer pcm, int frame_size, ByteBuffer compressed, int maxCompressedBytes); /** * Encodes a frame of audio.<br> * @param [in] st <tt>OpusCustomEncoder*</tt>: Encoder state<br> * @param [in] pcm <tt>opus_int16*</tt>: PCM audio in signed 16-bit format (native endian).<br> * There must be exactly frame_size samples per channel.<br> * @param [in] frame_size <tt>int</tt>: Number of samples per frame of input signal<br> * @param [out] compressed <tt>char *</tt>: The compressed data is written here. This may not alias pcm and must be at least maxCompressedBytes long.<br> * @param [in] maxCompressedBytes <tt>int</tt>: Maximum number of bytes to use for compressing the frame<br> * (can change from one frame to another)<br> * @return Number of bytes written to "compressed".<br> * If negative, an error has occurred (see error codes). It is IMPORTANT that<br> * the length returned be somehow transmitted to the decoder. Otherwise, no<br> * decoding is possible.<br> * Original signature : <code>int opus_custom_encode(OpusCustomEncoder*, const opus_int16*, int, unsigned char*, int)</code><br> * <i>native declaration : /tmp/opus_custom.h:223</i> */ int opus_custom_encode(PointerByReference st, ShortByReference pcm, int frame_size, Pointer compressed, int maxCompressedBytes); /** * Perform a CTL function on an Opus custom encoder.<br> * * Generally the request and subsequent arguments are generated<br> * by a convenience macro.<br> * @see opus_encoderctls<br> * Original signature : <code>int opus_custom_encoder_ctl(OpusCustomEncoder*, int, null)</code><br> * <i>native declaration : /tmp/opus_custom.h:237</i> */ int opus_custom_encoder_ctl(PointerByReference st, int request, Object... varargs); /** * Gets the size of an OpusCustomDecoder structure.<br> * @param [in] mode <tt>OpusCustomMode *</tt>: Mode configuration<br> * @param [in] channels <tt>int</tt>: Number of channels<br> * @returns size<br> * Original signature : <code>int opus_custom_decoder_get_size(const OpusCustomMode*, int)</code><br> * <i>native declaration : /tmp/opus_custom.h:248</i> */ int opus_custom_decoder_get_size(PointerByReference mode, int channels); /** * Initializes a previously allocated decoder state<br> * The memory pointed to by st must be the size returned by opus_custom_decoder_get_size.<br> * This is intended for applications which use their own allocator instead of malloc.<br> * @see opus_custom_decoder_create(),opus_custom_decoder_get_size()<br> * To reset a previously initialized state use the OPUS_RESET_STATE CTL.<br> * @param [in] st <tt>OpusCustomDecoder*</tt>: Decoder state<br> * @param [in] mode <tt>OpusCustomMode *</tt>: Contains all the information about the characteristics of<br> * the stream (must be the same characteristics as used for the<br> * encoder)<br> * @param [in] channels <tt>int</tt>: Number of channels<br> * @return OPUS_OK Success or @ref opus_errorcodes<br> * Original signature : <code>int opus_custom_decoder_init(OpusCustomDecoder*, const OpusCustomMode*, int)</code><br> * <i>native declaration : /tmp/opus_custom.h:265</i> */ int opus_custom_decoder_init(PointerByReference st, PointerByReference mode, int channels); /** * Creates a new decoder state. Each stream needs its own decoder state (can't<br> * be shared across simultaneous streams).<br> * @param [in] mode <tt>OpusCustomMode</tt>: Contains all the information about the characteristics of the<br> * stream (must be the same characteristics as used for the encoder)<br> * @param [in] channels <tt>int</tt>: Number of channels<br> * @param [out] error <tt>int*</tt>: Returns an error code<br> * @return Newly created decoder state.<br> * Original signature : <code>OpusCustomDecoder* opus_custom_decoder_create(const OpusCustomMode*, int, int*)</code><br> * <i>native declaration : /tmp/opus_custom.h:282</i> */ PointerByReference opus_custom_decoder_create(PointerByReference mode, int channels, IntBuffer error); /** * Creates a new decoder state. Each stream needs its own decoder state (can't<br> * be shared across simultaneous streams).<br> * @param [in] mode <tt>OpusCustomMode</tt>: Contains all the information about the characteristics of the<br> * stream (must be the same characteristics as used for the encoder)<br> * @param [in] channels <tt>int</tt>: Number of channels<br> * @param [out] error <tt>int*</tt>: Returns an error code<br> * @return Newly created decoder state.<br> * Original signature : <code>OpusCustomDecoder* opus_custom_decoder_create(const OpusCustomMode*, int, int*)</code><br> * <i>native declaration : /tmp/opus_custom.h:282</i> */ PointerByReference opus_custom_decoder_create(PointerByReference mode, int channels, IntByReference error); /** * Destroys a an decoder state.<br> * @param[in] st <tt>OpusCustomDecoder*</tt>: State to be freed.<br> * Original signature : <code>void opus_custom_decoder_destroy(OpusCustomDecoder*)</code><br> * <i>native declaration : /tmp/opus_custom.h:291</i> */ void opus_custom_decoder_destroy(PointerByReference st); /** * Decode an opus custom frame with floating point output<br> * @param [in] st <tt>OpusCustomDecoder*</tt>: Decoder state<br> * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss<br> * @param [in] len <tt>int</tt>: Number of bytes in payload<br> * @param [out] pcm <tt>float*</tt>: Output signal (interleaved if 2 channels). length<br> * is frame_size*channels*sizeof(float)<br> * @param [in] frame_size Number of samples per channel of available space in *pcm.<br> * @returns Number of decoded samples or @ref opus_errorcodes<br> * Original signature : <code>int opus_custom_decode_float(OpusCustomDecoder*, const unsigned char*, int, float*, int)</code><br> * <i>native declaration : /tmp/opus_custom.h:302</i> */ int opus_custom_decode_float(PointerByReference st, byte data[], int len, FloatBuffer pcm, int frame_size); /** * Decode an opus custom frame with floating point output<br> * @param [in] st <tt>OpusCustomDecoder*</tt>: Decoder state<br> * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss<br> * @param [in] len <tt>int</tt>: Number of bytes in payload<br> * @param [out] pcm <tt>float*</tt>: Output signal (interleaved if 2 channels). length<br> * is frame_size*channels*sizeof(float)<br> * @param [in] frame_size Number of samples per channel of available space in *pcm.<br> * @returns Number of decoded samples or @ref opus_errorcodes<br> * Original signature : <code>int opus_custom_decode_float(OpusCustomDecoder*, const unsigned char*, int, float*, int)</code><br> * <i>native declaration : /tmp/opus_custom.h:302</i> */ int opus_custom_decode_float(PointerByReference st, Pointer data, int len, FloatByReference pcm, int frame_size); /** * Decode an opus custom frame<br> * @param [in] st <tt>OpusCustomDecoder*</tt>: Decoder state<br> * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss<br> * @param [in] len <tt>int</tt>: Number of bytes in payload<br> * @param [out] pcm <tt>opus_int16*</tt>: Output signal (interleaved if 2 channels). length<br> * is frame_size*channels*sizeof(opus_int16)<br> * @param [in] frame_size Number of samples per channel of available space in *pcm.<br> * @returns Number of decoded samples or @ref opus_errorcodes<br> * Original signature : <code>int opus_custom_decode(OpusCustomDecoder*, const unsigned char*, int, opus_int16*, int)</code><br> * <i>native declaration : /tmp/opus_custom.h:319</i> */ int opus_custom_decode(PointerByReference st, byte data[], int len, ShortBuffer pcm, int frame_size); /** * Decode an opus custom frame<br> * @param [in] st <tt>OpusCustomDecoder*</tt>: Decoder state<br> * @param [in] data <tt>char*</tt>: Input payload. Use a NULL pointer to indicate packet loss<br> * @param [in] len <tt>int</tt>: Number of bytes in payload<br> * @param [out] pcm <tt>opus_int16*</tt>: Output signal (interleaved if 2 channels). length<br> * is frame_size*channels*sizeof(opus_int16)<br> * @param [in] frame_size Number of samples per channel of available space in *pcm.<br> * @returns Number of decoded samples or @ref opus_errorcodes<br> * Original signature : <code>int opus_custom_decode(OpusCustomDecoder*, const unsigned char*, int, opus_int16*, int)</code><br> * <i>native declaration : /tmp/opus_custom.h:319</i> */ int opus_custom_decode(PointerByReference st, Pointer data, int len, ShortByReference pcm, int frame_size); /** * Perform a CTL function on an Opus custom decoder.<br> * * Generally the request and subsequent arguments are generated<br> * by a convenience macro.<br> * @see opus_genericctls<br> * Original signature : <code>int opus_custom_decoder_ctl(OpusCustomDecoder*, int, null)</code><br> * <i>native declaration : /tmp/opus_custom.h:333</i> */ int opus_custom_decoder_ctl(PointerByReference st, int request, Object... varargs); public static class OpusCustomDecoder extends PointerType { public OpusCustomDecoder(Pointer address) { super(address); } public OpusCustomDecoder() { super(); } }; public static class OpusCustomEncoder extends PointerType { public OpusCustomEncoder(Pointer address) { super(address); } public OpusCustomEncoder() { super(); } }; public static class OpusCustomMode extends PointerType { public OpusCustomMode(Pointer address) { super(address); } public OpusCustomMode() { super(); } }; }
package samsungTest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class BOJ_21609_상어중학교 { private static int N,M, gr,gc,max, grain; private static int[][] map; private static int[][] dir = {{-1,0},{1,0},{0,-1},{0,1}}; private static boolean[][] visited; private static boolean[][] visited2; public static void main(String[] args) throws IOException{ // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); map = new int[N][N]; // 0 은 무지개 , -1은 돌 , -2는 빈칸으로 할것이다 for (int r = 0; r < N; r++) { st = new StringTokenizer(br.readLine()); for (int c = 0; c < N; c++) { map[r][c] = Integer.parseInt(st.nextToken()); } } int ans = 0; while(true) { visited = new boolean[N][N]; max = 0; gr = -1; gc = -1; grain = 0; // 가장 큰 블럭덩어리 찾기 findBlock(); // 종료 조건: 만약위의 블럭찾기를 한번도 하지 못했다면? if(max == 0) break; // 블럭제거하기 removeBlock(gr,gc); ans+=(max*max); // 중력 -> 회전 -> 중력 gravity(); rotate(); gravity(); } System.out.println(ans); } private static void findBlock() { for (int r = 0; r < N; r++) { for (int c = 0; c < N; c++) { // 방문한적 없고, 일반 블럭에 한에서만 bfs를 돌린다 if(!visited[r][c] && map[r][c] > 0) { bfs(r,c); } } } } // 4. 격자가 90도 반시계 방향으로 회전한다 private static void rotate() { int[][] mapClone = new int[N][N]; // 회전된걸 임시map에 넣어두고 , 그걸 다시 map으로 for (int r = 0; r < N; r++) { for (int c = 0; c < N; c++) { mapClone[r][c] = map[c][N-1-r]; } } for (int r = 0; r < N; r++) { for (int c = 0; c < N; c++) { map[r][c] = mapClone[r][c]; } } } // 3. 격자에 중력이 작용한다 private static void gravity() { Queue<Integer> queue = new LinkedList<>(); for (int c = 0; c < N; c++) { queue = new LinkedList<>(); for (int r = N-1; r >= 0; r--) { // 역순으로 빈칸이 아니라면 넣어둔다 if(map[r][c] != -2) { queue.offer(map[r][c]); } // 만약 돌맹이가 아니라면(블럭이라면) 싹비운다 if(map[r][c] >=0) { map[r][c] = -2; } } for (int r = N-1; r >= 0; r--) { // 큐가 비었다면, 더이상 넣어줄 블럭이없는것 if(queue.isEmpty()) break; // 빈칸이라면 넣어준다 if(queue.peek() != -1 && map[r][c] == -2) map[r][c] = queue.poll(); // 만약 넣어줄 블럭이 -1이라면, 만날때 까지 넘긴다 else if(queue.peek() == -1 && map[r][c] != -1) continue; // 만약 넣어줄 블럭이 -1이라면, -1을 만났다면 큐에서 빼주기만 한다 else if(queue.peek() == -1 && map[r][c] == -1) queue.poll(); } } } // 2. 1에서 찾은 블록 그룹의 모든 블록을 제거한다 // gr,gc를 넣어서 bfs를 돌리고 해당블럭그룹을 -2(빈칸)으로 바꿔준다 private static void removeBlock(int r, int c) { Queue<Pair> queue = new LinkedList<>(); queue.offer(new Pair(r,c)); int stand = map[r][c]; map[r][c] = -2; while(!queue.isEmpty()) { Pair p = queue.poll(); for (int i = 0; i < dir.length; i++) { int nr = dir[i][0] + p.r; int nc = dir[i][1] + p.c; if(isIn(nr,nc) && (map[nr][nc] == stand || map[nr][nc] == 0)){ queue.offer(new Pair(nr,nc)); map[nr][nc] = -2; } } } } // 1. 크기가 가장 큰 블록 그룹을 찾는다. private static void bfs(int r, int c) { // 해당위치에서의 그룹을 만들기위해 따로 방문처리를 만들어 사용한다 visited2 = new boolean[N][N]; Queue<Pair> queue = new LinkedList<>(); queue.offer(new Pair(r,c)); visited2[r][c] = true; visited[r][c] = true; // 현재 그룹에서의 블럭개수, 기준점, 무지개개수 int cnt = 1 , sr = r, sc = c , rain = 0; int stand = map[r][c]; while(!queue.isEmpty()) { Pair p = queue.poll(); for (int i = 0; i < dir.length; i++) { int nr = dir[i][0] + p.r; int nc = dir[i][1] + p.c; // 범위안에 있고, 방문하지 않은 점중에서 무지개 or 시작점의 색깔일 경우 그룹화 가능 if(isIn(nr,nc) && !visited2[nr][nc] && (map[nr][nc] == stand || map[nr][nc] == 0)){ cnt++; queue.offer(new Pair(nr,nc)); visited2[nr][nc] = true; visited[nr][nc] = true; if(map[nr][nc] ==0) rain++; // 기준블럭 찾기(무지개 블럭은 제외) else if(map[nr][nc] !=0) { // 작은행 if(sr> nr) { sr = nr; sc = nc; }else if(sr == nr) { // 작은열 if(sc > nc) { sr = nr; sc = nc; } } } } } } // cnt가 1 -> 블록그룹의 조건에 불충분할시 넘어간다 if(cnt == 1) return; // 블록그룹중에서 // 조건1. 가장 큰 블럭이면 if(max < cnt) { max = cnt; gr = sr; gc = sc; grain = rain; }else if(max == cnt) { // 조건 2. 무지개블럭이 많을것부터 if(grain < rain) { max = cnt; gr = sr; gc = sc; grain = rain; }else if(grain == rain) { // 조건3. 행이 큰것부터 if(gr < sr) { max = cnt; gr = sr; gc = sc; grain = rain; }else if(gr == sr) { // 조건. 열이 큰것부터 if(gc < sc) { max = cnt; gr = sr; gc = sc; grain = rain; } } } } } public static class Pair{ int r, c; public Pair(int r, int c) { super(); this.r = r; this.c = c; } } public static boolean isIn(int r, int c) { return r>=0 && c>=0 && r<N && c<N; } }
package com.kdp.wanandroidclient.ui.main; import android.content.Intent; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.widget.SearchView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.kdp.wanandroidclient.R; import com.kdp.wanandroidclient.application.AppContext; import com.kdp.wanandroidclient.bean.Article; import com.kdp.wanandroidclient.bean.Friend; import com.kdp.wanandroidclient.bean.Hotword; import com.kdp.wanandroidclient.common.Const; import com.kdp.wanandroidclient.event.Event; import com.kdp.wanandroidclient.inter.OnArticleListItemClickListener; import com.kdp.wanandroidclient.manager.UserInfoManager; import com.kdp.wanandroidclient.ui.adapter.ArticleListAdapter; import com.kdp.wanandroidclient.ui.adapter.BaseListAdapter; import com.kdp.wanandroidclient.ui.base.BaseAbListActivity; import com.kdp.wanandroidclient.ui.web.WebViewActivity; import com.kdp.wanandroidclient.utils.IntentUtils; import com.kdp.wanandroidclient.utils.ToastUtils; import com.zhy.view.flowlayout.FlowLayout; import com.zhy.view.flowlayout.TagAdapter; import com.zhy.view.flowlayout.TagFlowLayout; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * 搜索页面 * author: 康栋普 * date: 2018/4/5 */ public class SearchActivity extends BaseAbListActivity<SearchPresenter, Article> implements SearchContract.ISearchView, OnArticleListItemClickListener { private SearchView mSearchView; private SearchView.SearchAutoComplete searchAutoComplete; private View mHeaderView; private TagFlowLayout mKeywordTagLayout, mFriendTagLayout; private int position; private int id; private String keyword = ""; private List<Hotword> mHotwordDatas = new ArrayList<>(); private List<Friend> mFriendDatas = new ArrayList<>(); @Override protected boolean initToolbar() { mToolbar.setTitle(R.string.search); return true; } @Override protected View initHeaderView() { mHeaderView = LayoutInflater.from(this).inflate(R.layout.search_header, mRecyclerView, false); mKeywordTagLayout = mHeaderView.findViewById(R.id.keywordTaglayout); mFriendTagLayout = mHeaderView.findViewById(R.id.friendTaglayout); return mHeaderView; } //设置搜索的数据 @Override public void setData(List<Article> data) { mRecyclerView.removeHeaderView(); setRefreshEnable(true); setCanLoadMore(true); if (state != Const.PAGE_STATE.STATE_LOAD_MORE) mRecyclerView.scrollToPosition(0); mListData.addAll(data); } @Override public void showError() { super.showError(); setRefreshEnable(true); } @Override public String getKeyword() { return keyword; } @Override public int getArticleId() { return id; } //热搜关键词 @Override public void setHotwordData(final List<Hotword> mHotListDatas) { mHotwordDatas.clear(); mHotwordDatas.addAll(mHotListDatas); mKeywordTagLayout.setAdapter(new TagAdapter<Hotword>(mHotListDatas) { @Override public View getView(FlowLayout parent, int position, Hotword hotword) { TextView tagView = (TextView) LayoutInflater.from(SearchActivity.this).inflate(R.layout.item_search_tag, mKeywordTagLayout, false); tagView.setText(hotword.getName()); setTagTextColor(tagView); return tagView; } }); mKeywordTagLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() { @Override public boolean onTagClick(View view, int position, FlowLayout parent) { keyword = mHotListDatas.get(position).getName(); searchAutoComplete.setText(keyword); searchAutoComplete.setSelection(keyword.length()); mSearchView.setQuery(keyword, true); return false; } }); } //历史网站 @Override public void setFriendData(final List<Friend> mFriendListDatas) { mFriendDatas.clear(); mFriendDatas.addAll(mFriendListDatas); mFriendTagLayout.setAdapter(new TagAdapter<Friend>(mFriendDatas) { @Override public View getView(FlowLayout parent, int position, Friend friend) { TextView tagView = (TextView) LayoutInflater.from(SearchActivity.this).inflate(R.layout.item_search_tag, mFriendTagLayout, false); tagView.setText(friend.getName()); setTagTextColor(tagView); return tagView; } }); mFriendTagLayout.setOnTagClickListener( new TagFlowLayout.OnTagClickListener() { @Override public boolean onTagClick(View view, int position, FlowLayout parent) { Friend mFriend = mFriendListDatas.get(position); Article bean = new Article(); bean.setTitle(mFriend.getName()); bean.setLink(mFriend.getLink()); Intent intent = new Intent(SearchActivity.this, WebViewActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable(Const.BUNDLE_KEY.OBJ, bean); intent.putExtras(bundle); startActivity(intent); return false; } }); } //关键词颜色 private void setTagTextColor(TextView tagView) { int red, green, blue; Random mRandow = new Random(); red = mRandow.nextInt(255); green = mRandow.nextInt(255); blue = mRandow.nextInt(255); int color = Color.rgb(red, green, blue); tagView.setTextColor(color); } //SearchView相关设置 @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search_menu_setting, menu); MenuItem menuItem = menu.findItem(R.id.menu_search); //获取搜索框 mSearchView = (SearchView) menuItem.getActionView(); //设置搜索hint mSearchView.setQueryHint(getString(R.string.search_keyword)); mSearchView.onActionViewExpanded(); //去除搜索框背景 deleteSearchPlate(); searchAutoComplete = mSearchView.findViewById(R.id.search_src_text); searchAutoComplete.setHintTextColor(ContextCompat.getColor(this, R.color._60ffffff)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ImageView mCloseView = mSearchView.findViewById(R.id.search_close_btn); mCloseView.setBackground(ContextCompat.getDrawable(this, R.drawable.ripple_close)); } mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { keyword = query; refreshData(); return false; } @Override public boolean onQueryTextChange(String newText) { if (TextUtils.isEmpty(newText)) { keyword = newText; if (mHotwordDatas.size() == 0) loadTagDatas(); } return false; } }); return super.onCreateOptionsMenu(menu); } //去除SearchView的输入框默认背景 private void deleteSearchPlate() { try { Class<?> cla = mSearchView.getClass(); Field mSearchPlateField = cla.getDeclaredField("mSearchPlate"); mSearchPlateField.setAccessible(true); View searchPlate = (View) mSearchPlateField.get(mSearchView); searchPlate.setBackground(null); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } @Override protected SearchPresenter createPresenter() { return new SearchPresenter(); } @Override protected boolean isCanLoadMore() { return true; } @Override protected void loadDatas() { if (mSearchView == null) { loadTagDatas(); return; } loadArticleListDatas(); } private void loadTagDatas() { setRefreshEnable(false); setCanLoadMore(false); mListData.clear(); mRecyclerView.addHeaderView(mHeaderView); mListAdapter.notifyAllDatas(mListData, mRecyclerView); showContent(); mPresenter.getHotWord(); mPresenter.getFriend(); } private void loadArticleListDatas() { mHotwordDatas.clear(); mFriendDatas.clear(); mPresenter.search(); } @Override protected BaseListAdapter<Article> getListAdapter() { return new ArticleListAdapter(this, Const.LIST_TYPE.SEARCH); } @Override public void onItemClick(int position,Article bean) { Intent intent = new Intent(this, WebViewActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable(Const.BUNDLE_KEY.OBJ, bean); bundle.putString(Const.BUNDLE_KEY.TYPE, Const.EVENT_ACTION.SEARCH); intent.putExtras(bundle); startActivity(intent); } @Override public void onDeleteCollectClick(int position, int id, int originId) { } @Override public void collect(boolean isCollect, String result) { notifyItemData(isCollect, result); } private void notifyItemData(boolean isCollect, String result) { mListData.get(position).setCollect(isCollect); mListAdapter.notifyItemDataChanged(position, mRecyclerView); ToastUtils.showToast(AppContext.getContext(), result); } /** * 收藏 * @param position * @param id */ @Override public void onCollectClick(int position, int id) { if (!UserInfoManager.isLogin()) IntentUtils.goLogin(this); this.position = position; this.id = id; if (mListData.get(this.position).isCollect()) mPresenter.unCollectArticle(); else mPresenter.collectArticle(); } @Override protected String registerEvent() { return Const.EVENT_ACTION.SEARCH; } @Override protected void receiveEvent(Object object) { Event mEvent = (Event) object; if (mEvent.type == Event.Type.REFRESH_ITEM) { Article bean = (Article) mEvent.object; for (int i = 0; i < mListData.size(); i++) { if (bean.equals(mListData.get(i))) { position = i; notifyItemData(bean.isCollect(), getString(R.string.collect_success)); } } } else if (mEvent.type == Event.Type.REFRESH_LIST){ refreshData(); } } }
/** * */ package org.lucidant.springaop; import java.time.LocalDate; import java.time.Month; import org.aspectj.lang.annotation.Pointcut; import org.lucidant.springaop.model.MyPerformanceMonitorInterceptor; import org.lucidant.springaop.model.Person; import org.lucidant.springaop.model.PersonService; import org.springframework.aop.Advisor; import org.springframework.aop.aspectj.AspectJExpressionPointcut; import org.springframework.aop.interceptor.PerformanceMonitorInterceptor; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; /** * @author chrisfaulkner * */ @Configuration @EnableAspectJAutoProxy public class AopConfiguration { @Pointcut("execution(public String org.lucidant.springaop.model.PersonService.getFullName(..))") public void monitor() { } @Pointcut("execution(public int org.lucidant.springaop.model.PersonService.getAge(..))") public void myMonitor() { } @Bean public PerformanceMonitorInterceptor performanceMonitorInterceptor() { return new PerformanceMonitorInterceptor(true); } @Bean public Advisor performanceMonitorAdvisor() { final AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); pointcut.setExpression("org.lucidant.springaop.AopConfiguration.monitor()"); return new DefaultPointcutAdvisor(pointcut, performanceMonitorInterceptor()); } @Bean public Person person() { return new Person("John", "Smith", LocalDate.of(1980, Month.JANUARY, 12)); } @Bean public PersonService personService() { return new PersonService(); } @Bean public MyPerformanceMonitorInterceptor myPerformanceMonitorInterceptor() { return new MyPerformanceMonitorInterceptor(true); } @Bean public Advisor myPerformanceMonitorAdvisor() { final AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); pointcut.setExpression("org.lucidant.springaop.AopConfiguration.myMonitor()"); return new DefaultPointcutAdvisor(pointcut, myPerformanceMonitorInterceptor()); } }
package communicatorclient; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import communicatorshared.CommunicatorWebSocketMessage; import communicatorshared.CommunicatorWebSocketMessageOperation; import javax.websocket.*; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; // https://github.com/jetty-project/embedded-jetty-websocket-examples/tree/master/javax.websocket-example/src/main/java/org/eclipse/jetty/demo /** * Client-side implementation of abstract class Communicator using * WebSockets for communication. * * This code is based on the example code from: * https://github.com/jetty-project/embedded-jetty-websocket-examples/blob/ * master/javax.websocket-example/src/main/java/org/eclipse/jetty/ * demo/EventServerSocket.java * * @author Nico Kuijpers */ @ClientEndpoint public class CommunicatorClientWebSocket extends Communicator { // Singleton private static CommunicatorClientWebSocket instance = null; /** * The local websocket uri to connect to. */ private final String uri = "ws://localhost:8095/communicator/"; private Session session; private String message; private Gson gson = null; // Status of the webSocket client boolean isRunning = false; // Private constructor (singleton pattern) private CommunicatorClientWebSocket() { gson = new Gson(); } /** * Get singleton instance of this class. * Ensure that only one instance of this class is created. * @return instance of client web socket */ public static CommunicatorClientWebSocket getInstance() { if (instance == null) { System.out.println("[WebSocket Client create singleton instance]"); instance = new CommunicatorClientWebSocket(); } return instance; } /** * Start the connection. */ @Override public void start() { System.out.println("[WebSocket Client start connection]"); if (!isRunning) { startClient(); isRunning = true; } } @Override public void stop() { System.out.println("[WebSocket Client stop]"); if (isRunning) { stopClient(); isRunning = false; } } @Override public void sendDetails(String details) { CommunicatorWebSocketMessage message = new CommunicatorWebSocketMessage(); message.setDetails(details); message.setOperation(CommunicatorWebSocketMessageOperation.USERDETAIL); sendMessageToServer(message); } @Override public void sendMove(String position) { CommunicatorWebSocketMessage message = new CommunicatorWebSocketMessage(); message.setDetails(position); message.setOperation(CommunicatorWebSocketMessageOperation.MOVEMENT); sendMessageToServer(message); } @OnOpen public void onWebSocketConnect(Session session){ this.session = session; } @OnMessage public void onWebSocketText(String message, Session session){ this.message = message; processMessage(message); } @OnError public void onWebSocketError(Session session, Throwable cause) { } @OnClose public void onWebSocketClose(CloseReason reason){ session = null; } private void sendMessageToServer(CommunicatorWebSocketMessage message) { String jsonMessage = gson.toJson(message); // Use asynchronous communication session.getAsyncRemote().sendText(jsonMessage); } /** * Get the latest message received from the websocket communication. * @return The message from the websocket communication */ public String getMessage() { return message; } /** * Set the message, but no action is taken when the message is changed. * @param message the new message */ public void setMessage(String message) { this.message = message; } /** * Start a WebSocket client. */ private void startClient() { System.out.println("[WebSocket Client start]"); try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); container.connectToServer(this, new URI(uri)); } catch (IOException | URISyntaxException | DeploymentException ex) { // do something useful eventually ex.printStackTrace(); } } /** * Stop the client when it is running. */ private void stopClient(){ try { session.close(); } catch (IOException ex){ // do something useful eventually ex.printStackTrace(); } } // Process incoming json message private void processMessage(String jsonMessage) { if(jsonMessage.length() == 1) { this.setChanged(); this.notifyObservers(jsonMessage); return; } if(jsonMessage.equals("USERDETAILS")) { CommunicatorMessage commMessage = new CommunicatorMessage(); commMessage.setDetails("USERDETAILS"); this.setChanged(); this.notifyObservers(jsonMessage); return; } // Parse incoming message CommunicatorWebSocketMessage wsMessage; try { wsMessage = gson.fromJson(jsonMessage, CommunicatorWebSocketMessage.class); } catch (JsonSyntaxException ex) { System.out.println("[WebSocket Client ERROR: cannot parse Json message " + jsonMessage); return; } // Obtain content from message String details = wsMessage.getDetails(); if (details == null || "".equals(details)) { System.out.println("[WebSocket Client ERROR: message without content]"); return; } // Create instance of CommunicaterMessage for observers CommunicatorMessage commMessage = new CommunicatorMessage(); commMessage.setDetails(details); // Notify observers this.setChanged(); this.notifyObservers(commMessage); } }
package br.com.allerp.allbanks.entity.conta; import javax.persistence.Entity; import javax.persistence.Table; import br.com.allerp.allbanks.entity.GenericEntity; @Entity @Table(name = "EXTRATO_BANCARIO") public class ExtratoBancario extends GenericEntity { private static final long serialVersionUID = 4396459324533468341L; }
package com.clashwars.cwutils.events; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.messaging.PluginMessageListener; import com.clashwars.cwutils.CWUtils; public class PluginMessageEvents implements PluginMessageListener { private CWUtils cwu; public PluginMessageEvents(CWUtils cwu) { this.cwu = cwu; } @Override public void onPluginMessageReceived(String channel, Player player, byte[] message) { if (!channel.equalsIgnoreCase("CWBungee")) { return; } final DataInputStream in = new DataInputStream(new ByteArrayInputStream(message)); cwu.getServer().getScheduler().runTaskLater(cwu, new Runnable() { @Override public void run() { try { String ch = in.readUTF(); String s = ch.toLowerCase(); if (s.equals("queue")) { String uuid = in.readUTF().toString(); String type = in.readUTF(); String content = in.readUTF(); cwu.getQM().execute(UUID.fromString(uuid), type, content, false); } else if (s.equals("eventdata")) {// sender | event | arena | players | slots | status cwu.sendEventInfo(in.readUTF(), in.readUTF(), in.readUTF(), in.readUTF(), in.readUTF(), in.readUTF()); } } catch (Throwable e) { e.printStackTrace(); } } }, 5); } }
package naruter.com.outsourcing.dao; import naruter.com.outsourcing.vo.MemberInfo; public interface MeminfoDAO { public Integer loginSelect(MemberInfo memInfo); public Integer join(MemberInfo memInfo); //아이디 중복 조회 필요쓰 }
public class CalculateSalary { private int BaseSalary; private int ExtraHours; public CalculateSalary(int BaseSalary, int ExtraHours) { setBaseSalary(BaseSalary); setExtraHours(ExtraHours); } public int calculateSalary(int HourlyRate){ int totalSalary = getBaseSalary() + (getExtraHours() *HourlyRate); return totalSalary; } private int getExtraHours() { return ExtraHours; } public void setExtraHours(int X) { if (ExtraHours <= 0) throw new IllegalArgumentException("enter positive values"); ExtraHours = X; } private int getBaseSalary() { return BaseSalary; } public void setBaseSalary(int y) { BaseSalary = y; } } //public int CalculateMethod2(int BaseSalary, int ExtraHours, int HourlyRate){ //int result2 = BaseSalary+(ExtraHours*HourlyRate); //return result2; //} // The variable in this have scope only within this method ! So either we provide their values by creating object in Main method (No conditions can be applied though). // OR we can get their values from another method. For this, We need to make methods eg. here Getter/Setter! //Eg public void setMethod(int a); //Value = a; Now in this also, 'a' has scope only in setMethod. It is being used to give out a value ! Basically this is the value that we will provide to our variable! // So this variable just need to be defined in the class. That's it! // //Now one more twist is : When we create object of this class, we will pass values (arguments) in the object itself! These values will be taken by our parameters in CalculateMethod2. //the values will further be passed on to the methods (using these variables). //Methods carrying these values will have (type same as we want these values to be stored in). // then this method will pass these values out to a variable !that just needs to be defined in the class. Or we can say this is how we give value to a variable. // if this variable be used anywhere it will have that value we just defined above. // and we all this value defining by Main method !
package gui; import javax.swing.*; import map.Square; import java.awt.Dimension; import java.awt.Color; import java.util.Arrays; import javax.swing.border.*; import java.awt.*; import map.Background; public class Case extends JButton { /** * */ private static final long serialVersionUID = 1L; private int xCoord; private int yCoord; private ImageIcon icon; private Square square; public Case(int xCoord, int yCoord, Square square) { this.xCoord = xCoord; this.yCoord = yCoord; this.setPreferredSize(new Dimension(50,50)); int[] coordinates = new int[2]; coordinates[0] = xCoord; coordinates[1] = yCoord; this.setActionCommand(Arrays.toString(coordinates)); this.square = square; this.chooseBackground(square); this.chooseCharacterIcon(); } public int getXCoord() { return xCoord; } public int getYCoord() { return yCoord; } public void setXCoord(int x) { this.xCoord = x; } public void setYCoord(int y) { this.yCoord = y; } public Square getSquare() { return square; } public void chooseBackground (Square square) { // Ya du rififi dans background qui contient déjà le sprite? idk if (square.getBackground() != null) { Background background = square.getBackground(); this.setBackground(background.getColor()); } } public void chooseCharacterIcon () { if (square.getCharacter() != null) { this.icon = new ImageIcon("img/" + square.getCharacter().getSpriteLoc() + ".png"); this.setIcon(icon); } else { this.icon = null; this.setIcon(null); } this.revalidate(); this.repaint(); } public void showAsSelected() { this.setBorder(BorderFactory.createLineBorder(Color.black,3)); } public void showUnselected() { this.setBorder(BorderFactory.createLineBorder(Color.gray)); } public void showInRange() { this.setBorder(BorderFactory.createLineBorder(Color.red)); } public void showAsCurrentPLayer() { this.setBorder(BorderFactory.createLineBorder(Color.darkGray,3)); } }
package Sem2.HashTable; public class Main { public static void main(String[] args) { MyHashTable table = new MyHashTable(100); table.put("table", "стол"); String r = table.getK("table"); System.out.println(r); } }
package com.bingo.code.example.design.memento.module; /** * ����¼��խ�ӿڣ�û���κη������� */ public interface Memento { }
package com.nixsol.mahesh.model.response; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; public class FactResponse { @SerializedName("title") @Expose private String name; @SerializedName("rows") @Expose private ArrayList<Fact> factList; public FactResponse(String name, ArrayList<Fact> factList) { this.name = name; this.factList = factList; } public String getName() { return name; } public void setName(String name) { this.name = name; } public ArrayList<Fact> getFactList() { return factList; } public void setFactList(ArrayList<Fact> factList) { this.factList = factList; } }
package com.fundwit.sys.shikra.actuator; import org.springframework.stereotype.Service; import reactor.core.publisher.Mono; @Service public class ApplicationStatusManagerImpl implements ApplicationStatusManager{ // dataSourceCheck // mqCheck // redisCheck @Override public Mono<Boolean> isAlive() { return Mono.just(true); } @Override public Mono<Boolean> isReady() { return Mono.just(true); } }
/** * */ package com.cnk.travelogix.b2c.storefront.security; import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.servicelayer.session.SessionService; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import com.cnk.travelogix.b2c.facades.customer.B2cCustomerFacade; import com.cnk.travelogix.common.core.util.JsonUtil; /** * @author i322561 * */ public class AjaxAuthenticationFilter extends UsernamePasswordAuthenticationFilter { @Resource(name = "customerFacade") private B2cCustomerFacade customerFacade; @Resource(name = "sessionService") private SessionService sessionService; @Override protected void successfulAuthentication(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain, final Authentication authResult) throws IOException, ServletException { super.successfulAuthentication(request, response, null, authResult); if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) { final Map<String, String> message = new HashMap<String, String>(); message.put("success", "1"); final String userName = ((CustomerModel) sessionService.getAttribute("user")).getName(); message.put("userName", userName == null ? "" : userName); if (customerFacade.getUserActivationStatus(request.getParameter("j_username"))) { if (customerFacade.checkUserFirstLogin()) { message.put("firstLogin", "1"); } } else { message.put("redirect2Settings", "1"); } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(JsonUtil.toJson(message)); response.getWriter().flush(); } } @Override protected void unsuccessfulAuthentication(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException failed) throws IOException, ServletException { super.unsuccessfulAuthentication(request, response, failed); if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) { final Map<String, String> message = new HashMap<String, String>(); message.put("success", "0"); if (failed instanceof BadCredentialsException) { message.put("badCredential", "1"); message.put("userName", request.getParameter("j_username")); } else if (failed instanceof DisabledException) { customerFacade.sendAccountLockedInformingEmail(request.getParameter("j_username")); message.put("userName", request.getParameter("j_username")); message.put("userLocked", "1"); } response.setContentType("json"); response.getWriter().write(JsonUtil.toJson(message)); response.getWriter().flush(); } } }
/* * 文 件 名: UserStatusRestService.java * 描 述: UserStatusRestService.java * 时 间: 2013-6-27 */ package com.babyshow.rest.userstatus; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.babyshow.rest.RestService; import com.babyshow.rest.RestStaticConstant; import com.babyshow.user.bean.User; import com.babyshow.user.service.UserLoginLogService; import com.babyshow.user.service.UserService; /** * <一句话功能简述> * * @author ztc * @version [BABYSHOW V1R1C1, 2013-6-27] */ @Service public class UserStatusRestService extends RestService { @Autowired private UserService userService; @Autowired private UserLoginLogService userLoginLogService; /** * * 处理用户状态Rest请求 * * @param userStatusRequest * @return */ public UserStatusResponse handleUserStatus(UserStatusRequest userStatusRequest) { UserStatusResponse userStatus = new UserStatusResponse(); String deviceID = userStatusRequest.getDevice_id(); if(userService.isUserExistByDeviceID(deviceID)) { userStatus.setUserStatus(RestStaticConstant.USER_LOGIN_STATUS_NONFISRT); // 设置用户登录信息 User user = this.userService.findUserByDeviceID(deviceID); Date date = new Date(); this.userLoginLogService.insertUserLoginTime(user.getUserCode(), date); } else { userService.addNewUserByDeviceID(deviceID); User user = userService.findUserByDeviceID(deviceID); int userNum = user.getRegNum(); userStatus.setUserStatus(RestStaticConstant.USER_LOGIN_STATUS_FISRT); userStatus.setUserNum(userNum); // 设置用户首次登录信息 Date date = new Date(); this.userLoginLogService.insertUserLoginTime(user.getUserCode(), date); } return userStatus; } }
package com.bowlong.concurrent.async; import java.util.concurrent.Callable; public abstract class CallableExcept implements Callable<Exception> { @Override public Exception call() throws Exception { try { exec(); } catch (Exception e) { return e; } return null; } public abstract void exec() throws Exception; }
import com.dto.BookDto; import com.service.BookApiService; import com.util.JDBCUtil; import org.junit.Assert; import org.junit.Test; import java.math.BigDecimal; import java.sql.SQLException; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * Created by ville on 2017/3/25. */ public class BookApiServiceTest { @Test public void createTest() throws SQLException { BookApiService bookService = new BookApiService(); BookDto book = new BookDto(); book.setId(transferDate(new Date())); book.setCreateDate(new Timestamp(System.currentTimeMillis())); book.setName("九阳神功"); book.setPrice(new BigDecimal(99)); //开启事务 JDBCUtil.beginTransaction(); book = bookService.create(book); Assert.assertNotNull(book); //提交 JDBCUtil.commitTransaction(); } @Test public void queryTest() { BookApiService bookService = new BookApiService(); List<BookDto> bookList = bookService.query(); bookList.forEach(System.out::println); } @Test public void queryOneByTest() { BookApiService bookService = new BookApiService(); BookDto book = bookService.queryOneById("20171122030043"); System.out.println(book); } @Test public void modifyByIdTest() throws SQLException { BookDto book = new BookDto(); book.setId("20171122030043"); book.setCreateDate(new Timestamp(System.currentTimeMillis())); book.setName("Three Days to See"); book.setPrice(new BigDecimal(35)); BookApiService bookService = new BookApiService(); //开启事务 JDBCUtil.beginTransaction(); if (bookService.modifyById(book) <= 0) throw new AssertionError(); JDBCUtil.commitTransaction(); } @Test public void deleteByIdTest() throws SQLException { BookApiService bookService = new BookApiService(); //开启事务 JDBCUtil.beginTransaction(); if (bookService.deleteById("20171122030043") <= 0) { throw new AssertionError(); } } private static String transferDate(Date date) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss"); return dateFormat.format(date); } }
package com.walkerwang; import java.io.IOException; import java.io.ObjectInputStream; import java.net.ServerSocket; import java.net.Socket; public class ServerClient { public static void main(String[] args) throws Exception { @SuppressWarnings("resource") ServerSocket server = new ServerSocket(1118); try { Socket socket = server.accept(); ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); Parameters param = (Parameters)ois.readObject(); System.out.println(param.getN()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package TIterator; public interface Iterator { Object next(); boolean hasNext(); } class ConcreteIterator implements Iterator { IterableCollection collection; int index; public ConcreteIterator(IterableCollection collection) { this.collection = collection; } @Override public Object next() { Object o = collection.getInternalArray()[index++]; return o; } @Override public boolean hasNext() { if (index < collection.getInternalArray().length) return true; else return false; } }
package com.nmhung.model; import lombok.Data; @Data public class UserModel { private Integer id; private String username; private String password; private String fullname; private String email; private RoleModel role; public UserModel() { } public UserModel(Integer id, String username, String password, String fullname, String email) { this.id = id; this.username = username; this.password = password; this.fullname = fullname; this.email = email; } }
package edu.kit.pse.osip.core.utils.formatting; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * JUnit test class for FormatChecker.java. * * @author Maximilian Schwarzmann * @version 1.1 */ public class FormattingTest { /** * Tests normal port. */ @Test public void testPortNormal() { assertTrue(FormatChecker.isValidPort("2000")); } /** * Tests port that is too big. */ @Test public void testPortOverflow() { assertFalse(FormatChecker.isValidPort("70000")); } /** * Tests port with non-digits. */ @Test public void testPortFormat() { assertFalse(FormatChecker.isValidPort("20b10")); } /** * Tests port that is too small. */ @Test public void testPortUnderflow() { assertFalse(FormatChecker.isValidPort("0")); } /** * Tests a normal percentage. */ @Test public void testValidPercentage() { String input = "55"; assertTrue(FormatChecker.checkPercentage(input)); } /** * Tests inputs that are not percentages. */ @Test public void testInvalidPercentages() { assertFalse(FormatChecker.checkPercentage("a1")); assertFalse(FormatChecker.checkPercentage("-1")); assertFalse(FormatChecker.checkPercentage("120")); } /** * Tests valid IP address. */ @Test public void testHostIp() { assertTrue(FormatChecker.checkHost("66.249.69.000")); } /** * Tests invalid host names. */ @Test public void testInvalidHostName() { assertFalse(FormatChecker.checkHost("\\")); assertFalse(FormatChecker.checkHost("&/(&")); } /** * Tests null port. */ @Test(expected = NullPointerException.class) public void testNullPort() { FormatChecker.isValidPort(null); } /** * Tests null host. */ @Test public void testNullHost() { assertFalse(FormatChecker.checkHost(null)); } /** * Tests null percentage. */ @Test public void testNullPercentage() { assertFalse(FormatChecker.checkPercentage(null)); } }
package mymodules; import dagger.Module; import dagger.Provides; import mInterface.Lognview; import mybase.Baseview; /** * Created by 地地 on 2017/12/11. * 邮箱:461211527@qq.com. */ @Module public class Guanzhumoudule { private Baseview baseview; public Guanzhumoudule(Baseview baseview) { this.baseview = baseview; } @Provides Baseview provideMainView() { return baseview; } }
/* Given a linked list, rotate the list to the right by k places, where k is non-negative. Example 1: Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULL Example 2: Input: 0->1->2->NULL, k = 4 Output: 2->0->1->NULL Explanation: rotate 1 steps to the right: 2->0->1->NULL rotate 2 steps to the right: 1->2->0->NULL rotate 3 steps to the right: 0->1->2->NULL rotate 4 steps to the right: 2->0->1->NULL */ package leetcode_linkedlist; public class Question_61 { public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public ListNode rotateRight(ListNode head, int k) { if (head == null) { return null; } ListNode newHead = head; ListNode newTail = null; ListNode preTail = null; int size = 0; while(newHead != null) { size++; newHead = newHead.next; } k = k % size; int count = 0; while (count < k) { while (head != null) { if (newHead == null) { newHead = head; } if (head.next != null && head.next.next == null) { newTail = head.next; preTail = head; } head = head.next; } if (preTail != null) { preTail.next = null; } else { break; } if (newTail != null) { newTail.next = newHead; } else { break; } newHead = newTail; head = newHead; count++; } if (newHead == null) { return head; } return newHead; } public void solve() { ListNode root = new ListNode(1); root.next = new ListNode(2); root.next.next = new ListNode(3); //root.next.next.next = new ListNode(4); //root.next.next.next.next = new ListNode(5); ListNode result = rotateRight(root, 2000000000); while (result != null) { System.out.print(result.val); result = result.next; } } }
package com.hcl.dmu.demand.vo; public class DemandTrakerVo { private int demandId; private String Sno; private String streamName; private String projectName; private String skill; private int count; private int fullfilled; private int gap; private DemandStreamVo demandStreamVo; public String getSno() { return Sno; } public void setSno(String sno) { Sno = sno; } public int getDemandId() { return demandId; } public void setDemandId(int demandId) { this.demandId = demandId; } public String getStreamName() { return streamName; } public void setStreamName(String streamName) { this.streamName = streamName; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getSkill() { return skill; } public void setSkill(String skill) { this.skill = skill; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getFullfilled() { return fullfilled; } public void setFullfilled(int fullfilled) { this.fullfilled = fullfilled; } public int getGap() { return gap; } public void setGap(int gap) { this.gap = gap; } public DemandStreamVo getDemandStreamVo() { return demandStreamVo; } public void setDemandStreamVo(DemandStreamVo demandStreamVo) { this.demandStreamVo = demandStreamVo; } @Override public String toString() { return "DemandTrakerVo [Sno=" + Sno + ", demandId=" + demandId + ", streamName=" + streamName + ", projectName=" + projectName + ", skill=" + skill + ", count=" + count + ", fullfilled=" + fullfilled + ", gap=" + gap + ", demandStreamVo=" + demandStreamVo + "]"; } }
package com.app.artclass.database; import android.os.Build; import androidx.annotation.RequiresApi; import androidx.room.TypeConverter; import com.app.artclass.WEEKDAY; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.text.DecimalFormat; import java.text.NumberFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.List; @RequiresApi(api = Build.VERSION_CODES.O) public class DatabaseConverters { static Gson gson = new Gson(); public static DateTimeFormatter getTimeFormatter() { return timeFormatter; } public static DateTimeFormatter getDateFormatter() { return dateFormatter; } public static DateTimeFormatter getDateTimeFormatter() { return dateTimeFormatter; } private static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm"); private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy-HH:mm"); private static NumberFormat moneyFormat = new DecimalFormat("##'₴'"); public static NumberFormat getMoneyFormat() { return moneyFormat; } @TypeConverter public String fromLocalDate(LocalDate date){ return date.format(dateFormatter); } @TypeConverter public LocalDate toLocalDate(String date){ return LocalDate.parse(date,dateFormatter); } @TypeConverter public String fromLocalTime(LocalTime time){ return time.format(timeFormatter); } @TypeConverter public LocalTime toLocalTime(String time){ return LocalTime.parse(time,timeFormatter); } @TypeConverter public String fromLocalDateTime(LocalDateTime dateTime){ return dateTime.format(dateTimeFormatter); } @TypeConverter public LocalDateTime toLocalDateTime(String dateTime){ return LocalDateTime.parse(dateTime,dateTimeFormatter); } // list converter @TypeConverter public List<String> stringToStrList(String data) { if (data == null) { return Collections.emptyList(); } Type listType = new TypeToken<List<String>>() {}.getType(); return gson.fromJson(data, listType); } @TypeConverter public String strListToString(List<String> list) { return gson.toJson(list); } @TypeConverter public String weekdayToString(WEEKDAY weekday){ return weekday.toString(); } @TypeConverter public WEEKDAY stringToWeekday(String weekdayStr){ return WEEKDAY.valueOf(weekdayStr); } }
package ru.otus.api.service; import ru.otus.api.model.Accaunt; import java.util.Optional; public interface DBServiceAccaunt { long saveAccaunt(Accaunt accaunt); Optional<Accaunt> getAccaunt(long id); }
package global; public final class ConstantVars { private static RID globalRID; private static int readCount; private static int writeCount; private static int allocateCount; public static final void setGlobalRID(RID rid){ if(globalRID==null) globalRID = new RID(); globalRID.slotNo = rid.slotNo; globalRID.pageNo = rid.pageNo; } public static final RID getGlobalRID(){ return globalRID; } public static final void incrementReadCount(){ readCount++; } public static final int getReadCount(){ return readCount; } public static final void incrementWriteCount(){ writeCount++; } public static final int getWriteCount(){ return writeCount; } }
package com.tieto.javabootcamp.service; import com.tieto.javabootcamp.model.text.Comment; import com.tieto.javabootcamp.model.text.PrivateMessage; public interface PrivateMessageService { public PrivateMessage saveAritcle(PrivateMessage article); public Iterable<PrivateMessage> listArticles(); }
package br.com.treinarminas.academico; public class PrimeiraClasse { public static void main(String[] args) { System.out.println("teste de classe"); System.out.println("teste de git"); } }
package include.linguistics.chinese; import include.Tuple2; import chinese.pos.CTag; public final class CTagCSetOfLabels extends Tuple2<CTag, CSetOfLabels> { public CTagCSetOfLabels() { super(); } public CTagCSetOfLabels(final CTagCSetOfLabels tag_tagset) { refer(tag_tagset.m_object1, tag_tagset.m_object2); } public CTagCSetOfLabels(final CTag tag, final CSetOfLabels tagset) { super(tag, tagset); } @Override public CTag create_object1(final CTag a) { return a; } @Override public CSetOfLabels create_object2(final CSetOfLabels b) { return b; } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.common.function; /** * Validator is a Functional Interface that consumes an object to be validated. * @param <T> the type of the input to be validated. */ @FunctionalInterface public interface Validator<T> { /** * Method to perform validation on a given object. * @param validatee the inpected object being validated. */ void validate(T validatee); }
package xframe.example.pattern.chainofresp; public abstract class Handler { protected Handler nextor; public Handler getNextor() { return nextor; } public void setNextor(Handler nextor) { this.nextor = nextor; } //首先调用自身的handle 方法,在调用next方法 public abstract void handle(Request<?> request, Response resp); public void next(Request request, Response resp){ if(nextor!=null){ nextor.handle(request,resp); }else{ System.out.println("chain of responsibility end!"); return; } } }
package com.library.bexam.dao; import com.library.bexam.common.pojo.model.Result; import com.library.bexam.entity.ClassEntity; import com.library.bexam.form.ClassForm; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 班级操作数据库类 * @author caoqian * @date 20181213 */ public interface ClassDao { /** * 添加班级信息 * @param classEntity * @return */ boolean addClass(ClassEntity classEntity); /** * 根据学段ids查询班级信息 * @param periodIdArr 学段ids * @return */ List<ClassEntity> searchClassListByPeriodIds(@Param("periodIdArr") String[] periodIdArr); /** * 根据学段ids删除班级信息 * @param periodIdArr 学段ids * @return */ boolean deleteClassByPeriodIds(@Param("periodIdArr") String[] periodIdArr); /** * 根据班级ids删除学生与班级关系 * @param classList 班级集合 * @return */ boolean deleteClass2Student(List<ClassEntity> classList); /** * 根据班级ids删除班级信息 * @param classList * @return */ boolean deleteClassByClassIds(List<ClassEntity> classList); /** * 根据年级ids查询班级信息 * @param gradeIds 年级ids * @return */ List<ClassEntity> searchClassListByGradeIds(@Param("gradeIds") String[] gradeIds); /** * 修改班级信息 * @param classEntity * @return */ boolean updateClass(ClassEntity classEntity); /** * 根据班级id查询班级信息 * @param classId 班级id * @return */ ClassEntity searchClassById(@Param("classId") int classId); /** * 根据年级id查询班级信息,为空时查询全部班级 * @param gradeId 年级id * @param search 关键字 * @return */ List<ClassEntity> searchClassList(@Param("gradeId") int gradeId,@Param("search") String search); /** * * @param userId * @return */ List<ClassEntity> searchClassesByUserId(@Param("userId") int userId); /** * 分配班级给用户 * @param classFormList * @param userId * @return */ boolean allotClassToUser(@Param("list") List<ClassForm> classFormList,@Param("userId") int userId); }
package cr.ulacit.dao; import org.appfuse.dao.BaseDaoTestCase; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; public class MenuDishDaoTest extends BaseDaoTestCase { @Autowired private MenuDishDao menuDisDao; @Test public void testFindById() throws Exception{ log.debug("testing find dish by id..."); menuDisDao.getMenu(2); } }
package com.quam.quamtest.net; import android.content.Context; import com.quam.quamtest.BuildConfig; import com.quam.quamtest.net.rest.Api; import com.quam.quamtest.net.rest.Constant; import com.quam.quamtest.utils.SharedUtils; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import io.realm.RealmObject; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; final class ClientSettings { static Api createDefaultApi(Context context) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(BuildConfig.SERVER_ROOT) .addConverterFactory(GsonConverterFactory.create(prepareGson())) .client(prepareClient(context)) .build(); return retrofit.create(Api.class); } private static Gson prepareGson() { return new GsonBuilder() .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getDeclaringClass().equals(RealmObject.class); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }) .create(); } private static OkHttpClient prepareClient(final Context context) { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); return new OkHttpClient.Builder() .addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { final Request baseRequest = chain.request(); final Request.Builder requestBuilder = baseRequest.newBuilder() .header(Constant.X_PARSE_APPLICATION_ID, BuildConfig.PARSE_APPLICATION_ID) .header(Constant.X_PARSE_REST_API_KEY, BuildConfig.PARSE_API_KEY) .method(baseRequest.method(), baseRequest.body()); final String sessionToken = SharedUtils.getSessionToken(context); if (sessionToken != null) { requestBuilder.addHeader(Constant.X_Parse_Session_Token, sessionToken); } return chain.proceed(requestBuilder.build()); } }) .addInterceptor(logging) .build(); } }
package ex2; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextField; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JList; public class BandsJFrame extends JFrame { private static final long serialVersionUID = -5996269975712301203L; private JPanel contentPane; private JTextField txtInput; public BandsJFrame(String title) { super(title); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); DefaultListModel<String> listModel = new DefaultListModel<String>(); JList<String> listBands = new JList<String>(listModel); contentPane.add(listBands, BorderLayout.CENTER); txtInput = new JTextField(); txtInput.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { super.keyPressed(e); // 10 este enter in cod ASCII if (e.getKeyCode() == 10) { listModel.addElement(txtInput.getText()); // resetam caseta de text sa fie goala txtInput.setText(""); } } }); contentPane.add(txtInput, BorderLayout.NORTH); txtInput.setColumns(10); JButton btnStergere = new JButton("Sterge"); btnStergere.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int[] selectedIndices = listBands.getSelectedIndices(); for(int i = selectedIndices.length-1; i >= 0; i--) { listModel.removeElementAt(selectedIndices[i]); } } }); contentPane.add(btnStergere, BorderLayout.SOUTH); } }
public class Polinomio implements Function{ private int grado; private int[] coef; public Polinomio(int grado, int[] coef){ this.grado = grado; this.coef = coef; } @Override public double evaluate(double x) { double valor = 0; for (int i = 0; i <= this.grado; i++){ valor = this.coef[i] + (x * valor); } return valor; } }
package main; import net.egork.collections.intcollection.IntArray; import net.egork.utils.io.InputReader; import net.egork.utils.io.OutputWriter; import java.util.ArrayList; public class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { ArrayList arr=new ArrayList<Integer>(); int n=in.readInt(); int[][] a=new int[n][n]; for(int i=0;i<n;i++){ int cur=0; for(int j=0;j<n;j++){ a[i][j]=in.readInt(); if(a[i][j]==0||a[i][j]==-1||a[i][j]==2)continue; cur=1; } if(cur==0){ arr.add(i+1); } } out.printLine(arr.size()); for(int i=0;i<arr.size();i++)out.print(arr.get(i)+" "); } }
package com.sdl.webapp.tridion.query; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import com.sdl.webapp.common.api.model.entity.Teaser; import lombok.Data; import java.util.List; @Data /** * <p>Abstract BrokerQuery class.</p> */ public abstract class BrokerQuery { private int schemaId; private int publicationId; private int maxResults; private String sort; private int start; private int pageSize; private Multimap<String, String> keywordFilters = ArrayListMultimap.create(); private boolean hasMore; // TODO: Add filters for custom meta data /** * <p>executeQuery.</p> * * @return a {@link java.util.List} object. * @throws com.sdl.webapp.tridion.query.BrokerQueryException if any. */ public abstract List<Teaser> executeQuery() throws BrokerQueryException; }
package com.example.chris.androidcodingchallenge; import android.graphics.Bitmap; import java.io.IOException; import java.util.List; interface RemoteDataSource { List<User> createUserList() throws IOException; Bitmap getBitmapFromUrl(String urlName) throws IOException; }
package cc.stan.example.springbootwithdockergradleexample.ctl; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloCtl { @GetMapping("/") public String hello() { return "springboot with docker gradle "; } }
package com.tencent.sqlitelint.util; import com.tencent.matrix.d.b; public class SLog { private static final String TAG = "SQLiteLint.SLog"; private static volatile SLog mInstance = null; public static native void nativeSetLogger(int i); public static SLog getInstance() { if (mInstance == null) { synchronized (SLog.class) { if (mInstance == null) { mInstance = new SLog(); } } } return mInstance; } public void printLog(int i, String str, String str2) { switch (i) { case 2: b.v(str, str2, new Object[0]); return; case 3: b.d(str, str2, new Object[0]); return; case 4: b.i(str, str2, new Object[0]); return; case 5: b.w(str, str2, new Object[0]); return; case 6: case 7: b.e(str, str2, new Object[0]); return; default: try { b.i(str, str2, new Object[0]); return; } catch (Throwable th) { new StringBuilder("printLog ex ").append(th.getMessage()); } } new StringBuilder("printLog ex ").append(th.getMessage()); } public static void e(String str, String str2, Object... objArr) { getInstance().printLog(6, str, String.format(str2, objArr)); } public static void w(String str, String str2, Object... objArr) { getInstance().printLog(5, str, String.format(str2, objArr)); } public static void i(String str, String str2, Object... objArr) { getInstance().printLog(4, str, String.format(str2, objArr)); } public static void d(String str, String str2, Object... objArr) { getInstance().printLog(3, str, String.format(str2, objArr)); } public static void v(String str, String str2, Object... objArr) { getInstance().printLog(2, str, String.format(str2, objArr)); } }
package net.somethingnew.kawatan.flower; import android.content.Context; import android.widget.EditText; import android.widget.ImageView; import androidx.cardview.widget.CardView; import net.somethingnew.kawatan.flower.db.DatabaseHelper; import net.somethingnew.kawatan.flower.model.AvailableBookInfo; import net.somethingnew.kawatan.flower.model.CardModel; import net.somethingnew.kawatan.flower.model.FolderModel; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; /** * 全体管理クラス */ public class GlobalManager { public Context mApplicationContext; // GlobalManagerのシングルトンインスタンスの生成は、起動直後のSplashActivityで // static関数のonCreateApplication()を呼び出した時点で生成する。 // 同時にContextを渡してもらい、以後、アプリ内の各所でContext参照できるようにする private static GlobalManager mInstance = null; /** * 現在のVersion */ public int mCategory; /** * */ public int skinHeaderColor; public int skinBodyColor; /** * Folder一覧を保持するLinedList */ public LinkedList<FolderModel> mFolderLinkedList; public LinkedList<FolderModel> mSearchedFolderLinkedList; /** * Folder一覧でDrag&Dropによる並び順が変更になった場合に、どこからどこの範囲に並び替えの更新が発生したかを保持しておき、 * 終了時に並び順をDBに反映する */ public int mOrderChangedStartFolderIndex = 0; public int mOrderChangedEndFolderIndex = 0; /** * 現在処理中のFolderのLinkedList上のIndex * Listをタップしたときに確定する */ public int mCurrentFolderIndex; /** * FolderSettingsDialogでユーザによる設定変更が行われたか否かの識別 */ public boolean mChangedFolderSettings; /** * FolderSettingsDialog内のCardViewに表示する背景色と文字色 * および * ViewPagerの各Fragmentの文字色GridViewのIDを保持しておき、 * パステルカラーGridや色パレットでの色選択時に動的に背景色や文字色を変更するために利用 */ public FolderSettings mFolderSettings; /** * FolderSettingsDialog操作中の色の変更内容を一時的に保持し、ユーザーの明示的な保存行為を受けて * mFolderLinkedListの該当箇所のFolderModelを更新するため、その一時保存用 */ public FolderModel mTempFolder; /** * 各FolderのCardListを保持するMap * Key: folderのid * Value: CardのLinkedList */ public HashMap<String, LinkedList> mCardListMap; /** * CardSettingsDialogにて変更有無や表示対象ViewのID、変更内容を一時的に保持する */ public boolean mChangedCardSettings; public CardSettings mCardSettings; public CardModel mTempCard; /** * 現在処理中のCardのLinkedList上のIndex * 主にListをタップしたときに確定する */ public int mCurrentCardIndex; /** * Card数に変化があった場合(新規追加や削除)にFolderActivityからMainActivityに戻った時に * Card数の表示に反映させる必要がある場合かどうかの識別 */ public boolean mCardStatsChanged; /** * アイコンの5つのCategoryIconFragmentのうちどれを表示するかを示すインデックス */ public int currentCategoryPosition; /** * アプリ全体でのアイコン自動表示機能のON/OFF * SharedPreferenceで保持し、スライドメニューの設定画面でON/OFFを設定できる */ public boolean isIconAuto; /** * 端末の言語環境 */ public boolean isJapanese = false; /** * アプリの初めての起動か否かのフラグ */ public boolean isFirstTime = true; /** * 各インポートデータAvailableBookInfoをリストで管理 */ public List<AvailableBookInfo> availableBookInfoList; /** * SQLit DB接続のためのヘルパークラス */ public DatabaseHelper mDbHelper; // FolderSettingsやCardSettingsでユーザーの色選択や入力文字操作変更を動的に表示に反映させるため、 // 表示に関連するViewのリソースIDを保持しておく // 領域はカバー、おもて、うらで共用で、切り替えて使う(ImageViewを使うのはカバーのみ) class FolderSettings { CardView cardView; EditText editTextTitle; ImageView imageViewIcon; } class CardSettings { CardView cardViewFront; CardView cardViewBack; EditText editTextFront; EditText editTextBack; ImageView imageViewIconFront; ImageView imageViewIconBack; } /** * コンストラクタ. */ private GlobalManager(Context applicationContext) { this.mApplicationContext = applicationContext; this.mCardListMap = new HashMap<>(); this.mFolderSettings = new FolderSettings(); this.mCardSettings = new CardSettings(); this.availableBookInfoList = new ArrayList<>(); this.currentCategoryPosition = Constants.CATEGORY_INDEX_FLOWER; this.isJapanese = Locale.getDefault().getLanguage().equals("ja"); } static void onCreateApplication(Context applicationContext) { // Application#onCreateのタイミングでシングルトンが生成される mInstance = new GlobalManager(applicationContext); } /** * インスタンス取得.<br> * * @param * @return GlobalManager */ public static GlobalManager getInstance() { if (mInstance == null) { // SplashActivityからonCreateApplication()が呼び出されシングルトンインスタンスが生成されていれば // こんなことは起きないはず… throw new RuntimeException("MyContext should be initialized!"); } return mInstance; } }
package lnyswz.oa.bean; import java.io.Serializable; /** * * @author wenyang * @hibernate.class table="t_user" */ public class User implements Serializable{ private int id; private String name; private String password; private Person person; /** * @hibernate.id * generator-class="native" */ public int getId() { return id; } public void setId(int id) { this.id = id; } /** * @hibernate.property */ public String getName() { return name; } public void setName(String name) { this.name = name; } /** * @hibernate.property */ public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } /** * * @return * @hibernate.many-to-one */ public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } }
package com.brainmentors.apps.configdemo; public interface IB { void print(); void calc(); }
package com.example.onul_app; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class SelectLoginOrSignUp extends AppCompatActivity { private Button login_btn; private Button sign_up_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.selectloginorsignup); login_btn = (Button) findViewById(R.id.login_button); sign_up_btn = (Button) findViewById(R.id.sign_up_button); login_btn.setOnClickListener(onClickListener); sign_up_btn.setOnClickListener(onClickListener); } View.OnClickListener onClickListener = new View.OnClickListener(){ @Override public void onClick(View v){ switch(v.getId()){ case R.id.login_button: gotoLoginActivity(); break; case R.id.sign_up_button: gotoSignUpActivity(); break; } } }; private void gotoLoginActivity(){ Intent intent= new Intent(this, LoginActivity.class); startActivity(intent); finish(); } private void gotoSignUpActivity(){ Intent intent= new Intent(this,SignUpActivity.class); startActivity(intent); finish(); } }
package com.diozero.sampleapps.gol; /*- * #%L * Organisation: diozero * Project: diozero - Sample applications * Filename: GameOfLife.java * * This file is part of the diozero project. More information about this project * can be found at https://www.diozero.com/. * %% * Copyright (C) 2016 - 2023 diozero * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import java.util.concurrent.ThreadLocalRandom; public class GameOfLife { private final int width; private final int height; private final int size; private boolean[] cells; public GameOfLife(int width, int height) { this.width = width; this.height = height; this.size = width * height; cells = new boolean[size]; } public int getWidth() { return width; } public int getHeight() { return height; } public void randomise() { ThreadLocalRandom random = ThreadLocalRandom.current(); for (int i = 0; i < size; i++) { cells[i] = random.nextBoolean(); } } public boolean isAlive(int x, int y) { return cells[x + y * width]; } /** * Checks if the cell is alive * * @param x The x position * @param y The y position * @param d The grid data. * @return Alive */ private boolean willSurvive(int x, int y) { int count = 0; int cell_pos = y * width + x; for (int nx = x - 1; nx <= x + 1; nx++) { for (int ny = y - 1; ny <= y + 1; ny++) { int neighbour_pos = nx + ny * width; if (neighbour_pos >= 0 && neighbour_pos < size - 1 && neighbour_pos != cell_pos) { if (cells[neighbour_pos]) { count++; } } } } // Dead if (!cells[cell_pos]) { // Becomes alive if 3 neighbours return count == 3; } // Alive return count >= 2 && count <= 3; } /** * Iterates the game one step forward */ public void iterate() { boolean[] next = new boolean[size]; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { next[x + y * width] = willSurvive(x, y); } } cells = next; } }
package com.agileengine.test.gallery.model; import lombok.*; @Builder @AllArgsConstructor @NoArgsConstructor @ToString @Getter public class Image { private String complexSearchKey; private String id; private String croppedImageUrl; private String fullImageUrl; private String author; private String tags; private String camera; }
package com.ssm.wechatpro.service; import com.ssm.wechatpro.object.InputObject; import com.ssm.wechatpro.object.OutputObject; public interface WechatOutRefundService { /** * 客户进行申请退款 * @param inputObject * @param outputObject * @throws Exception */ public void applyForRefund(InputObject inputObject,OutputObject outputObject) throws Exception; /** * 用户处理退款 * @param inputObject * @param outputObject * @throws Exception */ public void dealWithRefund(InputObject inputObject,OutputObject outputObject) throws Exception; /** * 获取申请退款的列表 * @param inputObject * @param outputObject * @throws Exception */ public void getRefundList(InputObject inputObject ,OutputObject outputObject) throws Exception; }
package org.company.wsse; import org.apache.cxf.annotations.EndpointProperties; import org.apache.cxf.annotations.EndpointProperty; import org.apache.cxf.ws.security.SecurityConstants; import javax.jws.WebService; @EndpointProperties(value = { @EndpointProperty(key = SecurityConstants.SIGNATURE_PROPERTIES, value = "server.properties"), @EndpointProperty(key = SecurityConstants.ENCRYPT_PROPERTIES, value = "server.properties"), @EndpointProperty(key = SecurityConstants.SIGNATURE_USERNAME, value = "myservicekey"), @EndpointProperty(key = SecurityConstants.ENCRYPT_USERNAME, value = "myclientkey"), @EndpointProperty(key = SecurityConstants.CALLBACK_HANDLER, value = "org.company.wsse.handler.KeystorePasswordCallback") }) @WebService(portName = "hwPort", serviceName = "hw", wsdlLocation = "WEB-INF/wsdl/hw.wsdl", targetNamespace = "http://wsssampl.company.org/", endpointInterface = "org.company.wsse.IHelloWorld") public class HelloWorldImpl implements IHelloWorld { @Override public String getVersion() { return "v 1.0"; } }
package com.lingnet.vocs.dao.impl.statistics; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.hibernate.SQLQuery; import org.springframework.stereotype.Repository; import com.lingnet.common.dao.impl.BaseDaoImplInit; import com.lingnet.util.JsonUtil; import com.lingnet.util.Pager; import com.lingnet.vocs.dao.statistics.TaskScoreDao; @Repository("taskScoreDao") public class TaskScoreDaoImpl extends BaseDaoImplInit<Object, String> implements TaskScoreDao { @SuppressWarnings("unchecked") @Override public List<Object[]> getChartsData(String key) { Map<String, String> m = JsonUtil.parseProperties(key); String caliber = m.get("caliber"); String content = m.get("content"); StringBuffer sb = new StringBuffer(); if (null != m) { // 统计口径 if ("employee".equals(caliber)) { sb.append("select qu.name as employee"); } else if ("company".equals(caliber)) { sb.append("select p.name as partnerName"); } // 统计内容 if ("avgScore".equals(content)) { sb.append(",avg(cast(wo.score as numeric(10,2))) as avgScore"); } else if ("taskCount".equals(m.get("content"))) { sb.append(",count(qu.name) as taskCount"); } else { sb.append(",avg(cast(wo.score as numeric(10,2))) as avgScore"); sb.append(",count(qu.name) as taskCount"); } sb.append(" from workorder wo"); sb.append(" inner join qx_users qu on wo.replay_person = qu.id"); sb.append(" inner join partner p on wo.customer = p.id");//qx_user -- partner sb.append(" inner join orderclass oc on oc.id = wo.fault_type"); sb.append(" where (wo.state='5' or wo.state='6') "); // ----------------- 限定条件 // 1、故障类型 if (StringUtils.isNotEmpty(m.get("faultType"))) { sb.append(" and oc.id='" + m.get("faultType") + "'"); } // 2、时间区间 if (StringUtils.isNotEmpty(m.get("dateStart"))) { sb.append(" and wo.check_date >= '" + m.get("dateStart") + " 00:00:00 '"); } if (StringUtils.isNotEmpty(m.get("dateEnd"))) { sb.append(" and wo.check_date <= '" + m.get("dateEnd") + " 23:59:59'"); } // 3、所属公司 if (StringUtils.isNotEmpty(m.get("company"))) { sb.append(" and p.id = '" + m.get("company") + "'"); } // ----------------- 限定条件 // 统计口径 if ("employee".equals(caliber)) { sb.append(" group by qu.name order by qu.name asc"); } else if ("company".equals(caliber)) { sb.append(" group by p.name order by p.name asc"); } } SQLQuery query = this.getSession().createSQLQuery(sb.toString()); List<Object[]> list = query.list(); return list; } @Override public Pager getGridData(String key, Pager pager) { Map<String, String> m = JsonUtil.parseProperties(key); String caliber = m.get("caliber"); String content = m.get("content"); StringBuffer sb = new StringBuffer(); if (null != m) { // 统计口径 if ("employee".equals(caliber)) { sb.append("select qu.name as employee"); } else if ("company".equals(caliber)) { sb.append("select p.name as partnerName"); } // 统计内容 sb.append(",avg(cast(wo.score as numeric(10,2))) as avgScore"); sb.append(",count(qu.name) as taskCount"); sb.append(" from workorder wo"); sb.append(" inner join qx_users qu on wo.replay_person = qu.id"); sb.append(" inner join partner p on wo.customer = p.id"); sb.append(" inner join orderclass oc on oc.id = wo.fault_type"); sb.append(" where (wo.state='5' or wo.state='6') "); // ----------------- 限定条件 // 1、故障类型 if (StringUtils.isNotEmpty(m.get("faultType"))) { sb.append(" and oc.id='" + m.get("faultType") + "'"); } // 2、时间区间 if (StringUtils.isNotEmpty(m.get("dateStart"))) { sb.append(" and wo.check_date >= '" + m.get("dateStart") + " 00:00:00'"); } if (StringUtils.isNotEmpty(m.get("dateEnd"))) { sb.append(" and wo.check_date <= '" + m.get("dateEnd") + " 23:59:59'"); } // 3、所属公司 if (StringUtils.isNotEmpty(m.get("company"))) { sb.append(" and p.id = '" + m.get("company") + "'"); } // ----------------- 限定条件 // 统计口径 if ("employee".equals(caliber)) { sb.append(" group by qu.name order by qu.name asc"); } else if ("company".equals(caliber)) { sb.append(" group by p.name order by p.name asc"); } } pager = findPagerBySql(pager, sb.toString()); return pager; } }
package com.tencent.mm.plugin.wallet_index.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; class WalletOpenFingerprintPayRedirectUI$1 implements OnCancelListener { final /* synthetic */ WalletOpenFingerprintPayRedirectUI pDJ; WalletOpenFingerprintPayRedirectUI$1(WalletOpenFingerprintPayRedirectUI walletOpenFingerprintPayRedirectUI) { this.pDJ = walletOpenFingerprintPayRedirectUI; } public final void onCancel(DialogInterface dialogInterface) { WalletOpenFingerprintPayRedirectUI.a(this.pDJ); WalletOpenFingerprintPayRedirectUI.a(this.pDJ, ""); } }
/** * Methods to work with utils. */ package api.longpoll.bots.methods.impl.utils;
package com.plexobject.dp.sample.dao.memory; import com.plexobject.dp.sample.dao.SecurityDao; import com.plexobject.dp.sample.domain.Security; public class SecurityDaoImpl extends BaseDaoImpl<String, Security> implements SecurityDao { }
package SVisitor; import java.util.ArrayList; import java.util.List; public class VisitorTest { public static void main(String[] args) { //creating all objects for structure CarBody carBody = new CarBody(); Wheel wheel1 = new Wheel("front-left"); Wheel wheel2 = new Wheel("front-right"); Wheel wheel3 = new Wheel("rear-left"); Wheel wheel4 = new Wheel("rear-right"); List<Bolt> bolts = new ArrayList<>(); for (int i = 0; i < 24; i++) { bolts.add(i, new Bolt(i)); } //setting bolts on wheels for (int i = 0; i < 6; i++) { wheel1.setBolt(bolts.get(i)); } for (int i = 0; i < 6; i++) { wheel2.setBolt(bolts.get(i)); } for (int i = 0; i < 6; i++) { wheel3.setBolt(bolts.get(i)); } for (int i = 0; i < 6; i++) { wheel4.setBolt(bolts.get(i)); } //setting wheels on carBody carBody.setWheel(wheel1); carBody.setWheel(wheel2); carBody.setWheel(wheel3); carBody.setWheel(wheel4); //creating visitors Visitor hooligan = new HooliganVisitor(); Visitor mechanic = new MechanicVisitor(); //implementation visitors on carBody structure carBody.accept(hooligan); carBody.accept(mechanic); } }
package com.waes.backend.stepDefs; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.junit.Assert; import com.google.gson.Gson; import com.waes.backend.utilities.ApiUtils; import com.waes.backend.utilities.ReportingUtils; import cucumber.api.Scenario; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import io.cucumber.datatable.DataTable; import io.restassured.RestAssured; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; public class UserRepositoryTestSteps{ ReportingUtils reportUtil = new ReportingUtils(); public static Map<Object, Object> jMap = new HashMap<Object, Object>(); ApiUtils apiUtils = new ApiUtils(); Properties prop = new Properties(); Gson gSon = new Gson(); public static String baseURI = ""; public static String endPoint = ""; public static String url = ""; public static int id; public static String name; public static String username; public static String email; public static String superpower; public static String dataOfBirth; public static boolean isAdmin; public Scenario scenario; private Map<String, String> dataMap; private String strResponse; private int statusCode; @Given("the username {string} was registered in the database") public void the_username_was_registered_in_the_database(String username, DataTable dataT) { baseURI = getFirstStringFromDataTable(dataT, "baseURI"); Response response = getRequest(baseURI).param("username", username).get(RestAssured.baseURI); jMap = response.jsonPath().getMap(""); String strStatusCode = response.statusCode() + ""; reportUtil.writeToCucumberReport("Status Code : " + strStatusCode); Assert.assertEquals("Status Code : ", 200, response.statusCode()); } @When("a client app attempts to request user {string} details") public void attempts_to_request(String username) { if (baseURI.isEmpty()) { Assert.fail("BaseURI has not been captured properly"); } String strJsonResponse = getResponse(username).prettyPrint(); reportUtil.writeToCucumberReport("Response for " + username + " : " + strJsonResponse); Assert.assertTrue("User information is empty.", !jMap.isEmpty()); } @Then("^the response should be a JSON object equal to$") public void validateResponse(DataTable data) { List<Map<String, String>> expectedMap = data.asMaps(); id = Integer.parseInt(expectedMap.get(0).get("id")); name = expectedMap.get(0).get("name"); username = expectedMap.get(0).get("username"); email = expectedMap.get(0).get("email"); superpower = expectedMap.get(0).get("superpower"); dataOfBirth = expectedMap.get(0).get("dataOfBirth"); isAdmin = Boolean.parseBoolean(expectedMap.get(0).get("isAdmin")); Assert.assertEquals("id :", id, jMap.get("id")); Assert.assertEquals("name :", name, jMap.get("name")); Assert.assertEquals("username :", username, jMap.get("username")); Assert.assertEquals("email :", email, jMap.get("email")); // Skipped since this step getting updated by other testing steps // Assert.assertEquals("superpower :", superpower, jMap.get("superpower")); Assert.assertEquals("dataOfBirth :", dataOfBirth, jMap.get("dataOfBirth")); Assert.assertEquals("isAdmin :", isAdmin, jMap.get("isAdmin")); reportUtil.writeToCucumberReport("All attributes are as expected."); } @Given("the username {string} was registered in the database by {string}") public void the_username_was_registered_in_the_database(String username, String password, DataTable dataT) { String adminPass=""; adminPass = getAdminPass(username); List<Map<String, String>> dataMaps = dataT.asMaps(); baseURI = dataMaps.get(0).get("baseURI"); reportUtil.writeToCucumberReport("Data has been captured for user : " + username); Assert.assertTrue("Unauthotenticated user : ", !adminPass.isEmpty()); } private String getAdminPass(String username){ String adminPass = ""; if (username.equalsIgnoreCase("admin")) { Properties prop = new Properties(); FileInputStream inputF = null; try { inputF = new FileInputStream("user.properties"); } catch (FileNotFoundException e) { System.out.println("Properties files could not found"); } try { prop.load(inputF); } catch (IOException e) { System.out.println("Properties file not loaded"); } finally { adminPass = prop.getProperty("AdminPass"); try { inputF.close(); } catch (IOException e) { e.printStackTrace(); } } } else { reportUtil.writeToCucumberReport("Invalid User tried to have unautorized information."); Assert.fail("Invalid User tried to have unautorized information."); } return adminPass; } @When("a client app attempts to request user {string} details by {string}") public void attempts_to_request_with_pass(String username, String password) { String adminPass =""; adminPass= getAdminPass(username); if (baseURI.isEmpty()) { Assert.fail("BaseURI has not been captured properly"); } int statusCode = getResponseWithPass(username,adminPass).statusCode(); reportUtil.writeToCucumberReport("Status Code : " + statusCode +" for username :"+ username); Assert.assertEquals("Status Code : ", 200 , statusCode ); } @Then("print the results for autorized {string}") public void printResponse(String username) { String adminPass =""; adminPass= getAdminPass(username); if (baseURI.isEmpty()) { Assert.fail("BaseURI has not been captured properly"); } String strJsonResponse = getResponseWithPass(username,adminPass).prettyPrint(); //getResponse(user).prettyPrint(); reportUtil.writeToCucumberReport("Response for " + username + " : " + strJsonResponse); Assert.assertTrue("User information is empty.", !strJsonResponse.isEmpty()); } @Given("the user information has captured by {string} or {string}") public void captureUserDataByUsernameOrEmail(String username,String email, DataTable dataT) { baseURI = getFirstStringFromDataTable(dataT, "baseURI"); String usedData=""; if(username.isEmpty()) { username = getMapFromDataTable(dataT, "eMail", email).get("uName"); this.username = username; usedData = "Email"; }else { this.username = username; usedData = "UserName"; } // Response response = getRequest(baseURI).param("username", username).get(RestAssured.baseURI); jMap = getResponse(username).jsonPath().getMap(""); //response.jsonPath().getMap(""); // String strStatusCode = getResponse(username).statusCode() + ""; reportUtil.writeToCucumberReport("Data has captured by : " + usedData) ;//getResponse(username).statusCode()); Assert.assertTrue("Data has not captured : ", !getResponse(username).jsonPath().toString().isEmpty()); } @When("a client app attempts to request user information") public void attempts_to_request() { if (baseURI.isEmpty()) { Assert.fail("BaseURI has not been captured properly"); } int statusCode = getResponse(username).statusCode(); reportUtil.writeToCucumberReport("Status Code : " + statusCode +" for username :"+ username); Assert.assertEquals("Status Code : ", 200 , statusCode ); } @Then("print the user information from the response") public void printResponseWithoutAuth() { if (baseURI.isEmpty()) { Assert.fail("BaseURI has not been captured properly"); } String strJsonResponse = getResponse(username).prettyPrint(); reportUtil.writeToCucumberReport("Response for " + username + " : " + strJsonResponse); Assert.assertTrue("User information is empty.", !strJsonResponse.isEmpty()); } @Given("the user information has captured by {string} and {string}") public void captureDataByUsernameAndEmail(String username, String email, DataTable dataT){ List<Map<String, String>> dataMaps = dataT.asMaps(); dataMap = dataMaps.get(0); Assert.assertTrue("No Data Provided : ", !dataMap.isEmpty()); reportUtil.writeToCucumberReport("User data has captured for Username: " + dataMap.get("username")); Assert.assertEquals("Admin email does not match.", apiUtils.getUserProperty("AdminEmail") , email); String adminPass=""; adminPass = getAdminPass(username); baseURI = apiUtils.getURIProperty("baseURI"); // dataMaps.get(0).get("baseURI"); endPoint = apiUtils.getURIProperty("AllUsers_EndPoint"); url = baseURI+endPoint; reportUtil.writeToCucumberReport("Data has been captured for user : " + username); Assert.assertTrue("Unauthotenticated user : ", !adminPass.isEmpty()); } @Given("new user to make deleting process smoother") public void postToCreateNewUser(DataTable dataT) { Map<String, String> mapData = dataT.asMaps().get(0); baseURI = apiUtils.getURIProperty("baseURI"); String jsonRequestBody = gSon.toJson(mapData); Response response = apiUtils.getRequest(baseURI).header("Content-Type", "application/json") .body(jsonRequestBody).post(baseURI); int statusCode = response.statusCode(); Assert.assertEquals("Status code : ", 201, statusCode); reportUtil.writeToCucumberReport("Captured Status Code : " + statusCode); reportUtil.writeToCucumberReport("A new user has created successfully."); reportUtil.writeToCucumberReport("Full response body : \n " + response.jsonPath().prettyPrint()); } @When("data is deleted for the user") public void deleteUser(DataTable dataT) { Map<String, String> mapData = dataT.asMaps().get(0); baseURI = apiUtils.getURIProperty("baseURI"); String secretPass = apiUtils.getRealPass(mapData.get("username")); String jsonRequestBody = gSon.toJson(dataMap); // to DELEte Response response = apiUtils.getRequest(baseURI).auth().preemptive().basic(mapData.get("username"), secretPass) .header("Content-Type", "application/json").body(jsonRequestBody).delete(baseURI); int statusCode = response.statusCode(); Assert.assertEquals("Status code : ", 200, statusCode); reportUtil.writeToCucumberReport("Captured Status Code : " + statusCode); reportUtil.writeToCucumberReport("Response has received successfully"); // response comes as string message strResponse = response.asString(); } @Then("validate if only one data deleted") public void validataOneUserDeleted() { String expectedUsernameFromDeleteResponse = strResponse.substring(strResponse.indexOf("'")+1, strResponse.indexOf("'")+9); Assert.assertEquals("Expected user for removal could not found.",expectedUsernameFromDeleteResponse, dataMap.get("username")); reportUtil.writeToCucumberReport("Only one user has deleted from DB"); reportUtil.writeToCucumberReport("Full response after removal : \n \t \t" + strResponse); } @When("attemting to receive the deleted user data") public void attemptToReachDeletedUserData() { endPoint = apiUtils.getURIProperty("User_EndPoint"); url = baseURI+endPoint; Response response = apiUtils.getResponse(dataMap.get("username"), url); strResponse = response.jsonPath().prettyPrint(); statusCode = response.statusCode(); // String responseMessage = response.jsonPath().getString("message"); Assert.assertTrue("Response body should not be empty.", !strResponse.isEmpty()); reportUtil.writeToCucumberReport("Successfully attempted to reach the deleted information from DB."); } @Then("the user should not be present in the response") public void validateIfUserPresents() { Assert.assertEquals("Status Code : ", 404 , statusCode ); reportUtil.writeToCucumberReport("Status Code : " + statusCode +" for username : "+ dataMap.get("username")); reportUtil.writeToCucumberReport("Full response : \n \t \t "+ strResponse); } public String getFirstStringFromDataTable(DataTable dataT, String keyValueFromData) { String valueFromDataTable=""; List<Map<String, String>> dataMaps = dataT.asMaps(); valueFromDataTable = dataMaps.get(0).get(keyValueFromData); return valueFromDataTable; } public Map<String,String> getMapFromDataTable(DataTable dataT, String keyValueFromData, String matcingValue) { List<Map<String, String>> dataMaps = dataT.asMaps(); Map<String, String> desiredMap = new HashMap<String, String>(); for(Map<String,String> map : dataMaps) { if(map.get(keyValueFromData).toString().equalsIgnoreCase(matcingValue)) { desiredMap = map; break; } } return desiredMap; } public RequestSpecification getRequest(String baseURI) { RestAssured.baseURI = baseURI; RequestSpecification request = RestAssured.given(); return request; } public Response getResponse(String username) { Response response = getRequest(baseURI).param("username", username).get(RestAssured.baseURI); return response; } public Response getResponseWithPass(String username,String password) { Response response = getRequest(baseURI).auth().preemptive().basic(username, password).get(RestAssured.baseURI); return response; } }
package banyuan.day04.morning.practice01.P05; /* 1) 创建一个老师类:Teacher 2) 为老师添加字段:id,name,sex,age,height 3) 分别为字段添加对应的属性: id:int,不用校验 name:string,长度大于一位少于四位 sex:string,只能是男和女 age:int,只能在20-55之间 height:double,只能在1.50-1.80之间 定义一个ShowData方法,打印编号、姓名、性别、身高 4) 创建一个老师对象,调用其ShowData(); */ public class Teacher { private int id; private String name; private char sex; private int age; private double height; // public Teacher() { } public Teacher(int id, String name, char sex, int age, double height) { this.id = id; this.name = name; this.sex = sex; this.age = age; this.height = height; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { if (name.length() > 1 && name.length() < 4) this.name = name; } public char getSex() { return sex; } public void setSex(char sex) { if (sex == '男' || sex == '女') this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { if (age >= 22 && age <= 55) this.age = age; } public double getHeight() { return height; } public void setHeight(double height) { if (height >= 1.50 && height <= 1.80) this.height = height; } public String ShowData() { return "Teacher{" + "id=" + id + ", name='" + name + '\'' + ", sex=" + sex + ", height=" + height + '}'; } }
package kevin.jugg.product_service.domain; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import java.io.Serializable; /** * @Description:商品类 * @Author: Kevin * @Create 2020-01-09 14:47 */ @Data public class Product implements Serializable { public Product() { } public Product(int id, String name, int price, int store) { this.id = id; this.name = name; this.price = price; this.store = store; } /** * id */ @TableId(value = "id", type = IdType.AUTO) private int id; /** * 商品名字 */ private String name; /** * 价格 分为单位 */ private int price; /** * 库存 */ private int store; }
package eg.edu.alexu.csd.oop.draw; public class Triangle extends LineSegment{ }
package com.fleet.mybatis.dynamic.sql.service.impl; import com.fleet.mybatis.dynamic.sql.dao.UserDynamicSqlSupport; import com.fleet.mybatis.dynamic.sql.dao.UserMapper; import com.fleet.mybatis.dynamic.sql.entity.User; import com.fleet.mybatis.dynamic.sql.page.PageUtil; import com.fleet.mybatis.dynamic.sql.page.entity.Page; import com.fleet.mybatis.dynamic.sql.service.UserService; import org.mybatis.dynamic.sql.SqlBuilder; import org.mybatis.dynamic.sql.render.RenderingStrategies; import org.mybatis.dynamic.sql.select.render.SelectStatementProvider; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import java.util.Map; import java.util.Optional; import static org.mybatis.dynamic.sql.SqlBuilder.isIn; import static org.mybatis.dynamic.sql.SqlBuilder.isLikeWhenPresent; @Service public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; @Override public Boolean insert(User user) { if (userMapper.insert(user) == 0) { return false; } return true; } @Override public Boolean delete(Integer id) { if (userMapper.deleteByPrimaryKey(id) == 0) { return false; } return true; } @Override public Boolean update(User user) { if (userMapper.updateByPrimaryKeySelective(user) == 0) { return false; } return true; } @Override public User get(Integer id) { Optional<User> user = userMapper.selectByPrimaryKey(id); return user.orElse(null); } @Override public List<User> list() { // 使用 SqlBuilder 类构建 StatementProvider 查询 SelectStatementProvider selectStatementProvider = SqlBuilder.select(UserMapper.selectList) .from(UserDynamicSqlSupport.user) .where(UserDynamicSqlSupport.name, isLikeWhenPresent("%fleet%")) .and(UserDynamicSqlSupport.id, isIn(1, 2, 3)) .orderBy(UserDynamicSqlSupport.id.descending()) .build() .render(RenderingStrategies.MYBATIS3); return userMapper.selectMany(selectStatementProvider); } @Override public PageUtil<User> listPage(Map<String, Object> map, Page page) { PageUtil<User> pageUtil = new PageUtil<>(); // Lambda条件查询 List<User> list = userMapper.select(c -> c.where(UserDynamicSqlSupport.name, isLikeWhenPresent("%fleet%")) .and(UserDynamicSqlSupport.id, isIn(1, 2, 3)) .orderBy(UserDynamicSqlSupport.id.descending())); pageUtil.setList(list); return pageUtil; } }
package com.tencent.mm.plugin.gallery.ui; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.ListView; import com.tencent.mm.R; import com.tencent.mm.plugin.gallery.model.GalleryItem$AlbumItem; import com.tencent.mm.plugin.gallery.model.c; import com.tencent.mm.plugin.gallery.model.g.a; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.util.ArrayList; import java.util.Iterator; public class ImageFolderMgrView extends LinearLayout implements OnItemClickListener, a { boolean Ld = false; private a jDh = null; FrameLayout jDi; private View jDj; private ListView jDk; private b jDl; boolean jDm = false; public ImageFolderMgrView(Context context, AttributeSet attributeSet) { super(context, attributeSet); setOrientation(1); this.jDi = new FrameLayout(getContext()); LayoutParams layoutParams = new LinearLayout.LayoutParams(-1, -1); this.jDi.setVisibility(8); addView(this.jDi, layoutParams); this.jDj = new View(getContext()); this.jDj.setBackgroundColor(-872415232); this.jDj.setOnClickListener(new 3(this)); this.jDi.addView(this.jDj, new FrameLayout.LayoutParams(-1, -1)); this.jDk = new ListView(getContext()); this.jDk.setCacheColorHint(0); this.jDk.setBackgroundResource(R.e.navpage); this.jDk.setSelector(R.g.mm_trans); this.jDk.setOnItemClickListener(this); int dimensionPixelSize = getResources().getDimensionPixelSize(R.f.NormalPadding); this.jDk.setPadding(dimensionPixelSize, dimensionPixelSize / 3, dimensionPixelSize, (dimensionPixelSize * 2) / 3); layoutParams = new FrameLayout.LayoutParams(-1, -2); layoutParams.topMargin = getResources().getDimensionPixelSize(R.f.DefaultActionbarHeightPort); layoutParams.gravity = 80; this.jDi.addView(this.jDk, layoutParams); this.jDl = new b(getContext(), c.aRf().aRJ()); this.jDk.setAdapter(this.jDl); } public final void aRT() { fk(!this.Ld); } private void fk(boolean z) { Animation loadAnimation; if (this.Ld == z) { x.d("MicroMsg.ImageFolderMgrView", "want to expand, but same status, expanded %B", new Object[]{Boolean.valueOf(this.Ld)}); } else if (this.jDm) { x.d("MicroMsg.ImageFolderMgrView", "want to expand[%B], but now in animation", new Object[]{Boolean.valueOf(z)}); } else if (this.Ld) { this.jDm = true; loadAnimation = AnimationUtils.loadAnimation(getContext(), R.a.push_down_out); loadAnimation.setAnimationListener(new 1(this)); this.jDk.startAnimation(loadAnimation); this.jDj.startAnimation(AnimationUtils.loadAnimation(getContext(), R.a.fast_faded_out)); } else { this.jDm = true; this.jDi.setVisibility(0); this.jDj.startAnimation(AnimationUtils.loadAnimation(getContext(), R.a.fast_faded_in)); loadAnimation = AnimationUtils.loadAnimation(getContext(), R.a.push_up_in); loadAnimation.setAnimationListener(new 2(this)); this.jDk.startAnimation(loadAnimation); } } public void setListener(a aVar) { this.jDh = aVar; } public final void w(ArrayList<GalleryItem$AlbumItem> arrayList) { b bVar = this.jDl; bVar.jCO = arrayList; if (!(bVar.jCO == null || bVar.jCO.isEmpty() || ((GalleryItem$AlbumItem) bVar.jCO.get(0)).jAR == null)) { GalleryItem$AlbumItem galleryItem$AlbumItem; GalleryItem$AlbumItem galleryItem$AlbumItem2 = null; Iterator it = bVar.jCO.iterator(); while (true) { galleryItem$AlbumItem = galleryItem$AlbumItem2; if (!it.hasNext()) { break; } galleryItem$AlbumItem2 = (GalleryItem$AlbumItem) it.next(); if (galleryItem$AlbumItem != null) { if (galleryItem$AlbumItem.jAR.jAV >= galleryItem$AlbumItem2.jAR.jAV) { galleryItem$AlbumItem2 = galleryItem$AlbumItem; } } } if (galleryItem$AlbumItem != null) { bVar.jCP.jAR = galleryItem$AlbumItem.jAR; } } c.aRg().A(new 4(this)); } public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) { GalleryItem$AlbumItem qB = this.jDl.qB(i); if (qB == null) { x.d("MicroMsg.ImageFolderMgrView", "get folder failed:" + i); return; } if (this.jDh != null) { this.jDh.b(qB); } this.jDl.jCQ = bi.aG(qB.jAQ, ""); this.jDk.setSelection(0); this.jDl.notifyDataSetChanged(); this.jDj.performClick(); } }
package com.utils.tools.security.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.utils.tools.security.mapper.CompanyMapper; import com.utils.tools.security.pojo.Company; import com.utils.tools.security.service.SecurityService; import com.utils.util.wrapper.WrapMapper; import com.utils.util.wrapper.Wrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class SecurityServiceImpl extends ServiceImpl<CompanyMapper, Company> implements SecurityService { @Autowired private CompanyMapper companyMapper; @Override public Wrapper<List<Company>> getCompanyList() { List<Company> companies = companyMapper.selectList(new QueryWrapper<>(null)); return WrapMapper.ok(companies); } }
package br.com.biblioteca.livros.adapter.datastore.converter; import br.com.biblioteca.livros.adapter.datastore.entity.LivrosEntity; import br.com.biblioteca.livros.core.model.Livros; public class ModelToEntity { public static LivrosEntity modelParaEntity(Livros livros){ return new LivrosEntity().builder() .id(livros.getId()) .descricao(livros.getDescricao()) .nome(livros.getNome()) .valor(livros.getValor()) .build(); } }
package com.kplibwork.libcommon; import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.telephony.TelephonyManager; import android.util.Log; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Random; public final class KPUtils{ public static void onDestroy(Activity mActivity){ try { } catch (Exception e) { // TODO: handle exception } } public static void onPause(Activity mActivity){ try { } catch (Exception e) { // TODO: handle exception } } public static void onResume(Activity mActivity){ try { KPConstants.CURRENT_TOP_ACTIVITY = (Activity)mActivity; } catch (Exception e) { // TODO: handle exception } } public static void onStart(Activity mActivity){ try { } catch (Exception e) { // TODO: handle exception } } public static void onStop(Activity mActivity){ try { } catch (Exception e) { // TODO: handle exception } } public static boolean isNetworkPresent(Context context) { boolean isNetworkAvailable = false; try { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm != null) { NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null) { isNetworkAvailable = netInfo.isConnectedOrConnecting(); } } // check for wifi also if (!isNetworkAvailable) { WifiManager connec = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE); NetworkInfo.State wifi = cm.getNetworkInfo(1).getState(); if (connec.isWifiEnabled() && wifi.toString().equalsIgnoreCase("CONNECTED")) { isNetworkAvailable = true; } else { isNetworkAvailable = false; } } } catch (Exception ex) { Log.e("Network Avail Error", ex.getMessage()); } return isNetworkAvailable; } public static int getRandomNumber(int minTime, int maxTime) { Random random = new Random(); int randomNum = random.nextInt(maxTime - minTime + 1) + minTime; return randomNum; } // private static SecureRandom random = new SecureRandom(); // // public static String getRandomSessionString() { // return new BigInteger(130, random).toString(32); // } // public static NetworkInfo getNetworkInfo(Context context){ // ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // return cm.getActiveNetworkInfo(); // } // // public static boolean isConnected(Context context){ // NetworkInfo info = KPUtils.getNetworkInfo(context); // return (info != null && info.isConnected()); // } // // public static boolean isConnectedWifi(Context context){ // NetworkInfo info = KPUtils.getNetworkInfo(context); // return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI); // } // // public static boolean isConnectedMobile(Context context){ // NetworkInfo info = KPUtils.getNetworkInfo(context); // return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE); // } // // public static boolean isConnectedFast(Context context){ // NetworkInfo info = KPUtils.getNetworkInfo(context); // return (info != null && info.isConnected() && KPUtils.isConnectionFast(info.getType(),info.getSubtype())); // } // // public static boolean isConnectionFast(int type, int subType){ // if(type==ConnectivityManager.TYPE_WIFI){ // return true; // }else if(type==ConnectivityManager.TYPE_MOBILE){ // switch(subType){ // case TelephonyManager.NETWORK_TYPE_1xRTT: // return false; // ~ 50-100 kbps // case TelephonyManager.NETWORK_TYPE_CDMA: // return false; // ~ 14-64 kbps // case TelephonyManager.NETWORK_TYPE_EDGE: // return false; // ~ 50-100 kbps // case TelephonyManager.NETWORK_TYPE_EVDO_0: // return true; // ~ 400-1000 kbps // case TelephonyManager.NETWORK_TYPE_EVDO_A: // return true; // ~ 600-1400 kbps // case TelephonyManager.NETWORK_TYPE_GPRS: // return false; // ~ 100 kbps // case TelephonyManager.NETWORK_TYPE_HSDPA: // return true; // ~ 2-14 Mbps // case TelephonyManager.NETWORK_TYPE_HSPA: // return true; // ~ 700-1700 kbps // case TelephonyManager.NETWORK_TYPE_HSUPA: // return true; // ~ 1-23 Mbps // case TelephonyManager.NETWORK_TYPE_UMTS: // return true; // ~ 400-7000 kbps // case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11 // return true; // ~ 1-2 Mbps // case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9 // return true; // ~ 5 Mbps // case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13 // return true; // ~ 10-20 Mbps // case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8 // return false; // ~25 kbps // case TelephonyManager.NETWORK_TYPE_LTE: // API level 11 // return true; // ~ 10+ Mbps // // Unknown // case TelephonyManager.NETWORK_TYPE_UNKNOWN: // default: // return false; // } // }else{ // return false; // } // } // private static String TAG = KPUtils.class.getSimpleName(); // // private static KPBannerController.AdNetworkShowListener mAdNetworkShowListener; // private static String fbInterstitialId; // // public static void setAdNetworkShowListener(KPBannerController.AdNetworkShowListener _mAdNetworkShowListener) { // mAdNetworkShowListener = _mAdNetworkShowListener; // } // // private static void initAdmobInterstitialAd(final Context mActivity){ // mAdmobInterstitialAd = new com.google.android.gms.ads.InterstitialAd(mActivity); // mAdmobInterstitialAd.setAdUnitId(getAdmobInterstitialId(mActivity)); // // Set an AdListener. // mAdmobInterstitialAd.setAdListener(new com.google.android.gms.ads.AdListener() { // @Override // public void onAdLoaded() { // Log.d("Interstitial Ad Info ", "The interstitial is loaded"); // } // // @Override // public void onAdClosed() { // Log.d("Interstitial Ad Info ", "The interstitial is Closed"); // KPUtils.onRequestToLoadAdmobInterstitialAd(mActivity); // } // }); // } // // private static void initFBInterstitialAd(final Context mActivity){ // mFbInterstitialAd = new com.facebook.ads.InterstitialAd(mActivity,getFbInterstitialId(mActivity)); // // Set an AdListener. // mFbInterstitialAd.setAdListener(new com.facebook.ads.AbstractAdListener() { // @Override // public void onInterstitialDisplayed(com.facebook.ads.Ad ad) { // // } // // @Override // public void onInterstitialDismissed(com.facebook.ads.Ad ad) { // KPUtils.onRequestToLoadFBInterstitialAd(mActivity); // } // // @Override // public void onError(com.facebook.ads.Ad ad, com.facebook.ads.AdError adError) { // // } // // @Override // public void onAdLoaded(com.facebook.ads.Ad ad) { // // } // // @Override // public void onAdClicked(com.facebook.ads.Ad ad) { // // } // }); // // } // // public static void onRequestToShowInterstitialAd(final Context mActivity){ // if(null == mAdNetworkShowListener){ // Log.v(KPUtils.class.getName(),"AdNetworkShowListener is not set yet check KPUtils.setAdNetworkShowListener"); // }else { // try { // fbInterstitialId = mActivity.getString(mActivity.getResources().getIdentifier("fb_interstitial_id", "string", // mActivity.getApplicationContext().getPackageName())); // fbInterstitialId = KPSettings.getInstance(mActivity).getStringValue(KPConstants.FB_INTERSTITIAL_ID,fbInterstitialId); // } catch (Exception e) { // Log.v(KPUtils.class.getName(), "Need fb_interstitial_id in strings.xml file"); // } // // try { // KPConstants.pubAdmobInterstitialId = KPSettings.getInstance(mActivity).getIntValue(KPConstants.KEY_PUB_DEV_STATUS) == 300 ? KPConstants.devAdmobInterstitialId : KPSettings.getInstance(mActivity).getStringValue(KPConstants.ADMOB_INTERSTITIAL_ID, // mActivity.getString(mActivity.getResources().getIdentifier("admob_interstitial_id", "string", // mActivity.getApplicationContext().getPackageName())) // ); // } catch (Exception e) { // Log.v(KPUtils.class.getName(), "Need admob_interstitial_id in strings.xml file"); // } // // if (mFbInterstitialAd == null && mAdNetworkShowListener.shouldShowFan()) { // KPUtils.onRequestToLoadFBInterstitialAd(mActivity); // } // if (mAdmobInterstitialAd == null && mAdNetworkShowListener.shouldShowAdmob()) { // KPUtils.onRequestToLoadAdmobInterstitialAd(mActivity); // } // KPConstants.EventCount--; // if (KPConstants.EventCount <= 0) { // KPConstants.EventCount = KPConstants.FULLSCREEN_AD_FREQUENCY; // onShowInterstitialAd(mActivity); // } // } // } // // public static void onShowInterstitialAd(final Context mActivity){ // if(null == mAdNetworkShowListener){ // Log.v(KPUtils.class.getName(),"AdNetworkShowListener is not set yet check KPUtils.setAdNetworkShowListener"); // }else { // try { // String default_iadorder = "fan-admob"; // try { // default_iadorder = mActivity.getString(mActivity.getResources().getIdentifier("default_iad_order", "string", // mActivity.getApplicationContext().getPackageName())); // } catch (Exception e) { // Log.v(KPBannerController.class.getName(), "Need default_iad_order in strings.xml file"); // } // String data = KPSettings.getInstance(mActivity).getStringValue(KPConstants.DEFAULT_IAD_ORDER, default_iadorder); // String[] ads = data.split("-"); // Boolean adshown = false; // for (int i = 0; i < ads.length; i++) { // try { // if (null != ads[i] && ads[i].equalsIgnoreCase("fan") && mAdNetworkShowListener.shouldShowFan() && null != mFbInterstitialAd && mFbInterstitialAd.isAdLoaded()) { // mFbInterstitialAd.show(); // adshown = true; // if (KPSettings.getInstance(mActivity).getIntValue(KPConstants.KEY_PUB_DEV_STATUS) == 200) { // if (KPConstants.pub_dev_interstitial_count < 0) { // onReloadInterstitialPubDevStatus(mActivity); // } // KPConstants.pub_dev_interstitial_count--; // } // break; // }else if (null != ads[i] && ads[i].equalsIgnoreCase("admob") && mAdNetworkShowListener.shouldShowAdmob() && null != mAdmobInterstitialAd && mAdmobInterstitialAd.isLoaded()) { // mAdmobInterstitialAd.show(); // adshown = true; // if (KPSettings.getInstance(mActivity).getIntValue(KPConstants.KEY_PUB_DEV_STATUS) == 200) { // if (KPConstants.pub_dev_interstitial_count < 0) { // onReloadInterstitialPubDevStatus(mActivity); // } // KPConstants.pub_dev_interstitial_count--; // } // break; // } // } catch (Exception e) { // } // } // if (!adshown) { // KPUtils.onRequestToLoadFBInterstitialAd(mActivity); // KPUtils.onRequestToLoadAdmobInterstitialAd(mActivity); // } // } catch (Exception e) { // KPUtils.onRequestToLoadFBInterstitialAd(mActivity); // KPUtils.onRequestToLoadAdmobInterstitialAd(mActivity); // } // } // } // // private static void onReloadInterstitialPubDevStatus(final Context mCurrentContext){ // KPConstants.pub_dev_interstitial_count = KPConstants.CPUB_DEV_INTERSTITIAL_COUNT; // KPConstants.pub_interstitial_get = KPConstants.CPUB_INTERSTITIAL_GET; // KPConstants.dev_interstitial_get = KPConstants.CDEV_INTERSTITIAL_GET; // // try { // fbInterstitialId = mCurrentContext.getString(mCurrentContext.getResources().getIdentifier("fb_interstitial_id", "string", // mCurrentContext.getApplicationContext().getPackageName())); // fbInterstitialId = KPSettings.getInstance(mCurrentContext).getStringValue(KPConstants.FB_INTERSTITIAL_ID,fbInterstitialId); // }catch (Exception e){ // Log.v(KPUtils.class.getName(),"Need fb_interstitial_id in strings.xml file"); // } // // try { // KPConstants.pubAdmobInterstitialId = KPSettings.getInstance(mCurrentContext).getIntValue(KPConstants.KEY_PUB_DEV_STATUS) == 300?KPConstants.devAdmobInterstitialId:KPSettings.getInstance(mCurrentContext).getStringValue(KPConstants.ADMOB_INTERSTITIAL_ID, // mCurrentContext.getString(mCurrentContext.getResources().getIdentifier("admob_interstitial_id", "string", // mCurrentContext.getApplicationContext().getPackageName())) // ); // }catch (Exception e){ // Log.v(KPUtils.class.getName(),"Need admob_interstitial_id in strings.xml file"); // } // } // // private static com.google.android.gms.ads.InterstitialAd mAdmobInterstitialAd = null; // // public static void onRequestToLoadAdmobInterstitialAd(final Context mActivity) { // KPUtils.initAdmobInterstitialAd(mActivity); // // Create an ad request. // com.google.android.gms.ads.AdRequest.Builder adRequestBuilder = new com.google.android.gms.ads.AdRequest.Builder(); // // // Optionally populate the ad request builder. // adRequestBuilder.addTestDevice(com.google.android.gms.ads.AdRequest.DEVICE_ID_EMULATOR); // // // Start loading the ad now so that it is ready by the time the user is // // ready to go to // // the next level. // mAdmobInterstitialAd.loadAd(adRequestBuilder.build()); // } // // private static com.facebook.ads.InterstitialAd mFbInterstitialAd = null; // // public static void onRequestToLoadFBInterstitialAd(final Context mActivity) { // KPUtils.initFBInterstitialAd(mActivity); // mFbInterstitialAd.loadAd(); // } }
package com.uwetrottmann.trakt5.entities; public class Settings { public User user; public Account account; public Connections connections; public SharingText sharing_text; }
package com.test.kani.songhistory.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import com.test.kani.songhistory.R; import com.test.kani.songhistory.utility.FireStoreCallbackListener; import com.test.kani.songhistory.utility.FireStoreConnectionPool; import com.test.kani.songhistory.utility.LoadingDialog; import com.test.kani.songhistory.utility.SharedPreferencesInstance; import java.util.Map; public class LoginActivity extends AppCompatActivity { EditText idEditText, passwordEditText; CheckBox autoLoginCheckBox; Button signUpBtn, signInBtn; private FireStoreCallbackListener fireStoreCallbackListener; private LoadingDialog loadingDialog; public void setFireStoreCallbackListener(FireStoreCallbackListener listener) { this.fireStoreCallbackListener = listener; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); this.init(); this.bindUI(); } private void init() { SharedPreferencesInstance.getInstance().setSharedPreferencesContext(this, Context.MODE_PRIVATE); String id = (String) SharedPreferencesInstance.getInstance().get("id", SharedPreferencesInstance.Type.String); if( id != null ) { MainActivity.id = id; MainActivity.admin = (boolean) SharedPreferencesInstance.getInstance().get("admin", SharedPreferencesInstance.Type.Boolean); login(true); return; } this.setFireStoreCallbackListener(new FireStoreCallbackListener() { final int ID_NOT_EXISTED = 0; final int PASSWORD_NOT_MATCHED = 1; final int ID_SHORT = 2; final int PASSWORD_SHORT = 3; final int TASK_FAILURE = 4; @Override public void occurError(int errorCode) { switch (errorCode) { case ID_NOT_EXISTED: Log.d("LoginActivity", "This ID is not existed"); idEditText.setError("This ID is not existed"); idEditText.selectAll(); idEditText.requestFocus(); // Toast.makeText(getApplicationContext(), "ID is not existed", Toast.LENGTH_SHORT).show(); break; case PASSWORD_NOT_MATCHED: Log.d("LoginActivity", "Password is not matched"); passwordEditText.setError("Password is not matched"); passwordEditText.selectAll(); passwordEditText.requestFocus(); // Toast.makeText(getApplicationContext(), "Password is not matched", Toast.LENGTH_SHORT).show(); break; case ID_SHORT: Log.d("RegistActivity", "This ID is short"); // Toast.makeText(getApplicationContext(), "This ID is already existed.", Toast.LENGTH_SHORT).show(); idEditText.setError("This ID is too short. You must input at least 5 lengths."); idEditText.selectAll(); idEditText.requestFocus(); break; case PASSWORD_SHORT: Log.d("RegistActivity", "This Password is short"); // Toast.makeText(getApplicationContext(), "This ID is already existed.", Toast.LENGTH_SHORT).show(); passwordEditText.setError("This password is too short. You must input at least 5 lengths."); passwordEditText.selectAll(); passwordEditText.requestFocus(); break; case TASK_FAILURE: Log.d("LoginActivity", "Task is not successful"); break; default: break; } } @Override public void doNext(boolean isSuccesful, Object obj) { if( loadingDialog != null ) loadingDialog.dismiss(); if( !isSuccesful ) { occurError(TASK_FAILURE); return; } if (obj == null) occurError(ID_NOT_EXISTED); else { Map<String, Object> map = (Map<String, Object>) obj; if( map.get("password").equals(passwordEditText.getText().toString().trim()) ) { MainActivity.id = idEditText.getText().toString().trim(); MainActivity.admin = (boolean) map.get("admin"); login(false); } else { occurError(PASSWORD_NOT_MATCHED); return; } } } }); } private void bindUI() { this.idEditText = findViewById(R.id.id_editText); this.passwordEditText = findViewById(R.id.password_editText); this.autoLoginCheckBox = findViewById(R.id.auto_login_checkBox); this.signUpBtn = findViewById(R.id.sign_up_btn); this.signInBtn = findViewById(R.id.sign_in_btn); this.signUpBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(LoginActivity.this, RegistActivity.class)); } }); this.signInBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if( idEditText.getText().toString().trim().length() < 5 ) { fireStoreCallbackListener.occurError(2); return; } if( passwordEditText.getText().toString().trim().length() < 5 ) { fireStoreCallbackListener.occurError(3); return; } if( loadingDialog == null ) loadingDialog = new LoadingDialog(LoginActivity.this); loadingDialog.show("Login..."); FireStoreConnectionPool.getInstance().selectOne(fireStoreCallbackListener, "user", idEditText.getText().toString().trim()); } }); } private void login(boolean isAutoLogin) { if( !isAutoLogin && this.autoLoginCheckBox.isChecked() ) { SharedPreferencesInstance.getInstance().setSharedPreferencesContext(this, Context.MODE_ENABLE_WRITE_AHEAD_LOGGING); SharedPreferencesInstance.getInstance().set("id", MainActivity.id); SharedPreferencesInstance.getInstance().set("admin", MainActivity.admin); } startActivity(new Intent(LoginActivity.this, MainActivity.class)); this.finish(); } }
package com.designpattern.structuralpattern.decorator; public class ConcreteComponent implements Component { @Override public void method() { System.out.println("this is old method"); } }
package org.sherlock.s01; import lombok.SneakyThrows; import org.springframework.stereotype.Service; /** * @author Evgeny Borisov */ @Service public class BaronDeveloper { @SneakyThrows public void use(Box box) { String content = box.getContent(); if (content.contains("poison")) { throw new IamDyingException(); } System.out.println(content+" was used"); } }
public class Bomba { private String combustivel; private double valorLitro; private double qtdLitros; private double valorTotal; private boolean disponivel; public Bomba(String combustivel, double valorLitro){ this.combustivel = combustivel; this.valorLitro = valorLitro; } public void setDisponivel(boolean disponivel){ this.disponivel = disponivel; } public boolean abasteceLitros(double qtdLitros){ if( disponivel ){ this.qtdLitros = qtdLitros; valorTotal = qtdLitros * valorLitro; return true; } else return false; } public boolean abasteceValor(double valorTotal){ if( disponivel ){ this.valorTotal = valorTotal; qtdLitros = valorTotal / valorLitro; return true; } else return false; } public void resumoAbastecimento(){ if (disponivel){ System.out.println("+------------------------------+"); System.out.printf("|%-30s|\n",combustivel); System.out.printf("| Valor (litro) %.2f |\n", valorLitro); System.out.printf("| Qtde Abastecida %.2f |\n", qtdLitros); System.out.println("+------------------------------+"); System.out.printf("| Total R$: %.2f |\n", valorTotal); System.out.println("+------------------------------+"); } else{ System.out.println("+------------------------------+"); System.out.println("+ BOMBA INDISPONIVEL +"); System.out.println("+------------------------------+"); } } }
package id.ac.ub.ptiik.papps.base; <<<<<<< HEAD import java.util.ArrayList; ======= >>>>>>> masteronline public class NavMenu { public static final int MENU_HOME = 0; public static final int MENU_MESSAGES = 1; public static final int MENU_SCHEDULE = 2; public static final int MENU_AGENDA = 3; public static final int MENU_NEWS = 4; public String title; public String description; public int imageResourceId = 0; public boolean isActive = false; public int id; public String tag; <<<<<<< HEAD public int notificationCount = 0; ======= >>>>>>> masteronline public NavMenu(){} public NavMenu(int id, String title, String description, int imageResourceId, String tag){ this.id = id; this.title = title; this.description = description; this.imageResourceId = imageResourceId; this.tag = tag; } public void activate(){ this.isActive = true; } public void deactivate() { this.isActive = false; } <<<<<<< HEAD public void addCount() { this.notificationCount++; } public void clearCount() { this.notificationCount = 0; } public void reduceCount() { this.notificationCount--; } public static void activate(ArrayList<NavMenu> menus, int position) { for(int i=0;i<menus.size();i++) { if(i==position) menus.get(i).activate(); else menus.get(i).deactivate(); } } ======= >>>>>>> masteronline }
package com.pro.mongo.vo; import org.bson.types.ObjectId; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Data; @Data @Document("blogs") public class MemoVO { @Id ObjectId _id; String objectId; String user_id; String type; String title; String img; String desc; }
/* * Copyright (c) 2014-2016 Hewlett Packard Enterprise Development Company, L.P. * * 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 monasca.api.resource; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.codahale.metrics.annotation.Timed; import com.fasterxml.jackson.databind.JsonMappingException; import org.hibernate.validator.constraints.NotEmpty; import org.joda.time.DateTime; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.validation.Valid; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriInfo; import monasca.api.app.AlarmService; import monasca.api.app.command.UpdateAlarmCommand; import monasca.api.app.validation.MetricNameValidation; import monasca.api.app.validation.Validation; import monasca.api.domain.model.alarm.Alarm; import monasca.api.domain.model.alarm.AlarmCount; import monasca.api.domain.model.alarm.AlarmRepo; import monasca.api.domain.model.alarmstatehistory.AlarmStateHistory; import monasca.api.domain.model.alarmstatehistory.AlarmStateHistoryRepo; import monasca.api.infrastructure.persistence.PersistUtils; import monasca.api.resource.annotation.PATCH; import monasca.api.resource.exception.Exceptions; import monasca.common.model.alarm.AlarmSeverity; import monasca.common.model.alarm.AlarmState; /** * Alarm resource implementation. */ @Path("/v2.0/alarms") public class AlarmResource { private final AlarmService service; private final AlarmRepo repo; private final PersistUtils persistUtils; private final AlarmStateHistoryRepo stateHistoryRepo; private final static List<String> ALLOWED_GROUP_BY = Arrays.asList("alarm_definition_id", "name", "state", "severity", "link", "lifecycle_state", "metric_name", "dimension_name", "dimension_value"); private final static List<String> ALLOWED_SORT_BY = Arrays.asList("alarm_id", "alarm_definition_id", "alarm_definition_name", "state", "severity", "lifecycle_state", "link", "state_updated_timestamp", "updated_timestamp", "created_timestamp"); @Inject public AlarmResource(AlarmService service, AlarmRepo repo, AlarmStateHistoryRepo stateHistoryRepo, PersistUtils persistUtils) { this.service = service; this.repo = repo; this.stateHistoryRepo = stateHistoryRepo; this.persistUtils = persistUtils; } @DELETE @Timed @Path("/{alarm_id}") public void delete(@HeaderParam("X-Tenant-Id") String tenantId, @PathParam("alarm_id") String alarmId) { service.delete(tenantId, alarmId); } @GET @Timed @Path("/{alarm_id}") @Produces(MediaType.APPLICATION_JSON) public Alarm get( @Context UriInfo uriInfo, @HeaderParam("X-Tenant-Id") String tenantId, @PathParam("alarm_id") String alarm_id) { return fixAlarmLinks(uriInfo, repo.findById(tenantId, alarm_id)); } private Alarm fixAlarmLinks(UriInfo uriInfo, Alarm alarm) { Links.hydrate(alarm.getAlarmDefinition(), uriInfo, AlarmDefinitionResource.ALARM_DEFINITIONS_PATH); return Links.hydrate(alarm, uriInfo, true); } @GET @Timed @Path("/{alarm_id}/state-history") @Produces(MediaType.APPLICATION_JSON) public Object getStateHistory(@Context UriInfo uriInfo, @HeaderParam("X-Tenant-Id") String tenantId, @PathParam("alarm_id") String alarmId, @QueryParam("offset") String offset, @QueryParam("limit") String limit) throws Exception { final int paging_limit = this.persistUtils.getLimit(limit); final List<AlarmStateHistory> resource = stateHistoryRepo.findById(tenantId, alarmId, offset, paging_limit ); return Links.paginate(paging_limit, resource, uriInfo); } @GET @Timed @Path("/state-history") @Produces(MediaType.APPLICATION_JSON) public Object listStateHistory( @Context UriInfo uriInfo, @HeaderParam("X-Tenant-Id") String tenantId, @QueryParam("dimensions") String dimensionsStr, @QueryParam("start_time") String startTimeStr, @QueryParam("end_time") String endTimeStr, @QueryParam("offset") String offset, @QueryParam("limit") String limit) throws Exception { // Validate query parameters DateTime startTime = Validation.parseAndValidateDate(startTimeStr, "start_time", false); DateTime endTime = Validation.parseAndValidateDate(endTimeStr, "end_time", false); Validation.parseAndValidateDate(offset, "offset", false); if (startTime != null) { Validation.validateTimes(startTime, endTime); } Map<String, String> dimensions = Strings.isNullOrEmpty(dimensionsStr) ? null : Validation .parseAndValidateDimensions(dimensionsStr); final int paging_limit = this.persistUtils.getLimit(limit); final List<AlarmStateHistory> resources = stateHistoryRepo.find(tenantId, dimensions, startTime, endTime, offset, paging_limit ); return Links.paginate(paging_limit, resources, uriInfo); } @GET @Timed @Produces(MediaType.APPLICATION_JSON) public Object list(@Context UriInfo uriInfo, @HeaderParam("X-Tenant-Id") String tenantId, @QueryParam("alarm_definition_id") String alarmDefId, @QueryParam("metric_name") String metricName, @QueryParam("metric_dimensions") String metricDimensionsStr, @QueryParam("state") AlarmState state, @QueryParam("severity") String severity, @QueryParam("lifecycle_state") String lifecycleState, @QueryParam("link") String link, @QueryParam("state_updated_start_time") String stateUpdatedStartStr, @QueryParam("sort_by") String sortBy, @QueryParam("offset") String offset, @QueryParam("limit") String limit) throws Exception { Map<String, String> metricDimensions = Strings.isNullOrEmpty(metricDimensionsStr) ? null : Validation .parseAndValidateDimensions(metricDimensionsStr); MetricNameValidation.validate(metricName, false); DateTime stateUpdatedStart = Validation.parseAndValidateDate(stateUpdatedStartStr, "state_updated_start_time", false); List<String> sortByList = Validation.parseAndValidateSortBy(sortBy, ALLOWED_SORT_BY); if (!Strings.isNullOrEmpty(offset)) { Validation.parseAndValidateNumber(offset, "offset"); } List<AlarmSeverity> severityList = Validation.parseAndValidateSeverity(severity); final int paging_limit = this.persistUtils.getLimit(limit); final List<Alarm> alarms = repo.find(tenantId, alarmDefId, metricName, metricDimensions, state, severityList, lifecycleState, link, stateUpdatedStart, sortByList, offset, paging_limit, true); for (final Alarm alarm : alarms) { Links.hydrate( alarm.getAlarmDefinition(), uriInfo, AlarmDefinitionResource.ALARM_DEFINITIONS_PATH ); } return Links.paginateAlarming(paging_limit, Links.hydrate(alarms, uriInfo), uriInfo); } @PATCH @Timed @Path("/{alarm_id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Alarm patch(@Context UriInfo uriInfo, @HeaderParam("X-Tenant-Id") String tenantId, @PathParam("alarm_id") String alarmId, @NotEmpty Map<String, String> fields) throws JsonMappingException { String stateStr = fields.get("state"); String lifecycleState = fields.get("lifecycle_state"); String link = fields.get("link"); AlarmState state = stateStr == null ? null : Validation.parseAndValidate(AlarmState.class, stateStr); Validation.validateLifecycleState(lifecycleState); Validation.validateLink(link); return fixAlarmLinks(uriInfo, service.patch(tenantId, alarmId, state, lifecycleState, link)); } @PUT @Timed @Path("/{alarm_id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Alarm update(@Context UriInfo uriInfo, @HeaderParam("X-Tenant-Id") String tenantId, @PathParam("alarm_id") String alarmId, @Valid UpdateAlarmCommand command) { Validation.validateLifecycleState(command.lifecycleState); Validation.validateLink(command.link); return fixAlarmLinks(uriInfo, service.update(tenantId, alarmId, command)); } @GET @Timed @Path("/count") @Produces(MediaType.APPLICATION_JSON) public Object getCount(@Context UriInfo uriInfo, @HeaderParam("X-Tenant-Id") String tenantId, @PathParam("alarm_id") String alarmId, @QueryParam("alarm_definition_id") String alarmDefId, @QueryParam("metric_name") String metricName, @QueryParam("metric_dimensions") String metricDimensionsStr, @QueryParam("state") AlarmState state, @QueryParam("severity") String severity, @QueryParam("lifecycle_state") String lifecycleState, @QueryParam("link") String link, @QueryParam("state_updated_start_time") String stateUpdatedStartStr, @QueryParam("group_by") String groupByStr, @QueryParam("offset") String offset, @QueryParam("limit") String limit) throws Exception { Map<String, String> metricDimensions = Strings.isNullOrEmpty(metricDimensionsStr) ? null : Validation .parseAndValidateDimensions(metricDimensionsStr); MetricNameValidation.validate(metricName, false); DateTime stateUpdatedStart = Validation.parseAndValidateDate(stateUpdatedStartStr, "state_updated_start_time", false); List<AlarmSeverity> severityList = Validation.parseAndValidateSeverity(severity); List<String> groupBy = (Strings.isNullOrEmpty(groupByStr)) ? null : parseAndValidateGroupBy( groupByStr); if (offset != null) { Validation.parseAndValidateNumber(offset, "offset"); } final int paging_limit = this.persistUtils.getLimit(limit); final AlarmCount resource = repo.getAlarmsCount(tenantId, alarmDefId, metricName, metricDimensions, state, severityList, lifecycleState, link, stateUpdatedStart, groupBy, offset, paging_limit); Links.paginateAlarmCount(resource, paging_limit, uriInfo); return resource; } private List<String> parseAndValidateGroupBy(String groupByStr) { List<String> groupBy = null; if (!Strings.isNullOrEmpty(groupByStr)) { groupBy = Lists.newArrayList(Splitter.on(',').omitEmptyStrings().trimResults().split(groupByStr)); if (!ALLOWED_GROUP_BY.containsAll(groupBy)) { throw Exceptions.unprocessableEntity("Unprocessable Entity", "Invalid group_by field"); } } return groupBy; } }
package com.web.mapper; import com.web.pojo.TbProperty; public interface TbPropertyMapper { int deleteByPrimaryKey(Integer id); int insert(TbProperty record); int insertSelective(TbProperty record); TbProperty selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(TbProperty record); int updateByPrimaryKey(TbProperty record); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.clerezza.sparql; import org.apache.clerezza.IRI; import org.apache.clerezza.Language; import org.apache.clerezza.implementation.literal.PlainLiteralImpl; import org.apache.clerezza.sparql.query.*; import org.apache.clerezza.sparql.query.impl.SimpleTriplePattern; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import java.util.HashSet; import java.util.List; import java.util.Set; /** * * @author hasan */ @RunWith(JUnitPlatform.class) public class QueryParserTest { @Test public void testSelectQuery() throws ParseException { // SELECT ?title FROM <http://example.org/library> // WHERE { <http://example.org/book/book1> <http://purl.org/dc/elements/1.1/title> ?title . } final String variable = "title"; final String defaultGraph = "http://example.org/library"; final String subject = "http://example.org/book/book1"; final String predicate = "http://purl.org/dc/elements/1.1/title"; StringBuffer queryStrBuf = new StringBuffer(); queryStrBuf.append("SELECT ?").append(variable) .append(" FROM <").append(defaultGraph) .append("> WHERE { <").append(subject).append("> <") .append(predicate).append("> ?").append(variable).append(" . }"); Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); Assertions.assertTrue(SelectQuery.class.isAssignableFrom(q.getClass())); SelectQuery selectQuery = (SelectQuery) q; Assertions.assertTrue(selectQuery.getSelection().get(0) .equals(new Variable(variable))); Assertions.assertTrue(selectQuery.getDataSet().getDefaultGraphs().toArray()[0] .equals(new IRI(defaultGraph))); GraphPattern gp = (GraphPattern) selectQuery.getQueryPattern() .getGraphPatterns().toArray()[0]; Assertions.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); BasicGraphPattern bgp = (BasicGraphPattern) gp; Set<TriplePattern> triplePatterns = bgp.getTriplePatterns(); Assertions.assertTrue(triplePatterns.size()==1); ResourceOrVariable s = new ResourceOrVariable(new IRI(subject)); UriRefOrVariable p = new UriRefOrVariable(new IRI(predicate)); ResourceOrVariable o = new ResourceOrVariable(new Variable(variable)); Assertions.assertTrue(triplePatterns.contains( new SimpleTriplePattern(s, p, o))); } @Test public void testInvalidQuery() throws ParseException { Assertions.assertThrows(ParseException.class, () -> { Query q = QueryParser.getInstance().parse("Hello"); }); } @Test public void testSelectQuerySelection() throws ParseException { SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( "SELECT ?a ?b WHERE {?a ?x ?b}"); Set<Variable> selectionSet = new HashSet<Variable>( q.getSelection()); Set<Variable> expected = new HashSet<Variable>(); expected.add(new Variable("a")); expected.add(new Variable("b")); Assertions.assertEquals(expected, selectionSet); Assertions.assertFalse(q.isSelectAll()); } @Test public void testSelectAll() throws ParseException { SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( "SELECT * WHERE {?a ?x ?b}"); Set<Variable> selectionSet = new HashSet<Variable>( q.getSelection()); Set<Variable> expected = new HashSet<Variable>(); expected.add(new Variable("a")); expected.add(new Variable("b")); expected.add(new Variable("x")); Assertions.assertEquals(expected, selectionSet); Assertions.assertTrue(q.isSelectAll()); } @Test public void testPlainLiteral() throws ParseException { SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( "SELECT * WHERE {?a ?x 'tiger' . ?a ?x 'lion'@en . }"); GraphPattern gp = (GraphPattern) q.getQueryPattern() .getGraphPatterns().toArray()[0]; Assertions.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); BasicGraphPattern bgp = (BasicGraphPattern) gp; Set<TriplePattern> triplePatterns = bgp.getTriplePatterns(); Assertions.assertTrue(triplePatterns.size()==2); Assertions.assertTrue(triplePatterns.contains(new SimpleTriplePattern( new Variable("a"), new Variable("x"), new PlainLiteralImpl("tiger")))); Assertions.assertTrue(triplePatterns.contains(new SimpleTriplePattern( new Variable("a"), new Variable("x"), new PlainLiteralImpl("lion", new Language("en"))))); } @Test public void testOrderBy() throws ParseException { SelectQuery q = (SelectQuery) QueryParser.getInstance().parse( "SELECT * WHERE {?a ?x ?b} ORDER BY DESC(?b)"); List<OrderCondition> oc = ((QueryWithSolutionModifier) q).getOrderConditions(); Assertions.assertTrue(oc.size()==1); Assertions.assertFalse(oc.get(0).isAscending()); Variable b = new Variable("b"); Assertions.assertEquals(b, oc.get(0).getExpression()); } @Test public void testConstructQuery() throws ParseException { // CONSTRUCT { <http://example.org/person#Alice> <http://www.w3.org/2001/vcard-rdf/3.0#FN> ?name} // WHERE { ?x <http://xmlns.com/foaf/0.1/name> ?name} final String variable1 = "name"; final String variable2 = "x"; final String subject1 = "http://example.org/person#Alice"; final String predicate1 = "http://www.w3.org/2001/vcard-rdf/3.0#FN"; final String predicate2 = "http://xmlns.com/foaf/0.1/name"; StringBuffer queryStrBuf = new StringBuffer(); queryStrBuf.append("CONSTRUCT { <").append(subject1).append("> <") .append(predicate1).append("> ?").append(variable1) .append("} WHERE { ?").append(variable2).append(" <") .append(predicate2).append("> ?").append(variable1).append("}"); Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); Assertions.assertTrue(ConstructQuery.class.isAssignableFrom(q.getClass())); ConstructQuery constructQuery = (ConstructQuery) q; Set<TriplePattern> triplePatterns = constructQuery .getConstructTemplate(); Assertions.assertTrue(triplePatterns.size()==1); ResourceOrVariable s = new ResourceOrVariable(new IRI(subject1)); UriRefOrVariable p = new UriRefOrVariable(new IRI(predicate1)); ResourceOrVariable o = new ResourceOrVariable(new Variable(variable1)); Assertions.assertTrue(triplePatterns.contains( new SimpleTriplePattern(s, p, o))); GraphPattern gp = (GraphPattern) constructQuery.getQueryPattern() .getGraphPatterns().toArray()[0]; Assertions.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); BasicGraphPattern bgp = (BasicGraphPattern) gp; triplePatterns = bgp.getTriplePatterns(); Assertions.assertTrue(triplePatterns.size()==1); s = new ResourceOrVariable(new Variable(variable2)); p = new UriRefOrVariable(new IRI(predicate2)); Assertions.assertTrue(triplePatterns.contains( new SimpleTriplePattern(s, p, o))); } @Test public void testDescribeQuery() throws ParseException { // DESCRIBE <http://example.org/book/book1> final String resource = "http://example.org/book/book1"; StringBuffer queryStrBuf = new StringBuffer(); queryStrBuf.append("DESCRIBE <").append(resource).append(">"); Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); Assertions.assertTrue(DescribeQuery.class.isAssignableFrom(q.getClass())); DescribeQuery describeQuery = (DescribeQuery) q; Assertions.assertTrue(describeQuery.getResourcesToDescribe().get(0) .getResource().equals(new IRI(resource))); } @Test public void testAskQuery() throws ParseException { // ASK { ?x <http://xmlns.com/foaf/0.1/name> "Alice" } final String variable = "x"; final String predicate = "http://xmlns.com/foaf/0.1/name"; final String object = "Alice"; StringBuffer queryStrBuf = new StringBuffer(); queryStrBuf.append("ASK { ?").append(variable).append(" <") .append(predicate).append("> \"").append(object).append("\" }"); Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); Assertions.assertTrue(AskQuery.class.isAssignableFrom(q.getClass())); AskQuery askQuery = (AskQuery) q; GraphPattern gp = (GraphPattern) askQuery.getQueryPattern() .getGraphPatterns().toArray()[0]; Assertions.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); BasicGraphPattern bgp = (BasicGraphPattern) gp; Set<TriplePattern> triplePatterns = bgp.getTriplePatterns(); Assertions.assertTrue(triplePatterns.size()==1); Assertions.assertTrue(triplePatterns.contains(new SimpleTriplePattern(new Variable(variable), new IRI(predicate), new PlainLiteralImpl(object)))); } @Test public void testBaseAndPrefix() throws ParseException { // BASE <http://example.org/book/> // PREFIX dc: <http://purl.org/dc/elements/1.1/> // // SELECT $title // WHERE { <book1> dc:title ?title } final String base = "http://example.org/book/"; final String prefix = "dc"; final String prefixUri = "http://purl.org/dc/elements/1.1/"; final String variable = "title"; final String subject = "book1"; final String predicate = "title"; StringBuffer queryStrBuf = new StringBuffer(); queryStrBuf.append("BASE <").append(base).append(">") .append(" PREFIX ").append(prefix).append(": <") .append(prefixUri).append("> SELECT $").append(variable) .append(" WHERE { <").append(subject).append("> ") .append(prefix).append(":").append(predicate).append(" ?") .append(variable).append(" }"); Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); Assertions.assertTrue(SelectQuery.class.isAssignableFrom(q.getClass())); SelectQuery selectQuery = (SelectQuery) q; Assertions.assertTrue(selectQuery.getSelection().get(0) .equals(new Variable(variable))); GraphPattern gp = (GraphPattern) selectQuery.getQueryPattern() .getGraphPatterns().toArray()[0]; Assertions.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp.getClass())); BasicGraphPattern bgp = (BasicGraphPattern) gp; Set<TriplePattern> triplePatterns = bgp.getTriplePatterns(); Assertions.assertTrue(triplePatterns.size()==1); ResourceOrVariable s = new ResourceOrVariable(new IRI(base+subject)); UriRefOrVariable p = new UriRefOrVariable(new IRI(prefixUri+predicate)); ResourceOrVariable o = new ResourceOrVariable(new Variable(variable)); Assertions.assertTrue(triplePatterns.contains( new SimpleTriplePattern(s, p, o))); } @Test public void testOptionalAndFilter() throws ParseException { // PREFIX dc: <http://purl.org/dc/elements/1.1/> // PREFIX books: <http://example.org/book/> // // SELECT ?book ?title // WHERE // { ?book dc:title ?title . // OPTIONAL // { ?book books:author ?author .} // FILTER ( ! bound(?author) ) // } final String prefix1 = "dc"; final String prefix1Uri = "http://purl.org/dc/elements/1.1/"; final String prefix2 = "books"; final String prefix2Uri = "http://example.org/book/"; final String variable1 = "book"; final String variable2 = "title"; final String variable3 = "author"; final String predicate1 = "title"; final String predicate2 = "author"; StringBuffer queryStrBuf = new StringBuffer(); queryStrBuf.append("PREFIX ").append(prefix1).append(": <").append(prefix1Uri) .append("> PREFIX ").append(prefix2).append(": <").append(prefix2Uri) .append("> SELECT ?").append(variable1).append(" ?").append(variable2) .append(" WHERE { ?").append(variable1).append(" ") .append(prefix1).append(":").append(predicate1) .append(" ?").append(variable2).append(" . OPTIONAL { ?") .append(variable1).append(" ").append(prefix2).append(":") .append(predicate2).append(" ?").append(variable3) .append(" .} FILTER ( ! bound(?").append(variable3).append(") ) }"); Query q = QueryParser.getInstance().parse(queryStrBuf.toString()); Assertions.assertTrue(SelectQuery.class.isAssignableFrom(q.getClass())); SelectQuery selectQuery = (SelectQuery) q; Assertions.assertTrue(selectQuery.getSelection().size() == 2); Set<Variable> vars = new HashSet<Variable>(2); Variable var1 = new Variable(variable1); Variable var2 = new Variable(variable2); vars.add(var1); vars.add(var2); Assertions.assertTrue(selectQuery.getSelection().containsAll(vars)); GroupGraphPattern ggp = selectQuery.getQueryPattern(); List<Expression> constraints = ggp.getFilter(); Assertions.assertTrue(UnaryOperation.class.isAssignableFrom(constraints .get(0).getClass())); UnaryOperation uop = (UnaryOperation) constraints.get(0); Assertions.assertTrue(uop.getOperatorString().equals("!")); Assertions.assertTrue(BuiltInCall.class.isAssignableFrom(uop.getOperand() .getClass())); BuiltInCall bic = (BuiltInCall) uop.getOperand(); Assertions.assertTrue(bic.getName().equals("BOUND")); Variable var3 = new Variable(variable3); Assertions.assertTrue(bic.getArguements().get(0).equals(var3)); GraphPattern gp = (GraphPattern) ggp.getGraphPatterns().toArray()[0]; Assertions.assertTrue(OptionalGraphPattern.class.isAssignableFrom(gp.getClass())); OptionalGraphPattern ogp = (OptionalGraphPattern) gp; Assertions.assertTrue(BasicGraphPattern.class.isAssignableFrom( ogp.getMainGraphPattern().getClass())); BasicGraphPattern bgp = (BasicGraphPattern) ogp.getMainGraphPattern(); Set<TriplePattern> triplePatterns = bgp.getTriplePatterns(); Assertions.assertTrue(triplePatterns.size() == 1); Assertions.assertTrue(triplePatterns.contains(new SimpleTriplePattern(var1, new IRI(prefix1Uri + predicate1), var2))); GraphPattern gp2 = (GraphPattern) ogp.getOptionalGraphPattern() .getGraphPatterns().toArray()[0]; Assertions.assertTrue(BasicGraphPattern.class.isAssignableFrom(gp2.getClass())); bgp = (BasicGraphPattern) gp2; triplePatterns = bgp.getTriplePatterns(); Assertions.assertTrue(triplePatterns.size() == 1); Assertions.assertTrue(triplePatterns.contains(new SimpleTriplePattern(var1, new IRI(prefix2Uri + predicate2), var3))); } }
package com.app.lifecycle; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LifeCycleServlet */ public class LifeCycleServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LifeCycleServlet() { super(); // TODO Auto-generated constructor stub } /** * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException { System.out.println("I am from init-method"); } /** * @see Servlet#destroy() */ public void destroy() { System.out.println("I am from destroy-method"); } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("I am from service-method"); } }
package com.folder.functions; public class FunctionsJavaTest { public static boolean checkPalindrom(String str) { StringBuilder stringBuilder = new StringBuilder(str); String inversedString = stringBuilder.reverse().toString(); return inversedString.equalsIgnoreCase(str); } //Высчитывание Наибольший общий делитель NOD public static int gcd(int k, int s) { if (s==0) return k; return gcd(s,k%s); } //Высчитывание Наименьшее общее кратное NOK public static int lcm(int k, int s) { return k / gcd(k,s) * s; } //функция для определения целое/не целое число public static boolean checkPrimeNumber(int k) { if (k%1==0) { System.out.println ("Число целое "); return true; } else { System.out.println ("Число не целое число! "); return false; } } //функция для возврата true на четное и false на нечетное public static boolean dividesByTwo(int k) { if (k%2==0) { System.out.println("Число четное"); } else { System.out.println("Число не четное"); } return true; } //простое или составное число public static boolean isPrimeNumber(int k) { if (k == 1) { return false; } for (int i = 2; i < Math.sqrt(k); i++) { if (k % i == 0) { return false; } } return true; } }
package org.jrenner.learngl.cube; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector3; import org.jetbrains.annotations.NotNull; import org.jrenner.learngl.Main; import org.jrenner.learngl.gameworld.Chunk; import org.jrenner.learngl.gameworld.CubeData; import org.jrenner.learngl.gameworld.CubeType; import java.util.Iterator; public class CubeDataGrid implements Iterable<CubeData> { private static final int chunkSize = Chunk.OBJECT$.getChunkSize(); public static int width = chunkSize; public static int height = chunkSize; public static int depth = chunkSize; public boolean dirty = true; public int numElements; public CubeData[][][] grid = new CubeData[chunkSize][chunkSize][chunkSize]; public Vector3 origin = new Vector3(); public Vector3 center = new Vector3(); public Vector3 boundary = new Vector3(); public int x, y, z; public CubeDataGrid() { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { for (int z = 0; z < width; z++) { grid[y][x][z] = new CubeData(); } } } } public static CubeDataGrid create(float originX, float originY, float originZ) { //CubeDataGrid cdg = Pools.obtain(CubeDataGrid.class); CubeDataGrid cdg = Main.OBJECT$.getMainCDGPool().obtain(); cdg.init(originX, originY, originZ); return cdg; } public void init(float originX, float originY, float originZ) { this.origin.set(originX, originY, originZ); this.center.set(origin).add(width / 2, height / 2, depth / 2); this.boundary.set(origin).add(width, height, depth); this.x = MathUtils.round(origin.x); this.y = MathUtils.round(origin.y); this.z = MathUtils.round(origin.z); numElements = width * height * depth; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { for (int z = 0; z < depth; z++) { //CubeData cubeData = Pools.obtain(CubeData.class); CubeData cubeData = grid[y][x][z]; //cubeData.getPosition().set(x + origin.x, y + origin.y, z + origin.z); cubeData.setX(x + origin.x); cubeData.setY(y + origin.y); cubeData.setZ(z + origin.z); } } } } public boolean hasCubeAt(Vector3 vec) { return hasCubeAt(vec.x, vec.y, vec.z); } public boolean hasCubeAt(float worldX, float worldY, float worldZ) { return (worldX >= origin.x && worldX < boundary.x && worldY >= origin.y && worldY < boundary.y && worldZ >= origin.z && worldZ < boundary.z); /*int y = MathUtils.floor(worldY - origin.y); int x = MathUtils.floor(worldX - origin.x); int z = MathUtils.floor(worldZ - origin.z); boolean result = y >= 0 && y < height && x >= 0 && x < width && z >= 0 && z < depth; //System.out.printf("check for cube at, xyz: %d, %d, %d -- %s\n", x, y, z, result); return result;*/ } public CubeData getCubeAt(Vector3 vec) { return getCubeAt(vec.x, vec.y, vec.z); } public CubeData getCubeAt(float worldX, float worldY, float worldZ) { int y = MathUtils.floor(worldY - origin.y); int x = MathUtils.floor(worldX - origin.x); int z = MathUtils.floor(worldZ - origin.z); return grid[y][x][z]; } public int numberOfHiddenFaces() { int total = 0; for (CubeData cubeData : this) { total += cubeData.getHiddenFacesCount(); } return total; } public int getChunkLocalElevation(float xf, float zf) { int x = MathUtils.floor(xf); int z = MathUtils.floor(zf); int y; for (y = height-1; y >= 0; y--) { CubeData cube = getCubeAt(x, y, z); if (cube.getCubeType() != CubeType.Void) { return y; } } return -1; } // ITERATOR SECTION ------------------------------- private CubeDataGridIterator iterator = null; @NotNull @Override public Iterator<CubeData> iterator() { /*if (iterator == null) { iterator = new CubeDataGridIterator(this); } iterator.reset();*/ if (iterator == null) { iterator = new CubeDataGridIterator(); iterator.setParentCDG(this); } iterator.reset(); return iterator; } private class CubeDataGridIterator implements Iterator<CubeData> { int y; int x; int z; int maxY; int maxX; int maxZ; public void reset() { y = 0; x = 0; z = 0; } public CubeDataGridIterator() { } public void setParentCDG(CubeDataGrid cdg) { maxY = height - 1; maxX = width - 1; maxZ = depth - 1; } @Override public boolean hasNext() { return y <= maxY && x <= maxX && z <= maxZ; } @Override public CubeData next() { CubeData cubeData = grid[y][x][z]; // increment index if (z >= maxZ) { if (x >= maxX) { // this will go past array bounds, which call hasNext to return false y++; x = 0; z = 0; } else { x++; z = 0; } } else { z++; } return cubeData; } @Override public void remove() { } } public int numberOfNonVoidCubes() { int total = 0; for (CubeData cube : this) { if (cube.getCubeType() != CubeType.Void) { total++; } } return total; } public void free() { /*for (CubeData cube : this) { Pools.free(cube); }*/ //Pools.free(this); Main.OBJECT$.getMainCDGPool().free(this); } @Override public int hashCode() { return org.jrenner.learngl.utils.UtilsPackage.threeIntegerHashCode(x, y, z); } @Override public String toString() { return String.format("%.2f, %.2f, %.2f", origin.x, origin.y, origin.z); } }
package com.splendid.config; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Map; public class Configuration { public static final Path DEFAULT_OUTPUT_PATH = Paths.get("./out"); private Path template; private Path target; private Map data; public Configuration() { super(); } public Configuration withTemplate(Path template) { if (!Files.exists(template)) { throw new IllegalArgumentException(String.format("Path %s is not a valid template path.", template.toString())); } if (!Files.isDirectory(template)) { throw new IllegalArgumentException(String.format("Path %s is not a directory.", template.toString())); } if (!Files.isReadable(template)) { throw new IllegalArgumentException(String.format("Path %s is not readable.", template.toString())); } this.template = template; return this; } public Configuration withTarget(Path target) { this.target = target; return this; } public Configuration withData(String data) { this.withData(JsonReader.fromString(data)); return this; } public Configuration withData(Map data) { if (data.isEmpty()) { throw new IllegalArgumentException("Data cannot be null or empty"); } this.data = data; return this; } public Configuration withData(Path dataPath) { if (!Files.exists(dataPath)) { throw new IllegalArgumentException(String.format("Path %s is not a valid data path.", dataPath.toString())); } if (Files.isDirectory(dataPath)) { throw new IllegalArgumentException(String.format("Path %s is not a JSON file.", dataPath.toString())); } if (!Files.isReadable(dataPath)) { throw new IllegalArgumentException(String.format("Path %s is not readable.", dataPath.toString())); } try { this.withData(JsonReader.fromFile(dataPath)); return this; } catch (IOException exception) { throw new IllegalArgumentException(String.format("Cannot read data from path %s.", dataPath.toString()), exception); } } public Path getTemplate() { return template; } public Path getTarget() { return target; } public Map getData() { return data; } }
package com.example.mario.xiaoyou; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.app.ActivityOptions; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.AnimationDrawable; import android.os.AsyncTask; import android.os.Build; import android.support.v4.widget.NestedScrollView; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Base64; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Handler; import java.util.logging.LogRecord; public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, AbsListView.OnScrollListener { private View leftButton, upview,moreView,header; private ImageView imageView, menuButton; private AnimationDrawable animationDrawable; private ListView listView; private SwipeRefreshLayout swipeLayout; private List<Listviewover> amData; private TextView tx, bt; int numtorefresh = 1,touchSlop = 10,MaxNum,statusBarHeight,lastVisibleIndex; private AnimatorSet backAnimatorSet, hideAnimatorSet; private String biaozhi; private MyAdapter adapter; private String[] sArray1 , sArray , sArray3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MaxNum = 10; moreView = getLayoutInflater().inflate(R.layout.moredata, null); init(); tx.setVisibility(View.GONE); amData = new ArrayList<>(); int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); upview.measure(w, h); int height = upview.getMeasuredHeight(); touchSlop = (int) (ViewConfiguration.get(MainActivity.this).getScaledTouchSlop() * 0.9); //为ListView添加一个Header,这个Header与ToolBar一样高。这样我们可以正确的看到列表中的第一个元素而不被遮住。 header = new View(MainActivity.this); header.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height)); header.setBackgroundColor(Color.parseColor("#00000000")); listView.addHeaderView(header); listView.setOnTouchListener(onTouchListener); listView.setOnScrollListener(onScrollListener); listView.setOnItemClickListener(this); listView.setOnScrollListener(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); getWindow().setStatusBarColor(Color.TRANSPARENT); } new JSONTask().execute(numtorefresh, 2); imageView.setImageResource(R.drawable.animationlist); animationDrawable = (AnimationDrawable) imageView.getDrawable(); animationDrawable.start(); //动画刷新 swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { swipeLayout.postDelayed(new Runnable() { @Override public void run() { swipeLayout.setRefreshing(false); new JSONTask().execute(1, 2); imageView.setImageResource(R.drawable.animationlist); animationDrawable = (AnimationDrawable) imageView.getDrawable(); animationDrawable.start(); Savebitmap savebitmap = new Savebitmap(); Bitmap bitmap = savebitmap.getBitmap(); Think ai = new Think(); if (bitmap != null && ai.geta() == 1) { menuButton.setImageBitmap(bitmap); } else { menuButton.setImageResource(R.drawable.go); } } }, 100); } }); //下按钮监控 leftButton.setOnClickListener(new View.OnClickListener() { int pan; @Override public void onClick(View v) { Think a = new Think(); pan = a.a(0); if (pan == 1) { startActivity(new Intent(MainActivity.this, Person.class)); } else { Intent intent = new Intent(MainActivity.this, UnPersonname.class); startActivity(intent); overridePendingTransition(R.anim.in_from_out, R.anim.out_to_middle); } } }); //右上角按钮监控 menuButton.setOnClickListener(new View.OnClickListener() { int pan; @Override public void onClick(View v) { Think a = new Think(); pan = a.a(0); if (pan == 1) { Intent intent = new Intent(MainActivity.this, Personname.class); View sharedView = menuButton; String transitionName = getString(R.string.square_blue_name); ActivityOptions transitionActivityOptions = ActivityOptions.makeSceneTransitionAnimation(MainActivity.this, sharedView, transitionName); startActivity(intent, transitionActivityOptions.toBundle()); } else { Intent intent = new Intent(MainActivity.this, UnPersonname.class); startActivity(intent); overridePendingTransition(R.anim.in_from_out, R.anim.out_to_middle); } } }); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(MainActivity.this, Reply.class); int count = position - 1; String title = sArray[count]; String name = sArray1[count]; String time = sArray3[count]; intent.putExtra("name", name); intent.putExtra("title", title); intent.putExtra("time",time); startActivity(intent); } private void animateBack() { //先清除其他动画 if (hideAnimatorSet != null && hideAnimatorSet.isRunning()) { hideAnimatorSet.cancel(); } if (backAnimatorSet != null && backAnimatorSet.isRunning()) { //如果这个动画已经在运行了,就不管它 } else { backAnimatorSet = new AnimatorSet(); //下面两句是将头尾元素放回初始位置。 ObjectAnimator headerAnimator = ObjectAnimator.ofFloat(upview, "translationY", upview.getTranslationY(), 0f); ObjectAnimator footerAnimator = ObjectAnimator.ofFloat(leftButton, "translationY", leftButton.getTranslationY(), 0f); ArrayList<Animator> animators = new ArrayList<>(); animators.add(headerAnimator); animators.add(footerAnimator); backAnimatorSet.setDuration(300); backAnimatorSet.playTogether(animators); backAnimatorSet.start(); } } private void animateHide() { //先清除其他动画 if (backAnimatorSet != null && backAnimatorSet.isRunning()) { backAnimatorSet.cancel(); } if (hideAnimatorSet != null && hideAnimatorSet.isRunning()) { //如果这个动画已经在运行了,就不管它 } else { hideAnimatorSet = new AnimatorSet(); ObjectAnimator headerAnimator = ObjectAnimator.ofFloat(upview, "translationY", upview.getTranslationY(), -upview.getHeight() + statusBarHeight);//将ToolBar隐藏到上面 ObjectAnimator footerAnimator = ObjectAnimator.ofFloat(leftButton, "translationY", leftButton.getTranslationY(), leftButton.getHeight() + 60);//将Button隐藏到下面 ArrayList<Animator> animators = new ArrayList<>(); animators.add(headerAnimator); animators.add(footerAnimator); hideAnimatorSet.setDuration(200); hideAnimatorSet.playTogether(animators); hideAnimatorSet.start(); } } View.OnTouchListener onTouchListener = new View.OnTouchListener() { float lastY = 0f; float currentY = 0f; //下面两个表示滑动的方向,大于0表示向下滑动,小于0表示向上滑动,等于0表示未滑动 int lastDirection = 0; int currentDirection = 0; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: lastY = event.getY(); currentY = event.getY(); currentDirection = 0; lastDirection = 0; break; case MotionEvent.ACTION_MOVE: if (listView.getFirstVisiblePosition() > 0) { //只有在listView.getFirstVisiblePosition()>0的时候才判断是否进行显隐动画。因为listView.getFirstVisiblePosition()==0时, //ToolBar——也就是头部元素必须是可见的,如果这时候隐藏了起来,那么占位置用了headerview就被用户发现了 //但是当用户将列表向下拉露出列表的headerview的时候,应该要让头尾元素再次出现才对——这个判断写在了后面onScrollListener里面…… float tmpCurrentY = event.getY(); if (Math.abs(tmpCurrentY - lastY) > touchSlop) {//滑动距离大于touchslop时才进行判断 currentY = tmpCurrentY; currentDirection = (int) (currentY - lastY); if (lastDirection != currentDirection) { //如果与上次方向不同,则执行显/隐动画 if (currentDirection < 0) { animateHide(); } else { animateBack(); } } lastY = currentY; } } break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: //手指抬起的时候要把currentDirection设置为0,这样下次不管向哪拉,都与当前的不同(其实在ACTION_DOWN里写了之后这里就用不着了……) currentDirection = 0; lastDirection = 0; break; } return false; } }; AbsListView.OnScrollListener onScrollListener = new AbsListView.OnScrollListener() { //这个Listener其实是用来对付当用户的手离开列表后列表仍然在滑动的情况,也就是SCROLL_STATE_FLING int lastPosition = 0;//上次滚动到的第一个可见元素在listview里的位置——firstVisibleItem int state = SCROLL_STATE_IDLE; @Override public void onScrollStateChanged(AbsListView view, int scrollState) { //记录当前列表状态 state = scrollState; } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (firstVisibleItem == 0) { animateBack(); } if (firstVisibleItem > 0) { if (firstVisibleItem > lastPosition && state == SCROLL_STATE_FLING) { //如果上次的位置小于当前位置,那么隐藏头尾元素 animateHide(); } //================================ if (firstVisibleItem < lastPosition && state == SCROLL_STATE_FLING) { //如果上次的位置大于当前位置,那么显示头尾元素,其实本例中,这个if没用 //如果是滑动ListView触发的,那么,animateBack()肯定已经执行过了,所以没有必要 //如果是点击按钮啥的触发滚动,那么根据设计原则,按钮肯定是头尾元素之一,所以也不需要animateBack() //所以这个if块是不需要的 animateBack(); } //这里没有判断(firstVisibleItem == lastPosition && state == SCROLL_STATE_FLING)的情况, //但是如果列表中的单个item如果很长的话还是要判断的,只不过代码又要多几行 //但是可以取巧一下,在触发滑动的时候拖动执行一下animateHide()或者animateBack()——本例中的话就写在那个点击事件里就可以了) //BTW,如果列表的滑动纯是靠手滑动列表,而没有类似于点击一个按钮滚到某个位置的话,只要第一个if就够了… } lastPosition = firstVisibleItem; } }; @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); Rect rect = new Rect(); getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); // 状态栏高度 statusBarHeight = rect.top; View v = getWindow().findViewById(Window.ID_ANDROID_CONTENT); int contentTop = v.getTop(); } private class JSONTask extends AsyncTask<Integer, String, List<Listviewover>> { String str = "", str1 = "", str2 = "", str3 = ""; @Override protected List<Listviewover> doInBackground(Integer... params) { try { URL url = new URL("http://40.84.62.67:80/init"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(3000); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Content-type", "application/json"); connection.connect(); DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream()); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(dataOutputStream)); JSONObject jsonObject = new JSONObject(); try { jsonObject.put("howmany", params[0]); } catch (JSONException e) { e.printStackTrace(); } String result = jsonObject.toString(); bw.write(result); bw.flush(); connection.getInputStream(); dataOutputStream.close(); bw.close(); InputStream stream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder buffer = new StringBuilder(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line + "\n"); } String finalJson = buffer.toString(); JSONObject parentObject = new JSONObject(finalJson); biaozhi = parentObject.getString("Max");//接受到Max为end时,表明已经是最后一页了,要隐藏下面的button JSONArray parentArray = parentObject.getJSONArray("Servers"); for (int i = 0; i < parentArray.length(); i++) { JSONObject finalObject = parentArray.getJSONObject(i); String title = finalObject.getString("Title"); String name = finalObject.getString("Name"); String phototouxiang = finalObject.getString("Touxiangphoto"); String time = finalObject.getString("Time"); time +="_"; title += "_"; name += "_"; phototouxiang += "_"; str += title; str1 += name; str2 += phototouxiang; str3 += time; } sArray = str.split("_"); sArray1 = str1.split("_"); String[] sArray2 = str2.split("_"); sArray3 = str3.split("_"); if (params[1] == 2) { amData.clear(); numtorefresh = 1; } for (int j = 0; j < sArray.length; j++) { Bitmap bitmap = null; try { byte[] bitmapArray; bitmapArray = Base64.decode(sArray2[j], Base64.DEFAULT); bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length); } catch (Exception e) { e.printStackTrace(); } Listviewover a = new Listviewover(sArray[j], sArray1[j], bitmap); amData.add(a); } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return amData; } @Override protected void onPostExecute(List<Listviewover> data) { if (data != null) { listView.removeFooterView(moreView); LayoutInflater inflater = getLayoutInflater(); //Collections.reverse(data);倒置list adapter = new MyAdapter(inflater, data); listView.addFooterView(moreView);//添加底部view listView.setAdapter(adapter); if (biaozhi.equals("end")) { listView.removeFooterView(moreView); tx.setVisibility(View.VISIBLE);//提醒可见 } else { bt.setVisibility(View.VISIBLE); tx.setVisibility(View.GONE); } imageView.setImageResource(R.drawable.main_title); } } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // 计算最后可见条目的索引 lastVisibleIndex = visibleItemCount; } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // 滑到底部后自动加载,判断listview已经停止滚动并且最后可视的条目等于adapter的条目 if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL && lastVisibleIndex == adapter.getCount() && !biaozhi.equals("end")) { numtorefresh++; new JSONTask().execute(numtorefresh, 1);//继续加载数据 //adapter.notifyDataSetChanged();// 通知listView刷新数据 } } private void init() { imageView = (ImageView) findViewById(R.id.main_title_imageview); swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh); menuButton = (ImageView) findViewById(R.id.main_title_button_right); leftButton = findViewById(R.id.fab); listView = (ListView) findViewById(R.id.lie); upview = findViewById(R.id.include); bt = (TextView) moreView.findViewById(R.id.bt_load); tx = (TextView) moreView.findViewById(R.id.tx); } }
package org.pyload.android.client.module; import java.util.HashMap; public class GuiTask { private HashMap<Throwable, Runnable> exceptionMap; private final Runnable task; private final Runnable success; //how often the task can be called public int tries = 2; // called when anything goes wrong (optional) private Runnable critical; public GuiTask(Runnable task){ this.task = task; // Nop this.success = new Runnable() { public void run() { } }; } public GuiTask(Runnable task, Runnable success) { this.task = task; this.success = success; } public GuiTask(Runnable task, Runnable success, HashMap<Throwable, Runnable> excHashMap) { this.task = task; this.success = success; this.exceptionMap = excHashMap; } public Runnable getTask(){ return task; } public Runnable getSuccess(){ return success; } public boolean hasExceptionMap(){ return (exceptionMap != null && !exceptionMap.isEmpty()); } public HashMap<Throwable, Runnable> getExceptionMap(){ return exceptionMap; } public void putException(Throwable t, Runnable r){ if(exceptionMap == null) exceptionMap = new HashMap<Throwable, Runnable>(); exceptionMap.put(t, r); } public boolean hasCritical(){ return (critical != null); } public void setCritical(Runnable critical) { this.critical = critical; } public Runnable getCritical() { return critical; } }
package modelo.mutacion; import java.util.Random; import modelo.poblacion.Chromosome; import modelo.poblacion.Function; import modelo.poblacion.FunctionAnd; import modelo.poblacion.FunctionIf; import modelo.poblacion.FunctionNot; import modelo.poblacion.FunctionOr; import modelo.poblacion.Gene; import modelo.poblacion.TreeNode; public class MutacionFuncion extends Mutacion{ private int election; public MutacionFuncion(double p) { super(p); } @Override /* * Al azar se selecciona la nueva funci�n por la que vamos a sustituir a la antigua y llamamos a changeFunction. */ protected void mutate(Chromosome chromosome) { int functionsSize = getFunctionsSize(chromosome.getGenes()); if (functionsSize != 0) { Random rnd = new Random(System.currentTimeMillis()); election = Math.abs(rnd.nextInt()) % functionsSize; int function = Math.abs(rnd.nextInt())% (chromosome.getTypesOfGenes()-1); Function newFunction = null; switch (function) { case 0: newFunction = FunctionAnd.getInstance(); break; case 1: newFunction = FunctionOr.getInstance(); break; case 2: newFunction = FunctionNot.getInstance(); break; case 3: newFunction = FunctionIf.getInstance(); } changeFunction(chromosome, chromosome.getGenes(), newFunction,function); } } /* * A�ade al cromosoma un nodo terminal. */ private void addRandomTerminal(Chromosome chromosome, TreeNode<Gene> gene) { Random rnd = new Random(System.currentTimeMillis()); int election1 = Math.abs(rnd.nextInt())% 11; switch (election1) { case 0: gene.addChild(chromosome.getA0()); break; case 1: gene.addChild(chromosome.getA1()); break; case 2: gene.addChild(chromosome.getA2()); break; case 3: gene.addChild(chromosome.getD0()); break; case 4: gene.addChild(chromosome.getD1()); break; case 5: gene.addChild(chromosome.getD2()); break; case 6: gene.addChild(chromosome.getD3()); break; case 7: gene.addChild(chromosome.getD4()); break; case 8: gene.addChild(chromosome.getD5()); break; case 9: gene.addChild(chromosome.getD6()); break; case 10: gene.addChild(chromosome.getD7()); break; } } /* * Recorremos el arbol de raiz a hojas y elegimos la funci�n que vamos a cambiar basandonos en el paramentro election. * Se cambia la funci�n y se ajusta el numero de hijos. */ private void changeFunction(Chromosome chromosome,TreeNode<Gene> genes, Function newFunction,int idfunction) { if (Function.class.isInstance(genes.getData())) { if (election == 0){ int remove; Random rnd = new Random(System.currentTimeMillis()); if(genes.getChildren().size() != 3 && idfunction == 3){ while(genes.getChildren().size() < 3) { addRandomTerminal(chromosome, genes); } } else if(genes.getChildren().size() != 2 && (idfunction == 0 || idfunction == 1)){ while(genes.getChildren().size() < 2) { addRandomTerminal(chromosome, genes); } while(genes.getChildren().size() > 2) { remove = Math.abs(rnd.nextInt()) % genes.getChildren().size(); genes.removeChild(remove); } } else if(genes.getChildren().size() != 1 && idfunction == 2){ while(genes.getChildren().size() > 1) { remove = Math.abs(rnd.nextInt()) % genes.getChildren().size(); genes.removeChild(remove); } } genes.updateFunction(newFunction); election--; } else { election--; for (TreeNode<Gene> gene : genes.getChildren()) { changeFunction(chromosome, gene, newFunction, idfunction); } } } else { for (TreeNode<Gene> gene : genes.getChildren()) { changeFunction(chromosome, gene, newFunction, idfunction); } } } /* * Devuelve el n�mero total de nodos funci�n que hay en el cromosoma. */ private int getFunctionsSize(TreeNode<Gene> genes) { int size = 0; if (Function.class.isInstance(genes.getData())) size++; for (TreeNode<Gene> gene : genes.getChildren()) { size += getFunctionsSize(gene); } return size; } }
package piefarmer.immunology.block; import java.util.Random; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import piefarmer.immunology.common.Immunology; import piefarmer.immunology.lib.Names; import piefarmer.immunology.tileentity.TileEntityDiagnosticTable; import piefarmer.immunology.tileentity.TileEntityMedicalResearchTable; public class BlockDiagnosticTable extends BlockContainer{ public BlockDiagnosticTable(int par1) { super(par1, Material.iron); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.935F, 1.0F); this.setCreativeTab(Immunology.tabImmunology); } public int quantityDropped(Random par1Random) { return 1; } public int getRenderType() { return -1; } public int getRenderBlockPass() { return 1; } public boolean isOpaqueCube() { return false; } public boolean renderAsNormalBlock() { return false; } public void registerIcons(IconRegister par1IconRegister) { this.blockIcon = par1IconRegister.registerIcon(Immunology.modid + ":" + Names.diagBlock_unlocalizedName); } public void onBlockPlacedBy(World world, int i, int j, int k, EntityLiving entityliving, ItemStack par6ItemStack) { int rotation = MathHelper.floor_double((double)((entityliving.rotationYaw * 4F) / 360F) + 2.5D) & 3; world.setBlock(i, j, k, this.blockID, rotation, 2); } public TileEntity createNewTileEntity(World par1World) { return new TileEntityDiagnosticTable(); } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int i, float a, float b, float c) { TileEntityDiagnosticTable tileEntity = (TileEntityDiagnosticTable)world.getBlockTileEntity(x, y, z); if(tileEntity == null || player.isSneaking()) { return false; } player.openGui(Immunology.instance, 1, world, x, y, z); return true; } @Override public void breakBlock(World world, int x, int y, int z, int par5, int par6) { super.breakBlock(world, x, y, z, par5, par6); } }
package com.tencent.mm.plugin.ipcall.ui; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.tencent.mm.R; import com.tencent.mm.sdk.platformtools.bi; import java.util.ArrayList; import java.util.List; public final class f extends BaseAdapter { private String eIQ; private List<a> kuM = new ArrayList(); private IPCallCountryCodeSelectUI kuN; int[] kuO; boolean kuP = false; boolean kuQ = false; private List<a> list; static class a { TextView eMf; TextView kuR; TextView kuS; a() { } } public f(IPCallCountryCodeSelectUI iPCallCountryCodeSelectUI, List<a> list) { this.kuN = iPCallCountryCodeSelectUI; this.list = list; aYg(); aYh(); } private void aYg() { int size = this.list.size(); for (int i = 0; i < size; i++) { this.kuM.add(this.list.get(i)); } this.kuN.kuE.setVisibility(8); } private void aYh() { this.kuO = new int[this.list.size()]; int size = this.list.size(); for (int i = 0; i < size; i++) { this.kuO[i] = ((a) this.list.get(i)).aXZ(); } } public final int getCount() { return this.list.size(); } public final Object getItem(int i) { return this.list.get(i); } public final long getItemId(int i) { return (long) i; } public final void pi(String str) { if (str != null) { this.eIQ = str.trim(); this.list.clear(); int size = this.kuM.size(); int i = 0; while (i < size) { if (((a) this.kuM.get(i)).dYy.toUpperCase().contains(this.eIQ.toUpperCase()) || ((a) this.kuM.get(i)).dYz.toUpperCase().contains(this.eIQ.toUpperCase()) || ((a) this.kuM.get(i)).countryCode.contains(this.eIQ)) { this.list.add(this.kuM.get(i)); } i++; } aYh(); if (this.list.size() == 0) { this.kuN.kuE.setVisibility(0); } else { this.kuN.kuE.setVisibility(8); } super.notifyDataSetChanged(); } } public final View getView(int i, View view, ViewGroup viewGroup) { a aVar; a aVar2 = (a) getItem(i); if (view == null) { view = View.inflate(this.kuN, R.i.ip_call_country_list_item, null); aVar = new a(); aVar.kuR = (TextView) view.findViewById(R.h.contactitem_catalog); aVar.eMf = (TextView) view.findViewById(R.h.contactitem_nick); aVar.kuS = (TextView) view.findViewById(R.h.contactitem_signature); view.setTag(aVar); } else { aVar = (a) view.getTag(); } int i2 = i > 0 ? this.kuO[i - 1] : -1; if (i == 0) { aVar.kuR.setVisibility(0); if (this.kuQ) { aVar.kuR.setText(R.l.popular_country_header); } else { aVar.kuR.setText(rB(this.kuO[i])); } } else if (i <= 0 || this.kuO[i] == i2) { aVar.kuR.setVisibility(8); } else { aVar.kuR.setVisibility(0); aVar.kuR.setText(rB(this.kuO[i])); } if (bi.oW(this.eIQ)) { aVar.eMf.setText(aVar2.dYy); aVar.kuS.setText(" (+" + aVar2.countryCode + ")"); } else { aVar.eMf.setText(com.tencent.mm.plugin.fts.a.f.a(aVar2.dYy, this.eIQ)); aVar.kuS.setText(com.tencent.mm.plugin.fts.a.f.a(" (+" + aVar2.countryCode + ")", this.eIQ)); } if (this.kuP) { aVar.kuS.setVisibility(0); } else { aVar.kuS.setVisibility(4); } return view; } private static String rB(int i) { String valueOf = String.valueOf((char) i); for (String equals : IPCallCountryCodeScrollbar.kuT) { if (equals.equals(String.valueOf((char) i))) { return valueOf; } } return "#"; } }
package tw.org.iii.java; import java.io.File; public class Brad55 { public static void main(String[] args) { String path = "dir2"; File file = new File(path); if (file.exists()) { System.out.println("exist"); if (file.isDirectory()) { System.out.println("dir"); }else if (file.isFile()) { System.out.println("file"); } }else { System.out.println("not exist"); } } }
package code.interview; public class FourBillion { public static void main(String[] args) { System.out.println(Integer.MAX_VALUE); System.out.println(Math.pow(2, 31)); System.out.println(31 & 2); System.out.println(54 & 0x1F); } }
package com.training.day11.loops; public class TenBreak { public static void main(String[] args) { /* // Case 1 : Inside one loop if condition matches for (int i=1; i<=20; i++) { if (i == 10) { break; } System.out.print("i : " +i + " \t"); } // Note : It will stop printing values from 10 onwards. // o/p: i : 1 i : 2 i : 3 i : 4 i : 5 i : 6 i : 7 i : 8 i : 9 */ /* // Case 2 : Inside two loops if outer loop variable condition matches for (int i=0; i<20; i++) { for (int j = 0; j<=5; j++) { if (i == 10) { break; } System.out.println("i : " + i + ", j : " + j); } } */ // Note : It will stop printing the values where 10 is used. // Case 3 : Inside two loops if inner loop variable condition matches for (int i=0; i<20; i++) { for (int j = 0; j<=5; j++) { if (j == 3) { break; } System.out.println("i : " + i + ", j : " + j); } } // Note : It will stop printing the immediate above loop // where j value is 3 is used and it won't execute remaining lines. // It means it will skip the current loop on which it is running. } } /* i :0 i :1 i :2 i :3 i :4 i :5 i :6 i :7 i :8 i :9 */
package net.h2.web.core.config.basicsec; public interface CasAuthenticationConfigurer extends BaseAuthenticationConfigurer { String casUrl(); String applicationUrl(); String applicationName(); String casFailedUrl(); }
package com.polsl.edziennik.desktopclient.view.common.panels.button; import java.awt.FlowLayout; import java.util.ResourceBundle; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JPanel; import com.polsl.edziennik.desktopclient.controller.utils.LangManager; import com.polsl.edziennik.desktopclient.controller.utils.factory.GuiComponentFactory; import com.polsl.edziennik.desktopclient.controller.utils.factory.IGuiComponentAbstractFactory; import com.polsl.edziennik.desktopclient.controller.utils.factory.interfaces.IButton; import com.polsl.edziennik.desktopclient.properties.Properties; public class SaveExitButtonPanel extends JPanel { protected JButton exit; protected JButton save; protected ResourceBundle components = LangManager.getResource(Properties.Component); protected IGuiComponentAbstractFactory factory = GuiComponentFactory.getInstance(); protected IButton Button; public SaveExitButtonPanel(String hint) { super(new FlowLayout(FlowLayout.LEADING, 6, 6)); setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(""), BorderFactory.createEmptyBorder(0, 6, 6, 6))); Button = factory.createTextButton(); save = Button.getButton("saveTextButton", hint); exit = Button.getButton("exitTextButton", "exitTextButton"); add(save); add(exit); } public void activate(boolean value) { exit.setEnabled(value); save.setEnabled(value); } public void activateSave(boolean value) { save.setEnabled(value); } public JButton getExitButton() { return exit; } public JButton getSaveButton() { return save; } }